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