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