merge with/from trunk at r35190
[blender.git] / source / blender / blenkernel / intern / shrinkwrap.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) Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): Andr Pinto
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29 #include <string.h>
30 #include <float.h>
31 #include <math.h>
32 #include <memory.h>
33 #include <stdio.h>
34 #include <time.h>
35 #include <assert.h>
36
37 #include "DNA_object_types.h"
38 #include "DNA_modifier_types.h"
39 #include "DNA_meshdata_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_scene_types.h"
42 #include "DNA_windowmanager_types.h"
43
44 #include "BLI_editVert.h"
45 #include "BLI_math.h"
46 #include "BLI_utildefines.h"
47
48 #include "BKE_shrinkwrap.h"
49 #include "BKE_DerivedMesh.h"
50 #include "BKE_lattice.h"
51
52 #include "BKE_deform.h"
53 #include "BKE_mesh.h"
54 #include "BKE_subsurf.h"
55 #include "BKE_mesh.h"
56 #include "BKE_tessmesh.h"
57
58 /* Util macros */
59 #define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n"))
60
61 /* Benchmark macros */
62 #if !defined(_WIN32) && 0
63
64 #include <sys/time.h>
65
66 #define BENCH(a)        \
67         do {                    \
68                 double _t1, _t2;                                \
69                 struct timeval _tstart, _tend;  \
70                 clock_t _clock_init = clock();  \
71                 gettimeofday ( &_tstart, NULL); \
72                 (a);                                                    \
73                 gettimeofday ( &_tend, NULL);   \
74                 _t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 );    \
75                 _t2 = ( double )   _tend.tv_sec + ( double )   _tend.tv_usec/ ( 1000*1000 );    \
76                 printf("%s: %fs (real) %fs (cpu)\n", #a, _t2-_t1, (float)(clock()-_clock_init)/CLOCKS_PER_SEC);\
77         } while(0)
78
79 #else
80
81 #define BENCH(a)        (a)
82
83 #endif
84
85 typedef void ( *Shrinkwrap_ForeachVertexCallback) (DerivedMesh *target, float *co, float *normal);
86
87 /* get derived mesh */
88 //TODO is anyfunction that does this? returning the derivedFinal witouth we caring if its in edit mode or not?
89 DerivedMesh *object_get_derived_final(Object *ob)
90 {
91         Mesh *me= ob->data;
92         BMEditMesh *em = me->edit_btmesh;
93
94         if (em)
95         {
96                 DerivedMesh *dm = em->derivedFinal;
97                 return dm;
98         }
99
100         return ob->derivedFinal;
101 }
102
103 /* Space transform */
104 void space_transform_from_matrixs(SpaceTransform *data, float local[4][4], float target[4][4])
105 {
106         float itarget[4][4];
107         invert_m4_m4(itarget, target);
108         mul_serie_m4(data->local2target, itarget, local, NULL, NULL, NULL, NULL, NULL, NULL);
109         invert_m4_m4(data->target2local, data->local2target);
110 }
111
112 void space_transform_apply(const SpaceTransform *data, float *co)
113 {
114         mul_v3_m4v3(co, ((SpaceTransform*)data)->local2target, co);
115 }
116
117 void space_transform_invert(const SpaceTransform *data, float *co)
118 {
119         mul_v3_m4v3(co, ((SpaceTransform*)data)->target2local, co);
120 }
121
122 static void space_transform_apply_normal(const SpaceTransform *data, float *no)
123 {
124         mul_mat3_m4_v3( ((SpaceTransform*)data)->local2target, no);
125         normalize_v3(no); // TODO: could we just determine de scale value from the matrix?
126 }
127
128 static void space_transform_invert_normal(const SpaceTransform *data, float *no)
129 {
130         mul_mat3_m4_v3(((SpaceTransform*)data)->target2local, no);
131         normalize_v3(no); // TODO: could we just determine de scale value from the matrix?
132 }
133
134 /*
135  * Returns the squared distance between two given points
136  */
137 static float squared_dist(const float *a, const float *b)
138 {
139         float tmp[3];
140         VECSUB(tmp, a, b);
141         return INPR(tmp, tmp);
142 }
143
144 /*
145  * Shrinkwrap to the nearest vertex
146  *
147  * it builds a kdtree of vertexs we can attach to and then
148  * for each vertex performs a nearest vertex search on the tree
149  */
150 static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
151 {
152         int i;
153
154         BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
155         BVHTreeNearest  nearest  = NULL_BVHTreeNearest;
156
157
158         BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6));
159         if(treeData.tree == NULL)
160         {
161                 OUT_OF_MEMORY();
162                 return;
163         }
164
165         //Setup nearest
166         nearest.index = -1;
167         nearest.dist = FLT_MAX;
168 #ifndef __APPLE__
169 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(treeData,calc) schedule(static)
170 #endif
171         for(i = 0; i<calc->numVerts; ++i)
172         {
173                 float *co = calc->vertexCos[i];
174                 float tmp_co[3];
175                 float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
176                 if(weight == 0.0f) continue;
177
178
179                 //Convert the vertex to tree coordinates
180                 if(calc->vert)
181                 {
182                         VECCOPY(tmp_co, calc->vert[i].co);
183                 }
184                 else
185                 {
186                         VECCOPY(tmp_co, co);
187                 }
188                 space_transform_apply(&calc->local2target, tmp_co);
189
190                 //Use local proximity heuristics (to reduce the nearest search)
191                 //
192                 //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
193                 //so we can initiate the "nearest.dist" with the expected value to that last hit.
194                 //This will lead in prunning of the search tree.
195                 if(nearest.index != -1)
196                         nearest.dist = squared_dist(tmp_co, nearest.co);
197                 else
198                         nearest.dist = FLT_MAX;
199
200                 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
201
202
203                 //Found the nearest vertex
204                 if(nearest.index != -1)
205                 {
206                         //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
207                         float dist = sasqrt(nearest.dist);
208                         if(dist > FLT_EPSILON) weight *= (dist - calc->keepDist)/dist;
209
210                         //Convert the coordinates back to mesh coordinates
211                         VECCOPY(tmp_co, nearest.co);
212                         space_transform_invert(&calc->local2target, tmp_co);
213
214                         interp_v3_v3v3(co, co, tmp_co, weight); //linear interpolation
215                 }
216         }
217
218         free_bvhtree_from_mesh(&treeData);
219 }
220
221 /*
222  * This function raycast a single vertex and updates the hit if the "hit" is considered valid.
223  * Returns TRUE if "hit" was updated.
224  * Opts control whether an hit is valid or not
225  * Supported options are:
226  *      MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (front faces hits are ignored)
227  *      MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (back faces hits are ignored)
228  */
229 int normal_projection_project_vertex(char options, const float *vert, const float *dir, const SpaceTransform *transf, BVHTree *tree, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata)
230 {
231         float tmp_co[3], tmp_no[3];
232         const float *co, *no;
233         BVHTreeRayHit hit_tmp;
234
235         //Copy from hit (we need to convert hit rays from one space coordinates to the other
236         memcpy( &hit_tmp, hit, sizeof(hit_tmp) );
237
238         //Apply space transform (TODO readjust dist)
239         if(transf)
240         {
241                 VECCOPY( tmp_co, vert );
242                 space_transform_apply( transf, tmp_co );
243                 co = tmp_co;
244
245                 VECCOPY( tmp_no, dir );
246                 space_transform_apply_normal( transf, tmp_no );
247                 no = tmp_no;
248
249                 hit_tmp.dist *= mat4_to_scale( ((SpaceTransform*)transf)->local2target );
250         }
251         else
252         {
253                 co = vert;
254                 no = dir;
255         }
256
257         hit_tmp.index = -1;
258
259         BLI_bvhtree_ray_cast(tree, co, no, 0.0f, &hit_tmp, callback, userdata);
260
261         if(hit_tmp.index != -1) {
262                 /* invert the normal first so face culling works on rotated objects */
263                 if(transf) {
264                         space_transform_invert_normal(transf, hit_tmp.no);
265                 }
266
267                 if (options & (MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE|MOD_SHRINKWRAP_CULL_TARGET_BACKFACE)) {
268                         /* apply backface */
269                         const float dot= dot_v3v3(dir, hit_tmp.no);
270                         if(     ((options & MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE) && dot <= 0.0f) ||
271                                 ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f)
272                         ) {
273                                 return FALSE; /* Ignore hit */
274                         }
275                 }
276
277                 if(transf) {
278                         /* Inverting space transform (TODO make coeherent with the initial dist readjust) */
279                         space_transform_invert(transf, hit_tmp.co);
280                         hit_tmp.dist = len_v3v3((float *)vert, hit_tmp.co);
281                 }
282
283                 memcpy(hit, &hit_tmp, sizeof(hit_tmp) );
284                 return TRUE;
285         }
286         return FALSE;
287 }
288
289
290 static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
291 {
292         int i;
293
294         //Options about projection direction
295         const char use_normal   = calc->smd->shrinkOpts;
296         float proj_axis[3]              = {0.0f, 0.0f, 0.0f};
297
298         //Raycast and tree stuff
299         BVHTreeRayHit hit;
300         BVHTreeFromMesh treeData= NULL_BVHTreeFromMesh;
301
302         //auxiliar target
303         DerivedMesh *auxMesh    = NULL;
304         BVHTreeFromMesh auxData = NULL_BVHTreeFromMesh;
305         SpaceTransform local2aux;
306
307         //If the user doesn't allows to project in any direction of projection axis
308         //then theres nothing todo.
309         if((use_normal & (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0)
310                 return;
311
312
313         //Prepare data to retrieve the direction in which we should project each vertex
314         if(calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL)
315         {
316                 if(calc->vert == NULL) return;
317         }
318         else
319         {
320                 //The code supports any axis that is a combination of X,Y,Z
321                 //altought currently UI only allows to set the 3 diferent axis
322                 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS) proj_axis[0] = 1.0f;
323                 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS) proj_axis[1] = 1.0f;
324                 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS) proj_axis[2] = 1.0f;
325
326                 normalize_v3(proj_axis);
327
328                 //Invalid projection direction
329                 if(INPR(proj_axis, proj_axis) < FLT_EPSILON)
330                         return; 
331         }
332
333         if(calc->smd->auxTarget)
334         {
335                 auxMesh = object_get_derived_final(calc->smd->auxTarget);
336                 if(!auxMesh)
337                         return;
338                 space_transform_setup( &local2aux, calc->ob, calc->smd->auxTarget);
339         }
340
341         //After sucessufuly build the trees, start projection vertexs
342         if( bvhtree_from_mesh_faces(&treeData, calc->target, 0.0, 4, 6)
343         &&  (auxMesh == NULL || bvhtree_from_mesh_faces(&auxData, auxMesh, 0.0, 4, 6)))
344         {
345
346 #ifndef __APPLE__
347 #pragma omp parallel for private(i,hit) schedule(static)
348 #endif
349                 for(i = 0; i<calc->numVerts; ++i)
350                 {
351                         float *co = calc->vertexCos[i];
352                         float tmp_co[3], tmp_no[3];
353                         float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
354
355                         if(weight == 0.0f) continue;
356
357                         if(calc->vert)
358                         {
359                                 /* calc->vert contains verts from derivedMesh  */
360                                 /* this coordinated are deformed by vertexCos only for normal projection (to get correct normals) */
361                                 /* for other cases calc->varts contains undeformed coordinates and vertexCos should be used */
362                                 if(calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL) {
363                                         VECCOPY(tmp_co, calc->vert[i].co);
364                                         normal_short_to_float_v3(tmp_no, calc->vert[i].no);
365                                 } else {
366                                         VECCOPY(tmp_co, co);
367                                         VECCOPY(tmp_no, proj_axis);
368                                 }
369                         }
370                         else
371                         {
372                                 VECCOPY(tmp_co, co);
373                                 VECCOPY(tmp_no, proj_axis);
374                         }
375
376
377                         hit.index = -1;
378                         hit.dist = 10000.0f; //TODO: we should use FLT_MAX here, but sweepsphere code isnt prepared for that
379
380                         //Project over positive direction of axis
381                         if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR)
382                         {
383
384                                 if(auxData.tree)
385                                         normal_projection_project_vertex(0, tmp_co, tmp_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
386
387                                 normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
388                         }
389
390                         //Project over negative direction of axis
391                         if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR && hit.index == -1)
392                         {
393                                 float inv_no[3];
394                                 negate_v3_v3(inv_no, tmp_no);
395
396                                 if(auxData.tree)
397                                         normal_projection_project_vertex(0, tmp_co, inv_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
398
399                                 normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
400                         }
401
402
403                         if(hit.index != -1)
404                         {
405                                 madd_v3_v3v3fl(hit.co, hit.co, tmp_no, calc->keepDist);
406                                 interp_v3_v3v3(co, co, hit.co, weight);
407                         }
408                 }
409         }
410
411         //free data structures
412         free_bvhtree_from_mesh(&treeData);
413         free_bvhtree_from_mesh(&auxData);
414 }
415
416 /*
417  * Shrinkwrap moving vertexs to the nearest surface point on the target
418  *
419  * it builds a BVHTree from the target mesh and then performs a
420  * NN matchs for each vertex
421  */
422 static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
423 {
424         int i;
425
426         BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
427         BVHTreeNearest  nearest  = NULL_BVHTreeNearest;
428
429         //Create a bvh-tree of the given target
430         BENCH(bvhtree_from_mesh_faces( &treeData, calc->target, 0.0, 2, 6));
431         if(treeData.tree == NULL)
432         {
433                 OUT_OF_MEMORY();
434                 return;
435         }
436
437         //Setup nearest
438         nearest.index = -1;
439         nearest.dist = FLT_MAX;
440
441
442         //Find the nearest vertex
443 #ifndef __APPLE__
444 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc,treeData) schedule(static)
445 #endif
446         for(i = 0; i<calc->numVerts; ++i)
447         {
448                 float *co = calc->vertexCos[i];
449                 float tmp_co[3];
450                 float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
451                 if(weight == 0.0f) continue;
452
453                 //Convert the vertex to tree coordinates
454                 if(calc->vert)
455                 {
456                         VECCOPY(tmp_co, calc->vert[i].co);
457                 }
458                 else
459                 {
460                         VECCOPY(tmp_co, co);
461                 }
462                 space_transform_apply(&calc->local2target, tmp_co);
463
464                 //Use local proximity heuristics (to reduce the nearest search)
465                 //
466                 //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
467                 //so we can initiate the "nearest.dist" with the expected value to that last hit.
468                 //This will lead in prunning of the search tree.
469                 if(nearest.index != -1)
470                         nearest.dist = squared_dist(tmp_co, nearest.co);
471                 else
472                         nearest.dist = FLT_MAX;
473
474                 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
475
476                 //Found the nearest vertex
477                 if(nearest.index != -1)
478                 {
479                         if(calc->smd->shrinkOpts & MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE)
480                         {
481                                 //Make the vertex stay on the front side of the face
482                                 VECADDFAC(tmp_co, nearest.co, nearest.no, calc->keepDist);
483                         }
484                         else
485                         {
486                                 //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
487                                 float dist = sasqrt( nearest.dist );
488                                 if(dist > FLT_EPSILON)
489                                         interp_v3_v3v3(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist)/dist);       //linear interpolation
490                                 else
491                                         VECCOPY( tmp_co, nearest.co );
492                         }
493
494                         //Convert the coordinates back to mesh coordinates
495                         space_transform_invert(&calc->local2target, tmp_co);
496                         interp_v3_v3v3(co, co, tmp_co, weight); //linear interpolation
497                 }
498         }
499
500         free_bvhtree_from_mesh(&treeData);
501 }
502
503 /* Main shrinkwrap function */
504 void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
505 {
506
507         DerivedMesh *ss_mesh    = NULL;
508         ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData;
509
510         //remove loop dependencies on derived meshs (TODO should this be done elsewhere?)
511         if(smd->target == ob) smd->target = NULL;
512         if(smd->auxTarget == ob) smd->auxTarget = NULL;
513
514
515         //Configure Shrinkwrap calc data
516         calc.smd = smd;
517         calc.ob = ob;
518         calc.numVerts = numVerts;
519         calc.vertexCos = vertexCos;
520
521         //DeformVertex
522         calc.vgroup = defgroup_name_index(calc.ob, calc.smd->vgroup_name);
523         if(dm)
524         {
525                 calc.dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
526         }
527         else if(calc.ob->type == OB_LATTICE)
528         {
529                 calc.dvert = lattice_get_deform_verts(calc.ob);
530         }
531
532
533         if(smd->target)
534         {
535                 calc.target = object_get_derived_final(smd->target);
536
537                 //TODO there might be several "bugs" on non-uniform scales matrixs
538                 //because it will no longer be nearest surface, not sphere projection
539                 //because space has been deformed
540                 space_transform_setup(&calc.local2target, ob, smd->target);
541
542                 //TODO: smd->keepDist is in global units.. must change to local
543                 calc.keepDist = smd->keepDist;
544         }
545
546
547
548         calc.vgroup = defgroup_name_index(calc.ob, smd->vgroup_name);
549
550         if(dm != NULL && smd->shrinkType == MOD_SHRINKWRAP_PROJECT)
551         {
552                 //Setup arrays to get vertexs positions, normals and deform weights
553                 calc.vert   = dm->getVertDataArray(dm, CD_MVERT);
554                 calc.dvert  = dm->getVertDataArray(dm, CD_MDEFORMVERT);
555
556                 //Using vertexs positions/normals as if a subsurface was applied 
557                 if(smd->subsurfLevels)
558                 {
559                         SubsurfModifierData ssmd= {{0}};
560                         ssmd.subdivType = ME_CC_SUBSURF;                //catmull clark
561                         ssmd.levels             = smd->subsurfLevels;   //levels
562
563                         ss_mesh = subsurf_make_derived_from_derived(dm, &ssmd, FALSE, NULL, 0, 0);
564
565                         if(ss_mesh)
566                         {
567                                 calc.vert = ss_mesh->getVertDataArray(ss_mesh, CD_MVERT);
568                                 if(calc.vert)
569                                 {
570                                         //TRICKY: this code assumes subsurface will have the transformed original vertices
571                                         //in their original order at the end of the vert array.
572                                         calc.vert = calc.vert + ss_mesh->getNumVerts(ss_mesh) - dm->getNumVerts(dm);
573                                 }
574                         }
575
576                         //Just to make sure we are not leaving any memory behind
577                         assert(ssmd.emCache == NULL);
578                         assert(ssmd.mCache == NULL);
579                 }
580         }
581
582         //Projecting target defined - lets work!
583         if(calc.target)
584         {
585                 switch(smd->shrinkType)
586                 {
587                         case MOD_SHRINKWRAP_NEAREST_SURFACE:
588                                 BENCH(shrinkwrap_calc_nearest_surface_point(&calc));
589                         break;
590
591                         case MOD_SHRINKWRAP_PROJECT:
592                                 BENCH(shrinkwrap_calc_normal_projection(&calc));
593                         break;
594
595                         case MOD_SHRINKWRAP_NEAREST_VERTEX:
596                                 BENCH(shrinkwrap_calc_nearest_vertex(&calc));
597                         break;
598                 }
599         }
600
601         //free memory
602         if(ss_mesh)
603                 ss_mesh->release(ss_mesh);
604 }
605