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