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