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