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