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