Merge branch 'master' into blender2.8
[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, SnapSelect 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                                 /* TODO(sergey): Ideally force update is not needed here. */
320                                 td->ob->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
321                                 BKE_object_handle_update(G.main->eval_ctx, t->scene, td->ob);
322                                 copy_v3_v3(iloc, td->ob->obmat[3]);
323                         }
324                         
325                         if (ED_view3d_project_float_global(t->ar, iloc, mval_fl, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
326                                 if (snapObjectsTransform(
327                                         t, mval_fl, t->tsnap.modeSelect, &dist_px,
328                                         loc, no))
329                                 {
330 //                                      if (t->flag & (T_EDIT|T_POSE)) {
331 //                                              mul_m4_v3(imat, loc);
332 //                                      }
333
334                                         sub_v3_v3v3(tvec, loc, iloc);
335
336                                         mul_m3_v3(td->smtx, tvec);
337
338                                         add_v3_v3(td->loc, tvec);
339
340                                         if (t->tsnap.align && (t->flag & T_OBJECT)) {
341                                                 /* handle alignment as well */
342                                                 const float *original_normal;
343                                                 float mat[3][3];
344
345                                                 /* In pose mode, we want to align normals with Y axis of bones... */
346                                                 original_normal = td->axismtx[2];
347
348                                                 rotation_between_vecs_to_mat3(mat, original_normal, no);
349
350                                                 transform_data_ext_rotate(td, mat, true);
351
352                                                 /* TODO support constraints for rotation too? see ElementRotation */
353                                         }
354                                 }
355                         }
356                         
357                         //XXX constraintTransLim(t, td);
358                 }
359         }
360 }
361
362 void applyGridAbsolute(TransInfo *t)
363 {
364         float grid_size = 0.0f;
365         GearsType grid_action;
366         TransData *td;
367         float (*obmat)[4] = NULL;
368         bool use_obmat = false;
369         int i;
370         
371         if (!(activeSnap(t) && (ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID))))
372                 return;
373         
374         grid_action = BIG_GEARS;
375         if (t->modifiers & MOD_PRECISION)
376                 grid_action = SMALL_GEARS;
377         
378         switch (grid_action) {
379                 case NO_GEARS: grid_size = t->snap_spatial[0]; break;
380                 case BIG_GEARS: grid_size = t->snap_spatial[1]; break;
381                 case SMALL_GEARS: grid_size = t->snap_spatial[2]; break;
382         }
383         /* early exit on unusable grid size */
384         if (grid_size == 0.0f)
385                 return;
386         
387         if (t->flag & (T_EDIT | T_POSE)) {
388                 Object *ob = t->obedit ? t->obedit : t->poseobj;
389                 obmat = ob->obmat;
390                 use_obmat = true;
391         }
392         
393         for (i = 0, td = t->data; i < t->total; i++, td++) {
394                 float iloc[3], loc[3], tvec[3];
395                 
396                 if (td->flag & TD_NOACTION)
397                         break;
398                 
399                 if (td->flag & TD_SKIP)
400                         continue;
401                 
402                 if ((t->flag & T_PROP_EDIT) && (td->factor == 0.0f))
403                         continue;
404                 
405                 copy_v3_v3(iloc, td->loc);
406                 if (use_obmat) {
407                         mul_m4_v3(obmat, iloc);
408                 }
409                 else if (t->flag & T_OBJECT) {
410                         td->ob->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
411                         BKE_object_handle_update(G.main->eval_ctx, t->scene, td->ob);
412                         copy_v3_v3(iloc, td->ob->obmat[3]);
413                 }
414                 
415                 mul_v3_v3fl(loc, iloc, 1.0f / grid_size);
416                 loc[0] = roundf(loc[0]);
417                 loc[1] = roundf(loc[1]);
418                 loc[2] = roundf(loc[2]);
419                 mul_v3_fl(loc, grid_size);
420
421                 sub_v3_v3v3(tvec, loc, iloc);
422                 mul_m3_v3(td->smtx, tvec);
423                 add_v3_v3(td->loc, tvec);
424         }
425 }
426
427 void applySnapping(TransInfo *t, float *vec)
428 {
429         /* project is not applied this way */
430         if (t->tsnap.project)
431                 return;
432         
433         if (t->tsnap.status & SNAP_FORCED) {
434                 t->tsnap.targetSnap(t);
435         
436                 t->tsnap.applySnap(t, vec);
437         }
438         else if (!ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID) && activeSnap(t)) {
439                 double current = PIL_check_seconds_timer();
440                 
441                 // Time base quirky code to go around findnearest slowness
442                 /* !TODO! add exception for object mode, no need to slow it down then */
443                 if (current - t->tsnap.last >= 0.01) {
444                         t->tsnap.calcSnap(t, vec);
445                         t->tsnap.targetSnap(t);
446         
447                         t->tsnap.last = current;
448                 }
449                 if (validSnap(t)) {
450                         t->tsnap.applySnap(t, vec);
451                 }
452         }
453 }
454
455 void resetSnapping(TransInfo *t)
456 {
457         t->tsnap.status = 0;
458         t->tsnap.align = false;
459         t->tsnap.project = 0;
460         t->tsnap.mode = 0;
461         t->tsnap.modeSelect = 0;
462         t->tsnap.target = 0;
463         t->tsnap.last = 0;
464         t->tsnap.applySnap = NULL;
465
466         t->tsnap.snapNormal[0] = 0;
467         t->tsnap.snapNormal[1] = 0;
468         t->tsnap.snapNormal[2] = 0;
469         
470         t->tsnap.snapNodeBorder = 0;
471 }
472
473 bool usingSnappingNormal(TransInfo *t)
474 {
475         return t->tsnap.align;
476 }
477
478 bool validSnappingNormal(TransInfo *t)
479 {
480         if (validSnap(t)) {
481                 if (!is_zero_v3(t->tsnap.snapNormal)) {
482                         return true;
483                 }
484         }
485         
486         return false;
487 }
488
489 static bool bm_edge_is_snap_target(BMEdge *e, void *UNUSED(user_data))
490 {
491         if (BM_elem_flag_test(e, BM_ELEM_SELECT | BM_ELEM_HIDDEN) ||
492             BM_elem_flag_test(e->v1, BM_ELEM_SELECT) ||
493             BM_elem_flag_test(e->v2, BM_ELEM_SELECT))
494         {
495                 return false;
496         }
497
498         return true;
499 }
500
501 static bool bm_face_is_snap_target(BMFace *f, void *UNUSED(user_data))
502 {
503         if (BM_elem_flag_test(f, BM_ELEM_SELECT | BM_ELEM_HIDDEN)) {
504                 return false;
505         }
506
507         BMLoop *l_iter, *l_first;
508         l_iter = l_first = BM_FACE_FIRST_LOOP(f);
509         do {
510                 if (BM_elem_flag_test(l_iter->v, BM_ELEM_SELECT)) {
511                         return false;
512                 }
513         } while ((l_iter = l_iter->next) != l_first);
514
515         return true;
516 }
517
518 static void initSnappingMode(TransInfo *t)
519 {
520         ToolSettings *ts = t->settings;
521         Object *obedit = t->obedit;
522
523         if (t->spacetype == SPACE_NODE) {
524                 /* force project off when not supported */
525                 t->tsnap.project = 0;
526                 
527                 t->tsnap.mode = ts->snap_node_mode;
528         }
529         else if (t->spacetype == SPACE_IMAGE) {
530                 /* force project off when not supported */
531                 t->tsnap.project = 0;
532                 
533                 t->tsnap.mode = ts->snap_uv_mode;
534         }
535         else {
536                 /* force project off when not supported */
537                 if (ts->snap_mode != SCE_SNAP_MODE_FACE)
538                         t->tsnap.project = 0;
539                 
540                 t->tsnap.mode = ts->snap_mode;
541         }
542
543         if ((t->spacetype == SPACE_VIEW3D || t->spacetype == SPACE_IMAGE) &&  /* Only 3D view or UV */
544             (t->flag & T_CAMERA) == 0)  /* Not with camera selected in camera view */
545         {
546                 setSnappingCallback(t);
547
548                 /* Edit mode */
549                 if (t->tsnap.applySnap != NULL && // A snapping function actually exist
550                     (obedit != NULL && ELEM(obedit->type, OB_MESH, OB_ARMATURE, OB_CURVE, OB_LATTICE, OB_MBALL)) ) // Temporary limited to edit mode meshes, armature, curves, mballs
551                 {
552                         /* Exclude editmesh if using proportional edit */
553                         if ((obedit->type == OB_MESH) && (t->flag & T_PROP_EDIT)) {
554                                 t->tsnap.modeSelect = SNAP_NOT_OBEDIT;
555                         }
556                         else {
557                                 t->tsnap.modeSelect = t->tsnap.snap_self ? SNAP_ALL : SNAP_NOT_OBEDIT;
558                         }
559                 }
560                 /* Object mode */
561                 else if (t->tsnap.applySnap != NULL && // A snapping function actually exist
562                          (obedit == NULL) ) // Object Mode
563                 {
564                         t->tsnap.modeSelect = SNAP_NOT_SELECTED;
565                 }
566                 else {
567                         /* Grid if snap is not possible */
568                         t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
569                 }
570         }
571         else if (t->spacetype == SPACE_NODE) {
572                 setSnappingCallback(t);
573                 
574                 if (t->tsnap.applySnap != NULL) {
575                         t->tsnap.modeSelect = SNAP_NOT_SELECTED;
576                 }
577                 else {
578                         /* Grid if snap is not possible */
579                         t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
580                 }
581         }
582         else if (t->spacetype == SPACE_SEQ) {
583                 /* We do our own snapping currently, so nothing here */
584                 t->tsnap.mode = SCE_SNAP_MODE_GRID;  /* Dummy, should we rather add a NOP mode? */
585         }
586         else {
587                 /* Always grid outside of 3D view */
588                 t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
589         }
590
591         if (t->spacetype == SPACE_VIEW3D) {
592                 if (t->tsnap.object_context == NULL) {
593                         t->tsnap.object_context = ED_transform_snap_object_context_create_view3d(
594                                         G.main, t->scene, SNAP_OBJECT_USE_CACHE,
595                                         t->ar, t->view);
596
597                         ED_transform_snap_object_context_set_editmesh_callbacks(
598                                         t->tsnap.object_context,
599                                         (bool (*)(BMVert *, void *))BM_elem_cb_check_hflag_disabled,
600                                         bm_edge_is_snap_target,
601                                         bm_face_is_snap_target,
602                                         SET_UINT_IN_POINTER((BM_ELEM_SELECT | BM_ELEM_HIDDEN)));
603                 }
604         }
605 }
606
607 void initSnapping(TransInfo *t, wmOperator *op)
608 {
609         ToolSettings *ts = t->settings;
610         short snap_target = t->settings->snap_target;
611         
612         resetSnapping(t);
613         
614         /* if snap property exists */
615         if (op && RNA_struct_find_property(op->ptr, "snap") && RNA_struct_property_is_set(op->ptr, "snap")) {
616                 if (RNA_boolean_get(op->ptr, "snap")) {
617                         t->modifiers |= MOD_SNAP;
618
619                         if (RNA_struct_property_is_set(op->ptr, "snap_target")) {
620                                 snap_target = RNA_enum_get(op->ptr, "snap_target");
621                         }
622                         
623                         if (RNA_struct_property_is_set(op->ptr, "snap_point")) {
624                                 RNA_float_get_array(op->ptr, "snap_point", t->tsnap.snapPoint);
625                                 t->tsnap.status |= SNAP_FORCED | POINT_INIT;
626                         }
627                         
628                         /* snap align only defined in specific cases */
629                         if (RNA_struct_find_property(op->ptr, "snap_align")) {
630                                 t->tsnap.align = RNA_boolean_get(op->ptr, "snap_align");
631                                 RNA_float_get_array(op->ptr, "snap_normal", t->tsnap.snapNormal);
632                                 normalize_v3(t->tsnap.snapNormal);
633                         }
634
635                         if (RNA_struct_find_property(op->ptr, "use_snap_project")) {
636                                 t->tsnap.project = RNA_boolean_get(op->ptr, "use_snap_project");
637                         }
638
639                         if (RNA_struct_find_property(op->ptr, "use_snap_self")) {
640                                 t->tsnap.snap_self = RNA_boolean_get(op->ptr, "use_snap_self");
641                         }
642                 }
643         }
644         /* use scene defaults only when transform is modal */
645         else if (t->flag & T_MODAL) {
646                 if (ELEM(t->spacetype, SPACE_VIEW3D, SPACE_IMAGE, SPACE_NODE)) {
647                         if (ts->snap_flag & SCE_SNAP) {
648                                 t->modifiers |= MOD_SNAP;
649                         }
650
651                         t->tsnap.align = ((t->settings->snap_flag & SCE_SNAP_ROTATE) != 0);
652                         t->tsnap.project = ((t->settings->snap_flag & SCE_SNAP_PROJECT) != 0);
653                         t->tsnap.snap_self = !((t->settings->snap_flag & SCE_SNAP_NO_SELF) != 0);
654                         t->tsnap.peel = ((t->settings->snap_flag & SCE_SNAP_PROJECT) != 0);
655                 }
656
657                 /* for now only 3d view (others can be added if we want) */
658                 if (t->spacetype == SPACE_VIEW3D) {
659                         t->tsnap.snap_spatial_grid = ((t->settings->snap_flag & SCE_SNAP_ABS_GRID) != 0);
660                 }
661         }
662         
663         t->tsnap.target = snap_target;
664
665         initSnappingMode(t);
666 }
667
668 void freeSnapping(TransInfo *t)
669 {
670         if (t->tsnap.object_context) {
671                 ED_transform_snap_object_context_destroy(t->tsnap.object_context);
672                 t->tsnap.object_context = NULL;
673         }
674 }
675
676 static void setSnappingCallback(TransInfo *t)
677 {
678         t->tsnap.calcSnap = CalcSnapGeometry;
679
680         switch (t->tsnap.target) {
681                 case SCE_SNAP_TARGET_CLOSEST:
682                         t->tsnap.targetSnap = TargetSnapClosest;
683                         break;
684                 case SCE_SNAP_TARGET_CENTER:
685                         t->tsnap.targetSnap = TargetSnapCenter;
686                         break;
687                 case SCE_SNAP_TARGET_MEDIAN:
688                         t->tsnap.targetSnap = TargetSnapMedian;
689                         break;
690                 case SCE_SNAP_TARGET_ACTIVE:
691                         t->tsnap.targetSnap = TargetSnapActive;
692                         break;
693
694         }
695
696         switch (t->mode) {
697                 case TFM_TRANSLATION:
698                         t->tsnap.applySnap = ApplySnapTranslation;
699                         t->tsnap.distance = TranslationBetween;
700                         break;
701                 case TFM_ROTATION:
702                         t->tsnap.applySnap = ApplySnapRotation;
703                         t->tsnap.distance = RotationBetween;
704
705                         // Can't do TARGET_CENTER with rotation, use TARGET_MEDIAN instead
706                         if (t->tsnap.target == SCE_SNAP_TARGET_CENTER) {
707                                 t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
708                                 t->tsnap.targetSnap = TargetSnapMedian;
709                         }
710                         break;
711                 case TFM_RESIZE:
712                         t->tsnap.applySnap = ApplySnapResize;
713                         t->tsnap.distance = ResizeBetween;
714
715                         // Can't do TARGET_CENTER with resize, use TARGET_MEDIAN instead
716                         if (t->tsnap.target == SCE_SNAP_TARGET_CENTER) {
717                                 t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
718                                 t->tsnap.targetSnap = TargetSnapMedian;
719                         }
720                         break;
721                 default:
722                         t->tsnap.applySnap = NULL;
723                         break;
724         }
725 }
726
727 void addSnapPoint(TransInfo *t)
728 {
729         /* Currently only 3D viewport works for snapping points. */
730         if (t->tsnap.status & POINT_INIT && t->spacetype == SPACE_VIEW3D) {
731                 TransSnapPoint *p = MEM_callocN(sizeof(TransSnapPoint), "SnapPoint");
732
733                 t->tsnap.selectedPoint = p;
734
735                 copy_v3_v3(p->co, t->tsnap.snapPoint);
736
737                 BLI_addtail(&t->tsnap.points, p);
738
739                 t->tsnap.status |= MULTI_POINTS;
740         }
741 }
742
743 eRedrawFlag updateSelectedSnapPoint(TransInfo *t)
744 {
745         eRedrawFlag status = TREDRAW_NOTHING;
746
747         if (t->tsnap.status & MULTI_POINTS) {
748                 TransSnapPoint *p, *closest_p = NULL;
749                 float dist_min_sq = TRANSFORM_SNAP_MAX_PX;
750                 const float mval_fl[2] = {t->mval[0], t->mval[1]};
751                 float screen_loc[2];
752
753                 for (p = t->tsnap.points.first; p; p = p->next) {
754                         float dist_sq;
755
756                         if (ED_view3d_project_float_global(t->ar, p->co, screen_loc, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
757                                 continue;
758                         }
759
760                         dist_sq = len_squared_v2v2(mval_fl, screen_loc);
761
762                         if (dist_sq < dist_min_sq) {
763                                 closest_p = p;
764                                 dist_min_sq = dist_sq;
765                         }
766                 }
767
768                 if (closest_p) {
769                         if (t->tsnap.selectedPoint != closest_p) {
770                                 status = TREDRAW_HARD;
771                         }
772
773                         t->tsnap.selectedPoint = closest_p;
774                 }
775         }
776
777         return status;
778 }
779
780 void removeSnapPoint(TransInfo *t)
781 {
782         if (t->tsnap.status & MULTI_POINTS) {
783                 updateSelectedSnapPoint(t);
784
785                 if (t->tsnap.selectedPoint) {
786                         BLI_freelinkN(&t->tsnap.points, t->tsnap.selectedPoint);
787
788                         if (BLI_listbase_is_empty(&t->tsnap.points)) {
789                                 t->tsnap.status &= ~MULTI_POINTS;
790                         }
791
792                         t->tsnap.selectedPoint = NULL;
793                 }
794
795         }
796 }
797
798 void getSnapPoint(TransInfo *t, float vec[3])
799 {
800         if (t->tsnap.points.first) {
801                 TransSnapPoint *p;
802                 int total = 0;
803
804                 vec[0] = vec[1] = vec[2] = 0;
805
806                 for (p = t->tsnap.points.first; p; p = p->next, total++) {
807                         add_v3_v3(vec, p->co);
808                 }
809
810                 if (t->tsnap.status & POINT_INIT) {
811                         add_v3_v3(vec, t->tsnap.snapPoint);
812                         total++;
813                 }
814
815                 mul_v3_fl(vec, 1.0f / total);
816         }
817         else {
818                 copy_v3_v3(vec, t->tsnap.snapPoint);
819         }
820 }
821
822 /********************** APPLY **************************/
823
824 static void ApplySnapTranslation(TransInfo *t, float vec[3])
825 {
826         float point[3];
827         getSnapPoint(t, point);
828
829         if (t->spacetype == SPACE_NODE) {
830                 char border = t->tsnap.snapNodeBorder;
831                 if (border & (NODE_LEFT | NODE_RIGHT))
832                         vec[0] = point[0] - t->tsnap.snapTarget[0];
833                 if (border & (NODE_BOTTOM | NODE_TOP))
834                         vec[1] = point[1] - t->tsnap.snapTarget[1];
835         }
836         else {
837                 sub_v3_v3v3(vec, point, t->tsnap.snapTarget);
838         }
839 }
840
841 static void ApplySnapRotation(TransInfo *t, float *value)
842 {
843         float point[3];
844         getSnapPoint(t, point);
845
846         float dist = RotationBetween(t, t->tsnap.snapTarget, point);
847         *value = dist;
848 }
849
850 static void ApplySnapResize(TransInfo *t, float vec[3])
851 {
852         float point[3];
853         getSnapPoint(t, point);
854
855         float dist = ResizeBetween(t, t->tsnap.snapTarget, point);
856         copy_v3_fl(vec, dist);
857 }
858
859 /********************** DISTANCE **************************/
860
861 static float TranslationBetween(TransInfo *UNUSED(t), const float p1[3], const float p2[3])
862 {
863         return len_squared_v3v3(p1, p2);
864 }
865
866 static float RotationBetween(TransInfo *t, const float p1[3], const float p2[3])
867 {
868         float angle, start[3], end[3];
869
870         sub_v3_v3v3(start, p1, t->center_global);
871         sub_v3_v3v3(end,   p2, t->center_global);
872                 
873         // Angle around a constraint axis (error prone, will need debug)
874         if (t->con.applyRot != NULL && (t->con.mode & CON_APPLY)) {
875                 float axis[3], tmp[3];
876                 
877                 t->con.applyRot(t, NULL, axis, NULL);
878
879                 project_v3_v3v3(tmp, end, axis);
880                 sub_v3_v3v3(end, end, tmp);
881                 
882                 project_v3_v3v3(tmp, start, axis);
883                 sub_v3_v3v3(start, start, tmp);
884                 
885                 normalize_v3(end);
886                 normalize_v3(start);
887                 
888                 cross_v3_v3v3(tmp, start, end);
889                 
890                 if (dot_v3v3(tmp, axis) < 0.0f)
891                         angle = -acosf(dot_v3v3(start, end));
892                 else
893                         angle = acosf(dot_v3v3(start, end));
894         }
895         else {
896                 float mtx[3][3];
897                 
898                 copy_m3_m4(mtx, t->viewmat);
899
900                 mul_m3_v3(mtx, end);
901                 mul_m3_v3(mtx, start);
902                 
903                 angle = atan2f(start[1], start[0]) - atan2f(end[1], end[0]);
904         }
905         
906         if (angle > (float)M_PI) {
907                 angle = angle - 2 * (float)M_PI;
908         }
909         else if (angle < -((float)M_PI)) {
910                 angle = 2.0f * (float)M_PI + angle;
911         }
912         
913         return angle;
914 }
915
916 static float ResizeBetween(TransInfo *t, const float p1[3], const float p2[3])
917 {
918         float d1[3], d2[3], len_d1;
919
920         sub_v3_v3v3(d1, p1, t->center_global);
921         sub_v3_v3v3(d2, p2, t->center_global);
922
923         if (t->con.applyRot != NULL && (t->con.mode & CON_APPLY)) {
924                 mul_m3_v3(t->con.pmtx, d1);
925                 mul_m3_v3(t->con.pmtx, d2);
926         }
927
928         project_v3_v3v3(d1, d1, d2);
929         
930         len_d1 = len_v3(d1);
931
932         /* Use 'invalid' dist when `center == p1` (after projecting),
933          * in this case scale will _never_ move the point in relation to the center,
934          * so it makes no sense to take it into account when scaling. see: T46503 */
935         return len_d1 != 0.0f ? len_v3(d2) / len_d1 : TRANSFORM_DIST_INVALID;
936 }
937
938 /********************** CALC **************************/
939
940 static void UNUSED_FUNCTION(CalcSnapGrid) (TransInfo *t, float *UNUSED(vec))
941 {
942         snapGridIncrementAction(t, t->tsnap.snapPoint, BIG_GEARS);
943 }
944
945 static void CalcSnapGeometry(TransInfo *t, float *UNUSED(vec))
946 {
947         if (t->spacetype == SPACE_VIEW3D) {
948                 float loc[3];
949                 float no[3];
950                 float mval[2];
951                 bool found = false;
952                 float dist_px = SNAP_MIN_DISTANCE; // Use a user defined value here
953                 
954                 mval[0] = t->mval[0];
955                 mval[1] = t->mval[1];
956                 
957                 if (t->tsnap.mode == SCE_SNAP_MODE_VOLUME) {
958                         found = peelObjectsTransform(
959                                 t, mval, t->tsnap.modeSelect,
960                                 (t->settings->snap_flag & SCE_SNAP_PEEL_OBJECT) != 0,
961                                 loc, no, NULL);
962                 }
963                 else {
964                         zero_v3(no);  /* objects won't set this */
965                         found = snapObjectsTransform(
966                                 t, mval, t->tsnap.modeSelect, &dist_px,
967                                 loc, no);
968                 }
969                 
970                 if (found == true) {
971                         float tangent[3];
972                         
973                         sub_v2_v2v2(tangent, loc, t->tsnap.snapPoint);
974                         tangent[2] = 0.0f;
975                         
976                         if (!is_zero_v3(tangent)) {
977                                 copy_v3_v3(t->tsnap.snapTangent, tangent);
978                         }
979                         
980                         copy_v3_v3(t->tsnap.snapPoint, loc);
981                         copy_v3_v3(t->tsnap.snapNormal, no);
982
983                         t->tsnap.status |=  POINT_INIT;
984                 }
985                 else {
986                         t->tsnap.status &= ~POINT_INIT;
987                 }
988         }
989         else if (t->spacetype == SPACE_IMAGE && t->obedit != NULL && t->obedit->type == OB_MESH) {
990                 /* same as above but for UV's */
991                 Image *ima = ED_space_image(t->sa->spacedata.first);
992                 float co[2];
993                 
994                 UI_view2d_region_to_view(&t->ar->v2d, t->mval[0], t->mval[1], &co[0], &co[1]);
995
996                 if (ED_uvedit_nearest_uv(t->scene, t->obedit, ima, co, t->tsnap.snapPoint)) {
997                         t->tsnap.snapPoint[0] *= t->aspect[0];
998                         t->tsnap.snapPoint[1] *= t->aspect[1];
999
1000                         t->tsnap.status |=  POINT_INIT;
1001                 }
1002                 else {
1003                         t->tsnap.status &= ~POINT_INIT;
1004                 }
1005         }
1006         else if (t->spacetype == SPACE_NODE) {
1007                 float loc[2];
1008                 float dist_px = SNAP_MIN_DISTANCE; // Use a user defined value here
1009                 char node_border;
1010                 
1011                 if (snapNodesTransform(t, t->mval, t->tsnap.modeSelect, loc, &dist_px, &node_border)) {
1012                         copy_v2_v2(t->tsnap.snapPoint, loc);
1013                         t->tsnap.snapNodeBorder = node_border;
1014                         
1015                         t->tsnap.status |=  POINT_INIT;
1016                 }
1017                 else {
1018                         t->tsnap.status &= ~POINT_INIT;
1019                 }
1020         }
1021 }
1022
1023 /********************** TARGET **************************/
1024
1025 static void TargetSnapOffset(TransInfo *t, TransData *td)
1026 {
1027         if (t->spacetype == SPACE_NODE && td != NULL) {
1028                 bNode *node = td->extra;
1029                 char border = t->tsnap.snapNodeBorder;
1030                 float width  = BLI_rctf_size_x(&node->totr);
1031                 float height = BLI_rctf_size_y(&node->totr);
1032                 
1033 #ifdef USE_NODE_CENTER
1034                 if (border & NODE_LEFT)
1035                         t->tsnap.snapTarget[0] -= 0.5f * width;
1036                 if (border & NODE_RIGHT)
1037                         t->tsnap.snapTarget[0] += 0.5f * width;
1038                 if (border & NODE_BOTTOM)
1039                         t->tsnap.snapTarget[1] -= 0.5f * height;
1040                 if (border & NODE_TOP)
1041                         t->tsnap.snapTarget[1] += 0.5f * height;
1042 #else
1043                 if (border & NODE_LEFT)
1044                         t->tsnap.snapTarget[0] -= 0.0f;
1045                 if (border & NODE_RIGHT)
1046                         t->tsnap.snapTarget[0] += width;
1047                 if (border & NODE_BOTTOM)
1048                         t->tsnap.snapTarget[1] -= height;
1049                 if (border & NODE_TOP)
1050                         t->tsnap.snapTarget[1] += 0.0f;
1051 #endif
1052         }
1053 }
1054
1055 static void TargetSnapCenter(TransInfo *t)
1056 {
1057         /* Only need to calculate once */
1058         if ((t->tsnap.status & TARGET_INIT) == 0) {
1059                 copy_v3_v3(t->tsnap.snapTarget, t->center_global);
1060                 TargetSnapOffset(t, NULL);
1061                 
1062                 t->tsnap.status |= TARGET_INIT;
1063         }
1064 }
1065
1066 static void TargetSnapActive(TransInfo *t)
1067 {
1068         /* Only need to calculate once */
1069         if ((t->tsnap.status & TARGET_INIT) == 0) {
1070                 if (calculateCenterActive(t, true, t->tsnap.snapTarget)) {
1071                         if (t->flag & (T_EDIT | T_POSE)) {
1072                                 Object *ob = t->obedit ? t->obedit : t->poseobj;
1073                                 mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
1074                         }
1075
1076                         TargetSnapOffset(t, NULL);
1077
1078                         t->tsnap.status |= TARGET_INIT;
1079                 }
1080                 /* No active, default to median */
1081                 else {
1082                         t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
1083                         t->tsnap.targetSnap = TargetSnapMedian;
1084                         TargetSnapMedian(t);
1085                 }
1086         }
1087 }
1088
1089 static void TargetSnapMedian(TransInfo *t)
1090 {
1091         // Only need to calculate once
1092         if ((t->tsnap.status & TARGET_INIT) == 0) {
1093                 TransData *td = NULL;
1094                 int i;
1095
1096                 t->tsnap.snapTarget[0] = 0;
1097                 t->tsnap.snapTarget[1] = 0;
1098                 t->tsnap.snapTarget[2] = 0;
1099                 
1100                 for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1101                         add_v3_v3(t->tsnap.snapTarget, td->center);
1102                 }
1103                 
1104                 mul_v3_fl(t->tsnap.snapTarget, 1.0 / i);
1105                 
1106                 if (t->flag & (T_EDIT | T_POSE)) {
1107                         Object *ob = t->obedit ? t->obedit : t->poseobj;
1108                         mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
1109                 }
1110                 
1111                 TargetSnapOffset(t, NULL);
1112                 
1113                 t->tsnap.status |= TARGET_INIT;
1114         }
1115 }
1116
1117 static void TargetSnapClosest(TransInfo *t)
1118 {
1119         // Only valid if a snap point has been selected
1120         if (t->tsnap.status & POINT_INIT) {
1121                 float dist_closest = 0.0f;
1122                 TransData *closest = NULL, *td = NULL;
1123                 
1124                 /* Object mode */
1125                 if (t->flag & T_OBJECT) {
1126                         int i;
1127                         for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1128                                 struct BoundBox *bb = BKE_object_boundbox_get(td->ob);
1129                                 
1130                                 /* use boundbox if possible */
1131                                 if (bb) {
1132                                         int j;
1133                                         
1134                                         for (j = 0; j < 8; j++) {
1135                                                 float loc[3];
1136                                                 float dist;
1137                                                 
1138                                                 copy_v3_v3(loc, bb->vec[j]);
1139                                                 mul_m4_v3(td->ext->obmat, loc);
1140                                                 
1141                                                 dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1142
1143                                                 if ((dist != TRANSFORM_DIST_INVALID) &&
1144                                                     (closest == NULL || fabsf(dist) < fabsf(dist_closest)))
1145                                                 {
1146                                                         copy_v3_v3(t->tsnap.snapTarget, loc);
1147                                                         closest = td;
1148                                                         dist_closest = dist;
1149                                                 }
1150                                         }
1151                                 }
1152                                 /* use element center otherwise */
1153                                 else {
1154                                         float loc[3];
1155                                         float dist;
1156                                         
1157                                         copy_v3_v3(loc, td->center);
1158                                         
1159                                         dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1160
1161                                         if ((dist != TRANSFORM_DIST_INVALID) &&
1162                                             (closest == NULL || fabsf(dist) < fabsf(dist_closest)))
1163                                         {
1164                                                 copy_v3_v3(t->tsnap.snapTarget, loc);
1165                                                 closest = td;
1166                                         }
1167                                 }
1168                         }
1169                 }
1170                 else {
1171                         int i;
1172                         for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1173                                 float loc[3];
1174                                 float dist;
1175                                 
1176                                 copy_v3_v3(loc, td->center);
1177                                 
1178                                 if (t->flag & (T_EDIT | T_POSE)) {
1179                                         Object *ob = t->obedit ? t->obedit : t->poseobj;
1180                                         mul_m4_v3(ob->obmat, loc);
1181                                 }
1182                                 
1183                                 dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1184                                 
1185                                 if ((dist != TRANSFORM_DIST_INVALID) &&
1186                                     (closest == NULL || fabsf(dist) < fabsf(dist_closest)))
1187                                 {
1188                                         copy_v3_v3(t->tsnap.snapTarget, loc);
1189                                         closest = td;
1190                                         dist_closest = dist;
1191                                 }
1192                         }
1193                 }
1194                 
1195                 TargetSnapOffset(t, closest);
1196                 
1197                 t->tsnap.status |= TARGET_INIT;
1198         }
1199 }
1200
1201 bool snapObjectsTransform(
1202         TransInfo *t, const float mval[2], SnapSelect snap_select,
1203         float *dist_px,
1204         float r_loc[3], float r_no[3])
1205 {
1206         return ED_transform_snap_object_project_view3d_ex(
1207                 t->tsnap.object_context,
1208                 &(const struct SnapObjectParams){
1209                     .snap_select = snap_select,
1210                     .snap_to = t->scene->toolsettings->snap_mode,
1211                     .use_object_edit = (t->flag & T_EDIT) != 0,
1212                     .use_object_active = (t->options & CTX_GPENCIL_STROKES) == 0,
1213                 },
1214                 mval, dist_px, NULL,
1215                 r_loc, r_no, NULL);
1216 }
1217
1218
1219 /******************** PEELING *********************************/
1220
1221 bool peelObjectsSnapContext(
1222         SnapObjectContext *sctx,
1223         const float mval[2], SnapSelect snap_select, bool use_peel_object,
1224         /* return args */
1225         float r_loc[3], float r_no[3], float *r_thickness)
1226 {
1227         ListBase depths_peel = {0};
1228         ED_transform_snap_object_project_all_view3d_ex(
1229                 sctx,
1230                 &(const struct SnapObjectParams){
1231                     .snap_to = SCE_SNAP_MODE_FACE,
1232                     .snap_select = snap_select,
1233                     .use_object_edit = true,
1234                 },
1235                 mval, -1.0f, false,
1236                 &depths_peel);
1237
1238         if (!BLI_listbase_is_empty(&depths_peel)) {
1239                 /* At the moment we only use the hits of the first object */
1240                 struct SnapObjectHitDepth *hit_min = depths_peel.first;
1241                 for (struct SnapObjectHitDepth *iter = hit_min->next; iter; iter = iter->next) {
1242                         if (iter->depth < hit_min->depth) {
1243                                 hit_min = iter;
1244                         }
1245                 }
1246                 struct SnapObjectHitDepth *hit_max = NULL;
1247
1248                 if (use_peel_object) {
1249                         /* if peeling objects, take the first and last from each object */
1250                         hit_max = hit_min;
1251                         for (struct SnapObjectHitDepth *iter = depths_peel.first; iter; iter = iter->next) {
1252                                 if ((iter->depth > hit_max->depth) && (iter->ob_uuid == hit_min->ob_uuid)) {
1253                                         hit_max = iter;
1254                                 }
1255                         }
1256                 }
1257                 else {
1258                         /* otherwise, pair first with second and so on */
1259                         for (struct SnapObjectHitDepth *iter = depths_peel.first; iter; iter = iter->next) {
1260                                 if ((iter != hit_min) && (iter->ob_uuid == hit_min->ob_uuid)) {
1261                                         if (hit_max == NULL) {
1262                                                 hit_max = iter;
1263                                         }
1264                                         else if (iter->depth < hit_max->depth) {
1265                                                 hit_max = iter;
1266                                         }
1267                                 }
1268                         }
1269                         /* in this case has only one hit. treat as raycast */
1270                         if (hit_max == NULL) {
1271                                 hit_max = hit_min;
1272                         }
1273                 }
1274
1275                 mid_v3_v3v3(r_loc, hit_min->co, hit_max->co);
1276
1277                 if (r_thickness) {
1278                         *r_thickness = hit_max->depth - hit_min->depth;
1279                 }
1280
1281                 /* XXX, is there a correct normal in this case ???, for now just z up */
1282                 r_no[0] = 0.0;
1283                 r_no[1] = 0.0;
1284                 r_no[2] = 1.0;
1285
1286                 BLI_freelistN(&depths_peel);
1287                 return true;
1288         }
1289         return false;
1290 }
1291
1292 bool peelObjectsTransform(
1293         TransInfo *t,
1294         const float mval[2], SnapSelect snap_select, bool use_peel_object,
1295         /* return args */
1296         float r_loc[3], float r_no[3], float *r_thickness)
1297 {
1298         return peelObjectsSnapContext(
1299                 t->tsnap.object_context,
1300                 mval, snap_select, use_peel_object,
1301                 r_loc, r_no, r_thickness);
1302 }
1303
1304 /******************** NODES ***********************************/
1305
1306 static bool snapNodeTest(View2D *v2d, bNode *node, SnapSelect snap_select)
1307 {
1308         /* node is use for snapping only if a) snap mode matches and b) node is inside the view */
1309         return ((snap_select == SNAP_NOT_SELECTED && !(node->flag & NODE_SELECT)) ||
1310                 (snap_select == SNAP_ALL          && !(node->flag & NODE_ACTIVE))) &&
1311                 (node->totr.xmin < v2d->cur.xmax && node->totr.xmax > v2d->cur.xmin &&
1312                  node->totr.ymin < v2d->cur.ymax && node->totr.ymax > v2d->cur.ymin);
1313 }
1314
1315 static NodeBorder snapNodeBorder(int snap_node_mode)
1316 {
1317         switch (snap_node_mode) {
1318                 case SCE_SNAP_MODE_NODE_X:
1319                         return NODE_LEFT | NODE_RIGHT;
1320                 case SCE_SNAP_MODE_NODE_Y:
1321                         return NODE_TOP | NODE_BOTTOM;
1322                 case SCE_SNAP_MODE_NODE_XY:
1323                         return NODE_LEFT | NODE_RIGHT | NODE_TOP | NODE_BOTTOM;
1324         }
1325         return 0;
1326 }
1327
1328 static bool snapNode(
1329         ToolSettings *ts, SpaceNode *UNUSED(snode), ARegion *ar, bNode *node, const int mval[2],
1330         float r_loc[2], float *r_dist_px, char *r_node_border)
1331 {
1332         View2D *v2d = &ar->v2d;
1333         NodeBorder border = snapNodeBorder(ts->snap_node_mode);
1334         bool retval = false;
1335         rcti totr;
1336         int new_dist;
1337         
1338         UI_view2d_view_to_region_rcti(v2d, &node->totr, &totr);
1339         
1340         if (border & NODE_LEFT) {
1341                 new_dist = abs(totr.xmin - mval[0]);
1342                 if (new_dist < *r_dist_px) {
1343                         UI_view2d_region_to_view(v2d, totr.xmin, mval[1], &r_loc[0], &r_loc[1]);
1344                         *r_dist_px = new_dist;
1345                         *r_node_border = NODE_LEFT;
1346                         retval = true;
1347                 }
1348         }
1349         
1350         if (border & NODE_RIGHT) {
1351                 new_dist = abs(totr.xmax - mval[0]);
1352                 if (new_dist < *r_dist_px) {
1353                         UI_view2d_region_to_view(v2d, totr.xmax, mval[1], &r_loc[0], &r_loc[1]);
1354                         *r_dist_px = new_dist;
1355                         *r_node_border = NODE_RIGHT;
1356                         retval = true;
1357                 }
1358         }
1359         
1360         if (border & NODE_BOTTOM) {
1361                 new_dist = abs(totr.ymin - mval[1]);
1362                 if (new_dist < *r_dist_px) {
1363                         UI_view2d_region_to_view(v2d, mval[0], totr.ymin, &r_loc[0], &r_loc[1]);
1364                         *r_dist_px = new_dist;
1365                         *r_node_border = NODE_BOTTOM;
1366                         retval = true;
1367                 }
1368         }
1369         
1370         if (border & NODE_TOP) {
1371                 new_dist = abs(totr.ymax - mval[1]);
1372                 if (new_dist < *r_dist_px) {
1373                         UI_view2d_region_to_view(v2d, mval[0], totr.ymax, &r_loc[0], &r_loc[1]);
1374                         *r_dist_px = new_dist;
1375                         *r_node_border = NODE_TOP;
1376                         retval = true;
1377                 }
1378         }
1379         
1380         return retval;
1381 }
1382
1383 static bool snapNodes(
1384         ToolSettings *ts, SpaceNode *snode, ARegion *ar,
1385         const int mval[2], SnapSelect snap_select,
1386         float r_loc[2], float *r_dist_px, char *r_node_border)
1387 {
1388         bNodeTree *ntree = snode->edittree;
1389         bNode *node;
1390         bool retval = false;
1391         
1392         *r_node_border = 0;
1393         
1394         for (node = ntree->nodes.first; node; node = node->next) {
1395                 if (snapNodeTest(&ar->v2d, node, snap_select)) {
1396                         retval |= snapNode(ts, snode, ar, node, mval, r_loc, r_dist_px, r_node_border);
1397                 }
1398         }
1399         
1400         return retval;
1401 }
1402
1403 bool snapNodesTransform(
1404         TransInfo *t, const int mval[2], SnapSelect snap_select,
1405         float r_loc[2], float *r_dist_px, char *r_node_border)
1406 {
1407         return snapNodes(
1408                 t->settings, t->sa->spacedata.first, t->ar, mval, snap_select,
1409                 r_loc, r_dist_px, r_node_border);
1410 }
1411
1412 bool snapNodesContext(
1413         bContext *C, const int mval[2], SnapSelect snap_select,
1414         float r_loc[2], float *r_dist_px, char *r_node_border)
1415 {
1416         Scene *scene = CTX_data_scene(C);
1417         ARegion *ar = CTX_wm_region(C);
1418         return snapNodes(
1419                 scene->toolsettings, CTX_wm_space_node(C), ar, mval, snap_select,
1420                 r_loc, r_dist_px, r_node_border);
1421 }
1422
1423 /*================================================================*/
1424
1425 static void applyGridIncrement(TransInfo *t, float *val, int max_index, const float fac[3], GearsType action);
1426
1427
1428 void snapGridIncrementAction(TransInfo *t, float *val, GearsType action)
1429 {
1430         float fac[3];
1431
1432         fac[NO_GEARS]    = t->snap[0];
1433         fac[BIG_GEARS]   = t->snap[1];
1434         fac[SMALL_GEARS] = t->snap[2];
1435         
1436         applyGridIncrement(t, val, t->idx_max, fac, action);
1437 }
1438
1439
1440 void snapGridIncrement(TransInfo *t, float *val)
1441 {
1442         GearsType action;
1443
1444         /* only do something if using absolute or incremental grid snapping */
1445         if (!ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID))
1446                 return;
1447
1448         action = activeSnap(t) ? BIG_GEARS : NO_GEARS;
1449
1450         if (action == BIG_GEARS && (t->modifiers & MOD_PRECISION)) {
1451                 action = SMALL_GEARS;
1452         }
1453
1454         snapGridIncrementAction(t, val, action);
1455 }
1456
1457 void snapSequenceBounds(TransInfo *t, const int mval[2])
1458 {
1459         float xmouse, ymouse;
1460         int frame;
1461         int mframe;
1462         TransSeq *ts = t->custom.type.data;
1463         /* reuse increment, strictly speaking could be another snap mode, but leave as is */
1464         if (!(t->modifiers & MOD_SNAP_INVERT))
1465                 return;
1466
1467         /* convert to frame range */
1468         UI_view2d_region_to_view(&t->ar->v2d, mval[0], mval[1], &xmouse, &ymouse);
1469         mframe = iroundf(xmouse);
1470         /* now find the closest sequence */
1471         frame = BKE_sequencer_find_next_prev_edit(t->scene, mframe, SEQ_SIDE_BOTH, true, false, true);
1472
1473         if (!ts->snap_left)
1474                 frame = frame - (ts->max - ts->min);
1475
1476         t->values[0] = frame - ts->min;
1477 }
1478
1479 static void applyGridIncrement(TransInfo *t, float *val, int max_index, const float fac[3], GearsType action)
1480 {
1481         float asp_local[3] = {1, 1, 1};
1482         const bool use_aspect = ELEM(t->mode, TFM_TRANSLATION);
1483         const float *asp = use_aspect ? t->aspect : asp_local;
1484         int i;
1485
1486         BLI_assert(ELEM(t->tsnap.mode, SCE_SNAP_MODE_INCREMENT, SCE_SNAP_MODE_GRID));
1487         BLI_assert(max_index <= 2);
1488
1489         /* Early bailing out if no need to snap */
1490         if (fac[action] == 0.0f) {
1491                 return;
1492         }
1493
1494         if (use_aspect) {
1495                 /* custom aspect for fcurve */
1496                 if (t->spacetype == SPACE_IPO) {
1497                         View2D *v2d = &t->ar->v2d;
1498                         View2DGrid *grid;
1499                         SpaceIpo *sipo = t->sa->spacedata.first;
1500                         int unity = V2D_UNIT_VALUES;
1501                         int unitx = (sipo->flag & SIPO_DRAWTIME) ? V2D_UNIT_SECONDS : V2D_UNIT_FRAMESCALE;
1502
1503                         /* grid */
1504                         grid = UI_view2d_grid_calc(t->scene, v2d, unitx, V2D_GRID_NOCLAMP, unity, V2D_GRID_NOCLAMP, t->ar->winx, t->ar->winy);
1505
1506                         UI_view2d_grid_size(grid, &asp_local[0], &asp_local[1]);
1507                         UI_view2d_grid_free(grid);
1508
1509                         asp = asp_local;
1510                 }
1511         }
1512
1513         /* absolute snapping on grid based on global center */
1514         if ((t->tsnap.snap_spatial_grid) && (t->mode == TFM_TRANSLATION)) {
1515                 const float *center_global = t->center_global;
1516
1517                 /* use a fallback for cursor selection,
1518                  * this isn't useful as a global center for absolute grid snapping
1519                  * since its not based on the position of the selection. */
1520                 if (t->around == V3D_AROUND_CURSOR) {
1521                         const TransCenterData *cd = transformCenter_from_type(t, V3D_AROUND_CENTER_MEAN);
1522                         center_global = cd->global;
1523                 }
1524
1525                 for (i = 0; i <= max_index; i++) {
1526                         /* do not let unconstrained axis jump to absolute grid increments */
1527                         if (!(t->con.mode & CON_APPLY) || t->con.mode & (CON_AXIS0 << i)) {
1528                                 const float iter_fac = fac[action] * asp[i];
1529                                 val[i] = iter_fac * roundf((val[i] + center_global[i]) / iter_fac) - center_global[i];
1530                         }
1531                 }
1532         }
1533         else {
1534                 /* relative snapping in fixed increments */
1535                 for (i = 0; i <= max_index; i++) {
1536                         const float iter_fac = fac[action] * asp[i];
1537                         val[i] = iter_fac * roundf(val[i] / iter_fac);
1538                 }
1539         }
1540 }