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