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