Add snapping parameters to transform operators (only Translation, Resize and Rotation...
[blender.git] / source / blender / editors / transform / transform.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): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <math.h>
34 #include <float.h>
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #ifndef WIN32
41 #include <unistd.h>
42 #else
43 #include <io.h>
44 #endif
45
46 #include "MEM_guardedalloc.h"
47
48 #include "DNA_armature_types.h"
49 #include "DNA_action_types.h"  /* for some special action-editor settings */
50 #include "DNA_constraint_types.h"
51 #include "DNA_ipo_types.h"              /* some silly ipo flag  */
52 #include "DNA_listBase.h"
53 #include "DNA_meshdata_types.h"
54 #include "DNA_mesh_types.h"
55 #include "DNA_object_types.h"
56 #include "DNA_scene_types.h"            /* PET modes                    */
57 #include "DNA_screen_types.h"   /* area dimensions              */
58 #include "DNA_texture_types.h"
59 #include "DNA_userdef_types.h"
60 #include "DNA_view3d_types.h"
61 #include "DNA_space_types.h"
62 #include "DNA_windowmanager_types.h"
63
64 #include "RNA_access.h"
65
66 //#include "BIF_editview.h"             /* arrows_move_cursor   */
67 #include "BIF_gl.h"
68 #include "BIF_glutil.h"
69 //#include "BIF_mywindow.h"
70 //#include "BIF_resources.h"
71 //#include "BIF_screen.h"
72 //#include "BIF_space.h"                        /* undo                                 */
73 //#include "BIF_toets.h"                        /* persptoetsen                 */
74 //#include "BIF_mywindow.h"             /* warp_pointer                 */
75 //#include "BIF_toolbox.h"                      /* notice                               */
76 //#include "BIF_editmesh.h"
77 //#include "BIF_editsima.h"
78 //#include "BIF_editparticle.h"
79 //#include "BIF_editaction.h" 
80
81 #include "BKE_action.h" /* get_action_frame */
82 //#include "BKE_bad_level_calls.h"/* popmenu and error  */
83 #include "BKE_bmesh.h"
84 #include "BKE_context.h"
85 #include "BKE_constraint.h"
86 #include "BKE_global.h"
87 #include "BKE_particle.h"
88 #include "BKE_pointcache.h"
89 #include "BKE_utildefines.h"
90 #include "BKE_context.h"
91
92 //#include "BSE_drawipo.h"
93 //#include "BSE_editnla_types.h"        /* for NLAWIDTH */
94 //#include "BSE_editaction_types.h"
95 //#include "BSE_time.h"
96 //#include "BSE_view.h"
97
98 #include "ED_image.h"
99 #include "ED_screen.h"
100 #include "ED_space_api.h"
101 #include "ED_util.h"
102 #include "ED_view3d.h"
103
104 #include "UI_view2d.h"
105 #include "WM_types.h"
106 #include "WM_api.h"
107
108 #include "BLI_arithb.h"
109 #include "BLI_blenlib.h"
110 #include "BLI_editVert.h"
111
112 #include "PIL_time.h"                   /* sleep                                */
113
114 //#include "blendef.h"
115 //
116 //#include "mydevice.h"
117
118 #include "transform.h"
119
120 /* ************************** Dashed help line **************************** */
121
122
123 /* bad frontbuffer call... because it is used in transform after force_draw() */
124 static void helpline(TransInfo *t, float *vec)
125 {
126 #if 0 // TRANSFORM_FIX_ME
127         float vecrot[3], cent[2];
128         short mval[2];
129         
130         VECCOPY(vecrot, vec);
131         if(t->flag & T_EDIT) {
132                 Object *ob= t->obedit;
133                 if(ob) Mat4MulVecfl(ob->obmat, vecrot);
134         }
135         else if(t->flag & T_POSE) {
136                 Object *ob=t->poseobj;
137                 if(ob) Mat4MulVecfl(ob->obmat, vecrot);
138         }
139         
140         getmouseco_areawin(mval);
141         projectFloatView(t, vecrot, cent);      // no overflow in extreme cases
142
143         persp(PERSP_WIN);
144         
145         glDrawBuffer(GL_FRONT);
146         
147         BIF_ThemeColor(TH_WIRE);
148         
149         setlinestyle(3);
150         glBegin(GL_LINE_STRIP); 
151         glVertex2sv(mval); 
152         glVertex2fv(cent); 
153         glEnd();
154         setlinestyle(0);
155         
156         persp(PERSP_VIEW);
157         bglFlush(); // flush display for frontbuffer
158         glDrawBuffer(GL_BACK);
159 #endif
160 }
161
162 /* ************************** SPACE DEPENDANT CODE **************************** */
163
164 void setTransformViewMatrices(TransInfo *t)
165 {
166         if(t->spacetype==SPACE_VIEW3D && t->ar->regiontype == RGN_TYPE_WINDOW) {
167                 RegionView3D *rv3d = t->ar->regiondata;
168                 
169                 Mat4CpyMat4(t->viewmat, rv3d->viewmat);
170                 Mat4CpyMat4(t->viewinv, rv3d->viewinv);
171                 Mat4CpyMat4(t->persmat, rv3d->persmat);
172                 Mat4CpyMat4(t->persinv, rv3d->persinv);
173                 t->persp = rv3d->persp;
174         }
175         else {
176                 Mat4One(t->viewmat);
177                 Mat4One(t->viewinv);
178                 Mat4One(t->persmat);
179                 Mat4One(t->persinv);
180                 t->persp = V3D_ORTHO;
181         }
182         
183         calculateCenter2D(t);
184 }
185
186 void convertViewVec(TransInfo *t, float *vec, short dx, short dy)
187 {
188         if (t->spacetype==SPACE_VIEW3D) {
189                 if (t->ar->regiontype == RGN_TYPE_WINDOW)
190                 {
191                         window_to_3d_delta(t->ar, vec, dx, dy);
192                 }
193         }
194         else if(t->spacetype==SPACE_IMAGE) {
195                 View2D *v2d = t->view;
196                 float divx, divy, aspx, aspy;
197                 
198                 ED_space_image_uv_aspect(t->sa->spacedata.first, &aspx, &aspy);
199                 
200                 divx= v2d->mask.xmax-v2d->mask.xmin;
201                 divy= v2d->mask.ymax-v2d->mask.ymin;
202                 
203                 vec[0]= aspx*(v2d->cur.xmax-v2d->cur.xmin)*(dx)/divx;
204                 vec[1]= aspy*(v2d->cur.ymax-v2d->cur.ymin)*(dy)/divy;
205                 vec[2]= 0.0f;
206         }
207         else if(t->spacetype==SPACE_IPO) {
208                 View2D *v2d = t->view;
209                 float divx, divy;
210                 
211                 divx= v2d->mask.xmax-v2d->mask.xmin;
212                 divy= v2d->mask.ymax-v2d->mask.ymin;
213                 
214                 vec[0]= (v2d->cur.xmax-v2d->cur.xmin)*(dx) / (divx);
215                 vec[1]= (v2d->cur.ymax-v2d->cur.ymin)*(dy) / (divy);
216                 vec[2]= 0.0f;
217         }
218         else if(t->spacetype==SPACE_NODE) {
219                 View2D *v2d = &t->ar->v2d;
220                 float divx, divy;
221                 
222                 divx= v2d->mask.xmax-v2d->mask.xmin;
223                 divy= v2d->mask.ymax-v2d->mask.ymin;
224                 
225                 vec[0]= (v2d->cur.xmax-v2d->cur.xmin)*(dx)/divx;
226                 vec[1]= (v2d->cur.ymax-v2d->cur.ymin)*(dy)/divy;
227                 vec[2]= 0.0f;
228         }
229         else if(t->spacetype==SPACE_SEQ) {
230                 View2D *v2d = &t->ar->v2d;
231                 float divx, divy;
232
233                 divx= v2d->mask.xmax-v2d->mask.xmin;
234                 divy= v2d->mask.ymax-v2d->mask.ymin;
235
236                 vec[0]= (v2d->cur.xmax-v2d->cur.xmin)*(dx)/divx;
237                 vec[1]= (v2d->cur.ymax-v2d->cur.ymin)*(dy)/divy;
238                 vec[2]= 0.0f;
239         }
240 }
241
242 void projectIntView(TransInfo *t, float *vec, int *adr)
243 {
244         if (t->spacetype==SPACE_VIEW3D) {
245                 project_int_noclip(t->ar, vec, adr);
246         }
247         else if(t->spacetype==SPACE_IMAGE) {
248                 float aspx, aspy, v[2];
249                 
250                 ED_space_image_uv_aspect(t->sa->spacedata.first, &aspx, &aspy);
251                 v[0]= vec[0]/aspx;
252                 v[1]= vec[1]/aspy;
253                 
254                 UI_view2d_to_region_no_clip(t->view, v[0], v[1], adr, adr+1);
255         }
256         else if(t->spacetype==SPACE_IPO) {
257                 int out[2] = {0, 0};
258                 
259                 UI_view2d_view_to_region((View2D *)t->view, vec[0], vec[1], out, out+1); 
260                 adr[0]= out[0];
261                 adr[1]= out[1];
262         }
263         else if(t->spacetype==SPACE_SEQ) { /* XXX not tested yet, but should work */
264                 int out[2] = {0, 0};
265                 
266                 UI_view2d_view_to_region((View2D *)t->view, vec[0], vec[1], out, out+1);
267                 adr[0]= out[0];
268                 adr[1]= out[1];
269         }
270 }
271
272 void projectFloatView(TransInfo *t, float *vec, float *adr)
273 {
274         if (t->spacetype==SPACE_VIEW3D) {
275                 project_float_noclip(t->ar, vec, adr);
276         }
277         else if(t->spacetype==SPACE_IMAGE) {
278                 int a[2];
279                 
280                 projectIntView(t, vec, a);
281                 adr[0]= a[0];
282                 adr[1]= a[1];
283         }
284         else if(t->spacetype==SPACE_IPO) {
285                 int a[2];
286                 
287                 projectIntView(t, vec, a);
288                 adr[0]= a[0];
289                 adr[1]= a[1];
290         }
291 }
292
293 void applyAspectRatio(TransInfo *t, float *vec)
294 {
295         SpaceImage *sima= t->sa->spacedata.first;
296
297         if ((t->spacetype==SPACE_IMAGE) && (t->mode==TFM_TRANSLATION)) {
298                 float aspx, aspy;
299
300                 if((sima->flag & SI_COORDFLOATS)==0) {
301                         int width, height;
302                         ED_space_image_size(sima, &width, &height);
303
304                         vec[0] *= width;
305                         vec[1] *= height;
306                 }
307
308                 ED_space_image_uv_aspect(sima, &aspx, &aspy);
309                 vec[0] /= aspx;
310                 vec[1] /= aspy;
311         }
312 }
313
314 void removeAspectRatio(TransInfo *t, float *vec)
315 {
316         SpaceImage *sima= t->sa->spacedata.first;
317
318         if ((t->spacetype==SPACE_IMAGE) && (t->mode==TFM_TRANSLATION)) {
319                 float aspx, aspy;
320
321                 if((sima->flag & SI_COORDFLOATS)==0) {
322                         int width, height;
323                         ED_space_image_size(sima, &width, &height);
324
325                         vec[0] /= width;
326                         vec[1] /= height;
327                 }
328
329                 ED_space_image_uv_aspect(sima, &aspx, &aspy);
330                 vec[0] *= aspx;
331                 vec[1] *= aspy;
332         }
333 }
334
335 static void viewRedrawForce(bContext *C, TransInfo *t)
336 {
337         if (t->spacetype == SPACE_VIEW3D)
338         {
339                 /* Do we need more refined tags? */             
340                 WM_event_add_notifier(C, NC_OBJECT|ND_TRANSFORM, NULL);
341         }
342         else if (t->spacetype == SPACE_ACTION) {
343                 SpaceAction *saction= (SpaceAction *)t->sa->spacedata.first;
344                 
345                 // TRANSFORM_FIX_ME
346                 if (saction->lock) {
347                         // whole window...
348                 }
349                 else 
350                         ED_area_tag_redraw(t->sa);
351         }
352         else if (t->spacetype == SPACE_IPO) {
353                 SpaceIpo *sipo= (SpaceIpo *)t->sa->spacedata.first;
354                 
355                 // TRANSFORM_FIX_ME
356                 if (sipo->lock) {
357                         // whole window...
358                 }
359                 else 
360                         ED_area_tag_redraw(t->sa);
361         }
362         else if(t->spacetype == SPACE_NODE)
363         {
364                 //ED_area_tag_redraw(t->sa);
365                 WM_event_add_notifier(C, NC_SCENE|ND_NODES, NULL);
366         }
367         else if(t->spacetype == SPACE_SEQ)
368         {
369                 WM_event_add_notifier(C, NC_SCENE|ND_SEQUENCER, NULL);
370         }
371         else if (t->spacetype==SPACE_IMAGE) {
372                 // XXX how to deal with lock?
373 #if 0
374                 SpaceImage *sima= (SpaceImage*)t->sa->spacedata.first;
375                 if(sima->lock) force_draw_plus(SPACE_VIEW3D, 0);
376                 else force_draw(0);
377 #endif
378
379                 WM_event_add_notifier(C, NC_OBJECT|ND_GEOM_DATA, t->obedit);
380         }
381 }
382
383 static void viewRedrawPost(TransInfo *t)
384 {
385         ED_area_headerprint(t->sa, NULL);
386         
387 #if 0 // TRANSFORM_FIX_ME
388         if(t->spacetype==SPACE_VIEW3D) {
389                 allqueue(REDRAWBUTSOBJECT, 0);
390                 allqueue(REDRAWVIEW3D, 0);
391         }
392         else if(t->spacetype==SPACE_IMAGE) {
393                 allqueue(REDRAWIMAGE, 0);
394                 allqueue(REDRAWVIEW3D, 0);
395         }
396         else if(ELEM3(t->spacetype, SPACE_ACTION, SPACE_NLA, SPACE_IPO)) {
397                 allqueue(REDRAWVIEW3D, 0);
398                 allqueue(REDRAWACTION, 0);
399                 allqueue(REDRAWNLA, 0);
400                 allqueue(REDRAWIPO, 0);
401                 allqueue(REDRAWTIME, 0);
402                 allqueue(REDRAWBUTSOBJECT, 0);
403         }
404
405         scrarea_queue_headredraw(curarea);
406 #endif
407 }
408
409 /* ************************** TRANSFORMATIONS **************************** */
410
411 void BIF_selectOrientation() {
412 #if 0 // TRANSFORM_FIX_ME
413         short val;
414         char *str_menu = BIF_menustringTransformOrientation("Orientation");
415         val= pupmenu(str_menu);
416         MEM_freeN(str_menu);
417         
418         if(val >= 0) {
419                 G.vd->twmode = val;
420         }
421 #endif
422 }
423
424 static void view_editmove(unsigned short event)
425 {
426 #if 0 // TRANSFORM_FIX_ME
427         int refresh = 0;
428         /* Regular:   Zoom in */
429         /* Shift:     Scroll up */
430         /* Ctrl:      Scroll right */
431         /* Alt-Shift: Rotate up */
432         /* Alt-Ctrl:  Rotate right */
433         
434         /* only work in 3D window for now
435          * In the end, will have to send to event to a 2D window handler instead
436          */
437         if (Trans.flag & T_2D_EDIT)
438                 return;
439         
440         switch(event) {
441                 case WHEELUPMOUSE:
442                         
443                         if( G.qual & LR_SHIFTKEY ) {
444                                 if( G.qual & LR_ALTKEY ) { 
445                                         G.qual &= ~LR_SHIFTKEY;
446                                         persptoetsen(PAD2);
447                                         G.qual |= LR_SHIFTKEY;
448                                 } else {
449                                         persptoetsen(PAD2);
450                                 }
451                         } else if( G.qual & LR_CTRLKEY ) {
452                                 if( G.qual & LR_ALTKEY ) { 
453                                         G.qual &= ~LR_CTRLKEY;
454                                         persptoetsen(PAD4);
455                                         G.qual |= LR_CTRLKEY;
456                                 } else {
457                                         persptoetsen(PAD4);
458                                 }
459                         } else if(U.uiflag & USER_WHEELZOOMDIR) 
460                                 persptoetsen(PADMINUS);
461                         else
462                                 persptoetsen(PADPLUSKEY);
463                         
464                         refresh = 1;
465                         break;
466                 case WHEELDOWNMOUSE:
467                         if( G.qual & LR_SHIFTKEY ) {
468                                 if( G.qual & LR_ALTKEY ) { 
469                                         G.qual &= ~LR_SHIFTKEY;
470                                         persptoetsen(PAD8);
471                                         G.qual |= LR_SHIFTKEY;
472                                 } else {
473                                         persptoetsen(PAD8);
474                                 }
475                         } else if( G.qual & LR_CTRLKEY ) {
476                                 if( G.qual & LR_ALTKEY ) { 
477                                         G.qual &= ~LR_CTRLKEY;
478                                         persptoetsen(PAD6);
479                                         G.qual |= LR_CTRLKEY;
480                                 } else {
481                                         persptoetsen(PAD6);
482                                 }
483                         } else if(U.uiflag & USER_WHEELZOOMDIR) 
484                                 persptoetsen(PADPLUSKEY);
485                         else
486                                 persptoetsen(PADMINUS);
487                         
488                         refresh = 1;
489                         break;
490         }
491
492         if (refresh)
493                 setTransformViewMatrices(&Trans);
494 #endif
495 }
496
497 static char *transform_to_undostr(TransInfo *t)
498 {
499         switch (t->mode) {
500                 case TFM_TRANSLATION:
501                         return "Translate";
502                 case TFM_ROTATION:
503                         return "Rotate";
504                 case TFM_RESIZE:
505                         return "Scale";
506                 case TFM_TOSPHERE:
507                         return "To Sphere";
508                 case TFM_SHEAR:
509                         return "Shear";
510                 case TFM_WARP:
511                         return "Warp";
512                 case TFM_SHRINKFATTEN:
513                         return "Shrink/Fatten";
514                 case TFM_TILT:
515                         return "Tilt";
516                 case TFM_TRACKBALL:
517                         return "Trackball";
518                 case TFM_PUSHPULL:
519                         return "Push/Pull";
520                 case TFM_BEVEL:
521                         return "Bevel";
522                 case TFM_BWEIGHT:
523                         return "Bevel Weight";
524                 case TFM_CREASE:
525                         return "Crease";
526                 case TFM_BONESIZE:
527                         return "Bone Width";
528                 case TFM_BONE_ENVELOPE:
529                         return "Bone Envelope";
530                 case TFM_TIME_TRANSLATE:
531                         return "Translate Anim. Data";
532                 case TFM_TIME_SCALE:
533                         return "Scale Anim. Data";
534                 case TFM_TIME_SLIDE:
535                         return "Time Slide";
536                 case TFM_BAKE_TIME:
537                         return "Key Time";
538                 case TFM_MIRROR:
539                         return "Mirror";
540         }
541         return "Transform";
542 }
543
544 /* ************************************************* */
545
546 void transformEvent(TransInfo *t, wmEvent *event)
547 {
548         float mati[3][3] = {{1.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 1.0f}};
549         char cmode = constraintModeToChar(t);
550         
551         t->redraw |= handleMouseInput(t, &t->mouse, event);
552
553         if (event->type == MOUSEMOVE)
554         {
555                 t->mval[0] = event->x - t->ar->winrct.xmin;
556                 t->mval[1] = event->y - t->ar->winrct.ymin;
557                 
558                 t->redraw = 1;
559                 
560                 applyMouseInput(t, &t->mouse, t->mval, t->values);
561         }
562         
563         if (event->val) {
564                 switch (event->type){
565                 /* enforce redraw of transform when modifiers are used */
566                 case LEFTCTRLKEY:
567                 case RIGHTCTRLKEY:
568                         t->modifiers |= MOD_SNAP_GEARS;
569                         t->redraw = 1;
570                         break;
571                         
572                 case LEFTSHIFTKEY:
573                 case RIGHTSHIFTKEY:
574                         t->modifiers |= MOD_CONSTRAINT_PLANE;
575                         t->redraw = 1;
576                         break;
577
578                 case SPACEKEY:
579                         if ((t->spacetype==SPACE_VIEW3D) && event->alt) {
580 #if 0 // TRANSFORM_FIX_ME
581                                 short mval[2];
582                                 
583                                 getmouseco_sc(mval);
584                                 BIF_selectOrientation();
585                                 calc_manipulator_stats(curarea);
586                                 Mat3CpyMat4(t->spacemtx, G.vd->twmat);
587                                 warp_pointer(mval[0], mval[1]);
588 #endif
589                         }
590                         else {
591                                 t->state = TRANS_CONFIRM;
592                         }
593                         break;
594                         
595                 case MIDDLEMOUSE:
596                         if ((t->flag & T_NO_CONSTRAINT)==0) {
597                                 /* exception for switching to dolly, or trackball, in camera view */
598                                 if (t->flag & T_CAMERA) {
599                                         if (t->mode==TFM_TRANSLATION)
600                                                 setLocalConstraint(t, (CON_AXIS2), "along local Z");
601                                         else if (t->mode==TFM_ROTATION) {
602                                                 restoreTransObjects(t);
603                                                 initTrackball(t);
604                                         }
605                                 }
606                                 else {
607                                         t->modifiers |= MOD_CONSTRAINT_SELECT;
608                                         if (t->con.mode & CON_APPLY) {
609                                                 stopConstraint(t);
610                                         }
611                                         else {
612                                                 if (event->shift) {
613                                                         initSelectConstraint(t, t->spacemtx);
614                                                 }
615                                                 else {
616                                                         /* bit hackish... but it prevents mmb select to print the orientation from menu */
617                                                         strcpy(t->spacename, "global");
618                                                         initSelectConstraint(t, mati);
619                                                 }
620                                                 postSelectConstraint(t);
621                                         }
622                                 }
623                                 t->redraw = 1;
624                         }
625                         break;
626                 case ESCKEY:
627                 case RIGHTMOUSE:
628                         printf("cancelled\n");
629                         t->state = TRANS_CANCEL;
630                         break;
631                 case LEFTMOUSE:
632                 case PADENTER:
633                 case RETKEY:
634                         t->state = TRANS_CONFIRM;
635                         break;
636                 case GKEY:
637                         /* only switch when... */
638                         if( ELEM3(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL) ) { 
639                                 resetTransRestrictions(t); 
640                                 restoreTransObjects(t);
641                                 initTranslation(t);
642                                 t->redraw = 1;
643                         }
644                         break;
645                 case SKEY:
646                         /* only switch when... */
647                         if( ELEM3(t->mode, TFM_ROTATION, TFM_TRANSLATION, TFM_TRACKBALL) ) { 
648                                 resetTransRestrictions(t); 
649                                 restoreTransObjects(t);
650                                 initResize(t);
651                                 t->redraw = 1;
652                         }
653                         break;
654                 case RKEY:
655                         /* only switch when... */
656                         if( ELEM4(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL, TFM_TRANSLATION) ) {
657                                 
658                                 resetTransRestrictions(t); 
659                                 
660                                 if (t->mode == TFM_ROTATION) {
661                                         restoreTransObjects(t);
662                                         initTrackball(t);
663                                 }
664                                 else {
665                                         restoreTransObjects(t);
666                                         initRotation(t);
667                                 }
668                                 t->redraw = 1;
669                         }
670                         break;
671                 case CKEY:
672                         if (event->alt) {
673                                 t->flag ^= T_PROP_CONNECTED;
674                                 sort_trans_data_dist(t);
675                                 calculatePropRatio(t);
676                                 t->redraw= 1;
677                         }
678                         else {
679                                 stopConstraint(t);
680                                 t->redraw = 1;
681                         }
682                         break;
683                 case XKEY:
684                         if ((t->flag & T_NO_CONSTRAINT)==0) {
685                                 if (cmode == 'X') {
686                                         if (t->flag & T_2D_EDIT) {
687                                                 stopConstraint(t);
688                                         }
689                                         else {
690                                                 if (t->con.mode & CON_USER) {
691                                                         stopConstraint(t);
692                                                 }
693                                                 else {
694                                                         if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
695                                                                 setUserConstraint(t, (CON_AXIS0), "along %s X");
696                                                         else if (t->modifiers & MOD_CONSTRAINT_PLANE)
697                                                                 setUserConstraint(t, (CON_AXIS1|CON_AXIS2), "locking %s X");
698                                                 }
699                                         }
700                                 }
701                                 else {
702                                         if (t->flag & T_2D_EDIT) {
703                                                 setConstraint(t, mati, (CON_AXIS0), "along X axis");
704                                         }
705                                         else {
706                                                 if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
707                                                         setConstraint(t, mati, (CON_AXIS0), "along global X");
708                                                 else if (t->modifiers & MOD_CONSTRAINT_PLANE)
709                                                         setConstraint(t, mati, (CON_AXIS1|CON_AXIS2), "locking global X");
710                                         }
711                                 }
712                                 t->redraw = 1;
713                         }
714                         break;
715                 case YKEY:
716                         if ((t->flag & T_NO_CONSTRAINT)==0) {
717                                 if (cmode == 'Y') {
718                                         if (t->flag & T_2D_EDIT) {
719                                                 stopConstraint(t);
720                                         }
721                                         else {
722                                                 if (t->con.mode & CON_USER) {
723                                                         stopConstraint(t);
724                                                 }
725                                                 else {
726                                                         if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
727                                                                 setUserConstraint(t, (CON_AXIS1), "along %s Y");
728                                                         else if (t->modifiers & MOD_CONSTRAINT_PLANE)
729                                                                 setUserConstraint(t, (CON_AXIS0|CON_AXIS2), "locking %s Y");
730                                                 }
731                                         }
732                                 }
733                                 else {
734                                         if (t->flag & T_2D_EDIT) {
735                                                 setConstraint(t, mati, (CON_AXIS1), "along Y axis");
736                                         }
737                                         else {
738                                                 if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
739                                                         setConstraint(t, mati, (CON_AXIS1), "along global Y");
740                                                 else if (t->modifiers & MOD_CONSTRAINT_PLANE)
741                                                         setConstraint(t, mati, (CON_AXIS0|CON_AXIS2), "locking global Y");
742                                         }
743                                 }
744                                 t->redraw = 1;
745                         }
746                         break;
747                 case ZKEY:
748                         if ((t->flag & T_NO_CONSTRAINT)==0) {
749                                 if (cmode == 'Z') {
750                                         if (t->con.mode & CON_USER) {
751                                                 stopConstraint(t);
752                                         }
753                                         else {
754                                                 if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
755                                                         setUserConstraint(t, (CON_AXIS2), "along %s Z");
756                                                 else if ((t->modifiers & MOD_CONSTRAINT_PLANE) && ((t->flag & T_2D_EDIT)==0))
757                                                         setUserConstraint(t, (CON_AXIS0|CON_AXIS1), "locking %s Z");
758                                         }
759                                 }
760                                 else if ((t->flag & T_2D_EDIT)==0) {
761                                         if ((t->modifiers & MOD_CONSTRAINT_PLANE) == 0)
762                                                 setConstraint(t, mati, (CON_AXIS2), "along global Z");
763                                         else if (t->modifiers & MOD_CONSTRAINT_PLANE)
764                                                 setConstraint(t, mati, (CON_AXIS0|CON_AXIS1), "locking global Z");
765                                 }
766                                 t->redraw = 1;
767                         }
768                         break;
769                 case OKEY:
770                         if (t->flag & T_PROP_EDIT && event->shift) {
771                                 t->prop_mode = (t->prop_mode + 1) % 6;
772                                 calculatePropRatio(t);
773                                 t->redraw = 1;
774                         }
775                         break;
776                 case PADPLUSKEY:
777                         if(event->alt && t->flag & T_PROP_EDIT) {
778                                 t->prop_size *= 1.1f;
779                                 calculatePropRatio(t);
780                         }
781                         t->redraw= 1;
782                         break;
783                 case PAGEUPKEY:
784                 case WHEELDOWNMOUSE:
785                         if (t->flag & T_AUTOIK) {
786                                 transform_autoik_update(t, 1);
787                         }
788                         else if(t->flag & T_PROP_EDIT) {
789                                 t->prop_size*= 1.1f;
790                                 calculatePropRatio(t);
791                         }
792                         else view_editmove(event->type);
793                         t->redraw= 1;
794                         break;
795                 case PADMINUS:
796                         if(event->alt && t->flag & T_PROP_EDIT) {
797                                 t->prop_size*= 0.90909090f;
798                                 calculatePropRatio(t);
799                         }
800                         t->redraw= 1;
801                         break;
802                 case PAGEDOWNKEY:
803                 case WHEELUPMOUSE:
804                         if (t->flag & T_AUTOIK) {
805                                 transform_autoik_update(t, -1);
806                         }
807                         else if (t->flag & T_PROP_EDIT) {
808                                 t->prop_size*= 0.90909090f;
809                                 calculatePropRatio(t);
810                         }
811                         else view_editmove(event->type);
812                         t->redraw= 1;
813                         break;
814 //              case NDOFMOTION:
815 //            viewmoveNDOF(1);
816   //         break;
817                 }
818                 
819                 // Numerical input events
820                 t->redraw |= handleNumInput(&(t->num), event);
821                 
822                 // NDof input events
823                 switch(handleNDofInput(&(t->ndof), event))
824                 {
825                         case NDOF_CONFIRM:
826                                 if ((t->options & CTX_NDOF) == 0)
827                                 {
828                                         /* Confirm on normal transform only */
829                                         t->state = TRANS_CONFIRM;
830                                 }
831                                 break;
832                         case NDOF_CANCEL:
833                                 if (t->options & CTX_NDOF)
834                                 {
835                                         /* Cancel on pure NDOF transform */
836                                         t->state = TRANS_CANCEL; 
837                                 }
838                                 else
839                                 {
840                                         /* Otherwise, just redraw, NDof input was cancelled */
841                                         t->redraw = 1;
842                                 }
843                                 break;
844                         case NDOF_NOMOVE:
845                                 if (t->options & CTX_NDOF)
846                                 {
847                                         /* Confirm on pure NDOF transform */
848                                         t->state = TRANS_CONFIRM;
849                                 }
850                                 break;
851                         case NDOF_REFRESH:
852                                 t->redraw = 1;
853                                 break;
854                         
855                 }
856                 
857                 // Snapping events
858                 t->redraw |= handleSnapping(t, event);
859                 
860                 //arrows_move_cursor(event->type);
861         }
862         else {
863                 switch (event->type){
864                 case LEFTSHIFTKEY:
865                 case RIGHTSHIFTKEY:
866                         t->modifiers &= ~MOD_CONSTRAINT_PLANE;
867                         t->redraw = 1;
868                         break;
869
870                 case LEFTCTRLKEY:
871                 case RIGHTCTRLKEY:
872                         t->modifiers &= ~MOD_SNAP_GEARS;
873                         /* no redraw on release modifier keys! this makes sure you can assign the 'grid' still 
874                            after releasing modifer key */
875                         //t->redraw = 1;
876                         break;
877                 case MIDDLEMOUSE:
878                         if ((t->flag & T_NO_CONSTRAINT)==0) {
879                                 t->modifiers &= ~MOD_CONSTRAINT_SELECT;
880                                 postSelectConstraint(t);
881                                 t->redraw = 1;
882                         }
883                         break;
884                 case LEFTMOUSE:
885                 case RIGHTMOUSE:
886                         if(WM_modal_tweak_exit(event, t->event_type))
887 //                      if (t->options & CTX_TWEAK)
888                                 t->state = TRANS_CONFIRM;
889                         break;
890                 }
891         }
892         
893         // Per transform event, if present
894         if (t->handleEvent)
895                 t->redraw |= t->handleEvent(t, event);
896 }
897
898 int calculateTransformCenter(bContext *C, wmEvent *event, int centerMode, float *vec)
899 {
900         TransInfo *t = MEM_callocN(sizeof(TransInfo), "TransInfo data");
901         int success = 1;
902
903         t->state = TRANS_RUNNING;
904
905         t->options = CTX_NONE;
906         
907         t->mode = TFM_DUMMY;
908
909         initTransInfo(C, t, NULL, event);                                       // internal data, mouse, vectors
910
911         createTransData(C, t);                  // make TransData structs from selection
912
913         t->around = centerMode;                         // override userdefined mode
914
915         if (t->total == 0) {
916                 success = 0;
917         }
918         else {
919                 success = 1;
920                 
921                 calculateCenter(t);
922         
923                 // Copy center from constraint center. Transform center can be local    
924                 VECCOPY(vec, t->con.center);
925         }
926
927         postTrans(t);
928
929         /* aftertrans does insert ipos and action channels, and clears base flags, doesnt read transdata */
930         special_aftertrans_update(t);
931         
932         MEM_freeN(t);
933         
934         return success;
935 }
936
937 void drawTransform(const struct bContext *C, struct ARegion *ar, void *arg)
938 {
939         TransInfo *t = arg;
940         
941         drawConstraint(C, t);
942         drawPropCircle(C, t);
943         drawSnapping(C, t);
944 }
945
946 void saveTransform(bContext *C, TransInfo *t, wmOperator *op)
947 {
948         Scene *sce = CTX_data_scene(C);
949         int constraint_axis[3] = {0, 0, 0};
950         int proportional = 0;
951
952         if (t->flag & T_AUTOVALUES)
953         {
954                 RNA_float_set_array(op->ptr, "value", t->auto_values);
955         }
956         else
957         {
958                 RNA_float_set_array(op->ptr, "value", t->values);
959         }
960
961         /* XXX convert stupid flag to enum */
962         switch(t->flag & (T_PROP_EDIT|T_PROP_CONNECTED))
963         {
964         case (T_PROP_EDIT|T_PROP_CONNECTED):
965                 proportional = 2;
966                 break;
967         case T_PROP_EDIT:
968                 proportional = 1;
969                 break;
970         default:
971                 proportional = 0;
972         }
973
974         if (RNA_struct_find_property(op->ptr, "proportional"))
975         {
976                 RNA_enum_set(op->ptr, "proportional", proportional);
977                 RNA_enum_set(op->ptr, "proportional_editing_falloff", t->prop_mode);
978                 RNA_float_set(op->ptr, "proportional_size", t->prop_size);
979         }
980
981         if (RNA_struct_find_property(op->ptr, "mirror"))
982         {
983                 RNA_boolean_set(op->ptr, "mirror", t->flag & T_MIRROR);
984         }
985         
986         if (RNA_struct_find_property(op->ptr, "constraint_mode"))
987         {
988                 RNA_int_set(op->ptr, "constraint_mode", t->con.mode);
989                 RNA_int_set(op->ptr, "constraint_orientation", t->current_orientation);
990
991                 if (t->con.mode & CON_APPLY)
992                 {
993                         if (t->con.mode & CON_AXIS0) {
994                                 constraint_axis[0] = 1;
995                         }
996                         if (t->con.mode & CON_AXIS1) {
997                                 constraint_axis[1] = 1;
998                         }
999                         if (t->con.mode & CON_AXIS2) {
1000                                 constraint_axis[2] = 1;
1001                         }
1002                 }
1003
1004                 RNA_boolean_set_array(op->ptr, "constraint_axis", constraint_axis);
1005         }
1006
1007         // XXX If modal, save settings back in scene
1008         if (t->flag & T_MODAL)
1009         {
1010                 sce->prop_mode = t->prop_mode;
1011                 sce->proportional = proportional;
1012
1013                 if(t->spacetype == SPACE_VIEW3D)
1014                 {
1015                         View3D *v3d = t->view;
1016                         
1017                         v3d->twmode = t->current_orientation;
1018                 }
1019         }
1020 }
1021
1022 int initTransform(bContext *C, TransInfo *t, wmOperator *op, wmEvent *event, int mode)
1023 {
1024         int options = 0;
1025
1026         /* added initialize, for external calls to set stuff in TransInfo, like undo string */
1027
1028         t->state = TRANS_RUNNING;
1029
1030         t->options = options;
1031         
1032         t->mode = mode;
1033
1034         if (!initTransInfo(C, t, op, event))                                    // internal data, mouse, vectors
1035         {
1036                 return 0;
1037         }
1038
1039         initTransformOrientation(C, t);
1040
1041         if(t->spacetype == SPACE_VIEW3D)
1042         {
1043                 //calc_manipulator_stats(curarea);
1044                 if (t->ar->regiontype == RGN_TYPE_WINDOW)
1045                 {
1046                         RegionView3D *rv3d = t->ar->regiondata;
1047                         Mat3CpyMat4(t->spacemtx, rv3d->twmat);
1048                 }
1049                 Mat3Ortho(t->spacemtx);
1050                 
1051                 t->draw_handle = ED_region_draw_cb_activate(t->ar->type, drawTransform, t, REGION_DRAW_POST);
1052         }
1053         else if(t->spacetype == SPACE_IMAGE) {
1054                 Mat3One(t->spacemtx);
1055                 t->draw_handle = ED_region_draw_cb_activate(t->ar->type, drawTransform, t, REGION_DRAW_POST);
1056         }
1057         else
1058                 Mat3One(t->spacemtx);
1059
1060         createTransData(C, t);                  // make TransData structs from selection
1061
1062         if (t->total == 0) {
1063                 postTrans(t);
1064                 return 0;
1065         }
1066
1067         initSnapping(t, op); // Initialize snapping data AFTER mode flags
1068
1069         /* EVIL! posemode code can switch translation to rotate when 1 bone is selected. will be removed (ton) */
1070         /* EVIL2: we gave as argument also texture space context bit... was cleared */
1071         /* EVIL3: extend mode for animation editors also switches modes... but is best way to avoid duplicate code */
1072         mode = t->mode;
1073         
1074         calculatePropRatio(t);
1075         calculateCenter(t);
1076         
1077         initMouseInput(t, &t->mouse, t->center2d, t->imval);
1078
1079         switch (mode) {
1080         case TFM_TRANSLATION:
1081                 initTranslation(t);
1082                 break;
1083         case TFM_ROTATION:
1084                 initRotation(t);
1085                 break;
1086         case TFM_RESIZE:
1087                 initResize(t);
1088                 break;
1089         case TFM_TOSPHERE:
1090                 initToSphere(t);
1091                 break;
1092         case TFM_SHEAR:
1093                 initShear(t);
1094                 break;
1095         case TFM_WARP:
1096                 initWarp(t);
1097                 break;
1098         case TFM_SHRINKFATTEN:
1099                 initShrinkFatten(t);
1100                 break;
1101         case TFM_TILT:
1102                 initTilt(t);
1103                 break;
1104         case TFM_CURVE_SHRINKFATTEN:
1105                 initCurveShrinkFatten(t);
1106                 break;
1107         case TFM_TRACKBALL:
1108                 initTrackball(t);
1109                 break;
1110         case TFM_PUSHPULL:
1111                 initPushPull(t);
1112                 break;
1113         case TFM_CREASE:
1114                 initCrease(t);
1115                 break;
1116         case TFM_BONESIZE:
1117                 {       /* used for both B-Bone width (bonesize) as for deform-dist (envelope) */
1118                         bArmature *arm= t->poseobj->data;
1119                         if(arm->drawtype==ARM_ENVELOPE)
1120                                 initBoneEnvelope(t);
1121                         else
1122                                 initBoneSize(t);
1123                 }
1124                 break;
1125         case TFM_BONE_ENVELOPE:
1126                 initBoneEnvelope(t);
1127                 break;
1128         case TFM_BONE_ROLL:
1129                 initBoneRoll(t);
1130                 break;
1131         case TFM_TIME_TRANSLATE:
1132                 initTimeTranslate(t);
1133                 break;
1134         case TFM_TIME_SLIDE:
1135                 initTimeSlide(t);
1136                 break;
1137         case TFM_TIME_SCALE:
1138                 initTimeScale(t);
1139                 break;
1140         case TFM_TIME_EXTEND: 
1141                 /* now that transdata has been made, do like for TFM_TIME_TRANSLATE (for most Animation
1142                  * Editors because they have only 1D transforms for time values) or TFM_TRANSLATION
1143                  * (for Graph Editor only since it uses 'standard' transforms to get 2D movement)
1144                  * depending on which editor this was called from 
1145                  */
1146                 if (t->spacetype == SPACE_IPO)
1147                         initTranslation(t);
1148                 else
1149                         initTimeTranslate(t);
1150                 break;
1151         case TFM_BAKE_TIME:
1152                 initBakeTime(t);
1153                 break;
1154         case TFM_MIRROR:
1155                 initMirror(t);
1156                 break;
1157         case TFM_BEVEL:
1158                 initBevel(t);
1159                 break;
1160         case TFM_BWEIGHT:
1161                 initBevelWeight(t);
1162                 break;
1163         case TFM_ALIGN:
1164                 initAlign(t);
1165                 break;
1166         }
1167
1168         /* overwrite initial values if operator supplied a non-null vector */
1169         if (RNA_property_is_set(op->ptr, "value"))
1170         {
1171                 float values[4];
1172                 RNA_float_get_array(op->ptr, "value", values);
1173                 QUATCOPY(t->values, values);
1174                 QUATCOPY(t->auto_values, values);
1175                 t->flag |= T_AUTOVALUES;
1176         }
1177
1178         /* Constraint init from operator */
1179         if (RNA_struct_find_property(op->ptr, "constraint_axis") && RNA_property_is_set(op->ptr, "constraint_axis"))
1180         {
1181                 int constraint_axis[3];
1182
1183                 RNA_boolean_get_array(op->ptr, "constraint_axis", constraint_axis);
1184
1185                 if (constraint_axis[0] || constraint_axis[1] || constraint_axis[2])
1186                 {
1187                         t->con.mode |= CON_APPLY;
1188
1189                         if (constraint_axis[0]) {
1190                                 t->con.mode |= CON_AXIS0;
1191                         }
1192                         if (constraint_axis[1]) {
1193                                 t->con.mode |= CON_AXIS1;
1194                         }
1195                         if (constraint_axis[2]) {
1196                                 t->con.mode |= CON_AXIS2;
1197                         }
1198                                 
1199                         setUserConstraint(t, t->con.mode, "%s");                
1200                 }
1201         }
1202         
1203         return 1;
1204 }
1205
1206 void transformApply(bContext *C, TransInfo *t)
1207 {
1208         if (t->redraw)
1209         {
1210                 if (t->modifiers & MOD_CONSTRAINT_SELECT)
1211                         t->con.mode |= CON_SELECT;
1212
1213                 selectConstraint(t);
1214                 if (t->transform) {
1215                         t->transform(t, t->mval);  // calls recalcData()
1216                         viewRedrawForce(C, t);
1217                 }
1218                 t->redraw = 0;
1219         }
1220
1221         /* If auto confirm is on, break after one pass */               
1222         if (t->options & CTX_AUTOCONFIRM)
1223         {
1224                 t->state = TRANS_CONFIRM;
1225         }
1226
1227         if (BKE_ptcache_get_continue_physics())
1228         {
1229                 // TRANSFORM_FIX_ME
1230                 //do_screenhandlers(G.curscreen);
1231                 t->redraw = 1;
1232         }
1233 }
1234
1235 int transformEnd(bContext *C, TransInfo *t)
1236 {
1237         int exit_code = OPERATOR_RUNNING_MODAL;
1238         
1239         if (t->state != TRANS_RUNNING)
1240         {
1241                 /* handle restoring objects */
1242                 if(t->state == TRANS_CANCEL)
1243                 {
1244                         exit_code = OPERATOR_CANCELLED;
1245                         restoreTransObjects(t); // calls recalcData()
1246                 }
1247                 else
1248                 {
1249                         exit_code = OPERATOR_FINISHED;
1250                 }
1251                 
1252                 /* free data */
1253                 postTrans(t);
1254         
1255                 /* aftertrans does insert keyframes, and clears base flags, doesnt read transdata */
1256                 special_aftertrans_update(t);
1257         
1258                 /* send events out for redraws */
1259                 viewRedrawPost(t);
1260         
1261                 /*  Undo as last, certainly after special_trans_update! */
1262
1263                 if(t->state == TRANS_CANCEL) {
1264 //                      if(t->undostr) ED_undo_push(C, t->undostr);
1265                 }
1266                 else {
1267 //                      if(t->undostr) ED_undo_push(C, t->undostr);
1268 //                      else ED_undo_push(C, transform_to_undostr(t));
1269                 }
1270                 t->undostr= NULL;
1271
1272                 viewRedrawForce(C, t);
1273         }
1274         
1275         return exit_code;
1276 }
1277
1278 /* ************************** Manipulator init and main **************************** */
1279
1280 void initManipulator(int mode)
1281 {
1282 #if 0 // TRANSFORM_FIX_ME
1283         Trans.state = TRANS_RUNNING;
1284
1285         Trans.options = CTX_NONE;
1286         
1287         Trans.mode = mode;
1288         
1289         /* automatic switch to scaling bone envelopes */
1290         if(mode==TFM_RESIZE && t->obedit && t->obedit->type==OB_ARMATURE) {
1291                 bArmature *arm= t->obedit->data;
1292                 if(arm->drawtype==ARM_ENVELOPE)
1293                         mode= TFM_BONE_ENVELOPE;
1294         }
1295
1296         initTrans(&Trans);                                      // internal data, mouse, vectors
1297
1298         G.moving |= G_TRANSFORM_MANIP;          // signal to draw manipuls while transform
1299         createTransData(&Trans);                        // make TransData structs from selection
1300
1301         if (Trans.total == 0)
1302                 return;
1303
1304         initSnapping(&Trans); // Initialize snapping data AFTER mode flags
1305
1306         /* EVIL! posemode code can switch translation to rotate when 1 bone is selected. will be removed (ton) */
1307         /* EVIL2: we gave as argument also texture space context bit... was cleared */
1308         mode = Trans.mode;
1309         
1310         calculatePropRatio(&Trans);
1311         calculateCenter(&Trans);
1312
1313         switch (mode) {
1314         case TFM_TRANSLATION:
1315                 initTranslation(&Trans);
1316                 break;
1317         case TFM_ROTATION:
1318                 initRotation(&Trans);
1319                 break;
1320         case TFM_RESIZE:
1321                 initResize(&Trans);
1322                 break;
1323         case TFM_TRACKBALL:
1324                 initTrackball(&Trans);
1325                 break;
1326         }
1327
1328         Trans.flag |= T_USES_MANIPULATOR;
1329 #endif
1330 }
1331
1332 void ManipulatorTransform() 
1333 {
1334 #if 0 // TRANSFORM_FIX_ME
1335         int mouse_moved = 0;
1336         short pmval[2] = {0, 0}, mval[2], val;
1337         unsigned short event;
1338
1339         if (Trans.total == 0)
1340                 return;
1341
1342         Trans.redraw = 1; /* initial draw */
1343
1344         while (Trans.state == TRANS_RUNNING) {
1345                 
1346                 getmouseco_areawin(mval);
1347                 
1348                 if (mval[0] != pmval[0] || mval[1] != pmval[1]) {
1349                         Trans.redraw = 1;
1350                 }
1351                 if (Trans.redraw) {
1352                         pmval[0] = mval[0];
1353                         pmval[1] = mval[1];
1354
1355                         //selectConstraint(&Trans);  needed?
1356                         if (Trans.transform) {
1357                                 Trans.transform(&Trans, mval);
1358                         }
1359                         Trans.redraw = 0;
1360                 }
1361                 
1362                 /* essential for idling subloop */
1363                 if( qtest()==0) PIL_sleep_ms(2);
1364
1365                 while( qtest() ) {
1366                         event= extern_qread(&val);
1367
1368                         switch (event){
1369                         case MOUSEX:
1370                         case MOUSEY:
1371                                 mouse_moved = 1;
1372                                 break;
1373                         /* enforce redraw of transform when modifiers are used */
1374                         case LEFTCTRLKEY:
1375                         case RIGHTCTRLKEY:
1376                                 if(val) Trans.redraw = 1;
1377                                 break;
1378                         case LEFTSHIFTKEY:
1379                         case RIGHTSHIFTKEY:
1380                                 /* shift is modifier for higher resolution transform, works nice to store this mouse position */
1381                                 if(val) {
1382                                         getmouseco_areawin(Trans.shiftmval);
1383                                         Trans.flag |= T_SHIFT_MOD;
1384                                         Trans.redraw = 1;
1385                                 }
1386                                 else Trans.flag &= ~T_SHIFT_MOD; 
1387                                 break;
1388                                 
1389                         case ESCKEY:
1390                         case RIGHTMOUSE:
1391                                 Trans.state = TRANS_CANCEL;
1392                                 break;
1393                         case LEFTMOUSE:
1394                                 if(mouse_moved==0 && val==0) break;
1395                                 // else we pass on event to next, which cancels
1396                         case SPACEKEY:
1397                         case PADENTER:
1398                         case RETKEY:
1399                                 Trans.state = TRANS_CONFIRM;
1400                                 break;
1401    //         case NDOFMOTION:
1402      //           viewmoveNDOF(1);
1403      //           break;
1404                         }
1405                         if(val) {
1406                                 switch(event) {
1407                                 case PADPLUSKEY:
1408                                         if(G.qual & LR_ALTKEY && Trans.flag & T_PROP_EDIT) {
1409                                                 Trans.propsize*= 1.1f;
1410                                                 calculatePropRatio(&Trans);
1411                                         }
1412                                         Trans.redraw= 1;
1413                                         break;
1414                                 case PAGEUPKEY:
1415                                 case WHEELDOWNMOUSE:
1416                                         if (Trans.flag & T_AUTOIK) {
1417                                                 transform_autoik_update(&Trans, 1);
1418                                         }
1419                                         else if(Trans.flag & T_PROP_EDIT) {
1420                                                 Trans.propsize*= 1.1f;
1421                                                 calculatePropRatio(&Trans);
1422                                         }
1423                                         else view_editmove(event);
1424                                         Trans.redraw= 1;
1425                                         break;
1426                                 case PADMINUS:
1427                                         if(G.qual & LR_ALTKEY && Trans.flag & T_PROP_EDIT) {
1428                                                 Trans.propsize*= 0.90909090f;
1429                                                 calculatePropRatio(&Trans);
1430                                         }
1431                                         Trans.redraw= 1;
1432                                         break;
1433                                 case PAGEDOWNKEY:
1434                                 case WHEELUPMOUSE:
1435                                         if (Trans.flag & T_AUTOIK) {
1436                                                 transform_autoik_update(&Trans, -1);
1437                                         }
1438                                         else if (Trans.flag & T_PROP_EDIT) {
1439                                                 Trans.propsize*= 0.90909090f;
1440                                                 calculatePropRatio(&Trans);
1441                                         }
1442                                         else view_editmove(event);
1443                                         Trans.redraw= 1;
1444                                         break;
1445                                 }
1446                                                         
1447                                 // Numerical input events
1448                                 Trans.redraw |= handleNumInput(&(Trans.num), event);
1449                         }
1450                 }
1451         }
1452         
1453         if(Trans.state == TRANS_CANCEL) {
1454                 restoreTransObjects(&Trans);
1455         }
1456         
1457         /* free data, reset vars */
1458         postTrans(&Trans);
1459         
1460         /* aftertrans does insert ipos and action channels, and clears base flags */
1461         special_aftertrans_update(&Trans);
1462         
1463         /* send events out for redraws */
1464         viewRedrawPost(&Trans);
1465
1466         if(Trans.state != TRANS_CANCEL) {
1467                 BIF_undo_push(transform_to_undostr(&Trans));
1468         }
1469 #endif
1470 }
1471
1472 /* ************************** TRANSFORM LOCKS **************************** */
1473
1474 static void protectedTransBits(short protectflag, float *vec)
1475 {
1476         if(protectflag & OB_LOCK_LOCX)
1477                 vec[0]= 0.0f;
1478         if(protectflag & OB_LOCK_LOCY)
1479                 vec[1]= 0.0f;
1480         if(protectflag & OB_LOCK_LOCZ)
1481                 vec[2]= 0.0f;
1482 }
1483
1484 static void protectedSizeBits(short protectflag, float *size)
1485 {
1486         if(protectflag & OB_LOCK_SCALEX)
1487                 size[0]= 1.0f;
1488         if(protectflag & OB_LOCK_SCALEY)
1489                 size[1]= 1.0f;
1490         if(protectflag & OB_LOCK_SCALEZ)
1491                 size[2]= 1.0f;
1492 }
1493
1494 static void protectedRotateBits(short protectflag, float *eul, float *oldeul)
1495 {
1496         if(protectflag & OB_LOCK_ROTX)
1497                 eul[0]= oldeul[0];
1498         if(protectflag & OB_LOCK_ROTY)
1499                 eul[1]= oldeul[1];
1500         if(protectflag & OB_LOCK_ROTZ)
1501                 eul[2]= oldeul[2];
1502 }
1503
1504 static void protectedQuaternionBits(short protectflag, float *quat, float *oldquat)
1505 {
1506         /* quaternions get limited with euler... */
1507         /* this function only does the delta rotation */
1508         
1509         if(protectflag) {
1510                 float eul[3], oldeul[3], quat1[4];
1511                 
1512                 QUATCOPY(quat1, quat);
1513                 QuatToEul(quat, eul);
1514                 QuatToEul(oldquat, oldeul);
1515                 
1516                 if(protectflag & OB_LOCK_ROTX)
1517                         eul[0]= oldeul[0];
1518                 if(protectflag & OB_LOCK_ROTY)
1519                         eul[1]= oldeul[1];
1520                 if(protectflag & OB_LOCK_ROTZ)
1521                         eul[2]= oldeul[2];
1522                 
1523                 EulToQuat(eul, quat);
1524                 /* quaternions flip w sign to accumulate rotations correctly */
1525                 if( (quat1[0]<0.0f && quat[0]>0.0f) || (quat1[0]>0.0f && quat[0]<0.0f) ) {
1526                         QuatMulf(quat, -1.0f);
1527                 }
1528         }
1529 }
1530
1531 /* ******************* TRANSFORM LIMITS ********************** */
1532
1533 static void constraintTransLim(TransInfo *t, TransData *td)
1534 {
1535         if (td->con) {
1536                 bConstraintTypeInfo *cti= get_constraint_typeinfo(CONSTRAINT_TYPE_LOCLIMIT);
1537                 bConstraintOb cob;
1538                 bConstraint *con;
1539                 
1540                 /* Make a temporary bConstraintOb for using these limit constraints 
1541                  *      - they only care that cob->matrix is correctly set ;-)
1542                  *      - current space should be local
1543                  */
1544                 memset(&cob, 0, sizeof(bConstraintOb));
1545                 Mat4One(cob.matrix);
1546                 if (td->tdi) {
1547                         TransDataIpokey *tdi= td->tdi;
1548                         cob.matrix[3][0]= tdi->locx[0];
1549                         cob.matrix[3][1]= tdi->locy[0];
1550                         cob.matrix[3][2]= tdi->locz[0];
1551                 }
1552                 else {
1553                         VECCOPY(cob.matrix[3], td->loc);
1554                 }
1555                 
1556                 /* Evaluate valid constraints */
1557                 for (con= td->con; con; con= con->next) {
1558                         float tmat[4][4];
1559                         
1560                         /* only consider constraint if enabled */
1561                         if (con->flag & CONSTRAINT_DISABLE) continue;
1562                         if (con->enforce == 0.0f) continue;
1563                         
1564                         /* only use it if it's tagged for this purpose (and the right type) */
1565                         if (con->type == CONSTRAINT_TYPE_LOCLIMIT) {
1566                                 bLocLimitConstraint *data= con->data;
1567                                 
1568                                 if ((data->flag2 & LIMIT_TRANSFORM)==0) 
1569                                         continue;
1570                                 
1571                                 /* do space conversions */
1572                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1573                                         /* just multiply by td->mtx (this should be ok) */
1574                                         Mat4CpyMat4(tmat, cob.matrix);
1575                                         Mat4MulMat34(cob.matrix, td->mtx, tmat);
1576                                 }
1577                                 else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
1578                                         /* skip... incompatable spacetype */
1579                                         continue;
1580                                 }
1581                                 
1582                                 /* do constraint */
1583                                 cti->evaluate_constraint(con, &cob, NULL);
1584                                 
1585                                 /* convert spaces again */
1586                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1587                                         /* just multiply by td->mtx (this should be ok) */
1588                                         Mat4CpyMat4(tmat, cob.matrix);
1589                                         Mat4MulMat34(cob.matrix, td->smtx, tmat);
1590                                 }
1591                         }
1592                 }
1593                 
1594                 /* copy results from cob->matrix */
1595                 if (td->tdi) {
1596                         TransDataIpokey *tdi= td->tdi;
1597                         tdi->locx[0]= cob.matrix[3][0];
1598                         tdi->locy[0]= cob.matrix[3][1];
1599                         tdi->locz[0]= cob.matrix[3][2];
1600                 }
1601                 else {
1602                         VECCOPY(td->loc, cob.matrix[3]);
1603                 }
1604         }
1605 }
1606
1607 static void constraintRotLim(TransInfo *t, TransData *td)
1608 {
1609         if (td->con) {
1610                 bConstraintTypeInfo *cti= get_constraint_typeinfo(CONSTRAINT_TYPE_ROTLIMIT);
1611                 bConstraintOb cob;
1612                 bConstraint *con;
1613                 
1614                 /* Make a temporary bConstraintOb for using these limit constraints 
1615                  *      - they only care that cob->matrix is correctly set ;-)
1616                  *      - current space should be local
1617                  */
1618                 memset(&cob, 0, sizeof(bConstraintOb));
1619                 if (td->flag & TD_USEQUAT) {
1620                         /* quats */
1621                         if (td->ext)
1622                                 QuatToMat4(td->ext->quat, cob.matrix);
1623                         else
1624                                 return;
1625                 }
1626                 else if (td->tdi) {
1627                         /* ipo-keys eulers */
1628                         TransDataIpokey *tdi= td->tdi;
1629                         float eul[3];
1630                         
1631                         eul[0]= tdi->rotx[0];
1632                         eul[1]= tdi->roty[0];
1633                         eul[2]= tdi->rotz[0];
1634                         
1635                         EulToMat4(eul, cob.matrix);
1636                 }
1637                 else {
1638                         /* eulers */
1639                         if (td->ext)
1640                                 EulToMat4(td->ext->rot, cob.matrix);
1641                         else
1642                                 return;
1643                 }
1644                         
1645                 /* Evaluate valid constraints */
1646                 for (con= td->con; con; con= con->next) {
1647                         /* only consider constraint if enabled */
1648                         if (con->flag & CONSTRAINT_DISABLE) continue;
1649                         if (con->enforce == 0.0f) continue;
1650                         
1651                         /* we're only interested in Limit-Rotation constraints */
1652                         if (con->type == CONSTRAINT_TYPE_ROTLIMIT) {
1653                                 bRotLimitConstraint *data= con->data;
1654                                 float tmat[4][4];
1655                                 
1656                                 /* only use it if it's tagged for this purpose */
1657                                 if ((data->flag2 & LIMIT_TRANSFORM)==0) 
1658                                         continue;
1659                                         
1660                                 /* do space conversions */
1661                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1662                                         /* just multiply by td->mtx (this should be ok) */
1663                                         Mat4CpyMat4(tmat, cob.matrix);
1664                                         Mat4MulMat34(cob.matrix, td->mtx, tmat);
1665                                 }
1666                                 else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
1667                                         /* skip... incompatable spacetype */
1668                                         continue;
1669                                 }
1670                                 
1671                                 /* do constraint */
1672                                 cti->evaluate_constraint(con, &cob, NULL);
1673                                 
1674                                 /* convert spaces again */
1675                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1676                                         /* just multiply by td->mtx (this should be ok) */
1677                                         Mat4CpyMat4(tmat, cob.matrix);
1678                                         Mat4MulMat34(cob.matrix, td->smtx, tmat);
1679                                 }
1680                         }
1681                 }
1682                 
1683                 /* copy results from cob->matrix */
1684                 if (td->flag & TD_USEQUAT) {
1685                         /* quats */
1686                         Mat4ToQuat(cob.matrix, td->ext->quat);
1687                 }
1688                 else if (td->tdi) {
1689                         /* ipo-keys eulers */
1690                         TransDataIpokey *tdi= td->tdi;
1691                         float eul[3];
1692                         
1693                         Mat4ToEul(cob.matrix, eul);
1694                         
1695                         tdi->rotx[0]= eul[0];
1696                         tdi->roty[0]= eul[1];
1697                         tdi->rotz[0]= eul[2];
1698                 }
1699                 else {
1700                         /* eulers */
1701                         Mat4ToEul(cob.matrix, td->ext->rot);
1702                 }
1703         }
1704 }
1705
1706 static void constraintSizeLim(TransInfo *t, TransData *td)
1707 {
1708         if (td->con && td->ext) {
1709                 bConstraintTypeInfo *cti= get_constraint_typeinfo(CONSTRAINT_TYPE_SIZELIMIT);
1710                 bConstraintOb cob;
1711                 bConstraint *con;
1712                 
1713                 /* Make a temporary bConstraintOb for using these limit constraints 
1714                  *      - they only care that cob->matrix is correctly set ;-)
1715                  *      - current space should be local
1716                  */
1717                 memset(&cob, 0, sizeof(bConstraintOb));
1718                 if (td->tdi) {
1719                         TransDataIpokey *tdi= td->tdi;
1720                         float size[3];
1721                         
1722                         size[0]= tdi->sizex[0];
1723                         size[1]= tdi->sizey[0];
1724                         size[2]= tdi->sizez[0];
1725                         SizeToMat4(size, cob.matrix);
1726                 } 
1727                 else if ((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)) {
1728                         /* scale val and reset size */
1729                         return; // TODO: fix this case
1730                 }
1731                 else {
1732                         /* Reset val if SINGLESIZE but using a constraint */
1733                         if (td->flag & TD_SINGLESIZE)
1734                                 return;
1735                         
1736                         SizeToMat4(td->ext->size, cob.matrix);
1737                 }
1738                         
1739                 /* Evaluate valid constraints */
1740                 for (con= td->con; con; con= con->next) {
1741                         /* only consider constraint if enabled */
1742                         if (con->flag & CONSTRAINT_DISABLE) continue;
1743                         if (con->enforce == 0.0f) continue;
1744                         
1745                         /* we're only interested in Limit-Scale constraints */
1746                         if (con->type == CONSTRAINT_TYPE_SIZELIMIT) {
1747                                 bSizeLimitConstraint *data= con->data;
1748                                 float tmat[4][4];
1749                                 
1750                                 /* only use it if it's tagged for this purpose */
1751                                 if ((data->flag2 & LIMIT_TRANSFORM)==0) 
1752                                         continue;
1753                                         
1754                                 /* do space conversions */
1755                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1756                                         /* just multiply by td->mtx (this should be ok) */
1757                                         Mat4CpyMat4(tmat, cob.matrix);
1758                                         Mat4MulMat34(cob.matrix, td->mtx, tmat);
1759                                 }
1760                                 else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
1761                                         /* skip... incompatable spacetype */
1762                                         continue;
1763                                 }
1764                                 
1765                                 /* do constraint */
1766                                 cti->evaluate_constraint(con, &cob, NULL);
1767                                 
1768                                 /* convert spaces again */
1769                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1770                                         /* just multiply by td->mtx (this should be ok) */
1771                                         Mat4CpyMat4(tmat, cob.matrix);
1772                                         Mat4MulMat34(cob.matrix, td->smtx, tmat);
1773                                 }
1774                         }
1775                 }
1776                 
1777                 /* copy results from cob->matrix */
1778                 if (td->tdi) {
1779                         TransDataIpokey *tdi= td->tdi;
1780                         float size[3];
1781                         
1782                         Mat4ToSize(cob.matrix, size);
1783                         
1784                         tdi->sizex[0]= size[0];
1785                         tdi->sizey[0]= size[1];
1786                         tdi->sizez[0]= size[2];
1787                 } 
1788                 else if ((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)) {
1789                         /* scale val and reset size */
1790                         return; // TODO: fix this case
1791                 }
1792                 else {
1793                         /* Reset val if SINGLESIZE but using a constraint */
1794                         if (td->flag & TD_SINGLESIZE)
1795                                 return;
1796                                 
1797                         Mat4ToSize(cob.matrix, td->ext->size);
1798                 }
1799         }
1800 }
1801
1802 /* ************************** WARP *************************** */
1803
1804 void initWarp(TransInfo *t) 
1805 {
1806         float max[3], min[3];
1807         int i;
1808         
1809         t->mode = TFM_WARP;
1810         t->transform = Warp;
1811         t->handleEvent = handleEventWarp;
1812         
1813         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_RATIO);
1814
1815         t->idx_max = 0;
1816         t->num.idx_max = 0;
1817         t->snap[0] = 0.0f;
1818         t->snap[1] = 5.0f;
1819         t->snap[2] = 1.0f;
1820         
1821         t->flag |= T_NO_CONSTRAINT;
1822
1823         /* we need min/max in view space */
1824         for(i = 0; i < t->total; i++) {
1825                 float center[3];
1826                 VECCOPY(center, t->data[i].center);
1827                 Mat3MulVecfl(t->data[i].mtx, center);
1828                 Mat4MulVecfl(t->viewmat, center);
1829                 VecSubf(center, center, t->viewmat[3]);
1830                 if (i)
1831                         MinMax3(min, max, center);
1832                 else {
1833                         VECCOPY(max, center);
1834                         VECCOPY(min, center);
1835                 }
1836         }
1837         
1838         t->center[0]= (min[0]+max[0])/2.0f;
1839         t->center[1]= (min[1]+max[1])/2.0f;
1840         t->center[2]= (min[2]+max[2])/2.0f;
1841         
1842         if (max[0] == min[0]) max[0] += 0.1; /* not optimal, but flipping is better than invalid garbage (i.e. division by zero!) */
1843         t->val= (max[0]-min[0])/2.0f; /* t->val is X dimension projected boundbox */
1844 }
1845
1846 int handleEventWarp(TransInfo *t, wmEvent *event)
1847 {
1848         int status = 0;
1849         
1850         if (event->type == MIDDLEMOUSE && event->val)
1851         {
1852                 // Use customData pointer to signal warp direction
1853                 if      (t->customData == 0)
1854                         t->customData = (void*)1;
1855                 else
1856                         t->customData = 0;
1857                         
1858                 status = 1;
1859         }
1860         
1861         return status;
1862 }
1863
1864 int Warp(TransInfo *t, short mval[2])
1865 {
1866         TransData *td = t->data;
1867         float vec[3], circumfac, dist, phi0, co, si, *curs, cursor[3], gcursor[3];
1868         int i;
1869         char str[50];
1870         
1871         curs= give_cursor(t->scene, t->view);
1872         /*
1873          * gcursor is the one used for helpline.
1874          * It has to be in the same space as the drawing loop
1875          * (that means it needs to be in the object's space when in edit mode and
1876          *  in global space in object mode)
1877          *
1878          * cursor is used for calculations.
1879          * It needs to be in view space, but we need to take object's offset
1880          * into account if in Edit mode.
1881          */
1882         VECCOPY(cursor, curs);
1883         VECCOPY(gcursor, cursor);       
1884         if (t->flag & T_EDIT) {
1885                 VecSubf(cursor, cursor, t->obedit->obmat[3]);
1886                 VecSubf(gcursor, gcursor, t->obedit->obmat[3]);
1887                 Mat3MulVecfl(t->data->smtx, gcursor);
1888         }
1889         Mat4MulVecfl(t->viewmat, cursor);
1890         VecSubf(cursor, cursor, t->viewmat[3]);
1891
1892         /* amount of degrees for warp */
1893         circumfac = 360.0f * t->values[0];
1894         
1895         if (t->customData) /* non-null value indicates reversed input */
1896         {
1897                 circumfac *= -1;
1898         }
1899
1900         snapGrid(t, &circumfac);
1901         applyNumInput(&t->num, &circumfac);
1902         
1903         /* header print for NumInput */
1904         if (hasNumInput(&t->num)) {
1905                 char c[20];
1906                 
1907                 outputNumInput(&(t->num), c);
1908                 
1909                 sprintf(str, "Warp: %s", c);
1910         }
1911         else {
1912                 /* default header print */
1913                 sprintf(str, "Warp: %.3f", circumfac);
1914         }
1915         
1916         circumfac*= (float)(-M_PI/360.0);
1917         
1918         for(i = 0; i < t->total; i++, td++) {
1919                 float loc[3];
1920                 if (td->flag & TD_NOACTION)
1921                         break;
1922
1923                 if (td->flag & TD_SKIP)
1924                         continue;
1925                 
1926                 /* translate point to center, rotate in such a way that outline==distance */
1927                 VECCOPY(vec, td->iloc);
1928                 Mat3MulVecfl(td->mtx, vec);
1929                 Mat4MulVecfl(t->viewmat, vec);
1930                 VecSubf(vec, vec, t->viewmat[3]);
1931                 
1932                 dist= vec[0]-cursor[0];
1933                 
1934                 /* t->val is X dimension projected boundbox */
1935                 phi0= (circumfac*dist/t->val);  
1936                 
1937                 vec[1]= (vec[1]-cursor[1]);
1938                 
1939                 co= (float)cos(phi0);
1940                 si= (float)sin(phi0);
1941                 loc[0]= -si*vec[1]+cursor[0];
1942                 loc[1]= co*vec[1]+cursor[1];
1943                 loc[2]= vec[2];
1944                 
1945                 Mat4MulVecfl(t->viewinv, loc);
1946                 VecSubf(loc, loc, t->viewinv[3]);
1947                 Mat3MulVecfl(td->smtx, loc);
1948                 
1949                 VecSubf(loc, loc, td->iloc);
1950                 VecMulf(loc, td->factor);
1951                 VecAddf(td->loc, td->iloc, loc);
1952         }
1953
1954         recalcData(t);
1955         
1956         ED_area_headerprint(t->sa, str);
1957         
1958         helpline(t, gcursor);
1959         
1960         return 1;
1961 }
1962
1963 /* ************************** SHEAR *************************** */
1964
1965 void initShear(TransInfo *t) 
1966 {
1967         t->mode = TFM_SHEAR;
1968         t->transform = Shear;
1969         t->handleEvent = handleEventShear;
1970         
1971         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_ABSOLUTE);
1972         
1973         t->idx_max = 0;
1974         t->num.idx_max = 0;
1975         t->snap[0] = 0.0f;
1976         t->snap[1] = 0.1f;
1977         t->snap[2] = t->snap[1] * 0.1f;
1978         
1979         t->flag |= T_NO_CONSTRAINT;
1980 }
1981
1982 int handleEventShear(TransInfo *t, wmEvent *event)
1983 {
1984         int status = 0;
1985         
1986         if (event->type == MIDDLEMOUSE && event->val)
1987         {
1988                 // Use customData pointer to signal Shear direction
1989                 if      (t->customData == 0)
1990                 {
1991                         initMouseInputMode(t, &t->mouse, INPUT_VERTICAL_ABSOLUTE);
1992                         t->customData = (void*)1;
1993                 }
1994                 else
1995                 {
1996                         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_ABSOLUTE);
1997                         t->customData = 0;
1998                 }
1999                         
2000                 status = 1;
2001         }
2002         
2003         return status;
2004 }
2005
2006
2007 int Shear(TransInfo *t, short mval[2]) 
2008 {
2009         TransData *td = t->data;
2010         float vec[3];
2011         float smat[3][3], tmat[3][3], totmat[3][3], persmat[3][3], persinv[3][3];
2012         float value;
2013         int i;
2014         char str[50];
2015
2016         Mat3CpyMat4(persmat, t->viewmat);
2017         Mat3Inv(persinv, persmat);
2018
2019         value = 0.05f * t->values[0];
2020
2021         snapGrid(t, &value);
2022
2023         applyNumInput(&t->num, &value);
2024
2025         /* header print for NumInput */
2026         if (hasNumInput(&t->num)) {
2027                 char c[20];
2028
2029                 outputNumInput(&(t->num), c);
2030
2031                 sprintf(str, "Shear: %s %s", c, t->proptext);
2032         }
2033         else {
2034                 /* default header print */
2035                 sprintf(str, "Shear: %.3f %s", value, t->proptext);
2036         }
2037         
2038         Mat3One(smat);
2039         
2040         // Custom data signals shear direction
2041         if (t->customData == 0)
2042                 smat[1][0] = value;
2043         else
2044                 smat[0][1] = value;
2045         
2046         Mat3MulMat3(tmat, smat, persmat);
2047         Mat3MulMat3(totmat, persinv, tmat);
2048         
2049         for(i = 0 ; i < t->total; i++, td++) {
2050                 if (td->flag & TD_NOACTION)
2051                         break;
2052
2053                 if (td->flag & TD_SKIP)
2054                         continue;
2055
2056                 if (t->obedit) {
2057                         float mat3[3][3];
2058                         Mat3MulMat3(mat3, totmat, td->mtx);
2059                         Mat3MulMat3(tmat, td->smtx, mat3);
2060                 }
2061                 else {
2062                         Mat3CpyMat3(tmat, totmat);
2063                 }
2064                 VecSubf(vec, td->center, t->center);
2065
2066                 Mat3MulVecfl(tmat, vec);
2067
2068                 VecAddf(vec, vec, t->center);
2069                 VecSubf(vec, vec, td->center);
2070
2071                 VecMulf(vec, td->factor);
2072
2073                 VecAddf(td->loc, td->iloc, vec);
2074         }
2075
2076         recalcData(t);
2077
2078         ED_area_headerprint(t->sa, str);
2079
2080         helpline (t, t->center);
2081
2082         return 1;
2083 }
2084
2085 /* ************************** RESIZE *************************** */
2086
2087 void initResize(TransInfo *t) 
2088 {
2089         t->mode = TFM_RESIZE;
2090         t->transform = Resize;
2091         
2092         initMouseInputMode(t, &t->mouse, INPUT_SPRING_FLIP);
2093         
2094         t->flag |= T_NULL_ONE;
2095         t->num.flag |= NUM_NULL_ONE;
2096         t->num.flag |= NUM_AFFECT_ALL;
2097         if (!t->obedit) {
2098                 t->flag |= T_NO_ZERO;
2099                 t->num.flag |= NUM_NO_ZERO;
2100         }
2101         
2102         t->idx_max = 2;
2103         t->num.idx_max = 2;
2104         t->snap[0] = 0.0f;
2105         t->snap[1] = 0.1f;
2106         t->snap[2] = t->snap[1] * 0.1f;
2107 }
2108
2109 static void headerResize(TransInfo *t, float vec[3], char *str) {
2110         char tvec[60];
2111         if (hasNumInput(&t->num)) {
2112                 outputNumInput(&(t->num), tvec);
2113         }
2114         else {
2115                 sprintf(&tvec[0], "%.4f", vec[0]);
2116                 sprintf(&tvec[20], "%.4f", vec[1]);
2117                 sprintf(&tvec[40], "%.4f", vec[2]);
2118         }
2119
2120         if (t->con.mode & CON_APPLY) {
2121                 switch(t->num.idx_max) {
2122                 case 0:
2123                         sprintf(str, "Scale: %s%s %s", &tvec[0], t->con.text, t->proptext);
2124                         break;
2125                 case 1:
2126                         sprintf(str, "Scale: %s : %s%s %s", &tvec[0], &tvec[20], t->con.text, t->proptext);
2127                         break;
2128                 case 2:
2129                         sprintf(str, "Scale: %s : %s : %s%s %s", &tvec[0], &tvec[20], &tvec[40], t->con.text, t->proptext);
2130                 }
2131         }
2132         else {
2133                 if (t->flag & T_2D_EDIT)
2134                         sprintf(str, "Scale X: %s   Y: %s%s %s", &tvec[0], &tvec[20], t->con.text, t->proptext);
2135                 else
2136                         sprintf(str, "Scale X: %s   Y: %s  Z: %s%s %s", &tvec[0], &tvec[20], &tvec[40], t->con.text, t->proptext);
2137         }
2138 }
2139
2140 #define SIGN(a)         (a<-FLT_EPSILON?1:a>FLT_EPSILON?2:3)
2141 #define VECSIGNFLIP(a, b) ((SIGN(a[0]) & SIGN(b[0]))==0 || (SIGN(a[1]) & SIGN(b[1]))==0 || (SIGN(a[2]) & SIGN(b[2]))==0)
2142
2143 /* smat is reference matrix, only scaled */
2144 static void TransMat3ToSize( float mat[][3], float smat[][3], float *size)
2145 {
2146         float vec[3];
2147         
2148         VecCopyf(vec, mat[0]);
2149         size[0]= Normalize(vec);
2150         VecCopyf(vec, mat[1]);
2151         size[1]= Normalize(vec);
2152         VecCopyf(vec, mat[2]);
2153         size[2]= Normalize(vec);
2154         
2155         /* first tried with dotproduct... but the sign flip is crucial */
2156         if( VECSIGNFLIP(mat[0], smat[0]) ) size[0]= -size[0]; 
2157         if( VECSIGNFLIP(mat[1], smat[1]) ) size[1]= -size[1]; 
2158         if( VECSIGNFLIP(mat[2], smat[2]) ) size[2]= -size[2]; 
2159 }
2160
2161
2162 static void ElementResize(TransInfo *t, TransData *td, float mat[3][3]) {
2163         float tmat[3][3], smat[3][3], center[3];
2164         float vec[3];
2165
2166         if (t->flag & T_EDIT) {
2167                 Mat3MulMat3(smat, mat, td->mtx);
2168                 Mat3MulMat3(tmat, td->smtx, smat);
2169         }
2170         else {
2171                 Mat3CpyMat3(tmat, mat);
2172         }
2173
2174         if (t->con.applySize) {
2175                 t->con.applySize(t, td, tmat);
2176         }
2177
2178         /* local constraint shouldn't alter center */
2179         if (t->around == V3D_LOCAL) {
2180                 if (t->flag & T_OBJECT) {
2181                         VECCOPY(center, td->center);
2182                 }
2183                 else if (t->flag & T_EDIT) {
2184                         
2185                         if(t->around==V3D_LOCAL && (t->scene->selectmode & SCE_SELECT_FACE)) {
2186                                 VECCOPY(center, td->center);
2187                         }
2188                         else {
2189                                 VECCOPY(center, t->center);
2190                         }
2191                 }
2192                 else {
2193                         VECCOPY(center, t->center);
2194                 }
2195         }
2196         else {
2197                 VECCOPY(center, t->center);
2198         }
2199
2200         if (td->ext) {
2201                 float fsize[3];
2202                 
2203                 if (t->flag & (T_OBJECT|T_TEXTURE|T_POSE)) {
2204                         float obsizemat[3][3];
2205                         // Reorient the size mat to fit the oriented object.
2206                         Mat3MulMat3(obsizemat, tmat, td->axismtx);
2207                         //printmatrix3("obsizemat", obsizemat);
2208                         TransMat3ToSize(obsizemat, td->axismtx, fsize);
2209                         //printvecf("fsize", fsize);
2210                 }
2211                 else {
2212                         Mat3ToSize(tmat, fsize);
2213                 }
2214                 
2215                 protectedSizeBits(td->protectflag, fsize);
2216                 
2217                 if ((t->flag & T_V3D_ALIGN)==0) {       // align mode doesn't resize objects itself
2218                         /* handle ipokeys? */
2219                         if(td->tdi) {
2220                                 TransDataIpokey *tdi= td->tdi;
2221                                 /* calculate delta size (equal for size and dsize) */
2222                                 
2223                                 vec[0]= (tdi->oldsize[0])*(fsize[0] -1.0f) * td->factor;
2224                                 vec[1]= (tdi->oldsize[1])*(fsize[1] -1.0f) * td->factor;
2225                                 vec[2]= (tdi->oldsize[2])*(fsize[2] -1.0f) * td->factor;
2226                                 
2227                                 add_tdi_poin(tdi->sizex, tdi->oldsize,   vec[0]);
2228                                 add_tdi_poin(tdi->sizey, tdi->oldsize+1, vec[1]);
2229                                 add_tdi_poin(tdi->sizez, tdi->oldsize+2, vec[2]);
2230                                 
2231                         } 
2232                         else if((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)){
2233                                 /* scale val and reset size */
2234                                 *td->val = td->ival * fsize[0] * td->factor;
2235                                 
2236                                 td->ext->size[0] = td->ext->isize[0];
2237                                 td->ext->size[1] = td->ext->isize[1];
2238                                 td->ext->size[2] = td->ext->isize[2];
2239                         }
2240                         else {
2241                                 /* Reset val if SINGLESIZE but using a constraint */
2242                                 if (td->flag & TD_SINGLESIZE)
2243                                         *td->val = td->ival;
2244                                 
2245                                 td->ext->size[0] = td->ext->isize[0] * (fsize[0]) * td->factor;
2246                                 td->ext->size[1] = td->ext->isize[1] * (fsize[1]) * td->factor;
2247                                 td->ext->size[2] = td->ext->isize[2] * (fsize[2]) * td->factor;
2248                         }
2249                 }
2250                 
2251                 constraintSizeLim(t, td);
2252         }
2253         
2254         /* For individual element center, Editmode need to use iloc */
2255         if (t->flag & T_POINTS)
2256                 VecSubf(vec, td->iloc, center);
2257         else
2258                 VecSubf(vec, td->center, center);
2259
2260         Mat3MulVecfl(tmat, vec);
2261
2262         VecAddf(vec, vec, center);
2263         if (t->flag & T_POINTS)
2264                 VecSubf(vec, vec, td->iloc);
2265         else
2266                 VecSubf(vec, vec, td->center);
2267
2268         VecMulf(vec, td->factor);
2269
2270         if (t->flag & (T_OBJECT|T_POSE)) {
2271                 Mat3MulVecfl(td->smtx, vec);
2272         }
2273
2274         protectedTransBits(td->protectflag, vec);
2275
2276         if(td->tdi) {
2277                 TransDataIpokey *tdi= td->tdi;
2278                 add_tdi_poin(tdi->locx, tdi->oldloc, vec[0]);
2279                 add_tdi_poin(tdi->locy, tdi->oldloc+1, vec[1]);
2280                 add_tdi_poin(tdi->locz, tdi->oldloc+2, vec[2]);
2281         }
2282         else VecAddf(td->loc, td->iloc, vec);
2283         
2284         constraintTransLim(t, td);
2285 }
2286
2287 int Resize(TransInfo *t, short mval[2]) 
2288 {
2289         TransData *td;
2290         float size[3], mat[3][3];
2291         float ratio;
2292         int i;
2293         char str[200];
2294
2295         /* for manipulator, center handle, the scaling can't be done relative to center */
2296         if( (t->flag & T_USES_MANIPULATOR) && t->con.mode==0)
2297         {
2298                 ratio = 1.0f - ((t->imval[0] - mval[0]) + (t->imval[1] - mval[1]))/100.0f;
2299         }
2300         else
2301         {
2302                 ratio = t->values[0];
2303         }
2304         
2305         size[0] = size[1] = size[2] = ratio;
2306
2307         snapGrid(t, size);
2308
2309         if (hasNumInput(&t->num)) {
2310                 applyNumInput(&t->num, size);
2311                 constraintNumInput(t, size);
2312         }
2313
2314         applySnapping(t, size);
2315
2316         if (t->flag & T_AUTOVALUES)
2317         {
2318                 VECCOPY(size, t->auto_values);
2319         }
2320
2321         VECCOPY(t->values, size);
2322
2323         SizeToMat3(size, mat);
2324
2325         if (t->con.applySize) {
2326                 t->con.applySize(t, NULL, mat);
2327         }
2328
2329         Mat3CpyMat3(t->mat, mat);       // used in manipulator
2330         
2331         headerResize(t, size, str);
2332
2333         for(i = 0, td=t->data; i < t->total; i++, td++) {
2334                 if (td->flag & TD_NOACTION)
2335                         break;
2336
2337                 if (td->flag & TD_SKIP)
2338                         continue;
2339                 
2340                 ElementResize(t, td, mat);
2341         }
2342
2343         /* evil hack - redo resize if cliping needed */
2344         if (t->flag & T_CLIP_UV && clipUVTransform(t, size, 1)) {
2345                 SizeToMat3(size, mat);
2346
2347                 if (t->con.applySize)
2348                         t->con.applySize(t, NULL, mat);
2349
2350                 for(i = 0, td=t->data; i < t->total; i++, td++)
2351                         ElementResize(t, td, mat);
2352         }
2353
2354         recalcData(t);
2355
2356         ED_area_headerprint(t->sa, str);
2357
2358         if(!(t->flag & T_USES_MANIPULATOR)) helpline (t, t->center);
2359
2360         return 1;
2361 }
2362
2363 /* ************************** TOSPHERE *************************** */
2364
2365 void initToSphere(TransInfo *t) 
2366 {
2367         TransData *td = t->data;
2368         int i;
2369
2370         t->mode = TFM_TOSPHERE;
2371         t->transform = ToSphere;
2372         
2373         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_RATIO);
2374
2375         t->idx_max = 0;
2376         t->num.idx_max = 0;
2377         t->snap[0] = 0.0f;
2378         t->snap[1] = 0.1f;
2379         t->snap[2] = t->snap[1] * 0.1f;
2380         
2381         t->num.flag |= NUM_NULL_ONE | NUM_NO_NEGATIVE;
2382         t->flag |= T_NO_CONSTRAINT;
2383
2384         // Calculate average radius
2385         for(i = 0 ; i < t->total; i++, td++) {
2386                 t->val += VecLenf(t->center, td->iloc);
2387         }
2388
2389         t->val /= (float)t->total;
2390 }
2391
2392 int ToSphere(TransInfo *t, short mval[2]) 
2393 {
2394         float vec[3];
2395         float ratio, radius;
2396         int i;
2397         char str[64];
2398         TransData *td = t->data;
2399
2400         ratio = t->values[0];
2401
2402         snapGrid(t, &ratio);
2403
2404         applyNumInput(&t->num, &ratio);
2405
2406         if (ratio < 0)
2407                 ratio = 0.0f;
2408         else if (ratio > 1)
2409                 ratio = 1.0f;
2410
2411         /* header print for NumInput */
2412         if (hasNumInput(&t->num)) {
2413                 char c[20];
2414
2415                 outputNumInput(&(t->num), c);
2416
2417                 sprintf(str, "To Sphere: %s %s", c, t->proptext);
2418         }
2419         else {
2420                 /* default header print */
2421                 sprintf(str, "To Sphere: %.4f %s", ratio, t->proptext);
2422         }
2423         
2424         
2425         for(i = 0 ; i < t->total; i++, td++) {
2426                 float tratio;
2427                 if (td->flag & TD_NOACTION)
2428                         break;
2429
2430                 if (td->flag & TD_SKIP)
2431                         continue;
2432
2433                 VecSubf(vec, td->iloc, t->center);
2434
2435                 radius = Normalize(vec);
2436
2437                 tratio = ratio * td->factor;
2438
2439                 VecMulf(vec, radius * (1.0f - tratio) + t->val * tratio);
2440
2441                 VecAddf(td->loc, t->center, vec);
2442         }
2443         
2444
2445         recalcData(t);
2446
2447         ED_area_headerprint(t->sa, str);
2448
2449         return 1;
2450 }
2451
2452 /* ************************** ROTATION *************************** */
2453
2454
2455 void initRotation(TransInfo *t) 
2456 {
2457         t->mode = TFM_ROTATION;
2458         t->transform = Rotation;
2459         
2460         initMouseInputMode(t, &t->mouse, INPUT_ANGLE);
2461         
2462         t->ndof.axis = 16;
2463         /* Scale down and flip input for rotation */
2464         t->ndof.factor[0] = -0.2f;
2465         
2466         t->idx_max = 0;
2467         t->num.idx_max = 0;
2468         t->snap[0] = 0.0f;
2469         t->snap[1] = (float)((5.0/180)*M_PI);
2470         t->snap[2] = t->snap[1] * 0.2f;
2471         
2472         if (t->flag & T_2D_EDIT)
2473                 t->flag |= T_NO_CONSTRAINT;
2474 }
2475
2476 static void ElementRotation(TransInfo *t, TransData *td, float mat[3][3], short around) {
2477         float vec[3], totmat[3][3], smat[3][3];
2478         float eul[3], fmat[3][3], quat[4];
2479         float *center = t->center;
2480         
2481         /* local constraint shouldn't alter center */
2482         if (around == V3D_LOCAL) {
2483                 if (t->flag & (T_OBJECT|T_POSE)) {
2484                         center = td->center;
2485                 }
2486                 else {
2487                         /* !TODO! Make this if not rely on G */
2488                         if(around==V3D_LOCAL && (t->scene->selectmode & SCE_SELECT_FACE)) {
2489                                 center = td->center;
2490                         }
2491                 }
2492         }
2493                 
2494         if (t->flag & T_POINTS) {
2495                 Mat3MulMat3(totmat, mat, td->mtx);
2496                 Mat3MulMat3(smat, td->smtx, totmat);
2497                 
2498                 VecSubf(vec, td->iloc, center);
2499                 Mat3MulVecfl(smat, vec);
2500                 
2501                 VecAddf(td->loc, vec, center);
2502
2503                 VecSubf(vec,td->loc,td->iloc);
2504                 protectedTransBits(td->protectflag, vec);
2505                 VecAddf(td->loc, td->iloc, vec);
2506
2507                 if(td->flag & TD_USEQUAT) {
2508                         Mat3MulSerie(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2509                         Mat3ToQuat(fmat, quat); // Actual transform
2510                         
2511                         if(td->ext->quat){
2512                                 QuatMul(td->ext->quat, quat, td->ext->iquat);
2513                                 
2514                                 /* is there a reason not to have this here? -jahka */
2515                                 protectedQuaternionBits(td->protectflag, td->ext->quat, td->ext->iquat);
2516                         }
2517                 }
2518         }
2519         /**
2520          * HACK WARNING
2521          * 
2522          * This is some VERY ugly special case to deal with pose mode.
2523          * 
2524          * The problem is that mtx and smtx include each bone orientation.
2525          * 
2526          * That is needed to rotate each bone properly, HOWEVER, to calculate
2527          * the translation component, we only need the actual armature object's
2528          * matrix (and inverse). That is not all though. Once the proper translation
2529          * has been computed, it has to be converted back into the bone's space.
2530          */
2531         else if (t->flag & T_POSE) {
2532                 float pmtx[3][3], imtx[3][3];
2533
2534                 // Extract and invert armature object matrix            
2535                 Mat3CpyMat4(pmtx, t->poseobj->obmat);
2536                 Mat3Inv(imtx, pmtx);
2537                 
2538                 if ((td->flag & TD_NO_LOC) == 0)
2539                 {
2540                         VecSubf(vec, td->center, center);
2541                         
2542                         Mat3MulVecfl(pmtx, vec);        // To Global space
2543                         Mat3MulVecfl(mat, vec);         // Applying rotation
2544                         Mat3MulVecfl(imtx, vec);        // To Local space
2545                         
2546                         VecAddf(vec, vec, center);
2547                         /* vec now is the location where the object has to be */
2548                         
2549                         VecSubf(vec, vec, td->center); // Translation needed from the initial location
2550                         
2551                         Mat3MulVecfl(pmtx, vec);        // To Global space
2552                         Mat3MulVecfl(td->smtx, vec);// To Pose space
2553                                 
2554                         protectedTransBits(td->protectflag, vec);
2555                         
2556                         VecAddf(td->loc, td->iloc, vec);
2557                         
2558                         constraintTransLim(t, td);
2559                 }
2560                 
2561                 /* rotation */
2562                 if ((t->flag & T_V3D_ALIGN)==0) { // align mode doesn't rotate objects itself
2563                         /* euler or quaternion? */
2564                         if (td->flag & TD_USEQUAT) {
2565                                 Mat3MulSerie(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2566                                 
2567                                 Mat3ToQuat(fmat, quat); // Actual transform
2568                                 
2569                                 QuatMul(td->ext->quat, quat, td->ext->iquat);
2570                                 /* this function works on end result */
2571                                 protectedQuaternionBits(td->protectflag, td->ext->quat, td->ext->iquat);
2572                         }
2573                         else {
2574                                 float eulmat[3][3];
2575                                 
2576                                 Mat3MulMat3(totmat, mat, td->mtx);
2577                                 Mat3MulMat3(smat, td->smtx, totmat);
2578                                 
2579                                 /* calculate the total rotatation in eulers */
2580                                 VECCOPY(eul, td->ext->irot);
2581                                 EulToMat3(eul, eulmat);
2582                                 
2583                                 /* mat = transform, obmat = bone rotation */
2584                                 Mat3MulMat3(fmat, smat, eulmat);
2585                                 
2586                                 Mat3ToCompatibleEul(fmat, eul, td->ext->rot);
2587                                 
2588                                 /* and apply (to end result only) */
2589                                 protectedRotateBits(td->protectflag, eul, td->ext->irot);
2590                                 VECCOPY(td->ext->rot, eul);
2591                         }
2592                         
2593                         constraintRotLim(t, td);
2594                 }
2595         }
2596         else {
2597                 if ((td->flag & TD_NO_LOC) == 0)
2598                 {
2599                         /* translation */
2600                         VecSubf(vec, td->center, center);
2601                         Mat3MulVecfl(mat, vec);
2602                         VecAddf(vec, vec, center);
2603                         /* vec now is the location where the object has to be */
2604                         VecSubf(vec, vec, td->center);
2605                         Mat3MulVecfl(td->smtx, vec);
2606                         
2607                         protectedTransBits(td->protectflag, vec);
2608                         
2609                         if(td->tdi) {
2610                                 TransDataIpokey *tdi= td->tdi;
2611                                 add_tdi_poin(tdi->locx, tdi->oldloc, vec[0]);
2612                                 add_tdi_poin(tdi->locy, tdi->oldloc+1, vec[1]);
2613                                 add_tdi_poin(tdi->locz, tdi->oldloc+2, vec[2]);
2614                         }
2615                         else VecAddf(td->loc, td->iloc, vec);
2616                 }
2617                 
2618                 
2619                 constraintTransLim(t, td);
2620
2621                 /* rotation */
2622                 if ((t->flag & T_V3D_ALIGN)==0) { // align mode doesn't rotate objects itself
2623                         /* euler or quaternion? */
2624                     if (td->flag & TD_USEQUAT) {
2625                                 Mat3MulSerie(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2626                                 Mat3ToQuat(fmat, quat); // Actual transform
2627                                 
2628                                 QuatMul(td->ext->quat, quat, td->ext->iquat);
2629                                 /* this function works on end result */
2630                                 protectedQuaternionBits(td->protectflag, td->ext->quat, td->ext->iquat);
2631                         }
2632                         else {
2633                                 float obmat[3][3];
2634                                 
2635                                 /* are there ipo keys? */
2636                                 if(td->tdi) {
2637                                         TransDataIpokey *tdi= td->tdi;
2638                                         float current_rot[3];
2639                                         float rot[3];
2640                                         
2641                                         /* current IPO value for compatible euler */
2642                                         current_rot[0] = (tdi->rotx) ? tdi->rotx[0] : 0.0f;
2643                                         current_rot[1] = (tdi->roty) ? tdi->roty[0] : 0.0f;
2644                                         current_rot[2] = (tdi->rotz) ? tdi->rotz[0] : 0.0f;
2645                                         VecMulf(current_rot, (float)(M_PI_2 / 9.0));
2646                                         
2647                                         /* calculate the total rotatation in eulers */
2648                                         VecAddf(eul, td->ext->irot, td->ext->drot);
2649                                         EulToMat3(eul, obmat);
2650                                         /* mat = transform, obmat = object rotation */
2651                                         Mat3MulMat3(fmat, mat, obmat);
2652                                         
2653                                         Mat3ToCompatibleEul(fmat, eul, current_rot);
2654                                         
2655                                         /* correct back for delta rot */
2656                                         if(tdi->flag & TOB_IPODROT) {
2657                                                 VecSubf(rot, eul, td->ext->irot);
2658                                         }
2659                                         else {
2660                                                 VecSubf(rot, eul, td->ext->drot);
2661                                         }
2662                                         
2663                                         VecMulf(rot, (float)(9.0/M_PI_2));
2664                                         VecSubf(rot, rot, tdi->oldrot);
2665                                         
2666                                         protectedRotateBits(td->protectflag, rot, tdi->oldrot);
2667                                         
2668                                         add_tdi_poin(tdi->rotx, tdi->oldrot, rot[0]);
2669                                         add_tdi_poin(tdi->roty, tdi->oldrot+1, rot[1]);
2670                                         add_tdi_poin(tdi->rotz, tdi->oldrot+2, rot[2]);
2671                                 }
2672                                 else {
2673                                         Mat3MulMat3(totmat, mat, td->mtx);
2674                                         Mat3MulMat3(smat, td->smtx, totmat);
2675                                         
2676                                         /* calculate the total rotatation in eulers */
2677                                         VecAddf(eul, td->ext->irot, td->ext->drot); /* we have to correct for delta rot */
2678                                         EulToMat3(eul, obmat);
2679                                         /* mat = transform, obmat = object rotation */
2680                                         Mat3MulMat3(fmat, smat, obmat);
2681                                         
2682                                         Mat3ToCompatibleEul(fmat, eul, td->ext->rot);
2683                                         
2684                                         /* correct back for delta rot */
2685                                         VecSubf(eul, eul, td->ext->drot);
2686                                         
2687                                         /* and apply */
2688                                         protectedRotateBits(td->protectflag, eul, td->ext->irot);
2689                                         VECCOPY(td->ext->rot, eul);
2690                                 }
2691                         }
2692                         
2693                         constraintRotLim(t, td);
2694                 }
2695         }
2696 }
2697
2698 static void applyRotation(TransInfo *t, float angle, float axis[3]) 
2699 {
2700         TransData *td = t->data;
2701         float mat[3][3];
2702         int i;
2703
2704         VecRotToMat3(axis, angle, mat);
2705         
2706         for(i = 0 ; i < t->total; i++, td++) {
2707
2708                 if (td->flag & TD_NOACTION)
2709                         break;
2710
2711                 if (td->flag & TD_SKIP)
2712                         continue;
2713                 
2714                 if (t->con.applyRot) {
2715                         t->con.applyRot(t, td, axis, NULL);
2716                         VecRotToMat3(axis, angle * td->factor, mat);
2717                 }
2718                 else if (t->flag & T_PROP_EDIT) {
2719                         VecRotToMat3(axis, angle * td->factor, mat);
2720                 }
2721
2722                 ElementRotation(t, td, mat, t->around);
2723         }
2724 }
2725
2726 int Rotation(TransInfo *t, short mval[2]) 
2727 {
2728         char str[64];
2729
2730         float final;
2731
2732         float axis[3];
2733         float mat[3][3];
2734
2735         VECCOPY(axis, t->viewinv[2]);
2736         VecMulf(axis, -1.0f);
2737         Normalize(axis);
2738
2739         final = t->values[0];
2740
2741         applyNDofInput(&t->ndof, &final);
2742         
2743         snapGrid(t, &final);
2744
2745         if (t->con.applyRot) {
2746                 t->con.applyRot(t, NULL, axis, &final);
2747         }
2748         
2749         applySnapping(t, &final);
2750
2751         if (hasNumInput(&t->num)) {
2752                 char c[20];
2753
2754                 applyNumInput(&t->num, &final);
2755
2756                 outputNumInput(&(t->num), c);
2757
2758                 sprintf(str, "Rot: %s %s %s", &c[0], t->con.text, t->proptext);
2759
2760                 /* Clamp between -180 and 180 */
2761                 while (final >= 180.0)
2762                         final -= 360.0;
2763                 
2764                 while (final <= -180.0)
2765                         final += 360.0;
2766
2767                 final *= (float)(M_PI / 180.0);
2768         }
2769         else {
2770                 sprintf(str, "Rot: %.2f%s %s", 180.0*final/M_PI, t->con.text, t->proptext);
2771         }
2772
2773         VecRotToMat3(axis, final, mat);
2774
2775         // TRANSFORM_FIX_ME
2776 //      t->values[0] = final;           // used in manipulator
2777 //      Mat3CpyMat3(t->mat, mat);       // used in manipulator
2778         
2779         applyRotation(t, final, axis);
2780         
2781         recalcData(t);
2782
2783         ED_area_headerprint(t->sa, str);
2784
2785         if(!(t->flag & T_USES_MANIPULATOR)) helpline (t, t->center);
2786
2787         return 1;
2788 }
2789
2790
2791 /* ************************** TRACKBALL *************************** */
2792
2793 void initTrackball(TransInfo *t) 
2794 {
2795         t->mode = TFM_TRACKBALL;
2796         t->transform = Trackball;
2797         
2798         initMouseInputMode(t, &t->mouse, INPUT_TRACKBALL);
2799         
2800         t->ndof.axis = 40;
2801         /* Scale down input for rotation */
2802         t->ndof.factor[0] = 0.2f;
2803         t->ndof.factor[1] = 0.2f;
2804
2805         t->idx_max = 1;
2806         t->num.idx_max = 1;
2807         t->snap[0] = 0.0f;
2808         t->snap[1] = (float)((5.0/180)*M_PI);
2809         t->snap[2] = t->snap[1] * 0.2f;
2810         
2811         t->flag |= T_NO_CONSTRAINT;
2812 }
2813
2814 static void applyTrackball(TransInfo *t, float axis1[3], float axis2[3], float angles[2])
2815 {
2816         TransData *td = t->data;
2817         float mat[3][3], smat[3][3], totmat[3][3];
2818         int i;
2819
2820         VecRotToMat3(axis1, angles[0], smat);
2821         VecRotToMat3(axis2, angles[1], totmat);
2822         
2823         Mat3MulMat3(mat, smat, totmat);
2824
2825         for(i = 0 ; i < t->total; i++, td++) {
2826                 if (td->flag & TD_NOACTION)
2827                         break;
2828
2829                 if (td->flag & TD_SKIP)
2830                         continue;
2831                 
2832                 if (t->flag & T_PROP_EDIT) {
2833                         VecRotToMat3(axis1, td->factor * angles[0], smat);
2834                         VecRotToMat3(axis2, td->factor * angles[1], totmat);
2835                         
2836                         Mat3MulMat3(mat, smat, totmat);
2837                 }
2838                 
2839                 ElementRotation(t, td, mat, t->around);
2840         }
2841 }
2842
2843 int Trackball(TransInfo *t, short mval[2]) 
2844 {
2845         char str[128];
2846         float axis1[3], axis2[3];
2847         float mat[3][3], totmat[3][3], smat[3][3];
2848         float phi[2];
2849         
2850         VECCOPY(axis1, t->persinv[0]);
2851         VECCOPY(axis2, t->persinv[1]);
2852         Normalize(axis1);
2853         Normalize(axis2);
2854         
2855         phi[0] = t->values[0];
2856         phi[1] = t->values[1];
2857                 
2858         applyNDofInput(&t->ndof, phi);
2859         
2860         snapGrid(t, phi);
2861         
2862         if (hasNumInput(&t->num)) {
2863                 char c[40];
2864                 
2865                 applyNumInput(&t->num, phi);
2866                 
2867                 outputNumInput(&(t->num), c);
2868                 
2869                 sprintf(str, "Trackball: %s %s %s", &c[0], &c[20], t->proptext);
2870                 
2871                 phi[0] *= (float)(M_PI / 180.0);
2872                 phi[1] *= (float)(M_PI / 180.0);
2873         }
2874         else {
2875                 sprintf(str, "Trackball: %.2f %.2f %s", 180.0*phi[0]/M_PI, 180.0*phi[1]/M_PI, t->proptext);
2876         }
2877
2878         VecRotToMat3(axis1, phi[0], smat);
2879         VecRotToMat3(axis2, phi[1], totmat);
2880         
2881         Mat3MulMat3(mat, smat, totmat);
2882         
2883         // TRANSFORM_FIX_ME
2884         //Mat3CpyMat3(t->mat, mat);     // used in manipulator
2885         
2886         applyTrackball(t, axis1, axis2, phi);
2887         
2888         recalcData(t);
2889         
2890         ED_area_headerprint(t->sa, str);
2891         
2892         if(!(t->flag & T_USES_MANIPULATOR)) helpline (t, t->center);
2893         
2894         return 1;
2895 }
2896
2897 /* ************************** TRANSLATION *************************** */
2898         
2899 void initTranslation(TransInfo *t) 
2900 {
2901         t->mode = TFM_TRANSLATION;
2902         t->transform = Translation;
2903         
2904         initMouseInputMode(t, &t->mouse, INPUT_VECTOR);
2905
2906         t->idx_max = (t->flag & T_2D_EDIT)? 1: 2;
2907         t->num.flag = 0;
2908         t->num.idx_max = t->idx_max;
2909         
2910         t->ndof.axis = (t->flag & T_2D_EDIT)? 1|2: 1|2|4;
2911
2912         if(t->spacetype == SPACE_VIEW3D) {
2913                 View3D *v3d = t->view;
2914
2915                 t->snap[0] = 0.0f;
2916                 t->snap[1] = v3d->gridview * 1.0f;
2917                 t->snap[2] = t->snap[1] * 0.1f;
2918         }
2919         else if(t->spacetype == SPACE_IMAGE) {
2920                 t->snap[0] = 0.0f;
2921                 t->snap[1] = 0.125f;
2922                 t->snap[2] = 0.0625f;
2923         }
2924         else {
2925                 t->snap[0] = 0.0f;
2926                 t->snap[1] = t->snap[2] = 1.0f;
2927         }
2928 }
2929
2930 static void headerTranslation(TransInfo *t, float vec[3], char *str) {
2931         char tvec[60];
2932         char distvec[20];
2933         char autoik[20];
2934         float dist;
2935         
2936         if (hasNumInput(&t->num)) {
2937                 outputNumInput(&(t->num), tvec);
2938                 dist = VecLength(t->num.val);
2939         }
2940         else {
2941                 float dvec[3];
2942
2943                 VECCOPY(dvec, vec);
2944                 applyAspectRatio(t, dvec);
2945
2946                 dist = VecLength(vec);
2947                 sprintf(&tvec[0], "%.4f", dvec[0]);
2948                 sprintf(&tvec[20], "%.4f", dvec[1]);
2949                 sprintf(&tvec[40], "%.4f", dvec[2]);
2950         }
2951
2952         if( dist > 1e10 || dist < -1e10 )       /* prevent string buffer overflow */
2953                 sprintf(distvec, "%.4e", dist);
2954         else
2955                 sprintf(distvec, "%.4f", dist);
2956                 
2957         if(t->flag & T_AUTOIK) {
2958                 short chainlen= t->scene->toolsettings->autoik_chainlen;
2959                 
2960                 if(chainlen)
2961                         sprintf(autoik, "AutoIK-Len: %d", chainlen);
2962                 else
2963                         strcpy(autoik, "");
2964         }
2965         else
2966                 strcpy(autoik, "");
2967
2968         if (t->con.mode & CON_APPLY) {
2969                 switch(t->num.idx_max) {
2970                 case 0:
2971                         sprintf(str, "D: %s (%s)%s %s  %s", &tvec[0], distvec, t->con.text, t->proptext, &autoik[0]);
2972                         break;
2973                 case 1:
2974                         sprintf(str, "D: %s   D: %s (%s)%s %s  %s", &tvec[0], &tvec[20], distvec, t->con.text, t->proptext, &autoik[0]);
2975                         break;
2976                 case 2:
2977                         sprintf(str, "D: %s   D: %s  D: %s (%s)%s %s  %s", &tvec[0], &tvec[20], &tvec[40], distvec, t->con.text, t->proptext, &autoik[0]);
2978                 }
2979         }
2980         else {
2981                 if(t->flag & T_2D_EDIT)
2982                         sprintf(str, "Dx: %s   Dy: %s (%s)%s %s", &tvec[0], &tvec[20], distvec, t->con.text, t->proptext);
2983                 else
2984                         sprintf(str, "Dx: %s   Dy: %s  Dz: %s (%s)%s %s  %s", &tvec[0], &tvec[20], &tvec[40], distvec, t->con.text, t->proptext, &autoik[0]);
2985         }
2986 }
2987
2988 static void applyTranslation(TransInfo *t, float vec[3]) {
2989         TransData *td = t->data;
2990         float tvec[3];
2991         int i;
2992
2993         for(i = 0 ; i < t->total; i++, td++) {
2994                 if (td->flag & TD_NOACTION)
2995                         break;
2996                 
2997                 if (td->flag & TD_SKIP)
2998                         continue;
2999                 
3000                 /* handle snapping rotation before doing the translation */
3001                 if (usingSnappingNormal(t))
3002                 {
3003                         if (validSnappingNormal(t))
3004                         {
3005                                 float *original_normal = td->axismtx[2];
3006                                 float axis[3];
3007                                 float quat[4];
3008                                 float mat[3][3];
3009                                 float angle;
3010