Split up recalcData() function in transform_generics.c into smaller
[blender.git] / source / blender / editors / transform / transform_generics.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /** \file blender/editors/transform/transform_generics.c
31  *  \ingroup edtransform
32  */
33
34
35 #include <string.h>
36 #include <math.h>
37
38 #include "MEM_guardedalloc.h"
39
40 #include "BLO_sys_types.h" // for intptr_t support
41
42 #include "DNA_anim_types.h"
43 #include "DNA_armature_types.h"
44 #include "DNA_lattice_types.h"
45 #include "DNA_screen_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_object_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_view3d_types.h"
51 #include "DNA_modifier_types.h"
52
53 #include "RNA_access.h"
54
55 //#include "BIF_screen.h"
56 //#include "BIF_mywindow.h"
57 #include "BIF_gl.h"
58 #include "BIF_glutil.h"
59 //#include "BIF_editmesh.h"
60 //#include "BIF_editsima.h"
61 //#include "BIF_editparticle.h"
62 //#include "BIF_meshtools.h"
63
64 #include "BKE_animsys.h"
65 #include "BKE_action.h"
66 #include "BKE_armature.h"
67 #include "BKE_curve.h"
68 #include "BKE_depsgraph.h"
69 #include "BKE_displist.h"
70 #include "BKE_fcurve.h"
71 #include "BKE_lattice.h"
72 #include "BKE_mesh.h"
73 #include "BKE_nla.h"
74 #include "BKE_context.h"
75
76 #include "ED_anim_api.h"
77 #include "ED_armature.h"
78 #include "ED_image.h"
79 #include "ED_keyframing.h"
80 #include "ED_markers.h"
81 #include "ED_mesh.h"
82 #include "ED_particle.h"
83 #include "ED_screen_types.h"
84 #include "ED_space_api.h"
85 #include "ED_uvedit.h"
86 #include "ED_view3d.h"
87 #include "ED_curve.h" /* for ED_curve_editnurbs */
88
89 //#include "BDR_unwrapper.h"
90
91 #include "BLI_math.h"
92 #include "BLI_blenlib.h"
93 #include "BLI_editVert.h"
94 #include "BLI_rand.h"
95 #include "BLI_utildefines.h"
96
97 #include "WM_types.h"
98 #include "WM_api.h"
99
100 #include "UI_resources.h"
101
102 //#include "blendef.h"
103 //
104 //#include "mydevice.h"
105
106 #include "transform.h"
107
108 extern ListBase editelems;
109
110 /* ************************** Functions *************************** */
111
112 void getViewVector(TransInfo *t, float coord[3], float vec[3])
113 {
114         if (t->persp != RV3D_ORTHO)
115         {
116                 float p1[4], p2[4];
117                 
118                 VECCOPY(p1, coord);
119                 p1[3] = 1.0f;
120                 VECCOPY(p2, p1);
121                 p2[3] = 1.0f;
122                 mul_m4_v4(t->viewmat, p2);
123                 
124                 p2[0] = 2.0f * p2[0];
125                 p2[1] = 2.0f * p2[1];
126                 p2[2] = 2.0f * p2[2];
127                 
128                 mul_m4_v4(t->viewinv, p2);
129                 
130                 sub_v3_v3v3(vec, p1, p2);
131         }
132         else {
133                 VECCOPY(vec, t->viewinv[2]);
134         }
135         normalize_v3(vec);
136 }
137
138 /* ************************** GENERICS **************************** */
139
140 static void clipMirrorModifier(TransInfo *t, Object *ob)
141 {
142         ModifierData *md= ob->modifiers.first;
143         float tolerance[3] = {0.0f, 0.0f, 0.0f};
144         int axis = 0;
145         
146         for (; md; md=md->next) {
147                 if (md->type==eModifierType_Mirror) {
148                         MirrorModifierData *mmd = (MirrorModifierData*) md;
149                         
150                         if(mmd->flag & MOD_MIR_CLIPPING) {
151                                 axis = 0;
152                                 if(mmd->flag & MOD_MIR_AXIS_X) {
153                                         axis |= 1;
154                                         tolerance[0] = mmd->tolerance;
155                                 }
156                                 if(mmd->flag & MOD_MIR_AXIS_Y) {
157                                         axis |= 2;
158                                         tolerance[1] = mmd->tolerance;
159                                 }
160                                 if(mmd->flag & MOD_MIR_AXIS_Z) {
161                                         axis |= 4;
162                                         tolerance[2] = mmd->tolerance;
163                                 }
164                                 if (axis) {
165                                         float mtx[4][4], imtx[4][4];
166                                         int i;
167                                         TransData *td = t->data;
168                                         
169                                         if (mmd->mirror_ob) {
170                                                 float obinv[4][4];
171                                                 
172                                                 invert_m4_m4(obinv, mmd->mirror_ob->obmat);
173                                                 mul_m4_m4m4(mtx, ob->obmat, obinv);
174                                                 invert_m4_m4(imtx, mtx);
175                                         }
176                                         
177                                         for(i = 0 ; i < t->total; i++, td++) {
178                                                 int clip;
179                                                 float loc[3], iloc[3];
180                                                 
181                                                 if (td->flag & TD_NOACTION)
182                                                         break;
183                                                 if (td->loc==NULL)
184                                                         break;
185                                                 
186                                                 if (td->flag & TD_SKIP)
187                                                         continue;
188                                                 
189                                                 copy_v3_v3(loc,  td->loc);
190                                                 copy_v3_v3(iloc, td->iloc);
191                                                 
192                                                 if (mmd->mirror_ob) {
193                                                         mul_m4_v3(mtx, loc);
194                                                         mul_m4_v3(mtx, iloc);
195                                                 }
196                                                 
197                                                 clip = 0;
198                                                 if(axis & 1) {
199                                                         if(fabs(iloc[0])<=tolerance[0] ||
200                                                            loc[0]*iloc[0]<0.0f) {
201                                                                 loc[0]= 0.0f;
202                                                                 clip = 1;
203                                                         }
204                                                 }
205                                                 
206                                                 if(axis & 2) {
207                                                         if(fabs(iloc[1])<=tolerance[1] ||
208                                                            loc[1]*iloc[1]<0.0f) {
209                                                                 loc[1]= 0.0f;
210                                                                 clip = 1;
211                                                         }
212                                                 }
213                                                 if(axis & 4) {
214                                                         if(fabs(iloc[2])<=tolerance[2] ||
215                                                            loc[2]*iloc[2]<0.0f) {
216                                                                 loc[2]= 0.0f;
217                                                                 clip = 1;
218                                                         }
219                                                 }
220                                                 if (clip) {
221                                                         if (mmd->mirror_ob) {
222                                                                 mul_m4_v3(imtx, loc);
223                                                         }
224                                                         copy_v3_v3(td->loc, loc);
225                                                 }
226                                         }
227                                 }
228                                 
229                         }
230                 }
231         }
232 }
233
234 /* assumes obedit set to mesh object */
235 static void editmesh_apply_to_mirror(TransInfo *t)
236 {
237         TransData *td = t->data;
238         EditVert *eve;
239         int i;
240         
241         for(i = 0 ; i < t->total; i++, td++) {
242                 if (td->flag & TD_NOACTION)
243                         break;
244                 if (td->loc==NULL)
245                         break;
246                 if (td->flag & TD_SKIP)
247                         continue;
248                 
249                 eve = td->extra;
250                 if (eve) {
251                         eve->co[0]= -td->loc[0];
252                         eve->co[1]= td->loc[1];
253                         eve->co[2]= td->loc[2];
254                 }
255                 
256                 if (td->flag & TD_MIRROR_EDGE)
257                 {
258                         td->loc[0] = 0;
259                 }
260         }
261 }
262
263 /* for the realtime animation recording feature, handle overlapping data */
264 static void animrecord_check_state (Scene *scene, ID *id, wmTimer *animtimer)
265 {
266         ScreenAnimData *sad= (animtimer) ? animtimer->customdata : NULL;
267         
268         /* sanity checks */
269         if ELEM3(NULL, scene, id, sad)
270                 return;
271         
272         /* check if we need a new strip if:
273          *      - if animtimer is running 
274          *      - we're not only keying for available channels
275          *      - the option to add new actions for each round is not enabled
276          */
277         if (IS_AUTOKEY_FLAG(scene, INSERTAVAIL)==0 && (scene->toolsettings->autokey_flag & ANIMRECORD_FLAG_WITHNLA)) {
278                 /* if playback has just looped around, we need to add a new NLA track+strip to allow a clean pass to occur */
279                 if ((sad) && (sad->flag & ANIMPLAY_FLAG_JUMPED)) {
280                         AnimData *adt= BKE_animdata_from_id(id);
281                         
282                         /* perform push-down manually with some differences 
283                          * NOTE: BKE_nla_action_pushdown() sync warning...
284                          */
285                         if ((adt->action) && !(adt->flag & ADT_NLA_EDIT_ON)) {
286                                 float astart, aend;
287                                 
288                                 /* only push down if action is more than 1-2 frames long */
289                                 calc_action_range(adt->action, &astart, &aend, 1);
290                                 if (aend > astart+2.0f) {
291                                         NlaStrip *strip= add_nlastrip_to_stack(adt, adt->action);
292                                         
293                                         /* clear reference to action now that we've pushed it onto the stack */
294                                         adt->action->id.us--;
295                                         adt->action= NULL;
296                                         
297                                         /* adjust blending + extend so that they will behave correctly */
298                                         strip->extendmode= NLASTRIP_EXTEND_NOTHING;
299                                         strip->flag &= ~(NLASTRIP_FLAG_AUTO_BLENDS|NLASTRIP_FLAG_SELECT|NLASTRIP_FLAG_ACTIVE);
300                                         
301                                         /* also, adjust the AnimData's action extend mode to be on 
302                                          * 'nothing' so that previous result still play 
303                                          */
304                                         adt->act_extendmode= NLASTRIP_EXTEND_NOTHING;
305                                 }
306                         }
307                 }
308         }
309 }
310
311 static int fcu_test_selected(FCurve *fcu)
312 {
313         BezTriple *bezt= fcu->bezt;
314         unsigned int i;
315
316         if (bezt==NULL) /* ignore baked */
317                 return 0;
318
319         for (i=0; i < fcu->totvert; i++, bezt++) {
320                 if (BEZSELECTED(bezt)) return 1;
321         }
322
323         return 0;
324 }
325
326 /* helper for recalcData() - for Action Editor transforms */
327 static void recalcData_actedit(TransInfo *t)
328 {
329         Scene *scene= t->scene;
330         SpaceAction *saction= (SpaceAction *)t->sa->spacedata.first;
331         
332         bAnimContext ac= {NULL};
333         ListBase anim_data = {NULL, NULL};
334         bAnimListElem *ale;
335         int filter;
336         
337         /* initialise relevant anim-context 'context' data from TransInfo data */
338                 /* NOTE: sync this with the code in ANIM_animdata_get_context() */
339         ac.scene= t->scene;
340         ac.obact= OBACT;
341         ac.sa= t->sa;
342         ac.ar= t->ar;
343         ac.sl= (t->sa)? t->sa->spacedata.first : NULL;
344         ac.spacetype= (t->sa)? t->sa->spacetype : 0;
345         ac.regiontype= (t->ar)? t->ar->regiontype : 0;
346         
347         ANIM_animdata_context_getdata(&ac);
348         
349         /* perform flush */
350         if (ac.datatype == ANIMCONT_GPENCIL) {
351                 /* flush transform values back to actual coordinates */
352                 flushTransGPactionData(t);
353         }
354         else {
355                 /* get animdata blocks visible in editor, assuming that these will be the ones where things changed */
356                 filter= (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_ANIMDATA);
357                 ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
358                 
359                 /* just tag these animdata-blocks to recalc, assuming that some data there changed 
360                  * BUT only do this if realtime updates are enabled
361                  */
362                 if ((saction->flag & SACTION_NOREALTIMEUPDATES) == 0) {
363                         for (ale= anim_data.first; ale; ale= ale->next) {
364                                 /* set refresh tags for objects using this animation */
365                                 ANIM_list_elem_update(t->scene, ale);
366                         }
367                 }
368                 
369                 /* now free temp channels */
370                 BLI_freelistN(&anim_data);
371         }
372 }
373
374 /* helper for recalcData() - for Graph Editor transforms */
375 static void recalcData_graphedit(TransInfo *t)
376 {
377         SpaceIpo *sipo= (SpaceIpo *)t->sa->spacedata.first;
378         Scene *scene;
379         
380         ListBase anim_data = {NULL, NULL};
381         bAnimContext ac= {NULL};
382         int filter;
383         
384         bAnimListElem *ale;
385         int dosort = 0;
386         
387         
388         /* initialise relevant anim-context 'context' data from TransInfo data */
389                 /* NOTE: sync this with the code in ANIM_animdata_get_context() */
390         scene= ac.scene= t->scene;
391         ac.obact= OBACT;
392         ac.sa= t->sa;
393         ac.ar= t->ar;
394         ac.sl= (t->sa)? t->sa->spacedata.first : NULL;
395         ac.spacetype= (t->sa)? t->sa->spacetype : 0;
396         ac.regiontype= (t->ar)? t->ar->regiontype : 0;
397         
398         ANIM_animdata_context_getdata(&ac);
399         
400         /* do the flush first */
401         flushTransGraphData(t);
402         
403         /* get curves to check if a re-sort is needed */
404         filter= (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_FOREDIT | ANIMFILTER_CURVE_VISIBLE);
405         ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
406         
407         /* now test if there is a need to re-sort */
408         for (ale= anim_data.first; ale; ale= ale->next) {
409                 FCurve *fcu= (FCurve *)ale->key_data;
410                 
411                 /* ignore unselected fcurves */
412                 if (!fcu_test_selected(fcu))
413                         continue;
414                 
415                 // fixme: only do this for selected verts...
416                 ANIM_unit_mapping_apply_fcurve(ac.scene, ale->id, ale->key_data, ANIM_UNITCONV_ONLYSEL|ANIM_UNITCONV_SELVERTS|ANIM_UNITCONV_RESTORE);
417                 
418                 
419                 /* watch it: if the time is wrong: do not correct handles yet */
420                 if (test_time_fcurve(fcu))
421                         dosort++;
422                 else
423                         calchandles_fcurve(fcu);
424                 
425                 /* set refresh tags for objects using this animation,
426                  * BUT only if realtime updates are enabled  
427                  */
428                 if ((sipo->flag & SIPO_NOREALTIMEUPDATES) == 0)
429                         ANIM_list_elem_update(t->scene, ale);
430         }
431         
432         /* do resort and other updates? */
433         if (dosort) remake_graph_transdata(t, &anim_data);
434         
435         /* now free temp channels */
436         BLI_freelistN(&anim_data);
437 }
438
439 /* helper for recalcData() - for NLA Editor transforms */
440 static void recalcData_nla(TransInfo *t)
441 {
442         TransDataNla *tdn= (TransDataNla *)t->customData;
443         SpaceNla *snla= (SpaceNla *)t->sa->spacedata.first;
444         Scene *scene= t->scene;
445         double secf= FPS;
446         int i;
447         
448         /* for each strip we've got, perform some additional validation of the values that got set before
449          * using RNA to set the value (which does some special operations when setting these values to make
450          * sure that everything works ok)
451          */
452         for (i = 0; i < t->total; i++, tdn++) {
453                 NlaStrip *strip= tdn->strip;
454                 PointerRNA strip_ptr;
455                 short pExceeded, nExceeded, iter;
456                 int delta_y1, delta_y2;
457                 
458                 /* if this tdn has no handles, that means it is just a dummy that should be skipped */
459                 if (tdn->handle == 0)
460                         continue;
461                 
462                 /* set refresh tags for objects using this animation,
463                  * BUT only if realtime updates are enabled  
464                  */
465                 if ((snla->flag & SNLA_NOREALTIMEUPDATES) == 0)
466                         ANIM_id_update(t->scene, tdn->id);
467                 
468                 /* if cancelling transform, just write the values without validating, then move on */
469                 if (t->state == TRANS_CANCEL) {
470                         /* clear the values by directly overwriting the originals, but also need to restore
471                          * endpoints of neighboring transition-strips
472                          */
473                         
474                         /* start */
475                         strip->start= tdn->h1[0];
476                         
477                         if ((strip->prev) && (strip->prev->type == NLASTRIP_TYPE_TRANSITION))
478                                 strip->prev->end= tdn->h1[0];
479                         
480                         /* end */
481                         strip->end= tdn->h2[0];
482                         
483                         if ((strip->next) && (strip->next->type == NLASTRIP_TYPE_TRANSITION))
484                                 strip->next->start= tdn->h2[0];
485                         
486                         /* flush transforms to child strips (since this should be a meta) */
487                         BKE_nlameta_flush_transforms(strip);
488                         
489                         /* restore to original track (if needed) */
490                         if (tdn->oldTrack != tdn->nlt) {
491                                 /* just append to end of list for now, since strips get sorted in special_aftertrans_update() */
492                                 BLI_remlink(&tdn->nlt->strips, strip);
493                                 BLI_addtail(&tdn->oldTrack->strips, strip);
494                         }
495                         
496                         continue;
497                 }
498                 
499                 /* firstly, check if the proposed transform locations would overlap with any neighbouring strips
500                  * (barring transitions) which are absolute barriers since they are not being moved
501                  *
502                  * this is done as a iterative procedure (done 5 times max for now)
503                  */
504                 for (iter=0; iter < 5; iter++) {
505                         pExceeded= ((strip->prev) && (strip->prev->type != NLASTRIP_TYPE_TRANSITION) && (tdn->h1[0] < strip->prev->end));
506                         nExceeded= ((strip->next) && (strip->next->type != NLASTRIP_TYPE_TRANSITION) && (tdn->h2[0] > strip->next->start));
507                         
508                         if ((pExceeded && nExceeded) || (iter == 4) ) {
509                                 /* both endpoints exceeded (or iteration ping-pong'd meaning that we need a compromise)
510                                  *      - simply crop strip to fit within the bounds of the strips bounding it
511                                  *      - if there were no neighbours, clear the transforms (make it default to the strip's current values)
512                                  */
513                                 if (strip->prev && strip->next) {
514                                         tdn->h1[0]= strip->prev->end;
515                                         tdn->h2[0]= strip->next->start;
516                                 }
517                                 else {
518                                         tdn->h1[0]= strip->start;
519                                         tdn->h2[0]= strip->end;
520                                 }
521                         }
522                         else if (nExceeded) {
523                                 /* move backwards */
524                                 float offset= tdn->h2[0] - strip->next->start;
525                                 
526                                 tdn->h1[0] -= offset;
527                                 tdn->h2[0] -= offset;
528                         }
529                         else if (pExceeded) {
530                                 /* more forwards */
531                                 float offset= strip->prev->end - tdn->h1[0];
532                                 
533                                 tdn->h1[0] += offset;
534                                 tdn->h2[0] += offset;
535                         }
536                         else /* all is fine and well */
537                                 break;
538                 }
539                 
540                 /* handle auto-snapping */
541                 switch (snla->autosnap) {
542                         case SACTSNAP_FRAME: /* snap to nearest frame/time  */
543                                 if (snla->flag & SNLA_DRAWTIME) {
544                                         tdn->h1[0]= (float)( floor((tdn->h1[0]/secf) + 0.5f) * secf );
545                                         tdn->h2[0]= (float)( floor((tdn->h2[0]/secf) + 0.5f) * secf );
546                                 }
547                                 else {
548                                         tdn->h1[0]= (float)( floor(tdn->h1[0]+0.5f) );
549                                         tdn->h2[0]= (float)( floor(tdn->h2[0]+0.5f) );
550                                 }
551                                 break;
552                         
553                         case SACTSNAP_MARKER: /* snap to nearest marker */
554                                 tdn->h1[0]= (float)ED_markers_find_nearest_marker_time(&t->scene->markers, tdn->h1[0]);
555                                 tdn->h2[0]= (float)ED_markers_find_nearest_marker_time(&t->scene->markers, tdn->h2[0]);
556                                 break;
557                 }
558                 
559                 /* use RNA to write the values... */
560                 // TODO: do we need to write in 2 passes to make sure that no truncation goes on?
561                 RNA_pointer_create(NULL, &RNA_NlaStrip, strip, &strip_ptr);
562                 
563                 RNA_float_set(&strip_ptr, "frame_start", tdn->h1[0]);
564                 RNA_float_set(&strip_ptr, "frame_end", tdn->h2[0]);
565                 
566                 /* flush transforms to child strips (since this should be a meta) */
567                 BKE_nlameta_flush_transforms(strip);
568                 
569                 
570                 /* now, check if we need to try and move track
571                  *      - we need to calculate both, as only one may have been altered by transform if only 1 handle moved
572                  */
573                 delta_y1= ((int)tdn->h1[1] / NLACHANNEL_STEP(snla) - tdn->trackIndex);
574                 delta_y2= ((int)tdn->h2[1] / NLACHANNEL_STEP(snla) - tdn->trackIndex);
575                 
576                 if (delta_y1 || delta_y2) {
577                         NlaTrack *track;
578                         int delta = (delta_y2) ? delta_y2 : delta_y1;
579                         int n;
580                         
581                         /* move in the requested direction, checking at each layer if there's space for strip to pass through,
582                          * stopping on the last track available or that we're able to fit in
583                          */
584                         if (delta > 0) {
585                                 for (track=tdn->nlt->next, n=0; (track) && (n < delta); track=track->next, n++) {
586                                         /* check if space in this track for the strip */
587                                         if (BKE_nlatrack_has_space(track, strip->start, strip->end)) {
588                                                 /* move strip to this track */
589                                                 BLI_remlink(&tdn->nlt->strips, strip);
590                                                 BKE_nlatrack_add_strip(track, strip);
591                                                 
592                                                 tdn->nlt= track;
593                                                 tdn->trackIndex++;
594                                         }
595                                         else /* can't move any further */
596                                                 break;
597                                 }
598                         }
599                         else {
600                                 /* make delta 'positive' before using it, since we now know to go backwards */
601                                 delta= -delta;
602                                 
603                                 for (track=tdn->nlt->prev, n=0; (track) && (n < delta); track=track->prev, n++) {
604                                         /* check if space in this track for the strip */
605                                         if (BKE_nlatrack_has_space(track, strip->start, strip->end)) {
606                                                 /* move strip to this track */
607                                                 BLI_remlink(&tdn->nlt->strips, strip);
608                                                 BKE_nlatrack_add_strip(track, strip);
609                                                 
610                                                 tdn->nlt= track;
611                                                 tdn->trackIndex--;
612                                         }
613                                         else /* can't move any further */
614                                                 break;
615                                 }
616                         }
617                 }
618         }
619 }
620
621 /* helper for recalcData() - for 3d-view transforms */
622 static void recalcData_view3d(TransInfo *t)
623 {
624         Base *base = t->scene->basact;
625         
626         if (t->obedit) {
627                 if ELEM(t->obedit->type, OB_CURVE, OB_SURF) {
628                         Curve *cu= t->obedit->data;
629                         ListBase *nurbs= ED_curve_editnurbs(cu);
630                         Nurb *nu= nurbs->first;
631                         
632                         if(t->state != TRANS_CANCEL) {
633                                 clipMirrorModifier(t, t->obedit);
634                                 applyProject(t);
635                         }
636                         
637                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
638                                 
639                         if (t->state == TRANS_CANCEL) {
640                                 while(nu) {
641                                         calchandlesNurb(nu); /* Cant do testhandlesNurb here, it messes up the h1 and h2 flags */
642                                         nu= nu->next;
643                                 }
644                         } 
645                         else {
646                                 /* Normal updating */
647                                 while(nu) {
648                                         test2DNurb(nu);
649                                         calchandlesNurb(nu);
650                                         nu= nu->next;
651                                 }
652                         }
653                 }
654                 else if(t->obedit->type==OB_LATTICE) {
655                         Lattice *la= t->obedit->data;
656                         
657                         if(t->state != TRANS_CANCEL) {
658                                 applyProject(t);
659                         }
660                         
661                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
662                         
663                         if(la->editlatt->latt->flag & LT_OUTSIDE) outside_lattice(la->editlatt->latt);
664                 }
665                 else if (t->obedit->type == OB_MESH) {
666                         EditMesh *em = ((Mesh*)t->obedit->data)->edit_mesh;
667                         /* mirror modifier clipping? */
668                         if(t->state != TRANS_CANCEL) {
669                                 /* apply clipping after so we never project past the clip plane [#25423] */
670                                 applyProject(t);
671                                 clipMirrorModifier(t, t->obedit);
672                         }
673                         if((t->options & CTX_NO_MIRROR) == 0 && (t->flag & T_MIRROR))
674                                 editmesh_apply_to_mirror(t);
675                                 
676                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
677                         
678                         recalc_editnormals(em);
679                 }
680                 else if(t->obedit->type==OB_ARMATURE) { /* no recalc flag, does pose */
681                         bArmature *arm= t->obedit->data;
682                         ListBase *edbo = arm->edbo;
683                         EditBone *ebo;
684                         TransData *td = t->data;
685                         int i;
686                         
687                         if(t->state != TRANS_CANCEL) {
688                                 applyProject(t);
689                         }
690                         
691                         /* Ensure all bones are correctly adjusted */
692                         for (ebo = edbo->first; ebo; ebo = ebo->next){
693                                 
694                                 if ((ebo->flag & BONE_CONNECTED) && ebo->parent){
695                                         /* If this bone has a parent tip that has been moved */
696                                         if (ebo->parent->flag & BONE_TIPSEL){
697                                                 VECCOPY (ebo->head, ebo->parent->tail);
698                                                 if(t->mode==TFM_BONE_ENVELOPE) ebo->rad_head= ebo->parent->rad_tail;
699                                         }
700                                         /* If this bone has a parent tip that has NOT been moved */
701                                         else{
702                                                 VECCOPY (ebo->parent->tail, ebo->head);
703                                                 if(t->mode==TFM_BONE_ENVELOPE) ebo->parent->rad_tail= ebo->rad_head;
704                                         }
705                                 }
706                                 
707                                 /* on extrude bones, oldlength==0.0f, so we scale radius of points */
708                                 ebo->length= len_v3v3(ebo->head, ebo->tail);
709                                 if(ebo->oldlength==0.0f) {
710                                         ebo->rad_head= 0.25f*ebo->length;
711                                         ebo->rad_tail= 0.10f*ebo->length;
712                                         ebo->dist= 0.25f*ebo->length;
713                                         if(ebo->parent) {
714                                                 if(ebo->rad_head > ebo->parent->rad_tail)
715                                                         ebo->rad_head= ebo->parent->rad_tail;
716                                         }
717                                 }
718                                 else if(t->mode!=TFM_BONE_ENVELOPE) {
719                                         /* if bones change length, lets do that for the deform distance as well */
720                                         ebo->dist*= ebo->length/ebo->oldlength;
721                                         ebo->rad_head*= ebo->length/ebo->oldlength;
722                                         ebo->rad_tail*= ebo->length/ebo->oldlength;
723                                         ebo->oldlength= ebo->length;
724                                 }
725                         }
726                         
727                         
728                         if (t->mode != TFM_BONE_ROLL)
729                         {
730                                 /* fix roll */
731                                 for(i = 0; i < t->total; i++, td++)
732                                 {
733                                         if (td->extra)
734                                         {
735                                                 float vec[3], up_axis[3];
736                                                 float qrot[4];
737                                                 
738                                                 ebo = td->extra;
739                                                 VECCOPY(up_axis, td->axismtx[2]);
740                                                 
741                                                 if (t->mode != TFM_ROTATION)
742                                                 {
743                                                         sub_v3_v3v3(vec, ebo->tail, ebo->head);
744                                                         normalize_v3(vec);
745                                                         rotation_between_vecs_to_quat(qrot, td->axismtx[1], vec);
746                                                         mul_qt_v3(qrot, up_axis);
747                                                 }
748                                                 else
749                                                 {
750                                                         mul_m3_v3(t->mat, up_axis);
751                                                 }
752                                                 
753                                                 ebo->roll = ED_rollBoneToVector(ebo, up_axis, FALSE);
754                                         }
755                                 }
756                         }
757                         
758                         if(arm->flag & ARM_MIRROR_EDIT)
759                                 transform_armature_mirror_update(t->obedit);
760                         
761                 }
762                 else
763                 {
764                         if(t->state != TRANS_CANCEL) {
765                                 applyProject(t);
766                         }
767                         DAG_id_tag_update(t->obedit->data, 0);  /* sets recalc flags */
768                 }
769         }
770         else if( (t->flag & T_POSE) && t->poseobj) {
771                 Object *ob= t->poseobj;
772                 bArmature *arm= ob->data;
773                 
774                 /* if animtimer is running, and the object already has animation data,
775                  * check if the auto-record feature means that we should record 'samples'
776                  * (i.e. uneditable animation values)
777                  *
778                  * context is needed for keying set poll() functions.
779                  */
780                 // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
781                 if ((t->animtimer) && (t->context) && IS_AUTOKEY_ON(t->scene)) {
782                         int targetless_ik= (t->flag & T_AUTOIK); // XXX this currently doesn't work, since flags aren't set yet!
783                         
784                         animrecord_check_state(t->scene, &ob->id, t->animtimer);
785                         autokeyframe_pose_cb_func(t->context, t->scene, (View3D *)t->view, ob, t->mode, targetless_ik);
786                 }
787                 
788                 /* old optimize trick... this enforces to bypass the depgraph */
789                 if (!(arm->flag & ARM_DELAYDEFORM)) {
790                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);  /* sets recalc flags */
791                 }
792                 else
793                         where_is_pose(t->scene, ob);
794         }
795         else if(base && (base->object->mode & OB_MODE_PARTICLE_EDIT) && PE_get_current(t->scene, base->object)) {
796                 if(t->state != TRANS_CANCEL) {
797                         applyProject(t);
798                 }
799                 flushTransParticles(t);
800         }
801         else {
802                 int i;
803                 
804                 if(t->state != TRANS_CANCEL) {
805                         applyProject(t);
806                 }
807                 
808                 for (i = 0; i < t->total; i++) {
809                         TransData *td = t->data + i;
810                         Object *ob = td->ob;
811                         
812                         if (td->flag & TD_NOACTION)
813                                 break;
814                         
815                         if (td->flag & TD_SKIP)
816                                 continue;
817                         
818                         /* if animtimer is running, and the object already has animation data,
819                          * check if the auto-record feature means that we should record 'samples'
820                          * (i.e. uneditable animation values)
821                          */
822                         // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
823                         if ((t->animtimer) && IS_AUTOKEY_ON(t->scene)) {
824                                 animrecord_check_state(t->scene, &ob->id, t->animtimer);
825                                 autokeyframe_ob_cb_func(t->context, t->scene, (View3D *)t->view, ob, t->mode);
826                         }
827                         
828                         /* sets recalc flags fully, instead of flushing existing ones 
829                          * otherwise proxies don't function correctly
830                          */
831                         DAG_id_tag_update(&ob->id, OB_RECALC_OB);
832                 }
833         }
834 }
835
836 /* called for updating while transform acts, once per redraw */
837 void recalcData(TransInfo *t)
838 {
839         if (t->spacetype==SPACE_NODE) {
840                 flushTransNodes(t);
841         }
842         else if (t->spacetype==SPACE_SEQ) {
843                 flushTransSeq(t);
844         }
845         else if (t->spacetype == SPACE_ACTION) {
846                 recalcData_actedit(t);
847         }
848         else if (t->spacetype == SPACE_IPO) {
849                 recalcData_graphedit(t);
850         }
851         else if (t->spacetype == SPACE_NLA) {
852                 recalcData_nla(t);
853         }
854         else if (t->spacetype == SPACE_IMAGE) {
855                 if (t->obedit && t->obedit->type == OB_MESH) {
856                         SpaceImage *sima= t->sa->spacedata.first;
857                         
858                         flushTransUVs(t);
859                         if(sima->flag & SI_LIVE_UNWRAP)
860                                 ED_uvedit_live_unwrap_re_solve();
861                         
862                         DAG_id_tag_update(t->obedit->data, 0);
863                 }
864         }
865         else if (t->spacetype == SPACE_VIEW3D) {
866                 recalcData_view3d(t);
867         }
868 }
869
870 void drawLine(TransInfo *t, float *center, float *dir, char axis, short options)
871 {
872         float v1[3], v2[3], v3[3];
873         unsigned char col[3], col2[3];
874
875         if (t->spacetype == SPACE_VIEW3D)
876         {
877                 View3D *v3d = t->view;
878                 
879                 glPushMatrix();
880                 
881                 //if(t->obedit) glLoadMatrixf(t->obedit->obmat);        // sets opengl viewing
882                 
883                 
884                 copy_v3_v3(v3, dir);
885                 mul_v3_fl(v3, v3d->far);
886                 
887                 sub_v3_v3v3(v2, center, v3);
888                 add_v3_v3v3(v1, center, v3);
889                 
890                 if (options & DRAWLIGHT) {
891                         col[0] = col[1] = col[2] = 220;
892                 }
893                 else {
894                         UI_GetThemeColor3ubv(TH_GRID, col);
895                 }
896                 UI_make_axis_color(col, col2, axis);
897                 glColor3ubv(col2);
898                 
899                 setlinestyle(0);
900                 glBegin(GL_LINE_STRIP);
901                         glVertex3fv(v1);
902                         glVertex3fv(v2);
903                 glEnd();
904                 
905                 glPopMatrix();
906         }
907 }
908
909 void resetTransRestrictions(TransInfo *t)
910 {
911         t->flag &= ~T_ALL_RESTRICTIONS;
912 }
913
914 int initTransInfo (bContext *C, TransInfo *t, wmOperator *op, wmEvent *event)
915 {
916         Scene *sce = CTX_data_scene(C);
917         ToolSettings *ts = CTX_data_tool_settings(C);
918         ARegion *ar = CTX_wm_region(C);
919         ScrArea *sa = CTX_wm_area(C);
920         Object *obedit = CTX_data_edit_object(C);
921         
922         /* moving: is shown in drawobject() (transform color) */
923 //  TRANSFORM_FIX_ME
924 //      if(obedit || (t->flag & T_POSE) ) G.moving= G_TRANSFORM_EDIT;
925 //      else if(G.f & G_PARTICLEEDIT) G.moving= G_TRANSFORM_PARTICLE;
926 //      else G.moving= G_TRANSFORM_OBJ;
927         
928         t->scene = sce;
929         t->sa = sa;
930         t->ar = ar;
931         t->obedit = obedit;
932         t->settings = ts;
933         
934         t->data = NULL;
935         t->ext = NULL;
936         
937         t->helpline = HLP_NONE;
938         
939         t->flag = 0;
940         
941         t->redraw = 1; /* redraw first time */
942         
943         if (event)
944         {
945                 VECCOPY2D(t->imval, event->mval);
946                 t->event_type = event->type;
947         }
948         else
949         {
950                 t->imval[0] = 0;
951                 t->imval[1] = 0;
952         }
953         
954         t->con.imval[0] = t->imval[0];
955         t->con.imval[1] = t->imval[1];
956         
957         t->mval[0] = t->imval[0];
958         t->mval[1] = t->imval[1];
959         
960         t->transform            = NULL;
961         t->handleEvent          = NULL;
962         
963         t->total                        = 0;
964         
965         t->val = 0.0f;
966         
967         t->vec[0]                       =
968                 t->vec[1]               =
969                 t->vec[2]               = 0.0f;
970         
971         t->center[0]            =
972                 t->center[1]    =
973                 t->center[2]    = 0.0f;
974         
975         unit_m3(t->mat);
976         
977         /* if there's an event, we're modal */
978         if (event) {
979                 t->flag |= T_MODAL;
980         }
981
982         /* Crease needs edge flag */
983         if (t->mode == TFM_CREASE) {
984                 t->options |= CTX_EDGE;
985         }
986
987
988         /* Assign the space type, some exceptions for running in different mode */
989         if(sa == NULL) {
990                 /* background mode */
991                 t->spacetype= SPACE_EMPTY;
992         }
993         else if ((ar == NULL) && (sa->spacetype == SPACE_VIEW3D)) {
994                 /* running in the text editor */
995                 t->spacetype= SPACE_EMPTY;
996         }
997         else {
998                 /* normal operation */
999                 t->spacetype= sa->spacetype;
1000         }
1001
1002
1003         if(t->spacetype == SPACE_VIEW3D)
1004         {
1005                 View3D *v3d = sa->spacedata.first;
1006                 
1007                 t->view = v3d;
1008                 t->animtimer= CTX_wm_screen(C)->animtimer;
1009                 
1010                 /* turn manipulator off during transform */
1011                 // FIXME: but don't do this when USING the manipulator...
1012                 if (t->flag & T_MODAL) {
1013                         t->twtype = v3d->twtype;
1014                         v3d->twtype = 0;
1015                 }
1016
1017                 if(v3d->flag & V3D_ALIGN) t->flag |= T_V3D_ALIGN;
1018                 t->around = v3d->around;
1019                 
1020                 if (op && RNA_struct_find_property(op->ptr, "constraint_orientation") && RNA_property_is_set(op->ptr, "constraint_orientation"))
1021                 {
1022                         t->current_orientation = RNA_enum_get(op->ptr, "constraint_orientation");
1023                         
1024                         if (t->current_orientation >= V3D_MANIP_CUSTOM + BIF_countTransformOrientation(C))
1025                         {
1026                                 t->current_orientation = V3D_MANIP_GLOBAL;
1027                         }
1028                 }
1029                 else
1030                 {
1031                         t->current_orientation = v3d->twmode;
1032                 }
1033
1034                 /* exceptional case */
1035                 if(t->around==V3D_LOCAL && (t->settings->selectmode & SCE_SELECT_FACE)) {
1036                         if(ELEM3(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL)) {
1037                                 t->options |= CTX_NO_PET;
1038                         }
1039                 }
1040         }
1041         else if(t->spacetype==SPACE_IMAGE)
1042         {
1043                 SpaceImage *sima = sa->spacedata.first;
1044                 // XXX for now, get View2D from the active region
1045                 t->view = &ar->v2d;
1046                 t->around = sima->around;
1047         }
1048         else if(t->spacetype==SPACE_NODE)
1049         {
1050                 // XXX for now, get View2D from the active region
1051                 t->view = &ar->v2d;
1052                 t->around = V3D_CENTER;
1053         }
1054         else if(t->spacetype==SPACE_IPO) 
1055         {
1056                 SpaceIpo *sipo= sa->spacedata.first;
1057                 t->view = &ar->v2d;
1058                 t->around = sipo->around;
1059         }
1060         else
1061         {
1062                 if(ar) {
1063                         // XXX for now, get View2D  from the active region
1064                         t->view = &ar->v2d;
1065                         // XXX for now, the center point is the midpoint of the data
1066                 }
1067                 else {
1068                         t->view= NULL;
1069                 }
1070                 t->around = V3D_CENTER;
1071         }
1072         
1073         if (op && RNA_property_is_set(op->ptr, "release_confirm"))
1074         {
1075                 if (RNA_boolean_get(op->ptr, "release_confirm"))
1076                 {
1077                         t->flag |= T_RELEASE_CONFIRM;
1078                 }
1079         }
1080         else
1081         {
1082                 if (U.flag & USER_RELEASECONFIRM)
1083                 {
1084                         t->flag |= T_RELEASE_CONFIRM;
1085                 }
1086         }
1087
1088         if (op && RNA_struct_find_property(op->ptr, "mirror") && RNA_property_is_set(op->ptr, "mirror"))
1089         {
1090                 if (RNA_boolean_get(op->ptr, "mirror"))
1091                 {
1092                         t->flag |= T_MIRROR;
1093                         t->mirror = 1;
1094                 }
1095         }
1096         // Need stuff to take it from edit mesh or whatnot here
1097         else
1098         {
1099                 if (t->obedit && t->obedit->type == OB_MESH && (((Mesh *)t->obedit->data)->editflag & ME_EDIT_MIRROR_X))
1100                 {
1101                         t->flag |= T_MIRROR;
1102                         t->mirror = 1;
1103                 }
1104         }
1105         
1106         /* setting PET flag only if property exist in operator. Otherwise, assume it's not supported */
1107         if (op && RNA_struct_find_property(op->ptr, "proportional"))
1108         {
1109                 if (RNA_property_is_set(op->ptr, "proportional"))
1110                 {
1111                         switch(RNA_enum_get(op->ptr, "proportional"))
1112                         {
1113                         case PROP_EDIT_CONNECTED:
1114                                 t->flag |= T_PROP_CONNECTED;
1115                         case PROP_EDIT_ON:
1116                                 t->flag |= T_PROP_EDIT;
1117                                 break;
1118                         }
1119                 }
1120                 else
1121                 {
1122                         /* use settings from scene only if modal */
1123                         if (t->flag & T_MODAL)
1124                         {
1125                                 if ((t->options & CTX_NO_PET) == 0)
1126                                 {
1127                                         if (t->obedit && ts->proportional != PROP_EDIT_OFF)
1128                                         {
1129                                                 t->flag |= T_PROP_EDIT;
1130
1131                                                 if(ts->proportional == PROP_EDIT_CONNECTED)
1132                                                         t->flag |= T_PROP_CONNECTED;
1133                                         }
1134                                         else if (t->obedit == NULL && ts->proportional_objects)
1135                                         {
1136                                                 t->flag |= T_PROP_EDIT;
1137                                         }
1138                                 }
1139                         }
1140                 }
1141                 
1142                 if (op && RNA_struct_find_property(op->ptr, "proportional_size") && RNA_property_is_set(op->ptr, "proportional_size"))
1143                 {
1144                         t->prop_size = RNA_float_get(op->ptr, "proportional_size");
1145                 }
1146                 else
1147                 {
1148                         t->prop_size = ts->proportional_size;
1149                 }
1150                 
1151                 
1152                 /* TRANSFORM_FIX_ME rna restrictions */
1153                 if (t->prop_size <= 0.00001f)
1154                 {
1155                         printf("Proportional size (%f) under 0.00001, reseting to 1!\n", t->prop_size);
1156                         t->prop_size = 1.0f;
1157                 }
1158                 
1159                 if (op && RNA_struct_find_property(op->ptr, "proportional_edit_falloff") && RNA_property_is_set(op->ptr, "proportional_edit_falloff"))
1160                 {
1161                         t->prop_mode = RNA_enum_get(op->ptr, "proportional_edit_falloff");
1162                 }
1163                 else
1164                 {
1165                         t->prop_mode = ts->prop_mode;
1166                 }
1167         }
1168         else /* add not pet option to context when not available */
1169         {
1170                 t->options |= CTX_NO_PET;
1171         }
1172         
1173         setTransformViewMatrices(t);
1174         initNumInput(&t->num);
1175         initNDofInput(&t->ndof);
1176         
1177         return 1;
1178 }
1179
1180 /* Here I would suggest only TransInfo related issues, like free data & reset vars. Not redraws */
1181 void postTrans (bContext *C, TransInfo *t)
1182 {
1183         TransData *td;
1184         
1185         if (t->draw_handle_view)
1186                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_view);
1187         if (t->draw_handle_apply)
1188                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_apply);
1189         if (t->draw_handle_pixel)
1190                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_pixel);
1191         if (t->draw_handle_cursor)
1192                 WM_paint_cursor_end(CTX_wm_manager(C), t->draw_handle_cursor);
1193
1194         if (t->customFree) {
1195                 /* Can take over freeing t->data and data2d etc... */
1196                 t->customFree(t);
1197         }
1198         else if (t->customData) {
1199                 MEM_freeN(t->customData);
1200         }
1201
1202         /* postTrans can be called when nothing is selected, so data is NULL already */
1203         if (t->data) {
1204                 int a;
1205                 
1206                 /* free data malloced per trans-data */
1207                 for(a=0, td= t->data; a<t->total; a++, td++) {
1208                         if (td->flag & TD_BEZTRIPLE) 
1209                                 MEM_freeN(td->hdata);
1210                 }
1211                 MEM_freeN(t->data);
1212         }
1213         
1214         BLI_freelistN(&t->tsnap.points);
1215
1216         if (t->ext) MEM_freeN(t->ext);
1217         if (t->data2d) {
1218                 MEM_freeN(t->data2d);
1219                 t->data2d= NULL;
1220         }
1221         
1222         if(t->spacetype==SPACE_IMAGE) {
1223                 SpaceImage *sima= t->sa->spacedata.first;
1224                 if(sima->flag & SI_LIVE_UNWRAP)
1225                         ED_uvedit_live_unwrap_end(t->state == TRANS_CANCEL);
1226         }
1227         else if(t->spacetype==SPACE_VIEW3D) {
1228                 View3D *v3d = t->sa->spacedata.first;
1229                 /* restore manipulator */
1230                 if (t->flag & T_MODAL) {
1231                         v3d->twtype = t->twtype;
1232                 }
1233         }
1234         
1235         if (t->mouse.data)
1236         {
1237                 MEM_freeN(t->mouse.data);
1238         }
1239 }
1240
1241 void applyTransObjects(TransInfo *t)
1242 {
1243         TransData *td;
1244         
1245         for (td = t->data; td < t->data + t->total; td++) {
1246                 VECCOPY(td->iloc, td->loc);
1247                 if (td->ext->rot) {
1248                         VECCOPY(td->ext->irot, td->ext->rot);
1249                 }
1250                 if (td->ext->size) {
1251                         VECCOPY(td->ext->isize, td->ext->size);
1252                 }
1253         }
1254         recalcData(t);
1255 }
1256
1257 static void restoreElement(TransData *td) {
1258         /* TransData for crease has no loc */
1259         if (td->loc) {
1260                 VECCOPY(td->loc, td->iloc);
1261         }
1262         if (td->val) {
1263                 *td->val = td->ival;
1264         }
1265
1266         if (td->ext && (td->flag&TD_NO_EXT)==0) {
1267                 if (td->ext->rot) {
1268                         VECCOPY(td->ext->rot, td->ext->irot);
1269                 }
1270                 if(td->ext->rotAngle) {
1271                         *td->ext->rotAngle= td->ext->irotAngle;
1272                 }
1273                 if(td->ext->rotAxis) {
1274                         VECCOPY(td->ext->rotAxis, td->ext->irotAxis);
1275                 }
1276                 /* XXX, drotAngle & drotAxis not used yet */
1277                 if (td->ext->size) {
1278                         VECCOPY(td->ext->size, td->ext->isize);
1279                 }
1280                 if (td->ext->quat) {
1281                         QUATCOPY(td->ext->quat, td->ext->iquat);
1282                 }
1283         }
1284         
1285         if (td->flag & TD_BEZTRIPLE) {
1286                 *(td->hdata->h1) = td->hdata->ih1;
1287                 *(td->hdata->h2) = td->hdata->ih2;
1288         }
1289 }
1290
1291 void restoreTransObjects(TransInfo *t)
1292 {
1293         TransData *td;
1294         TransData2D *td2d;
1295
1296         for (td = t->data; td < t->data + t->total; td++) {
1297                 restoreElement(td);
1298         }
1299         
1300         for (td2d=t->data2d; t->data2d && td2d < t->data2d + t->total; td2d++) {
1301                 if (td2d->h1) {
1302                         td2d->h1[0] = td2d->ih1[0];
1303                         td2d->h1[1] = td2d->ih1[1];
1304                 }
1305                 if (td2d->h2) {
1306                         td2d->h2[0] = td2d->ih2[0];
1307                         td2d->h2[1] = td2d->ih2[1];
1308                 }
1309         }
1310
1311         unit_m3(t->mat);
1312         
1313         recalcData(t);
1314 }
1315
1316 void calculateCenter2D(TransInfo *t)
1317 {
1318         if (t->flag & (T_EDIT|T_POSE)) {
1319                 Object *ob= t->obedit?t->obedit:t->poseobj;
1320                 float vec[3];
1321                 
1322                 VECCOPY(vec, t->center);
1323                 mul_m4_v3(ob->obmat, vec);
1324                 projectIntView(t, vec, t->center2d);
1325         }
1326         else {
1327                 projectIntView(t, t->center, t->center2d);
1328         }
1329 }
1330
1331 void calculateCenterCursor(TransInfo *t)
1332 {
1333         float *cursor;
1334         
1335         cursor = give_cursor(t->scene, t->view);
1336         VECCOPY(t->center, cursor);
1337         
1338         /* If edit or pose mode, move cursor in local space */
1339         if (t->flag & (T_EDIT|T_POSE)) {
1340                 Object *ob = t->obedit?t->obedit:t->poseobj;
1341                 float mat[3][3], imat[3][3];
1342                 
1343                 sub_v3_v3v3(t->center, t->center, ob->obmat[3]);
1344                 copy_m3_m4(mat, ob->obmat);
1345                 invert_m3_m3(imat, mat);
1346                 mul_m3_v3(imat, t->center);
1347         }
1348         
1349         calculateCenter2D(t);
1350 }
1351
1352 void calculateCenterCursor2D(TransInfo *t)
1353 {
1354         float aspx=1.0, aspy=1.0;
1355         float *cursor= NULL;
1356         
1357         if(t->spacetype==SPACE_IMAGE) {
1358                 SpaceImage *sima= (SpaceImage *)t->sa->spacedata.first;
1359                 /* only space supported right now but may change */
1360                 ED_space_image_uv_aspect(sima, &aspx, &aspy);
1361                 cursor = sima->cursor;
1362         }
1363         
1364         if (cursor) {
1365                 t->center[0] = cursor[0] * aspx;
1366                 t->center[1] = cursor[1] * aspy;
1367         }
1368         
1369         calculateCenter2D(t);
1370 }
1371
1372 static void calculateCenterCursorGraph2D(TransInfo *t)
1373 {
1374         SpaceIpo *sipo= (SpaceIpo *)t->sa->spacedata.first;
1375         Scene *scene= t->scene;
1376         
1377         /* cursor is combination of current frame, and graph-editor cursor value */
1378         t->center[0]= (float)(scene->r.cfra);
1379         t->center[1]= sipo->cursorVal;
1380         
1381         calculateCenter2D(t);
1382 }
1383
1384 void calculateCenterMedian(TransInfo *t)
1385 {
1386         float partial[3] = {0.0f, 0.0f, 0.0f};
1387         int total = 0;
1388         int i;
1389         
1390         for(i = 0; i < t->total; i++) {
1391                 if (t->data[i].flag & TD_SELECTED) {
1392                         if (!(t->data[i].flag & TD_NOCENTER))
1393                         {
1394                                 add_v3_v3(partial, t->data[i].center);
1395                                 total++;
1396                         }
1397                 }
1398                 else {
1399                         /*
1400                            All the selected elements are at the head of the array
1401                            which means we can stop when it finds unselected data
1402                         */
1403                         break;
1404                 }
1405         }
1406         if(i)
1407                 mul_v3_fl(partial, 1.0f / total);
1408         VECCOPY(t->center, partial);
1409         
1410         calculateCenter2D(t);
1411 }
1412
1413 void calculateCenterBound(TransInfo *t)
1414 {
1415         float max[3];
1416         float min[3];
1417         int i;
1418         for(i = 0; i < t->total; i++) {
1419                 if (i) {
1420                         if (t->data[i].flag & TD_SELECTED) {
1421                                 if (!(t->data[i].flag & TD_NOCENTER))
1422                                         minmax_v3v3_v3(min, max, t->data[i].center);
1423                         }
1424                         else {
1425                                 /*
1426                                    All the selected elements are at the head of the array
1427                                    which means we can stop when it finds unselected data
1428                                 */
1429                                 break;
1430                         }
1431                 }
1432                 else {
1433                         VECCOPY(max, t->data[i].center);
1434                         VECCOPY(min, t->data[i].center);
1435                 }
1436         }
1437         add_v3_v3v3(t->center, min, max);
1438         mul_v3_fl(t->center, 0.5);
1439         
1440         calculateCenter2D(t);
1441 }
1442
1443 void calculateCenter(TransInfo *t)
1444 {
1445         switch(t->around) {
1446         case V3D_CENTER:
1447                 calculateCenterBound(t);
1448                 break;
1449         case V3D_CENTROID:
1450                 calculateCenterMedian(t);
1451                 break;
1452         case V3D_CURSOR:
1453                 if(t->spacetype==SPACE_IMAGE)
1454                         calculateCenterCursor2D(t);
1455                 else if(t->spacetype==SPACE_IPO)
1456                         calculateCenterCursorGraph2D(t);
1457                 else
1458                         calculateCenterCursor(t);
1459                 break;
1460         case V3D_LOCAL:
1461                 /* Individual element center uses median center for helpline and such */
1462                 calculateCenterMedian(t);
1463                 break;
1464         case V3D_ACTIVE:
1465                 {
1466                 /* set median, and if if if... do object center */
1467                 
1468                 /* EDIT MODE ACTIVE EDITMODE ELEMENT */
1469
1470                 if (t->obedit && t->obedit->type == OB_MESH) {
1471                         EditSelection ese;
1472                         EditMesh *em = BKE_mesh_get_editmesh(t->obedit->data);
1473                         
1474                         if (EM_get_actSelection(em, &ese)) {
1475                                 EM_editselection_center(t->center, &ese);
1476                                 calculateCenter2D(t);
1477                                 break;
1478                         }
1479                 } /* END EDIT MODE ACTIVE ELEMENT */
1480                 
1481                 calculateCenterMedian(t);
1482                 if((t->flag & (T_EDIT|T_POSE))==0)
1483                 {
1484                         Scene *scene = t->scene;
1485                         Object *ob= OBACT;
1486                         if(ob)
1487                         {
1488                                 VECCOPY(t->center, ob->obmat[3]);
1489                                 projectIntView(t, t->center, t->center2d);
1490                         }
1491                 }
1492                 
1493                 }
1494         }
1495         
1496         /* setting constraint center */
1497         VECCOPY(t->con.center, t->center);
1498         if(t->flag & (T_EDIT|T_POSE))
1499         {
1500                 Object *ob= t->obedit?t->obedit:t->poseobj;
1501                 mul_m4_v3(ob->obmat, t->con.center);
1502         }
1503         
1504         /* for panning from cameraview */
1505         if(t->flag & T_OBJECT)
1506         {
1507                 if(t->spacetype==SPACE_VIEW3D && t->ar && t->ar->regiontype == RGN_TYPE_WINDOW)
1508                 {
1509                         View3D *v3d = t->view;
1510                         Scene *scene = t->scene;
1511                         RegionView3D *rv3d = t->ar->regiondata;
1512                         
1513                         if(v3d->camera == OBACT && rv3d->persp==RV3D_CAMOB)
1514                         {
1515                                 float axis[3];
1516                                 /* persinv is nasty, use viewinv instead, always right */
1517                                 VECCOPY(axis, t->viewinv[2]);
1518                                 normalize_v3(axis);
1519                                 
1520                                 /* 6.0 = 6 grid units */
1521                                 axis[0]= t->center[0]- 6.0f*axis[0];
1522                                 axis[1]= t->center[1]- 6.0f*axis[1];
1523                                 axis[2]= t->center[2]- 6.0f*axis[2];
1524                                 
1525                                 projectIntView(t, axis, t->center2d);
1526                                 
1527                                 /* rotate only needs correct 2d center, grab needs initgrabz() value */
1528                                 if(t->mode==TFM_TRANSLATION)
1529                                 {
1530                                         VECCOPY(t->center, axis);
1531                                         VECCOPY(t->con.center, t->center);
1532                                 }
1533                         }
1534                 }
1535         }
1536         
1537         if(t->spacetype==SPACE_VIEW3D)
1538         {
1539                 /* initgrabz() defines a factor for perspective depth correction, used in window_to_3d_delta() */
1540                 if(t->flag & (T_EDIT|T_POSE)) {
1541                         Object *ob= t->obedit?t->obedit:t->poseobj;
1542                         float vec[3];
1543                         
1544                         VECCOPY(vec, t->center);
1545                         mul_m4_v3(ob->obmat, vec);
1546                         initgrabz(t->ar->regiondata, vec[0], vec[1], vec[2]);
1547                 }
1548                 else {
1549                         initgrabz(t->ar->regiondata, t->center[0], t->center[1], t->center[2]);
1550                 }
1551         }
1552 }
1553
1554 void calculatePropRatio(TransInfo *t)
1555 {
1556         TransData *td = t->data;
1557         int i;
1558         float dist;
1559         short connected = t->flag & T_PROP_CONNECTED;
1560
1561         if (t->flag & T_PROP_EDIT) {
1562                 for(i = 0 ; i < t->total; i++, td++) {
1563                         if (td->flag & TD_SELECTED) {
1564                                 td->factor = 1.0f;
1565                         }
1566                         else if (t->flag & T_MIRROR && td->loc[0] * t->mirror < -0.00001f)
1567                         {
1568                                 td->flag |= TD_SKIP;
1569                                 td->factor = 0.0f;
1570                                 restoreElement(td);
1571                         }
1572                         else if ((connected &&
1573                                                 (td->flag & TD_NOTCONNECTED || td->dist > t->prop_size))
1574                                 ||
1575                                         (connected == 0 &&
1576                                                 td->rdist > t->prop_size)) {
1577                                 /*
1578                                    The elements are sorted according to their dist member in the array,
1579                                    that means we can stop when it finds one element outside of the propsize.
1580                                 */
1581                                 td->flag |= TD_NOACTION;
1582                                 td->factor = 0.0f;
1583                                 restoreElement(td);
1584                         }
1585                         else {
1586                                 /* Use rdist for falloff calculations, it is the real distance */
1587                                 td->flag &= ~TD_NOACTION;
1588                                 
1589                                 if (connected)
1590                                         dist= (t->prop_size-td->dist)/t->prop_size;
1591                                 else
1592                                         dist= (t->prop_size-td->rdist)/t->prop_size;
1593
1594                                 /*
1595                                  * Clamp to positive numbers.
1596                                  * Certain corner cases with connectivity and individual centers
1597                                  * can give values of rdist larger than propsize.
1598                                  */
1599                                 if (dist < 0.0f)
1600                                         dist = 0.0f;
1601                                 
1602                                 switch(t->prop_mode) {
1603                                 case PROP_SHARP:
1604                                         td->factor= dist*dist;
1605                                         break;
1606                                 case PROP_SMOOTH:
1607                                         td->factor= 3.0f*dist*dist - 2.0f*dist*dist*dist;
1608                                         break;
1609                                 case PROP_ROOT:
1610                                         td->factor = (float)sqrt(dist);
1611                                         break;
1612                                 case PROP_LIN:
1613                                         td->factor = dist;
1614                                         break;
1615                                 case PROP_CONST:
1616                                         td->factor = 1.0f;
1617                                         break;
1618                                 case PROP_SPHERE:
1619                                         td->factor = (float)sqrt(2*dist - dist * dist);
1620                                         break;
1621                                 case PROP_RANDOM:
1622                                         BLI_srand( BLI_rand() ); /* random seed */
1623                                         td->factor = BLI_frand()*dist;
1624                                         break;
1625                                 default:
1626                                         td->factor = 1;
1627                                 }
1628                         }
1629                 }
1630                 switch(t->prop_mode) {
1631                 case PROP_SHARP:
1632                         strcpy(t->proptext, "(Sharp)");
1633                         break;
1634                 case PROP_SMOOTH:
1635                         strcpy(t->proptext, "(Smooth)");
1636                         break;
1637                 case PROP_ROOT:
1638                         strcpy(t->proptext, "(Root)");
1639                         break;
1640                 case PROP_LIN:
1641                         strcpy(t->proptext, "(Linear)");
1642                         break;
1643                 case PROP_CONST:
1644                         strcpy(t->proptext, "(Constant)");
1645                         break;
1646                 case PROP_SPHERE:
1647                         strcpy(t->proptext, "(Sphere)");
1648                         break;
1649                 case PROP_RANDOM:
1650                         strcpy(t->proptext, "(Random)");
1651                         break;
1652                 default:
1653                         strcpy(t->proptext, "");
1654                 }
1655         }
1656         else {
1657                 for(i = 0 ; i < t->total; i++, td++) {
1658                         td->factor = 1.0;
1659                 }
1660                 strcpy(t->proptext, "");
1661         }
1662 }