2 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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.
18 * The Original Code is Copyright (C) Blender Foundation.
19 * All rights reserved.
21 * The Original Code is: all of this file.
23 * Contributor(s): Andr Pinto
25 * ***** END GPL LICENSE BLOCK *****
28 /** \file blender/blenkernel/intern/shrinkwrap.c
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"
47 #include "BLI_utildefines.h"
49 #include "BKE_shrinkwrap.h"
50 #include "BKE_DerivedMesh.h"
51 #include "BKE_lattice.h"
53 #include "BKE_deform.h"
55 #include "BKE_subsurf.h"
57 #include "BKE_editmesh.h"
61 # include "PIL_time.h"
63 # define TIMEIT_BENCH(expr, id) (expr)
67 #define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n"))
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)
74 BMEditMesh *em = me->edit_btmesh;
77 DerivedMesh *dm = em->derivedFinal;
81 return ob->derivedFinal;
85 void space_transform_from_matrixs(SpaceTransform *data, float local[4][4], float target[4][4])
88 invert_m4_m4(itarget, target);
89 mul_m4_m4m4(data->local2target, itarget, local);
90 invert_m4_m4(data->target2local, data->local2target);
93 void space_transform_apply(const SpaceTransform *data, float co[3])
95 mul_v3_m4v3(co, ((SpaceTransform *)data)->local2target, co);
98 void space_transform_invert(const SpaceTransform *data, float co[3])
100 mul_v3_m4v3(co, ((SpaceTransform *)data)->target2local, co);
103 static void space_transform_apply_normal(const SpaceTransform *data, float no[3])
105 mul_mat3_m4_v3(((SpaceTransform *)data)->local2target, no);
106 normalize_v3(no); /* TODO: could we just determine de scale value from the matrix? */
109 static void space_transform_invert_normal(const SpaceTransform *data, float no[3])
111 mul_mat3_m4_v3(((SpaceTransform *)data)->target2local, no);
112 normalize_v3(no); /* TODO: could we just determine de scale value from the matrix? */
116 * Shrinkwrap to the nearest vertex
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
121 static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
125 BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
126 BVHTreeNearest nearest = NULL_BVHTreeNearest;
129 TIMEIT_BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6), bvhtree_verts);
130 if (treeData.tree == NULL) {
137 nearest.dist = FLT_MAX;
139 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(treeData, calc) schedule(static)
141 for (i = 0; i < calc->numVerts; ++i) {
142 float *co = calc->vertexCos[i];
144 float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
145 if (weight == 0.0f) {
150 /* Convert the vertex to tree coordinates */
152 copy_v3_v3(tmp_co, calc->vert[i].co);
155 copy_v3_v3(tmp_co, co);
157 space_transform_apply(&calc->local2target, tmp_co);
159 /* Use local proximity heuristics (to reduce the nearest search)
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);
167 nearest.dist = FLT_MAX;
169 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
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;
181 /* Convert the coordinates back to mesh coordinates */
182 copy_v3_v3(tmp_co, nearest.co);
183 space_transform_invert(&calc->local2target, tmp_co);
185 interp_v3_v3v3(co, co, tmp_co, weight); /* linear interpolation */
189 free_bvhtree_from_mesh(&treeData);
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)
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)
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
211 float tmp_co[3], tmp_no[3];
212 const float *co, *no;
213 BVHTreeRayHit hit_tmp;
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));
218 /* Apply space transform (TODO readjust dist) */
220 copy_v3_v3(tmp_co, vert);
221 space_transform_apply(transf, tmp_co);
224 copy_v3_v3(tmp_no, dir);
225 space_transform_apply_normal(transf, tmp_no);
228 #ifdef USE_DIST_CORRECT
229 hit_tmp.dist *= mat4_to_scale(((SpaceTransform *)transf)->local2target);
239 BLI_bvhtree_ray_cast(tree, co, no, 0.0f, &hit_tmp, callback, userdata);
241 if (hit_tmp.index != -1) {
242 /* invert the normal first so face culling works on rotated objects */
244 space_transform_invert_normal(transf, hit_tmp.no);
247 if (options & (MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE | MOD_SHRINKWRAP_CULL_TARGET_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))
253 return FALSE; /* Ignore hit */
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);
265 BLI_assert(hit_tmp.dist <= hit->dist);
267 memcpy(hit, &hit_tmp, sizeof(hit_tmp));
274 static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
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};
283 /* Raycast and tree stuff */
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 */
289 BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
291 /* auxiliary target */
292 DerivedMesh *auxMesh = NULL;
293 BVHTreeFromMesh auxData = NULL_BVHTreeFromMesh;
294 SpaceTransform local2aux;
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)
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;
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;
313 normalize_v3(proj_axis);
315 /* Invalid projection direction */
316 if (len_squared_v3(proj_axis) < FLT_EPSILON) {
321 if (calc->smd->auxTarget) {
322 auxMesh = object_get_derived_final(calc->smd->auxTarget);
325 SPACE_TRANSFORM_SETUP(&local2aux, calc->ob, calc->smd->auxTarget);
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)))
334 #pragma omp parallel for private(i, hit) schedule(static)
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);
341 if (weight == 0.0f) {
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);
354 copy_v3_v3(tmp_co, co);
355 copy_v3_v3(tmp_no, proj_axis);
359 copy_v3_v3(tmp_co, co);
360 copy_v3_v3(tmp_no, proj_axis);
365 hit.dist = 10000.0f; /* TODO: we should use FLT_MAX here, but sweepsphere code isn't prepared for that */
367 /* Project over positive direction of axis */
368 if (use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR) {
371 BKE_shrinkwrap_project_normal(0, tmp_co, tmp_no,
372 &local2aux, auxData.tree, &hit,
373 auxData.raycast_callback, &auxData);
376 BKE_shrinkwrap_project_normal(calc->smd->shrinkOpts, tmp_co, tmp_no,
377 &calc->local2target, treeData.tree, &hit,
378 treeData.raycast_callback, &treeData);
381 /* Project over negative direction of axis */
382 if (use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR) {
384 negate_v3_v3(inv_no, tmp_no);
387 BKE_shrinkwrap_project_normal(0, tmp_co, inv_no,
388 &local2aux, auxData.tree, &hit,
389 auxData.raycast_callback, &auxData);
392 BKE_shrinkwrap_project_normal(calc->smd->shrinkOpts, tmp_co, inv_no,
393 &calc->local2target, treeData.tree, &hit,
394 treeData.raycast_callback, &treeData);
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) {
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);
412 /* free data structures */
413 free_bvhtree_from_mesh(&treeData);
414 free_bvhtree_from_mesh(&auxData);
418 * Shrinkwrap moving vertexs to the nearest surface point on the target
420 * it builds a BVHTree from the target mesh and then performs a
421 * NN matches for each vertex
423 static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
427 BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
428 BVHTreeNearest nearest = NULL_BVHTreeNearest;
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) {
439 nearest.dist = FLT_MAX;
442 /* Find the nearest vertex */
444 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc, treeData) schedule(static)
446 for (i = 0; i < calc->numVerts; ++i) {
447 float *co = calc->vertexCos[i];
449 float weight = defvert_array_find_weight_safe(calc->dvert, i, calc->vgroup);
450 if (weight == 0.0f) continue;
452 /* Convert the vertex to tree coordinates */
454 copy_v3_v3(tmp_co, calc->vert[i].co);
457 copy_v3_v3(tmp_co, co);
459 space_transform_apply(&calc->local2target, tmp_co);
461 /* Use local proximity heuristics (to reduce the nearest search)
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);
469 nearest.dist = FLT_MAX;
471 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
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);
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);
488 copy_v3_v3(tmp_co, nearest.co);
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 */
498 free_bvhtree_from_mesh(&treeData);
501 /* Main shrinkwrap function */
502 void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm,
503 float (*vertexCos)[3], int numVerts)
506 DerivedMesh *ss_mesh = NULL;
507 ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData;
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;
514 /* Configure Shrinkwrap calc data */
517 calc.numVerts = numVerts;
518 calc.vertexCos = vertexCos;
521 calc.vgroup = defgroup_name_index(calc.ob, calc.smd->vgroup_name);
523 calc.dvert = dm->getVertDataArray(dm, CD_MDEFORMVERT);
525 else if (calc.ob->type == OB_LATTICE) {
526 calc.dvert = BKE_lattice_deform_verts_get(calc.ob);
531 calc.target = object_get_derived_final(smd->target);
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);
538 /* TODO: smd->keepDist is in global units.. must change to local */
539 calc.keepDist = smd->keepDist;
544 calc.vgroup = defgroup_name_index(calc.ob, smd->vgroup_name);
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);
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 */
557 ss_mesh = subsurf_make_derived_from_derived(dm, &ssmd, NULL, (ob->mode & OB_MODE_EDIT) ? SUBSURF_IN_EDIT_MODE : 0);
560 calc.vert = ss_mesh->getVertDataArray(ss_mesh, CD_MVERT);
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);
568 /* Just to make sure we are not leaving any memory behind */
569 assert(ssmd.emCache == NULL);
570 assert(ssmd.mCache == NULL);
574 /* Projecting target defined - lets work! */
576 switch (smd->shrinkType) {
577 case MOD_SHRINKWRAP_NEAREST_SURFACE:
578 TIMEIT_BENCH(shrinkwrap_calc_nearest_surface_point(&calc), deform_surface);
581 case MOD_SHRINKWRAP_PROJECT:
582 TIMEIT_BENCH(shrinkwrap_calc_normal_projection(&calc), deform_project);
585 case MOD_SHRINKWRAP_NEAREST_VERTEX:
586 TIMEIT_BENCH(shrinkwrap_calc_nearest_vertex(&calc), deform_vertex);
593 ss_mesh->release(ss_mesh);