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