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