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