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