Fix T52414: Blender 2.79 crash on object duplication via menu.
[blender.git] / source / blender / editors / transform / transform_snap_object.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  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/editors/transform/transform_snap_object.c
22  *  \ingroup edtransform
23  */
24
25 #include <stdlib.h>
26 #include <math.h>
27 #include <float.h>
28 #include <stdio.h>
29
30 #include "MEM_guardedalloc.h"
31
32 #include "BLI_math.h"
33 #include "BLI_kdopbvh.h"
34 #include "BLI_memarena.h"
35 #include "BLI_ghash.h"
36 #include "BLI_linklist.h"
37 #include "BLI_listbase.h"
38 #include "BLI_utildefines.h"
39
40 #include "DNA_armature_types.h"
41 #include "DNA_curve_types.h"
42 #include "DNA_scene_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_screen_types.h"
46 #include "DNA_view3d_types.h"
47
48 #include "BKE_DerivedMesh.h"
49 #include "BKE_object.h"
50 #include "BKE_anim.h"  /* for duplis */
51 #include "BKE_editmesh.h"
52 #include "BKE_main.h"
53 #include "BKE_tracking.h"
54
55 #include "ED_transform.h"
56 #include "ED_transform_snap_object_context.h"
57 #include "ED_view3d.h"
58 #include "ED_armature.h"
59
60 #include "transform.h"
61
62 enum eViewProj {
63         VIEW_PROJ_NONE = -1,
64         VIEW_PROJ_ORTHO = 0,
65         VIEW_PROJ_PERSP = -1,
66 };
67
68 typedef struct SnapData {
69         short snap_to;
70         float mval[2];
71         float ray_origin[3];
72         float ray_start[3];
73         float ray_dir[3];
74         float pmat[4][4]; /* perspective matrix */
75         float win_half[2];/* win x and y */
76         enum eViewProj view_proj;
77         float depth_range[2];
78 } SnapData;
79
80 typedef struct SnapObjectData {
81         enum {
82                 SNAP_MESH = 1,
83                 SNAP_EDIT_MESH,
84         } type;
85 } SnapObjectData;
86
87 typedef struct SnapObjectData_Mesh {
88         SnapObjectData sd;
89         BVHTreeFromMesh *bvh_trees[3];
90         MPoly *mpoly;
91         bool poly_allocated;
92
93 } SnapObjectData_Mesh;
94
95 typedef struct SnapObjectData_EditMesh {
96         SnapObjectData sd;
97         BVHTreeFromEditMesh *bvh_trees[3];
98
99 } SnapObjectData_EditMesh;
100
101 struct SnapObjectContext {
102         Main *bmain;
103         Scene *scene;
104         int flag;
105
106         /* Optional: when performing screen-space projection.
107          * otherwise this doesn't take viewport into account. */
108         bool use_v3d;
109         struct {
110                 const struct View3D *v3d;
111                 const struct ARegion *ar;
112         } v3d_data;
113
114
115         /* Object -> SnapObjectData map */
116         struct {
117                 GHash *object_map;
118                 MemArena *mem_arena;
119         } cache;
120
121         /* Filter data, returns true to check this value */
122         struct {
123                 struct {
124                         bool (*test_vert_fn)(BMVert *, void *user_data);
125                         bool (*test_edge_fn)(BMEdge *, void *user_data);
126                         bool (*test_face_fn)(BMFace *, void *user_data);
127                         void *user_data;
128                 } edit_mesh;
129         } callbacks;
130
131 };
132
133 /** \} */
134
135
136 /* -------------------------------------------------------------------- */
137
138 /** Common utilities
139 * \{ */
140
141
142 typedef void(*IterSnapObjsCallback)(SnapObjectContext *sctx, bool is_obedit, Object *ob, float obmat[4][4], void *data);
143
144 /**
145  * Walks through all objects in the scene to create the list of objets to snap.
146  *
147  * \param sctx: Snap context to store data.
148  * \param snap_select : from enum SnapSelect.
149  * \param obedit : Object Edited to use its coordinates of BMesh(if any) to do the snapping.
150  */
151 static void iter_snap_objects(
152         SnapObjectContext *sctx,
153         const SnapSelect snap_select,
154         Object *obedit,
155         IterSnapObjsCallback sob_callback,
156         void *data)
157 {
158         Base *base_act = sctx->scene->basact;
159         /* Need an exception for particle edit because the base is flagged with BA_HAS_RECALC_DATA
160          * which makes the loop skip it, even the derived mesh will never change
161          *
162          * To solve that problem, we do it first as an exception.
163          * */
164         if (base_act && base_act->object && base_act->object->mode & OB_MODE_PARTICLE_EDIT) {
165                 sob_callback(sctx, false, base_act->object, base_act->object->obmat, data);
166         }
167
168         for (Base *base = sctx->scene->base.first; base != NULL; base = base->next) {
169                 if ((BASE_VISIBLE_BGMODE(sctx->v3d_data.v3d, sctx->scene, base)) &&
170                     (base->flag & (BA_HAS_RECALC_OB | BA_HAS_RECALC_DATA)) == 0 &&
171                     !((snap_select == SNAP_NOT_SELECTED && (base->flag & (SELECT | BA_WAS_SEL))) ||
172                       (snap_select == SNAP_NOT_ACTIVE && base == base_act)))
173                 {
174                         bool use_obedit;
175                         Object *obj = base->object;
176                         if (obj->transflag & OB_DUPLI) {
177                                 DupliObject *dupli_ob;
178                                 ListBase *lb = object_duplilist(sctx->bmain->eval_ctx, sctx->scene, obj);
179                                 for (dupli_ob = lb->first; dupli_ob; dupli_ob = dupli_ob->next) {
180                                         use_obedit = obedit && dupli_ob->ob->data == obedit->data;
181                                         sob_callback(sctx, use_obedit, use_obedit ? obedit : dupli_ob->ob, dupli_ob->mat, data);
182                                 }
183                                 free_object_duplilist(lb);
184                         }
185
186                         use_obedit = obedit && obj->data == obedit->data;
187                         sob_callback(sctx, use_obedit, use_obedit ? obedit : obj, obj->obmat, data);
188                 }
189         }
190 }
191
192
193 /**
194  * Generates a struct with the immutable parameters that will be used on all objects.
195  *
196  * \param snap_to: Element to snap, Vertice, Edge or Face.
197  * \param view_proj: ORTHO or PERSP.
198  * Currently only works one at a time, but can eventually operate as flag.
199  *
200  * \param mval: Mouse coords.
201  * (When NULL, ray-casting is handled without any projection matrix correction.)
202  * \param ray_origin: ray_start before being moved toward the ray_normal at the distance from vew3d clip_min.
203  * \param ray_start: ray_origin moved for the start clipping plane (clip_min).
204  * \param ray_direction: Unit length direction of the ray.
205  * \param depth_range: distances of clipe plane min and clip plane max;
206  */
207 static void snap_data_set(
208         SnapData *snapdata,
209         const ARegion *ar, const unsigned short snap_to, const enum eViewProj view_proj,
210         const float mval[2], const float ray_origin[3], const float ray_start[3],
211         const float ray_direction[3], const float depth_range[2])
212 {
213         copy_m4_m4(snapdata->pmat, ((RegionView3D *)ar->regiondata)->persmat);
214         snapdata->win_half[0] = ar->winx / 2;
215         snapdata->win_half[1] = ar->winy / 2;
216         copy_v2_v2(snapdata->mval, mval);
217         snapdata->snap_to = snap_to;
218         copy_v3_v3(snapdata->ray_origin, ray_origin);
219         copy_v3_v3(snapdata->ray_start, ray_start);
220         copy_v3_v3(snapdata->ray_dir, ray_direction);
221         snapdata->view_proj = view_proj;
222         copy_v2_v2(snapdata->depth_range, depth_range);
223 }
224
225
226 MINLINE float depth_get(const float co[3], const float ray_start[3], const float ray_dir[3])
227 {
228         float dvec[3];
229         sub_v3_v3v3(dvec, co, ray_start);
230         return dot_v3v3(dvec, ray_dir);
231 }
232
233
234 static bool walk_parent_bvhroot_cb(const BVHTreeAxisRange *bounds, void *userdata)
235 {
236         BVHTreeRay *ray = userdata;
237         const float bbmin[3] = {bounds[0].min, bounds[1].min, bounds[2].min};
238         const float bbmax[3] = {bounds[0].max, bounds[1].max, bounds[2].max};
239         if (!isect_ray_aabb_v3_simple(ray->origin, ray->direction, bbmin, bbmax, &ray->radius, NULL)) {
240                 ray->radius = -1;
241         }
242         return false;
243 }
244
245
246 static bool isect_ray_bvhroot_v3(struct BVHTree *tree, const float ray_start[3], const float ray_dir[3], float *depth)
247 {
248         BVHTreeRay ray;
249         copy_v3_v3(ray.origin, ray_start);
250         copy_v3_v3(ray.direction, ray_dir);
251
252         BLI_bvhtree_walk_dfs(tree, walk_parent_bvhroot_cb, NULL, NULL, &ray);
253
254         if (ray.radius > 0) {
255                 *depth = ray.radius;
256                 return true;
257         }
258         else {
259                 return false;
260         }
261 }
262
263
264 static int dm_looptri_to_poly_index(DerivedMesh *dm, const MLoopTri *lt);
265
266 /** \} */
267
268
269 /* -------------------------------------------------------------------- */
270
271 /** \name Ray Cast Funcs
272 * \{ */
273
274 /* Store all ray-hits
275  * Support for storing all depths, not just the first (raycast 'all') */
276
277 struct RayCastAll_Data {
278         void *bvhdata;
279
280         /* internal vars for adding depths */
281         BVHTree_RayCastCallback raycast_callback;
282
283         const float(*obmat)[4];
284         const float(*timat)[3];
285
286         float len_diff;
287         float local_scale;
288
289         Object *ob;
290         unsigned int ob_uuid;
291
292         /* output data */
293         ListBase *hit_list;
294         bool retval;
295 };
296
297
298 static struct SnapObjectHitDepth *hit_depth_create(
299         const float depth, const float co[3], const float no[3], int index,
300         Object *ob, const float obmat[4][4], unsigned int ob_uuid)
301 {
302         struct SnapObjectHitDepth *hit = MEM_mallocN(sizeof(*hit), __func__);
303
304         hit->depth = depth;
305         copy_v3_v3(hit->co, co);
306         copy_v3_v3(hit->no, no);
307         hit->index = index;
308
309         hit->ob = ob;
310         copy_m4_m4(hit->obmat, (float(*)[4])obmat);
311         hit->ob_uuid = ob_uuid;
312
313         return hit;
314 }
315
316 static int hit_depth_cmp(const void *arg1, const void *arg2)
317 {
318         const struct SnapObjectHitDepth *h1 = arg1;
319         const struct SnapObjectHitDepth *h2 = arg2;
320         int val = 0;
321
322         if (h1->depth < h2->depth) {
323                 val = -1;
324         }
325         else if (h1->depth > h2->depth) {
326                 val = 1;
327         }
328
329         return val;
330 }
331
332 static void raycast_all_cb(void *userdata, int index, const BVHTreeRay *ray, BVHTreeRayHit *hit)
333 {
334         struct RayCastAll_Data *data = userdata;
335         data->raycast_callback(data->bvhdata, index, ray, hit);
336         if (hit->index != -1) {
337                 /* get all values in worldspace */
338                 float location[3], normal[3];
339                 float depth;
340
341                 /* worldspace location */
342                 mul_v3_m4v3(location, (float(*)[4])data->obmat, hit->co);
343                 depth = (hit->dist + data->len_diff) / data->local_scale;
344
345                 /* worldspace normal */
346                 copy_v3_v3(normal, hit->no);
347                 mul_m3_v3((float(*)[3])data->timat, normal);
348                 normalize_v3(normal);
349
350                 /* currently unused, and causes issues when looptri's haven't been calculated.
351                  * since theres some overhead in ensuring this data is valid, it may need to be optional. */
352 #if 0
353                 if (data->dm) {
354                         hit->index = dm_looptri_to_poly_index(data->dm, &data->dm_looptri[hit->index]);
355                 }
356 #endif
357
358                 struct SnapObjectHitDepth *hit_item = hit_depth_create(
359                         depth, location, normal, hit->index,
360                         data->ob, data->obmat, data->ob_uuid);
361                 BLI_addtail(data->hit_list, hit_item);
362         }
363 }
364
365
366 static bool raycastDerivedMesh(
367         SnapObjectContext *sctx,
368         const float ray_start[3], const float ray_dir[3],
369         Object *ob, DerivedMesh *dm, float obmat[4][4], const unsigned int ob_index,
370         /* read/write args */
371         float *ray_depth,
372         /* return args */
373         float r_loc[3], float r_no[3], int *r_index,
374         ListBase *r_hit_list)
375 {
376         bool retval = false;
377
378         if (dm->getNumPolys(dm) == 0) {
379                 return retval;
380         }
381
382         float imat[4][4];
383         float timat[3][3]; /* transpose inverse matrix for normals */
384         float ray_start_local[3], ray_normal_local[3];
385         float local_scale, local_depth, len_diff = 0.0f;
386
387         invert_m4_m4(imat, obmat);
388         transpose_m3_m4(timat, imat);
389
390         copy_v3_v3(ray_start_local, ray_start);
391         copy_v3_v3(ray_normal_local, ray_dir);
392
393         mul_m4_v3(imat, ray_start_local);
394         mul_mat3_m4_v3(imat, ray_normal_local);
395
396         /* local scale in normal direction */
397         local_scale = normalize_v3(ray_normal_local);
398         local_depth = *ray_depth;
399         if (local_depth != BVH_RAYCAST_DIST_MAX) {
400                 local_depth *= local_scale;
401         }
402
403         /* Test BoundBox */
404         BoundBox *bb = BKE_object_boundbox_get(ob);
405         if (bb) {
406                 /* was BKE_boundbox_ray_hit_check, see: cf6ca226fa58 */
407                 if (!isect_ray_aabb_v3_simple(
408                         ray_start_local, ray_normal_local, bb->vec[0], bb->vec[6], &len_diff, NULL))
409                 {
410                         return retval;
411                 }
412         }
413
414         SnapObjectData_Mesh *sod = NULL;
415         BVHTreeFromMesh *treedata;
416
417         void **sod_p;
418         if (BLI_ghash_ensure_p(sctx->cache.object_map, ob, &sod_p)) {
419                 sod = *sod_p;
420         }
421         else {
422                 sod = *sod_p = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*sod));
423                 sod->sd.type = SNAP_MESH;
424         }
425
426         if (sod->bvh_trees[2] == NULL) {
427                 sod->bvh_trees[2] = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*treedata));
428         }
429
430         treedata = sod->bvh_trees[2];
431
432         if (treedata) {
433                 /* the tree is owned by the DM and may have been freed since we last used! */
434                 if (treedata->tree) {
435                         if (treedata->cached && !bvhcache_has_tree(dm->bvhCache, treedata->tree)) {
436                                 free_bvhtree_from_mesh(treedata);
437                         }
438                         else {
439                                 if (treedata->vert == NULL) {
440                                         treedata->vert = DM_get_vert_array(dm, &treedata->vert_allocated);
441                                 }
442                                 if (treedata->loop == NULL) {
443                                         treedata->loop = DM_get_loop_array(dm, &treedata->loop_allocated);
444                                 }
445                                 if (treedata->looptri == NULL) {
446                                         if (sod->mpoly == NULL) {
447                                                 sod->mpoly = DM_get_poly_array(dm, &sod->poly_allocated);
448                                         }
449                                         treedata->looptri = dm->getLoopTriArray(dm);
450                                         treedata->looptri_allocated = false;
451                                 }
452                         }
453                 }
454
455                 if (treedata->tree == NULL) {
456                         bvhtree_from_mesh_looptri(treedata, dm, 0.0f, 4, 6);
457
458                         if (treedata->tree == NULL) {
459                                 return retval;
460                         }
461                 }
462         }
463         else {
464                 return retval;
465         }
466
467         /* Only use closer ray_start in case of ortho view! In perspective one, ray_start may already
468          * been *inside* boundbox, leading to snap failures (see T38409).
469          * Note also ar might be null (see T38435), in this case we assume ray_start is ok!
470          */
471         if (len_diff == 0.0f) {  /* do_ray_start_correction */
472                 /* We *need* a reasonably valid len_diff in this case.
473                  * Get the distance to bvhtree root */
474                 if (!isect_ray_bvhroot_v3(treedata->tree, ray_start_local, ray_normal_local, &len_diff)) {
475                         return retval;
476                 }
477         }
478         /* You need to make sure that ray_start is really far away,
479          * because even in the Orthografic view, in some cases,
480          * the ray can start inside the object (see T50486) */
481         if (len_diff > 400.0f) {
482                 /* We pass a temp ray_start, set from object's boundbox, to avoid precision issues with
483                  * very far away ray_start values (as returned in case of ortho view3d), see T38358.
484                  */
485                 len_diff -= local_scale; /* make temp start point a bit away from bbox hit point. */
486                 madd_v3_v3fl(ray_start_local, ray_normal_local, len_diff);
487                 local_depth -= len_diff;
488         }
489         else {
490                 len_diff = 0.0f;
491         }
492         if (r_hit_list) {
493                 struct RayCastAll_Data data;
494
495                 data.bvhdata = treedata;
496                 data.raycast_callback = treedata->raycast_callback;
497                 data.obmat = obmat;
498                 data.timat = timat;
499                 data.len_diff = len_diff;
500                 data.local_scale = local_scale;
501                 data.ob = ob;
502                 data.ob_uuid = ob_index;
503                 data.hit_list = r_hit_list;
504                 data.retval = retval;
505
506                 BLI_bvhtree_ray_cast_all(
507                         treedata->tree, ray_start_local, ray_normal_local, 0.0f,
508                         *ray_depth, raycast_all_cb, &data);
509
510                 retval = data.retval;
511         }
512         else {
513                 BVHTreeRayHit hit = {.index = -1, .dist = local_depth};
514
515                 if (BLI_bvhtree_ray_cast(
516                         treedata->tree, ray_start_local, ray_normal_local, 0.0f,
517                         &hit, treedata->raycast_callback, treedata) != -1)
518                 {
519                         hit.dist += len_diff;
520                         hit.dist /= local_scale;
521                         if (hit.dist <= *ray_depth) {
522                                 *ray_depth = hit.dist;
523                                 copy_v3_v3(r_loc, hit.co);
524
525                                 /* back to worldspace */
526                                 mul_m4_v3(obmat, r_loc);
527
528                                 if (r_no) {
529                                         copy_v3_v3(r_no, hit.no);
530                                         mul_m3_v3(timat, r_no);
531                                         normalize_v3(r_no);
532                                 }
533
534                                 retval = true;
535
536                                 if (r_index) {
537                                         *r_index = dm_looptri_to_poly_index(dm, &treedata->looptri[hit.index]);
538                                 }
539                         }
540                 }
541         }
542
543         return retval;
544 }
545
546 static bool raycastEditMesh(
547         SnapObjectContext *sctx,
548         const float ray_start[3], const float ray_dir[3],
549         Object *ob, BMEditMesh *em, float obmat[4][4], const unsigned int ob_index,
550         /* read/write args */
551         float *ray_depth,
552         /* return args */
553         float r_loc[3], float r_no[3], int *r_index,
554         ListBase *r_hit_list)
555 {
556         bool retval = false;
557         if (em->bm->totface == 0) {
558                 return retval;
559         }
560
561         SnapObjectData_EditMesh *sod = NULL;
562         BVHTreeFromEditMesh *treedata = NULL;
563
564         void **sod_p;
565         if (BLI_ghash_ensure_p(sctx->cache.object_map, ob, &sod_p)) {
566                 sod = *sod_p;
567         }
568         else {
569                 sod = *sod_p = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*sod));
570                 sod->sd.type = SNAP_EDIT_MESH;
571         }
572
573         if (sod->bvh_trees[2] == NULL) {
574                 sod->bvh_trees[2] = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*treedata));
575         }
576         treedata = sod->bvh_trees[2];
577
578         if (treedata) {
579                 if (treedata->tree == NULL) {
580                         BLI_bitmap *elem_mask = NULL;
581                         int looptri_num_active = -1;
582
583                         if (sctx->callbacks.edit_mesh.test_face_fn) {
584                                 elem_mask = BLI_BITMAP_NEW(em->tottri, __func__);
585                                 looptri_num_active = BM_iter_mesh_bitmap_from_filter_tessface(
586                                         em->bm, elem_mask,
587                                         sctx->callbacks.edit_mesh.test_face_fn, sctx->callbacks.edit_mesh.user_data);
588                         }
589                         bvhtree_from_editmesh_looptri_ex(treedata, em, elem_mask, looptri_num_active, 0.0f, 4, 6, NULL);
590
591                         if (elem_mask) {
592                                 MEM_freeN(elem_mask);
593                         }
594                 }
595                 if (treedata->tree == NULL) {
596                         return retval;
597                 }
598         }
599         else {
600                 return retval;
601         }
602
603         float imat[4][4];
604         float timat[3][3]; /* transpose inverse matrix for normals */
605         float ray_normal_local[3], ray_start_local[3], len_diff = 0.0f;
606
607         invert_m4_m4(imat, obmat);
608         transpose_m3_m4(timat, imat);
609
610         copy_v3_v3(ray_normal_local, ray_dir);
611         mul_mat3_m4_v3(imat, ray_normal_local);
612
613         copy_v3_v3(ray_start_local, ray_start);
614         mul_m4_v3(imat, ray_start_local);
615
616         /* local scale in normal direction */
617         float local_scale = normalize_v3(ray_normal_local);
618         float local_depth = *ray_depth;
619         if (local_depth != BVH_RAYCAST_DIST_MAX) {
620                 local_depth *= local_scale;
621         }
622
623         /* Only use closer ray_start in case of ortho view! In perspective one, ray_start
624          * may already been *inside* boundbox, leading to snap failures (see T38409).
625          * Note also ar might be null (see T38435), in this case we assume ray_start is ok!
626          */
627         if (sctx->use_v3d && !((RegionView3D *)sctx->v3d_data.ar->regiondata)->is_persp) {  /* do_ray_start_correction */
628                 /* We *need* a reasonably valid len_diff in this case.
629                  * Get the distance to bvhtree root */
630                 if (!isect_ray_bvhroot_v3(treedata->tree, ray_start_local, ray_normal_local, &len_diff)) {
631                         return retval;
632                 }
633                 /* You need to make sure that ray_start is really far away,
634                  * because even in the Orthografic view, in some cases,
635                  * the ray can start inside the object (see T50486) */
636                 if (len_diff > 400.0f) {
637                         /* We pass a temp ray_start, set from object's boundbox, to avoid precision issues with
638                          * very far away ray_start values (as returned in case of ortho view3d), see T38358.
639                          */
640                         len_diff -= local_scale; /* make temp start point a bit away from bbox hit point. */
641                         madd_v3_v3fl(ray_start_local, ray_normal_local, len_diff);
642                         local_depth -= len_diff;
643                 }
644                 else len_diff = 0.0f;
645         }
646         if (r_hit_list) {
647                 struct RayCastAll_Data data;
648
649                 data.bvhdata = treedata;
650                 data.raycast_callback = treedata->raycast_callback;
651                 data.obmat = obmat;
652                 data.timat = timat;
653                 data.len_diff = len_diff;
654                 data.local_scale = local_scale;
655                 data.ob = ob;
656                 data.ob_uuid = ob_index;
657                 data.hit_list = r_hit_list;
658                 data.retval = retval;
659
660                 BLI_bvhtree_ray_cast_all(
661                         treedata->tree, ray_start_local, ray_normal_local, 0.0f,
662                         *ray_depth, raycast_all_cb, &data);
663
664                 retval = data.retval;
665         }
666         else {
667                 BVHTreeRayHit hit = {.index = -1, .dist = local_depth};
668
669                 if (BLI_bvhtree_ray_cast(
670                         treedata->tree, ray_start_local, ray_normal_local, 0.0f,
671                         &hit, treedata->raycast_callback, treedata) != -1)
672                 {
673                         hit.dist += len_diff;
674                         hit.dist /= local_scale;
675                         if (hit.dist <= *ray_depth) {
676                                 *ray_depth = hit.dist;
677                                 copy_v3_v3(r_loc, hit.co);
678
679                                 /* back to worldspace */
680                                 mul_m4_v3(obmat, r_loc);
681
682                                 if (r_no) {
683                                         copy_v3_v3(r_no, hit.no);
684                                         mul_m3_v3(timat, r_no);
685                                         normalize_v3(r_no);
686                                 }
687
688                                 retval = true;
689
690                                 if (r_index) {
691                                         *r_index = hit.index;
692                                 }
693                         }
694                 }
695         }
696
697         return retval;
698 }
699
700
701 /**
702  * \param use_obedit: Uses the coordinates of BMesh (if any) to do the snapping;
703  *
704  * \note Duplicate args here are documented at #snapObjectsRay
705  */
706 static bool raycastObj(
707         SnapObjectContext *sctx,
708         const float ray_start[3], const float ray_dir[3],
709         Object *ob, float obmat[4][4], const unsigned int ob_index,
710         bool use_obedit,
711         /* read/write args */
712         float *ray_depth,
713         /* return args */
714         float r_loc[3], float r_no[3], int *r_index,
715         Object **r_ob, float r_obmat[4][4],
716         ListBase *r_hit_list)
717 {
718         bool retval = false;
719
720         if (ob->type == OB_MESH) {
721                 BMEditMesh *em;
722
723                 if (use_obedit) {
724                         em = BKE_editmesh_from_object(ob);
725                         retval = raycastEditMesh(
726                                 sctx,
727                                 ray_start, ray_dir,
728                                 ob, em, obmat, ob_index,
729                                 ray_depth, r_loc, r_no, r_index, r_hit_list);
730                 }
731                 else {
732                         /* in this case we want the mesh from the editmesh, avoids stale data. see: T45978.
733                          * still set the 'em' to NULL, since we only want the 'dm'. */
734                         DerivedMesh *dm;
735                         em = BKE_editmesh_from_object(ob);
736                         if (em) {
737                                 editbmesh_get_derived_cage_and_final(sctx->scene, ob, em, CD_MASK_BAREMESH, &dm);
738                         }
739                         else {
740                                 dm = mesh_get_derived_final(sctx->scene, ob, CD_MASK_BAREMESH);
741                         }
742                         retval = raycastDerivedMesh(
743                                 sctx,
744                                 ray_start, ray_dir,
745                                 ob, dm, obmat, ob_index,
746                                 ray_depth, r_loc, r_no, r_index, r_hit_list);
747                 }
748         }
749
750         if (retval) {
751                 if (r_ob) {
752                         *r_ob = ob;
753                         copy_m4_m4(r_obmat, obmat);
754                 }
755         }
756
757         return retval;
758 }
759
760
761 struct RaycastObjUserData {
762         const float *ray_start;
763         const float *ray_dir;
764         unsigned int ob_index;
765         /* read/write args */
766         float *ray_depth;
767         /* return args */
768         float *r_loc;
769         float *r_no;
770         int *r_index;
771         Object **r_ob;
772         float (*r_obmat)[4];
773         ListBase *r_hit_list;
774         bool ret;
775 };
776
777 static void raycast_obj_cb(SnapObjectContext *sctx, bool is_obedit, Object *ob, float obmat[4][4], void *data)
778 {
779         struct RaycastObjUserData *dt = data;
780         dt->ret |= raycastObj(
781                 sctx,
782                 dt->ray_start, dt->ray_dir,
783                 ob, obmat, dt->ob_index++, is_obedit,
784                 dt->ray_depth,
785                 dt->r_loc, dt->r_no, dt->r_index,
786                 dt->r_ob, dt->r_obmat,
787                 dt->r_hit_list);
788 }
789
790 /**
791  * Main RayCast Function
792  * ======================
793  *
794  * Walks through all objects in the scene to find the `hit` on object surface.
795  *
796  * \param sctx: Snap context to store data.
797  * \param snapdata: struct generated in `set_snapdata`.
798  * \param snap_select : from enum SnapSelect.
799  * \param use_object_edit_cage : Uses the coordinates of BMesh(if any) to do the snapping.
800  * \param obj_list: List with objects to snap (created in `create_object_list`).
801  *
802  * Read/Write Args
803  * ---------------
804  *
805  * \param ray_depth: maximum depth allowed for r_co, elements deeper than this value will be ignored.
806  *
807  * Output Args
808  * -----------
809  *
810  * \param r_loc: Hit location.
811  * \param r_no: Hit normal (optional).
812  * \param r_index: Hit index or -1 when no valid index is found.
813  * (currently only set to the polygon index when when using ``snap_to == SCE_SNAP_MODE_FACE``).
814  * \param r_ob: Hit object.
815  * \param r_obmat: Object matrix (may not be #Object.obmat with dupli-instances).
816  * \param r_hit_list: List of #SnapObjectHitDepth (caller must free).
817  *
818  */
819 static bool raycastObjects(
820         SnapObjectContext *sctx,
821         const float ray_start[3], const float ray_dir[3],
822         const SnapSelect snap_select, const bool use_object_edit_cage,
823         /* read/write args */
824         float *ray_depth,
825         /* return args */
826         float r_loc[3], float r_no[3], int *r_index,
827         Object **r_ob, float r_obmat[4][4],
828         ListBase *r_hit_list)
829 {
830         Object *obedit = use_object_edit_cage ? sctx->scene->obedit : NULL;
831
832         struct RaycastObjUserData data = {
833                 .ray_start = ray_start,
834                 .ray_dir = ray_dir,
835                 .ob_index = 0,
836                 .ray_depth = ray_depth,
837                 .r_loc = r_loc,
838                 .r_no = r_no,
839                 .r_index = r_index,
840                 .r_ob = r_ob,
841                 .r_obmat = r_obmat,
842                 .r_hit_list = r_hit_list,
843                 .ret = false,
844         };
845
846         iter_snap_objects(sctx, snap_select, obedit, raycast_obj_cb, &data);
847
848         return data.ret;
849 }
850
851
852 /** \} */
853
854
855 /* -------------------------------------------------------------------- */
856
857 /** Snap Nearest utilities
858  * \{ */
859
860 static void copy_dm_vert_no(const int index, float r_no[3], const BVHTreeFromMesh *data)
861 {
862         const MVert *vert = data->vert + index;
863
864         normal_short_to_float_v3(r_no, vert->no);
865 }
866
867 static void copy_bvert_no(const int index, float r_no[3], const BVHTreeFromEditMesh *data)
868 {
869         BMVert *eve = BM_vert_at_index(data->em->bm, index);
870
871         copy_v3_v3(r_no, eve->no);
872 }
873
874 static void get_dm_edge_verts(const int index, const float *v_pair[2], const BVHTreeFromMesh *data)
875 {
876         const MVert *vert = data->vert;
877         const MEdge *edge = data->edge + index;
878
879         v_pair[0] = vert[edge->v1].co;
880         v_pair[1] = vert[edge->v2].co;
881 }
882
883 static void get_bedge_verts(const int index, const float *v_pair[2], const BVHTreeFromEditMesh *data)
884 {
885         BMEdge *eed = BM_edge_at_index(data->em->bm, index);
886
887         v_pair[0] = eed->v1->co;
888         v_pair[1] = eed->v2->co;
889 }
890
891 static bool test_projected_vert_dist(
892         const float depth_range[2], const float mval[2], const float co[3],
893         float pmat[4][4], const float win_half[2], const bool is_persp,
894         float *dist_px_sq, float r_co[3])
895 {
896         float depth;
897         if (is_persp) {
898                 depth = mul_project_m4_v3_zfac(pmat, co);
899                 if (depth < depth_range[0] || depth > depth_range[1]) {
900                         return false;
901                 }
902         }
903
904         float co2d[2] = {
905                 (dot_m4_v3_row_x(pmat, co) + pmat[3][0]),
906                 (dot_m4_v3_row_y(pmat, co) + pmat[3][1]),
907         };
908
909         if (is_persp) {
910                 mul_v2_fl(co2d, 1 / depth);
911         }
912
913         co2d[0] += 1.0f;
914         co2d[1] += 1.0f;
915         co2d[0] *= win_half[0];
916         co2d[1] *= win_half[1];
917
918         const float dist_sq = len_squared_v2v2(mval, co2d);
919         if (dist_sq < *dist_px_sq) {
920                 copy_v3_v3(r_co, co);
921                 *dist_px_sq = dist_sq;
922                 return true;
923         }
924         return false;
925 }
926
927 static bool test_projected_edge_dist(
928         const float depth_range[2], const float mval[2],
929         float pmat[4][4], const float win_half[2], const bool is_persp,
930         const float ray_start[3], const float ray_dir[3],
931         const float va[3], const float vb[3],
932         float *dist_px_sq, float r_co[3])
933 {
934
935         float tmp_co[3], depth;
936         dist_squared_ray_to_seg_v3(ray_start, ray_dir, va, vb, tmp_co, &depth);
937         return test_projected_vert_dist(depth_range, mval, tmp_co, pmat, win_half, is_persp, dist_px_sq, r_co);
938 }
939 typedef struct Nearest2dPrecalc {
940         float ray_origin_local[3];
941         float ray_direction_local[3];
942         float ray_inv_dir[3];
943
944         float ray_min_dist;
945         float pmat[4][4]; /* perspective matrix multiplied by object matrix */
946         bool is_persp;
947         float win_half[2];
948
949         float mval[2];
950         bool sign[3];
951 } Nearest2dPrecalc;
952
953 /**
954  * \param lpmat: Perspective matrix multiplied by object matrix
955  */
956 static void dist_squared_to_projected_aabb_precalc(
957         struct Nearest2dPrecalc *neasrest_precalc,
958         float lpmat[4][4], bool is_persp, const float win_half[2],
959         const float ray_min_dist, const float mval[2],
960         const float ray_origin_local[3], const float ray_direction_local[3])
961 {
962         copy_m4_m4(neasrest_precalc->pmat, lpmat);
963         neasrest_precalc->is_persp = is_persp;
964         copy_v2_v2(neasrest_precalc->win_half, win_half);
965         neasrest_precalc->ray_min_dist = ray_min_dist;
966
967         copy_v3_v3(neasrest_precalc->ray_origin_local, ray_origin_local);
968         copy_v3_v3(neasrest_precalc->ray_direction_local, ray_direction_local);
969         copy_v2_v2(neasrest_precalc->mval, mval);
970
971         for (int i = 0; i < 3; i++) {
972                 neasrest_precalc->ray_inv_dir[i] =
973                         (neasrest_precalc->ray_direction_local[i] != 0.0f) ?
974                         (1.0f / neasrest_precalc->ray_direction_local[i]) : FLT_MAX;
975                 neasrest_precalc->sign[i] = (neasrest_precalc->ray_inv_dir[i] < 0.0f);
976         }
977 }
978
979 /* Returns the distance from a 2d coordinate to a BoundBox (Projected) */
980 static float dist_squared_to_projected_aabb(
981         struct Nearest2dPrecalc *data,
982         const float bbmin[3], const float bbmax[3],
983         bool r_axis_closest[3])
984 {
985         float local_bvmin[3], local_bvmax[3];
986         if (data->sign[0]) {
987                 local_bvmin[0] = bbmax[0];
988                 local_bvmax[0] = bbmin[0];
989         }
990         else {
991                 local_bvmin[0] = bbmin[0];
992                 local_bvmax[0] = bbmax[0];
993         }
994         if (data->sign[1]) {
995                 local_bvmin[1] = bbmax[1];
996                 local_bvmax[1] = bbmin[1];
997         }
998         else {
999                 local_bvmin[1] = bbmin[1];
1000                 local_bvmax[1] = bbmax[1];
1001         }
1002         if (data->sign[2]) {
1003                 local_bvmin[2] = bbmax[2];
1004                 local_bvmax[2] = bbmin[2];
1005         }
1006         else {
1007                 local_bvmin[2] = bbmin[2];
1008                 local_bvmax[2] = bbmax[2];
1009         }
1010
1011         const float tmin[3] = {
1012                 (local_bvmin[0] - data->ray_origin_local[0]) * data->ray_inv_dir[0],
1013                 (local_bvmin[1] - data->ray_origin_local[1]) * data->ray_inv_dir[1],
1014                 (local_bvmin[2] - data->ray_origin_local[2]) * data->ray_inv_dir[2],
1015         };
1016         const float tmax[3] = {
1017                 (local_bvmax[0] - data->ray_origin_local[0]) * data->ray_inv_dir[0],
1018                 (local_bvmax[1] - data->ray_origin_local[1]) * data->ray_inv_dir[1],
1019                 (local_bvmax[2] - data->ray_origin_local[2]) * data->ray_inv_dir[2],
1020         };
1021         /* `va` and `vb` are the coordinates of the AABB edge closest to the ray */
1022         float va[3], vb[3];
1023         /* `rtmin` and `rtmax` are the minimum and maximum distances of the ray hits on the AABB */
1024         float rtmin, rtmax;
1025         int main_axis;
1026
1027         if ((tmax[0] <= tmax[1]) && (tmax[0] <= tmax[2])) {
1028                 rtmax = tmax[0];
1029                 va[0] = vb[0] = local_bvmax[0];
1030                 main_axis = 3;
1031                 r_axis_closest[0] = data->sign[0];
1032         }
1033         else if ((tmax[1] <= tmax[0]) && (tmax[1] <= tmax[2])) {
1034                 rtmax = tmax[1];
1035                 va[1] = vb[1] = local_bvmax[1];
1036                 main_axis = 2;
1037                 r_axis_closest[1] = data->sign[1];
1038         }
1039         else {
1040                 rtmax = tmax[2];
1041                 va[2] = vb[2] = local_bvmax[2];
1042                 main_axis = 1;
1043                 r_axis_closest[2] = data->sign[2];
1044         }
1045
1046         if ((tmin[0] >= tmin[1]) && (tmin[0] >= tmin[2])) {
1047                 rtmin = tmin[0];
1048                 va[0] = vb[0] = local_bvmin[0];
1049                 main_axis -= 3;
1050                 r_axis_closest[0] = !data->sign[0];
1051         }
1052         else if ((tmin[1] >= tmin[0]) && (tmin[1] >= tmin[2])) {
1053                 rtmin = tmin[1];
1054                 va[1] = vb[1] = local_bvmin[1];
1055                 main_axis -= 1;
1056                 r_axis_closest[1] = !data->sign[1];
1057         }
1058         else {
1059                 rtmin = tmin[2];
1060                 va[2] = vb[2] = local_bvmin[2];
1061                 main_axis -= 2;
1062                 r_axis_closest[2] = !data->sign[2];
1063         }
1064         if (main_axis < 0) {
1065                 main_axis += 3;
1066         }
1067
1068         /* if rtmin < rtmax, ray intersect `AABB` */
1069         if (rtmin <= rtmax) {
1070 #define IGNORE_BEHIND_RAY
1071 #ifdef IGNORE_BEHIND_RAY
1072                 /* `if rtmax < depth_min`, the hit is behind us */
1073                 if (rtmax < data->ray_min_dist) {
1074                         /* Test if the entire AABB is behind us */
1075                         float depth = depth_get(
1076                                 local_bvmax, data->ray_origin_local, data->ray_direction_local);
1077                         if (depth < (data->ray_min_dist)) {
1078                                 return FLT_MAX;
1079                         }
1080                 }
1081 #endif
1082                 const float proj = rtmin * data->ray_direction_local[main_axis];
1083                 r_axis_closest[main_axis] = (proj - va[main_axis]) < (vb[main_axis] - proj);
1084                 return 0.0f;
1085         }
1086 #ifdef IGNORE_BEHIND_RAY
1087         /* `if rtmin < depth_min`, the hit is behing us */
1088         else if (rtmin < data->ray_min_dist) {
1089                 /* Test if the entire AABB is behind us */
1090                 float depth = depth_get(
1091                         local_bvmax, data->ray_origin_local, data->ray_direction_local);
1092                 if (depth < (data->ray_min_dist)) {
1093                         return FLT_MAX;
1094                 }
1095         }
1096 #endif
1097 #undef IGNORE_BEHIND_RAY
1098         if (data->sign[main_axis]) {
1099                 va[main_axis] = local_bvmax[main_axis];
1100                 vb[main_axis] = local_bvmin[main_axis];
1101         }
1102         else {
1103                 va[main_axis] = local_bvmin[main_axis];
1104                 vb[main_axis] = local_bvmax[main_axis];
1105         }
1106         float scale = fabsf(local_bvmax[main_axis] - local_bvmin[main_axis]);
1107
1108         float (*pmat)[4] = data->pmat;
1109
1110         float va2d[2] = {
1111                 (dot_m4_v3_row_x(pmat, va) + pmat[3][0]),
1112                 (dot_m4_v3_row_y(pmat, va) + pmat[3][1]),
1113         };
1114         float vb2d[2] = {
1115                 (va2d[0] + pmat[main_axis][0] * scale),
1116                 (va2d[1] + pmat[main_axis][1] * scale),
1117         };
1118
1119         if (data->is_persp) {
1120                 float depth_a = mul_project_m4_v3_zfac(pmat, va);
1121                 float depth_b = depth_a + pmat[main_axis][3] * scale;
1122                 va2d[0] /= depth_a;
1123                 va2d[1] /= depth_a;
1124                 vb2d[0] /= depth_b;
1125                 vb2d[1] /= depth_b;
1126         }
1127
1128         va2d[0] += 1.0f;
1129         va2d[1] += 1.0f;
1130         vb2d[0] += 1.0f;
1131         vb2d[1] += 1.0f;
1132
1133         va2d[0] *= data->win_half[0];
1134         va2d[1] *= data->win_half[1];
1135         vb2d[0] *= data->win_half[0];
1136         vb2d[1] *= data->win_half[1];
1137
1138         float dvec[2], edge[2], lambda, rdist;
1139         sub_v2_v2v2(dvec, data->mval, va2d);
1140         sub_v2_v2v2(edge, vb2d, va2d);
1141         lambda = dot_v2v2(dvec, edge);
1142         if (lambda != 0.0f) {
1143                 lambda /= len_squared_v2(edge);
1144                 if (lambda <= 0.0f) {
1145                         rdist = len_squared_v2v2(data->mval, va2d);
1146                         r_axis_closest[main_axis] = true;
1147                 }
1148                 else if (lambda >= 1.0f) {
1149                         rdist = len_squared_v2v2(data->mval, vb2d);
1150                         r_axis_closest[main_axis] = false;
1151                 }
1152                 else {
1153                         va2d[0] += edge[0] * lambda;
1154                         va2d[1] += edge[1] * lambda;
1155                         rdist = len_squared_v2v2(data->mval, va2d);
1156                         r_axis_closest[main_axis] = lambda < 0.5f;
1157                 }
1158         }
1159         else {
1160                 rdist = len_squared_v2v2(data->mval, va2d);
1161         }
1162         return rdist;
1163 }
1164
1165 static float dist_squared_to_projected_aabb_simple(
1166         float lpmat[4][4], const float win_half[2],
1167         const float ray_min_dist, const float mval[2],
1168         const float ray_origin_local[3], const float ray_direction_local[3],
1169         const float bbmin[3], const float bbmax[3])
1170 {
1171         struct Nearest2dPrecalc data;
1172         dist_squared_to_projected_aabb_precalc(
1173                 &data, lpmat, true, win_half, ray_min_dist,
1174                 mval, ray_origin_local, ray_direction_local);
1175
1176         bool dummy[3] = {true, true, true};
1177         return dist_squared_to_projected_aabb(&data, bbmin, bbmax, dummy);
1178 }
1179
1180 /** \} */
1181
1182
1183 /* -------------------------------------------------------------------- */
1184
1185 /** Walk DFS
1186  * \{ */
1187
1188 typedef void (*Nearest2DGetEdgeVertsCallback)(const int index, const float *v_pair[2], void *data);
1189 typedef void (*Nearest2DCopyVertNoCallback)(const int index, float r_no[3], void *data);
1190
1191 typedef struct Nearest2dUserData {
1192         struct Nearest2dPrecalc data_precalc;
1193
1194         float dist_px_sq;
1195
1196         bool r_axis_closest[3];
1197
1198         float depth_range[2];
1199
1200         void *userdata;
1201         Nearest2DGetEdgeVertsCallback get_edge_verts;
1202         Nearest2DCopyVertNoCallback copy_vert_no;
1203
1204         int index;
1205         float co[3];
1206         float no[3];
1207 } Nearest2dUserData;
1208
1209
1210 static bool cb_walk_parent_snap_project(const BVHTreeAxisRange *bounds, void *user_data)
1211 {
1212         Nearest2dUserData *data = user_data;
1213         const float bbmin[3] = {bounds[0].min, bounds[1].min, bounds[2].min};
1214         const float bbmax[3] = {bounds[0].max, bounds[1].max, bounds[2].max};
1215         const float rdist = dist_squared_to_projected_aabb(
1216                 &data->data_precalc, bbmin, bbmax, data->r_axis_closest);
1217         return rdist < data->dist_px_sq;
1218 }
1219
1220 static bool cb_walk_leaf_snap_vert(const BVHTreeAxisRange *bounds, int index, void *userdata)
1221 {
1222         struct Nearest2dUserData *data = userdata;
1223         struct Nearest2dPrecalc *neasrest_precalc = &data->data_precalc;
1224         const float co[3] = {
1225                 (bounds[0].min + bounds[0].max) / 2,
1226                 (bounds[1].min + bounds[1].max) / 2,
1227                 (bounds[2].min + bounds[2].max) / 2,
1228         };
1229
1230         if (test_projected_vert_dist(
1231                 data->depth_range,
1232                 neasrest_precalc->mval, co,
1233                 neasrest_precalc->pmat,
1234                 neasrest_precalc->win_half,
1235                 neasrest_precalc->is_persp,
1236                 &data->dist_px_sq,
1237                 data->co))
1238         {
1239                 data->copy_vert_no(index, data->no, data->userdata);
1240                 data->index = index;
1241         }
1242         return true;
1243 }
1244
1245 static bool cb_walk_leaf_snap_edge(const BVHTreeAxisRange *UNUSED(bounds), int index, void *userdata)
1246 {
1247         struct Nearest2dUserData *data = userdata;
1248         struct Nearest2dPrecalc *neasrest_precalc = &data->data_precalc;
1249
1250         const float *v_pair[2];
1251         data->get_edge_verts(index, v_pair, data->userdata);
1252
1253         if (test_projected_edge_dist(
1254                 data->depth_range,
1255                 neasrest_precalc->mval,
1256                 neasrest_precalc->pmat,
1257                 neasrest_precalc->win_half,
1258                 neasrest_precalc->is_persp,
1259                 neasrest_precalc->ray_origin_local,
1260                 neasrest_precalc->ray_direction_local,
1261                 v_pair[0], v_pair[1],
1262                 &data->dist_px_sq,
1263                 data->co))
1264         {
1265                 sub_v3_v3v3(data->no, v_pair[0], v_pair[1]);
1266                 data->index = index;
1267         }
1268         return true;
1269 }
1270
1271 static bool cb_nearest_walk_order(const BVHTreeAxisRange *UNUSED(bounds), char axis, void *userdata)
1272 {
1273         const bool *r_axis_closest = ((struct Nearest2dUserData *)userdata)->r_axis_closest;
1274         return r_axis_closest[axis];
1275 }
1276
1277 /** \} */
1278
1279 /* -------------------------------------------------------------------- */
1280
1281 /** \name Internal Object Snapping API
1282  * \{ */
1283
1284 static bool snapArmature(
1285         SnapData *snapdata,
1286         Object *ob, bArmature *arm, float obmat[4][4],
1287         /* read/write args */
1288         float *ray_depth, float *dist_px,
1289         /* return args */
1290         float r_loc[3], float *UNUSED(r_no))
1291 {
1292         bool retval = false;
1293
1294         float ray_start_local[3], ray_normal_local[3]; /* Used only in the snap to edges */
1295         if (snapdata->snap_to == SCE_SNAP_MODE_EDGE) {
1296                 float imat[4][4];
1297                 invert_m4_m4(imat, obmat);
1298
1299                 copy_v3_v3(ray_start_local, snapdata->ray_origin);
1300                 copy_v3_v3(ray_normal_local, snapdata->ray_dir);
1301                 mul_m4_v3(imat, ray_start_local);
1302                 mul_mat3_m4_v3(imat, ray_normal_local);
1303         }
1304         else if (snapdata->snap_to != SCE_SNAP_MODE_VERTEX) { /* Currently only edge and vert */
1305                 return retval;
1306         }
1307
1308         bool is_persp = snapdata->view_proj == VIEW_PROJ_PERSP;
1309         float lpmat[4][4], dist_px_sq;
1310         mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
1311         dist_px_sq = SQUARE(*dist_px);
1312
1313         if (arm->edbo) {
1314                 for (EditBone *eBone = arm->edbo->first; eBone; eBone = eBone->next) {
1315                         if (eBone->layer & arm->layer) {
1316                                 /* skip hidden or moving (selected) bones */
1317                                 if ((eBone->flag & (BONE_HIDDEN_A | BONE_ROOTSEL | BONE_TIPSEL)) == 0) {
1318                                         switch (snapdata->snap_to) {
1319                                                 case SCE_SNAP_MODE_VERTEX:
1320                                                         retval |= test_projected_vert_dist(
1321                                                                 snapdata->depth_range, snapdata->mval, eBone->head,
1322                                                                 lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1323                                                                 r_loc);
1324                                                         retval |= test_projected_vert_dist(
1325                                                                 snapdata->depth_range, snapdata->mval, eBone->tail,
1326                                                                 lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1327                                                                 r_loc);
1328                                                         break;
1329                                                 case SCE_SNAP_MODE_EDGE:
1330                                                         retval |= test_projected_edge_dist(
1331                                                                 snapdata->depth_range, snapdata->mval, lpmat,
1332                                                                 snapdata->win_half, is_persp, ray_start_local, ray_normal_local,
1333                                                                 eBone->head, eBone->tail,
1334                                                                 &dist_px_sq, r_loc);
1335                                                         break;
1336                                         }
1337                                 }
1338                         }
1339                 }
1340         }
1341         else if (ob->pose && ob->pose->chanbase.first) {
1342                 for (bPoseChannel *pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1343                         Bone *bone = pchan->bone;
1344                         /* skip hidden bones */
1345                         if (bone && !(bone->flag & (BONE_HIDDEN_P | BONE_HIDDEN_PG))) {
1346                                 const float *head_vec = pchan->pose_head;
1347                                 const float *tail_vec = pchan->pose_tail;
1348
1349                                 switch (snapdata->snap_to) {
1350                                         case SCE_SNAP_MODE_VERTEX:
1351                                                 retval |= test_projected_vert_dist(
1352                                                         snapdata->depth_range, snapdata->mval, head_vec,
1353                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1354                                                         r_loc);
1355                                                 retval |= test_projected_vert_dist(
1356                                                         snapdata->depth_range, snapdata->mval, tail_vec,
1357                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1358                                                         r_loc);
1359                                                 break;
1360                                         case SCE_SNAP_MODE_EDGE:
1361                                                 retval |= test_projected_edge_dist(
1362                                                         snapdata->depth_range, snapdata->mval, lpmat,
1363                                                         snapdata->win_half, is_persp, ray_start_local, ray_normal_local,
1364                                                         head_vec, tail_vec,
1365                                                         &dist_px_sq, r_loc);
1366                                                 break;
1367                                 }
1368                         }
1369                 }
1370         }
1371         if (retval) {
1372                 *dist_px = sqrtf(dist_px_sq);
1373                 mul_m4_v3(obmat, r_loc);
1374                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1375                 return true;
1376         }
1377         return false;
1378 }
1379
1380 static bool snapCurve(
1381         SnapData *snapdata,
1382         Object *ob, Curve *cu, float obmat[4][4],
1383         /* read/write args */
1384         float *ray_depth, float *dist_px,
1385         /* return args */
1386         float r_loc[3], float *UNUSED(r_no))
1387 {
1388         bool retval = false;
1389
1390         /* only vertex snapping mode (eg control points and handles) supported for now) */
1391         if (snapdata->snap_to != SCE_SNAP_MODE_VERTEX) {
1392                 return retval;
1393         }
1394
1395         bool is_persp = snapdata->view_proj == VIEW_PROJ_PERSP;
1396         float lpmat[4][4], dist_px_sq;
1397         mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
1398         dist_px_sq = SQUARE(*dist_px);
1399
1400         for (Nurb *nu = (ob->mode == OB_MODE_EDIT ? cu->editnurb->nurbs.first : cu->nurb.first); nu; nu = nu->next) {
1401                 for (int u = 0; u < nu->pntsu; u++) {
1402                         switch (snapdata->snap_to) {
1403                                 case SCE_SNAP_MODE_VERTEX:
1404                                 {
1405                                         if (ob->mode == OB_MODE_EDIT) {
1406                                                 if (nu->bezt) {
1407                                                         /* don't snap to selected (moving) or hidden */
1408                                                         if (nu->bezt[u].f2 & SELECT || nu->bezt[u].hide != 0) {
1409                                                                 break;
1410                                                         }
1411                                                         retval |= test_projected_vert_dist(
1412                                                                 snapdata->depth_range, snapdata->mval, nu->bezt[u].vec[1],
1413                                                                 lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1414                                                                 r_loc);
1415                                                         /* don't snap if handle is selected (moving), or if it is aligning to a moving handle */
1416                                                         if (!(nu->bezt[u].f1 & SELECT) &&
1417                                                             !(nu->bezt[u].h1 & HD_ALIGN && nu->bezt[u].f3 & SELECT))
1418                                                         {
1419                                                                 retval |= test_projected_vert_dist(
1420                                                                         snapdata->depth_range, snapdata->mval, nu->bezt[u].vec[0],
1421                                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1422                                                                         r_loc);
1423                                                         }
1424                                                         if (!(nu->bezt[u].f3 & SELECT) &&
1425                                                             !(nu->bezt[u].h2 & HD_ALIGN && nu->bezt[u].f1 & SELECT))
1426                                                         {
1427                                                                 retval |= test_projected_vert_dist(
1428                                                                         snapdata->depth_range, snapdata->mval, nu->bezt[u].vec[2],
1429                                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1430                                                                         r_loc);
1431                                                         }
1432                                                 }
1433                                                 else {
1434                                                         /* don't snap to selected (moving) or hidden */
1435                                                         if (nu->bp[u].f1 & SELECT || nu->bp[u].hide != 0) {
1436                                                                 break;
1437                                                         }
1438                                                         retval |= test_projected_vert_dist(
1439                                                                 snapdata->depth_range, snapdata->mval, nu->bp[u].vec,
1440                                                                 lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1441                                                                 r_loc);
1442                                                 }
1443                                         }
1444                                         else {
1445                                                 /* curve is not visible outside editmode if nurb length less than two */
1446                                                 if (nu->pntsu > 1) {
1447                                                         if (nu->bezt) {
1448                                                                 retval |= test_projected_vert_dist(
1449                                                                         snapdata->depth_range, snapdata->mval, nu->bezt[u].vec[1],
1450                                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1451                                                                         r_loc);
1452                                                         }
1453                                                         else {
1454                                                                 retval |= test_projected_vert_dist(
1455                                                                         snapdata->depth_range, snapdata->mval, nu->bp[u].vec,
1456                                                                         lpmat, snapdata->win_half, is_persp, &dist_px_sq,
1457                                                                         r_loc);
1458                                                         }
1459                                                 }
1460                                         }
1461                                         break;
1462                                 }
1463                                 default:
1464                                         break;
1465                         }
1466                 }
1467         }
1468         if (retval) {
1469                 *dist_px = sqrtf(dist_px_sq);
1470                 mul_m4_v3(obmat, r_loc);
1471                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1472                 return true;
1473         }
1474         return false;
1475 }
1476
1477 /* may extend later (for now just snaps to empty center) */
1478 static bool snapEmpty(
1479         SnapData *snapdata,
1480         Object *ob, float obmat[4][4],
1481         /* read/write args */
1482         float *ray_depth, float *dist_px,
1483         /* return args */
1484         float r_loc[3], float *UNUSED(r_no))
1485 {
1486         bool retval = false;
1487
1488         if (ob->transflag & OB_DUPLI) {
1489                 return retval;
1490         }
1491
1492         /* for now only vertex supported */
1493         switch (snapdata->snap_to) {
1494                 case SCE_SNAP_MODE_VERTEX:
1495                 {
1496                         bool is_persp = snapdata->view_proj == VIEW_PROJ_PERSP;
1497                         float dist_px_sq = SQUARE(*dist_px);
1498                         float tmp_co[3];
1499                         copy_v3_v3(tmp_co, obmat[3]);
1500                         if (test_projected_vert_dist(
1501                                 snapdata->depth_range, snapdata->mval, tmp_co,
1502                                 snapdata->pmat, snapdata->win_half, is_persp, &dist_px_sq,
1503                                 r_loc))
1504                         {
1505                                 *dist_px = sqrtf(dist_px_sq);
1506                                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1507                                 retval = true;
1508                         }
1509                         break;
1510                 }
1511                 default:
1512                         break;
1513         }
1514
1515         return retval;
1516 }
1517
1518 static bool snapCamera(
1519         const SnapObjectContext *sctx, SnapData *snapdata,
1520         Object *object, float obmat[4][4],
1521         /* read/write args */
1522         float *ray_depth, float *dist_px,
1523         /* return args */
1524         float r_loc[3], float *UNUSED(r_no))
1525 {
1526         Scene *scene = sctx->scene;
1527
1528         bool is_persp = snapdata->view_proj == VIEW_PROJ_PERSP;
1529         float dist_px_sq = SQUARE(*dist_px);
1530
1531         float orig_camera_mat[4][4], orig_camera_imat[4][4], imat[4][4];
1532         bool retval = false;
1533         MovieClip *clip = BKE_object_movieclip_get(scene, object, false);
1534         MovieTracking *tracking;
1535
1536         if (clip == NULL) {
1537                 return retval;
1538         }
1539         if (object->transflag & OB_DUPLI) {
1540                 return retval;
1541         }
1542
1543         tracking = &clip->tracking;
1544
1545         BKE_tracking_get_camera_object_matrix(scene, object, orig_camera_mat);
1546
1547         invert_m4_m4(orig_camera_imat, orig_camera_mat);
1548         invert_m4_m4(imat, obmat);
1549
1550         switch (snapdata->snap_to) {
1551                 case SCE_SNAP_MODE_VERTEX:
1552                 {
1553                         MovieTrackingObject *tracking_object;
1554
1555                         for (tracking_object = tracking->objects.first;
1556                              tracking_object;
1557                              tracking_object = tracking_object->next)
1558                         {
1559                                 ListBase *tracksbase = BKE_tracking_object_get_tracks(tracking, tracking_object);
1560                                 MovieTrackingTrack *track;
1561                                 float reconstructed_camera_mat[4][4],
1562                                       reconstructed_camera_imat[4][4];
1563                                 float (*vertex_obmat)[4];
1564
1565                                 if ((tracking_object->flag & TRACKING_OBJECT_CAMERA) == 0) {
1566                                         BKE_tracking_camera_get_reconstructed_interpolate(tracking, tracking_object,
1567                                                                                           CFRA, reconstructed_camera_mat);
1568
1569                                         invert_m4_m4(reconstructed_camera_imat, reconstructed_camera_mat);
1570                                 }
1571
1572                                 for (track = tracksbase->first; track; track = track->next) {
1573                                         float bundle_pos[3];
1574
1575                                         if ((track->flag & TRACK_HAS_BUNDLE) == 0) {
1576                                                 continue;
1577                                         }
1578
1579                                         copy_v3_v3(bundle_pos, track->bundle_pos);
1580                                         if (tracking_object->flag & TRACKING_OBJECT_CAMERA) {
1581                                                 vertex_obmat = orig_camera_mat;
1582                                         }
1583                                         else {
1584                                                 mul_m4_v3(reconstructed_camera_imat, bundle_pos);
1585                                                 vertex_obmat = obmat;
1586                                         }
1587
1588                                         mul_m4_v3(vertex_obmat, bundle_pos);
1589                                         retval |= test_projected_vert_dist(
1590                                                 snapdata->depth_range, snapdata->mval, bundle_pos,
1591                                                 snapdata->pmat, snapdata->win_half, is_persp, &dist_px_sq,
1592                                                 r_loc);
1593                                 }
1594                         }
1595
1596                         break;
1597                 }
1598                 default:
1599                         break;
1600         }
1601
1602         if (retval) {
1603                 *dist_px = sqrtf(dist_px_sq);
1604                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1605                 return true;
1606         }
1607         return false;
1608 }
1609
1610 static int dm_looptri_to_poly_index(DerivedMesh *dm, const MLoopTri *lt)
1611 {
1612         const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX);
1613         return index_mp_to_orig ? index_mp_to_orig[lt->poly] : lt->poly;
1614 }
1615
1616 static bool snapDerivedMesh(
1617         SnapObjectContext *sctx, SnapData *snapdata,
1618         Object *ob, DerivedMesh *dm, float obmat[4][4],
1619         /* read/write args */
1620         float *ray_depth, float *dist_px,
1621         /* return args */
1622         float r_loc[3], float r_no[3])
1623 {
1624         bool retval = false;
1625
1626         if (snapdata->snap_to == SCE_SNAP_MODE_EDGE) {
1627                 if (dm->getNumEdges(dm) == 0) {
1628                         return retval;
1629                 }
1630         }
1631         else {
1632                 if (dm->getNumVerts(dm) == 0) {
1633                         return retval;
1634                 }
1635         }
1636
1637         float imat[4][4];
1638         float timat[3][3]; /* transpose inverse matrix for normals */
1639         float ray_normal_local[3];
1640         float local_scale;
1641
1642         invert_m4_m4(imat, obmat);
1643         transpose_m3_m4(timat, imat);
1644
1645         copy_v3_v3(ray_normal_local, snapdata->ray_dir);
1646
1647         mul_mat3_m4_v3(imat, ray_normal_local);
1648
1649         /* local scale in normal direction */
1650         local_scale = normalize_v3(ray_normal_local);
1651
1652         float lpmat[4][4];
1653         float ray_org_local[3];
1654         float ray_min_dist;
1655
1656         mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
1657         ray_min_dist = snapdata->depth_range[0] * local_scale;
1658
1659         copy_v3_v3(ray_org_local, snapdata->ray_origin);
1660         mul_m4_v3(imat, ray_org_local);
1661
1662         /* Test BoundBox */
1663         BoundBox *bb = BKE_object_boundbox_get(ob);
1664         if (bb) {
1665                 /* In vertex and edges you need to get the pixel distance from ray to BoundBox, see: T46099, T46816 */
1666                 float dist_px_sq = dist_squared_to_projected_aabb_simple(
1667                             lpmat, snapdata->win_half, ray_min_dist, snapdata->mval,
1668                             ray_org_local, ray_normal_local, bb->vec[0], bb->vec[6]);
1669                 if (dist_px_sq > SQUARE(*dist_px)) {
1670                         return retval;
1671                 }
1672         }
1673
1674         SnapObjectData_Mesh *sod = NULL;
1675         BVHTreeFromMesh *treedata = NULL;
1676
1677         void **sod_p;
1678         if (BLI_ghash_ensure_p(sctx->cache.object_map, ob, &sod_p)) {
1679                 sod = *sod_p;
1680         }
1681         else {
1682                 sod = *sod_p = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*sod));
1683                 sod->sd.type = SNAP_MESH;
1684         }
1685
1686         int tree_index = -1;
1687         switch (snapdata->snap_to) {
1688                 case SCE_SNAP_MODE_EDGE:
1689                         tree_index = 1;
1690                         break;
1691                 case SCE_SNAP_MODE_VERTEX:
1692                         tree_index = 0;
1693                         break;
1694         }
1695         if (tree_index != -1) {
1696                 if (sod->bvh_trees[tree_index] == NULL) {
1697                         sod->bvh_trees[tree_index] = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*treedata));
1698                 }
1699                 treedata = sod->bvh_trees[tree_index];
1700
1701                 /* the tree is owned by the DM and may have been freed since we last used! */
1702                 if (treedata && treedata->tree) {
1703                         if (treedata->cached && !bvhcache_has_tree(dm->bvhCache, treedata->tree)) {
1704                                 free_bvhtree_from_mesh(treedata);
1705                         }
1706                         else {
1707                                 if (treedata->vert == NULL) {
1708                                         treedata->vert = DM_get_vert_array(dm, &treedata->vert_allocated);
1709                                 }
1710                                 if ((tree_index == 1) && (treedata->edge == NULL)) {
1711                                         treedata->edge = DM_get_edge_array(dm, &treedata->edge_allocated);
1712                                 }
1713                         }
1714                 }
1715         }
1716
1717         if (treedata) {
1718                 if (treedata->tree == NULL) {
1719                         switch (snapdata->snap_to) {
1720                                 case SCE_SNAP_MODE_EDGE:
1721                                         bvhtree_from_mesh_edges(treedata, dm, 0.0f, 2, 6);
1722                                         break;
1723                                 case SCE_SNAP_MODE_VERTEX:
1724                                         bvhtree_from_mesh_verts(treedata, dm, 0.0f, 2, 6);
1725                                         break;
1726                         }
1727                 }
1728                 if (treedata->tree == NULL) {
1729                         return retval;
1730                 }
1731         }
1732         else {
1733                 return retval;
1734         }
1735
1736         /* Warning: the depth_max is currently being used only in perspective view.
1737          * It is not correct to limit the maximum depth for elements obtained with nearest
1738          * since this limitation depends on the normal and the size of the occlusion face.
1739          * And more... ray_depth is being confused with Z-depth here... (varies only the precision) */
1740         const float ray_depth_max_global = *ray_depth + snapdata->depth_range[0];
1741
1742         Nearest2dUserData neasrest2d = {
1743                 .dist_px_sq = SQUARE(*dist_px),
1744                 .r_axis_closest = {1.0f, 1.0f, 1.0f},
1745                 .depth_range = {snapdata->depth_range[0], ray_depth_max_global},
1746                 .userdata = treedata,
1747                 .get_edge_verts = (Nearest2DGetEdgeVertsCallback)get_dm_edge_verts,
1748                 .copy_vert_no = (Nearest2DCopyVertNoCallback)copy_dm_vert_no,
1749                 .index = -1};
1750
1751         dist_squared_to_projected_aabb_precalc(
1752                 &neasrest2d.data_precalc, lpmat,
1753                 snapdata->view_proj == VIEW_PROJ_PERSP, snapdata->win_half,
1754                 ray_min_dist, snapdata->mval, ray_org_local, ray_normal_local);
1755
1756         BVHTree_WalkLeafCallback cb_walk_leaf =
1757                 (snapdata->snap_to == SCE_SNAP_MODE_VERTEX) ?
1758                 cb_walk_leaf_snap_vert : cb_walk_leaf_snap_edge;
1759
1760         BLI_bvhtree_walk_dfs(
1761                 treedata->tree,
1762                 cb_walk_parent_snap_project, cb_walk_leaf, cb_nearest_walk_order, &neasrest2d);
1763
1764         if (neasrest2d.index != -1) {
1765                 copy_v3_v3(r_loc, neasrest2d.co);
1766                 mul_m4_v3(obmat, r_loc);
1767                 if (r_no) {
1768                         copy_v3_v3(r_no, neasrest2d.no);
1769                         mul_m3_v3(timat, r_no);
1770                         normalize_v3(r_no);
1771                 }
1772                 *dist_px = sqrtf(neasrest2d.dist_px_sq);
1773                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1774
1775                 retval = true;
1776         }
1777
1778         return retval;
1779 }
1780
1781 static bool snapEditMesh(
1782         SnapObjectContext *sctx, SnapData *snapdata,
1783         Object *ob, BMEditMesh *em, float obmat[4][4],
1784         /* read/write args */
1785         float *ray_depth, float *dist_px,
1786         /* return args */
1787         float r_loc[3], float r_no[3])
1788 {
1789         bool retval = false;
1790
1791         if (snapdata->snap_to == SCE_SNAP_MODE_EDGE) {
1792                 if (em->bm->totedge == 0) {
1793                         return retval;
1794                 }
1795         }
1796         else {
1797                 if (em->bm->totvert == 0) {
1798                         return retval;
1799                 }
1800         }
1801
1802         float imat[4][4];
1803         float timat[3][3]; /* transpose inverse matrix for normals */
1804         float ray_normal_local[3];
1805
1806         invert_m4_m4(imat, obmat);
1807         transpose_m3_m4(timat, imat);
1808
1809         copy_v3_v3(ray_normal_local, snapdata->ray_dir);
1810
1811         mul_mat3_m4_v3(imat, ray_normal_local);
1812
1813         /* local scale in normal direction */
1814         float local_scale = normalize_v3(ray_normal_local);
1815
1816         SnapObjectData_EditMesh *sod = NULL;
1817         BVHTreeFromEditMesh *treedata = NULL;
1818
1819         void **sod_p;
1820         if (BLI_ghash_ensure_p(sctx->cache.object_map, ob, &sod_p)) {
1821                 sod = *sod_p;
1822         }
1823         else {
1824                 sod = *sod_p = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*sod));
1825                 sod->sd.type = SNAP_EDIT_MESH;
1826         }
1827
1828         int tree_index = -1;
1829         switch (snapdata->snap_to) {
1830                 case SCE_SNAP_MODE_EDGE:
1831                         tree_index = 1;
1832                         break;
1833                 case SCE_SNAP_MODE_VERTEX:
1834                         tree_index = 0;
1835                         break;
1836         }
1837         if (tree_index != -1) {
1838                 if (sod->bvh_trees[tree_index] == NULL) {
1839                         sod->bvh_trees[tree_index] = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*treedata));
1840                 }
1841                 treedata = sod->bvh_trees[tree_index];
1842         }
1843
1844         if (treedata) {
1845                 if (treedata->tree == NULL) {
1846                         BLI_bitmap *elem_mask = NULL;
1847                         switch (snapdata->snap_to) {
1848                                 case SCE_SNAP_MODE_EDGE:
1849                                 {
1850                                         int edges_num_active = -1;
1851                                         if (sctx->callbacks.edit_mesh.test_edge_fn) {
1852                                                 elem_mask = BLI_BITMAP_NEW(em->bm->totedge, __func__);
1853                                                 edges_num_active = BM_iter_mesh_bitmap_from_filter(
1854                                                         BM_EDGES_OF_MESH, em->bm, elem_mask,
1855                                                         (bool (*)(BMElem *, void *))sctx->callbacks.edit_mesh.test_edge_fn,
1856                                                         sctx->callbacks.edit_mesh.user_data);
1857                                         }
1858                                         bvhtree_from_editmesh_edges_ex(treedata, em, elem_mask, edges_num_active, 0.0f, 2, 6);
1859                                         break;
1860                                 }
1861                                 case SCE_SNAP_MODE_VERTEX:
1862                                 {
1863                                         int verts_num_active = -1;
1864                                         if (sctx->callbacks.edit_mesh.test_vert_fn) {
1865                                                 elem_mask = BLI_BITMAP_NEW(em->bm->totvert, __func__);
1866                                                 verts_num_active = BM_iter_mesh_bitmap_from_filter(
1867                                                         BM_VERTS_OF_MESH, em->bm, elem_mask,
1868                                                         (bool (*)(BMElem *, void *))sctx->callbacks.edit_mesh.test_vert_fn,
1869                                                         sctx->callbacks.edit_mesh.user_data);
1870                                         }
1871                                         bvhtree_from_editmesh_verts_ex(treedata, em, elem_mask, verts_num_active, 0.0f, 2, 6);
1872                                         break;
1873                                 }
1874                         }
1875                         if (elem_mask) {
1876                                 MEM_freeN(elem_mask);
1877                         }
1878                 }
1879                 if (treedata->tree == NULL) {
1880                         return retval;
1881                 }
1882         }
1883         else {
1884                 return retval;
1885         }
1886
1887         float ray_org_local[3];
1888         copy_v3_v3(ray_org_local, snapdata->ray_origin);
1889         mul_m4_v3(imat, ray_org_local);
1890
1891         Nearest2dUserData neasrest2d = {
1892                 .dist_px_sq = SQUARE(*dist_px),
1893                 .r_axis_closest = {1.0f, 1.0f, 1.0f},
1894                 .depth_range = {snapdata->depth_range[0], *ray_depth + snapdata->depth_range[0]},
1895                 .userdata = treedata,
1896                 .get_edge_verts = (Nearest2DGetEdgeVertsCallback)get_bedge_verts,
1897                 .copy_vert_no = (Nearest2DCopyVertNoCallback)copy_bvert_no,
1898                 .index = -1};
1899
1900         float lpmat[4][4];
1901         mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
1902         dist_squared_to_projected_aabb_precalc(
1903                 &neasrest2d.data_precalc, lpmat,
1904                 snapdata->view_proj == VIEW_PROJ_PERSP, snapdata->win_half,
1905                 (snapdata->depth_range[0] * local_scale), snapdata->mval,
1906                 ray_org_local, ray_normal_local);
1907
1908         BVHTree_WalkLeafCallback cb_walk_leaf =
1909                 (snapdata->snap_to == SCE_SNAP_MODE_VERTEX) ?
1910                 cb_walk_leaf_snap_vert : cb_walk_leaf_snap_edge;
1911
1912         BLI_bvhtree_walk_dfs(
1913                 treedata->tree,
1914                 cb_walk_parent_snap_project, cb_walk_leaf, cb_nearest_walk_order, &neasrest2d);
1915
1916         if (neasrest2d.index != -1) {
1917                 copy_v3_v3(r_loc, neasrest2d.co);
1918                 mul_m4_v3(obmat, r_loc);
1919                 if (r_no) {
1920                         copy_v3_v3(r_no, neasrest2d.no);
1921                         mul_m3_v3(timat, r_no);
1922                         normalize_v3(r_no);
1923                 }
1924                 *dist_px = sqrtf(neasrest2d.dist_px_sq);
1925                 *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
1926
1927                 retval = true;
1928         }
1929
1930         return retval;
1931 }
1932
1933 /**
1934  * \param use_obedit: Uses the coordinates of BMesh (if any) to do the snapping;
1935  *
1936  * \note Duplicate args here are documented at #snapObjectsRay
1937  */
1938 static bool snapObject(
1939         SnapObjectContext *sctx, SnapData *snapdata,
1940         Object *ob, float obmat[4][4],
1941         bool use_obedit,
1942         /* read/write args */
1943         float *ray_depth, float *dist_px,
1944         /* return args */
1945         float r_loc[3], float r_no[3],
1946         Object **r_ob, float r_obmat[4][4])
1947 {
1948         bool retval = false;
1949
1950         if (ob->type == OB_MESH) {
1951                 BMEditMesh *em;
1952
1953                 if (use_obedit) {
1954                         em = BKE_editmesh_from_object(ob);
1955                         retval = snapEditMesh(
1956                                 sctx, snapdata, ob, em, obmat,
1957                                 ray_depth, dist_px,
1958                                 r_loc, r_no);
1959                 }
1960                 else {
1961                         /* in this case we want the mesh from the editmesh, avoids stale data. see: T45978.
1962                          * still set the 'em' to NULL, since we only want the 'dm'. */
1963                         DerivedMesh *dm;
1964                         em = BKE_editmesh_from_object(ob);
1965                         if (em) {
1966                                 editbmesh_get_derived_cage_and_final(sctx->scene, ob, em, CD_MASK_BAREMESH, &dm);
1967                         }
1968                         else {
1969                                 dm = mesh_get_derived_final(sctx->scene, ob, CD_MASK_BAREMESH);
1970                         }
1971                         retval = snapDerivedMesh(
1972                                 sctx, snapdata, ob, dm, obmat,
1973                                 ray_depth, dist_px,
1974                                 r_loc, r_no);
1975
1976                         dm->release(dm);
1977                 }
1978         }
1979         else if (snapdata->snap_to != SCE_SNAP_MODE_FACE) {
1980                 if (ob->type == OB_ARMATURE) {
1981                         retval = snapArmature(
1982                                 snapdata,
1983                                 ob, ob->data, obmat,
1984                                 ray_depth, dist_px,
1985                                 r_loc, r_no);
1986                 }
1987                 else if (ob->type == OB_CURVE) {
1988                         retval = snapCurve(
1989                                 snapdata,
1990                                 ob, ob->data, obmat,
1991                                 ray_depth, dist_px,
1992                                 r_loc, r_no);
1993                 }
1994                 else if (ob->type == OB_EMPTY) {
1995                         retval = snapEmpty(
1996                                 snapdata,
1997                                 ob, obmat,
1998                                 ray_depth, dist_px,
1999                                 r_loc, r_no);
2000                 }
2001                 else if (ob->type == OB_CAMERA) {
2002                         retval = snapCamera(
2003                                 sctx, snapdata, ob, obmat,
2004                                 ray_depth, dist_px,
2005                                 r_loc, r_no);
2006                 }
2007         }
2008
2009         if (retval) {
2010                 if (r_ob) {
2011                         *r_ob = ob;
2012                         copy_m4_m4(r_obmat, obmat);
2013                 }
2014         }
2015
2016         return retval;
2017 }
2018
2019
2020 struct SnapObjUserData {
2021         SnapData *snapdata;
2022         /* read/write args */
2023         float *ray_depth;
2024         float *dist_px;
2025         /* return args */
2026         float *r_loc;
2027         float *r_no;
2028         Object **r_ob;
2029         float (*r_obmat)[4];
2030         bool ret;
2031 };
2032
2033 static void sanp_obj_cb(SnapObjectContext *sctx, bool is_obedit, Object *ob, float obmat[4][4], void *data)
2034 {
2035         struct SnapObjUserData *dt = data;
2036         dt->ret |= snapObject(
2037                 sctx, dt->snapdata,
2038                 ob, obmat, is_obedit,
2039                 /* read/write args */
2040                 dt->ray_depth, dt->dist_px,
2041                 /* return args */
2042                 dt->r_loc, dt->r_no,
2043                 dt->r_ob, dt->r_obmat);
2044 }
2045
2046
2047 /**
2048  * Main Snapping Function
2049  * ======================
2050  *
2051  * Walks through all objects in the scene to find the closest snap element ray.
2052  *
2053  * \param sctx: Snap context to store data.
2054  * \param snapdata: struct generated in `get_snapdata`.
2055  * \param snap_select : from enum SnapSelect.
2056  * \param use_object_edit_cage : Uses the coordinates of BMesh(if any) to do the snapping.
2057  *
2058  * Read/Write Args
2059  * ---------------
2060  *
2061  * \param ray_depth: maximum depth allowed for r_co, elements deeper than this value will be ignored.
2062  * \param dist_px: Maximum threshold distance (in pixels).
2063  *
2064  * Output Args
2065  * -----------
2066  *
2067  * \param r_loc: Hit location.
2068  * \param r_no: Hit normal (optional).
2069  * \param r_index: Hit index or -1 when no valid index is found.
2070  * (currently only set to the polygon index when when using ``snap_to == SCE_SNAP_MODE_FACE``).
2071  * \param r_ob: Hit object.
2072  * \param r_obmat: Object matrix (may not be #Object.obmat with dupli-instances).
2073  *
2074  */
2075 static bool snapObjectsRay(
2076         SnapObjectContext *sctx, SnapData *snapdata,
2077         const SnapSelect snap_select, const bool use_object_edit_cage,
2078         /* read/write args */
2079         float *ray_depth, float *dist_px,
2080         /* return args */
2081         float r_loc[3], float r_no[3],
2082         Object **r_ob, float r_obmat[4][4])
2083 {
2084         Object *obedit = use_object_edit_cage ? sctx->scene->obedit : NULL;
2085
2086         struct SnapObjUserData data = {
2087                 .snapdata = snapdata,
2088                 .ray_depth = ray_depth,
2089                 .dist_px = dist_px,
2090                 .r_loc = r_loc,
2091                 .r_no = r_no,
2092                 .r_ob = r_ob,
2093                 .r_obmat = r_obmat,
2094                 .ret = false,
2095         };
2096
2097         iter_snap_objects(sctx, snap_select, obedit, sanp_obj_cb, &data);
2098
2099         return data.ret;
2100 }
2101
2102 /** \} */
2103
2104
2105 /* -------------------------------------------------------------------- */
2106
2107 /** \name Public Object Snapping API
2108  * \{ */
2109
2110 SnapObjectContext *ED_transform_snap_object_context_create(
2111         Main *bmain, Scene *scene, int flag)
2112 {
2113         SnapObjectContext *sctx = MEM_callocN(sizeof(*sctx), __func__);
2114
2115         sctx->flag = flag;
2116
2117         sctx->bmain = bmain;
2118         sctx->scene = scene;
2119
2120         sctx->cache.object_map = BLI_ghash_ptr_new(__func__);
2121         sctx->cache.mem_arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
2122
2123         return sctx;
2124 }
2125
2126 SnapObjectContext *ED_transform_snap_object_context_create_view3d(
2127         Main *bmain, Scene *scene, int flag,
2128         /* extra args for view3d */
2129         const ARegion *ar, const View3D *v3d)
2130 {
2131         SnapObjectContext *sctx = ED_transform_snap_object_context_create(bmain, scene, flag);
2132
2133         sctx->use_v3d = true;
2134         sctx->v3d_data.ar = ar;
2135         sctx->v3d_data.v3d = v3d;
2136
2137         return sctx;
2138 }
2139
2140 static void snap_object_data_free(void *sod_v)
2141 {
2142         switch (((SnapObjectData *)sod_v)->type) {
2143                 case SNAP_MESH:
2144                 {
2145                         SnapObjectData_Mesh *sod = sod_v;
2146                         for (int i = 0; i < ARRAY_SIZE(sod->bvh_trees); i++) {
2147                                 if (sod->bvh_trees[i]) {
2148                                         free_bvhtree_from_mesh(sod->bvh_trees[i]);
2149                                 }
2150                         }
2151                         if (sod->poly_allocated) {
2152                                 MEM_freeN(sod->mpoly);
2153                         }
2154                         break;
2155                 }
2156                 case SNAP_EDIT_MESH:
2157                 {
2158                         SnapObjectData_EditMesh *sod = sod_v;
2159                         for (int i = 0; i < ARRAY_SIZE(sod->bvh_trees); i++) {
2160                                 if (sod->bvh_trees[i]) {
2161                                         free_bvhtree_from_editmesh(sod->bvh_trees[i]);
2162                                 }
2163                         }
2164                         break;
2165                 }
2166         }
2167 }
2168
2169 void ED_transform_snap_object_context_destroy(SnapObjectContext *sctx)
2170 {
2171         BLI_ghash_free(sctx->cache.object_map, NULL, snap_object_data_free);
2172         BLI_memarena_free(sctx->cache.mem_arena);
2173
2174         MEM_freeN(sctx);
2175 }
2176
2177 void ED_transform_snap_object_context_set_editmesh_callbacks(
2178         SnapObjectContext *sctx,
2179         bool (*test_vert_fn)(BMVert *, void *user_data),
2180         bool (*test_edge_fn)(BMEdge *, void *user_data),
2181         bool (*test_face_fn)(BMFace *, void *user_data),
2182         void *user_data)
2183 {
2184         sctx->callbacks.edit_mesh.test_vert_fn = test_vert_fn;
2185         sctx->callbacks.edit_mesh.test_edge_fn = test_edge_fn;
2186         sctx->callbacks.edit_mesh.test_face_fn = test_face_fn;
2187
2188         sctx->callbacks.edit_mesh.user_data = user_data;
2189 }
2190
2191 bool ED_transform_snap_object_project_ray_ex(
2192         SnapObjectContext *sctx,
2193         const struct SnapObjectParams *params,
2194         const float ray_start[3], const float ray_normal[3],
2195         float *ray_depth,
2196         float r_loc[3], float r_no[3], int *r_index,
2197         Object **r_ob, float r_obmat[4][4])
2198 {
2199         return raycastObjects(
2200                 sctx,
2201                 ray_start, ray_normal,
2202                 params->snap_select, params->use_object_edit_cage,
2203                 ray_depth, r_loc, r_no, r_index, r_ob, r_obmat, NULL);
2204 }
2205
2206 /**
2207  * Fill in a list of all hits.
2208  *
2209  * \param ray_depth: Only depths in this range are considered, -1.0 for maximum.
2210  * \param sort: Optionally sort the hits by depth.
2211  * \param r_hit_list: List of #SnapObjectHitDepth (caller must free).
2212  */
2213 bool ED_transform_snap_object_project_ray_all(
2214         SnapObjectContext *sctx,
2215         const struct SnapObjectParams *params,
2216         const float ray_start[3], const float ray_normal[3],
2217         float ray_depth, bool sort,
2218         ListBase *r_hit_list)
2219 {
2220         if (ray_depth == -1.0f) {
2221                 ray_depth = BVH_RAYCAST_DIST_MAX;
2222         }
2223
2224 #ifdef DEBUG
2225         float ray_depth_prev = ray_depth;
2226 #endif
2227
2228         bool retval = raycastObjects(
2229                 sctx,
2230                 ray_start, ray_normal,
2231                 params->snap_select, params->use_object_edit_cage,
2232                 &ray_depth, NULL, NULL, NULL, NULL, NULL,
2233                 r_hit_list);
2234
2235         /* meant to be readonly for 'all' hits, ensure it is */
2236 #ifdef DEBUG
2237         BLI_assert(ray_depth_prev == ray_depth);
2238 #endif
2239
2240         if (sort) {
2241                 BLI_listbase_sort(r_hit_list, hit_depth_cmp);
2242         }
2243
2244         return retval;
2245 }
2246
2247 /**
2248  * Convenience function for snap ray-casting.
2249  *
2250  * Given a ray, cast it into the scene (snapping to faces).
2251  *
2252  * \return Snap success
2253  */
2254 static bool transform_snap_context_project_ray_impl(
2255         SnapObjectContext *sctx,
2256         const struct SnapObjectParams *params,
2257         const float ray_start[3], const float ray_normal[3], float *ray_depth,
2258         float r_co[3], float r_no[3])
2259 {
2260         bool ret;
2261
2262         /* try snap edge, then face if it fails */
2263         ret = ED_transform_snap_object_project_ray_ex(
2264                 sctx,
2265                 params,
2266                 ray_start, ray_normal, ray_depth,
2267                 r_co, r_no, NULL,
2268                 NULL, NULL);
2269
2270         return ret;
2271 }
2272
2273 bool ED_transform_snap_object_project_ray(
2274         SnapObjectContext *sctx,
2275         const struct SnapObjectParams *params,
2276         const float ray_origin[3], const float ray_direction[3], float *ray_depth,
2277         float r_co[3], float r_no[3])
2278 {
2279         float ray_depth_fallback;
2280         if (ray_depth == NULL) {
2281                 ray_depth_fallback = BVH_RAYCAST_DIST_MAX;
2282                 ray_depth = &ray_depth_fallback;
2283         }
2284
2285         return transform_snap_context_project_ray_impl(
2286                 sctx,
2287                 params,
2288                 ray_origin, ray_direction, ray_depth,
2289                 r_co, r_no);
2290 }
2291
2292 static bool transform_snap_context_project_view3d_mixed_impl(
2293         SnapObjectContext *sctx,
2294         const unsigned short snap_to_flag,
2295         const struct SnapObjectParams *params,
2296         const float mval[2], float *dist_px,
2297         bool use_depth,
2298         float r_co[3], float r_no[3])
2299 {
2300         float ray_depth = BVH_RAYCAST_DIST_MAX;
2301         bool is_hit = false;
2302
2303         const int  elem_type[3] = {SCE_SNAP_MODE_VERTEX, SCE_SNAP_MODE_EDGE, SCE_SNAP_MODE_FACE};
2304
2305         BLI_assert(snap_to_flag != 0);
2306         BLI_assert((snap_to_flag & ~(1 | 2 | 4)) == 0);
2307
2308         if (use_depth) {
2309                 const float dist_px_orig = dist_px ? *dist_px : 0;
2310                 for (int i = 2; i >= 0; i--) {
2311                         if (snap_to_flag & (1 << i)) {
2312                                 if (i == 0) {
2313                                         BLI_assert(dist_px != NULL);
2314                                         *dist_px = dist_px_orig;
2315                                 }
2316                                 if (ED_transform_snap_object_project_view3d(
2317                                         sctx,
2318                                         elem_type[i], params,
2319                                         mval, dist_px, &ray_depth,
2320                                         r_co, r_no))
2321                                 {
2322                                         /* 0.01 is a random but small value to prioritizing
2323                                          * the first elements of the loop */
2324                                         ray_depth += 0.01f;
2325                                         is_hit = true;
2326                                 }
2327                         }
2328                 }
2329         }
2330         else {
2331                 for (int i = 0; i < 3; i++) {
2332                         if (snap_to_flag & (1 << i)) {
2333                                 if (ED_transform_snap_object_project_view3d(
2334                                         sctx,
2335                                         elem_type[i], params,
2336                                         mval, dist_px, &ray_depth,
2337                                         r_co, r_no))
2338                                 {
2339                                         is_hit = true;
2340                                         break;
2341                                 }
2342                         }
2343                 }
2344         }
2345
2346         return is_hit;
2347 }
2348
2349 /**
2350  * Convenience function for performing snapping.
2351  *
2352  * Given a 2D region value, snap to vert/edge/face.
2353  *
2354  * \param sctx: Snap context.
2355  * \param mval_fl: Screenspace coordinate.
2356  * \param dist_px: Maximum distance to snap (in pixels).
2357  * \param use_depth: Snap to the closest element, use when using more than one snap type.
2358  * \param r_co: hit location.
2359  * \param r_no: hit normal (optional).
2360  * \return Snap success
2361  */
2362 bool ED_transform_snap_object_project_view3d_mixed(
2363         SnapObjectContext *sctx,
2364         const unsigned short snap_to_flag,
2365         const struct SnapObjectParams *params,
2366         const float mval_fl[2], float *dist_px,
2367         bool use_depth,
2368         float r_co[3], float r_no[3])
2369 {
2370         return transform_snap_context_project_view3d_mixed_impl(
2371                 sctx,
2372                 snap_to_flag, params,
2373                 mval_fl, dist_px, use_depth,
2374                 r_co, r_no);
2375 }
2376
2377 bool ED_transform_snap_object_project_view3d_ex(
2378         SnapObjectContext *sctx,
2379         const unsigned short snap_to,
2380         const struct SnapObjectParams *params,
2381         const float mval[2], float *dist_px,
2382         float *ray_depth,
2383         float r_loc[3], float r_no[3], int *r_index)
2384 {
2385         float ray_origin[3], ray_start[3], ray_normal[3], depth_range[2], ray_end[3];
2386
2387         const ARegion *ar = sctx->v3d_data.ar;
2388         const RegionView3D *rv3d = ar->regiondata;
2389
2390         ED_view3d_win_to_origin(ar, mval, ray_origin);
2391         ED_view3d_win_to_vector(ar, mval, ray_normal);
2392
2393         ED_view3d_clip_range_get(
2394                 sctx->v3d_data.v3d, sctx->v3d_data.ar->regiondata,
2395                 &depth_range[0], &depth_range[1], false);
2396
2397         madd_v3_v3v3fl(ray_start, ray_origin, ray_normal, depth_range[0]);
2398         madd_v3_v3v3fl(ray_end, ray_origin, ray_normal, depth_range[1]);
2399
2400         if (!ED_view3d_clip_segment(rv3d, ray_start, ray_end)) {
2401                 return false;
2402         }
2403
2404         float ray_depth_fallback;
2405         if (ray_depth == NULL) {
2406                 ray_depth_fallback = BVH_RAYCAST_DIST_MAX;
2407                 ray_depth = &ray_depth_fallback;
2408         }
2409
2410         if (snap_to == SCE_SNAP_MODE_FACE) {
2411                 return raycastObjects(
2412                         sctx,
2413                         ray_start, ray_normal,
2414                         params->snap_select, params->use_object_edit_cage,
2415                         ray_depth, r_loc, r_no, r_index, NULL, NULL, NULL);
2416         }
2417         else {
2418                 SnapData snapdata;
2419                 const enum eViewProj view_proj = ((RegionView3D *)ar->regiondata)->is_persp ? VIEW_PROJ_PERSP : VIEW_PROJ_ORTHO;
2420                 snap_data_set(&snapdata, ar, snap_to, view_proj, mval,
2421                         ray_origin, ray_start, ray_normal, depth_range);
2422
2423                 return snapObjectsRay(
2424                         sctx, &snapdata,
2425                         params->snap_select, params->use_object_edit_cage,
2426                         ray_depth, dist_px, r_loc, r_no, NULL, NULL);
2427         }
2428 }
2429
2430 bool ED_transform_snap_object_project_view3d(
2431         SnapObjectContext *sctx,
2432         const unsigned short snap_to,
2433         const struct SnapObjectParams *params,
2434         const float mval[2], float *dist_px,
2435         float *ray_depth,
2436         float r_loc[3], float r_no[3])
2437 {
2438         return ED_transform_snap_object_project_view3d_ex(
2439                 sctx,
2440                 snap_to,
2441                 params,
2442                 mval, dist_px,
2443                 ray_depth,
2444                 r_loc, r_no, NULL);
2445 }
2446
2447 /**
2448  * see: #ED_transform_snap_object_project_ray_all
2449  */
2450 bool ED_transform_snap_object_project_all_view3d_ex(
2451         SnapObjectContext *sctx,
2452         const struct SnapObjectParams *params,
2453         const float mval[2],
2454         float ray_depth, bool sort,
2455         ListBase *r_hit_list)
2456 {
2457         float ray_start[3], ray_normal[3];
2458
2459         if (!ED_view3d_win_to_ray_ex(
2460                 sctx->v3d_data.ar, sctx->v3d_data.v3d,
2461                 mval, NULL, ray_normal, ray_start, true))
2462         {
2463                 return false;
2464         }
2465
2466         return ED_transform_snap_object_project_ray_all(
2467                 sctx,
2468                 params,
2469                 ray_start, ray_normal, ray_depth, sort,
2470                 r_hit_list);
2471 }
2472
2473 /** \} */