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