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