Cleanup: trailing space
[blender.git] / source / blender / editors / transform / transform_snap.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Martin Poirier
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/transform/transform_snap.c
29  *  \ingroup edtransform
30  */
31
32 #include <stdlib.h>
33 #include <math.h>
34 #include <float.h>
35 #include <stdio.h>
36
37 #include "PIL_time.h"
38
39 #include "DNA_scene_types.h"
40 #include "DNA_object_types.h"
41 #include "DNA_meshdata_types.h"  /* Temporary, for snapping to other unselected meshes */
42 #include "DNA_node_types.h"
43 #include "DNA_space_types.h"
44 #include "DNA_screen_types.h"
45 #include "DNA_view3d_types.h"
46 #include "DNA_windowmanager_types.h"
47
48 #include "BLI_math.h"
49 #include "BLI_blenlib.h"
50 #include "BLI_utildefines.h"
51
52 #include "BIF_gl.h"
53
54 #include "BKE_DerivedMesh.h"
55 #include "BKE_global.h"
56 #include "BKE_object.h"
57 #include "BKE_anim.h"  /* for duplis */
58 #include "BKE_context.h"
59 #include "BKE_editmesh.h"
60 #include "BKE_sequencer.h"
61 #include "BKE_main.h"
62
63 #include "RNA_access.h"
64
65 #include "WM_types.h"
66
67 #include "ED_image.h"
68 #include "ED_node.h"
69 #include "ED_uvedit.h"
70 #include "ED_view3d.h"
71 #include "ED_transform_snap_object_context.h"
72
73 #include "UI_resources.h"
74 #include "UI_view2d.h"
75
76 #include "MEM_guardedalloc.h"
77
78 #include "transform.h"
79
80 /* this should be passed as an arg for use in snap functions */
81 #undef BASACT
82
83 /* use half of flt-max so we can scale up without an exception */
84
85 /********************* PROTOTYPES ***********************/
86
87 static void setSnappingCallback(TransInfo *t);
88
89 static void ApplySnapTranslation(TransInfo *t, float vec[3]);
90 static void ApplySnapRotation(TransInfo *t, float *vec);
91 static void ApplySnapResize(TransInfo *t, float vec[2]);
92
93 /* static void CalcSnapGrid(TransInfo *t, float *vec); */
94 static void CalcSnapGeometry(TransInfo *t, float *vec);
95
96 static void TargetSnapMedian(TransInfo *t);
97 static void TargetSnapCenter(TransInfo *t);
98 static void TargetSnapClosest(TransInfo *t);
99 static void TargetSnapActive(TransInfo *t);
100
101 static float RotationBetween(TransInfo *t, const float p1[3], const float p2[3]);
102 static float TranslationBetween(TransInfo *t, const float p1[3], const float p2[3]);
103 static float ResizeBetween(TransInfo *t, const float p1[3], const float p2[3]);
104
105
106 /****************** IMPLEMENTATIONS *********************/
107
108 static bool snapNodeTest(View2D *v2d, bNode *node, eSnapSelect snap_select);
109 static NodeBorder snapNodeBorder(int snap_node_mode);
110
111 #if 0
112 int BIF_snappingSupported(Object *obedit)
113 {
114         int status = 0;
115
116         /* only support object mesh, armature, curves */
117         if (obedit == NULL || ELEM(obedit->type, OB_MESH, OB_ARMATURE, OB_CURVE, OB_LATTICE, OB_MBALL)) {
118                 status = 1;
119         }
120
121         return status;
122 }
123 #endif
124
125 bool validSnap(TransInfo *t)
126 {
127         return (t->tsnap.status & (POINT_INIT | TARGET_INIT)) == (POINT_INIT | TARGET_INIT) ||
128                (t->tsnap.status & (MULTI_POINTS | TARGET_INIT)) == (MULTI_POINTS | TARGET_INIT);
129 }
130
131 bool activeSnap(TransInfo *t)
132 {
133         return ((t->modifiers & (MOD_SNAP | MOD_SNAP_INVERT)) == MOD_SNAP) ||
134                ((t->modifiers & (MOD_SNAP | MOD_SNAP_INVERT)) == MOD_SNAP_INVERT);
135 }
136
137 void drawSnapping(const struct bContext *C, TransInfo *t)
138 {
139         unsigned char col[4], selectedCol[4], activeCol[4];
140
141         if (!activeSnap(t))
142                 return;
143
144         UI_GetThemeColor3ubv(TH_TRANSFORM, col);
145         col[3] = 128;
146
147         UI_GetThemeColor3ubv(TH_SELECT, selectedCol);
148         selectedCol[3] = 128;
149
150         UI_GetThemeColor3ubv(TH_ACTIVE, activeCol);
151         activeCol[3] = 192;
152
153         if (t->spacetype == SPACE_VIEW3D) {
154                 if (validSnap(t)) {
155                         TransSnapPoint *p;
156                         View3D *v3d = CTX_wm_view3d(C);
157                         RegionView3D *rv3d = CTX_wm_region_view3d(C);
158                         float imat[4][4];
159                         float size;
160
161                         glDisable(GL_DEPTH_TEST);
162
163                         size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
164
165                         invert_m4_m4(imat, rv3d->viewmat);
166
167                         for (p = t->tsnap.points.first; p; p = p->next) {
168                                 if (p == t->tsnap.selectedPoint) {
169                                         glColor4ubv(selectedCol);
170                                 }
171                                 else {
172                                         glColor4ubv(col);
173                                 }
174
175                                 drawcircball(GL_LINE_LOOP, p->co, ED_view3d_pixel_size(rv3d, p->co) * size * 0.75f, imat);
176                         }
177
178                         if (t->tsnap.status & POINT_INIT) {
179                                 glColor4ubv(activeCol);
180
181                                 drawcircball(GL_LINE_LOOP, t->tsnap.snapPoint, ED_view3d_pixel_size(rv3d, t->tsnap.snapPoint) * size, imat);
182                         }
183
184                         /* draw normal if needed */
185                         if (usingSnappingNormal(t) && validSnappingNormal(t)) {
186                                 glColor4ubv(activeCol);
187
188                                 glBegin(GL_LINES);
189                                 glVertex3f(t->tsnap.snapPoint[0], t->tsnap.snapPoint[1], t->tsnap.snapPoint[2]);
190                                 glVertex3f(t->tsnap.snapPoint[0] + t->tsnap.snapNormal[0],
191                                            t->tsnap.snapPoint[1] + t->tsnap.snapNormal[1],
192                                            t->tsnap.snapPoint[2] + t->tsnap.snapNormal[2]);
193                                 glEnd();
194                         }
195
196                         if (v3d->zbuf)
197                                 glEnable(GL_DEPTH_TEST);
198                 }
199         }
200         else if (t->spacetype == SPACE_IMAGE) {
201                 if (validSnap(t)) {
202                         /* This will not draw, and Im nor sure why - campbell */
203 #if 0
204                         float xuser_asp, yuser_asp;
205                         int wi, hi;
206                         float w, h;
207
208                         calc_image_view(G.sima, 'f');   // float
209                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
210                         glLoadIdentity();
211
212                         ED_space_image_get_aspect(t->sa->spacedata.first, &xuser_aspx, &yuser_asp);
213                         ED_space_image_width(t->sa->spacedata.first, &wi, &hi);
214                         w = (((float)wi) / IMG_SIZE_FALLBACK) * G.sima->zoom * xuser_asp;
215                         h = (((float)hi) / IMG_SIZE_FALLBACK) * G.sima->zoom * yuser_asp;
216
217                         cpack(0xFFFFFF);
218                         glTranslate2fv(t->tsnap.snapPoint);
219
220                         //glRectf(0, 0, 1, 1);
221
222                         setlinestyle(0);
223                         cpack(0x0);
224                         fdrawline(-0.020 / w, 0, -0.1 / w, 0);
225                         fdrawline(0.1 / w, 0, 0.020 / w, 0);
226                         fdrawline(0, -0.020 / h, 0, -0.1 / h);
227                         fdrawline(0, 0.1 / h, 0, 0.020 / h);
228
229                         glTranslatef(-t->tsnap.snapPoint[0], -t->tsnap.snapPoint[1], 0.0f);
230                         setlinestyle(0);
231 #endif
232                 }
233         }
234         else if (t->spacetype == SPACE_NODE) {
235                 if (validSnap(t)) {
236                         ARegion *ar = CTX_wm_region(C);
237                         TransSnapPoint *p;
238                         float size;
239
240                         size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
241
242                         glEnable(GL_BLEND);
243
244                         for (p = t->tsnap.points.first; p; p = p->next) {
245                                 if (p == t->tsnap.selectedPoint) {
246                                         glColor4ubv(selectedCol);
247                                 }
248                                 else {
249                                         glColor4ubv(col);
250                                 }
251
252                                 ED_node_draw_snap(&ar->v2d, p->co, size, 0);
253                         }
254
255                         if (t->tsnap.status & POINT_INIT) {
256                                 glColor4ubv(activeCol);
257
258                                 ED_node_draw_snap(&ar->v2d, t->tsnap.snapPoint, size, t->tsnap.snapNodeBorder);
259                         }
260
261                         glDisable(GL_BLEND);
262                 }
263         }
264 }
265
266 eRedrawFlag handleSnapping(TransInfo *t, const wmEvent *event)
267 {
268         eRedrawFlag status = TREDRAW_NOTHING;
269
270 #if 0 // XXX need a proper selector for all snap mode
271         if (BIF_snappingSupported(t->obedit) && event->type == TABKEY && event->shift) {
272                 /* toggle snap and reinit */
273                 t->settings->snap_flag ^= SCE_SNAP;
274                 initSnapping(t, NULL);
275                 status = TREDRAW_HARD;
276         }
277 #endif
278         if (event->type == MOUSEMOVE) {
279                 status |= updateSelectedSnapPoint(t);
280         }
281
282         return status;
283 }
284
285 void applyProject(TransInfo *t)
286 {
287         /* XXX FLICKER IN OBJECT MODE */
288         if ((t->tsnap.project) && activeSnap(t) && (t->flag & T_NO_PROJECT) == 0) {
289                 TransData *td = t->data;
290                 float tvec[3];
291                 float imat[4][4];
292                 int i;
293
294                 if (t->flag & (T_EDIT | T_POSE)) {
295                         Object *ob = t->obedit ? t->obedit : t->poseobj;
296                         invert_m4_m4(imat, ob->obmat);
297                 }
298
299                 for (i = 0; i < t->total; i++, td++) {
300                         float iloc[3], loc[3], no[3];
301                         float mval_fl[2];
302                         float dist_px = TRANSFORM_DIST_MAX_PX;
303
304                         if (td->flag & TD_NOACTION)
305                                 break;
306
307                         if (td->flag & TD_SKIP)
308                                 continue;
309
310                         if ((t->flag & T_PROP_EDIT) && (td->factor == 0.0f))
311                                 continue;
312
313                         copy_v3_v3(iloc, td->loc);
314                         if (t->flag & (T_EDIT | T_POSE)) {
315                                 Object *ob = t->obedit ? t->obedit : t->poseobj;
316                                 mul_m4_v3(ob->obmat, iloc);
317                         }
318                         else if (t->flag & T_OBJECT) {
319                                 BKE_object_eval_transform_all(G.main->eval_ctx, t->scene, td->ob);
320                                 copy_v3_v3(iloc, td->ob->obmat[3]);
321                         }
322
323                         if (ED_view3d_project_float_global(t->ar, iloc, mval_fl, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
324                                 if (snapObjectsTransform(
325                                         t, mval_fl, &dist_px,
326                                         loc, no))
327                                 {
328 //                                      if (t->flag & (T_EDIT|T_POSE)) {
329 //                                              mul_m4_v3(imat, loc);
330 //                                      }
331
332                                         sub_v3_v3v3(tvec, loc, iloc);
333
334                                         mul_m3_v3(td->smtx, tvec);
335
336                                         add_v3_v3(td->loc, tvec);
337
338                                         if (t->tsnap.align && (t->flag & T_OBJECT)) {
339                                                 /* handle alignment as well */
340                                                 const float *original_normal;
341                                                 float mat[3][3];
342
343                                                 /* In pose mode, we want to align normals with Y axis of bones... */
344                                                 original_normal = td->axismtx[2];
345
346                                                 rotation_between_vecs_to_mat3(mat, original_normal, no);
347
348                                                 transform_data_ext_rotate(td, mat, true);
349
350                                                 /* TODO support constraints for rotation too? see ElementRotation */
351                                         }
352                                 }
353                         }
354
355                         //XXX constraintTransLim(t, td);
356                 }
357         }
358 }
359
360 void applyGridAbsolute(TransInfo *t)
361 {
362         float grid_size = 0.0f;
363         GearsType grid_action;
364         TransData *td;
365         float (*obmat)[4] = NULL;
366         bool use_obmat = false;
367         int i;
368
369         if (!(activeSnap(t) && (ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID))))
370                 return;
371
372         grid_action = BIG_GEARS;
373         if (t->modifiers & MOD_PRECISION)
374                 grid_action = SMALL_GEARS;
375
376         switch (grid_action) {
377                 case NO_GEARS: grid_size = t->snap_spatial[0]; break;
378                 case BIG_GEARS: grid_size = t->snap_spatial[1]; break;
379                 case SMALL_GEARS: grid_size = t->snap_spatial[2]; break;
380         }
381         /* early exit on unusable grid size */
382         if (grid_size == 0.0f)
383                 return;
384
385         if (t->flag & (T_EDIT | T_POSE)) {
386                 Object *ob = t->obedit ? t->obedit : t->poseobj;
387                 obmat = ob->obmat;
388                 use_obmat = true;
389         }
390
391         for (i = 0, td = t->data; i < t->total; i++, td++) {
392                 float iloc[3], loc[3], tvec[3];
393
394                 if (td->flag & TD_NOACTION)
395                         break;
396
397                 if (td->flag & TD_SKIP)
398                         continue;
399
400                 if ((t->flag & T_PROP_EDIT) && (td->factor == 0.0f))
401                         continue;
402
403                 copy_v3_v3(iloc, td->loc);
404                 if (use_obmat) {
405                         mul_m4_v3(obmat, iloc);
406                 }
407                 else if (t->flag & T_OBJECT) {
408                         BKE_object_eval_transform_all(G.main->eval_ctx, t->scene, td->ob);
409                         copy_v3_v3(iloc, td->ob->obmat[3]);
410                 }
411
412                 mul_v3_v3fl(loc, iloc, 1.0f / grid_size);
413                 loc[0] = roundf(loc[0]);
414                 loc[1] = roundf(loc[1]);
415                 loc[2] = roundf(loc[2]);
416                 mul_v3_fl(loc, grid_size);
417
418                 sub_v3_v3v3(tvec, loc, iloc);
419                 mul_m3_v3(td->smtx, tvec);
420                 add_v3_v3(td->loc, tvec);
421         }
422 }
423
424 void applySnapping(TransInfo *t, float *vec)
425 {
426         /* project is not applied this way */
427         if (t->tsnap.project)
428                 return;
429
430         if (t->tsnap.status & SNAP_FORCED) {
431                 t->tsnap.targetSnap(t);
432
433                 t->tsnap.applySnap(t, vec);
434         }
435         else if (!ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID) && activeSnap(t)) {
436                 double current = PIL_check_seconds_timer();
437
438                 // Time base quirky code to go around findnearest slowness
439                 /* !TODO! add exception for object mode, no need to slow it down then */
440                 if (current - t->tsnap.last >= 0.01) {
441                         t->tsnap.calcSnap(t, vec);
442                         t->tsnap.targetSnap(t);
443
444                         t->tsnap.last = current;
445                 }
446                 if (validSnap(t)) {
447                         t->tsnap.applySnap(t, vec);
448                 }
449         }
450 }
451
452 void resetSnapping(TransInfo *t)
453 {
454         t->tsnap.status = 0;
455         t->tsnap.align = false;
456         t->tsnap.project = 0;
457         t->tsnap.mode = 0;
458         t->tsnap.modeSelect = 0;
459         t->tsnap.target = 0;
460         t->tsnap.last = 0;
461         t->tsnap.applySnap = NULL;
462
463         t->tsnap.snapNormal[0] = 0;
464         t->tsnap.snapNormal[1] = 0;
465         t->tsnap.snapNormal[2] = 0;
466
467         t->tsnap.snapNodeBorder = 0;
468 }
469
470 bool usingSnappingNormal(TransInfo *t)
471 {
472         return t->tsnap.align;
473 }
474
475 bool validSnappingNormal(TransInfo *t)
476 {
477         if (validSnap(t)) {
478                 if (!is_zero_v3(t->tsnap.snapNormal)) {
479                         return true;
480                 }
481         }
482
483         return false;
484 }
485
486 static bool bm_edge_is_snap_target(BMEdge *e, void *UNUSED(user_data))
487 {
488         if (BM_elem_flag_test(e, BM_ELEM_SELECT | BM_ELEM_HIDDEN) ||
489             BM_elem_flag_test(e->v1, BM_ELEM_SELECT) ||
490             BM_elem_flag_test(e->v2, BM_ELEM_SELECT))
491         {
492                 return false;
493         }
494
495         return true;
496 }
497
498 static bool bm_face_is_snap_target(BMFace *f, void *UNUSED(user_data))
499 {
500         if (BM_elem_flag_test(f, BM_ELEM_SELECT | BM_ELEM_HIDDEN)) {
501                 return false;
502         }
503
504         BMLoop *l_iter, *l_first;
505         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
506         do {
507                 if (BM_elem_flag_test(l_iter->v, BM_ELEM_SELECT)) {
508                         return false;
509                 }
510         } while ((l_iter = l_iter->next) != l_first);
511
512         return true;
513 }
514
515 static void initSnappingMode(TransInfo *t)
516 {
517         ToolSettings *ts = t->settings;
518         Object *obedit = t->obedit;
519         Scene *scene = t->scene;
520         Base *base_act = scene->basact;
521
522         if (t->spacetype == SPACE_NODE) {
523                 /* force project off when not supported */
524                 t->tsnap.project = 0;
525
526                 t->tsnap.mode = ts->snap_node_mode;
527         }
528         else if (t->spacetype == SPACE_IMAGE) {
529                 /* force project off when not supported */
530                 t->tsnap.project = 0;
531
532                 t->tsnap.mode = ts->snap_uv_mode;
533         }
534         else {
535                 /* force project off when not supported */
536                 if (ts->snap_mode != SCE_SNAP_MODE_FACE)
537                         t->tsnap.project = 0;
538
539                 t->tsnap.mode = ts->snap_mode;
540         }
541
542         if ((t->spacetype == SPACE_VIEW3D || t->spacetype == SPACE_IMAGE) &&  /* Only 3D view or UV */
543             (t->flag & T_CAMERA) == 0)  /* Not with camera selected in camera view */
544         {
545                 setSnappingCallback(t);
546
547                 /* Edit mode */
548                 if (t->tsnap.applySnap != NULL && // A snapping function actually exist
549                     (obedit != NULL && ELEM(obedit->type, OB_MESH, OB_ARMATURE, OB_CURVE, OB_LATTICE, OB_MBALL)) ) // Temporary limited to edit mode meshes, armature, curves, mballs
550                 {
551                         /* Exclude editmesh if using proportional edit */
552                         if ((obedit->type == OB_MESH) && (t->flag & T_PROP_EDIT)) {
553                                 t->tsnap.modeSelect = SNAP_NOT_ACTIVE;
554                         }
555                         else {
556                                 t->tsnap.modeSelect = t->tsnap.snap_self ? SNAP_ALL : SNAP_NOT_ACTIVE;
557                         }
558                 }
559                 /* Particles edit mode*/
560                 else if (t->tsnap.applySnap != NULL && // A snapping function actually exist
561                          (obedit == NULL && base_act && base_act->object && base_act->object->mode & OB_MODE_PARTICLE_EDIT))
562                 {
563                         t->tsnap.modeSelect = SNAP_ALL;
564                 }
565                 /* Object mode */
566                 else if (t->tsnap.applySnap != NULL && // A snapping function actually exist
567                          (obedit == NULL) ) // Object Mode
568                 {
569                         /* In "Edit Strokes" mode, Snap tool can perform snap to selected or active objects (see T49632)
570                          * TODO: perform self snap in gpencil_strokes */
571                         t->tsnap.modeSelect = ((t->options & CTX_GPENCIL_STROKES) != 0) ? SNAP_ALL : SNAP_NOT_SELECTED;
572                 }
573                 else {
574                         /* Grid if snap is not possible */
575                         t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
576                 }
577         }
578         else if (t->spacetype == SPACE_NODE) {
579                 setSnappingCallback(t);
580
581                 if (t->tsnap.applySnap != NULL) {
582                         t->tsnap.modeSelect = SNAP_NOT_SELECTED;
583                 }
584                 else {
585                         /* Grid if snap is not possible */
586                         t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
587                 }
588         }
589         else if (t->spacetype == SPACE_SEQ) {
590                 /* We do our own snapping currently, so nothing here */
591                 t->tsnap.mode = SCE_SNAP_MODE_GRID;  /* Dummy, should we rather add a NOP mode? */
592         }
593         else {
594                 /* Always grid outside of 3D view */
595                 t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
596         }
597
598         if (t->spacetype == SPACE_VIEW3D) {
599                 if (t->tsnap.object_context == NULL) {
600                         t->tsnap.object_context = ED_transform_snap_object_context_create_view3d(
601                                 G.main, t->scene, 0,
602                                 t->ar, t->view);
603
604                         ED_transform_snap_object_context_set_editmesh_callbacks(
605                                 t->tsnap.object_context,
606                                 (bool (*)(BMVert *, void *))BM_elem_cb_check_hflag_disabled,
607                                 bm_edge_is_snap_target,
608                                 bm_face_is_snap_target,
609                                 SET_UINT_IN_POINTER((BM_ELEM_SELECT | BM_ELEM_HIDDEN)));
610                 }
611         }
612 }
613
614 void initSnapping(TransInfo *t, wmOperator *op)
615 {
616         ToolSettings *ts = t->settings;
617         short snap_target = t->settings->snap_target;
618
619         resetSnapping(t);
620
621         /* if snap property exists */
622         if (op && RNA_struct_find_property(op->ptr, "snap") && RNA_struct_property_is_set(op->ptr, "snap")) {
623                 if (RNA_boolean_get(op->ptr, "snap")) {
624                         t->modifiers |= MOD_SNAP;
625
626                         if (RNA_struct_property_is_set(op->ptr, "snap_target")) {
627                                 snap_target = RNA_enum_get(op->ptr, "snap_target");
628                         }
629
630                         if (RNA_struct_property_is_set(op->ptr, "snap_point")) {
631                                 RNA_float_get_array(op->ptr, "snap_point", t->tsnap.snapPoint);
632                                 t->tsnap.status |= SNAP_FORCED | POINT_INIT;
633                         }
634
635                         /* snap align only defined in specific cases */
636                         if (RNA_struct_find_property(op->ptr, "snap_align")) {
637                                 t->tsnap.align = RNA_boolean_get(op->ptr, "snap_align");
638                                 RNA_float_get_array(op->ptr, "snap_normal", t->tsnap.snapNormal);
639                                 normalize_v3(t->tsnap.snapNormal);
640                         }
641
642                         if (RNA_struct_find_property(op->ptr, "use_snap_project")) {
643                                 t->tsnap.project = RNA_boolean_get(op->ptr, "use_snap_project");
644                         }
645
646                         if (RNA_struct_find_property(op->ptr, "use_snap_self")) {
647                                 t->tsnap.snap_self = RNA_boolean_get(op->ptr, "use_snap_self");
648                         }
649                 }
650         }
651         /* use scene defaults only when transform is modal */
652         else if (t->flag & T_MODAL) {
653                 if (ELEM(t->spacetype, SPACE_VIEW3D, SPACE_IMAGE, SPACE_NODE)) {
654                         if (ts->snap_flag & SCE_SNAP) {
655                                 t->modifiers |= MOD_SNAP;
656                         }
657
658                         t->tsnap.align = ((t->settings->snap_flag & SCE_SNAP_ROTATE) != 0);
659                         t->tsnap.project = ((t->settings->snap_flag & SCE_SNAP_PROJECT) != 0);
660                         t->tsnap.snap_self = !((t->settings->snap_flag & SCE_SNAP_NO_SELF) != 0);
661                         t->tsnap.peel = ((t->settings->snap_flag & SCE_SNAP_PROJECT) != 0);
662                 }
663
664                 /* for now only 3d view (others can be added if we want) */
665                 if (t->spacetype == SPACE_VIEW3D) {
666                         t->tsnap.snap_spatial_grid = ((t->settings->snap_flag & SCE_SNAP_ABS_GRID) != 0);
667                 }
668         }
669
670         t->tsnap.target = snap_target;
671
672         initSnappingMode(t);
673 }
674
675 void freeSnapping(TransInfo *t)
676 {
677         if (t->tsnap.object_context) {
678                 ED_transform_snap_object_context_destroy(t->tsnap.object_context);
679                 t->tsnap.object_context = NULL;
680         }
681 }
682
683 static void setSnappingCallback(TransInfo *t)
684 {
685         t->tsnap.calcSnap = CalcSnapGeometry;
686
687         switch (t->tsnap.target) {
688                 case SCE_SNAP_TARGET_CLOSEST:
689                         t->tsnap.targetSnap = TargetSnapClosest;
690                         break;
691                 case SCE_SNAP_TARGET_CENTER:
692                         t->tsnap.targetSnap = TargetSnapCenter;
693                         break;
694                 case SCE_SNAP_TARGET_MEDIAN:
695                         t->tsnap.targetSnap = TargetSnapMedian;
696                         break;
697                 case SCE_SNAP_TARGET_ACTIVE:
698                         t->tsnap.targetSnap = TargetSnapActive;
699                         break;
700
701         }
702
703         switch (t->mode) {
704                 case TFM_TRANSLATION:
705                         t->tsnap.applySnap = ApplySnapTranslation;
706                         t->tsnap.distance = TranslationBetween;
707                         break;
708                 case TFM_ROTATION:
709                         t->tsnap.applySnap = ApplySnapRotation;
710                         t->tsnap.distance = RotationBetween;
711
712                         // Can't do TARGET_CENTER with rotation, use TARGET_MEDIAN instead
713                         if (t->tsnap.target == SCE_SNAP_TARGET_CENTER) {
714                                 t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
715                                 t->tsnap.targetSnap = TargetSnapMedian;
716                         }
717                         break;
718                 case TFM_RESIZE:
719                         t->tsnap.applySnap = ApplySnapResize;
720                         t->tsnap.distance = ResizeBetween;
721
722                         // Can't do TARGET_CENTER with resize, use TARGET_MEDIAN instead
723                         if (t->tsnap.target == SCE_SNAP_TARGET_CENTER) {
724                                 t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
725                                 t->tsnap.targetSnap = TargetSnapMedian;
726                         }
727                         break;
728                 default:
729                         t->tsnap.applySnap = NULL;
730                         break;
731         }
732 }
733
734 void addSnapPoint(TransInfo *t)
735 {
736         /* Currently only 3D viewport works for snapping points. */
737         if (t->tsnap.status & POINT_INIT && t->spacetype == SPACE_VIEW3D) {
738                 TransSnapPoint *p = MEM_callocN(sizeof(TransSnapPoint), "SnapPoint");
739
740                 t->tsnap.selectedPoint = p;
741
742                 copy_v3_v3(p->co, t->tsnap.snapPoint);
743
744                 BLI_addtail(&t->tsnap.points, p);
745
746                 t->tsnap.status |= MULTI_POINTS;
747         }
748 }
749
750 eRedrawFlag updateSelectedSnapPoint(TransInfo *t)
751 {
752         eRedrawFlag status = TREDRAW_NOTHING;
753
754         if (t->tsnap.status & MULTI_POINTS) {
755                 TransSnapPoint *p, *closest_p = NULL;
756                 float dist_min_sq = TRANSFORM_SNAP_MAX_PX;
757                 const float mval_fl[2] = {t->mval[0], t->mval[1]};
758                 float screen_loc[2];
759
760                 for (p = t->tsnap.points.first; p; p = p->next) {
761                         float dist_sq;
762
763                         if (ED_view3d_project_float_global(t->ar, p->co, screen_loc, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
764                                 continue;
765                         }
766
767                         dist_sq = len_squared_v2v2(mval_fl, screen_loc);
768
769                         if (dist_sq < dist_min_sq) {
770                                 closest_p = p;
771                                 dist_min_sq = dist_sq;
772                         }
773                 }
774
775                 if (closest_p) {
776                         if (t->tsnap.selectedPoint != closest_p) {
777                                 status = TREDRAW_HARD;
778                         }
779
780                         t->tsnap.selectedPoint = closest_p;
781                 }
782         }
783
784         return status;
785 }
786
787 void removeSnapPoint(TransInfo *t)
788 {
789         if (t->tsnap.status & MULTI_POINTS) {
790                 updateSelectedSnapPoint(t);
791
792                 if (t->tsnap.selectedPoint) {
793                         BLI_freelinkN(&t->tsnap.points, t->tsnap.selectedPoint);
794
795                         if (BLI_listbase_is_empty(&t->tsnap.points)) {
796                                 t->tsnap.status &= ~MULTI_POINTS;
797                         }
798
799                         t->tsnap.selectedPoint = NULL;
800                 }
801
802         }
803 }
804
805 void getSnapPoint(TransInfo *t, float vec[3])
806 {
807         if (t->tsnap.points.first) {
808                 TransSnapPoint *p;
809                 int total = 0;
810
811                 vec[0] = vec[1] = vec[2] = 0;
812
813                 for (p = t->tsnap.points.first; p; p = p->next, total++) {
814                         add_v3_v3(vec, p->co);
815                 }
816
817                 if (t->tsnap.status & POINT_INIT) {
818                         add_v3_v3(vec, t->tsnap.snapPoint);
819                         total++;
820                 }
821
822                 mul_v3_fl(vec, 1.0f / total);
823         }
824         else {
825                 copy_v3_v3(vec, t->tsnap.snapPoint);
826         }
827 }
828
829 /********************** APPLY **************************/
830
831 static void ApplySnapTranslation(TransInfo *t, float vec[3])
832 {
833         float point[3];
834         getSnapPoint(t, point);
835
836         if (t->spacetype == SPACE_NODE) {
837                 char border = t->tsnap.snapNodeBorder;
838                 if (border & (NODE_LEFT | NODE_RIGHT))
839                         vec[0] = point[0] - t->tsnap.snapTarget[0];
840                 if (border & (NODE_BOTTOM | NODE_TOP))
841                         vec[1] = point[1] - t->tsnap.snapTarget[1];
842         }
843         else {
844                 if (t->spacetype == SPACE_VIEW3D) {
845                         if (t->options & CTX_PAINT_CURVE) {
846                                 if (ED_view3d_project_float_global(t->ar, point, point, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
847                                         zero_v3(point);  /* no good answer here... */
848                                 }
849                         }
850                 }
851
852                 sub_v3_v3v3(vec, point, t->tsnap.snapTarget);
853         }
854 }
855
856 static void ApplySnapRotation(TransInfo *t, float *value)
857 {
858         float point[3];
859         getSnapPoint(t, point);
860
861         float dist = RotationBetween(t, t->tsnap.snapTarget, point);
862         *value = dist;
863 }
864
865 static void ApplySnapResize(TransInfo *t, float vec[3])
866 {
867         float point[3];
868         getSnapPoint(t, point);
869
870         float dist = ResizeBetween(t, t->tsnap.snapTarget, point);
871         copy_v3_fl(vec, dist);
872 }
873
874 /********************** DISTANCE **************************/
875
876 static float TranslationBetween(TransInfo *UNUSED(t), const float p1[3], const float p2[3])
877 {
878         return len_squared_v3v3(p1, p2);
879 }
880
881 static float RotationBetween(TransInfo *t, const float p1[3], const float p2[3])
882 {
883         float angle, start[3], end[3];
884
885         sub_v3_v3v3(start, p1, t->center_global);
886         sub_v3_v3v3(end,   p2, t->center_global);
887
888         // Angle around a constraint axis (error prone, will need debug)
889         if (t->con.applyRot != NULL && (t->con.mode & CON_APPLY)) {
890                 float axis[3], tmp[3];
891
892                 t->con.applyRot(t, NULL, axis, NULL);
893
894                 project_v3_v3v3(tmp, end, axis);
895                 sub_v3_v3v3(end, end, tmp);
896
897                 project_v3_v3v3(tmp, start, axis);
898                 sub_v3_v3v3(start, start, tmp);
899
900                 normalize_v3(end);
901                 normalize_v3(start);
902
903                 cross_v3_v3v3(tmp, start, end);
904
905                 if (dot_v3v3(tmp, axis) < 0.0f)
906                         angle = -acosf(dot_v3v3(start, end));
907                 else
908                         angle = acosf(dot_v3v3(start, end));
909         }
910         else {
911                 float mtx[3][3];
912
913                 copy_m3_m4(mtx, t->viewmat);
914
915                 mul_m3_v3(mtx, end);
916                 mul_m3_v3(mtx, start);
917
918                 angle = atan2f(start[1], start[0]) - atan2f(end[1], end[0]);
919         }
920
921         if (angle > (float)M_PI) {
922                 angle = angle - 2 * (float)M_PI;
923         }
924         else if (angle < -((float)M_PI)) {
925                 angle = 2.0f * (float)M_PI + angle;
926         }
927
928         return angle;
929 }
930
931 static float ResizeBetween(TransInfo *t, const float p1[3], const float p2[3])
932 {
933         float d1[3], d2[3], len_d1;
934
935         sub_v3_v3v3(d1, p1, t->center_global);
936         sub_v3_v3v3(d2, p2, t->center_global);
937
938         if (t->con.applyRot != NULL && (t->con.mode & CON_APPLY)) {
939                 mul_m3_v3(t->con.pmtx, d1);
940                 mul_m3_v3(t->con.pmtx, d2);
941         }
942
943         project_v3_v3v3(d1, d1, d2);
944
945         len_d1 = len_v3(d1);
946
947         /* Use 'invalid' dist when `center == p1` (after projecting),
948          * in this case scale will _never_ move the point in relation to the center,
949          * so it makes no sense to take it into account when scaling. see: T46503 */
950         return len_d1 != 0.0f ? len_v3(d2) / len_d1 : TRANSFORM_DIST_INVALID;
951 }
952
953 /********************** CALC **************************/
954
955 static void UNUSED_FUNCTION(CalcSnapGrid) (TransInfo *t, float *UNUSED(vec))
956 {
957         snapGridIncrementAction(t, t->tsnap.snapPoint, BIG_GEARS);
958 }
959
960 static void CalcSnapGeometry(TransInfo *t, float *UNUSED(vec))
961 {
962         if (t->spacetype == SPACE_VIEW3D) {
963                 float loc[3];
964                 float no[3];
965                 float mval[2];
966                 bool found = false;
967                 float dist_px = SNAP_MIN_DISTANCE; // Use a user defined value here
968
969                 mval[0] = t->mval[0];
970                 mval[1] = t->mval[1];
971
972                 if (t->tsnap.mode == SCE_SNAP_MODE_VOLUME) {
973                         found = peelObjectsTransform(
974                                 t, mval,
975                                 (t->settings->snap_flag & SCE_SNAP_PEEL_OBJECT) != 0,
976                                 loc, no, NULL);
977                 }
978                 else {
979                         zero_v3(no);  /* objects won't set this */
980                         found = snapObjectsTransform(
981                                 t, mval, &dist_px,
982                                 loc, no);
983                 }
984
985                 if (found == true) {
986                         copy_v3_v3(t->tsnap.snapPoint, loc);
987                         copy_v3_v3(t->tsnap.snapNormal, no);
988
989                         t->tsnap.status |=  POINT_INIT;
990                 }
991                 else {
992                         t->tsnap.status &= ~POINT_INIT;
993                 }
994         }
995         else if (t->spacetype == SPACE_IMAGE && t->obedit != NULL && t->obedit->type == OB_MESH) {
996                 /* same as above but for UV's */
997                 Image *ima = ED_space_image(t->sa->spacedata.first);
998                 float co[2];
999
1000                 UI_view2d_region_to_view(&t->ar->v2d, t->mval[0], t->mval[1], &co[0], &co[1]);
1001
1002                 if (ED_uvedit_nearest_uv(t->scene, t->obedit, ima, co, t->tsnap.snapPoint)) {
1003                         t->tsnap.snapPoint[0] *= t->aspect[0];
1004                         t->tsnap.snapPoint[1] *= t->aspect[1];
1005
1006                         t->tsnap.status |=  POINT_INIT;
1007                 }
1008                 else {
1009                         t->tsnap.status &= ~POINT_INIT;
1010                 }
1011         }
1012         else if (t->spacetype == SPACE_NODE) {
1013                 float loc[2];
1014                 float dist_px = SNAP_MIN_DISTANCE; // Use a user defined value here
1015                 char node_border;
1016
1017                 if (snapNodesTransform(t, t->mval, loc, &dist_px, &node_border)) {
1018                         copy_v2_v2(t->tsnap.snapPoint, loc);
1019                         t->tsnap.snapNodeBorder = node_border;
1020
1021                         t->tsnap.status |=  POINT_INIT;
1022                 }
1023                 else {
1024                         t->tsnap.status &= ~POINT_INIT;
1025                 }
1026         }
1027 }
1028
1029 /********************** TARGET **************************/
1030
1031 static void TargetSnapOffset(TransInfo *t, TransData *td)
1032 {
1033         if (t->spacetype == SPACE_NODE && td != NULL) {
1034                 bNode *node = td->extra;
1035                 char border = t->tsnap.snapNodeBorder;
1036                 float width  = BLI_rctf_size_x(&node->totr);
1037                 float height = BLI_rctf_size_y(&node->totr);
1038
1039 #ifdef USE_NODE_CENTER
1040                 if (border & NODE_LEFT)
1041                         t->tsnap.snapTarget[0] -= 0.5f * width;
1042                 if (border & NODE_RIGHT)
1043                         t->tsnap.snapTarget[0] += 0.5f * width;
1044                 if (border & NODE_BOTTOM)
1045                         t->tsnap.snapTarget[1] -= 0.5f * height;
1046                 if (border & NODE_TOP)
1047                         t->tsnap.snapTarget[1] += 0.5f * height;
1048 #else
1049                 if (border & NODE_LEFT)
1050                         t->tsnap.snapTarget[0] -= 0.0f;
1051                 if (border & NODE_RIGHT)
1052                         t->tsnap.snapTarget[0] += width;
1053                 if (border & NODE_BOTTOM)
1054                         t->tsnap.snapTarget[1] -= height;
1055                 if (border & NODE_TOP)
1056                         t->tsnap.snapTarget[1] += 0.0f;
1057 #endif
1058         }
1059 }
1060
1061 static void TargetSnapCenter(TransInfo *t)
1062 {
1063         /* Only need to calculate once */
1064         if ((t->tsnap.status & TARGET_INIT) == 0) {
1065                 copy_v3_v3(t->tsnap.snapTarget, t->center_global);
1066                 TargetSnapOffset(t, NULL);
1067
1068                 t->tsnap.status |= TARGET_INIT;
1069         }
1070 }
1071
1072 static void TargetSnapActive(TransInfo *t)
1073 {
1074         /* Only need to calculate once */
1075         if ((t->tsnap.status & TARGET_INIT) == 0) {
1076                 if (calculateCenterActive(t, true, t->tsnap.snapTarget)) {
1077                         if (t->flag & (T_EDIT | T_POSE)) {
1078                                 Object *ob = t->obedit ? t->obedit : t->poseobj;
1079                                 mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
1080                         }
1081
1082                         TargetSnapOffset(t, NULL);
1083
1084                         t->tsnap.status |= TARGET_INIT;
1085                 }
1086                 /* No active, default to median */
1087                 else {
1088                         t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
1089                         t->tsnap.targetSnap = TargetSnapMedian;
1090                         TargetSnapMedian(t);
1091                 }
1092         }
1093 }
1094
1095 static void TargetSnapMedian(TransInfo *t)
1096 {
1097         // Only need to calculate once
1098         if ((t->tsnap.status & TARGET_INIT) == 0) {
1099                 TransData *td = NULL;
1100                 int i;
1101
1102                 t->tsnap.snapTarget[0] = 0;
1103                 t->tsnap.snapTarget[1] = 0;
1104                 t->tsnap.snapTarget[2] = 0;
1105
1106                 for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1107                         add_v3_v3(t->tsnap.snapTarget, td->center);
1108                 }
1109
1110                 mul_v3_fl(t->tsnap.snapTarget, 1.0 / i);
1111
1112                 if (t->flag & (T_EDIT | T_POSE)) {
1113                         Object *ob = t->obedit ? t->obedit : t->poseobj;
1114                         mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
1115                 }
1116
1117                 TargetSnapOffset(t, NULL);
1118
1119                 t->tsnap.status |= TARGET_INIT;
1120         }
1121 }
1122
1123 static void TargetSnapClosest(TransInfo *t)
1124 {
1125         // Only valid if a snap point has been selected
1126         if (t->tsnap.status & POINT_INIT) {
1127                 float dist_closest = 0.0f;
1128                 TransData *closest = NULL, *td = NULL;
1129
1130                 /* Object mode */
1131                 if (t->flag & T_OBJECT) {
1132                         int i;
1133                         for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1134                                 struct BoundBox *bb = BKE_object_boundbox_get(td->ob);
1135
1136                                 /* use boundbox if possible */
1137                                 if (bb) {
1138                                         int j;
1139
1140                                         for (j = 0; j < 8; j++) {
1141                                                 float loc[3];
1142                                                 float dist;
1143
1144                                                 copy_v3_v3(loc, bb->vec[j]);
1145                                                 mul_m4_v3(td->ext->obmat, loc);
1146
1147                                                 dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1148
1149                                                 if ((dist != TRANSFORM_DIST_INVALID) &&
1150                                                     (closest == NULL || fabsf(dist) < fabsf(dist_closest)))
1151                                                 {
1152                                                         copy_v3_v3(t->tsnap.snapTarget, loc);
1153                                                         closest = td;
1154                                                         dist_closest = dist;
1155                                                 }
1156                                         }
1157                                 }
1158                                 /* use element center otherwise */
1159                                 else {
1160                                         float loc[3];
1161                                         float dist;
1162
1163                                         copy_v3_v3(loc, td->center);
1164
1165                                         dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1166
1167                                         if ((dist != TRANSFORM_DIST_INVALID) &&
1168                                             (closest == NULL || fabsf(dist) < fabsf(dist_closest)))
1169                                         {
1170                                                 copy_v3_v3(t->tsnap.snapTarget, loc);
1171                                                 closest = td;
1172                                         }
1173                                 }
1174                         }
1175                 }
1176                 else {
1177                         int i;
1178                         for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1179                                 float loc[3];
1180                                 float dist;
1181
1182                                 copy_v3_v3(loc, td->center);
1183
1184                                 if (t->flag & (T_EDIT | T_POSE)) {
1185                                         Object *ob = t->obedit ? t->obedit : t->poseobj;
1186                                         mul_m4_v3(ob->obmat, loc);
1187                                 }
1188
1189                                 dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1190
1191                                 if ((dist != TRANSFORM_DIST_INVALID) &&
1192                                     (closest == NULL || fabsf(dist) < fabsf(dist_closest)))
1193                                 {
1194                                         copy_v3_v3(t->tsnap.snapTarget, loc);
1195                                         closest = td;
1196                                         dist_closest = dist;
1197                                 }
1198                         }
1199                 }
1200
1201                 TargetSnapOffset(t, closest);
1202
1203                 t->tsnap.status |= TARGET_INIT;
1204         }
1205 }
1206
1207 bool snapObjectsTransform(
1208         TransInfo *t, const float mval[2],
1209         float *dist_px,
1210         float r_loc[3], float r_no[3])
1211 {
1212         return ED_transform_snap_object_project_view3d_ex(
1213                 t->tsnap.object_context,
1214                 t->scene->toolsettings->snap_mode,
1215                 &(const struct SnapObjectParams){
1216                     .snap_select = t->tsnap.modeSelect,
1217                     .use_object_edit_cage = (t->flag & T_EDIT) != 0,
1218                 },
1219                 mval, dist_px, NULL,
1220                 r_loc, r_no, NULL,
1221                 NULL, NULL);
1222 }
1223
1224
1225 /******************** PEELING *********************************/
1226
1227 bool peelObjectsSnapContext(
1228         SnapObjectContext *sctx,
1229         const float mval[2],
1230         const struct SnapObjectParams *params,
1231         const bool use_peel_object,
1232         /* return args */
1233         float r_loc[3], float r_no[3], float *r_thickness)
1234 {
1235         ListBase depths_peel = {0};
1236         ED_transform_snap_object_project_all_view3d_ex(
1237                 sctx,
1238                 params,
1239                 mval, -1.0f, false,
1240                 &depths_peel);
1241
1242         if (!BLI_listbase_is_empty(&depths_peel)) {
1243                 /* At the moment we only use the hits of the first object */
1244                 struct SnapObjectHitDepth *hit_min = depths_peel.first;
1245                 for (struct SnapObjectHitDepth *iter = hit_min->next; iter; iter = iter->next) {
1246                         if (iter->depth < hit_min->depth) {
1247                                 hit_min = iter;
1248                         }
1249                 }
1250                 struct SnapObjectHitDepth *hit_max = NULL;
1251
1252                 if (use_peel_object) {
1253                         /* if peeling objects, take the first and last from each object */
1254                         hit_max = hit_min;
1255                         for (struct SnapObjectHitDepth *iter = depths_peel.first; iter; iter = iter->next) {
1256                                 if ((iter->depth > hit_max->depth) && (iter->ob_uuid == hit_min->ob_uuid)) {
1257                                         hit_max = iter;
1258                                 }
1259                         }
1260                 }
1261                 else {
1262                         /* otherwise, pair first with second and so on */
1263                         for (struct SnapObjectHitDepth *iter = depths_peel.first; iter; iter = iter->next) {
1264                                 if ((iter != hit_min) && (iter->ob_uuid == hit_min->ob_uuid)) {
1265                                         if (hit_max == NULL) {
1266                                                 hit_max = iter;
1267                                         }
1268                                         else if (iter->depth < hit_max->depth) {
1269                                                 hit_max = iter;
1270                                         }
1271                                 }
1272                         }
1273                         /* in this case has only one hit. treat as raycast */
1274                         if (hit_max == NULL) {
1275                                 hit_max = hit_min;
1276                         }
1277                 }
1278
1279                 mid_v3_v3v3(r_loc, hit_min->co, hit_max->co);
1280
1281                 if (r_thickness) {
1282                         *r_thickness = hit_max->depth - hit_min->depth;
1283                 }
1284
1285                 /* XXX, is there a correct normal in this case ???, for now just z up */
1286                 r_no[0] = 0.0;
1287                 r_no[1] = 0.0;
1288                 r_no[2] = 1.0;
1289
1290                 BLI_freelistN(&depths_peel);
1291                 return true;
1292         }
1293         return false;
1294 }
1295
1296 bool peelObjectsTransform(
1297         TransInfo *t,
1298         const float mval[2],
1299         const bool use_peel_object,
1300         /* return args */
1301         float r_loc[3], float r_no[3], float *r_thickness)
1302 {
1303         return peelObjectsSnapContext(
1304                 t->tsnap.object_context,
1305                 mval,
1306                 &(const struct SnapObjectParams){
1307                     .snap_select = t->tsnap.modeSelect,
1308                     .use_object_edit_cage = (t->flag & T_EDIT) != 0,
1309                 },
1310                 use_peel_object,
1311                 r_loc, r_no, r_thickness);
1312 }
1313
1314 /******************** NODES ***********************************/
1315
1316 static bool snapNodeTest(View2D *v2d, bNode *node, eSnapSelect snap_select)
1317 {
1318         /* node is use for snapping only if a) snap mode matches and b) node is inside the view */
1319         return ((snap_select == SNAP_NOT_SELECTED && !(node->flag & NODE_SELECT)) ||
1320                 (snap_select == SNAP_ALL          && !(node->flag & NODE_ACTIVE))) &&
1321                 (node->totr.xmin < v2d->cur.xmax && node->totr.xmax > v2d->cur.xmin &&
1322                  node->totr.ymin < v2d->cur.ymax && node->totr.ymax > v2d->cur.ymin);
1323 }
1324
1325 static NodeBorder snapNodeBorder(int snap_node_mode)
1326 {
1327         switch (snap_node_mode) {
1328                 case SCE_SNAP_MODE_NODE_X:
1329                         return NODE_LEFT | NODE_RIGHT;
1330                 case SCE_SNAP_MODE_NODE_Y:
1331                         return NODE_TOP | NODE_BOTTOM;
1332                 case SCE_SNAP_MODE_NODE_XY:
1333                         return NODE_LEFT | NODE_RIGHT | NODE_TOP | NODE_BOTTOM;
1334         }
1335         return 0;
1336 }
1337
1338 static bool snapNode(
1339         ToolSettings *ts, SpaceNode *UNUSED(snode), ARegion *ar, bNode *node, const int mval[2],
1340         float r_loc[2], float *r_dist_px, char *r_node_border)
1341 {
1342         View2D *v2d = &ar->v2d;
1343         NodeBorder border = snapNodeBorder(ts->snap_node_mode);
1344         bool retval = false;
1345         rcti totr;
1346         int new_dist;
1347
1348         UI_view2d_view_to_region_rcti(v2d, &node->totr, &totr);
1349
1350         if (border & NODE_LEFT) {
1351                 new_dist = abs(totr.xmin - mval[0]);
1352                 if (new_dist < *r_dist_px) {
1353                         UI_view2d_region_to_view(v2d, totr.xmin, mval[1], &r_loc[0], &r_loc[1]);
1354                         *r_dist_px = new_dist;
1355                         *r_node_border = NODE_LEFT;
1356                         retval = true;
1357                 }
1358         }
1359
1360         if (border & NODE_RIGHT) {
1361                 new_dist = abs(totr.xmax - mval[0]);
1362                 if (new_dist < *r_dist_px) {
1363                         UI_view2d_region_to_view(v2d, totr.xmax, mval[1], &r_loc[0], &r_loc[1]);
1364                         *r_dist_px = new_dist;
1365                         *r_node_border = NODE_RIGHT;
1366                         retval = true;
1367                 }
1368         }
1369
1370         if (border & NODE_BOTTOM) {
1371                 new_dist = abs(totr.ymin - mval[1]);
1372                 if (new_dist < *r_dist_px) {
1373                         UI_view2d_region_to_view(v2d, mval[0], totr.ymin, &r_loc[0], &r_loc[1]);
1374                         *r_dist_px = new_dist;
1375                         *r_node_border = NODE_BOTTOM;
1376                         retval = true;
1377                 }
1378         }
1379
1380         if (border & NODE_TOP) {
1381                 new_dist = abs(totr.ymax - mval[1]);
1382                 if (new_dist < *r_dist_px) {
1383                         UI_view2d_region_to_view(v2d, mval[0], totr.ymax, &r_loc[0], &r_loc[1]);
1384                         *r_dist_px = new_dist;
1385                         *r_node_border = NODE_TOP;
1386                         retval = true;
1387                 }
1388         }
1389
1390         return retval;
1391 }
1392
1393 static bool snapNodes(
1394         ToolSettings *ts, SpaceNode *snode, ARegion *ar,
1395         const int mval[2], eSnapSelect snap_select,
1396         float r_loc[2], float *r_dist_px, char *r_node_border)
1397 {
1398         bNodeTree *ntree = snode->edittree;
1399         bNode *node;
1400         bool retval = false;
1401
1402         *r_node_border = 0;
1403
1404         for (node = ntree->nodes.first; node; node = node->next) {
1405                 if (snapNodeTest(&ar->v2d, node, snap_select)) {
1406                         retval |= snapNode(ts, snode, ar, node, mval, r_loc, r_dist_px, r_node_border);
1407                 }
1408         }
1409
1410         return retval;
1411 }
1412
1413 bool snapNodesTransform(
1414         TransInfo *t, const int mval[2],
1415         float r_loc[2], float *r_dist_px, char *r_node_border)
1416 {
1417         return snapNodes(
1418                 t->settings, t->sa->spacedata.first, t->ar, mval, t->tsnap.modeSelect,
1419                 r_loc, r_dist_px, r_node_border);
1420 }
1421
1422 /*================================================================*/
1423
1424 static void applyGridIncrement(TransInfo *t, float *val, int max_index, const float fac[3], GearsType action);
1425
1426
1427 void snapGridIncrementAction(TransInfo *t, float *val, GearsType action)
1428 {
1429         float fac[3];
1430
1431         fac[NO_GEARS]    = t->snap[0];
1432         fac[BIG_GEARS]   = t->snap[1];
1433         fac[SMALL_GEARS] = t->snap[2];
1434
1435         applyGridIncrement(t, val, t->idx_max, fac, action);
1436 }
1437
1438
1439 void snapGridIncrement(TransInfo *t, float *val)
1440 {
1441         GearsType action;
1442
1443         /* only do something if using absolute or incremental grid snapping */
1444         if (!ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID))
1445                 return;
1446
1447         action = activeSnap(t) ? BIG_GEARS : NO_GEARS;
1448
1449         if (action == BIG_GEARS && (t->modifiers & MOD_PRECISION)) {
1450                 action = SMALL_GEARS;
1451         }
1452
1453         snapGridIncrementAction(t, val, action);
1454 }
1455
1456 void snapSequenceBounds(TransInfo *t, const int mval[2])
1457 {
1458         float xmouse, ymouse;
1459         int frame;
1460         int mframe;
1461         TransSeq *ts = t->custom.type.data;
1462         /* reuse increment, strictly speaking could be another snap mode, but leave as is */
1463         if (!(t->modifiers & MOD_SNAP_INVERT))
1464                 return;
1465
1466         /* convert to frame range */
1467         UI_view2d_region_to_view(&t->ar->v2d, mval[0], mval[1], &xmouse, &ymouse);
1468         mframe = round_fl_to_int(xmouse);
1469         /* now find the closest sequence */
1470         frame = BKE_sequencer_find_next_prev_edit(t->scene, mframe, SEQ_SIDE_BOTH, true, false, true);
1471
1472         if (!ts->snap_left)
1473                 frame = frame - (ts->max - ts->min);
1474
1475         t->values[0] = frame - ts->min;
1476 }
1477
1478 static void applyGridIncrement(TransInfo *t, float *val, int max_index, const float fac[3], GearsType action)
1479 {
1480         float asp_local[3] = {1, 1, 1};
1481         const bool use_aspect = ELEM(t->mode, TFM_TRANSLATION);
1482         const float *asp = use_aspect ? t->aspect : asp_local;
1483         int i;
1484
1485         BLI_assert(ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID));
1486         BLI_assert(max_index <= 2);
1487
1488         /* Early bailing out if no need to snap */
1489         if (fac[action] == 0.0f) {
1490                 return;
1491         }
1492
1493         if (use_aspect) {
1494                 /* custom aspect for fcurve */
1495                 if (t->spacetype == SPACE_IPO) {
1496                         View2D *v2d = &t->ar->v2d;
1497                         View2DGrid *grid;
1498                         SpaceIpo *sipo = t->sa->spacedata.first;
1499                         int unity = V2D_UNIT_VALUES;
1500                         int unitx = (sipo->flag & SIPO_DRAWTIME) ? V2D_UNIT_SECONDS : V2D_UNIT_FRAMESCALE;
1501
1502                         /* grid */
1503                         grid = UI_view2d_grid_calc(t->scene, v2d, unitx, V2D_GRID_NOCLAMP, unity, V2D_GRID_NOCLAMP, t->ar->winx, t->ar->winy);
1504
1505                         UI_view2d_grid_size(grid, &asp_local[0], &asp_local[1]);
1506                         UI_view2d_grid_free(grid);
1507
1508                         asp = asp_local;
1509                 }
1510         }
1511
1512         /* absolute snapping on grid based on global center */
1513         if ((t->tsnap.snap_spatial_grid) && (t->mode == TFM_TRANSLATION)) {
1514                 const float *center_global = t->center_global;
1515
1516                 /* use a fallback for cursor selection,
1517                  * this isn't useful as a global center for absolute grid snapping
1518                  * since its not based on the position of the selection. */
1519                 if (t->around == V3D_AROUND_CURSOR) {
1520                         const TransCenterData *cd = transformCenter_from_type(t, V3D_AROUND_CENTER_MEAN);
1521                         center_global = cd->global;
1522                 }
1523
1524                 for (i = 0; i <= max_index; i++) {
1525                         /* do not let unconstrained axis jump to absolute grid increments */
1526                         if (!(t->con.mode & CON_APPLY) || t->con.mode & (CON_AXIS0 << i)) {
1527                                 const float iter_fac = fac[action] * asp[i];
1528                                 val[i] = iter_fac * roundf((val[i] + center_global[i]) / iter_fac) - center_global[i];
1529                         }
1530                 }
1531         }
1532         else {
1533                 /* relative snapping in fixed increments */
1534                 for (i = 0; i <= max_index; i++) {
1535                         const float iter_fac = fac[action] * asp[i];
1536                         val[i] = iter_fac * roundf(val[i] / iter_fac);
1537                 }
1538         }
1539 }