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