2d95e2ecdc687ad8e1b2982a7e7e16889c0df01f
[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_armature_types.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"  /* Temporary, for snapping to other unselected meshes */
44 #include "DNA_node_types.h"
45 #include "DNA_space_types.h"
46 #include "DNA_screen_types.h"
47 #include "DNA_view3d_types.h"
48 #include "DNA_windowmanager_types.h"
49
50 #include "RNA_access.h"
51
52 #include "BLI_math.h"
53 #include "BLI_blenlib.h"
54 #include "BLI_utildefines.h"
55
56 #include "BIF_gl.h"
57
58 #include "BKE_DerivedMesh.h"
59 #include "BKE_object.h"
60 #include "BKE_anim.h"  /* for duplis */
61 #include "BKE_context.h"
62 #include "BKE_tessmesh.h"
63 #include "BKE_mesh.h"
64
65 #include "ED_armature.h"
66 #include "ED_image.h"
67 #include "ED_mesh.h"
68 #include "ED_node.h"
69 #include "ED_uvedit.h"
70 #include "ED_view3d.h"
71
72 #include "WM_types.h"
73
74 #include "UI_resources.h"
75 #include "UI_view2d.h"
76
77 #include "MEM_guardedalloc.h"
78
79 #include "transform.h"
80
81 #define TRANSFORM_DIST_MAX_PX 1000
82
83 /********************* PROTOTYPES ***********************/
84
85 static void setSnappingCallback(TransInfo *t);
86
87 static void ApplySnapTranslation(TransInfo *t, float vec[3]);
88 static void ApplySnapRotation(TransInfo *t, float *vec);
89 static void ApplySnapResize(TransInfo *t, float vec[2]);
90
91 /* static void CalcSnapGrid(TransInfo *t, float *vec); */
92 static void CalcSnapGeometry(TransInfo *t, float *vec);
93
94 static void TargetSnapMedian(TransInfo *t);
95 static void TargetSnapCenter(TransInfo *t);
96 static void TargetSnapClosest(TransInfo *t);
97 static void TargetSnapActive(TransInfo *t);
98
99 static float RotationBetween(TransInfo *t, float p1[3], float p2[3]);
100 static float TranslationBetween(TransInfo *t, float p1[3], float p2[3]);
101 static float ResizeBetween(TransInfo *t, float p1[3], float p2[3]);
102
103
104 /****************** IMPLEMENTATIONS *********************/
105
106 static int snapNodeTest(View2D *v2d, bNode *node, SnapMode mode);
107 static NodeBorder snapNodeBorder(int snap_node_mode);
108
109 #if 0
110 int BIF_snappingSupported(Object *obedit)
111 {
112         int status = 0;
113         
114         if (obedit == NULL || ELEM4(obedit->type, OB_MESH, OB_ARMATURE, OB_CURVE, OB_LATTICE)) /* only support object mesh, armature, curves */
115         {
116                 status = 1;
117         }
118         
119         return status;
120 }
121 #endif
122
123 int validSnap(TransInfo *t)
124 {
125         return (t->tsnap.status & (POINT_INIT | TARGET_INIT)) == (POINT_INIT | TARGET_INIT) ||
126                (t->tsnap.status & (MULTI_POINTS | TARGET_INIT)) == (MULTI_POINTS | TARGET_INIT);
127 }
128
129 int activeSnap(TransInfo *t)
130 {
131         return (t->modifiers & (MOD_SNAP | MOD_SNAP_INVERT)) == MOD_SNAP || (t->modifiers & (MOD_SNAP | MOD_SNAP_INVERT)) == MOD_SNAP_INVERT;
132 }
133
134 void drawSnapping(const struct bContext *C, TransInfo *t)
135 {
136         unsigned char col[4], selectedCol[4], activeCol[4];
137         
138         if (!activeSnap(t))
139                 return;
140         
141         UI_GetThemeColor3ubv(TH_TRANSFORM, col);
142         col[3] = 128;
143         
144         UI_GetThemeColor3ubv(TH_SELECT, selectedCol);
145         selectedCol[3] = 128;
146         
147         UI_GetThemeColor3ubv(TH_ACTIVE, activeCol);
148         activeCol[3] = 192;
149         
150         if (t->spacetype == SPACE_VIEW3D) {
151                 if (validSnap(t)) {
152                         TransSnapPoint *p;
153                         View3D *v3d = CTX_wm_view3d(C);
154                         RegionView3D *rv3d = CTX_wm_region_view3d(C);
155                         float imat[4][4];
156                         float size;
157                         
158                         glDisable(GL_DEPTH_TEST);
159                         
160                         size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
161                         
162                         invert_m4_m4(imat, rv3d->viewmat);
163                         
164                         for (p = t->tsnap.points.first; p; p = p->next) {
165                                 if (p == t->tsnap.selectedPoint) {
166                                         glColor4ubv(selectedCol);
167                                 }
168                                 else {
169                                         glColor4ubv(col);
170                                 }
171                                 
172                                 drawcircball(GL_LINE_LOOP, p->co, ED_view3d_pixel_size(rv3d, p->co) * size * 0.75f, imat);
173                         }
174                         
175                         if (t->tsnap.status & POINT_INIT) {
176                                 glColor4ubv(activeCol);
177                                 
178                                 drawcircball(GL_LINE_LOOP, t->tsnap.snapPoint, ED_view3d_pixel_size(rv3d, t->tsnap.snapPoint) * size, imat);
179                         }
180                         
181                         /* draw normal if needed */
182                         if (usingSnappingNormal(t) && validSnappingNormal(t)) {
183                                 glColor4ubv(activeCol);
184                                 
185                                 glBegin(GL_LINES);
186                                 glVertex3f(t->tsnap.snapPoint[0], t->tsnap.snapPoint[1], t->tsnap.snapPoint[2]);
187                                 glVertex3f(t->tsnap.snapPoint[0] + t->tsnap.snapNormal[0],
188                                            t->tsnap.snapPoint[1] + t->tsnap.snapNormal[1],
189                                            t->tsnap.snapPoint[2] + t->tsnap.snapNormal[2]);
190                                 glEnd();
191                         }
192                         
193                         if (v3d->zbuf)
194                                 glEnable(GL_DEPTH_TEST);
195                 }
196         }
197         else if (t->spacetype == SPACE_IMAGE) {
198                 if (validSnap(t)) {
199                         /* This will not draw, and Im nor sure why - campbell */
200 #if 0
201                         float xuser_asp, yuser_asp;
202                         int wi, hi;
203                         float w, h;
204                         
205                         calc_image_view(G.sima, 'f');   // float
206                         myortho2(G.v2d->cur.xmin, G.v2d->cur.xmax, G.v2d->cur.ymin, G.v2d->cur.ymax);
207                         glLoadIdentity();
208                         
209                         ED_space_image_get_aspect(t->sa->spacedata.first, &xuser_aspx, &yuser_asp);
210                         ED_space_image_width(t->sa->spacedata.first, &wi, &hi);
211                         w = (((float)wi) / IMG_SIZE_FALLBACK) * G.sima->zoom * xuser_asp;
212                         h = (((float)hi) / IMG_SIZE_FALLBACK) * G.sima->zoom * yuser_asp;
213                         
214                         cpack(0xFFFFFF);
215                         glTranslatef(t->tsnap.snapPoint[0], t->tsnap.snapPoint[1], 0.0f);
216                         
217                         //glRectf(0, 0, 1, 1);
218                         
219                         setlinestyle(0);
220                         cpack(0x0);
221                         fdrawline(-0.020 / w, 0, -0.1 / w, 0);
222                         fdrawline(0.1 / w, 0, 0.020 / w, 0);
223                         fdrawline(0, -0.020 / h, 0, -0.1 / h);
224                         fdrawline(0, 0.1 / h, 0, 0.020 / h);
225                         
226                         glTranslatef(-t->tsnap.snapPoint[0], -t->tsnap.snapPoint[1], 0.0f);
227                         setlinestyle(0);
228 #endif
229                 }
230         }
231         else if (t->spacetype == SPACE_NODE) {
232                 if (validSnap(t)) {
233                         ARegion *ar = CTX_wm_region(C);
234                         TransSnapPoint *p;
235                         float size;
236                         
237                         size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
238                         
239                         glEnable(GL_BLEND);
240                         
241                         for (p = t->tsnap.points.first; p; p = p->next) {
242                                 if (p == t->tsnap.selectedPoint) {
243                                         glColor4ubv(selectedCol);
244                                 }
245                                 else {
246                                         glColor4ubv(col);
247                                 }
248                                 
249                                 ED_node_draw_snap(&ar->v2d, p->co, size, 0);
250                         }
251                         
252                         if (t->tsnap.status & POINT_INIT) {
253                                 glColor4ubv(activeCol);
254                                 
255                                 ED_node_draw_snap(&ar->v2d, t->tsnap.snapPoint, size, t->tsnap.snapNodeBorder);
256                         }
257                         
258                         glDisable(GL_BLEND);
259                 }
260         }
261 }
262
263 int  handleSnapping(TransInfo *t, wmEvent *event)
264 {
265         int status = 0;
266
267 #if 0 // XXX need a proper selector for all snap mode
268         if (BIF_snappingSupported(t->obedit) && event->type == TABKEY && event->shift) {
269                 /* toggle snap and reinit */
270                 t->settings->snap_flag ^= SCE_SNAP;
271                 initSnapping(t, NULL);
272                 status = 1;
273         }
274 #endif
275         if (event->type == MOUSEMOVE) {
276                 status |= updateSelectedSnapPoint(t);
277         }
278         
279         return status;
280 }
281
282 void applyProject(TransInfo *t)
283 {
284         /* XXX FLICKER IN OBJECT MODE */
285         if ((t->tsnap.project) && activeSnap(t) && (t->flag & T_NO_PROJECT) == 0) {
286                 TransData *td = t->data;
287                 float tvec[3];
288                 float imat[4][4];
289                 int i;
290         
291                 if (t->flag & (T_EDIT | T_POSE)) {
292                         Object *ob = t->obedit ? t->obedit : t->poseobj;
293                         invert_m4_m4(imat, ob->obmat);
294                 }
295
296                 for (i = 0; i < t->total; i++, td++) {
297                         float iloc[3], loc[3], no[3];
298                         float mval[2];
299                         int dist = TRANSFORM_DIST_MAX_PX;
300                         
301                         if (td->flag & TD_NOACTION)
302                                 break;
303                         
304                         if (td->flag & TD_SKIP)
305                                 continue;
306                         
307                         copy_v3_v3(iloc, td->loc);
308                         if (t->flag & (T_EDIT | T_POSE)) {
309                                 Object *ob = t->obedit ? t->obedit : t->poseobj;
310                                 mul_m4_v3(ob->obmat, iloc);
311                         }
312                         else if (t->flag & T_OBJECT) {
313                                 td->ob->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
314                                 BKE_object_handle_update(t->scene, td->ob);
315                                 copy_v3_v3(iloc, td->ob->obmat[3]);
316                         }
317                         
318                         if (ED_view3d_project_float_global(t->ar, iloc, mval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
319                                 if (snapObjectsTransform(t, mval, &dist, loc, no, t->tsnap.modeSelect)) {
320 //                                      if (t->flag & (T_EDIT|T_POSE)) {
321 //                                              mul_m4_v3(imat, loc);
322 //                                      }
323
324                                         sub_v3_v3v3(tvec, loc, iloc);
325
326                                         mul_m3_v3(td->smtx, tvec);
327
328                                         add_v3_v3(td->loc, tvec);
329                                 }
330                         }
331                         
332                         //XXX constraintTransLim(t, td);
333                 }
334         }
335 }
336
337 void applySnapping(TransInfo *t, float *vec)
338 {
339         /* project is not applied this way */
340         if (t->tsnap.project)
341                 return;
342         
343         if (t->tsnap.status & SNAP_FORCED) {
344                 t->tsnap.targetSnap(t);
345         
346                 t->tsnap.applySnap(t, vec);
347         }
348         else if ((t->tsnap.mode != SCE_SNAP_MODE_INCREMENT) && activeSnap(t)) {
349                 double current = PIL_check_seconds_timer();
350                 
351                 // Time base quirky code to go around findnearest slowness
352                 /* !TODO! add exception for object mode, no need to slow it down then */
353                 if (current - t->tsnap.last >= 0.01) {
354                         t->tsnap.calcSnap(t, vec);
355                         t->tsnap.targetSnap(t);
356         
357                         t->tsnap.last = current;
358                 }
359                 if (validSnap(t)) {
360                         t->tsnap.applySnap(t, vec);
361                 }
362         }
363 }
364
365 void resetSnapping(TransInfo *t)
366 {
367         t->tsnap.status = 0;
368         t->tsnap.align = 0;
369         t->tsnap.project = 0;
370         t->tsnap.mode = 0;
371         t->tsnap.modeSelect = 0;
372         t->tsnap.target = 0;
373         t->tsnap.last = 0;
374         t->tsnap.applySnap = NULL;
375
376         t->tsnap.snapNormal[0] = 0;
377         t->tsnap.snapNormal[1] = 0;
378         t->tsnap.snapNormal[2] = 0;
379         
380         t->tsnap.snapNodeBorder = 0;
381 }
382
383 int usingSnappingNormal(TransInfo *t)
384 {
385         return t->tsnap.align;
386 }
387
388 int validSnappingNormal(TransInfo *t)
389 {
390         if (validSnap(t)) {
391                 if (dot_v3v3(t->tsnap.snapNormal, t->tsnap.snapNormal) > 0) {
392                         return 1;
393                 }
394         }
395         
396         return 0;
397 }
398
399 static void initSnappingMode(TransInfo *t)
400 {
401         ToolSettings *ts = t->settings;
402         Object *obedit = t->obedit;
403         Scene *scene = t->scene;
404
405         if (t->spacetype == SPACE_NODE) {
406                 /* force project off when not supported */
407                 t->tsnap.project = 0;
408                 
409                 t->tsnap.mode = ts->snap_node_mode;
410         }
411         else if (t->spacetype == SPACE_IMAGE) {
412                 /* force project off when not supported */
413                 t->tsnap.project = 0;
414                 
415                 t->tsnap.mode = ts->snap_uv_mode;
416         }
417         else {
418                 /* force project off when not supported */
419                 if (ts->snap_mode != SCE_SNAP_MODE_FACE)
420                         t->tsnap.project = 0;
421                 
422                 t->tsnap.mode = ts->snap_mode;
423         }
424
425         if ((t->spacetype == SPACE_VIEW3D || t->spacetype == SPACE_IMAGE) &&  /* Only 3D view or UV */
426             (t->flag & T_CAMERA) == 0)  /* Not with camera selected in camera view */
427         {
428                 setSnappingCallback(t);
429
430                 /* Edit mode */
431                 if (t->tsnap.applySnap != NULL && // A snapping function actually exist
432                     (obedit != NULL && ELEM4(obedit->type, OB_MESH, OB_ARMATURE, OB_CURVE, OB_LATTICE)) ) // Temporary limited to edit mode meshes, armature, curves
433                 {
434                         /* Exclude editmesh if using proportional edit */
435                         if ((obedit->type == OB_MESH) && (t->flag & T_PROP_EDIT)) {
436                                 t->tsnap.modeSelect = SNAP_NOT_OBEDIT;
437                         }
438                         else {
439                                 t->tsnap.modeSelect = t->tsnap.snap_self ? SNAP_ALL : SNAP_NOT_OBEDIT;
440                         }
441                 }
442                 /* Particles edit mode*/
443                 else if (t->tsnap.applySnap != NULL && // A snapping function actually exist
444                          (obedit == NULL && BASACT && BASACT->object && BASACT->object->mode & OB_MODE_PARTICLE_EDIT))
445                 {
446                         t->tsnap.modeSelect = SNAP_ALL;
447                 }
448                 /* Object mode */
449                 else if (t->tsnap.applySnap != NULL && // A snapping function actually exist
450                          (obedit == NULL) ) // Object Mode
451                 {
452                         t->tsnap.modeSelect = SNAP_NOT_SELECTED;
453                 }
454                 else {
455                         /* Grid if snap is not possible */
456                         t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
457                 }
458         }
459         else if (t->spacetype == SPACE_NODE) {
460                 setSnappingCallback(t);
461                 
462                 if (t->tsnap.applySnap != NULL) {
463                         t->tsnap.modeSelect = SNAP_NOT_SELECTED;
464                 }
465                 else {
466                         /* Grid if snap is not possible */
467                         t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
468                 }
469         }
470         else {
471                 /* Always grid outside of 3D view */
472                 t->tsnap.mode = SCE_SNAP_MODE_INCREMENT;
473         }
474 }
475
476 void initSnapping(TransInfo *t, wmOperator *op)
477 {
478         ToolSettings *ts = t->settings;
479         short snap_target = t->settings->snap_target;
480         
481         resetSnapping(t);
482         
483         /* if snap property exists */
484         if (op && RNA_struct_find_property(op->ptr, "snap") && RNA_struct_property_is_set(op->ptr, "snap")) {
485                 if (RNA_boolean_get(op->ptr, "snap")) {
486                         t->modifiers |= MOD_SNAP;
487
488                         if (RNA_struct_property_is_set(op->ptr, "snap_target")) {
489                                 snap_target = RNA_enum_get(op->ptr, "snap_target");
490                         }
491                         
492                         if (RNA_struct_property_is_set(op->ptr, "snap_point")) {
493                                 RNA_float_get_array(op->ptr, "snap_point", t->tsnap.snapPoint);
494                                 t->tsnap.status |= SNAP_FORCED | POINT_INIT;
495                         }
496                         
497                         /* snap align only defined in specific cases */
498                         if (RNA_struct_find_property(op->ptr, "snap_align")) {
499                                 t->tsnap.align = RNA_boolean_get(op->ptr, "snap_align");
500                                 RNA_float_get_array(op->ptr, "snap_normal", t->tsnap.snapNormal);
501                                 normalize_v3(t->tsnap.snapNormal);
502                         }
503
504                         if (RNA_struct_find_property(op->ptr, "use_snap_project")) {
505                                 t->tsnap.project = RNA_boolean_get(op->ptr, "use_snap_project");
506                         }
507
508                         if (RNA_struct_find_property(op->ptr, "use_snap_self")) {
509                                 t->tsnap.snap_self = RNA_boolean_get(op->ptr, "use_snap_self");
510                         }
511                 }
512         }
513         /* use scene defaults only when transform is modal */
514         else if (t->flag & T_MODAL) {
515                 if (ELEM3(t->spacetype, SPACE_VIEW3D, SPACE_IMAGE, SPACE_NODE)) {
516                         if (ts->snap_flag & SCE_SNAP) {
517                                 t->modifiers |= MOD_SNAP;
518                         }
519
520                         t->tsnap.align = ((t->settings->snap_flag & SCE_SNAP_ROTATE) == SCE_SNAP_ROTATE);
521                         t->tsnap.project = ((t->settings->snap_flag & SCE_SNAP_PROJECT) == SCE_SNAP_PROJECT);
522                         t->tsnap.snap_self = !((t->settings->snap_flag & SCE_SNAP_NO_SELF) == SCE_SNAP_NO_SELF);
523                         t->tsnap.peel = ((t->settings->snap_flag & SCE_SNAP_PROJECT) == SCE_SNAP_PROJECT);
524                 }
525         }
526         
527         t->tsnap.target = snap_target;
528
529         initSnappingMode(t);
530 }
531
532 static void setSnappingCallback(TransInfo *t)
533 {
534         t->tsnap.calcSnap = CalcSnapGeometry;
535
536         switch (t->tsnap.target) {
537                 case SCE_SNAP_TARGET_CLOSEST:
538                         t->tsnap.targetSnap = TargetSnapClosest;
539                         break;
540                 case SCE_SNAP_TARGET_CENTER:
541                         t->tsnap.targetSnap = TargetSnapCenter;
542                         break;
543                 case SCE_SNAP_TARGET_MEDIAN:
544                         t->tsnap.targetSnap = TargetSnapMedian;
545                         break;
546                 case SCE_SNAP_TARGET_ACTIVE:
547                         t->tsnap.targetSnap = TargetSnapActive;
548                         break;
549
550         }
551
552         switch (t->mode) {
553                 case TFM_TRANSLATION:
554                         t->tsnap.applySnap = ApplySnapTranslation;
555                         t->tsnap.distance = TranslationBetween;
556                         break;
557                 case TFM_ROTATION:
558                         t->tsnap.applySnap = ApplySnapRotation;
559                         t->tsnap.distance = RotationBetween;
560
561                         // Can't do TARGET_CENTER with rotation, use TARGET_MEDIAN instead
562                         if (t->tsnap.target == SCE_SNAP_TARGET_CENTER) {
563                                 t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
564                                 t->tsnap.targetSnap = TargetSnapMedian;
565                         }
566                         break;
567                 case TFM_RESIZE:
568                         t->tsnap.applySnap = ApplySnapResize;
569                         t->tsnap.distance = ResizeBetween;
570
571                         // Can't do TARGET_CENTER with resize, use TARGET_MEDIAN instead
572                         if (t->tsnap.target == SCE_SNAP_TARGET_CENTER) {
573                                 t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
574                                 t->tsnap.targetSnap = TargetSnapMedian;
575                         }
576                         break;
577                 default:
578                         t->tsnap.applySnap = NULL;
579                         break;
580         }
581 }
582
583 void addSnapPoint(TransInfo *t)
584 {
585         if (t->tsnap.status & POINT_INIT) {
586                 TransSnapPoint *p = MEM_callocN(sizeof(TransSnapPoint), "SnapPoint");
587
588                 t->tsnap.selectedPoint = p;
589
590                 copy_v3_v3(p->co, t->tsnap.snapPoint);
591
592                 BLI_addtail(&t->tsnap.points, p);
593
594                 t->tsnap.status |= MULTI_POINTS;
595         }
596 }
597
598 int updateSelectedSnapPoint(TransInfo *t)
599 {
600         int status = 0;
601         if (t->tsnap.status & MULTI_POINTS) {
602                 TransSnapPoint *p, *closest_p = NULL;
603                 int closest_dist = 0;
604                 int screen_loc[2];
605
606                 for (p = t->tsnap.points.first; p; p = p->next) {
607                         int dx, dy;
608                         int dist;
609
610                         if (ED_view3d_project_int_global(t->ar, p->co, screen_loc, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
611                                 continue;
612                         }
613
614                         dx = t->mval[0] - screen_loc[0];
615                         dy = t->mval[1] - screen_loc[1];
616
617                         dist = dx * dx + dy * dy;
618
619                         if (dist < 100 && (closest_p == NULL || closest_dist > dist)) {
620                                 closest_p = p;
621                                 closest_dist = dist;
622                         }
623                 }
624
625                 if (closest_p) {
626                         status = t->tsnap.selectedPoint == closest_p ? 0 : 1;
627                         t->tsnap.selectedPoint = closest_p;
628                 }
629         }
630
631         return status;
632 }
633
634 void removeSnapPoint(TransInfo *t)
635 {
636         if (t->tsnap.status & MULTI_POINTS) {
637                 updateSelectedSnapPoint(t);
638
639                 if (t->tsnap.selectedPoint) {
640                         BLI_freelinkN(&t->tsnap.points, t->tsnap.selectedPoint);
641
642                         if (t->tsnap.points.first == NULL) {
643                                 t->tsnap.status &= ~MULTI_POINTS;
644                         }
645
646                         t->tsnap.selectedPoint = NULL;
647                 }
648
649         }
650 }
651
652 void getSnapPoint(TransInfo *t, float vec[3])
653 {
654         if (t->tsnap.points.first) {
655                 TransSnapPoint *p;
656                 int total = 0;
657
658                 vec[0] = vec[1] = vec[2] = 0;
659
660                 for (p = t->tsnap.points.first; p; p = p->next, total++) {
661                         add_v3_v3(vec, p->co);
662                 }
663
664                 if (t->tsnap.status & POINT_INIT) {
665                         add_v3_v3(vec, t->tsnap.snapPoint);
666                         total++;
667                 }
668
669                 mul_v3_fl(vec, 1.0f / total);
670         }
671         else {
672                 copy_v3_v3(vec, t->tsnap.snapPoint);
673         }
674 }
675
676 /********************** APPLY **************************/
677
678 static void ApplySnapTranslation(TransInfo *t, float vec[3])
679 {
680         float point[3];
681         getSnapPoint(t, point);
682
683         if (t->spacetype == SPACE_NODE) {
684                 char border = t->tsnap.snapNodeBorder;
685                 if (border & (NODE_LEFT | NODE_RIGHT))
686                         vec[0] = point[0] - t->tsnap.snapTarget[0];
687                 if (border & (NODE_BOTTOM | NODE_TOP))
688                         vec[1] = point[1] - t->tsnap.snapTarget[1];
689         }
690         else {
691                 sub_v3_v3v3(vec, point, t->tsnap.snapTarget);
692         }
693 }
694
695 static void ApplySnapRotation(TransInfo *t, float *value)
696 {
697         if (t->tsnap.target == SCE_SNAP_TARGET_CLOSEST) {
698                 *value = t->tsnap.dist;
699         }
700         else {
701                 float point[3];
702                 getSnapPoint(t, point);
703                 *value = RotationBetween(t, t->tsnap.snapTarget, point);
704         }
705 }
706
707 static void ApplySnapResize(TransInfo *t, float vec[3])
708 {
709         if (t->tsnap.target == SCE_SNAP_TARGET_CLOSEST) {
710                 vec[0] = vec[1] = vec[2] = t->tsnap.dist;
711         }
712         else {
713                 float point[3];
714                 getSnapPoint(t, point);
715                 vec[0] = vec[1] = vec[2] = ResizeBetween(t, t->tsnap.snapTarget, point);
716         }
717 }
718
719 /********************** DISTANCE **************************/
720
721 static float TranslationBetween(TransInfo *UNUSED(t), float p1[3], float p2[3])
722 {
723         return len_v3v3(p1, p2);
724 }
725
726 static float RotationBetween(TransInfo *t, float p1[3], float p2[3])
727 {
728         float angle, start[3], end[3], center[3];
729         
730         copy_v3_v3(center, t->center);
731         if (t->flag & (T_EDIT | T_POSE)) {
732                 Object *ob = t->obedit ? t->obedit : t->poseobj;
733                 mul_m4_v3(ob->obmat, center);
734         }
735
736         sub_v3_v3v3(start, p1, center);
737         sub_v3_v3v3(end, p2, center);
738                 
739         // Angle around a constraint axis (error prone, will need debug)
740         if (t->con.applyRot != NULL && (t->con.mode & CON_APPLY)) {
741                 float axis[3], tmp[3];
742                 
743                 t->con.applyRot(t, NULL, axis, NULL);
744
745                 project_v3_v3v3(tmp, end, axis);
746                 sub_v3_v3v3(end, end, tmp);
747                 
748                 project_v3_v3v3(tmp, start, axis);
749                 sub_v3_v3v3(start, start, tmp);
750                 
751                 normalize_v3(end);
752                 normalize_v3(start);
753                 
754                 cross_v3_v3v3(tmp, start, end);
755                 
756                 if (dot_v3v3(tmp, axis) < 0.0f)
757                         angle = -acos(dot_v3v3(start, end));
758                 else
759                         angle = acos(dot_v3v3(start, end));
760         }
761         else {
762                 float mtx[3][3];
763                 
764                 copy_m3_m4(mtx, t->viewmat);
765
766                 mul_m3_v3(mtx, end);
767                 mul_m3_v3(mtx, start);
768                 
769                 angle = atan2(start[1], start[0]) - atan2(end[1], end[0]);
770         }
771         
772         if (angle > (float)M_PI) {
773                 angle = angle - 2 * (float)M_PI;
774         }
775         else if (angle < -((float)M_PI)) {
776                 angle = 2.0f * (float)M_PI + angle;
777         }
778         
779         return angle;
780 }
781
782 static float ResizeBetween(TransInfo *t, float p1[3], float p2[3])
783 {
784         float d1[3], d2[3], center[3], len_d1;
785         
786         copy_v3_v3(center, t->center);
787         if (t->flag & (T_EDIT | T_POSE)) {
788                 Object *ob = t->obedit ? t->obedit : t->poseobj;
789                 mul_m4_v3(ob->obmat, center);
790         }
791
792         sub_v3_v3v3(d1, p1, center);
793         sub_v3_v3v3(d2, p2, center);
794         
795         if (t->con.applyRot != NULL && (t->con.mode & CON_APPLY)) {
796                 mul_m3_v3(t->con.pmtx, d1);
797                 mul_m3_v3(t->con.pmtx, d2);
798         }
799         
800         len_d1 = len_v3(d1);
801
802         return len_d1 != 0.0f ? len_v3(d2) / len_d1 : 1;
803 }
804
805 /********************** CALC **************************/
806
807 static void UNUSED_FUNCTION(CalcSnapGrid) (TransInfo * t, float *UNUSED(vec))
808 {
809         snapGridAction(t, t->tsnap.snapPoint, BIG_GEARS);
810 }
811
812 static void CalcSnapGeometry(TransInfo *t, float *UNUSED(vec))
813 {
814         if (t->spacetype == SPACE_VIEW3D) {
815                 float loc[3];
816                 float no[3];
817                 float mval[2];
818                 int found = 0;
819                 int dist = SNAP_MIN_DISTANCE; // Use a user defined value here
820                 
821                 mval[0] = t->mval[0];
822                 mval[1] = t->mval[1];
823                 
824                 if (t->tsnap.mode == SCE_SNAP_MODE_VOLUME) {
825                         ListBase depth_peels;
826                         DepthPeel *p1, *p2;
827                         float *last_p = NULL;
828                         float max_dist = FLT_MAX;
829                         float p[3] = {0.0f, 0.0f, 0.0f};
830                         
831                         depth_peels.first = depth_peels.last = NULL;
832                         
833                         peelObjectsTransForm(t, &depth_peels, mval, t->tsnap.modeSelect);
834                         
835 //                      if (LAST_SNAP_POINT_VALID)
836 //                      {
837 //                              last_p = LAST_SNAP_POINT;
838 //                      }
839 //                      else
840 //                      {
841                                 last_p = t->tsnap.snapPoint;
842 //                      }
843                         
844                         
845                         for (p1 = depth_peels.first; p1; p1 = p1->next) {
846                                 if (p1->flag == 0) {
847                                         float vec[3];
848                                         float new_dist;
849                                         
850                                         p2 = NULL;
851                                         p1->flag = 1;
852                 
853                                         /* if peeling objects, take the first and last from each object */
854                                         if (t->settings->snap_flag & SCE_SNAP_PEEL_OBJECT) {
855                                                 DepthPeel *peel;
856                                                 for (peel = p1->next; peel; peel = peel->next) {
857                                                         if (peel->ob == p1->ob) {
858                                                                 peel->flag = 1;
859                                                                 p2 = peel;
860                                                         }
861                                                 }
862                                         }
863                                         /* otherwise, pair first with second and so on */
864                                         else {
865                                                 for (p2 = p1->next; p2 && p2->ob != p1->ob; p2 = p2->next) {
866                                                         /* nothing to do here */
867                                                 }
868                                         }
869                                         
870                                         if (p2) {
871                                                 p2->flag = 1;
872                                                 
873                                                 add_v3_v3v3(vec, p1->p, p2->p);
874                                                 mul_v3_fl(vec, 0.5f);
875                                         }
876                                         else {
877                                                 copy_v3_v3(vec, p1->p);
878                                         }
879
880                                         if (last_p == NULL) {
881                                                 copy_v3_v3(p, vec);
882                                                 max_dist = 0;
883                                                 break;
884                                         }
885                                         
886                                         new_dist = len_v3v3(last_p, vec);
887                                         
888                                         if (new_dist < max_dist) {
889                                                 copy_v3_v3(p, vec);
890                                                 max_dist = new_dist;
891                                         }
892                                 }
893                         }
894                         
895                         if (max_dist != FLT_MAX) {
896                                 copy_v3_v3(loc, p);
897                                 /* XXX, is there a correct normal in this case ???, for now just z up */
898                                 no[0] = 0.0;
899                                 no[1] = 0.0;
900                                 no[2] = 1.0;
901                                 found = 1;
902                         }
903                         
904                         BLI_freelistN(&depth_peels);
905                 }
906                 else {
907                         found = snapObjectsTransform(t, mval, &dist, loc, no, t->tsnap.modeSelect);
908                 }
909                 
910                 if (found == 1) {
911                         float tangent[3];
912                         
913                         sub_v3_v3v3(tangent, loc, t->tsnap.snapPoint);
914                         tangent[2] = 0; 
915                         
916                         if (dot_v3v3(tangent, tangent) > 0) {
917                                 copy_v3_v3(t->tsnap.snapTangent, tangent);
918                         }
919                         
920                         copy_v3_v3(t->tsnap.snapPoint, loc);
921                         copy_v3_v3(t->tsnap.snapNormal, no);
922
923                         t->tsnap.status |=  POINT_INIT;
924                 }
925                 else {
926                         t->tsnap.status &= ~POINT_INIT;
927                 }
928         }
929         else if (t->spacetype == SPACE_IMAGE && t->obedit != NULL && t->obedit->type == OB_MESH) {
930                 /* same as above but for UV's */
931                 Image *ima = ED_space_image(t->sa->spacedata.first);
932                 float aspx, aspy, co[2];
933                 
934                 UI_view2d_region_to_view(&t->ar->v2d, t->mval[0], t->mval[1], co, co + 1);
935
936                 if (ED_uvedit_nearest_uv(t->scene, t->obedit, ima, co, t->tsnap.snapPoint)) {
937                         ED_space_image_get_uv_aspect(t->sa->spacedata.first, &aspx, &aspy);
938                         t->tsnap.snapPoint[0] *= aspx;
939                         t->tsnap.snapPoint[1] *= aspy;
940
941                         t->tsnap.status |=  POINT_INIT;
942                 }
943                 else {
944                         t->tsnap.status &= ~POINT_INIT;
945                 }
946         }
947         else if (t->spacetype == SPACE_NODE) {
948                 float loc[2];
949                 int dist = SNAP_MIN_DISTANCE; // Use a user defined value here
950                 char node_border;
951                 
952                 if (snapNodesTransform(t, t->mval, &dist, loc, &node_border, t->tsnap.modeSelect)) {
953                         copy_v2_v2(t->tsnap.snapPoint, loc);
954                         t->tsnap.snapNodeBorder = node_border;
955                         
956                         t->tsnap.status |=  POINT_INIT;
957                 }
958                 else {
959                         t->tsnap.status &= ~POINT_INIT;
960                 }
961         }
962 }
963
964 /********************** TARGET **************************/
965
966 static void TargetSnapOffset(TransInfo *t, TransData *td)
967 {
968         if (t->spacetype == SPACE_NODE && td != NULL) {
969                 bNode *node = td->extra;
970                 char border = t->tsnap.snapNodeBorder;
971                 float width  = BLI_rctf_size_x(&node->totr);
972                 float height = BLI_rctf_size_y(&node->totr);
973                 
974                 if (border & NODE_LEFT)
975                         t->tsnap.snapTarget[0] -= 0.5f * width;
976                 if (border & NODE_RIGHT)
977                         t->tsnap.snapTarget[0] += 0.5f * width;
978                 if (border & NODE_BOTTOM)
979                         t->tsnap.snapTarget[1] -= 0.5f * height;
980                 if (border & NODE_TOP)
981                         t->tsnap.snapTarget[1] += 0.5f * height;
982         }
983 }
984
985 static void TargetSnapCenter(TransInfo *t)
986 {
987         /* Only need to calculate once */
988         if ((t->tsnap.status & TARGET_INIT) == 0) {
989                 copy_v3_v3(t->tsnap.snapTarget, t->center);
990                 
991                 if (t->flag & (T_EDIT | T_POSE)) {
992                         Object *ob = t->obedit ? t->obedit : t->poseobj;
993                         mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
994                 }
995                 
996                 TargetSnapOffset(t, NULL);
997                 
998                 t->tsnap.status |= TARGET_INIT;
999         }
1000 }
1001
1002 static void TargetSnapActive(TransInfo *t)
1003 {
1004         /* Only need to calculate once */
1005         if ((t->tsnap.status & TARGET_INIT) == 0) {
1006                 TransData *td = NULL;
1007                 TransData *active_td = NULL;
1008                 int i;
1009
1010                 for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1011                         if (td->flag & TD_ACTIVE) {
1012                                 active_td = td;
1013                                 break;
1014                         }
1015                 }
1016
1017                 if (active_td) {
1018                         copy_v3_v3(t->tsnap.snapTarget, active_td->center);
1019                         
1020                         if (t->flag & (T_EDIT | T_POSE)) {
1021                                 Object *ob = t->obedit ? t->obedit : t->poseobj;
1022                                 mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
1023                         }
1024                         
1025                         TargetSnapOffset(t, active_td);
1026                         
1027                         t->tsnap.status |= TARGET_INIT;
1028                 }
1029                 /* No active, default to median */
1030                 else {
1031                         t->tsnap.target = SCE_SNAP_TARGET_MEDIAN;
1032                         t->tsnap.targetSnap = TargetSnapMedian;
1033                         TargetSnapMedian(t);
1034                 }
1035         }
1036 }
1037
1038 static void TargetSnapMedian(TransInfo *t)
1039 {
1040         // Only need to calculate once
1041         if ((t->tsnap.status & TARGET_INIT) == 0) {
1042                 TransData *td = NULL;
1043                 int i;
1044
1045                 t->tsnap.snapTarget[0] = 0;
1046                 t->tsnap.snapTarget[1] = 0;
1047                 t->tsnap.snapTarget[2] = 0;
1048                 
1049                 for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1050                         add_v3_v3(t->tsnap.snapTarget, td->center);
1051                 }
1052                 
1053                 mul_v3_fl(t->tsnap.snapTarget, 1.0 / i);
1054                 
1055                 if (t->flag & (T_EDIT | T_POSE)) {
1056                         Object *ob = t->obedit ? t->obedit : t->poseobj;
1057                         mul_m4_v3(ob->obmat, t->tsnap.snapTarget);
1058                 }
1059                 
1060                 TargetSnapOffset(t, NULL);
1061                 
1062                 t->tsnap.status |= TARGET_INIT;
1063         }
1064 }
1065
1066 static void TargetSnapClosest(TransInfo *t)
1067 {
1068         // Only valid if a snap point has been selected
1069         if (t->tsnap.status & POINT_INIT) {
1070                 TransData *closest = NULL, *td = NULL;
1071                 
1072                 /* Object mode */
1073                 if (t->flag & T_OBJECT) {
1074                         int i;
1075                         for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1076                                 struct BoundBox *bb = BKE_object_boundbox_get(td->ob);
1077                                 
1078                                 /* use boundbox if possible */
1079                                 if (bb) {
1080                                         int j;
1081                                         
1082                                         for (j = 0; j < 8; j++) {
1083                                                 float loc[3];
1084                                                 float dist;
1085                                                 
1086                                                 copy_v3_v3(loc, bb->vec[j]);
1087                                                 mul_m4_v3(td->ext->obmat, loc);
1088                                                 
1089                                                 dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1090                                                 
1091                                                 if (closest == NULL || fabsf(dist) < fabsf(t->tsnap.dist)) {
1092                                                         copy_v3_v3(t->tsnap.snapTarget, loc);
1093                                                         closest = td;
1094                                                         t->tsnap.dist = dist; 
1095                                                 }
1096                                         }
1097                                 }
1098                                 /* use element center otherwise */
1099                                 else {
1100                                         float loc[3];
1101                                         float dist;
1102                                         
1103                                         copy_v3_v3(loc, td->center);
1104                                         
1105                                         dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1106                                         
1107                                         if (closest == NULL || fabsf(dist) < fabsf(t->tsnap.dist)) {
1108                                                 copy_v3_v3(t->tsnap.snapTarget, loc);
1109                                                 closest = td;
1110                                                 t->tsnap.dist = dist; 
1111                                         }
1112                                 }
1113                         }
1114                 }
1115                 else {
1116                         int i;
1117                         for (td = t->data, i = 0; i < t->total && td->flag & TD_SELECTED; i++, td++) {
1118                                 float loc[3];
1119                                 float dist;
1120                                 
1121                                 copy_v3_v3(loc, td->center);
1122                                 
1123                                 if (t->flag & (T_EDIT | T_POSE)) {
1124                                         Object *ob = t->obedit ? t->obedit : t->poseobj;
1125                                         mul_m4_v3(ob->obmat, loc);
1126                                 }
1127                                 
1128                                 dist = t->tsnap.distance(t, loc, t->tsnap.snapPoint);
1129                                 
1130                                 if (closest == NULL || fabsf(dist) < fabsf(t->tsnap.dist)) {
1131                                         copy_v3_v3(t->tsnap.snapTarget, loc);
1132                                         closest = td;
1133                                         t->tsnap.dist = dist; 
1134                                 }
1135                         }
1136                 }
1137                 
1138                 TargetSnapOffset(t, closest);
1139                 
1140                 t->tsnap.status |= TARGET_INIT;
1141         }
1142 }
1143
1144 static int snapEdge(ARegion *ar, float v1co[3], short v1no[3], float v2co[3], short v2no[3], float obmat[][4], float timat[][3],
1145                     const float ray_start[3], const float ray_start_local[3], const float ray_normal_local[3], const float mval[2],
1146                     float r_loc[3], float r_no[3], int *r_dist, float *r_depth)
1147 {
1148         float intersect[3] = {0, 0, 0}, ray_end[3], dvec[3];
1149         int result;
1150         int retval = 0;
1151         
1152         copy_v3_v3(ray_end, ray_normal_local);
1153         mul_v3_fl(ray_end, 2000);
1154         add_v3_v3v3(ray_end, ray_start_local, ray_end);
1155         
1156         result = isect_line_line_v3(v1co, v2co, ray_start_local, ray_end, intersect, dvec); /* dvec used but we don't care about result */
1157         
1158         if (result) {
1159                 float edge_loc[3], vec[3];
1160                 float mul;
1161         
1162                 /* check for behind ray_start */
1163                 sub_v3_v3v3(dvec, intersect, ray_start_local);
1164                 
1165                 sub_v3_v3v3(edge_loc, v1co, v2co);
1166                 sub_v3_v3v3(vec, intersect, v2co);
1167                 
1168                 mul = dot_v3v3(vec, edge_loc) / dot_v3v3(edge_loc, edge_loc);
1169                 
1170                 if (mul > 1) {
1171                         mul = 1;
1172                         copy_v3_v3(intersect, v1co);
1173                 }
1174                 else if (mul < 0) {
1175                         mul = 0;
1176                         copy_v3_v3(intersect, v2co);
1177                 }
1178
1179                 if (dot_v3v3(ray_normal_local, dvec) > 0) {
1180                         float location[3];
1181                         float new_depth;
1182                         int screen_loc[2];
1183                         int new_dist;
1184                         
1185                         copy_v3_v3(location, intersect);
1186                         
1187                         mul_m4_v3(obmat, location);
1188                         
1189                         new_depth = len_v3v3(location, ray_start);
1190                         
1191                         if (ED_view3d_project_int_global(ar, location, screen_loc, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1192                                 new_dist = abs(screen_loc[0] - (int)mval[0]) + abs(screen_loc[1] - (int)mval[1]);
1193                         }
1194                         else {
1195                                 new_dist = TRANSFORM_DIST_MAX_PX;
1196                         }
1197                         
1198                         /* 10% threshold if edge is closer but a bit further
1199                          * this takes care of series of connected edges a bit slanted w.r.t the viewport
1200                          * otherwise, it would stick to the verts of the closest edge and not slide along merrily 
1201                          * */
1202                         if (new_dist <= *r_dist && new_depth < *r_depth * 1.001f) {
1203                                 float n1[3], n2[3];
1204                                 
1205                                 *r_depth = new_depth;
1206                                 retval = 1;
1207                                 
1208                                 sub_v3_v3v3(edge_loc, v1co, v2co);
1209                                 sub_v3_v3v3(vec, intersect, v2co);
1210                                 
1211                                 mul = dot_v3v3(vec, edge_loc) / dot_v3v3(edge_loc, edge_loc);
1212                                 
1213                                 if (r_no) {
1214                                         normal_short_to_float_v3(n1, v1no);
1215                                         normal_short_to_float_v3(n2, v2no);
1216                                         interp_v3_v3v3(r_no, n2, n1, mul);
1217                                         mul_m3_v3(timat, r_no);
1218                                         normalize_v3(r_no);
1219                                 }
1220
1221                                 copy_v3_v3(r_loc, location);
1222                                 
1223                                 *r_dist = new_dist;
1224                         }
1225                 }
1226         }
1227         
1228         return retval;
1229 }
1230
1231 static int snapVertex(ARegion *ar, float vco[3], short vno[3], float obmat[][4], float timat[][3],
1232                       const float ray_start[3], const float ray_start_local[3], const float ray_normal_local[3], const float mval[2],
1233                       float r_loc[3], float r_no[3], int *r_dist, float *r_depth)
1234 {
1235         int retval = 0;
1236         float dvec[3];
1237         
1238         sub_v3_v3v3(dvec, vco, ray_start_local);
1239         
1240         if (dot_v3v3(ray_normal_local, dvec) > 0) {
1241                 float location[3];
1242                 float new_depth;
1243                 int screen_loc[2];
1244                 int new_dist;
1245                 
1246                 copy_v3_v3(location, vco);
1247                 
1248                 mul_m4_v3(obmat, location);
1249                 
1250                 new_depth = len_v3v3(location, ray_start);
1251                 
1252                 if (ED_view3d_project_int_global(ar, location, screen_loc, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1253                         new_dist = abs(screen_loc[0] - (int)mval[0]) + abs(screen_loc[1] - (int)mval[1]);
1254                 }
1255                 else {
1256                         new_dist = TRANSFORM_DIST_MAX_PX;
1257                 }
1258
1259                 
1260                 if (new_dist <= *r_dist && new_depth < *r_depth) {
1261                         *r_depth = new_depth;
1262                         retval = 1;
1263                         
1264                         copy_v3_v3(r_loc, location);
1265                         
1266                         if (r_no) {
1267                                 normal_short_to_float_v3(r_no, vno);
1268                                 mul_m3_v3(timat, r_no);
1269                                 normalize_v3(r_no);
1270                         }
1271
1272                         *r_dist = new_dist;
1273                 }
1274         }
1275         
1276         return retval;
1277 }
1278
1279 static int snapArmature(short snap_mode, ARegion *ar, Object *ob, bArmature *arm, float obmat[][4],
1280                         const float ray_start[3], const float ray_normal[3], const float mval[2],
1281                         float r_loc[3], float *UNUSED(r_no), int *r_dist, float *r_depth)
1282 {
1283         float imat[4][4];
1284         float ray_start_local[3], ray_normal_local[3];
1285         int retval = 0;
1286
1287         invert_m4_m4(imat, obmat);
1288
1289         copy_v3_v3(ray_start_local, ray_start);
1290         copy_v3_v3(ray_normal_local, ray_normal);
1291         
1292         mul_m4_v3(imat, ray_start_local);
1293         mul_mat3_m4_v3(imat, ray_normal_local);
1294
1295         if (arm->edbo) {
1296                 EditBone *eBone;
1297
1298                 for (eBone = arm->edbo->first; eBone; eBone = eBone->next) {
1299                         if (eBone->layer & arm->layer) {
1300                                 /* skip hidden or moving (selected) bones */
1301                                 if ((eBone->flag & (BONE_HIDDEN_A | BONE_ROOTSEL | BONE_TIPSEL)) == 0) {
1302                                         switch (snap_mode) {
1303                                                 case SCE_SNAP_MODE_VERTEX:
1304                                                         retval |= snapVertex(ar, eBone->head, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist, r_depth);
1305                                                         retval |= snapVertex(ar, eBone->tail, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist, r_depth);
1306                                                         break;
1307                                                 case SCE_SNAP_MODE_EDGE:
1308                                                         retval |= snapEdge(ar, eBone->head, NULL, eBone->tail, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist, r_depth);
1309                                                         break;
1310                                         }
1311                                 }
1312                         }
1313                 }
1314         }
1315         else if (ob->pose && ob->pose->chanbase.first) {
1316                 bPoseChannel *pchan;
1317                 Bone *bone;
1318                 
1319                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1320                         bone = pchan->bone;
1321                         /* skip hidden bones */
1322                         if (bone && !(bone->flag & (BONE_HIDDEN_P | BONE_HIDDEN_PG))) {
1323                                 float *head_vec = pchan->pose_head;
1324                                 float *tail_vec = pchan->pose_tail;
1325                                 
1326                                 switch (snap_mode) {
1327                                         case SCE_SNAP_MODE_VERTEX:
1328                                                 retval |= snapVertex(ar, head_vec, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist, r_depth);
1329                                                 retval |= snapVertex(ar, tail_vec, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist, r_depth);
1330                                                 break;
1331                                         case SCE_SNAP_MODE_EDGE:
1332                                                 retval |= snapEdge(ar, head_vec, NULL, tail_vec, NULL, obmat, NULL, ray_start, ray_start_local, ray_normal_local, mval, r_loc, NULL, r_dist, r_depth);
1333                                                 break;
1334                                 }
1335                         }
1336                 }
1337         }
1338
1339         return retval;
1340 }
1341
1342 static int snapDerivedMesh(short snap_mode, ARegion *ar, Object *ob, DerivedMesh *dm, BMEditMesh *em, float obmat[][4],
1343                            const float ray_start[3], const float ray_normal[3], const float mval[2],
1344                            float r_loc[3], float r_no[3], int *r_dist, float *r_depth)
1345 {
1346         int retval = 0;
1347         int totvert = dm->getNumVerts(dm);
1348         int totface = dm->getNumTessFaces(dm);
1349
1350         if (totvert > 0) {
1351                 float imat[4][4];
1352                 float timat[3][3]; /* transpose inverse matrix for normals */
1353                 float ray_start_local[3], ray_normal_local[3];
1354                 int test = 1;
1355
1356                 invert_m4_m4(imat, obmat);
1357
1358                 copy_m3_m4(timat, imat);
1359                 transpose_m3(timat);
1360                 
1361                 copy_v3_v3(ray_start_local, ray_start);
1362                 copy_v3_v3(ray_normal_local, ray_normal);
1363                 
1364                 mul_m4_v3(imat, ray_start_local);
1365                 mul_mat3_m4_v3(imat, ray_normal_local);
1366                 
1367                 
1368                 /* If number of vert is more than an arbitrary limit, 
1369                  * test against boundbox first
1370                  * */
1371                 if (totface > 16) {
1372                         struct BoundBox *bb = BKE_object_boundbox_get(ob);
1373                         test = BKE_boundbox_ray_hit_check(bb, ray_start_local, ray_normal_local);
1374                 }
1375                 
1376                 if (test == 1) {
1377                         
1378                         switch (snap_mode) {
1379                                 case SCE_SNAP_MODE_FACE:
1380                                 {
1381                                         BVHTreeRayHit hit;
1382                                         BVHTreeFromMesh treeData;
1383
1384                                         /* local scale in normal direction */
1385                                         float local_scale = len_v3(ray_normal_local);
1386
1387                                         treeData.em_evil = em;
1388                                         bvhtree_from_mesh_faces(&treeData, dm, 0.0f, 4, 6);
1389
1390                                         hit.index = -1;
1391                                         hit.dist = *r_depth * (*r_depth == FLT_MAX ? 1.0f : local_scale);
1392
1393                                         if (treeData.tree && BLI_bvhtree_ray_cast(treeData.tree, ray_start_local, ray_normal_local, 0.0f, &hit, treeData.raycast_callback, &treeData) != -1) {
1394                                                 if (hit.dist / local_scale <= *r_depth) {
1395                                                         *r_depth = hit.dist / local_scale;
1396                                                         copy_v3_v3(r_loc, hit.co);
1397                                                         copy_v3_v3(r_no, hit.no);
1398
1399                                                         /* back to worldspace */
1400                                                         mul_m4_v3(obmat, r_loc);
1401                                                         copy_v3_v3(r_no, hit.no);
1402
1403                                                         mul_m3_v3(timat, r_no);
1404                                                         normalize_v3(r_no);
1405
1406                                                         retval |= 1;
1407                                                 }
1408                                         }
1409                                         break;
1410                                 }
1411                                 case SCE_SNAP_MODE_VERTEX:
1412                                 {
1413                                         MVert *verts = dm->getVertArray(dm);
1414                                         int *index_array = NULL;
1415                                         int index = 0;
1416                                         int i;
1417                                         
1418                                         if (em != NULL) {
1419                                                 index_array = dm->getVertDataArray(dm, CD_ORIGINDEX);
1420                                                 EDBM_index_arrays_init(em, 1, 0, 0);
1421                                         }
1422                                         
1423                                         for (i = 0; i < totvert; i++) {
1424                                                 BMVert *eve = NULL;
1425                                                 MVert *v = verts + i;
1426                                                 
1427                                                 test = 1; /* reset for every vert */
1428                                         
1429                                                 if (em != NULL) {
1430                                                         if (index_array) {
1431                                                                 index = index_array[i];
1432                                                         }
1433                                                         else {
1434                                                                 index = i;
1435                                                         }
1436                                                         
1437                                                         if (index == ORIGINDEX_NONE) {
1438                                                                 test = 0;
1439                                                         }
1440                                                         else {
1441                                                                 eve = EDBM_vert_at_index(em, index);
1442                                                                 
1443                                                                 if (eve && (BM_elem_flag_test(eve, BM_ELEM_HIDDEN) || BM_elem_flag_test(eve, BM_ELEM_SELECT))) {
1444                                                                         test = 0;
1445                                                                 }
1446                                                         }
1447                                                 }
1448                                                 
1449                                                 
1450                                                 if (test) {
1451                                                         retval |= snapVertex(ar, v->co, v->no, obmat, timat, ray_start, ray_start_local, ray_normal_local, mval, r_loc, r_no, r_dist, r_depth);
1452                                                 }
1453                                         }
1454
1455                                         if (em != NULL) {
1456                                                 EDBM_index_arrays_free(em);
1457                                         }
1458                                         break;
1459                                 }
1460                                 case SCE_SNAP_MODE_EDGE:
1461                                 {
1462                                         MVert *verts = dm->getVertArray(dm);
1463                                         MEdge *edges = dm->getEdgeArray(dm);
1464                                         int totedge = dm->getNumEdges(dm);
1465                                         int *index_array = NULL;
1466                                         int index = 0;
1467                                         int i;
1468                                         
1469                                         if (em != NULL) {
1470                                                 index_array = dm->getEdgeDataArray(dm, CD_ORIGINDEX);
1471                                                 EDBM_index_arrays_init(em, 0, 1, 0);
1472                                         }
1473                                         
1474                                         for (i = 0; i < totedge; i++) {
1475                                                 BMEdge *eed = NULL;
1476                                                 MEdge *e = edges + i;
1477                                                 
1478                                                 test = 1; /* reset for every vert */
1479                                         
1480                                                 if (em != NULL) {
1481                                                         if (index_array) {
1482                                                                 index = index_array[i];
1483                                                         }
1484                                                         else {
1485                                                                 index = i;
1486                                                         }
1487                                                         
1488                                                         if (index == ORIGINDEX_NONE) {
1489                                                                 test = 0;
1490                                                         }
1491                                                         else {
1492                                                                 eed = EDBM_edge_at_index(em, index);
1493                                                                 
1494                                                                 if (eed && (BM_elem_flag_test(eed, BM_ELEM_HIDDEN) ||
1495                                                                             BM_elem_flag_test(eed->v1, BM_ELEM_SELECT) ||
1496                                                                             BM_elem_flag_test(eed->v2, BM_ELEM_SELECT)))
1497                                                                 {
1498                                                                         test = 0;
1499                                                                 }
1500                                                         }
1501                                                 }
1502
1503                                                 if (test) {
1504                                                         retval |= snapEdge(ar, verts[e->v1].co, verts[e->v1].no, verts[e->v2].co, verts[e->v2].no, obmat, timat, ray_start, ray_start_local, ray_normal_local, mval, r_loc, r_no, r_dist, r_depth);
1505                                                 }
1506                                         }
1507
1508                                         if (em != NULL) {
1509                                                 EDBM_index_arrays_free(em);
1510                                         }
1511                                         break;
1512                                 }
1513                         }
1514                 }
1515         }
1516
1517         return retval;
1518
1519
1520 static int snapObject(Scene *scene, ARegion *ar, Object *ob, int editobject, float obmat[][4],
1521                       const float ray_start[3], const float ray_normal[3], const float mval[2],
1522                       float r_loc[3], float r_no[3], int *r_dist, float *r_depth)
1523 {
1524         ToolSettings *ts = scene->toolsettings;
1525         int retval = 0;
1526         
1527         if (ob->type == OB_MESH) {
1528                 BMEditMesh *em;
1529                 DerivedMesh *dm;
1530                 
1531                 if (editobject) {
1532                         em = BMEdit_FromObject(ob);
1533                         /* dm = editbmesh_get_derived_cage(scene, ob, em, CD_MASK_BAREMESH); */
1534                         dm = editbmesh_get_derived_base(ob, em); /* limitation, em & dm MUST have the same number of faces */
1535                 }
1536                 else {
1537                         em = NULL;
1538                         dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
1539                 }
1540                 
1541                 retval = snapDerivedMesh(ts->snap_mode, ar, ob, dm, em, obmat, ray_start, ray_normal, mval, r_loc, r_no, r_dist, r_depth);
1542
1543                 dm->release(dm);
1544         }
1545         else if (ob->type == OB_ARMATURE) {
1546                 retval = snapArmature(ts->snap_mode, ar, ob, ob->data, obmat, ray_start, ray_normal, mval, r_loc, r_no, r_dist, r_depth);
1547         }
1548         
1549         return retval;
1550 }
1551
1552 static int snapObjects(Scene *scene, View3D *v3d, ARegion *ar, Object *obedit, const float mval[2],
1553                        int *r_dist, float r_loc[3], float r_no[3], SnapMode mode)
1554 {
1555         Base *base;
1556         float depth = FLT_MAX;
1557         int retval = 0;
1558         float ray_start[3], ray_normal[3];
1559         
1560         ED_view3d_win_to_ray(ar, v3d, mval, ray_start, ray_normal);
1561
1562         if (mode == SNAP_ALL && obedit) {
1563                 Object *ob = obedit;
1564
1565                 retval |= snapObject(scene, ar, ob, 1, ob->obmat, ray_start, ray_normal, mval, r_loc, r_no, r_dist, &depth);
1566         }
1567
1568         /* Need an exception for particle edit because the base is flagged with BA_HAS_RECALC_DATA
1569          * which makes the loop skip it, even the derived mesh will never change
1570          *
1571          * To solve that problem, we do it first as an exception. 
1572          * */
1573         base = BASACT;
1574         if (base && base->object && base->object->mode & OB_MODE_PARTICLE_EDIT) {
1575                 Object *ob = base->object;
1576                 retval |= snapObject(scene, ar, ob, 0, ob->obmat, ray_start, ray_normal, mval, r_loc, r_no, r_dist, &depth);
1577         }
1578
1579         for (base = FIRSTBASE; base != NULL; base = base->next) {
1580                 if ((BASE_VISIBLE(v3d, base)) &&
1581                     (base->flag & (BA_HAS_RECALC_OB | BA_HAS_RECALC_DATA)) == 0 &&
1582
1583                     ((mode == SNAP_NOT_SELECTED && (base->flag & (SELECT | BA_WAS_SEL)) == 0) ||
1584                      (ELEM(mode, SNAP_ALL, SNAP_NOT_OBEDIT) && base != BASACT)))
1585                 {
1586                         Object *ob = base->object;
1587                         
1588                         if (ob->transflag & OB_DUPLI) {
1589                                 DupliObject *dupli_ob;
1590                                 ListBase *lb = object_duplilist(scene, ob, FALSE);
1591                                 
1592                                 for (dupli_ob = lb->first; dupli_ob; dupli_ob = dupli_ob->next) {
1593                                         Object *dob = dupli_ob->ob;
1594                                         
1595                                         retval |= snapObject(scene, ar, dob, 0, dupli_ob->mat, ray_start, ray_normal, mval, r_loc, r_no, r_dist, &depth);
1596                                 }
1597                                 
1598                                 free_object_duplilist(lb);
1599                         }
1600                         
1601                         retval |= snapObject(scene, ar, ob, 0, ob->obmat, ray_start, ray_normal, mval, r_loc, r_no, r_dist, &depth);
1602                 }
1603         }
1604         
1605         return retval;
1606 }
1607
1608 int snapObjectsTransform(TransInfo *t, const float mval[2], int *r_dist, float r_loc[3], float r_no[3], SnapMode mode)
1609 {
1610         return snapObjects(t->scene, t->view, t->ar, t->obedit, mval, r_dist, r_loc, r_no, mode);
1611 }
1612
1613 int snapObjectsContext(bContext *C, const float mval[2], int *r_dist, float r_loc[3], float r_no[3], SnapMode mode)
1614 {
1615         ScrArea *sa = CTX_wm_area(C);
1616         View3D *v3d = sa->spacedata.first;
1617
1618         return snapObjects(CTX_data_scene(C), v3d, CTX_wm_region(C), CTX_data_edit_object(C), mval, r_dist, r_loc, r_no, mode);
1619 }
1620
1621 /******************** PEELING *********************************/
1622
1623
1624 static int cmpPeel(void *arg1, void *arg2)
1625 {
1626         DepthPeel *p1 = arg1;
1627         DepthPeel *p2 = arg2;
1628         int val = 0;
1629         
1630         if (p1->depth < p2->depth) {
1631                 val = -1;
1632         }
1633         else if (p1->depth > p2->depth) {
1634                 val = 1;
1635         }
1636         
1637         return val;
1638 }
1639
1640 static void removeDoublesPeel(ListBase *depth_peels)
1641 {
1642         DepthPeel *peel;
1643         
1644         for (peel = depth_peels->first; peel; peel = peel->next) {
1645                 DepthPeel *next_peel = peel->next;
1646
1647                 if (next_peel && ABS(peel->depth - next_peel->depth) < 0.0015f) {
1648                         peel->next = next_peel->next;
1649                         
1650                         if (next_peel->next) {
1651                                 next_peel->next->prev = peel;
1652                         }
1653                         
1654                         MEM_freeN(next_peel);
1655                 }
1656         }
1657 }
1658
1659 static void addDepthPeel(ListBase *depth_peels, float depth, float p[3], float no[3], Object *ob)
1660 {
1661         DepthPeel *peel = MEM_callocN(sizeof(DepthPeel), "DepthPeel");
1662         
1663         peel->depth = depth;
1664         peel->ob = ob;
1665         copy_v3_v3(peel->p, p);
1666         copy_v3_v3(peel->no, no);
1667         
1668         BLI_addtail(depth_peels, peel);
1669         
1670         peel->flag = 0;
1671 }
1672
1673 static int peelDerivedMesh(Object *ob, DerivedMesh *dm, float obmat[][4],
1674                            const float ray_start[3], const float ray_normal[3], const float UNUSED(mval[2]),
1675                            ListBase *depth_peels)
1676 {
1677         int retval = 0;
1678         int totvert = dm->getNumVerts(dm);
1679         int totface = dm->getNumTessFaces(dm);
1680         
1681         if (totvert > 0) {
1682                 float imat[4][4];
1683                 float timat[3][3]; /* transpose inverse matrix for normals */
1684                 float ray_start_local[3], ray_normal_local[3];
1685                 int test = 1;
1686
1687                 invert_m4_m4(imat, obmat);
1688
1689                 copy_m3_m4(timat, imat);
1690                 transpose_m3(timat);
1691                 
1692                 copy_v3_v3(ray_start_local, ray_start);
1693                 copy_v3_v3(ray_normal_local, ray_normal);
1694                 
1695                 mul_m4_v3(imat, ray_start_local);
1696                 mul_mat3_m4_v3(imat, ray_normal_local);
1697                 
1698                 
1699                 /* If number of vert is more than an arbitrary limit, 
1700                  * test against boundbox first
1701                  * */
1702                 if (totface > 16) {
1703                         struct BoundBox *bb = BKE_object_boundbox_get(ob);
1704                         test = BKE_boundbox_ray_hit_check(bb, ray_start_local, ray_normal_local);
1705                 }
1706                 
1707                 if (test == 1) {
1708                         MVert *verts = dm->getVertArray(dm);
1709                         MFace *faces = dm->getTessFaceArray(dm);
1710                         int i;
1711                         
1712                         for (i = 0; i < totface; i++) {
1713                                 MFace *f = faces + i;
1714                                 float lambda;
1715                                 int result;
1716                                 
1717                                 
1718                                 result = isect_ray_tri_threshold_v3(ray_start_local, ray_normal_local, verts[f->v1].co, verts[f->v2].co, verts[f->v3].co, &lambda, NULL, 0.001);
1719                                 
1720                                 if (result) {
1721                                         float location[3], normal[3];
1722                                         float intersect[3];
1723                                         float new_depth;
1724                                         
1725                                         copy_v3_v3(intersect, ray_normal_local);
1726                                         mul_v3_fl(intersect, lambda);
1727                                         add_v3_v3(intersect, ray_start_local);
1728                                         
1729                                         copy_v3_v3(location, intersect);
1730                                         
1731                                         if (f->v4)
1732                                                 normal_quad_v3(normal, verts[f->v1].co, verts[f->v2].co, verts[f->v3].co, verts[f->v4].co);
1733                                         else
1734                                                 normal_tri_v3(normal, verts[f->v1].co, verts[f->v2].co, verts[f->v3].co);
1735
1736                                         mul_m4_v3(obmat, location);
1737                                         
1738                                         new_depth = len_v3v3(location, ray_start);
1739                                         
1740                                         mul_m3_v3(timat, normal);
1741                                         normalize_v3(normal);
1742
1743                                         addDepthPeel(depth_peels, new_depth, location, normal, ob);
1744                                 }
1745                 
1746                                 if (f->v4 && result == 0) {
1747                                         result = isect_ray_tri_threshold_v3(ray_start_local, ray_normal_local, verts[f->v3].co, verts[f->v4].co, verts[f->v1].co, &lambda, NULL, 0.001);
1748                                         
1749                                         if (result) {
1750                                                 float location[3], normal[3];
1751                                                 float intersect[3];
1752                                                 float new_depth;
1753                                                 
1754                                                 copy_v3_v3(intersect, ray_normal_local);
1755                                                 mul_v3_fl(intersect, lambda);
1756                                                 add_v3_v3(intersect, ray_start_local);
1757                                                 
1758                                                 copy_v3_v3(location, intersect);
1759                                                 
1760                                                 if (f->v4)
1761                                                         normal_quad_v3(normal, verts[f->v1].co, verts[f->v2].co, verts[f->v3].co, verts[f->v4].co);
1762                                                 else
1763                                                         normal_tri_v3(normal, verts[f->v1].co, verts[f->v2].co, verts[f->v3].co);
1764
1765                                                 mul_m4_v3(obmat, location);
1766                                                 
1767                                                 new_depth = len_v3v3(location, ray_start);
1768                                                 
1769                                                 mul_m3_v3(timat, normal);
1770                                                 normalize_v3(normal);
1771         
1772                                                 addDepthPeel(depth_peels, new_depth, location, normal, ob);
1773                                         }
1774                                 }
1775                         }
1776                 }
1777         }
1778
1779         return retval;
1780
1781
1782 static int peelObjects(Scene *scene, View3D *v3d, ARegion *ar, Object *obedit, ListBase *depth_peels, const float mval[2], SnapMode mode)
1783 {
1784         Base *base;
1785         int retval = 0;
1786         float ray_start[3], ray_normal[3];
1787         
1788         ED_view3d_win_to_ray(ar, v3d, mval, ray_start, ray_normal);
1789
1790         for (base = scene->base.first; base != NULL; base = base->next) {
1791                 if (BASE_SELECTABLE(v3d, base)) {
1792                         Object *ob = base->object;
1793
1794                         if (ob->transflag & OB_DUPLI) {
1795                                 DupliObject *dupli_ob;
1796                                 ListBase *lb = object_duplilist(scene, ob, FALSE);
1797                                 
1798                                 for (dupli_ob = lb->first; dupli_ob; dupli_ob = dupli_ob->next) {
1799                                         Object *dob = dupli_ob->ob;
1800                                         
1801                                         if (dob->type == OB_MESH) {
1802                                                 BMEditMesh *em;
1803                                                 DerivedMesh *dm = NULL;
1804                                                 int val;
1805
1806                                                 if (dob != obedit) {
1807                                                         dm = mesh_get_derived_final(scene, dob, CD_MASK_BAREMESH);
1808                                                         
1809                                                         val = peelDerivedMesh(dob, dm, dob->obmat, ray_start, ray_normal, mval, depth_peels);
1810                                                 }
1811                                                 else {
1812                                                         em = BMEdit_FromObject(dob);
1813                                                         dm = editbmesh_get_derived_cage(scene, obedit, em, CD_MASK_BAREMESH);
1814                                                         
1815                                                         val = peelDerivedMesh(dob, dm, dob->obmat, ray_start, ray_normal, mval, depth_peels);
1816                                                 }
1817
1818                                                 retval = retval || val;
1819                                                 
1820                                                 dm->release(dm);
1821                                         }
1822                                 }
1823                                 
1824                                 free_object_duplilist(lb);
1825                         }
1826                         
1827                         if (ob->type == OB_MESH) {
1828                                 int val = 0;
1829
1830                                 if (ob != obedit && ((mode == SNAP_NOT_SELECTED && (base->flag & (SELECT | BA_WAS_SEL)) == 0) || ELEM(mode, SNAP_ALL, SNAP_NOT_OBEDIT))) {
1831                                         DerivedMesh *dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
1832                                         
1833                                         val = peelDerivedMesh(ob, dm, ob->obmat, ray_start, ray_normal, mval, depth_peels);
1834                                         dm->release(dm);
1835                                 }
1836                                 else if (ob == obedit && mode != SNAP_NOT_OBEDIT) {
1837                                         BMEditMesh *em = BMEdit_FromObject(ob);
1838                                         DerivedMesh *dm = editbmesh_get_derived_cage(scene, obedit, em, CD_MASK_BAREMESH);
1839                                         
1840                                         val = peelDerivedMesh(ob, dm, ob->obmat, ray_start, ray_normal, mval, depth_peels);
1841                                         dm->release(dm);
1842                                 }
1843                                         
1844                                 retval = retval || val;
1845                                 
1846                         }
1847                 }
1848         }
1849         
1850         BLI_sortlist(depth_peels, cmpPeel);
1851         removeDoublesPeel(depth_peels);
1852         
1853         return retval;
1854 }
1855
1856 int peelObjectsTransForm(TransInfo *t, ListBase *depth_peels, const float mval[2], SnapMode mode)
1857 {
1858         return peelObjects(t->scene, t->view, t->ar, t->obedit, depth_peels, mval, mode);
1859 }
1860
1861 int peelObjectsContext(bContext *C, ListBase *depth_peels, const float mval[2], SnapMode mode)
1862 {
1863         ScrArea *sa = CTX_wm_area(C);
1864         View3D *v3d = sa->spacedata.first;
1865
1866         return peelObjects(CTX_data_scene(C), v3d, CTX_wm_region(C), CTX_data_edit_object(C), depth_peels, mval, mode);
1867 }
1868
1869 /******************** NODES ***********************************/
1870
1871 static int snapNodeTest(View2D *v2d, bNode *node, SnapMode mode)
1872 {
1873         /* node is use for snapping only if a) snap mode matches and b) node is inside the view */
1874         return ((mode == SNAP_NOT_SELECTED && !(node->flag & NODE_SELECT)) ||
1875                 (mode == SNAP_ALL && !(node->flag & NODE_ACTIVE))) &&
1876                 (node->totr.xmin < v2d->cur.xmax && node->totr.xmax > v2d->cur.xmin &&
1877                  node->totr.ymin < v2d->cur.ymax && node->totr.ymax > v2d->cur.ymin);
1878 }
1879
1880 static NodeBorder snapNodeBorder(int snap_node_mode)
1881 {
1882         switch (snap_node_mode) {
1883                 case SCE_SNAP_MODE_NODE_X:
1884                         return NODE_LEFT | NODE_RIGHT;
1885                 case SCE_SNAP_MODE_NODE_Y:
1886                         return NODE_TOP | NODE_BOTTOM;
1887                 case SCE_SNAP_MODE_NODE_XY:
1888                         return NODE_LEFT | NODE_RIGHT | NODE_TOP | NODE_BOTTOM;
1889         }
1890         return 0;
1891 }
1892
1893 static int snapNode(ToolSettings *ts, SpaceNode *UNUSED(snode), ARegion *ar, bNode *node, const int mval[2],
1894                     float r_loc[2], int *r_dist, char *r_node_border)
1895 {
1896         View2D *v2d = &ar->v2d;
1897         NodeBorder border = snapNodeBorder(ts->snap_node_mode);
1898         int retval = 0;
1899         rcti totr;
1900         int new_dist;
1901         
1902         UI_view2d_to_region_no_clip(v2d, node->totr.xmin, node->totr.ymin, &totr.xmin, &totr.ymin);
1903         UI_view2d_to_region_no_clip(v2d, node->totr.xmax, node->totr.ymax, &totr.xmax, &totr.ymax);
1904         
1905         if (border & NODE_LEFT) {
1906                 new_dist = abs(totr.xmin - mval[0]);
1907                 if (new_dist < *r_dist) {
1908                         UI_view2d_region_to_view(v2d, totr.xmin, mval[1], &r_loc[0], &r_loc[1]);
1909                         *r_dist = new_dist;
1910                         *r_node_border = NODE_LEFT;
1911                         retval = 1;
1912                 }
1913         }
1914         
1915         if (border & NODE_RIGHT) {
1916                 new_dist = abs(totr.xmax - mval[0]);
1917                 if (new_dist < *r_dist) {
1918                         UI_view2d_region_to_view(v2d, totr.xmax, mval[1], &r_loc[0], &r_loc[1]);
1919                         *r_dist = new_dist;
1920                         *r_node_border = NODE_RIGHT;
1921                         retval = 1;
1922                 }
1923         }
1924         
1925         if (border & NODE_BOTTOM) {
1926                 new_dist = abs(totr.ymin - mval[1]);
1927                 if (new_dist < *r_dist) {
1928                         UI_view2d_region_to_view(v2d, mval[0], totr.ymin, &r_loc[0], &r_loc[1]);
1929                         *r_dist = new_dist;
1930                         *r_node_border = NODE_BOTTOM;
1931                         retval = 1;
1932                 }
1933         }
1934         
1935         if (border & NODE_TOP) {
1936                 new_dist = abs(totr.ymax - mval[1]);
1937                 if (new_dist < *r_dist) {
1938                         UI_view2d_region_to_view(v2d, mval[0], totr.ymax, &r_loc[0], &r_loc[1]);
1939                         *r_dist = new_dist;
1940                         *r_node_border = NODE_TOP;
1941                         retval = 1;
1942                 }
1943         }
1944         
1945         return retval;
1946 }
1947
1948 static int snapNodes(ToolSettings *ts, SpaceNode *snode, ARegion *ar, const int mval[2],
1949                      int *r_dist, float r_loc[2], char *r_node_border, SnapMode mode)
1950 {
1951         bNodeTree *ntree = snode->edittree;
1952         bNode *node;
1953         int retval = 0;
1954         
1955         *r_node_border = 0;
1956         
1957         for (node = ntree->nodes.first; node; node = node->next) {
1958                 if (snapNodeTest(&ar->v2d, node, mode))
1959                         retval |= snapNode(ts, snode, ar, node, mval, r_loc, r_dist, r_node_border);
1960         }
1961         
1962         return retval;
1963 }
1964
1965 int snapNodesTransform(TransInfo *t, const int mval[2], int *r_dist, float r_loc[2], char *r_node_border, SnapMode mode)
1966 {
1967         return snapNodes(t->settings, t->sa->spacedata.first, t->ar, mval, r_dist, r_loc, r_node_border, mode);
1968 }
1969
1970 int snapNodesContext(bContext *C, const int mval[2], int *r_dist, float r_loc[2], char *r_node_border, SnapMode mode)
1971 {
1972         Scene *scene = CTX_data_scene(C);
1973         return snapNodes(scene->toolsettings, CTX_wm_space_node(C), CTX_wm_region(C), mval, r_dist, r_loc, r_node_border, mode);
1974 }
1975
1976 /*================================================================*/
1977
1978 static void applyGrid(TransInfo *t, float *val, int max_index, float fac[3], GearsType action);
1979
1980
1981 void snapGridAction(TransInfo *t, float *val, GearsType action)
1982 {
1983         float fac[3];
1984
1985         fac[NO_GEARS]    = t->snap[0];
1986         fac[BIG_GEARS]   = t->snap[1];
1987         fac[SMALL_GEARS] = t->snap[2];
1988         
1989         applyGrid(t, val, t->idx_max, fac, action);
1990 }
1991
1992
1993 void snapGrid(TransInfo *t, float *val)
1994 {
1995         GearsType action;
1996
1997         // Only do something if using Snap to Grid
1998         if (t->tsnap.mode != SCE_SNAP_MODE_INCREMENT)
1999                 return;
2000
2001         action = activeSnap(t) ? BIG_GEARS : NO_GEARS;
2002
2003         if (action == BIG_GEARS && (t->modifiers & MOD_PRECISION)) {
2004                 action = SMALL_GEARS;
2005         }
2006
2007         snapGridAction(t, val, action);
2008 }
2009
2010
2011 static void applyGrid(TransInfo *t, float *val, int max_index, float fac[3], GearsType action)
2012 {
2013         int i;
2014         float asp[3] = {1.0f, 1.0f, 1.0f}; // TODO: Remove hard coded limit here (3)
2015
2016         if (max_index > 2) {
2017                 printf("applyGrid: invalid index %d, clamping\n", max_index);
2018                 max_index = 2;
2019         }
2020
2021         // Early bailing out if no need to snap
2022         if (fac[action] == 0.0f)
2023                 return;
2024         
2025         /* evil hack - snapping needs to be adapted for image aspect ratio */
2026         if ((t->spacetype == SPACE_IMAGE) && (t->mode == TFM_TRANSLATION)) {
2027                 if (t->options & CTX_MASK) {
2028                         ED_space_image_get_aspect(t->sa->spacedata.first, asp, asp + 1);
2029                 }
2030                 else {
2031                         ED_space_image_get_uv_aspect(t->sa->spacedata.first, asp, asp + 1);
2032                 }
2033         }
2034
2035         for (i = 0; i <= max_index; i++) {
2036                 val[i] = fac[action] * asp[i] * (float)floor(val[i] / (fac[action] * asp[i]) + 0.5f);
2037         }
2038 }