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