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