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