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