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