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