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