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