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