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