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