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