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