4 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 * The Original Code is Copyright (C) Blender Foundation.
21 * All rights reserved.
23 * The Original Code is: all of this file.
25 * Contributor(s): André Pinto
27 * ***** END GPL LICENSE BLOCK *****
37 #include "DNA_object_types.h"
38 #include "DNA_modifier_types.h"
39 #include "DNA_meshdata_types.h"
40 #include "DNA_mesh_types.h"
42 #include "BKE_shrinkwrap.h"
43 #include "BKE_DerivedMesh.h"
44 #include "BKE_lattice.h"
45 #include "BKE_utildefines.h"
46 #include "BKE_deform.h"
47 #include "BKE_cdderivedmesh.h"
48 #include "BKE_displist.h"
49 #include "BKE_global.h"
50 #include "BKE_subsurf.h"
52 #include "BLI_arithb.h"
53 #include "BLI_kdtree.h"
54 #include "BLI_kdopbvh.h"
56 #include "RE_raytrace.h"
57 #include "MEM_guardedalloc.h"
62 #define JOIN(a,b) a##b
64 #define OUT_OF_MEMORY() ((void)printf("Shrinkwrap: Out of memory\n"))
66 /* Benchmark macros */
67 #if !defined(_WIN32) && 0
74 struct timeval _tstart, _tend; \
75 clock_t _clock_init = clock(); \
76 gettimeofday ( &_tstart, NULL); \
78 gettimeofday ( &_tend, NULL); \
79 _t1 = ( double ) _tstart.tv_sec + ( double ) _tstart.tv_usec/ ( 1000*1000 ); \
80 _t2 = ( double ) _tend.tv_sec + ( double ) _tend.tv_usec/ ( 1000*1000 ); \
81 printf("%s: %fs (real) %fs (cpu)\n", #a, _t2-_t1, (float)(clock()-_clock_init)/CLOCKS_PER_SEC);\
90 typedef void ( *Shrinkwrap_ForeachVertexCallback) (DerivedMesh *target, float *co, float *normal);
92 /* get derived mesh */
93 //TODO is anyfunction that does this? returning the derivedFinal witouth we caring if its in edit mode or not?
94 DerivedMesh *object_get_derived_final(Object *ob, CustomDataMask dataMask)
98 DerivedMesh *final = NULL;
99 editmesh_get_derived_cage_and_final(&final, dataMask);
103 return mesh_get_derived_final(ob, dataMask);
106 /* Space transform */
107 void space_transform_from_matrixs(SpaceTransform *data, float local[4][4], float target[4][4])
110 Mat4Invert(itarget, target);
111 Mat4MulSerie(data->local2target, itarget, local, 0, 0, 0, 0, 0, 0);
112 Mat4Invert(data->target2local, data->local2target);
115 void space_transform_apply(const SpaceTransform *data, float *co)
117 VecMat4MulVecfl(co, ((SpaceTransform*)data)->local2target, co);
120 void space_transform_invert(const SpaceTransform *data, float *co)
122 VecMat4MulVecfl(co, ((SpaceTransform*)data)->target2local, co);
125 void space_transform_apply_normal(const SpaceTransform *data, float *no)
127 Mat4Mul3Vecfl( ((SpaceTransform*)data)->local2target, no);
128 Normalize(no); // TODO: could we just determine de scale value from the matrix?
131 void space_transform_invert_normal(const SpaceTransform *data, float *no)
133 Mat4Mul3Vecfl(((SpaceTransform*)data)->target2local, no);
134 Normalize(no); // TODO: could we just determine de scale value from the matrix?
138 * Returns the squared distance between two given points
140 static float squared_dist(const float *a, const float *b)
144 return INPR(tmp, tmp);
147 /* Main shrinkwrap function */
148 void shrinkwrapModifier_deform(ShrinkwrapModifierData *smd, Object *ob, DerivedMesh *dm, float (*vertexCos)[3], int numVerts)
151 ShrinkwrapCalcData calc = NULL_ShrinkwrapCalcData;
153 //remove loop dependencies on derived meshs (TODO should this be done elsewhere?)
154 if(smd->target == ob) smd->target = NULL;
155 if(smd->auxTarget == ob) smd->auxTarget = NULL;
158 //Configure Shrinkwrap calc data
162 calc.numVerts = numVerts;
163 calc.vertexCos = vertexCos;
166 calc.vgroup = get_named_vertexgroup_num(calc.ob, calc.smd->vgroup_name);
169 calc.dvert = calc.original->getVertDataArray(calc.original, CD_MDEFORMVERT);
171 else if(calc.ob->type == OB_LATTICE)
173 calc.dvert = lattice_get_deform_verts(calc.ob);
179 //TODO currently we need a copy in case object_get_derived_final returns an emDM that does not defines getVertArray or getFace array
180 calc.target = CDDM_copy( object_get_derived_final(smd->target, CD_MASK_BAREMESH) );
182 //TODO there might be several "bugs" on non-uniform scales matrixs.. because it will no longer be nearest surface, not sphere projection
183 //because space has been deformed
184 space_transform_setup(&calc.local2target, ob, smd->target);
186 calc.keepDist = smd->keepDist; //TODO: smd->keepDist is in global units.. must change to local
190 //Projecting target defined - lets work!
193 switch(smd->shrinkType)
195 case MOD_SHRINKWRAP_NEAREST_SURFACE:
196 BENCH(shrinkwrap_calc_nearest_surface_point(&calc));
199 case MOD_SHRINKWRAP_PROJECT:
200 BENCH(shrinkwrap_calc_normal_projection(&calc));
203 case MOD_SHRINKWRAP_NEAREST_VERTEX:
204 BENCH(shrinkwrap_calc_nearest_vertex(&calc));
211 calc.target->release( calc.target );
215 * Shrinkwrap to the nearest vertex
217 * it builds a kdtree of vertexs we can attach to and then
218 * for each vertex performs a nearest vertex search on the tree
220 void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
224 BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
225 BVHTreeNearest nearest = NULL_BVHTreeNearest;
228 BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6));
229 if(treeData.tree == NULL)
237 nearest.dist = FLT_MAX;
239 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(treeData,calc) schedule(static)
240 for(i = 0; i<calc->numVerts; ++i)
242 float *co = calc->vertexCos[i];
244 float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
245 if(weight == 0.0f) continue;
248 space_transform_apply(&calc->local2target, tmp_co); //Convert the coordinates to the tree coordinates
250 //Use local proximity heuristics (to reduce the nearest search)
252 //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
253 //so we can initiate the "nearest.dist" with the expected value to that last hit.
254 //This will lead in prunning of the search tree.
255 if(nearest.index != -1)
256 nearest.dist = squared_dist(tmp_co, nearest.co);
258 nearest.dist = FLT_MAX;
260 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
263 //Found the nearest vertex
264 if(nearest.index != -1)
266 //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
267 float dist = sasqrt(nearest.dist);
268 if(dist > FLT_EPSILON) weight *= (dist - calc->keepDist)/dist;
270 //Convert the coordinates back to mesh coordinates
271 VECCOPY(tmp_co, nearest.co);
272 space_transform_invert(&calc->local2target, tmp_co);
274 VecLerpf(co, co, tmp_co, weight); //linear interpolation
278 free_bvhtree_from_mesh(&treeData);
282 * This function raycast a single vertex and updates the hit if the "hit" is considered valid.
283 * Returns TRUE if "hit" was updated.
284 * Opts control whether an hit is valid or not
285 * Supported options are:
286 * MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE (front faces hits are ignored)
287 * MOD_SHRINKWRAP_CULL_TARGET_BACKFACE (back faces hits are ignored)
289 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)
291 float tmp_co[3], tmp_no[3];
292 const float *co, *no;
293 BVHTreeRayHit hit_tmp;
295 //Copy from hit (we need to convert hit rays from one space coordinates to the other
296 memcpy( &hit_tmp, hit, sizeof(hit_tmp) );
298 //Apply space transform (TODO readjust dist)
301 VECCOPY( tmp_co, vert );
302 space_transform_apply( transf, tmp_co );
305 VECCOPY( tmp_no, dir );
306 space_transform_apply_normal( transf, tmp_no );
309 hit_tmp.dist *= Mat4ToScalef( ((SpaceTransform*)transf)->local2target );
319 BLI_bvhtree_ray_cast(tree, co, no, 0.0f, &hit_tmp, callback, userdata);
321 if(hit_tmp.index != -1)
323 float dot = INPR( dir, hit_tmp.no);
325 if(((options & MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE) && dot <= 0.0f)
326 || ((options & MOD_SHRINKWRAP_CULL_TARGET_BACKFACE) && dot >= 0.0f))
327 return FALSE; //Ignore hit
330 //Inverting space transform (TODO make coeherent with the initial dist readjust)
333 space_transform_invert( transf, hit_tmp.co );
334 space_transform_invert_normal( transf, hit_tmp.no );
336 hit_tmp.dist = VecLenf( (float*)vert, hit_tmp.co );
339 memcpy(hit, &hit_tmp, sizeof(hit_tmp) );
346 void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc)
350 //Options about projection direction
351 const char use_normal = calc->smd->shrinkOpts;
352 float proj_axis[3] = {0.0f, 0.0f, 0.0f};
353 MVert *vert = NULL; //Needed in case of vertex normal
354 DerivedMesh* ss_mesh = NULL;
356 //Raycast and tree stuff
358 BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh; //target
361 DerivedMesh * aux_mesh = NULL;
362 BVHTreeFromMesh auxData= NULL_BVHTreeFromMesh;
363 SpaceTransform local2aux;
368 //Prepare data to retrieve the direction in which we should project each vertex
369 if(calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL)
371 //No Mvert information: jump to "free memory and return" part
372 if(calc->original == NULL) break;
374 if(calc->smd->subsurfLevels)
376 SubsurfModifierData smd;
377 memset(&smd, 0, sizeof(smd));
378 smd.subdivType = ME_CC_SUBSURF; //catmull clark
379 smd.levels = calc->smd->subsurfLevels; //levels
381 ss_mesh = subsurf_make_derived_from_derived(calc->original, &smd, FALSE, NULL, 0, 0);
385 vert = ss_mesh->getVertDataArray(ss_mesh, CD_MVERT);
388 //TRICKY: this code assumes subsurface will have the transformed original vertices
389 //in their original order at the end of the vert array.
391 + ss_mesh->getNumVerts(ss_mesh)
392 - calc->original->getNumVerts(calc->original);
396 //To make sure we are not letting any memory behind
397 assert(smd.emCache == NULL);
398 assert(smd.mCache == NULL);
401 vert = calc->original->getVertDataArray(calc->original, CD_MVERT);
403 //Not able to get vert information: jump to "free memory and return" part
404 if(vert == NULL) break;
408 //The code supports any axis that is a combination of X,Y,Z.. altought currently UI only allows to set the 3 diferent axis
409 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_X_AXIS) proj_axis[0] = 1.0f;
410 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Y_AXIS) proj_axis[1] = 1.0f;
411 if(calc->smd->projAxis & MOD_SHRINKWRAP_PROJECT_OVER_Z_AXIS) proj_axis[2] = 1.0f;
413 Normalize(proj_axis);
415 //Invalid projection direction: jump to "free memory and return" part
416 if(INPR(proj_axis, proj_axis) < FLT_EPSILON) break;
419 //If the user doesn't allows to project in any direction of projection axis... then theres nothing todo.
420 if((use_normal & (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0)
421 break; //jump to "free memory and return" part
425 BENCH(bvhtree_from_mesh_faces(&treeData, calc->target, calc->keepDist, 4, 6));
426 if(treeData.tree == NULL)
427 break; //jump to "free memory and return" part
430 //Build auxiliar target
431 if(calc->smd->auxTarget)
433 space_transform_setup( &local2aux, calc->ob, calc->smd->auxTarget);
435 aux_mesh = CDDM_copy( object_get_derived_final(calc->smd->auxTarget, CD_MASK_BAREMESH) ); //TODO currently we need a copy in case object_get_derived_final returns an emDM that does not defines getVertArray or getFace array
437 BENCH(bvhtree_from_mesh_faces(&auxData, aux_mesh, 0.0, 4, 6));
439 printf("Auxiliar target finalDerived mesh is null\n");
443 //Now, everything is ready to project the vertexs!
444 #pragma omp parallel for private(i,hit) schedule(static)
445 for(i = 0; i<calc->numVerts; ++i)
447 float *co = calc->vertexCos[i];
448 float tmp_co[3], tmp_no[3];
449 float lim = 10000.0f; //TODO: we should use FLT_MAX here, but sweepsphere code isnt prepared for that
450 float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
452 if(weight == 0.0f) continue;
456 VECCOPY(tmp_co, vert[i].co);
465 NormalShortToFloat(tmp_no, vert[i].no);
467 VECCOPY( tmp_no, proj_axis );
474 //Project over positive direction of axis
475 if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR)
479 normal_projection_project_vertex(0, tmp_co, tmp_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
481 normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, tmp_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
484 //Project over negative direction of axis
485 if(use_normal & MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)
487 float inv_no[3] = { -tmp_no[0], -tmp_no[1], -tmp_no[2] };
491 normal_projection_project_vertex(0, tmp_co, inv_no, &local2aux, auxData.tree, &hit, auxData.raycast_callback, &auxData);
493 normal_projection_project_vertex(calc->smd->shrinkOpts, tmp_co, inv_no, &calc->local2target, treeData.tree, &hit, treeData.raycast_callback, &treeData);
499 VecLerpf(co, co, hit.co, weight);
504 //Simple do{} while(0) structure to allow to easily jump to the "free memory and return" part
507 //free data structures
509 free_bvhtree_from_mesh(&treeData);
510 free_bvhtree_from_mesh(&auxData);
513 aux_mesh->release(aux_mesh);
516 ss_mesh->release(ss_mesh);
520 * Shrinkwrap moving vertexs to the nearest surface point on the target
522 * it builds a BVHTree from the target mesh and then performs a
523 * NN matchs for each vertex
525 void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
529 BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
530 BVHTreeNearest nearest = NULL_BVHTreeNearest;
534 //Create a bvh-tree of the given target
535 BENCH(bvhtree_from_mesh_faces( &treeData, calc->target, 0.0, 2, 6));
536 if(treeData.tree == NULL)
544 nearest.dist = FLT_MAX;
547 //Find the nearest vertex
548 #pragma omp parallel for default(none) private(i) firstprivate(nearest) shared(calc,treeData) schedule(static)
549 for(i = 0; i<calc->numVerts; ++i)
551 float *co = calc->vertexCos[i];
553 float weight = vertexgroup_get_vertex_weight(calc->dvert, i, calc->vgroup);
554 if(weight == 0.0f) continue;
556 //Convert the vertex to tree coordinates
558 space_transform_apply(&calc->local2target, tmp_co);
560 //Use local proximity heuristics (to reduce the nearest search)
562 //If we already had an hit before.. we assume this vertex is going to have a close hit to that other vertex
563 //so we can initiate the "nearest.dist" with the expected value to that last hit.
564 //This will lead in prunning of the search tree.
565 if(nearest.index != -1)
566 nearest.dist = squared_dist(tmp_co, nearest.co);
568 nearest.dist = FLT_MAX;
570 BLI_bvhtree_find_nearest(treeData.tree, tmp_co, &nearest, treeData.nearest_callback, &treeData);
572 //Found the nearest vertex
573 if(nearest.index != -1)
575 if(calc->smd->shrinkOpts & MOD_SHRINKWRAP_KEEP_ABOVE_SURFACE)
577 //Make the vertex stay on the front side of the face
578 VECADDFAC(tmp_co, nearest.co, nearest.no, calc->keepDist);
582 //Adjusting the vertex weight, so that after interpolating it keeps a certain distance from the nearest position
583 float dist = sasqrt( nearest.dist );
584 if(dist > FLT_EPSILON)
585 VecLerpf(tmp_co, tmp_co, nearest.co, (dist - calc->keepDist)/dist); //linear interpolation
587 VECCOPY( tmp_co, nearest.co );
590 //Convert the coordinates back to mesh coordinates
591 space_transform_invert(&calc->local2target, tmp_co);
592 VecLerpf(co, co, tmp_co, weight); //linear interpolation
597 free_bvhtree_from_mesh(&treeData);