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