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