Merge from trunk -r 24182:24247. Skipped change 24182 (merge of this branch into...
[blender.git] / source / blender / editors / transform / transform.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <math.h>
34 #include <float.h>
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #ifndef WIN32
41 #include <unistd.h>
42 #else
43 #include <io.h>
44 #endif
45
46 #include "MEM_guardedalloc.h"
47
48 #include "DNA_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 = RV3D_ORTHO;
144         }
145
146         calculateCenter2D(t);
147 }
148
149 void convertViewVec(TransInfo *t, float *vec, short dx, short dy)
150 {
151         if (t->spacetype==SPACE_VIEW3D) {
152                 if (t->ar->regiontype == RGN_TYPE_WINDOW)
153                 {
154                         window_to_3d_delta(t->ar, vec, dx, dy);
155                 }
156         }
157         else if(t->spacetype==SPACE_IMAGE) {
158                 View2D *v2d = t->view;
159                 float divx, divy, aspx, aspy;
160
161                 ED_space_image_uv_aspect(t->sa->spacedata.first, &aspx, &aspy);
162
163                 divx= v2d->mask.xmax-v2d->mask.xmin;
164                 divy= v2d->mask.ymax-v2d->mask.ymin;
165
166                 vec[0]= aspx*(v2d->cur.xmax-v2d->cur.xmin)*(dx)/divx;
167                 vec[1]= aspy*(v2d->cur.ymax-v2d->cur.ymin)*(dy)/divy;
168                 vec[2]= 0.0f;
169         }
170         else if(ELEM(t->spacetype, SPACE_IPO, SPACE_NLA)) {
171                 View2D *v2d = t->view;
172                 float divx, divy;
173
174                 divx= v2d->mask.xmax-v2d->mask.xmin;
175                 divy= v2d->mask.ymax-v2d->mask.ymin;
176
177                 vec[0]= (v2d->cur.xmax-v2d->cur.xmin)*(dx) / (divx);
178                 vec[1]= (v2d->cur.ymax-v2d->cur.ymin)*(dy) / (divy);
179                 vec[2]= 0.0f;
180         }
181         else if(t->spacetype==SPACE_NODE) {
182                 View2D *v2d = &t->ar->v2d;
183                 float divx, divy;
184
185                 divx= v2d->mask.xmax-v2d->mask.xmin;
186                 divy= v2d->mask.ymax-v2d->mask.ymin;
187
188                 vec[0]= (v2d->cur.xmax-v2d->cur.xmin)*(dx)/divx;
189                 vec[1]= (v2d->cur.ymax-v2d->cur.ymin)*(dy)/divy;
190                 vec[2]= 0.0f;
191         }
192         else if(t->spacetype==SPACE_SEQ) {
193                 View2D *v2d = &t->ar->v2d;
194                 float divx, divy;
195
196                 divx= v2d->mask.xmax-v2d->mask.xmin;
197                 divy= v2d->mask.ymax-v2d->mask.ymin;
198
199                 vec[0]= (v2d->cur.xmax-v2d->cur.xmin)*(dx)/divx;
200                 vec[1]= (v2d->cur.ymax-v2d->cur.ymin)*(dy)/divy;
201                 vec[2]= 0.0f;
202         }
203 }
204
205 void projectIntView(TransInfo *t, float *vec, int *adr)
206 {
207         if (t->spacetype==SPACE_VIEW3D) {
208                 if(t->ar->regiontype == RGN_TYPE_WINDOW)
209                         project_int_noclip(t->ar, vec, adr);
210         }
211         else if(t->spacetype==SPACE_IMAGE) {
212                 float aspx, aspy, v[2];
213
214                 ED_space_image_uv_aspect(t->sa->spacedata.first, &aspx, &aspy);
215                 v[0]= vec[0]/aspx;
216                 v[1]= vec[1]/aspy;
217
218                 UI_view2d_to_region_no_clip(t->view, v[0], v[1], adr, adr+1);
219         }
220         else if(ELEM(t->spacetype, SPACE_IPO, SPACE_NLA)) {
221                 int out[2] = {0, 0};
222
223                 UI_view2d_view_to_region((View2D *)t->view, vec[0], vec[1], out, out+1);
224                 adr[0]= out[0];
225                 adr[1]= out[1];
226         }
227         else if(t->spacetype==SPACE_SEQ) { /* XXX not tested yet, but should work */
228                 int out[2] = {0, 0};
229
230                 UI_view2d_view_to_region((View2D *)t->view, vec[0], vec[1], out, out+1);
231                 adr[0]= out[0];
232                 adr[1]= out[1];
233         }
234 }
235
236 void projectFloatView(TransInfo *t, float *vec, float *adr)
237 {
238         if (t->spacetype==SPACE_VIEW3D) {
239                 if(t->ar->regiontype == RGN_TYPE_WINDOW)
240                         project_float_noclip(t->ar, vec, adr);
241         }
242         else if(t->spacetype==SPACE_IMAGE) {
243                 int a[2];
244
245                 projectIntView(t, vec, a);
246                 adr[0]= a[0];
247                 adr[1]= a[1];
248         }
249         else if(ELEM(t->spacetype, SPACE_IPO, SPACE_NLA)) {
250                 int a[2];
251
252                 projectIntView(t, vec, a);
253                 adr[0]= a[0];
254                 adr[1]= a[1];
255         }
256 }
257
258 void applyAspectRatio(TransInfo *t, float *vec)
259 {
260         SpaceImage *sima= t->sa->spacedata.first;
261
262         if ((t->spacetype==SPACE_IMAGE) && (t->mode==TFM_TRANSLATION)) {
263                 float aspx, aspy;
264
265                 if((sima->flag & SI_COORDFLOATS)==0) {
266                         int width, height;
267                         ED_space_image_size(sima, &width, &height);
268
269                         vec[0] *= width;
270                         vec[1] *= height;
271                 }
272
273                 ED_space_image_uv_aspect(sima, &aspx, &aspy);
274                 vec[0] /= aspx;
275                 vec[1] /= aspy;
276         }
277 }
278
279 void removeAspectRatio(TransInfo *t, float *vec)
280 {
281         SpaceImage *sima= t->sa->spacedata.first;
282
283         if ((t->spacetype==SPACE_IMAGE) && (t->mode==TFM_TRANSLATION)) {
284                 float aspx, aspy;
285
286                 if((sima->flag & SI_COORDFLOATS)==0) {
287                         int width, height;
288                         ED_space_image_size(sima, &width, &height);
289
290                         vec[0] /= width;
291                         vec[1] /= height;
292                 }
293
294                 ED_space_image_uv_aspect(sima, &aspx, &aspy);
295                 vec[0] *= aspx;
296                 vec[1] *= aspy;
297         }
298 }
299
300 static void viewRedrawForce(bContext *C, TransInfo *t)
301 {
302         if (t->spacetype == SPACE_VIEW3D)
303         {
304                 /* Do we need more refined tags? */
305                 WM_event_add_notifier(C, NC_OBJECT|ND_TRANSFORM, NULL);
306                 
307                 /* for realtime animation record - send notifiers recognised by animation editors */
308                 if ((t->animtimer) && IS_AUTOKEY_ON(t->scene))
309                         WM_event_add_notifier(C, NC_OBJECT|ND_KEYS, NULL);
310         }
311         else if (t->spacetype == SPACE_ACTION) {
312                 //SpaceAction *saction= (SpaceAction *)t->sa->spacedata.first;
313                 WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME_EDIT, NULL);
314         }
315         else if (t->spacetype == SPACE_IPO) {
316                 //SpaceIpo *sipo= (SpaceIpo *)t->sa->spacedata.first;
317                 WM_event_add_notifier(C, NC_ANIMATION|ND_KEYFRAME_EDIT, NULL);
318         }
319         else if (t->spacetype == SPACE_NLA) {
320                 WM_event_add_notifier(C, NC_ANIMATION|ND_NLA_EDIT, NULL);
321         }
322         else if(t->spacetype == SPACE_NODE)
323         {
324                 //ED_area_tag_redraw(t->sa);
325                 WM_event_add_notifier(C, NC_SPACE|ND_SPACE_NODE_VIEW, NULL);
326         }
327         else if(t->spacetype == SPACE_SEQ)
328         {
329                 WM_event_add_notifier(C, NC_SCENE|ND_SEQUENCER, NULL);
330         }
331         else if (t->spacetype==SPACE_IMAGE) {
332                 // XXX how to deal with lock?
333 #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
1016         /* aftertrans does insert ipos and action channels, and clears base flags, doesnt read transdata */
1017         special_aftertrans_update(t);
1018
1019         postTrans(t);
1020
1021         MEM_freeN(t);
1022
1023         return success;
1024 }
1025
1026 typedef enum {
1027         UP,
1028         DOWN,
1029         LEFT,
1030         RIGHT
1031 } ArrowDirection;
1032 static void drawArrow(ArrowDirection d, short offset, short length, short size)
1033 {
1034         switch(d)
1035         {
1036                 case LEFT:
1037                         offset = -offset;
1038                         length = -length;
1039                         size = -size;
1040                 case RIGHT:
1041                         glBegin(GL_LINES);
1042                         glVertex2s( offset, 0);
1043                         glVertex2s( offset + length, 0);
1044                         glVertex2s( offset + length, 0);
1045                         glVertex2s( offset + length - size, -size);
1046                         glVertex2s( offset + length, 0);
1047                         glVertex2s( offset + length - size,  size);
1048                         glEnd();
1049                         break;
1050                 case DOWN:
1051                         offset = -offset;
1052                         length = -length;
1053                         size = -size;
1054                 case UP:
1055                         glBegin(GL_LINES);
1056                         glVertex2s( 0, offset);
1057                         glVertex2s( 0, offset + length);
1058                         glVertex2s( 0, offset + length);
1059                         glVertex2s(-size, offset + length - size);
1060                         glVertex2s( 0, offset + length);
1061                         glVertex2s( size, offset + length - size);
1062                         glEnd();
1063                         break;
1064         }
1065 }
1066
1067 static void drawArrowHead(ArrowDirection d, short size)
1068 {
1069         switch(d)
1070         {
1071                 case LEFT:
1072                         size = -size;
1073                 case RIGHT:
1074                         glBegin(GL_LINES);
1075                         glVertex2s( 0, 0);
1076                         glVertex2s( -size, -size);
1077                         glVertex2s( 0, 0);
1078                         glVertex2s( -size,  size);
1079                         glEnd();
1080                         break;
1081                 case DOWN:
1082                         size = -size;
1083                 case UP:
1084                         glBegin(GL_LINES);
1085                         glVertex2s( 0, 0);
1086                         glVertex2s(-size, -size);
1087                         glVertex2s( 0, 0);
1088                         glVertex2s( size, -size);
1089                         glEnd();
1090                         break;
1091         }
1092 }
1093
1094 static void drawArc(float size, float angle_start, float angle_end, int segments)
1095 {
1096         float delta = (angle_end - angle_start) / segments;
1097         float angle;
1098
1099         glBegin(GL_LINE_STRIP);
1100
1101         for( angle = angle_start; angle < angle_end; angle += delta)
1102         {
1103                 glVertex2f( cosf(angle) * size, sinf(angle) * size);
1104         }
1105         glVertex2f( cosf(angle_end) * size, sinf(angle_end) * size);
1106
1107         glEnd();
1108 }
1109
1110 void drawHelpline(const struct bContext *C, TransInfo *t)
1111 {
1112         if (t->helpline != HLP_NONE && !(t->flag & T_USES_MANIPULATOR))
1113         {
1114                 float vecrot[3], cent[2];
1115
1116                 VECCOPY(vecrot, t->center);
1117                 if(t->flag & T_EDIT) {
1118                         Object *ob= t->obedit;
1119                         if(ob) Mat4MulVecfl(ob->obmat, vecrot);
1120                 }
1121                 else if(t->flag & T_POSE) {
1122                         Object *ob=t->poseobj;
1123                         if(ob) Mat4MulVecfl(ob->obmat, vecrot);
1124                 }
1125
1126                 projectFloatView(t, vecrot, cent);      // no overflow in extreme cases
1127
1128                 glPushMatrix();
1129
1130                 switch(t->helpline)
1131                 {
1132                         case HLP_SPRING:
1133                                 UI_ThemeColor(TH_WIRE);
1134
1135                                 setlinestyle(3);
1136                                 glBegin(GL_LINE_STRIP);
1137                                 glVertex2sv(t->mval);
1138                                 glVertex2fv(cent);
1139                                 glEnd();
1140
1141                                 glTranslatef(t->mval[0], t->mval[1], 0);
1142                                 glRotatef(-180 / M_PI * atan2f(cent[0] - t->mval[0], cent[1] - t->mval[1]), 0, 0, 1);
1143
1144                                 setlinestyle(0);
1145                                 glLineWidth(3.0);
1146                                 drawArrow(UP, 5, 10, 5);
1147                                 drawArrow(DOWN, 5, 10, 5);
1148                                 glLineWidth(1.0);
1149                                 break;
1150                         case HLP_HARROW:
1151                                 UI_ThemeColor(TH_WIRE);
1152
1153                                 glTranslatef(t->mval[0], t->mval[1], 0);
1154
1155                                 glLineWidth(3.0);
1156                                 drawArrow(RIGHT, 5, 10, 5);
1157                                 drawArrow(LEFT, 5, 10, 5);
1158                                 glLineWidth(1.0);
1159                                 break;
1160                         case HLP_VARROW:
1161                                 UI_ThemeColor(TH_WIRE);
1162
1163                                 glTranslatef(t->mval[0], t->mval[1], 0);
1164
1165                                 glLineWidth(3.0);
1166                                 glBegin(GL_LINES);
1167                                 drawArrow(UP, 5, 10, 5);
1168                                 drawArrow(DOWN, 5, 10, 5);
1169                                 glLineWidth(1.0);
1170                                 break;
1171                         case HLP_ANGLE:
1172                                 {
1173                                         float dx = t->mval[0] - cent[0], dy = t->mval[1] - cent[1];
1174                                         float angle = atan2f(dy, dx);
1175                                         float dist = sqrtf(dx*dx + dy*dy);
1176                                         float delta_angle = MIN2(15 / dist, M_PI/4);
1177                                         float spacing_angle = MIN2(5 / dist, M_PI/12);
1178                                         UI_ThemeColor(TH_WIRE);
1179
1180                                         setlinestyle(3);
1181                                         glBegin(GL_LINE_STRIP);
1182                                         glVertex2sv(t->mval);
1183                                         glVertex2fv(cent);
1184                                         glEnd();
1185
1186                                         glTranslatef(cent[0], cent[1], 0);
1187
1188                                         setlinestyle(0);
1189                                         glLineWidth(3.0);
1190                                         drawArc(dist, angle - delta_angle, angle - spacing_angle, 10);
1191                                         drawArc(dist, angle + spacing_angle, angle + delta_angle, 10);
1192
1193                                         glPushMatrix();
1194
1195                                         glTranslatef(cosf(angle - delta_angle) * dist, sinf(angle - delta_angle) * dist, 0);
1196                                         glRotatef(180 / M_PI * (angle - delta_angle), 0, 0, 1);
1197
1198                                         drawArrowHead(DOWN, 5);
1199
1200                                         glPopMatrix();
1201
1202                                         glTranslatef(cosf(angle + delta_angle) * dist, sinf(angle + delta_angle) * dist, 0);
1203                                         glRotatef(180 / M_PI * (angle + delta_angle), 0, 0, 1);
1204
1205                                         drawArrowHead(UP, 5);
1206
1207                                         glLineWidth(1.0);
1208                                         break;
1209                                 }
1210                                 case HLP_TRACKBALL:
1211                                 {
1212                                         char col[3], col2[3];
1213                                         UI_GetThemeColor3ubv(TH_GRID, col);
1214
1215                                         glTranslatef(t->mval[0], t->mval[1], 0);
1216
1217                                         glLineWidth(3.0);
1218
1219                                         UI_make_axis_color(col, col2, 'x');
1220                                         glColor3ubv((GLubyte *)col2);
1221
1222                                         drawArrow(RIGHT, 5, 10, 5);
1223                                         drawArrow(LEFT, 5, 10, 5);
1224
1225                                         UI_make_axis_color(col, col2, 'y');
1226                                         glColor3ubv((GLubyte *)col2);
1227
1228                                         drawArrow(UP, 5, 10, 5);
1229                                         drawArrow(DOWN, 5, 10, 5);
1230                                         glLineWidth(1.0);
1231                                         break;
1232                                 }
1233                 }
1234
1235                 glPopMatrix();
1236         }
1237 }
1238
1239 void drawTransformView(const struct bContext *C, struct ARegion *ar, void *arg)
1240 {
1241         TransInfo *t = arg;
1242
1243         drawConstraint(C, t);
1244         drawPropCircle(C, t);
1245         drawSnapping(C, t);
1246 }
1247
1248 void drawTransformPixel(const struct bContext *C, struct ARegion *ar, void *arg)
1249 {
1250         TransInfo *t = arg;
1251
1252         drawHelpline(C, t);
1253 }
1254
1255 void saveTransform(bContext *C, TransInfo *t, wmOperator *op)
1256 {
1257         ToolSettings *ts = CTX_data_tool_settings(C);
1258         int constraint_axis[3] = {0, 0, 0};
1259         int proportional = 0;
1260
1261         if (RNA_struct_find_property(op->ptr, "value"))
1262         {
1263                 if (t->flag & T_AUTOVALUES)
1264                 {
1265                         RNA_float_set_array(op->ptr, "value", t->auto_values);
1266                 }
1267                 else
1268                 {
1269                         RNA_float_set_array(op->ptr, "value", t->values);
1270                 }
1271         }
1272
1273         /* XXX convert stupid flag to enum */
1274         switch(t->flag & (T_PROP_EDIT|T_PROP_CONNECTED))
1275         {
1276         case (T_PROP_EDIT|T_PROP_CONNECTED):
1277                 proportional = 2;
1278                 break;
1279         case T_PROP_EDIT:
1280                 proportional = 1;
1281                 break;
1282         default:
1283                 proportional = 0;
1284         }
1285
1286         // If modal, save settings back in scene if not set as operator argument
1287         if (t->flag & T_MODAL)
1288         {
1289                 /* save settings if not set in operator */
1290                 if (RNA_struct_find_property(op->ptr, "proportional") && !RNA_property_is_set(op->ptr, "proportional"))
1291                 {
1292                         ts->proportional = proportional;
1293                 }
1294
1295                 if (RNA_struct_find_property(op->ptr, "proportional_size") && !RNA_property_is_set(op->ptr, "proportional_size"))
1296                 {
1297                         ts->proportional_size = t->prop_size;
1298                 }
1299                         
1300                 if (RNA_struct_find_property(op->ptr, "proportional_editing_falloff") && !RNA_property_is_set(op->ptr, "proportional_editing_falloff"))
1301                 {
1302                         ts->prop_mode = t->prop_mode;
1303                 }
1304                 
1305                 if(t->spacetype == SPACE_VIEW3D)
1306                 {
1307                         if (RNA_struct_find_property(op->ptr, "constraint_orientation") && !RNA_property_is_set(op->ptr, "constraint_orientation"))
1308                         {
1309                                 View3D *v3d = t->view;
1310         
1311                                 v3d->twmode = t->current_orientation;
1312                         }
1313                 }
1314         }
1315         
1316         if (RNA_struct_find_property(op->ptr, "proportional"))
1317         {
1318                 RNA_enum_set(op->ptr, "proportional", proportional);
1319                 RNA_enum_set(op->ptr, "proportional_editing_falloff", t->prop_mode);
1320                 RNA_float_set(op->ptr, "proportional_size", t->prop_size);
1321         }
1322
1323         if (RNA_struct_find_property(op->ptr, "mirror"))
1324         {
1325                 RNA_boolean_set(op->ptr, "mirror", t->flag & T_MIRROR);
1326         }
1327
1328         if (RNA_struct_find_property(op->ptr, "constraint_axis"))
1329         {
1330                 RNA_enum_set(op->ptr, "constraint_orientation", t->current_orientation);
1331
1332                 if (t->con.mode & CON_APPLY)
1333                 {
1334                         if (t->con.mode & CON_AXIS0) {
1335                                 constraint_axis[0] = 1;
1336                         }
1337                         if (t->con.mode & CON_AXIS1) {
1338                                 constraint_axis[1] = 1;
1339                         }
1340                         if (t->con.mode & CON_AXIS2) {
1341                                 constraint_axis[2] = 1;
1342                         }
1343                 }
1344
1345                 RNA_boolean_set_array(op->ptr, "constraint_axis", constraint_axis);
1346         }
1347 }
1348
1349 int initTransform(bContext *C, TransInfo *t, wmOperator *op, wmEvent *event, int mode)
1350 {
1351         int options = 0;
1352
1353         /* added initialize, for external calls to set stuff in TransInfo, like undo string */
1354
1355         t->state = TRANS_RUNNING;
1356
1357         t->options = options;
1358
1359         t->mode = mode;
1360
1361         if (!initTransInfo(C, t, op, event))                                    // internal data, mouse, vectors
1362         {
1363                 return 0;
1364         }
1365
1366         if(t->spacetype == SPACE_VIEW3D)
1367         {
1368                 //calc_manipulator_stats(curarea);
1369                 initTransformOrientation(C, t);
1370
1371                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1372                 t->draw_handle_pixel = ED_region_draw_cb_activate(t->ar->type, drawTransformPixel, t, REGION_DRAW_POST_PIXEL);
1373         }
1374         else if(t->spacetype == SPACE_IMAGE) {
1375                 Mat3One(t->spacemtx);
1376                 t->draw_handle_view = ED_region_draw_cb_activate(t->ar->type, drawTransformView, t, REGION_DRAW_POST_VIEW);
1377                 t->draw_handle_pixel = ED_region_draw_cb_activate(t->ar->type, drawTransformPixel, t, REGION_DRAW_POST_PIXEL);
1378         }
1379         else
1380                 Mat3One(t->spacemtx);
1381
1382         createTransData(C, t);                  // make TransData structs from selection
1383
1384         if (t->total == 0) {
1385                 postTrans(t);
1386                 return 0;
1387         }
1388
1389         initSnapping(t, op); // Initialize snapping data AFTER mode flags
1390
1391         /* EVIL! posemode code can switch translation to rotate when 1 bone is selected. will be removed (ton) */
1392         /* EVIL2: we gave as argument also texture space context bit... was cleared */
1393         /* EVIL3: extend mode for animation editors also switches modes... but is best way to avoid duplicate code */
1394         mode = t->mode;
1395
1396         calculatePropRatio(t);
1397         calculateCenter(t);
1398
1399         initMouseInput(t, &t->mouse, t->center2d, t->imval);
1400
1401         switch (mode) {
1402         case TFM_TRANSLATION:
1403                 initTranslation(t);
1404                 break;
1405         case TFM_ROTATION:
1406                 initRotation(t);
1407                 break;
1408         case TFM_RESIZE:
1409                 initResize(t);
1410                 break;
1411         case TFM_TOSPHERE:
1412                 initToSphere(t);
1413                 break;
1414         case TFM_SHEAR:
1415                 initShear(t);
1416                 break;
1417         case TFM_WARP:
1418                 initWarp(t);
1419                 break;
1420         case TFM_SHRINKFATTEN:
1421                 initShrinkFatten(t);
1422                 break;
1423         case TFM_TILT:
1424                 initTilt(t);
1425                 break;
1426         case TFM_CURVE_SHRINKFATTEN:
1427                 initCurveShrinkFatten(t);
1428                 break;
1429         case TFM_TRACKBALL:
1430                 initTrackball(t);
1431                 break;
1432         case TFM_PUSHPULL:
1433                 initPushPull(t);
1434                 break;
1435         case TFM_CREASE:
1436                 initCrease(t);
1437                 break;
1438         case TFM_BONESIZE:
1439                 {       /* used for both B-Bone width (bonesize) as for deform-dist (envelope) */
1440                         bArmature *arm= t->poseobj->data;
1441                         if(arm->drawtype==ARM_ENVELOPE)
1442                                 initBoneEnvelope(t);
1443                         else
1444                                 initBoneSize(t);
1445                 }
1446                 break;
1447         case TFM_BONE_ENVELOPE:
1448                 initBoneEnvelope(t);
1449                 break;
1450         case TFM_EDGE_SLIDE:
1451                 initEdgeSlide(t);
1452                 break;
1453         case TFM_BONE_ROLL:
1454                 initBoneRoll(t);
1455                 break;
1456         case TFM_TIME_TRANSLATE:
1457                 initTimeTranslate(t);
1458                 break;
1459         case TFM_TIME_SLIDE:
1460                 initTimeSlide(t);
1461                 break;
1462         case TFM_TIME_SCALE:
1463                 initTimeScale(t);
1464                 break;
1465         case TFM_TIME_EXTEND:
1466                 /* now that transdata has been made, do like for TFM_TIME_TRANSLATE (for most Animation
1467                  * Editors because they have only 1D transforms for time values) or TFM_TRANSLATION
1468                  * (for Graph/NLA Editors only since they uses 'standard' transforms to get 2D movement)
1469                  * depending on which editor this was called from
1470                  */
1471                 if ELEM(t->spacetype, SPACE_IPO, SPACE_NLA)
1472                         initTranslation(t);
1473                 else
1474                         initTimeTranslate(t);
1475                 break;
1476         case TFM_BAKE_TIME:
1477                 initBakeTime(t);
1478                 break;
1479         case TFM_MIRROR:
1480                 initMirror(t);
1481                 break;
1482         case TFM_BEVEL:
1483                 initBevel(t);
1484                 break;
1485         case TFM_BWEIGHT:
1486                 initBevelWeight(t);
1487                 break;
1488         case TFM_ALIGN:
1489                 initAlign(t);
1490                 break;
1491         }
1492
1493         /* overwrite initial values if operator supplied a non-null vector */
1494         if (RNA_property_is_set(op->ptr, "value"))
1495         {
1496                 float values[4];
1497                 RNA_float_get_array(op->ptr, "value", values);
1498                 QUATCOPY(t->values, values);
1499                 QUATCOPY(t->auto_values, values);
1500                 t->flag |= T_AUTOVALUES;
1501         }
1502
1503         /* Constraint init from operator */
1504         if (RNA_struct_find_property(op->ptr, "constraint_axis") && RNA_property_is_set(op->ptr, "constraint_axis"))
1505         {
1506                 int constraint_axis[3];
1507
1508                 RNA_boolean_get_array(op->ptr, "constraint_axis", constraint_axis);
1509
1510                 if (constraint_axis[0] || constraint_axis[1] || constraint_axis[2])
1511                 {
1512                         t->con.mode |= CON_APPLY;
1513
1514                         if (constraint_axis[0]) {
1515                                 t->con.mode |= CON_AXIS0;
1516                         }
1517                         if (constraint_axis[1]) {
1518                                 t->con.mode |= CON_AXIS1;
1519                         }
1520                         if (constraint_axis[2]) {
1521                                 t->con.mode |= CON_AXIS2;
1522                         }
1523
1524                         setUserConstraint(t, t->current_orientation, t->con.mode, "%s");
1525                 }
1526         }
1527
1528         return 1;
1529 }
1530
1531 void transformApply(bContext *C, TransInfo *t)
1532 {
1533         if (t->redraw)
1534         {
1535                 if (t->modifiers & MOD_CONSTRAINT_SELECT)
1536                         t->con.mode |= CON_SELECT;
1537
1538                 selectConstraint(t);
1539                 if (t->transform) {
1540                         t->transform(t, t->mval);  // calls recalcData()
1541                         viewRedrawForce(C, t);
1542                 }
1543                 t->redraw = 0;
1544         }
1545
1546         /* If auto confirm is on, break after one pass */
1547         if (t->options & CTX_AUTOCONFIRM)
1548         {
1549                 t->state = TRANS_CONFIRM;
1550         }
1551
1552         if (BKE_ptcache_get_continue_physics())
1553         {
1554                 // TRANSFORM_FIX_ME
1555                 //do_screenhandlers(G.curscreen);
1556                 t->redraw = 1;
1557         }
1558 }
1559
1560 int transformEnd(bContext *C, TransInfo *t)
1561 {
1562         int exit_code = OPERATOR_RUNNING_MODAL;
1563
1564         if (t->state != TRANS_RUNNING)
1565         {
1566                 /* handle restoring objects */
1567                 if(t->state == TRANS_CANCEL)
1568                 {
1569                         exit_code = OPERATOR_CANCELLED;
1570                         restoreTransObjects(t); // calls recalcData()
1571                 }
1572                 else
1573                 {
1574                         exit_code = OPERATOR_FINISHED;
1575                 }
1576
1577                 /* aftertrans does insert keyframes, and clears base flags, doesnt read transdata */
1578                 special_aftertrans_update(t);
1579
1580                 /* free data */
1581                 postTrans(t);
1582
1583                 /* send events out for redraws */
1584                 viewRedrawPost(t);
1585
1586                 /*  Undo as last, certainly after special_trans_update! */
1587
1588                 if(t->state == TRANS_CANCEL) {
1589 //                      if(t->undostr) ED_undo_push(C, t->undostr);
1590                 }
1591                 else {
1592 //                      if(t->undostr) ED_undo_push(C, t->undostr);
1593 //                      else ED_undo_push(C, transform_to_undostr(t));
1594                 }
1595                 t->undostr= NULL;
1596
1597                 viewRedrawForce(C, t);
1598         }
1599
1600         return exit_code;
1601 }
1602
1603 /* ************************** TRANSFORM LOCKS **************************** */
1604
1605 static void protectedTransBits(short protectflag, float *vec)
1606 {
1607         if(protectflag & OB_LOCK_LOCX)
1608                 vec[0]= 0.0f;
1609         if(protectflag & OB_LOCK_LOCY)
1610                 vec[1]= 0.0f;
1611         if(protectflag & OB_LOCK_LOCZ)
1612                 vec[2]= 0.0f;
1613 }
1614
1615 static void protectedSizeBits(short protectflag, float *size)
1616 {
1617         if(protectflag & OB_LOCK_SCALEX)
1618                 size[0]= 1.0f;
1619         if(protectflag & OB_LOCK_SCALEY)
1620                 size[1]= 1.0f;
1621         if(protectflag & OB_LOCK_SCALEZ)
1622                 size[2]= 1.0f;
1623 }
1624
1625 static void protectedRotateBits(short protectflag, float *eul, float *oldeul)
1626 {
1627         if(protectflag & OB_LOCK_ROTX)
1628                 eul[0]= oldeul[0];
1629         if(protectflag & OB_LOCK_ROTY)
1630                 eul[1]= oldeul[1];
1631         if(protectflag & OB_LOCK_ROTZ)
1632                 eul[2]= oldeul[2];
1633 }
1634
1635
1636 /* this function only does the delta rotation */
1637 /* axis-angle is usually internally stored as quats... */
1638 static void protectedAxisAngleBits(short protectflag, float axis[3], float *angle, float oldAxis[3], float oldAngle)
1639 {
1640         /* check that protection flags are set */
1641         if ((protectflag & (OB_LOCK_ROTX|OB_LOCK_ROTY|OB_LOCK_ROTZ|OB_LOCK_ROTW)) == 0)
1642                 return;
1643         
1644         if (protectflag & OB_LOCK_ROT4D) {
1645                 /* axis-angle getting limited as 4D entities that they are... */
1646                 if (protectflag & OB_LOCK_ROTW)
1647                         *angle= oldAngle;
1648                 if (protectflag & OB_LOCK_ROTX)
1649                         axis[0]= oldAxis[0];
1650                 if (protectflag & OB_LOCK_ROTY)
1651                         axis[1]= oldAxis[1];
1652                 if (protectflag & OB_LOCK_ROTZ)
1653                         axis[2]= oldAxis[2];
1654         }
1655         else {
1656                 /* axis-angle get limited with euler... */
1657                 float eul[3], oldeul[3];
1658                 
1659                 AxisAngleToEulO(axis, *angle, eul, EULER_ORDER_DEFAULT);
1660                 AxisAngleToEulO(oldAxis, oldAngle, oldeul, EULER_ORDER_DEFAULT);
1661                 
1662                 if (protectflag & OB_LOCK_ROTX)
1663                         eul[0]= oldeul[0];
1664                 if (protectflag & OB_LOCK_ROTY)
1665                         eul[1]= oldeul[1];
1666                 if (protectflag & OB_LOCK_ROTZ)
1667                         eul[2]= oldeul[2];
1668                 
1669                 EulOToAxisAngle(eul, EULER_ORDER_DEFAULT, axis, angle);
1670                 
1671                 /* when converting to axis-angle, we need a special exception for the case when there is no axis */
1672                 if (IS_EQ(axis[0], axis[1]) && IS_EQ(axis[1], axis[2])) {
1673                         /* for now, rotate around y-axis then (so that it simply becomes the roll) */
1674                         axis[1]= 1.0f;
1675                 }
1676         }
1677 }
1678
1679 /* this function only does the delta rotation */
1680 static void protectedQuaternionBits(short protectflag, float *quat, float *oldquat)
1681 {
1682         /* check that protection flags are set */
1683         if ((protectflag & (OB_LOCK_ROTX|OB_LOCK_ROTY|OB_LOCK_ROTZ|OB_LOCK_ROTW)) == 0)
1684                 return;
1685         
1686         if (protectflag & OB_LOCK_ROT4D) {
1687                 /* quaternions getting limited as 4D entities that they are... */
1688                 if (protectflag & OB_LOCK_ROTW)
1689                         quat[0]= oldquat[0];
1690                 if (protectflag & OB_LOCK_ROTX)
1691                         quat[1]= oldquat[1];
1692                 if (protectflag & OB_LOCK_ROTY)
1693                         quat[2]= oldquat[2];
1694                 if (protectflag & OB_LOCK_ROTZ)
1695                         quat[3]= oldquat[3];
1696         }
1697         else {
1698                 /* quaternions get limited with euler... (compatability mode) */
1699                 float eul[3], oldeul[3], quat1[4];
1700                 
1701                 QUATCOPY(quat1, quat);
1702                 QuatToEul(quat, eul);
1703                 QuatToEul(oldquat, oldeul);
1704                 
1705                 if (protectflag & OB_LOCK_ROTX)
1706                         eul[0]= oldeul[0];
1707                 if (protectflag & OB_LOCK_ROTY)
1708                         eul[1]= oldeul[1];
1709                 if (protectflag & OB_LOCK_ROTZ)
1710                         eul[2]= oldeul[2];
1711                 
1712                 EulToQuat(eul, quat);
1713                 
1714                 /* quaternions flip w sign to accumulate rotations correctly */
1715                 if ( (quat1[0]<0.0f && quat[0]>0.0f) || (quat1[0]>0.0f && quat[0]<0.0f) ) {
1716                         QuatMulf(quat, -1.0f);
1717                 }
1718         }
1719 }
1720
1721 /* ******************* TRANSFORM LIMITS ********************** */
1722
1723 static void constraintTransLim(TransInfo *t, TransData *td)
1724 {
1725         if (td->con) {
1726                 bConstraintTypeInfo *cti= get_constraint_typeinfo(CONSTRAINT_TYPE_LOCLIMIT);
1727                 bConstraintOb cob;
1728                 bConstraint *con;
1729                 
1730                 /* Make a temporary bConstraintOb for using these limit constraints
1731                  *      - they only care that cob->matrix is correctly set ;-)
1732                  *      - current space should be local
1733                  */
1734                 memset(&cob, 0, sizeof(bConstraintOb));
1735                 Mat4One(cob.matrix);
1736                 VECCOPY(cob.matrix[3], td->loc);
1737                 
1738                 /* Evaluate valid constraints */
1739                 for (con= td->con; con; con= con->next) {
1740                         float tmat[4][4];
1741                         
1742                         /* only consider constraint if enabled */
1743                         if (con->flag & CONSTRAINT_DISABLE) continue;
1744                         if (con->enforce == 0.0f) continue;
1745                         
1746                         /* only use it if it's tagged for this purpose (and the right type) */
1747                         if (con->type == CONSTRAINT_TYPE_LOCLIMIT) {
1748                                 bLocLimitConstraint *data= con->data;
1749                                 
1750                                 if ((data->flag2 & LIMIT_TRANSFORM)==0)
1751                                         continue;
1752                                 
1753                                 /* do space conversions */
1754                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1755                                         /* just multiply by td->mtx (this should be ok) */
1756                                         Mat4CpyMat4(tmat, cob.matrix);
1757                                         Mat4MulMat34(cob.matrix, td->mtx, tmat);
1758                                 }
1759                                 else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
1760                                         /* skip... incompatable spacetype */
1761                                         continue;
1762                                 }
1763                                 
1764                                 /* do constraint */
1765                                 cti->evaluate_constraint(con, &cob, NULL);
1766                                 
1767                                 /* convert spaces again */
1768                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1769                                         /* just multiply by td->mtx (this should be ok) */
1770                                         Mat4CpyMat4(tmat, cob.matrix);
1771                                         Mat4MulMat34(cob.matrix, td->smtx, tmat);
1772                                 }
1773                         }
1774                 }
1775                 
1776                 /* copy results from cob->matrix */
1777                 VECCOPY(td->loc, cob.matrix[3]);
1778         }
1779 }
1780
1781 static void constraintRotLim(TransInfo *t, TransData *td)
1782 {
1783         if (td->con) {
1784                 bConstraintTypeInfo *cti= get_constraint_typeinfo(CONSTRAINT_TYPE_ROTLIMIT);
1785                 bConstraintOb cob;
1786                 bConstraint *con;
1787
1788                 /* Make a temporary bConstraintOb for using these limit constraints
1789                  *      - they only care that cob->matrix is correctly set ;-)
1790                  *      - current space should be local
1791                  */
1792                 memset(&cob, 0, sizeof(bConstraintOb));
1793                 if (td->rotOrder == ROT_MODE_QUAT) {
1794                         /* quats */
1795                         if (td->ext)
1796                                 QuatToMat4(td->ext->quat, cob.matrix);
1797                         else
1798                                 return;
1799                 }
1800                 else if (td->rotOrder == ROT_MODE_AXISANGLE) {
1801                         /* axis angle */
1802                         if (td->ext)
1803                                 AxisAngleToMat4(&td->ext->quat[1], td->ext->quat[0], cob.matrix);
1804                         else
1805                                 return;
1806                 }
1807                 else {
1808                         /* eulers */
1809                         if (td->ext)
1810                                 EulOToMat4(td->ext->rot, td->rotOrder, cob.matrix);
1811                         else
1812                                 return;
1813                 }
1814                 
1815                 /* Evaluate valid constraints */
1816                 for (con= td->con; con; con= con->next) {
1817                         /* only consider constraint if enabled */
1818                         if (con->flag & CONSTRAINT_DISABLE) continue;
1819                         if (con->enforce == 0.0f) continue;
1820                         
1821                         /* we're only interested in Limit-Rotation constraints */
1822                         if (con->type == CONSTRAINT_TYPE_ROTLIMIT) {
1823                                 bRotLimitConstraint *data= con->data;
1824                                 float tmat[4][4];
1825                                 
1826                                 /* only use it if it's tagged for this purpose */
1827                                 if ((data->flag2 & LIMIT_TRANSFORM)==0)
1828                                         continue;
1829                                 
1830                                 /* do space conversions */
1831                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1832                                         /* just multiply by td->mtx (this should be ok) */
1833                                         Mat4CpyMat4(tmat, cob.matrix);
1834                                         Mat4MulMat34(cob.matrix, td->mtx, tmat);
1835                                 }
1836                                 else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
1837                                         /* skip... incompatable spacetype */
1838                                         continue;
1839                                 }
1840                                 
1841                                 /* do constraint */
1842                                 cti->evaluate_constraint(con, &cob, NULL);
1843                                 
1844                                 /* convert spaces again */
1845                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1846                                         /* just multiply by td->mtx (this should be ok) */
1847                                         Mat4CpyMat4(tmat, cob.matrix);
1848                                         Mat4MulMat34(cob.matrix, td->smtx, tmat);
1849                                 }
1850                         }
1851                 }
1852                 
1853                 /* copy results from cob->matrix */
1854                 if (td->rotOrder == ROT_MODE_QUAT) {
1855                         /* quats */
1856                         Mat4ToQuat(cob.matrix, td->ext->quat);
1857                 }
1858                 else if (td->rotOrder == ROT_MODE_AXISANGLE) {
1859                         /* axis angle */
1860                         Mat4ToAxisAngle(cob.matrix, &td->ext->quat[1], &td->ext->quat[0]);
1861                 }
1862                 else {
1863                         /* eulers */
1864                         Mat4ToEulO(cob.matrix, td->ext->rot, td->rotOrder);
1865                 }
1866         }
1867 }
1868
1869 static void constraintSizeLim(TransInfo *t, TransData *td)
1870 {
1871         if (td->con && td->ext) {
1872                 bConstraintTypeInfo *cti= get_constraint_typeinfo(CONSTRAINT_TYPE_SIZELIMIT);
1873                 bConstraintOb cob;
1874                 bConstraint *con;
1875                 
1876                 /* Make a temporary bConstraintOb for using these limit constraints
1877                  *      - they only care that cob->matrix is correctly set ;-)
1878                  *      - current space should be local
1879                  */
1880                 memset(&cob, 0, sizeof(bConstraintOb));
1881                 if ((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)) {
1882                         /* scale val and reset size */
1883                         return; // TODO: fix this case
1884                 }
1885                 else {
1886                         /* Reset val if SINGLESIZE but using a constraint */
1887                         if (td->flag & TD_SINGLESIZE)
1888                                 return;
1889                         
1890                         SizeToMat4(td->ext->size, cob.matrix);
1891                 }
1892                 
1893                 /* Evaluate valid constraints */
1894                 for (con= td->con; con; con= con->next) {
1895                         /* only consider constraint if enabled */
1896                         if (con->flag & CONSTRAINT_DISABLE) continue;
1897                         if (con->enforce == 0.0f) continue;
1898                         
1899                         /* we're only interested in Limit-Scale constraints */
1900                         if (con->type == CONSTRAINT_TYPE_SIZELIMIT) {
1901                                 bSizeLimitConstraint *data= con->data;
1902                                 float tmat[4][4];
1903                                 
1904                                 /* only use it if it's tagged for this purpose */
1905                                 if ((data->flag2 & LIMIT_TRANSFORM)==0)
1906                                         continue;
1907                                 
1908                                 /* do space conversions */
1909                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1910                                         /* just multiply by td->mtx (this should be ok) */
1911                                         Mat4CpyMat4(tmat, cob.matrix);
1912                                         Mat4MulMat34(cob.matrix, td->mtx, tmat);
1913                                 }
1914                                 else if (con->ownspace != CONSTRAINT_SPACE_LOCAL) {
1915                                         /* skip... incompatable spacetype */
1916                                         continue;
1917                                 }
1918                                 
1919                                 /* do constraint */
1920                                 cti->evaluate_constraint(con, &cob, NULL);
1921                                 
1922                                 /* convert spaces again */
1923                                 if (con->ownspace == CONSTRAINT_SPACE_WORLD) {
1924                                         /* just multiply by td->mtx (this should be ok) */
1925                                         Mat4CpyMat4(tmat, cob.matrix);
1926                                         Mat4MulMat34(cob.matrix, td->smtx, tmat);
1927                                 }
1928                         }
1929                 }
1930                 
1931                 /* copy results from cob->matrix */
1932                 if ((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)) {
1933                         /* scale val and reset size */
1934                         return; // TODO: fix this case
1935                 }
1936                 else {
1937                         /* Reset val if SINGLESIZE but using a constraint */
1938                         if (td->flag & TD_SINGLESIZE)
1939                                 return;
1940                         
1941                         Mat4ToSize(cob.matrix, td->ext->size);
1942                 }
1943         }
1944 }
1945
1946 /* ************************** WARP *************************** */
1947
1948 void initWarp(TransInfo *t)
1949 {
1950         float max[3], min[3];
1951         int i;
1952         
1953         t->mode = TFM_WARP;
1954         t->transform = Warp;
1955         t->handleEvent = handleEventWarp;
1956         
1957         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_RATIO);
1958         
1959         t->idx_max = 0;
1960         t->num.idx_max = 0;
1961         t->snap[0] = 0.0f;
1962         t->snap[1] = 5.0f;
1963         t->snap[2] = 1.0f;
1964         
1965         t->flag |= T_NO_CONSTRAINT;
1966         
1967         /* we need min/max in view space */
1968         for(i = 0; i < t->total; i++) {
1969                 float center[3];
1970                 VECCOPY(center, t->data[i].center);
1971                 Mat3MulVecfl(t->data[i].mtx, center);
1972                 Mat4MulVecfl(t->viewmat, center);
1973                 VecSubf(center, center, t->viewmat[3]);
1974                 if (i)
1975                         MinMax3(min, max, center);
1976                 else {
1977                         VECCOPY(max, center);
1978                         VECCOPY(min, center);
1979                 }
1980         }
1981         
1982         t->center[0]= (min[0]+max[0])/2.0f;
1983         t->center[1]= (min[1]+max[1])/2.0f;
1984         t->center[2]= (min[2]+max[2])/2.0f;
1985
1986         if (max[0] == min[0]) max[0] += 0.1; /* not optimal, but flipping is better than invalid garbage (i.e. division by zero!) */
1987         t->val= (max[0]-min[0])/2.0f; /* t->val is X dimension projected boundbox */
1988 }
1989
1990 int handleEventWarp(TransInfo *t, wmEvent *event)
1991 {
1992         int status = 0;
1993         
1994         if (event->type == MIDDLEMOUSE && event->val==KM_PRESS)
1995         {
1996                 // Use customData pointer to signal warp direction
1997                 if      (t->customData == 0)
1998                         t->customData = (void*)1;
1999                 else
2000                         t->customData = 0;
2001                 
2002                 status = 1;
2003         }
2004         
2005         return status;
2006 }
2007
2008 int Warp(TransInfo *t, short mval[2])
2009 {
2010         TransData *td = t->data;
2011         float vec[3], circumfac, dist, phi0, co, si, *curs, cursor[3], gcursor[3];
2012         int i;
2013         char str[50];
2014         
2015         curs= give_cursor(t->scene, t->view);
2016         /*
2017          * gcursor is the one used for helpline.
2018          * It has to be in the same space as the drawing loop
2019          * (that means it needs to be in the object's space when in edit mode and
2020          *  in global space in object mode)
2021          *
2022          * cursor is used for calculations.
2023          * It needs to be in view space, but we need to take object's offset
2024          * into account if in Edit mode.
2025          */
2026         VECCOPY(cursor, curs);
2027         VECCOPY(gcursor, cursor);
2028         if (t->flag & T_EDIT) {
2029                 VecSubf(cursor, cursor, t->obedit->obmat[3]);
2030                 VecSubf(gcursor, gcursor, t->obedit->obmat[3]);
2031                 Mat3MulVecfl(t->data->smtx, gcursor);
2032         }
2033         Mat4MulVecfl(t->viewmat, cursor);
2034         VecSubf(cursor, cursor, t->viewmat[3]);
2035         
2036         /* amount of degrees for warp */
2037         circumfac = 360.0f * t->values[0];
2038         
2039         if (t->customData) /* non-null value indicates reversed input */
2040         {
2041                 circumfac *= -1;
2042         }
2043         
2044         snapGrid(t, &circumfac);
2045         applyNumInput(&t->num, &circumfac);
2046         
2047         /* header print for NumInput */
2048         if (hasNumInput(&t->num)) {
2049                 char c[20];
2050                 
2051                 outputNumInput(&(t->num), c);
2052                 
2053                 sprintf(str, "Warp: %s", c);
2054         }
2055         else {
2056                 /* default header print */
2057                 sprintf(str, "Warp: %.3f", circumfac);
2058         }
2059         
2060         circumfac*= (float)(-M_PI/360.0);
2061         
2062         for(i = 0; i < t->total; i++, td++) {
2063                 float loc[3];
2064                 if (td->flag & TD_NOACTION)
2065                         break;
2066                 
2067                 if (td->flag & TD_SKIP)
2068                         continue;
2069                 
2070                 /* translate point to center, rotate in such a way that outline==distance */
2071                 VECCOPY(vec, td->iloc);
2072                 Mat3MulVecfl(td->mtx, vec);
2073                 Mat4MulVecfl(t->viewmat, vec);
2074                 VecSubf(vec, vec, t->viewmat[3]);
2075                 
2076                 dist= vec[0]-cursor[0];
2077                 
2078                 /* t->val is X dimension projected boundbox */
2079                 phi0= (circumfac*dist/t->val);
2080                 
2081                 vec[1]= (vec[1]-cursor[1]);
2082                 
2083                 co= (float)cos(phi0);
2084                 si= (float)sin(phi0);
2085                 loc[0]= -si*vec[1]+cursor[0];
2086                 loc[1]= co*vec[1]+cursor[1];
2087                 loc[2]= vec[2];
2088                 
2089                 Mat4MulVecfl(t->viewinv, loc);
2090                 VecSubf(loc, loc, t->viewinv[3]);
2091                 Mat3MulVecfl(td->smtx, loc);
2092                 
2093                 VecSubf(loc, loc, td->iloc);
2094                 VecMulf(loc, td->factor);
2095                 VecAddf(td->loc, td->iloc, loc);
2096         }
2097         
2098         recalcData(t);
2099         
2100         ED_area_headerprint(t->sa, str);
2101         
2102         return 1;
2103 }
2104
2105 /* ************************** SHEAR *************************** */
2106
2107 void initShear(TransInfo *t)
2108 {
2109         t->mode = TFM_SHEAR;
2110         t->transform = Shear;
2111         t->handleEvent = handleEventShear;
2112         
2113         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_ABSOLUTE);
2114         
2115         t->idx_max = 0;
2116         t->num.idx_max = 0;
2117         t->snap[0] = 0.0f;
2118         t->snap[1] = 0.1f;
2119         t->snap[2] = t->snap[1] * 0.1f;
2120         
2121         t->flag |= T_NO_CONSTRAINT;
2122 }
2123
2124 int handleEventShear(TransInfo *t, wmEvent *event)
2125 {
2126         int status = 0;
2127         
2128         if (event->type == MIDDLEMOUSE && event->val==KM_PRESS)
2129         {
2130                 // Use customData pointer to signal Shear direction
2131                 if      (t->customData == 0)
2132                 {
2133                         initMouseInputMode(t, &t->mouse, INPUT_VERTICAL_ABSOLUTE);
2134                         t->customData = (void*)1;
2135                 }
2136                 else
2137                 {
2138                         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_ABSOLUTE);
2139                         t->customData = 0;
2140                 }
2141                 
2142                 status = 1;
2143         }
2144         
2145         return status;
2146 }
2147
2148
2149 int Shear(TransInfo *t, short mval[2])
2150 {
2151         TransData *td = t->data;
2152         float vec[3];
2153         float smat[3][3], tmat[3][3], totmat[3][3], persmat[3][3], persinv[3][3];
2154         float value;
2155         int i;
2156         char str[50];
2157         
2158         Mat3CpyMat4(persmat, t->viewmat);
2159         Mat3Inv(persinv, persmat);
2160         
2161         value = 0.05f * t->values[0];
2162         
2163         snapGrid(t, &value);
2164         
2165         applyNumInput(&t->num, &value);
2166         
2167         /* header print for NumInput */
2168         if (hasNumInput(&t->num)) {
2169                 char c[20];
2170                 
2171                 outputNumInput(&(t->num), c);
2172                 
2173                 sprintf(str, "Shear: %s %s", c, t->proptext);
2174         }
2175         else {
2176                 /* default header print */
2177                 sprintf(str, "Shear: %.3f %s", value, t->proptext);
2178         }
2179         
2180         Mat3One(smat);
2181         
2182         // Custom data signals shear direction
2183         if (t->customData == 0)
2184                 smat[1][0] = value;
2185         else
2186                 smat[0][1] = value;
2187         
2188         Mat3MulMat3(tmat, smat, persmat);
2189         Mat3MulMat3(totmat, persinv, tmat);
2190         
2191         for(i = 0 ; i < t->total; i++, td++) {
2192                 if (td->flag & TD_NOACTION)
2193                         break;
2194                 
2195                 if (td->flag & TD_SKIP)
2196                         continue;
2197                 
2198                 if (t->obedit) {
2199                         float mat3[3][3];
2200                         Mat3MulMat3(mat3, totmat, td->mtx);
2201                         Mat3MulMat3(tmat, td->smtx, mat3);
2202                 }
2203                 else {
2204                         Mat3CpyMat3(tmat, totmat);
2205                 }
2206                 VecSubf(vec, td->center, t->center);
2207                 
2208                 Mat3MulVecfl(tmat, vec);
2209                 
2210                 VecAddf(vec, vec, t->center);
2211                 VecSubf(vec, vec, td->center);
2212                 
2213                 VecMulf(vec, td->factor);
2214                 
2215                 VecAddf(td->loc, td->iloc, vec);
2216         }
2217         
2218         recalcData(t);
2219         
2220         ED_area_headerprint(t->sa, str);
2221
2222         return 1;
2223 }
2224
2225 /* ************************** RESIZE *************************** */
2226
2227 void initResize(TransInfo *t)
2228 {
2229         t->mode = TFM_RESIZE;
2230         t->transform = Resize;
2231         
2232         initMouseInputMode(t, &t->mouse, INPUT_SPRING_FLIP);
2233         
2234         t->flag |= T_NULL_ONE;
2235         t->num.flag |= NUM_NULL_ONE;
2236         t->num.flag |= NUM_AFFECT_ALL;
2237         if (!t->obedit) {
2238                 t->flag |= T_NO_ZERO;
2239                 t->num.flag |= NUM_NO_ZERO;
2240         }
2241         
2242         t->idx_max = 2;
2243         t->num.idx_max = 2;
2244         t->snap[0] = 0.0f;
2245         t->snap[1] = 0.1f;
2246         t->snap[2] = t->snap[1] * 0.1f;
2247 }
2248
2249 static void headerResize(TransInfo *t, float vec[3], char *str) {
2250         char tvec[60];
2251         if (hasNumInput(&t->num)) {
2252                 outputNumInput(&(t->num), tvec);
2253         }
2254         else {
2255                 sprintf(&tvec[0], "%.4f", vec[0]);
2256                 sprintf(&tvec[20], "%.4f", vec[1]);
2257                 sprintf(&tvec[40], "%.4f", vec[2]);
2258         }
2259         
2260         if (t->con.mode & CON_APPLY) {
2261                 switch(t->num.idx_max) {
2262                 case 0:
2263                         sprintf(str, "Scale: %s%s %s", &tvec[0], t->con.text, t->proptext);
2264                         break;
2265                 case 1:
2266                         sprintf(str, "Scale: %s : %s%s %s", &tvec[0], &tvec[20], t->con.text, t->proptext);
2267                         break;
2268                 case 2:
2269                         sprintf(str, "Scale: %s : %s : %s%s %s", &tvec[0], &tvec[20], &tvec[40], t->con.text, t->proptext);
2270                 }
2271         }
2272         else {
2273                 if (t->flag & T_2D_EDIT)
2274                         sprintf(str, "Scale X: %s   Y: %s%s %s", &tvec[0], &tvec[20], t->con.text, t->proptext);
2275                 else
2276                         sprintf(str, "Scale X: %s   Y: %s  Z: %s%s %s", &tvec[0], &tvec[20], &tvec[40], t->con.text, t->proptext);
2277         }
2278 }
2279
2280 #define SIGN(a)         (a<-FLT_EPSILON?1:a>FLT_EPSILON?2:3)
2281 #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)
2282
2283 /* smat is reference matrix, only scaled */
2284 static void TransMat3ToSize( float mat[][3], float smat[][3], float *size)
2285 {
2286         float vec[3];
2287         
2288         VecCopyf(vec, mat[0]);
2289         size[0]= Normalize(vec);
2290         VecCopyf(vec, mat[1]);
2291         size[1]= Normalize(vec);
2292         VecCopyf(vec, mat[2]);
2293         size[2]= Normalize(vec);
2294         
2295         /* first tried with dotproduct... but the sign flip is crucial */
2296         if( VECSIGNFLIP(mat[0], smat[0]) ) size[0]= -size[0];
2297         if( VECSIGNFLIP(mat[1], smat[1]) ) size[1]= -size[1];
2298         if( VECSIGNFLIP(mat[2], smat[2]) ) size[2]= -size[2];
2299 }
2300
2301
2302 static void ElementResize(TransInfo *t, TransData *td, float mat[3][3]) {
2303         float tmat[3][3], smat[3][3], center[3];
2304         float vec[3];
2305         
2306         if (t->flag & T_EDIT) {
2307                 Mat3MulMat3(smat, mat, td->mtx);
2308                 Mat3MulMat3(tmat, td->smtx, smat);
2309         }
2310         else {
2311                 Mat3CpyMat3(tmat, mat);
2312         }
2313         
2314         if (t->con.applySize) {
2315                 t->con.applySize(t, td, tmat);
2316         }
2317         
2318         /* local constraint shouldn't alter center */
2319         if (t->around == V3D_LOCAL) {
2320                 if (t->flag & T_OBJECT) {
2321                         VECCOPY(center, td->center);
2322                 }
2323                 else if (t->flag & T_EDIT) {
2324                         
2325                         if(t->around==V3D_LOCAL && (t->settings->selectmode & SCE_SELECT_FACE)) {
2326                                 VECCOPY(center, td->center);
2327                         }
2328                         else {
2329                                 VECCOPY(center, t->center);
2330                         }
2331                 }
2332                 else {
2333                         VECCOPY(center, t->center);
2334                 }
2335         }
2336         else {
2337                 VECCOPY(center, t->center);
2338         }
2339         
2340         if (td->ext) {
2341                 float fsize[3];
2342                 
2343                 if (t->flag & (T_OBJECT|T_TEXTURE|T_POSE)) {
2344                         float obsizemat[3][3];
2345                         // Reorient the size mat to fit the oriented object.
2346                         Mat3MulMat3(obsizemat, tmat, td->axismtx);
2347                         //printmatrix3("obsizemat", obsizemat);
2348                         TransMat3ToSize(obsizemat, td->axismtx, fsize);
2349                         //printvecf("fsize", fsize);
2350                 }
2351                 else {
2352                         Mat3ToSize(tmat, fsize);
2353                 }
2354                 
2355                 protectedSizeBits(td->protectflag, fsize);
2356                 
2357                 if ((t->flag & T_V3D_ALIGN)==0) {       // align mode doesn't resize objects itself
2358                         if((td->flag & TD_SINGLESIZE) && !(t->con.mode & CON_APPLY)){
2359                                 /* scale val and reset size */
2360                                 *td->val = td->ival * (1 + (fsize[0] - 1) * td->factor);
2361                                 
2362                                 td->ext->size[0] = td->ext->isize[0];
2363                                 td->ext->size[1] = td->ext->isize[1];
2364                                 td->ext->size[2] = td->ext->isize[2];
2365                         }
2366                         else {
2367                                 /* Reset val if SINGLESIZE but using a constraint */
2368                                 if (td->flag & TD_SINGLESIZE)
2369                                         *td->val = td->ival;
2370                                 
2371                                 td->ext->size[0] = td->ext->isize[0] * (1 + (fsize[0] - 1) * td->factor);
2372                                 td->ext->size[1] = td->ext->isize[1] * (1 + (fsize[1] - 1) * td->factor);
2373                                 td->ext->size[2] = td->ext->isize[2] * (1 + (fsize[2] - 1) * td->factor);
2374                         }
2375                 }
2376                 
2377                 constraintSizeLim(t, td);
2378         }
2379         
2380         /* For individual element center, Editmode need to use iloc */
2381         if (t->flag & T_POINTS)
2382                 VecSubf(vec, td->iloc, center);
2383         else
2384                 VecSubf(vec, td->center, center);
2385         
2386         Mat3MulVecfl(tmat, vec);
2387         
2388         VecAddf(vec, vec, center);
2389         if (t->flag & T_POINTS)
2390                 VecSubf(vec, vec, td->iloc);
2391         else
2392                 VecSubf(vec, vec, td->center);
2393         
2394         VecMulf(vec, td->factor);
2395         
2396         if (t->flag & (T_OBJECT|T_POSE)) {
2397                 Mat3MulVecfl(td->smtx, vec);
2398         }
2399         
2400         protectedTransBits(td->protectflag, vec);
2401         VecAddf(td->loc, td->iloc, vec);
2402         
2403         constraintTransLim(t, td);
2404 }
2405
2406 int Resize(TransInfo *t, short mval[2])
2407 {
2408         TransData *td;
2409         float size[3], mat[3][3];
2410         float ratio;
2411         int i;
2412         char str[200];
2413         
2414         /* for manipulator, center handle, the scaling can't be done relative to center */
2415         if( (t->flag & T_USES_MANIPULATOR) && t->con.mode==0)
2416         {
2417                 ratio = 1.0f - ((t->imval[0] - mval[0]) + (t->imval[1] - mval[1]))/100.0f;
2418         }
2419         else
2420         {
2421                 ratio = t->values[0];
2422         }
2423         
2424         size[0] = size[1] = size[2] = ratio;
2425         
2426         snapGrid(t, size);
2427         
2428         if (hasNumInput(&t->num)) {
2429                 applyNumInput(&t->num, size);
2430                 constraintNumInput(t, size);
2431         }
2432         
2433         applySnapping(t, size);
2434         
2435         if (t->flag & T_AUTOVALUES)
2436         {
2437                 VECCOPY(size, t->auto_values);
2438         }
2439         
2440         VECCOPY(t->values, size);
2441         
2442         SizeToMat3(size, mat);
2443         
2444         if (t->con.applySize) {
2445                 t->con.applySize(t, NULL, mat);
2446         }
2447         
2448         Mat3CpyMat3(t->mat, mat);       // used in manipulator
2449         
2450         headerResize(t, size, str);
2451         
2452         for(i = 0, td=t->data; i < t->total; i++, td++) {
2453                 if (td->flag & TD_NOACTION)
2454                         break;
2455                 
2456                 if (td->flag & TD_SKIP)
2457                         continue;
2458                 
2459                 ElementResize(t, td, mat);
2460         }
2461         
2462         /* evil hack - redo resize if cliping needed */
2463         if (t->flag & T_CLIP_UV && clipUVTransform(t, size, 1)) {
2464                 SizeToMat3(size, mat);
2465                 
2466                 if (t->con.applySize)
2467                         t->con.applySize(t, NULL, mat);
2468                 
2469                 for(i = 0, td=t->data; i < t->total; i++, td++)
2470                         ElementResize(t, td, mat);
2471         }
2472         
2473         recalcData(t);
2474         
2475         ED_area_headerprint(t->sa, str);
2476         
2477         return 1;
2478 }
2479
2480 /* ************************** TOSPHERE *************************** */
2481
2482 void initToSphere(TransInfo *t)
2483 {
2484         TransData *td = t->data;
2485         int i;
2486         
2487         t->mode = TFM_TOSPHERE;
2488         t->transform = ToSphere;
2489         
2490         initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_RATIO);
2491         
2492         t->idx_max = 0;
2493         t->num.idx_max = 0;
2494         t->snap[0] = 0.0f;
2495         t->snap[1] = 0.1f;
2496         t->snap[2] = t->snap[1] * 0.1f;
2497         
2498         t->num.flag |= NUM_NULL_ONE | NUM_NO_NEGATIVE;
2499         t->flag |= T_NO_CONSTRAINT;
2500         
2501         // Calculate average radius
2502         for(i = 0 ; i < t->total; i++, td++) {
2503                 t->val += VecLenf(t->center, td->iloc);
2504         }
2505         
2506         t->val /= (float)t->total;
2507 }
2508
2509 int ToSphere(TransInfo *t, short mval[2])
2510 {
2511         float vec[3];
2512         float ratio, radius;
2513         int i;
2514         char str[64];
2515         TransData *td = t->data;
2516         
2517         ratio = t->values[0];
2518         
2519         snapGrid(t, &ratio);
2520         
2521         applyNumInput(&t->num, &ratio);
2522         
2523         if (ratio < 0)
2524                 ratio = 0.0f;
2525         else if (ratio > 1)
2526                 ratio = 1.0f;
2527         
2528         /* header print for NumInput */
2529         if (hasNumInput(&t->num)) {
2530                 char c[20];
2531                 
2532                 outputNumInput(&(t->num), c);
2533                 
2534                 sprintf(str, "To Sphere: %s %s", c, t->proptext);
2535         }
2536         else {
2537                 /* default header print */
2538                 sprintf(str, "To Sphere: %.4f %s", ratio, t->proptext);
2539         }
2540         
2541         
2542         for(i = 0 ; i < t->total; i++, td++) {
2543                 float tratio;
2544                 if (td->flag & TD_NOACTION)
2545                         break;
2546                 
2547                 if (td->flag & TD_SKIP)
2548                         continue;
2549                 
2550                 VecSubf(vec, td->iloc, t->center);
2551                 
2552                 radius = Normalize(vec);
2553                 
2554                 tratio = ratio * td->factor;
2555                 
2556                 VecMulf(vec, radius * (1.0f - tratio) + t->val * tratio);
2557                 
2558                 VecAddf(td->loc, t->center, vec);
2559         }
2560         
2561         
2562         recalcData(t);
2563         
2564         ED_area_headerprint(t->sa, str);
2565         
2566         return 1;
2567 }
2568
2569 /* ************************** ROTATION *************************** */
2570
2571
2572 void initRotation(TransInfo *t)
2573 {
2574         t->mode = TFM_ROTATION;
2575         t->transform = Rotation;
2576         
2577         initMouseInputMode(t, &t->mouse, INPUT_ANGLE);
2578         
2579         t->ndof.axis = 16;
2580         /* Scale down and flip input for rotation */
2581         t->ndof.factor[0] = -0.2f;
2582         
2583         t->idx_max = 0;
2584         t->num.idx_max = 0;
2585         t->snap[0] = 0.0f;
2586         t->snap[1] = (float)((5.0/180)*M_PI);
2587         t->snap[2] = t->snap[1] * 0.2f;
2588         
2589         if (t->flag & T_2D_EDIT)
2590                 t->flag |= T_NO_CONSTRAINT;
2591 }
2592
2593 static void ElementRotation(TransInfo *t, TransData *td, float mat[3][3], short around) {
2594         float vec[3], totmat[3][3], smat[3][3];
2595         float eul[3], fmat[3][3], quat[4];
2596         float *center = t->center;
2597         
2598         /* local constraint shouldn't alter center */
2599         if (around == V3D_LOCAL) {
2600                 if (t->flag & (T_OBJECT|T_POSE)) {
2601                         center = td->center;
2602                 }
2603                 else {
2604                         if(around==V3D_LOCAL && (t->settings->selectmode & SCE_SELECT_FACE)) {
2605                                 center = td->center;
2606                         }
2607                 }
2608         }
2609         
2610         if (t->flag & T_POINTS) {
2611                 Mat3MulMat3(totmat, mat, td->mtx);
2612                 Mat3MulMat3(smat, td->smtx, totmat);
2613                 
2614                 VecSubf(vec, td->iloc, center);
2615                 Mat3MulVecfl(smat, vec);
2616                 
2617                 VecAddf(td->loc, vec, center);
2618                 
2619                 VecSubf(vec,td->loc,td->iloc);
2620                 protectedTransBits(td->protectflag, vec);
2621                 VecAddf(td->loc, td->iloc, vec);
2622                 
2623                 
2624                 if(td->flag & TD_USEQUAT) {
2625                         Mat3MulSerie(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2626                         Mat3ToQuat(fmat, quat); // Actual transform
2627                         
2628                         if(td->ext->quat){
2629                                 QuatMul(td->ext->quat, quat, td->ext->iquat);
2630                                 
2631                                 /* is there a reason not to have this here? -jahka */
2632                                 protectedQuaternionBits(td->protectflag, td->ext->quat, td->ext->iquat);
2633                         }
2634                 }
2635         }
2636         /**
2637          * HACK WARNING
2638          *
2639          * This is some VERY ugly special case to deal with pose mode.
2640          *
2641          * The problem is that mtx and smtx include each bone orientation.
2642          *
2643          * That is needed to rotate each bone properly, HOWEVER, to calculate
2644          * the translation component, we only need the actual armature object's
2645          * matrix (and inverse). That is not all though. Once the proper translation
2646          * has been computed, it has to be converted back into the bone's space.
2647          */
2648         else if (t->flag & T_POSE) {
2649                 float pmtx[3][3], imtx[3][3];
2650                 
2651                 // Extract and invert armature object matrix
2652                 Mat3CpyMat4(pmtx, t->poseobj->obmat);
2653                 Mat3Inv(imtx, pmtx);
2654                 
2655                 if ((td->flag & TD_NO_LOC) == 0)
2656                 {
2657                         VecSubf(vec, td->center, center);
2658                         
2659                         Mat3MulVecfl(pmtx, vec);        // To Global space
2660                         Mat3MulVecfl(mat, vec);         // Applying rotation
2661                         Mat3MulVecfl(imtx, vec);        // To Local space
2662                         
2663                         VecAddf(vec, vec, center);
2664                         /* vec now is the location where the object has to be */
2665                         
2666                         VecSubf(vec, vec, td->center); // Translation needed from the initial location
2667                         
2668                         Mat3MulVecfl(pmtx, vec);        // To Global space
2669                         Mat3MulVecfl(td->smtx, vec);// To Pose space
2670                         
2671                         protectedTransBits(td->protectflag, vec);
2672                         
2673                         VecAddf(td->loc, td->iloc, vec);
2674                         
2675                         constraintTransLim(t, td);
2676                 }
2677                 
2678                 /* rotation */
2679                 if ((t->flag & T_V3D_ALIGN)==0) { // align mode doesn't rotate objects itself
2680                         /* euler or quaternion/axis-angle? */
2681                         if (td->rotOrder == ROT_MODE_QUAT) {
2682                                 Mat3MulSerie(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2683                                 
2684                                 Mat3ToQuat(fmat, quat); // Actual transform
2685                                 
2686                                 QuatMul(td->ext->quat, quat, td->ext->iquat);
2687                                 /* this function works on end result */
2688                                 protectedQuaternionBits(td->protectflag, td->ext->quat, td->ext->iquat);
2689                                 
2690                         }
2691                         else if (td->rotOrder == ROT_MODE_AXISANGLE) {
2692                                 /* calculate effect based on quats */
2693                                 float iquat[4], tquat[4];
2694                                 
2695                                 AxisAngleToQuat(iquat, td->ext->irotAxis, td->ext->irotAngle);
2696                                 
2697                                 Mat3MulSerie(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2698                                 Mat3ToQuat(fmat, quat); // Actual transform
2699                                 QuatMul(tquat, quat, iquat);
2700                                 
2701                                 QuatToAxisAngle(tquat, td->ext->rotAxis, td->ext->rotAngle); 
2702                                 
2703                                 /* this function works on end result */
2704                                 protectedAxisAngleBits(td->protectflag, td->ext->rotAxis, td->ext->rotAngle, td->ext->irotAxis, td->ext->irotAngle);
2705                         }
2706                         else { 
2707                                 float eulmat[3][3];
2708                                 
2709                                 Mat3MulMat3(totmat, mat, td->mtx);
2710                                 Mat3MulMat3(smat, td->smtx, totmat);
2711                                 
2712                                 /* calculate the total rotatation in eulers */
2713                                 VECCOPY(eul, td->ext->irot);
2714                                 EulOToMat3(eul, td->rotOrder, eulmat);
2715                                 
2716                                 /* mat = transform, obmat = bone rotation */
2717                                 Mat3MulMat3(fmat, smat, eulmat);
2718                                 
2719                                 Mat3ToCompatibleEulO(fmat, eul, td->ext->rot, td->rotOrder);
2720                                 
2721                                 /* and apply (to end result only) */
2722                                 protectedRotateBits(td->protectflag, eul, td->ext->irot);
2723                                 VECCOPY(td->ext->rot, eul);
2724                         }
2725                         
2726                         constraintRotLim(t, td);
2727                 }
2728         }
2729         else {
2730                 if ((td->flag & TD_NO_LOC) == 0)
2731                 {
2732                         /* translation */
2733                         VecSubf(vec, td->center, center);
2734                         Mat3MulVecfl(mat, vec);
2735                         VecAddf(vec, vec, center);
2736                         /* vec now is the location where the object has to be */
2737                         VecSubf(vec, vec, td->center);
2738                         Mat3MulVecfl(td->smtx, vec);
2739                         
2740                         protectedTransBits(td->protectflag, vec);
2741                         
2742                         VecAddf(td->loc, td->iloc, vec);
2743                 }
2744                 
2745                 
2746                 constraintTransLim(t, td);
2747                 
2748                 /* rotation */
2749                 if ((t->flag & T_V3D_ALIGN)==0) { // align mode doesn't rotate objects itself
2750                         /* euler or quaternion? */
2751                     if ((td->rotOrder == ROT_MODE_QUAT) || (td->flag & TD_USEQUAT)) {
2752                                 Mat3MulSerie(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2753                                 Mat3ToQuat(fmat, quat); // Actual transform
2754                                 
2755                                 QuatMul(td->ext->quat, quat, td->ext->iquat);
2756                                 /* this function works on end result */
2757                                 protectedQuaternionBits(td->protectflag, td->ext->quat, td->ext->iquat);
2758                         }
2759                         else if (td->rotOrder == ROT_MODE_AXISANGLE) {
2760                                 /* calculate effect based on quats */
2761                                 float iquat[4], tquat[4];
2762                                 
2763                                 AxisAngleToQuat(iquat, td->ext->irotAxis, td->ext->irotAngle);
2764                                 
2765                                 Mat3MulSerie(fmat, td->mtx, mat, td->smtx, 0, 0, 0, 0, 0);
2766                                 Mat3ToQuat(fmat, quat); // Actual transform
2767                                 QuatMul(tquat, quat, iquat);
2768                                 
2769                                 QuatToAxisAngle(quat, td->ext->rotAxis, td->ext->rotAngle); 
2770                                 
2771                                 /* this function works on end result */
2772                                 protectedAxisAngleBits(td->protectflag, td->ext->rotAxis, td->ext->rotAngle, td->ext->irotAxis, td->ext->irotAngle);
2773                         }
2774                         else {
2775                                 float obmat[3][3];
2776                                 
2777                                 Mat3MulMat3(totmat, mat, td->mtx);
2778                                 Mat3MulMat3(smat, td->smtx, totmat);
2779                                 
2780                                 /* calculate the total rotatation in eulers */
2781                                 VecAddf(eul, td->ext->irot, td->ext->drot); /* we have to correct for delta rot */
2782                                 EulOToMat3(eul, td->rotOrder, obmat);
2783                                 /* mat = transform, obmat = object rotation */
2784                                 Mat3MulMat3(fmat, smat, obmat);
2785                                 
2786                                 Mat3ToCompatibleEulO(fmat, eul, td->ext->rot, td->rotOrder);
2787                                 
2788                                 /* correct back for delta rot */
2789                                 VecSubf(eul, eul, td->ext->drot);
2790                                 
2791                                 /* and apply */
2792                                 protectedRotateBits(td->protectflag, eul, td->ext->irot);
2793                                 VECCOPY(td->ext->rot, eul);
2794                         }
2795                         
2796                         constraintRotLim(t, td);
2797                 }
2798         }
2799 }
2800
2801 static void applyRotation(TransInfo *t, float angle, float axis[3])
2802 {
2803         TransData *td = t->data;
2804         float mat[3][3];
2805         int i;
2806         
2807         VecRotToMat3(axis, angle, mat);
2808         
2809         for(i = 0 ; i < t->total; i++, td++) {
2810                 
2811                 if (td->flag & TD_NOACTION)
2812                         break;
2813                 
2814                 if (td->flag & TD_SKIP)
2815                         continue;
2816                 
2817                 if (t->con.applyRot) {
2818                         t->con.applyRot(t, td, axis, NULL);
2819                         VecRotToMat3(axis, angle * td->factor, mat);
2820                 }
2821                 else if (t->flag & T_PROP_EDIT) {
2822                         VecRotToMat3(axis, angle * td->factor, mat);
2823                 }
2824                 
2825                 ElementRotation(t, td, mat, t->around);
2826         }
2827 }
2828
2829 int Rotation(TransInfo *t, short mval[2])
2830 {
2831         char str[64];
2832         
2833         float final;
2834         
2835         float axis[3];
2836         float mat[3][3];
2837         
2838         VECCOPY(axis, t->viewinv[2]);
2839         VecMulf(axis, -1.0f);
2840         Normalize(axis);
2841         
2842         final = t->values[0];
2843         
2844         applyNDofInput(&t->ndof, &final);
2845         
2846         snapGrid(t, &final);
2847         
2848         if (t->con.applyRot) {
2849                 t->con.applyRot(t, NULL, axis, &final);
2850         }
2851         
2852         applySnapping(t, &final);
2853         
2854         if (hasNumInput(&t->num)) {
2855                 char c[20];
2856                 
2857                 applyNumInput(&t->num, &final);
2858                 
2859                 outputNumInput(&(t->num), c);
2860                 
2861                 sprintf(str, "Rot: %s %s %s", &c[0], t->con.text, t->proptext);
2862                 
2863                 /* Clamp between -180 and 180 */
2864                 while (final >= 180.0)
2865                         final -= 360.0;
2866                 
2867                 while (final <= -180.0)
2868                         final += 360.0;
2869                 
2870                 final *= (float)(M_PI / 180.0);
2871         }
2872         else {
2873                 sprintf(str, "Rot: %.2f%s %s", 180.0*final/M_PI, t->con.text, t->proptext);
2874         }
2875         
2876         VecRotToMat3(axis, final, mat);
2877         
2878         // TRANSFORM_FIX_ME
2879 //      t->values[0] = final;           // used in manipulator
2880 //      Mat3CpyMat3(t->mat, mat);       // used in manipulator
2881         
2882         applyRotation(t, final, axis);
2883         
2884         recalcData(t);
2885         
2886         ED_area_headerprint(t->sa, str);
2887         
2888         return 1;
2889 }
2890
2891
2892 /* ************************** TRACKBALL *************************** */
2893
2894 void initTrackball(TransInfo *t)
2895 {
2896         t->mode = TFM_TRACKBALL;
2897         t->transform = Trackball;
2898
2899         initMouseInputMode(t, &t->mouse, INPUT_TRACKBALL);
2900
2901         t->ndof.axis = 40;
2902         /* Scale down input for rotation */
2903         t->ndof.factor[0] = 0.2f;
2904         t->ndof.factor[1] = 0.2f;
2905
2906         t->idx_max = 1;
2907         t->num.idx_max = 1;
2908         t->snap[0] = 0.0f;
2909         t->snap[1] = (float)((5.0/180)*M_PI);
2910         t->snap[2] = t->snap[1] * 0.2f;
2911
2912         t->flag |= T_NO_CONSTRAINT;
2913 }
2914
2915 static void applyTrackball(TransInfo *t, float axis1[3], float axis2[3], float angles[2])
2916 {
2917         TransData *td = t->data;
2918         float mat[3][3], smat[3][3], totmat[3][3];
2919         int i;
2920
2921         VecRotToMat3(axis1, angles[0], smat);
2922         VecRotToMat3(axis2, angles[1], totmat);
2923
2924         Mat3MulMat3(mat, smat, totmat);
2925
2926         for(i = 0 ; i < t->total; i++, td++) {
2927                 if (td->flag & TD_NOACTION)
2928                         break;
2929
2930                 if (td->flag & TD_SKIP)
2931                         continue;
2932
2933                 if (t->flag & T_PROP_EDIT) {
2934                         VecRotToMat3(axis1, td->factor * angles[0], smat);
2935                         VecRotToMat3(axis2, td->factor * angles[1], totmat);
2936
2937                         Mat3MulMat3(mat, smat, totmat);
2938                 }
2939
2940                 ElementRotation(t, td, mat, t->around);
2941         }
2942 }
2943
2944 int Trackball(TransInfo *t, short mval[2])
2945 {
2946         char str[128];
2947         float axis1[3], axis2[3];
2948         float mat[3][3], totmat[3][3], smat[3][3];
2949         float phi[2];
2950
2951         VECCOPY(axis1, t->persinv[0]);
2952         VECCOPY(axis2, t->persinv[1]);
2953         Normalize(axis1);
2954         Normalize(axis2);
2955
2956         phi[0] = t->values[0];
2957         phi[1] = t->values[1];
2958
2959         applyNDofInput(&t->ndof, phi);
2960
2961         snapGrid(t, phi);
2962
2963         if (hasNumInput(&t->num)) {
2964                 char c[40];
2965
2966                 applyNumInput(&t->num, phi);
2967
2968                 outputNumInput(&(t->num), c);
2969
2970                 sprintf(str, "Trackball: %s %s %s", &c[0], &c[20], t->proptext);
2971
2972                 phi[0] *= (float)(M_PI / 180.0);
2973                 phi[1] *= (float)(M_PI / 180.0);
2974         }
2975         else {
2976                 sprintf(str, "Trackball: %.2f %.2f %s", 180.0*phi[0]/M_PI, 180.0*phi[1]/M_PI, t->proptext);
2977         }
2978
2979         VecRotToMat3(axis1, phi[0], smat);
2980         VecRotToMat3(axis2, phi[1], totmat);
2981
2982         Mat3MulMat3(mat, smat, totmat);
2983
2984         // TRANSFORM_FIX_ME
2985         //Mat3CpyMat3(t->mat, mat);     // used in manipulator
2986
2987         applyTrackball(t, axis1, axis2, phi);
2988
2989         recalcData(t);
2990
2991         ED_area_headerprint(t->sa, str);
2992
2993         return 1;
2994 }
2995
2996 /* ************************** TRANSLATION *************************** */
2997
2998 void initTranslation(TransInfo *t)