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