experiences with memory organization (store the vertexs coords on RayFace)
[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(int val) {}
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         assert(0); //TODO
405         //sys->heat.raytree = RE_rayobject_mesh_create(me, me);
406
407         sys->heat.vface = MEM_callocN(sizeof(MFace*)*me->totvert, "HeatVFaces");
408         for(a=0, mface=me->mface; a<me->totface; a++, mface++) {
409                 sys->heat.vface[mface->v1]= mface;
410                 sys->heat.vface[mface->v2]= mface;
411                 sys->heat.vface[mface->v3]= mface;
412                 if(mface->v4) sys->heat.vface[mface->v4]= mface;
413         }
414 }
415
416 static int heat_ray_bone_visible(LaplacianSystem *sys, int vertex, int bone)
417 {
418         Isect isec;
419         MFace *mface;
420         float end[3];
421         int visible;
422
423         assert( 0 );
424         mface= sys->heat.vface[vertex];
425         if(!mface)
426                 return 1;
427
428         /* setup isec */
429         memset(&isec, 0, sizeof(isec));
430         isec.mode= RE_RAY_SHADOW;
431         isec.lay= -1;
432         isec.orig.face = mface;
433         isec.skip = RE_SKIP_CULLFACE;
434
435         VECCOPY(isec.start, sys->heat.verts[vertex]);
436         PclosestVL3Dfl(end, isec.start, sys->heat.root[bone], sys->heat.tip[bone]);
437
438         VECSUB(isec.vec, end, isec.start);
439         isec.labda = 1.0f;
440
441 #if 0
442         TODO
443         /* add an extra offset to the start position to avoid self intersection */
444         VECCOPY(dir, isec.vec);
445         Normalize(dir);
446         VecMulf(dir, 1e-5);
447         VecAddf(isec.start, isec.start, dir);
448 #endif  
449         visible= !RE_rayobject_raycast(sys->heat.raytree, &isec);
450
451         return visible;
452 }
453
454 static float heat_bone_distance(LaplacianSystem *sys, int vertex, int bone)
455 {
456         float closest[3], d[3], dist, cosine;
457         
458         /* compute euclidian distance */
459         PclosestVL3Dfl(closest, sys->heat.verts[vertex],
460                 sys->heat.root[bone], sys->heat.tip[bone]);
461
462         VecSubf(d, sys->heat.verts[vertex], closest);
463         dist= Normalize(d);
464
465         /* if the vertex normal does not point along the bone, increase distance */
466         cosine= INPR(d, sys->heat.vnors[vertex]);
467
468         return dist/(0.5f*(cosine + 1.001f));
469 }
470
471 static int heat_bone_closest(LaplacianSystem *sys, int vertex, int bone)
472 {
473         float dist;
474         
475         dist= heat_bone_distance(sys, vertex, bone);
476
477         if(dist <= sys->heat.mindist[vertex]*(1.0f + DISTANCE_EPSILON))
478                 if(heat_ray_bone_visible(sys, vertex, bone))
479                         return 1;
480         
481         return 0;
482 }
483
484 static void heat_set_H(LaplacianSystem *sys, int vertex)
485 {
486         float dist, mindist, h;
487         int j, numclosest = 0;
488
489         mindist= 1e10;
490
491         /* compute minimum distance */
492         for(j=0; j<sys->heat.numbones; j++) {
493                 dist= heat_bone_distance(sys, vertex, j);
494
495                 if(dist < mindist)
496                         mindist= dist;
497         }
498
499         sys->heat.mindist[vertex]= mindist;
500
501         /* count number of bones with approximately this minimum distance */
502         for(j=0; j<sys->heat.numbones; j++)
503                 if(heat_bone_closest(sys, vertex, j))
504                         numclosest++;
505
506         sys->heat.p[vertex]= (numclosest > 0)? 1.0f/numclosest: 0.0f;
507
508         /* compute H entry */
509         if(numclosest > 0) {
510                 if(mindist > 1e-5)
511                         h= numclosest*C_WEIGHT/(mindist*mindist);
512                 else
513                         h= 1e10f;
514         }
515         else
516                 h= 0.0f;
517         
518         sys->heat.H[vertex]= h;
519 }
520
521 void heat_calc_vnormals(LaplacianSystem *sys)
522 {
523         float fnor[3];
524         int a, v1, v2, v3, (*face)[3];
525
526         sys->heat.vnors= MEM_callocN(sizeof(float)*3*sys->totvert, "HeatVNors");
527
528         for(a=0, face=sys->faces; a<sys->totface; a++, face++) {
529                 v1= (*face)[0];
530                 v2= (*face)[1];
531                 v3= (*face)[2];
532
533                 CalcNormFloat(sys->verts[v1], sys->verts[v2], sys->verts[v3], fnor);
534                 
535                 VecAddf(sys->heat.vnors[v1], sys->heat.vnors[v1], fnor);
536                 VecAddf(sys->heat.vnors[v2], sys->heat.vnors[v2], fnor);
537                 VecAddf(sys->heat.vnors[v3], sys->heat.vnors[v3], fnor);
538         }
539
540         for(a=0; a<sys->totvert; a++)
541                 Normalize(sys->heat.vnors[a]);
542 }
543
544 static void heat_laplacian_create(LaplacianSystem *sys)
545 {
546         Mesh *me = sys->heat.mesh;
547         MFace *mface;
548         int a;
549
550         /* heat specific definitions */
551         sys->heat.mindist= MEM_callocN(sizeof(float)*me->totvert, "HeatMinDist");
552         sys->heat.H= MEM_callocN(sizeof(float)*me->totvert, "HeatH");
553         sys->heat.p= MEM_callocN(sizeof(float)*me->totvert, "HeatP");
554
555         /* add verts and faces to laplacian */
556         for(a=0; a<me->totvert; a++)
557                 laplacian_add_vertex(sys, sys->heat.verts[a], 0);
558
559         for(a=0, mface=me->mface; a<me->totface; a++, mface++) {
560                 laplacian_add_triangle(sys, mface->v1, mface->v2, mface->v3);
561                 if(mface->v4)
562                         laplacian_add_triangle(sys, mface->v1, mface->v3, mface->v4);
563         }
564
565         /* for distance computation in set_H */
566         heat_calc_vnormals(sys);
567
568         for(a=0; a<me->totvert; a++)
569                 heat_set_H(sys, a);
570 }
571
572 static float heat_limit_weight(float weight)
573 {
574         float t;
575
576         if(weight < WEIGHT_LIMIT_END) {
577                 return 0.0f;
578         }
579         else if(weight < WEIGHT_LIMIT_START) {
580                 t= (weight - WEIGHT_LIMIT_END)/(WEIGHT_LIMIT_START - WEIGHT_LIMIT_END);
581                 return t*WEIGHT_LIMIT_START;
582         }
583         else
584                 return weight;
585 }
586
587 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)
588 {
589         LaplacianSystem *sys;
590         MFace *mface;
591         float solution, weight;
592         int *vertsflipped = NULL;
593         int a, totface, j, bbone, firstsegment, lastsegment, thrownerror = 0;
594
595         /* count triangles */
596         for(totface=0, a=0, mface=me->mface; a<me->totface; a++, mface++) {
597                 totface++;
598                 if(mface->v4) totface++;
599         }
600
601         /* create laplacian */
602         sys = laplacian_system_construct_begin(me->totvert, totface, 1);
603
604         sys->heat.mesh= me;
605         sys->heat.verts= verts;
606         sys->heat.root= root;
607         sys->heat.tip= tip;
608         sys->heat.numbones= numbones;
609
610         heat_ray_tree_create(sys);
611         heat_laplacian_create(sys);
612
613         laplacian_system_construct_end(sys);
614
615         if(dgroupflip) {
616                 vertsflipped = MEM_callocN(sizeof(int)*me->totvert, "vertsflipped");
617                 for(a=0; a<me->totvert; a++)
618                         vertsflipped[a] = mesh_get_x_mirror_vert(ob, a);
619         }
620
621         /* compute weights per bone */
622         for(j=0; j<numbones; j++) {
623                 if(!selected[j])
624                         continue;
625
626                 firstsegment= (j == 0 || dgrouplist[j-1] != dgrouplist[j]);
627                 lastsegment= (j == numbones-1 || dgrouplist[j] != dgrouplist[j+1]);
628                 bbone= !(firstsegment && lastsegment);
629
630                 /* clear weights */
631                 if(bbone && firstsegment) {
632                         for(a=0; a<me->totvert; a++) {
633                                 remove_vert_defgroup(ob, dgrouplist[j], a);
634                                 if(vertsflipped && dgroupflip[j] && vertsflipped[a] >= 0)
635                                         remove_vert_defgroup(ob, dgroupflip[j], vertsflipped[a]);
636                         }
637                 }
638
639                 /* fill right hand side */
640                 laplacian_begin_solve(sys, -1);
641
642                 for(a=0; a<me->totvert; a++)
643                         if(heat_bone_closest(sys, a, j))
644                                 laplacian_add_right_hand_side(sys, a,
645                                         sys->heat.H[a]*sys->heat.p[a]);
646
647                 /* solve */
648                 if(laplacian_system_solve(sys)) {
649                         /* load solution into vertex groups */
650                         for(a=0; a<me->totvert; a++) {
651                                 solution= laplacian_system_get_solution(a);
652                                 
653                                 if(bbone) {
654                                         if(solution > 0.0f)
655                                                 add_vert_to_defgroup(ob, dgrouplist[j], a, solution,
656                                                         WEIGHT_ADD);
657                                 }
658                                 else {
659                                         weight= heat_limit_weight(solution);
660                                         if(weight > 0.0f)
661                                                 add_vert_to_defgroup(ob, dgrouplist[j], a, weight,
662                                                         WEIGHT_REPLACE);
663                                         else
664                                                 remove_vert_defgroup(ob, dgrouplist[j], a);
665                                 }
666
667                                 /* do same for mirror */
668                                 if(vertsflipped && dgroupflip[j] && vertsflipped[a] >= 0) {
669                                         if(bbone) {
670                                                 if(solution > 0.0f)
671                                                         add_vert_to_defgroup(ob, dgroupflip[j], vertsflipped[a],
672                                                                 solution, WEIGHT_ADD);
673                                         }
674                                         else {
675                                                 weight= heat_limit_weight(solution);
676                                                 if(weight > 0.0f)
677                                                         add_vert_to_defgroup(ob, dgroupflip[j], vertsflipped[a],
678                                                                 weight, WEIGHT_REPLACE);
679                                                 else
680                                                         remove_vert_defgroup(ob, dgroupflip[j], vertsflipped[a]);
681                                         }
682                                 }
683                         }
684                 }
685                 else if(!thrownerror) {
686                         error("Bone Heat Weighting:"
687                                 " failed to find solution for one or more bones");
688                         thrownerror= 1;
689                         break;
690                 }
691
692                 /* remove too small vertex weights */
693                 if(bbone && lastsegment) {
694                         for(a=0; a<me->totvert; a++) {
695                                 weight= get_vert_defgroup(ob, dgrouplist[j], a);
696                                 weight= heat_limit_weight(weight);
697                                 if(weight <= 0.0f)
698                                         remove_vert_defgroup(ob, dgrouplist[j], a);
699
700                                 if(vertsflipped && dgroupflip[j] && vertsflipped[a] >= 0) {
701                                         weight= get_vert_defgroup(ob, dgroupflip[j], vertsflipped[a]);
702                                         weight= heat_limit_weight(weight);
703                                         if(weight <= 0.0f)
704                                                 remove_vert_defgroup(ob, dgroupflip[j], vertsflipped[a]);
705                                 }
706                         }
707                 }
708         }
709
710         /* free */
711         if(vertsflipped) MEM_freeN(vertsflipped);
712
713         RE_rayobject_free(sys->heat.raytree);
714         MEM_freeN(sys->heat.vface);
715
716         MEM_freeN(sys->heat.mindist);
717         MEM_freeN(sys->heat.H);
718         MEM_freeN(sys->heat.p);
719         MEM_freeN(sys->heat.vnors);
720
721         laplacian_system_delete(sys);
722 }
723
724 #ifdef RIGID_DEFORM
725 /********************** As-Rigid-As-Possible Deformation ******************/
726 /* From "As-Rigid-As-Possible Surface Modeling",
727         Olga Sorkine and Marc Alexa, ESGP 2007. */
728
729 /* investigate:
730    - transpose R in orthogonal
731    - flipped normals and per face adding
732    - move cancelling to transform, make origco pointer
733 */
734
735 static LaplacianSystem *RigidDeformSystem = NULL;
736
737 static void rigid_add_half_edge_to_R(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
738 {
739         float e[3], e_[3];
740         int i;
741
742         VecSubf(e, sys->rigid.origco[v1->tmp.l], sys->rigid.origco[v2->tmp.l]);
743         VecSubf(e_, v1->co, v2->co);
744
745         /* formula (5) */
746         for (i=0; i<3; i++) {
747                 sys->rigid.R[v1->tmp.l][i][0] += w*e[0]*e_[i];
748                 sys->rigid.R[v1->tmp.l][i][1] += w*e[1]*e_[i];
749                 sys->rigid.R[v1->tmp.l][i][2] += w*e[2]*e_[i];
750         }
751 }
752
753 static void rigid_add_edge_to_R(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
754 {
755         rigid_add_half_edge_to_R(sys, v1, v2, w);
756         rigid_add_half_edge_to_R(sys, v2, v1, w);
757 }
758
759 static void rigid_orthogonalize_R(float R[][3])
760 {
761         HMatrix M, Q, S;
762
763         Mat4CpyMat3(M, R);
764         polar_decomp(M, Q, S);
765         Mat3CpyMat4(R, Q);
766 }
767
768 static void rigid_add_half_edge_to_rhs(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
769 {
770         /* formula (8) */
771         float Rsum[3][3], rhs[3];
772
773         if (sys->vpinned[v1->tmp.l])
774                 return;
775
776         Mat3AddMat3(Rsum, sys->rigid.R[v1->tmp.l], sys->rigid.R[v2->tmp.l]);
777         Mat3Transp(Rsum);
778
779         VecSubf(rhs, sys->rigid.origco[v1->tmp.l], sys->rigid.origco[v2->tmp.l]);
780         Mat3MulVecfl(Rsum, rhs);
781         VecMulf(rhs, 0.5f);
782         VecMulf(rhs, w);
783
784         VecAddf(sys->rigid.rhs[v1->tmp.l], sys->rigid.rhs[v1->tmp.l], rhs);
785 }
786
787 static void rigid_add_edge_to_rhs(LaplacianSystem *sys, EditVert *v1, EditVert *v2, float w)
788 {
789         rigid_add_half_edge_to_rhs(sys, v1, v2, w);
790         rigid_add_half_edge_to_rhs(sys, v2, v1, w);
791 }
792
793 void rigid_deform_iteration()
794 {
795         LaplacianSystem *sys= RigidDeformSystem;
796         EditMesh *em;
797         EditVert *eve;
798         EditFace *efa;
799         int a, i;
800
801         if(!sys)
802                 return;
803         
804         nlMakeCurrent(sys->context);
805         em= sys->rigid.mesh;
806
807         /* compute R */
808         memset(sys->rigid.R, 0, sizeof(float)*3*3*sys->totvert);
809         memset(sys->rigid.rhs, 0, sizeof(float)*3*sys->totvert);
810
811         for(a=0, efa=em->faces.first; efa; efa=efa->next, a++) {
812                 rigid_add_edge_to_R(sys, efa->v1, efa->v2, sys->fweights[a][2]);
813                 rigid_add_edge_to_R(sys, efa->v2, efa->v3, sys->fweights[a][0]);
814                 rigid_add_edge_to_R(sys, efa->v3, efa->v1, sys->fweights[a][1]);
815
816                 if(efa->v4) {
817                         a++;
818                         rigid_add_edge_to_R(sys, efa->v1, efa->v3, sys->fweights[a][2]);
819                         rigid_add_edge_to_R(sys, efa->v3, efa->v4, sys->fweights[a][0]);
820                         rigid_add_edge_to_R(sys, efa->v4, efa->v1, sys->fweights[a][1]);
821                 }
822         }
823
824         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++) {
825                 rigid_orthogonalize_R(sys->rigid.R[a]);
826                 eve->tmp.l= a;
827         }
828         
829         /* compute right hand sides for solving */
830         for(a=0, efa=em->faces.first; efa; efa=efa->next, a++) {
831                 rigid_add_edge_to_rhs(sys, efa->v1, efa->v2, sys->fweights[a][2]);
832                 rigid_add_edge_to_rhs(sys, efa->v2, efa->v3, sys->fweights[a][0]);
833                 rigid_add_edge_to_rhs(sys, efa->v3, efa->v1, sys->fweights[a][1]);
834
835                 if(efa->v4) {
836                         a++;
837                         rigid_add_edge_to_rhs(sys, efa->v1, efa->v3, sys->fweights[a][2]);
838                         rigid_add_edge_to_rhs(sys, efa->v3, efa->v4, sys->fweights[a][0]);
839                         rigid_add_edge_to_rhs(sys, efa->v4, efa->v1, sys->fweights[a][1]);
840                 }
841         }
842
843         /* solve for positions, for X,Y and Z separately */
844         for(i=0; i<3; i++) {
845                 laplacian_begin_solve(sys, i);
846
847                 for(a=0; a<sys->totvert; a++)
848                         if(!sys->vpinned[a])
849                                 laplacian_add_right_hand_side(sys, a, sys->rigid.rhs[a][i]);
850
851                 if(laplacian_system_solve(sys)) {
852                         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++)
853                                 eve->co[i]= laplacian_system_get_solution(a);
854                 }
855                 else {
856                         if(!sys->rigid.thrownerror) {
857                                 error("RigidDeform: failed to find solution.");
858                                 sys->rigid.thrownerror= 1;
859                         }
860                         break;
861                 }
862         }
863 }
864
865 static void rigid_laplacian_create(LaplacianSystem *sys)
866 {
867         EditMesh *em = sys->rigid.mesh;
868         EditVert *eve;
869         EditFace *efa;
870         int a;
871
872         /* add verts and faces to laplacian */
873         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++) {
874                 laplacian_add_vertex(sys, eve->co, eve->pinned);
875                 eve->tmp.l= a;
876         }
877
878         for(efa=em->faces.first; efa; efa=efa->next) {
879                 laplacian_add_triangle(sys,
880                         efa->v1->tmp.l, efa->v2->tmp.l, efa->v3->tmp.l);
881                 if(efa->v4)
882                         laplacian_add_triangle(sys,
883                                 efa->v1->tmp.l, efa->v3->tmp.l, efa->v4->tmp.l);
884         }
885 }
886
887 void rigid_deform_begin(EditMesh *em)
888 {
889         LaplacianSystem *sys;
890         EditVert *eve;
891         EditFace *efa;
892         int a, totvert, totface;
893
894         /* count vertices, triangles */
895         for(totvert=0, eve=em->verts.first; eve; eve=eve->next)
896                 totvert++;
897
898         for(totface=0, efa=em->faces.first; efa; efa=efa->next) {
899                 totface++;
900                 if(efa->v4) totface++;
901         }
902
903         /* create laplacian */
904         sys = laplacian_system_construct_begin(totvert, totface, 0);
905
906         sys->rigid.mesh= em;
907         sys->rigid.R = MEM_callocN(sizeof(float)*3*3*totvert, "RigidDeformR");
908         sys->rigid.rhs = MEM_callocN(sizeof(float)*3*totvert, "RigidDeformRHS");
909         sys->rigid.origco = MEM_callocN(sizeof(float)*3*totvert, "RigidDeformCo");
910
911         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++)
912                 VecCopyf(sys->rigid.origco[a], eve->co);
913
914         sys->areaweights= 0;
915         sys->storeweights= 1;
916
917         rigid_laplacian_create(sys);
918
919         laplacian_system_construct_end(sys);
920
921         RigidDeformSystem = sys;
922 }
923
924 void rigid_deform_end(int cancel)
925 {
926         LaplacianSystem *sys = RigidDeformSystem;
927
928         if(sys) {
929                 EditMesh *em = sys->rigid.mesh;
930                 EditVert *eve;
931                 int a;
932
933                 if(cancel)
934                         for(a=0, eve=em->verts.first; eve; eve=eve->next, a++)
935                                 if(!eve->pinned)
936                                         VecCopyf(eve->co, sys->rigid.origco[a]);
937
938                 if(sys->rigid.R) MEM_freeN(sys->rigid.R);
939                 if(sys->rigid.rhs) MEM_freeN(sys->rigid.rhs);
940                 if(sys->rigid.origco) MEM_freeN(sys->rigid.origco);
941
942                 /* free */
943                 laplacian_system_delete(sys);
944         }
945
946         RigidDeformSystem = NULL;
947 }
948 #endif
949
950 /************************** Harmonic Coordinates ****************************/
951 /* From "Harmonic Coordinates for Character Articulation",
952         Pushkar Joshi, Mark Meyer, Tony DeRose, Brian Green and Tom Sanocki,
953         SIGGRAPH 2007. */
954
955 #define EPSILON 0.0001f
956
957 #define MESHDEFORM_TAG_UNTYPED  0
958 #define MESHDEFORM_TAG_BOUNDARY 1
959 #define MESHDEFORM_TAG_INTERIOR 2
960 #define MESHDEFORM_TAG_EXTERIOR 3
961
962 #define MESHDEFORM_LEN_THRESHOLD 1e-6
963
964 #define MESHDEFORM_MIN_INFLUENCE 0.0005
965
966 static int MESHDEFORM_OFFSET[7][3] =
967                 {{0,0,0}, {1,0,0}, {-1,0,0}, {0,1,0}, {0,-1,0}, {0,0,1}, {0,0,-1}};
968
969 typedef struct MDefBoundIsect {
970         float co[3], uvw[4];
971         int nvert, v[4], facing;
972         float len;
973 } MDefBoundIsect;
974
975 typedef struct MDefBindInfluence {
976         struct MDefBindInfluence *next;
977         float weight;
978         int vertex;
979 } MDefBindInfluence;
980
981 typedef struct MeshDeformBind {
982         /* grid dimensions */
983         float min[3], max[3];
984         float width[3], halfwidth[3];
985         int size, size3;
986
987         /* meshes */
988         DerivedMesh *cagedm;
989         float (*cagecos)[3];
990         float (*vertexcos)[3];
991         int totvert, totcagevert;
992
993         /* grids */
994         MemArena *memarena;
995         MDefBoundIsect *(*boundisect)[6];
996         int *semibound;
997         int *tag;
998         float *phi, *totalphi;
999
1000         /* mesh stuff */
1001         int *inside;
1002         float *weights;
1003         MDefBindInfluence **dyngrid;
1004         float cagemat[4][4];
1005
1006         /* direct solver */
1007         int *varidx;
1008
1009         /* raytrace */
1010         RayObject *raytree;
1011 } MeshDeformBind;
1012
1013 /* ray intersection */
1014
1015 /* our own triangle intersection, so we can fully control the epsilons and
1016  * prevent corner case from going wrong*/
1017 static int meshdeform_tri_intersect(float orig[3], float end[3], float vert0[3],
1018     float vert1[3], float vert2[3], float *isectco, float *uvw)
1019 {
1020         float edge1[3], edge2[3], tvec[3], pvec[3], qvec[3];
1021         float det,inv_det, u, v, dir[3], isectdir[3];
1022
1023         VECSUB(dir, end, orig);
1024
1025         /* find vectors for two edges sharing vert0 */
1026         VECSUB(edge1, vert1, vert0);
1027         VECSUB(edge2, vert2, vert0);
1028
1029         /* begin calculating determinant - also used to calculate U parameter */
1030         Crossf(pvec, dir, edge2);
1031
1032         /* if determinant is near zero, ray lies in plane of triangle */
1033         det = INPR(edge1, pvec);
1034
1035         if (det == 0.0f)
1036           return 0;
1037         inv_det = 1.0f / det;
1038
1039         /* calculate distance from vert0 to ray origin */
1040         VECSUB(tvec, orig, vert0);
1041
1042         /* calculate U parameter and test bounds */
1043         u = INPR(tvec, pvec) * inv_det;
1044         if (u < -EPSILON || u > 1.0f+EPSILON)
1045           return 0;
1046
1047         /* prepare to test V parameter */
1048         Crossf(qvec, tvec, edge1);
1049
1050         /* calculate V parameter and test bounds */
1051         v = INPR(dir, qvec) * inv_det;
1052         if (v < -EPSILON || u + v > 1.0f+EPSILON)
1053           return 0;
1054
1055         isectco[0]= (1.0f - u - v)*vert0[0] + u*vert1[0] + v*vert2[0];
1056         isectco[1]= (1.0f - u - v)*vert0[1] + u*vert1[1] + v*vert2[1];
1057         isectco[2]= (1.0f - u - v)*vert0[2] + u*vert1[2] + v*vert2[2];
1058
1059         uvw[0]= 1.0 - u - v;
1060         uvw[1]= u;
1061         uvw[2]= v;
1062
1063         /* check if it is within the length of the line segment */
1064         VECSUB(isectdir, isectco, orig);
1065
1066         if(INPR(dir, isectdir) < -EPSILON)
1067                 return 0;
1068         
1069         if(INPR(dir, dir) + EPSILON < INPR(isectdir, isectdir))
1070                 return 0;
1071
1072         return 1;
1073 }
1074
1075 /* blender's raytracer is not use now, even though it is much faster. it can
1076  * give problems with rays falling through, so we use our own intersection 
1077  * function above with tweaked epsilons */
1078
1079 #if 0
1080 static MeshDeformBind *MESHDEFORM_BIND = NULL;
1081
1082 static void meshdeform_ray_coords_func(RayFace *face, float **v1, float **v2, float **v3, float **v4)
1083 {
1084         MFace *mface= (MFace*)face;
1085         float (*cagecos)[3]= MESHDEFORM_BIND->cagecos;
1086
1087         *v1= cagecos[mface->v1];
1088         *v2= cagecos[mface->v2];
1089         *v3= cagecos[mface->v3];
1090         *v4= (mface->v4)? cagecos[mface->v4]: NULL;
1091 }
1092
1093 static int meshdeform_ray_check_func(Isect *is, RayFace *face)
1094 {
1095         return 1;
1096 }
1097
1098 static void meshdeform_ray_tree_create(MeshDeformBind *mdb)
1099 {
1100         MFace *mface;
1101         float min[3], max[3];
1102         int a, totface;
1103
1104         /* create a raytrace tree from the mesh */
1105         INIT_MINMAX(min, max);
1106
1107         for(a=0; a<mdb->totcagevert; a++)
1108                 DO_MINMAX(mdb->cagecos[a], min, max)
1109
1110         MESHDEFORM_BIND= mdb;
1111
1112         mface= mdb->cagedm->getFaceArray(mdb->cagedm);
1113         totface= mdb->cagedm->getNumFaces(mdb->cagedm);
1114
1115         mdb->raytree= RE_ray_tree_create(64, totface, min, max,
1116                 meshdeform_ray_coords_func, meshdeform_ray_check_func);
1117
1118         for(a=0; a<totface; a++, mface++)
1119                 RE_ray_tree_add_face(mdb->raytree, mface);
1120
1121         RE_ray_tree_done(mdb->raytree);
1122 }
1123
1124 static void meshdeform_ray_tree_free(MeshDeformBind *mdb)
1125 {
1126         MESHDEFORM_BIND= NULL;
1127         RE_ray_tree_free(mdb->raytree);
1128 }
1129 #endif
1130
1131 static int meshdeform_intersect(MeshDeformBind *mdb, Isect *isec)
1132 {
1133         MFace *mface;
1134         float face[4][3], co[3], uvw[3], len, nor[3], end[3];
1135         int f, hit, is= 0, totface;
1136
1137         isec->labda= 1e10;
1138
1139         mface= mdb->cagedm->getFaceArray(mdb->cagedm);
1140         totface= mdb->cagedm->getNumFaces(mdb->cagedm);
1141
1142         VECADDFAC( end, isec->start, isec->vec, isec->labda );
1143
1144         for(f=0; f<totface; f++, mface++) {
1145                 VECCOPY(face[0], mdb->cagecos[mface->v1]);
1146                 VECCOPY(face[1], mdb->cagecos[mface->v2]);
1147                 VECCOPY(face[2], mdb->cagecos[mface->v3]);
1148
1149                 if(mface->v4) {
1150                         VECCOPY(face[3], mdb->cagecos[mface->v4]);
1151                         hit = meshdeform_tri_intersect(isec->start, end, face[0], face[1], face[2], co, uvw);
1152
1153                         if(hit) {
1154                                 CalcNormFloat(face[0], face[1], face[2], nor);
1155                         }
1156                         else {
1157                                 hit= meshdeform_tri_intersect(isec->start, end, face[0], face[2], face[3], co, uvw);
1158                                 CalcNormFloat(face[0], face[2], face[3], nor);
1159                         }
1160                 }
1161                 else {
1162                         hit= meshdeform_tri_intersect(isec->start, end, face[0], face[1], face[2], co, uvw);
1163                         CalcNormFloat(face[0], face[1], face[2], nor);
1164                 }
1165
1166                 if(hit) {
1167                         len= VecLenf(isec->start, co)/VecLenf(isec->start, end);
1168                         if(len < isec->labda) {
1169                                 isec->labda= len;
1170                                 isec->hit.face = mface;
1171                                 isec->isect= (INPR(isec->vec, nor) <= 0.0f);
1172                                 is= 1;
1173                         }
1174                 }
1175         }
1176
1177         return is;
1178 }
1179
1180 static MDefBoundIsect *meshdeform_ray_tree_intersect(MeshDeformBind *mdb, float *co1, float *co2)
1181 {
1182         MDefBoundIsect *isect;
1183         Isect isec;
1184         float (*cagecos)[3];
1185         MFace *mface;
1186         float vert[4][3], len, end[3];
1187         static float epsilon[3]= {0, 0, 0}; //1e-4, 1e-4, 1e-4};
1188
1189         /* setup isec */
1190         memset(&isec, 0, sizeof(isec));
1191         isec.mode= RE_RAY_MIRROR; /* we want the closest intersection */
1192         isec.lay= -1;
1193         isec.labda= 1e10f;
1194
1195         VECADD(isec.start, co1, epsilon);
1196         VECADD(end, co2, epsilon);
1197         VECSUB(isec.vec, end, isec.start);
1198
1199 #if 0
1200         /*if(RE_ray_tree_intersect(mdb->raytree, &isec)) {*/
1201 #endif
1202
1203         if(meshdeform_intersect(mdb, &isec)) {
1204                 len= isec.labda;
1205                 mface=(MFace*)isec.hit.face;
1206
1207                 /* create MDefBoundIsect */
1208                 isect= BLI_memarena_alloc(mdb->memarena, sizeof(*isect));
1209
1210                 /* compute intersection coordinate */
1211                 isect->co[0]= co1[0] + isec.vec[0]*len;
1212                 isect->co[1]= co1[1] + isec.vec[1]*len;
1213                 isect->co[2]= co1[2] + isec.vec[2]*len;
1214
1215                 isect->len= VecLenf(co1, isect->co);
1216                 if(isect->len < MESHDEFORM_LEN_THRESHOLD)
1217                         isect->len= MESHDEFORM_LEN_THRESHOLD;
1218
1219                 isect->v[0]= mface->v1;
1220                 isect->v[1]= mface->v2;
1221                 isect->v[2]= mface->v3;
1222                 isect->v[3]= mface->v4;
1223                 isect->nvert= (mface->v4)? 4: 3;
1224
1225                 isect->facing= isec.isect;
1226
1227                 /* compute mean value coordinates for interpolation */
1228                 cagecos= mdb->cagecos;
1229                 VECCOPY(vert[0], cagecos[mface->v1]);
1230                 VECCOPY(vert[1], cagecos[mface->v2]);
1231                 VECCOPY(vert[2], cagecos[mface->v3]);
1232                 if(mface->v4) VECCOPY(vert[3], cagecos[mface->v4]);
1233                 MeanValueWeights(vert, isect->nvert, isect->co, isect->uvw);
1234
1235                 return isect;
1236         }
1237
1238         return NULL;
1239 }
1240
1241 static int meshdeform_inside_cage(MeshDeformBind *mdb, float *co)
1242 {
1243         MDefBoundIsect *isect;
1244         float outside[3], start[3], dir[3];
1245         int i, counter;
1246
1247         for(i=1; i<=6; i++) {
1248                 counter = 0;
1249
1250                 outside[0] = co[0] + (mdb->max[0] - mdb->min[0] + 1.0f)*MESHDEFORM_OFFSET[i][0];
1251                 outside[1] = co[1] + (mdb->max[1] - mdb->min[1] + 1.0f)*MESHDEFORM_OFFSET[i][1];
1252                 outside[2] = co[2] + (mdb->max[2] - mdb->min[2] + 1.0f)*MESHDEFORM_OFFSET[i][2];
1253
1254                 VECCOPY(start, co);
1255                 VECSUB(dir, outside, start);
1256                 Normalize(dir);
1257                 
1258                 isect = meshdeform_ray_tree_intersect(mdb, start, outside);
1259                 if(isect && !isect->facing)
1260                         return 1;
1261         }
1262
1263         return 0;
1264 }
1265
1266 /* solving */
1267
1268 static int meshdeform_index(MeshDeformBind *mdb, int x, int y, int z, int n)
1269 {
1270         int size= mdb->size;
1271         
1272         x += MESHDEFORM_OFFSET[n][0];
1273         y += MESHDEFORM_OFFSET[n][1];
1274         z += MESHDEFORM_OFFSET[n][2];
1275
1276         if(x < 0 || x >= mdb->size)
1277                 return -1;
1278         if(y < 0 || y >= mdb->size)
1279                 return -1;
1280         if(z < 0 || z >= mdb->size)
1281                 return -1;
1282
1283         return x + y*size + z*size*size;
1284 }
1285
1286 static void meshdeform_cell_center(MeshDeformBind *mdb, int x, int y, int z, int n, float *center)
1287 {
1288         x += MESHDEFORM_OFFSET[n][0];
1289         y += MESHDEFORM_OFFSET[n][1];
1290         z += MESHDEFORM_OFFSET[n][2];
1291
1292         center[0]= mdb->min[0] + x*mdb->width[0] + mdb->halfwidth[0];
1293         center[1]= mdb->min[1] + y*mdb->width[1] + mdb->halfwidth[1];
1294         center[2]= mdb->min[2] + z*mdb->width[2] + mdb->halfwidth[2];
1295 }
1296
1297 static void meshdeform_add_intersections(MeshDeformBind *mdb, int x, int y, int z)
1298 {
1299         MDefBoundIsect *isect;
1300         float center[3], ncenter[3];
1301         int i, a;
1302
1303         a= meshdeform_index(mdb, x, y, z, 0);
1304         meshdeform_cell_center(mdb, x, y, z, 0, center);
1305
1306         /* check each outgoing edge for intersection */
1307         for(i=1; i<=6; i++) {
1308                 if(meshdeform_index(mdb, x, y, z, i) == -1)
1309                         continue;
1310
1311                 meshdeform_cell_center(mdb, x, y, z, i, ncenter);
1312
1313                 isect= meshdeform_ray_tree_intersect(mdb, center, ncenter);
1314                 if(isect) {
1315                         mdb->boundisect[a][i-1]= isect;
1316                         mdb->tag[a]= MESHDEFORM_TAG_BOUNDARY;
1317                 }
1318         }
1319 }
1320
1321 static void meshdeform_bind_floodfill(MeshDeformBind *mdb)
1322 {
1323         int *stack, *tag= mdb->tag;
1324         int a, b, i, xyz[3], stacksize, size= mdb->size;
1325
1326         stack= MEM_callocN(sizeof(int)*mdb->size3, "MeshDeformBindStack");
1327
1328         /* we know lower left corner is EXTERIOR because of padding */
1329         tag[0]= MESHDEFORM_TAG_EXTERIOR;
1330         stack[0]= 0;
1331         stacksize= 1;
1332
1333         /* floodfill exterior tag */
1334         while(stacksize > 0) {
1335                 a= stack[--stacksize];
1336
1337                 xyz[2]= a/(size*size);
1338                 xyz[1]= (a - xyz[2]*size*size)/size;
1339                 xyz[0]= a - xyz[1]*size - xyz[2]*size*size;
1340
1341                 for(i=1; i<=6; i++) {
1342                         b= meshdeform_index(mdb, xyz[0], xyz[1], xyz[2], i);
1343
1344                         if(b != -1) {
1345                                 if(tag[b] == MESHDEFORM_TAG_UNTYPED ||
1346                                    (tag[b] == MESHDEFORM_TAG_BOUNDARY && !mdb->boundisect[a][i-1])) {
1347                                         tag[b]= MESHDEFORM_TAG_EXTERIOR;
1348                                         stack[stacksize++]= b;
1349                                 }
1350                         }
1351                 }
1352         }
1353
1354         /* other cells are interior */
1355         for(a=0; a<size*size*size; a++)
1356                 if(tag[a]==MESHDEFORM_TAG_UNTYPED)
1357                         tag[a]= MESHDEFORM_TAG_INTERIOR;
1358
1359 #if 0
1360         {
1361                 int tb, ti, te, ts;
1362                 tb= ti= te= ts= 0;
1363                 for(a=0; a<size*size*size; a++)
1364                         if(tag[a]==MESHDEFORM_TAG_BOUNDARY)
1365                                 tb++;
1366                         else if(tag[a]==MESHDEFORM_TAG_INTERIOR)
1367                                 ti++;
1368                         else if(tag[a]==MESHDEFORM_TAG_EXTERIOR) {
1369                                 te++;
1370
1371                                 if(mdb->semibound[a])
1372                                         ts++;
1373                         }
1374                 
1375                 printf("interior %d exterior %d boundary %d semi-boundary %d\n", ti, te, tb, ts);
1376         }
1377 #endif
1378
1379         MEM_freeN(stack);
1380 }
1381
1382 static float meshdeform_boundary_phi(MeshDeformBind *mdb, MDefBoundIsect *isect, int cagevert)
1383 {
1384         int a;
1385
1386         for(a=0; a<isect->nvert; a++)
1387                 if(isect->v[a] == cagevert)
1388                         return isect->uvw[a];
1389         
1390         return 0.0f;
1391 }
1392
1393 static float meshdeform_interp_w(MeshDeformBind *mdb, float *gridvec, float *vec, int cagevert)
1394 {
1395         float dvec[3], ivec[3], wx, wy, wz, result=0.0f;
1396         float weight, totweight= 0.0f;
1397         int i, a, x, y, z;
1398
1399         for(i=0; i<3; i++) {
1400                 ivec[i]= (int)gridvec[i];
1401                 dvec[i]= gridvec[i] - ivec[i];
1402         }
1403
1404         for(i=0; i<8; i++) {
1405                 if(i & 1) { x= ivec[0]+1; wx= dvec[0]; }
1406                 else { x= ivec[0]; wx= 1.0f-dvec[0]; } 
1407
1408                 if(i & 2) { y= ivec[1]+1; wy= dvec[1]; }
1409                 else { y= ivec[1]; wy= 1.0f-dvec[1]; } 
1410
1411                 if(i & 4) { z= ivec[2]+1; wz= dvec[2]; }
1412                 else { z= ivec[2]; wz= 1.0f-dvec[2]; } 
1413
1414                 CLAMP(x, 0, mdb->size-1);
1415                 CLAMP(y, 0, mdb->size-1);
1416                 CLAMP(z, 0, mdb->size-1);
1417
1418                 a= meshdeform_index(mdb, x, y, z, 0);
1419                 weight= wx*wy*wz;
1420                 result += weight*mdb->phi[a];
1421                 totweight += weight;
1422         }
1423
1424         if(totweight > 0.0f)
1425                 result /= totweight;
1426
1427         return result;
1428 }
1429
1430 static void meshdeform_check_semibound(MeshDeformBind *mdb, int x, int y, int z)
1431 {
1432         int i, a;
1433
1434         a= meshdeform_index(mdb, x, y, z, 0);
1435         if(mdb->tag[a] != MESHDEFORM_TAG_EXTERIOR)
1436                 return;
1437
1438         for(i=1; i<=6; i++)
1439                 if(mdb->boundisect[a][i-1]) 
1440                         mdb->semibound[a]= 1;
1441 }
1442
1443 static float meshdeform_boundary_total_weight(MeshDeformBind *mdb, int x, int y, int z)
1444 {
1445         float weight, totweight= 0.0f;
1446         int i, a;
1447
1448         a= meshdeform_index(mdb, x, y, z, 0);
1449
1450         /* count weight for neighbour cells */
1451         for(i=1; i<=6; i++) {
1452                 if(meshdeform_index(mdb, x, y, z, i) == -1)
1453                         continue;
1454
1455                 if(mdb->boundisect[a][i-1])
1456                         weight= 1.0f/mdb->boundisect[a][i-1]->len;
1457                 else if(!mdb->semibound[a])
1458                         weight= 1.0f/mdb->width[0];
1459                 else
1460                         weight= 0.0f;
1461
1462                 totweight += weight;
1463         }
1464
1465         return totweight;
1466 }
1467
1468 static void meshdeform_matrix_add_cell(MeshDeformBind *mdb, int x, int y, int z)
1469 {
1470         MDefBoundIsect *isect;
1471         float weight, totweight;
1472         int i, a, acenter;
1473
1474         acenter= meshdeform_index(mdb, x, y, z, 0);
1475         if(mdb->tag[acenter] == MESHDEFORM_TAG_EXTERIOR)
1476                 return;
1477
1478         nlMatrixAdd(mdb->varidx[acenter], mdb->varidx[acenter], 1.0f);
1479         
1480         totweight= meshdeform_boundary_total_weight(mdb, x, y, z);
1481         for(i=1; i<=6; i++) {
1482                 a= meshdeform_index(mdb, x, y, z, i);
1483                 if(a == -1 || mdb->tag[a] == MESHDEFORM_TAG_EXTERIOR)
1484                         continue;
1485
1486                 isect= mdb->boundisect[acenter][i-1];
1487                 if (!isect) {
1488                         weight= (1.0f/mdb->width[0])/totweight;
1489                         nlMatrixAdd(mdb->varidx[acenter], mdb->varidx[a], -weight);
1490                 }
1491         }
1492 }
1493
1494 static void meshdeform_matrix_add_rhs(MeshDeformBind *mdb, int x, int y, int z, int cagevert)
1495 {
1496         MDefBoundIsect *isect;
1497         float rhs, weight, totweight;
1498         int i, a, acenter;
1499
1500         acenter= meshdeform_index(mdb, x, y, z, 0);
1501         if(mdb->tag[acenter] == MESHDEFORM_TAG_EXTERIOR)
1502                 return;
1503
1504         totweight= meshdeform_boundary_total_weight(mdb, x, y, z);
1505         for(i=1; i<=6; i++) {
1506                 a= meshdeform_index(mdb, x, y, z, i);
1507                 if(a == -1)
1508                         continue;
1509
1510                 isect= mdb->boundisect[acenter][i-1];
1511
1512                 if (isect) {
1513                         weight= (1.0f/isect->len)/totweight;
1514                         rhs= weight*meshdeform_boundary_phi(mdb, isect, cagevert);
1515                         nlRightHandSideAdd(0, mdb->varidx[acenter], rhs);
1516                 }
1517         }
1518 }
1519
1520 static void meshdeform_matrix_add_semibound_phi(MeshDeformBind *mdb, int x, int y, int z, int cagevert)
1521 {
1522         MDefBoundIsect *isect;
1523         float rhs, weight, totweight;
1524         int i, a;
1525
1526         a= meshdeform_index(mdb, x, y, z, 0);
1527         if(!mdb->semibound[a])
1528                 return;
1529         
1530         mdb->phi[a]= 0.0f;
1531
1532         totweight= meshdeform_boundary_total_weight(mdb, x, y, z);
1533         for(i=1; i<=6; i++) {
1534                 isect= mdb->boundisect[a][i-1];
1535
1536                 if (isect) {
1537                         weight= (1.0f/isect->len)/totweight;
1538                         rhs= weight*meshdeform_boundary_phi(mdb, isect, cagevert);
1539                         mdb->phi[a] += rhs;
1540                 }
1541         }
1542 }
1543
1544 static void meshdeform_matrix_add_exterior_phi(MeshDeformBind *mdb, int x, int y, int z, int cagevert)
1545 {
1546         float phi, totweight;
1547         int i, a, acenter;
1548
1549         acenter= meshdeform_index(mdb, x, y, z, 0);
1550         if(mdb->tag[acenter] != MESHDEFORM_TAG_EXTERIOR || mdb->semibound[acenter])
1551                 return;
1552
1553         phi= 0.0f;
1554         totweight= 0.0f;
1555         for(i=1; i<=6; i++) {
1556                 a= meshdeform_index(mdb, x, y, z, i);
1557
1558                 if(a != -1 && mdb->semibound[a]) {
1559                         phi += mdb->phi[a];
1560                         totweight += 1.0f;
1561                 }
1562         }
1563
1564         if(totweight != 0.0f)
1565                 mdb->phi[acenter]= phi/totweight;
1566 }
1567
1568 static void meshdeform_matrix_solve(MeshDeformBind *mdb)
1569 {
1570         NLContext *context;
1571         float vec[3], gridvec[3];
1572         int a, b, x, y, z, totvar;
1573         char message[1024];
1574
1575         /* setup variable indices */
1576         mdb->varidx= MEM_callocN(sizeof(int)*mdb->size3, "MeshDeformDSvaridx");
1577         for(a=0, totvar=0; a<mdb->size3; a++)
1578                 mdb->varidx[a]= (mdb->tag[a] == MESHDEFORM_TAG_EXTERIOR)? -1: totvar++;
1579
1580         if(totvar == 0) {
1581                 MEM_freeN(mdb->varidx);
1582                 return;
1583         }
1584
1585         progress_bar(0, "Starting mesh deform solve");
1586
1587         /* setup opennl solver */
1588         nlNewContext();
1589         context= nlGetCurrent();
1590
1591         nlSolverParameteri(NL_NB_VARIABLES, totvar);
1592         nlSolverParameteri(NL_NB_ROWS, totvar);
1593         nlSolverParameteri(NL_NB_RIGHT_HAND_SIDES, 1);
1594
1595         nlBegin(NL_SYSTEM);
1596         nlBegin(NL_MATRIX);
1597
1598         /* build matrix */
1599         for(z=0; z<mdb->size; z++)
1600                 for(y=0; y<mdb->size; y++)
1601                         for(x=0; x<mdb->size; x++)
1602                                 meshdeform_matrix_add_cell(mdb, x, y, z);
1603
1604         /* solve for each cage vert */
1605         for(a=0; a<mdb->totcagevert; a++) {
1606                 if(a != 0) {
1607                         nlBegin(NL_SYSTEM);
1608                         nlBegin(NL_MATRIX);
1609                 }
1610
1611                 /* fill in right hand side and solve */
1612                 for(z=0; z<mdb->size; z++)
1613                         for(y=0; y<mdb->size; y++)
1614                                 for(x=0; x<mdb->size; x++)
1615                                         meshdeform_matrix_add_rhs(mdb, x, y, z, a);
1616
1617                 nlEnd(NL_MATRIX);
1618                 nlEnd(NL_SYSTEM);
1619
1620 #if 0
1621                 nlPrintMatrix();
1622 #endif
1623
1624                 if(nlSolveAdvanced(NULL, NL_TRUE)) {
1625                         for(z=0; z<mdb->size; z++)
1626                                 for(y=0; y<mdb->size; y++)
1627                                         for(x=0; x<mdb->size; x++)
1628                                                 meshdeform_matrix_add_semibound_phi(mdb, x, y, z, a);
1629
1630                         for(z=0; z<mdb->size; z++)
1631                                 for(y=0; y<mdb->size; y++)
1632                                         for(x=0; x<mdb->size; x++)
1633                                                 meshdeform_matrix_add_exterior_phi(mdb, x, y, z, a);
1634
1635                         for(b=0; b<mdb->size3; b++) {
1636                                 if(mdb->tag[b] != MESHDEFORM_TAG_EXTERIOR)
1637                                         mdb->phi[b]= nlGetVariable(0, mdb->varidx[b]);
1638                                 mdb->totalphi[b] += mdb->phi[b];
1639                         }
1640
1641                         if(mdb->weights) {
1642                                 /* static bind : compute weights for each vertex */
1643                                 for(b=0; b<mdb->totvert; b++) {
1644                                         if(mdb->inside[b]) {
1645                                                 VECCOPY(vec, mdb->vertexcos[b]);
1646                                                 Mat4MulVecfl(mdb->cagemat, vec);
1647                                                 gridvec[0]= (vec[0] - mdb->min[0] - mdb->halfwidth[0])/mdb->width[0];
1648                                                 gridvec[1]= (vec[1] - mdb->min[1] - mdb->halfwidth[1])/mdb->width[1];
1649                                                 gridvec[2]= (vec[2] - mdb->min[2] - mdb->halfwidth[2])/mdb->width[2];
1650
1651                                                 mdb->weights[b*mdb->totcagevert + a]= meshdeform_interp_w(mdb, gridvec, vec, a);
1652                                         }
1653                                 }
1654                         }
1655                         else {
1656                                 MDefBindInfluence *inf;
1657
1658                                 /* dynamic bind */
1659                                 for(b=0; b<mdb->size3; b++) {
1660                                         if(mdb->phi[b] >= MESHDEFORM_MIN_INFLUENCE) {
1661                                                 inf= BLI_memarena_alloc(mdb->memarena, sizeof(*inf));
1662                                                 inf->vertex= a;
1663                                                 inf->weight= mdb->phi[b];
1664                                                 inf->next= mdb->dyngrid[b];
1665                                                 mdb->dyngrid[b]= inf;
1666                                         }
1667                                 }
1668                         }
1669                 }
1670                 else {
1671                         error("Mesh Deform: failed to find solution.");
1672                         break;
1673                 }
1674
1675                 sprintf(message, "Mesh deform solve %d / %d       |||", a+1, mdb->totcagevert);
1676                 progress_bar((float)(a+1)/(float)(mdb->totcagevert), message);
1677         }
1678
1679 #if 0
1680         /* sanity check */
1681         for(b=0; b<mdb->size3; b++)
1682                 if(mdb->tag[b] != MESHDEFORM_TAG_EXTERIOR)
1683                         if(fabs(mdb->totalphi[b] - 1.0f) > 1e-4)
1684                                 printf("totalphi deficiency [%s|%d] %d: %.10f\n",
1685                                         (mdb->tag[b] == MESHDEFORM_TAG_INTERIOR)? "interior": "boundary", mdb->semibound[b], mdb->varidx[b], mdb->totalphi[b]);
1686 #endif
1687         
1688         /* free */
1689         MEM_freeN(mdb->varidx);
1690
1691         nlDeleteContext(context);
1692 }
1693
1694 void harmonic_coordinates_bind(Scene *scene, MeshDeformModifierData *mmd, float (*vertexcos)[3], int totvert, float cagemat[][4])
1695 {
1696         MeshDeformBind mdb;
1697         MDefBindInfluence *inf;
1698         MDefInfluence *mdinf;
1699         MDefCell *cell;
1700         MVert *mvert;
1701         float center[3], vec[3], maxwidth, totweight;
1702         int a, b, x, y, z, totinside, offset;
1703
1704         waitcursor(1);
1705         start_progress_bar();
1706
1707         memset(&mdb, 0, sizeof(MeshDeformBind));
1708
1709         /* get mesh and cage mesh */
1710         mdb.vertexcos= vertexcos;
1711         mdb.totvert= totvert;
1712         
1713         mdb.cagedm= mesh_create_derived_no_deform(scene, mmd->object, NULL, CD_MASK_BAREMESH);
1714         mdb.totcagevert= mdb.cagedm->getNumVerts(mdb.cagedm);
1715         mdb.cagecos= MEM_callocN(sizeof(*mdb.cagecos)*mdb.totcagevert, "MeshDeformBindCos");
1716         Mat4CpyMat4(mdb.cagemat, cagemat);
1717
1718         mvert= mdb.cagedm->getVertArray(mdb.cagedm);
1719         for(a=0; a<mdb.totcagevert; a++)
1720                 VECCOPY(mdb.cagecos[a], mvert[a].co)
1721
1722         /* compute bounding box of the cage mesh */
1723         INIT_MINMAX(mdb.min, mdb.max);
1724
1725         for(a=0; a<mdb.totcagevert; a++)
1726                 DO_MINMAX(mdb.cagecos[a], mdb.min, mdb.max);
1727
1728         /* allocate memory */
1729         mdb.size= (2<<(mmd->gridsize-1)) + 2;
1730         mdb.size3= mdb.size*mdb.size*mdb.size;
1731         mdb.tag= MEM_callocN(sizeof(int)*mdb.size3, "MeshDeformBindTag");
1732         mdb.phi= MEM_callocN(sizeof(float)*mdb.size3, "MeshDeformBindPhi");
1733         mdb.totalphi= MEM_callocN(sizeof(float)*mdb.size3, "MeshDeformBindTotalPhi");
1734         mdb.boundisect= MEM_callocN(sizeof(*mdb.boundisect)*mdb.size3, "MDefBoundIsect");
1735         mdb.semibound= MEM_callocN(sizeof(int)*mdb.size3, "MDefSemiBound");
1736
1737         mdb.inside= MEM_callocN(sizeof(int)*mdb.totvert, "MDefInside");
1738
1739         if(mmd->flag & MOD_MDEF_DYNAMIC_BIND)
1740                 mdb.dyngrid= MEM_callocN(sizeof(MDefBindInfluence*)*mdb.size3, "MDefDynGrid");
1741         else
1742                 mdb.weights= MEM_callocN(sizeof(float)*mdb.totvert*mdb.totcagevert, "MDefWeights");
1743
1744         mdb.memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
1745         BLI_memarena_use_calloc(mdb.memarena);
1746
1747         /* make bounding box equal size in all directions, add padding, and compute
1748          * width of the cells */
1749         maxwidth = -1.0f;
1750         for(a=0; a<3; a++)
1751                 if(mdb.max[a]-mdb.min[a] > maxwidth)
1752                         maxwidth= mdb.max[a]-mdb.min[a];
1753
1754         for(a=0; a<3; a++) {
1755                 center[a]= (mdb.min[a]+mdb.max[a])*0.5f;
1756                 mdb.min[a]= center[a] - maxwidth*0.5f;
1757                 mdb.max[a]= center[a] + maxwidth*0.5f;
1758
1759                 mdb.width[a]= (mdb.max[a]-mdb.min[a])/(mdb.size-4);
1760                 mdb.min[a] -= 2.1f*mdb.width[a];
1761                 mdb.max[a] += 2.1f*mdb.width[a];
1762
1763                 mdb.width[a]= (mdb.max[a]-mdb.min[a])/mdb.size;
1764                 mdb.halfwidth[a]= mdb.width[a]*0.5f;
1765         }
1766
1767         progress_bar(0, "Setting up mesh deform system");
1768
1769 #if 0
1770         /* create ray tree */
1771         meshdeform_ray_tree_create(&mdb);
1772 #endif
1773
1774         totinside= 0;
1775         for(a=0; a<mdb.totvert; a++) {
1776                 VECCOPY(vec, mdb.vertexcos[a]);
1777                 Mat4MulVecfl(mdb.cagemat, vec);
1778                 mdb.inside[a]= meshdeform_inside_cage(&mdb, vec);
1779                 if(mdb.inside[a])
1780                         totinside++;
1781         }
1782
1783         /* free temporary MDefBoundIsects */
1784         BLI_memarena_free(mdb.memarena);
1785         mdb.memarena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE);
1786
1787         /* start with all cells untyped */
1788         for(a=0; a<mdb.size3; a++)
1789                 mdb.tag[a]= MESHDEFORM_TAG_UNTYPED;
1790         
1791         /* detect intersections and tag boundary cells */
1792         for(z=0; z<mdb.size; z++)
1793                 for(y=0; y<mdb.size; y++)
1794                         for(x=0; x<mdb.size; x++)
1795                                 meshdeform_add_intersections(&mdb, x, y, z);
1796
1797 #if 0
1798         /* free ray tree */
1799         meshdeform_ray_tree_free(&mdb);
1800 #endif
1801
1802         /* compute exterior and interior tags */
1803         meshdeform_bind_floodfill(&mdb);
1804
1805         for(z=0; z<mdb.size; z++)
1806                 for(y=0; y<mdb.size; y++)
1807                         for(x=0; x<mdb.size; x++)
1808                                 meshdeform_check_semibound(&mdb, x, y, z);
1809
1810         /* solve */
1811         meshdeform_matrix_solve(&mdb);
1812
1813         /* assign results */
1814         mmd->bindcos= (float*)mdb.cagecos;
1815         mmd->totvert= mdb.totvert;
1816         mmd->totcagevert= mdb.totcagevert;
1817         Mat4CpyMat4(mmd->bindmat, mmd->object->obmat);
1818
1819         if(mmd->flag & MOD_MDEF_DYNAMIC_BIND) {
1820                 mmd->totinfluence= 0;
1821                 for(a=0; a<mdb.size3; a++)
1822                         for(inf=mdb.dyngrid[a]; inf; inf=inf->next)
1823                                 mmd->totinfluence++;
1824
1825                 /* convert MDefBindInfluences to smaller MDefInfluences */
1826                 mmd->dyngrid= MEM_callocN(sizeof(MDefCell)*mdb.size3, "MDefDynGrid");
1827                 mmd->dyninfluences= MEM_callocN(sizeof(MDefInfluence)*mmd->totinfluence, "MDefInfluence");
1828                 offset= 0;
1829                 for(a=0; a<mdb.size3; a++) {
1830                         cell= &mmd->dyngrid[a];
1831                         cell->offset= offset;
1832
1833                         totweight= 0.0f;
1834                         mdinf= mmd->dyninfluences + cell->offset;
1835                         for(inf=mdb.dyngrid[a]; inf; inf=inf->next, mdinf++) {
1836                                 mdinf->weight= inf->weight;
1837                                 mdinf->vertex= inf->vertex;
1838                                 totweight += mdinf->weight;
1839                                 cell->totinfluence++;
1840                         }
1841
1842                         if(totweight > 0.0f) {
1843                                 mdinf= mmd->dyninfluences + cell->offset;
1844                                 for(b=0; b<cell->totinfluence; b++, mdinf++)
1845                                         mdinf->weight /= totweight;
1846                         }
1847
1848                         offset += cell->totinfluence;
1849                 }
1850
1851                 mmd->dynverts= mdb.inside;
1852                 mmd->dyngridsize= mdb.size;
1853                 VECCOPY(mmd->dyncellmin, mdb.min);
1854                 mmd->dyncellwidth= mdb.width[0];
1855                 MEM_freeN(mdb.dyngrid);
1856         }
1857         else {
1858                 mmd->bindweights= mdb.weights;
1859                 MEM_freeN(mdb.inside);
1860         }
1861
1862         /* transform bindcos to world space */
1863         for(a=0; a<mdb.totcagevert; a++)
1864                 Mat4MulVecfl(mmd->object->obmat, mmd->bindcos+a*3);
1865
1866         /* free */
1867         mdb.cagedm->release(mdb.cagedm);
1868         MEM_freeN(mdb.tag);
1869         MEM_freeN(mdb.phi);
1870         MEM_freeN(mdb.totalphi);
1871         MEM_freeN(mdb.boundisect);
1872         MEM_freeN(mdb.semibound);
1873         BLI_memarena_free(mdb.memarena);
1874
1875         end_progress_bar();
1876         waitcursor(0);
1877 }
1878