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