svn merge ^/trunk/blender -r47003:47047
[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 (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 /* 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         else {
1132                 if (ar) {
1133                         // XXX for now, get View2D  from the active region
1134                         t->view = &ar->v2d;
1135                         // XXX for now, the center point is the midpoint of the data
1136                 }
1137                 else {
1138                         t->view= NULL;
1139                 }
1140                 t->around = V3D_CENTER;
1141         }
1142         
1143         if (op && RNA_struct_property_is_set(op->ptr, "release_confirm")) {
1144                 if (RNA_boolean_get(op->ptr, "release_confirm")) {
1145                         t->flag |= T_RELEASE_CONFIRM;
1146                 }
1147         }
1148         else {
1149                 if (U.flag & USER_RELEASECONFIRM) {
1150                         t->flag |= T_RELEASE_CONFIRM;
1151                 }
1152         }
1153
1154         if (op && (RNA_struct_find_property(op->ptr, "mirror") &&
1155                    RNA_struct_property_is_set(op->ptr, "mirror")))
1156         {
1157                 if (RNA_boolean_get(op->ptr, "mirror")) {
1158                         t->flag |= T_MIRROR;
1159                         t->mirror = 1;
1160                 }
1161         }
1162         // Need stuff to take it from edit mesh or whatnot here
1163         else if (t->spacetype == SPACE_VIEW3D) {
1164                 if (t->obedit && t->obedit->type == OB_MESH && (((Mesh *)t->obedit->data)->editflag & ME_EDIT_MIRROR_X)) {
1165                         t->flag |= T_MIRROR;
1166                         t->mirror = 1;
1167                 }
1168         }
1169         
1170         /* setting PET flag only if property exist in operator. Otherwise, assume it's not supported */
1171         if (op && RNA_struct_find_property(op->ptr, "proportional")) {
1172                 if (RNA_struct_property_is_set(op->ptr, "proportional")) {
1173                         switch (RNA_enum_get(op->ptr, "proportional")) {
1174                                 case PROP_EDIT_CONNECTED:
1175                                         t->flag |= T_PROP_CONNECTED;
1176                                 case PROP_EDIT_ON:
1177                                         t->flag |= T_PROP_EDIT;
1178                                         break;
1179                         }
1180                 }
1181                 else {
1182                         /* use settings from scene only if modal */
1183                         if (t->flag & T_MODAL) {
1184                                 if ((t->options & CTX_NO_PET) == 0) {
1185                                         if (t->obedit && ts->proportional != PROP_EDIT_OFF) {
1186                                                 t->flag |= T_PROP_EDIT;
1187
1188                                                 if (ts->proportional == PROP_EDIT_CONNECTED) {
1189                                                         t->flag |= T_PROP_CONNECTED;
1190                                                 }
1191                                         }
1192                                         else if (t->obedit == NULL && ts->proportional_objects) {
1193                                                 t->flag |= T_PROP_EDIT;
1194                                         }
1195                                 }
1196                         }
1197                 }
1198                 
1199                 if (op && (RNA_struct_find_property(op->ptr, "proportional_size") &&
1200                            RNA_struct_property_is_set(op->ptr, "proportional_size")))
1201                 {
1202                         t->prop_size = RNA_float_get(op->ptr, "proportional_size");
1203                 }
1204                 else {
1205                         t->prop_size = ts->proportional_size;
1206                 }
1207                 
1208                 
1209                 /* TRANSFORM_FIX_ME rna restrictions */
1210                 if (t->prop_size <= 0.00001f) {
1211                         printf("Proportional size (%f) under 0.00001, reseting to 1!\n", t->prop_size);
1212                         t->prop_size = 1.0f;
1213                 }
1214                 
1215                 if (op && (RNA_struct_find_property(op->ptr, "proportional_edit_falloff") &&
1216                            RNA_struct_property_is_set(op->ptr, "proportional_edit_falloff")))
1217                 {
1218                         t->prop_mode = RNA_enum_get(op->ptr, "proportional_edit_falloff");
1219                 }
1220                 else {
1221                         t->prop_mode = ts->prop_mode;
1222                 }
1223         }
1224         else { /* add not pet option to context when not available */
1225                 t->options |= CTX_NO_PET;
1226         }
1227         
1228         // Mirror is not supported with PET, turn it off.
1229         if (t->flag & T_PROP_EDIT) {
1230                 t->flag &= ~T_MIRROR;
1231         }
1232
1233         setTransformViewMatrices(t);
1234         initNumInput(&t->num);
1235         
1236         return 1;
1237 }
1238
1239 /* Here I would suggest only TransInfo related issues, like free data & reset vars. Not redraws */
1240 void postTrans(bContext *C, TransInfo *t)
1241 {
1242         TransData *td;
1243         
1244         if (t->draw_handle_view)
1245                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_view);
1246         if (t->draw_handle_apply)
1247                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_apply);
1248         if (t->draw_handle_pixel)
1249                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_pixel);
1250         if (t->draw_handle_cursor)
1251                 WM_paint_cursor_end(CTX_wm_manager(C), t->draw_handle_cursor);
1252
1253         if (t->customFree) {
1254                 /* Can take over freeing t->data and data2d etc... */
1255                 t->customFree(t);
1256         }
1257         else if ((t->customData != NULL) && (t->flag & T_FREE_CUSTOMDATA)) {
1258                 MEM_freeN(t->customData);
1259         }
1260
1261         /* postTrans can be called when nothing is selected, so data is NULL already */
1262         if (t->data) {
1263                 int a;
1264                 
1265                 /* free data malloced per trans-data */
1266                 for (a=0, td= t->data; a<t->total; a++, td++) {
1267                         if (td->flag & TD_BEZTRIPLE) 
1268                                 MEM_freeN(td->hdata);
1269                 }
1270                 MEM_freeN(t->data);
1271         }
1272         
1273         BLI_freelistN(&t->tsnap.points);
1274
1275         if (t->ext) MEM_freeN(t->ext);
1276         if (t->data2d) {
1277                 MEM_freeN(t->data2d);
1278                 t->data2d= NULL;
1279         }
1280         
1281         if (t->spacetype==SPACE_IMAGE) {
1282                 SpaceImage *sima= t->sa->spacedata.first;
1283                 if (sima->flag & SI_LIVE_UNWRAP)
1284                         ED_uvedit_live_unwrap_end(t->state == TRANS_CANCEL);
1285         }
1286         else if (t->spacetype==SPACE_VIEW3D) {
1287                 View3D *v3d = t->sa->spacedata.first;
1288                 /* restore manipulator */
1289                 if (t->flag & T_MODAL) {
1290                         v3d->twtype = t->twtype;
1291                 }
1292         }
1293         
1294         if (t->mouse.data) {
1295                 MEM_freeN(t->mouse.data);
1296         }
1297 }
1298
1299 void applyTransObjects(TransInfo *t)
1300 {
1301         TransData *td;
1302         
1303         for (td = t->data; td < t->data + t->total; td++) {
1304                 copy_v3_v3(td->iloc, td->loc);
1305                 if (td->ext->rot) {
1306                         copy_v3_v3(td->ext->irot, td->ext->rot);
1307                 }
1308                 if (td->ext->size) {
1309                         copy_v3_v3(td->ext->isize, td->ext->size);
1310                 }
1311         }
1312         recalcData(t);
1313 }
1314
1315 static void restoreElement(TransData *td)
1316 {
1317         /* TransData for crease has no loc */
1318         if (td->loc) {
1319                 copy_v3_v3(td->loc, td->iloc);
1320         }
1321         if (td->val) {
1322                 *td->val = td->ival;
1323         }
1324
1325         if (td->ext && (td->flag&TD_NO_EXT)==0) {
1326                 if (td->ext->rot) {
1327                         copy_v3_v3(td->ext->rot, td->ext->irot);
1328                 }
1329                 if (td->ext->rotAngle) {
1330                         *td->ext->rotAngle= td->ext->irotAngle;
1331                 }
1332                 if (td->ext->rotAxis) {
1333                         copy_v3_v3(td->ext->rotAxis, td->ext->irotAxis);
1334                 }
1335                 /* XXX, drotAngle & drotAxis not used yet */
1336                 if (td->ext->size) {
1337                         copy_v3_v3(td->ext->size, td->ext->isize);
1338                 }
1339                 if (td->ext->quat) {
1340                         copy_qt_qt(td->ext->quat, td->ext->iquat);
1341                 }
1342         }
1343         
1344         if (td->flag & TD_BEZTRIPLE) {
1345                 *(td->hdata->h1) = td->hdata->ih1;
1346                 *(td->hdata->h2) = td->hdata->ih2;
1347         }
1348 }
1349
1350 void restoreTransObjects(TransInfo *t)
1351 {
1352         TransData *td;
1353         TransData2D *td2d;
1354
1355         for (td = t->data; td < t->data + t->total; td++) {
1356                 restoreElement(td);
1357         }
1358         
1359         for (td2d=t->data2d; t->data2d && td2d < t->data2d + t->total; td2d++) {
1360                 if (td2d->h1) {
1361                         td2d->h1[0] = td2d->ih1[0];
1362                         td2d->h1[1] = td2d->ih1[1];
1363                 }
1364                 if (td2d->h2) {
1365                         td2d->h2[0] = td2d->ih2[0];
1366                         td2d->h2[1] = td2d->ih2[1];
1367                 }
1368         }
1369
1370         unit_m3(t->mat);
1371         
1372         recalcData(t);
1373 }
1374
1375 void calculateCenter2D(TransInfo *t)
1376 {
1377         if (t->flag & (T_EDIT|T_POSE)) {
1378                 Object *ob= t->obedit?t->obedit:t->poseobj;
1379                 float vec[3];
1380                 
1381                 copy_v3_v3(vec, t->center);
1382                 mul_m4_v3(ob->obmat, vec);
1383                 projectIntView(t, vec, t->center2d);
1384         }
1385         else {
1386                 projectIntView(t, t->center, t->center2d);
1387         }
1388 }
1389
1390 void calculateCenterCursor(TransInfo *t)
1391 {
1392         float *cursor;
1393         
1394         cursor = give_cursor(t->scene, t->view);
1395         copy_v3_v3(t->center, cursor);
1396         
1397         /* If edit or pose mode, move cursor in local space */
1398         if (t->flag & (T_EDIT|T_POSE)) {
1399                 Object *ob = t->obedit?t->obedit:t->poseobj;
1400                 float mat[3][3], imat[3][3];
1401                 
1402                 sub_v3_v3v3(t->center, t->center, ob->obmat[3]);
1403                 copy_m3_m4(mat, ob->obmat);
1404                 invert_m3_m3(imat, mat);
1405                 mul_m3_v3(imat, t->center);
1406         }
1407         
1408         calculateCenter2D(t);
1409 }
1410
1411 void calculateCenterCursor2D(TransInfo *t)
1412 {
1413         float aspx=1.0, aspy=1.0;
1414         float *cursor= NULL;
1415         
1416         if (t->spacetype==SPACE_IMAGE) {
1417                 SpaceImage *sima= (SpaceImage *)t->sa->spacedata.first;
1418                 /* only space supported right now but may change */
1419                 ED_space_image_uv_aspect(sima, &aspx, &aspy);
1420                 cursor = sima->cursor;
1421         }
1422         
1423         if (cursor) {
1424                 t->center[0] = cursor[0] * aspx;
1425                 t->center[1] = cursor[1] * aspy;
1426         }
1427         
1428         calculateCenter2D(t);
1429 }
1430
1431 static void calculateCenterCursorGraph2D(TransInfo *t)
1432 {
1433         SpaceIpo *sipo= (SpaceIpo *)t->sa->spacedata.first;
1434         Scene *scene= t->scene;
1435         
1436         /* cursor is combination of current frame, and graph-editor cursor value */
1437         t->center[0]= (float)(scene->r.cfra);
1438         t->center[1]= sipo->cursorVal;
1439         
1440         calculateCenter2D(t);
1441 }
1442
1443 void calculateCenterMedian(TransInfo *t)
1444 {
1445         float partial[3] = {0.0f, 0.0f, 0.0f};
1446         int total = 0;
1447         int i;
1448         
1449         for (i = 0; i < t->total; i++) {
1450                 if (t->data[i].flag & TD_SELECTED) {
1451                         if (!(t->data[i].flag & TD_NOCENTER)) {
1452                                 add_v3_v3(partial, t->data[i].center);
1453                                 total++;
1454                         }
1455                 }
1456                 else {
1457                         /*
1458                          * All the selected elements are at the head of the array
1459                          * which means we can stop when it finds unselected data
1460                          */
1461                         break;
1462                 }
1463         }
1464         if (i)
1465                 mul_v3_fl(partial, 1.0f / total);
1466         copy_v3_v3(t->center, partial);
1467         
1468         calculateCenter2D(t);
1469 }
1470
1471 void calculateCenterBound(TransInfo *t)
1472 {
1473         float max[3];
1474         float min[3];
1475         int i;
1476         for (i = 0; i < t->total; i++) {
1477                 if (i) {
1478                         if (t->data[i].flag & TD_SELECTED) {
1479                                 if (!(t->data[i].flag & TD_NOCENTER))
1480                                         minmax_v3v3_v3(min, max, t->data[i].center);
1481                         }
1482                         else {
1483                                 /*
1484                                  * All the selected elements are at the head of the array
1485                                  * which means we can stop when it finds unselected data
1486                                  */
1487                                 break;
1488                         }
1489                 }
1490                 else {
1491                         copy_v3_v3(max, t->data[i].center);
1492                         copy_v3_v3(min, t->data[i].center);
1493                 }
1494         }
1495         add_v3_v3v3(t->center, min, max);
1496         mul_v3_fl(t->center, 0.5);
1497         
1498         calculateCenter2D(t);
1499 }
1500
1501 void calculateCenter(TransInfo *t)
1502 {
1503         switch (t->around) {
1504         case V3D_CENTER:
1505                 calculateCenterBound(t);
1506                 break;
1507         case V3D_CENTROID:
1508                 calculateCenterMedian(t);
1509                 break;
1510         case V3D_CURSOR:
1511                 if (t->spacetype==SPACE_IMAGE)
1512                         calculateCenterCursor2D(t);
1513                 else if (t->spacetype==SPACE_IPO)
1514                         calculateCenterCursorGraph2D(t);
1515                 else
1516                         calculateCenterCursor(t);
1517                 break;
1518         case V3D_LOCAL:
1519                 /* Individual element center uses median center for helpline and such */
1520                 calculateCenterMedian(t);
1521                 break;
1522         case V3D_ACTIVE:
1523                 {
1524                 /* set median, and if if if... do object center */
1525                 
1526                 /* EDIT MODE ACTIVE EDITMODE ELEMENT */
1527
1528                 if (t->obedit) {
1529                         if (t->obedit && t->obedit->type == OB_MESH) {
1530                                 BMEditSelection ese;
1531                                 BMEditMesh *em = BMEdit_FromObject(t->obedit);
1532
1533                                 if (BM_select_history_active_get(em->bm, &ese)) {
1534                                         BM_editselection_center(&ese, t->center);
1535                                         calculateCenter2D(t);
1536                                         break;
1537                                 }
1538                         }
1539                         else if (ELEM(t->obedit->type, OB_CURVE, OB_SURF)) {
1540                                 float center[3];
1541                                 Curve *cu= (Curve *)t->obedit->data;
1542
1543                                 if (ED_curve_actSelection(cu, center)) {
1544                                         copy_v3_v3(t->center, center);
1545                                         calculateCenter2D(t);
1546                                         break;
1547                                 }
1548                         }
1549                 } /* END EDIT MODE ACTIVE ELEMENT */
1550
1551                 calculateCenterMedian(t);
1552                 if ((t->flag & (T_EDIT|T_POSE))==0) {
1553                         Scene *scene = t->scene;
1554                         Object *ob= OBACT;
1555                         if (ob) {
1556                                 copy_v3_v3(t->center, ob->obmat[3]);
1557                                 projectIntView(t, t->center, t->center2d);
1558                         }
1559                 }
1560                 
1561                 }
1562         }
1563         
1564         /* setting constraint center */
1565         copy_v3_v3(t->con.center, t->center);
1566         if (t->flag & (T_EDIT|T_POSE)) {
1567                 Object *ob= t->obedit?t->obedit:t->poseobj;
1568                 mul_m4_v3(ob->obmat, t->con.center);
1569         }
1570         
1571         /* for panning from cameraview */
1572         if (t->flag & T_OBJECT) {
1573                 if (t->spacetype==SPACE_VIEW3D && t->ar && t->ar->regiontype == RGN_TYPE_WINDOW) {
1574                         View3D *v3d = t->view;
1575                         Scene *scene = t->scene;
1576                         RegionView3D *rv3d = t->ar->regiondata;
1577                         
1578                         if (v3d->camera == OBACT && rv3d->persp==RV3D_CAMOB) {
1579                                 float axis[3];
1580                                 /* persinv is nasty, use viewinv instead, always right */
1581                                 copy_v3_v3(axis, t->viewinv[2]);
1582                                 normalize_v3(axis);
1583                                 
1584                                 /* 6.0 = 6 grid units */
1585                                 axis[0]= t->center[0]- 6.0f*axis[0];
1586                                 axis[1]= t->center[1]- 6.0f*axis[1];
1587                                 axis[2]= t->center[2]- 6.0f*axis[2];
1588                                 
1589                                 projectIntView(t, axis, t->center2d);
1590                                 
1591                                 /* rotate only needs correct 2d center, grab needs initgrabz() value */
1592                                 if (t->mode==TFM_TRANSLATION) {
1593                                         copy_v3_v3(t->center, axis);
1594                                         copy_v3_v3(t->con.center, t->center);
1595                                 }
1596                         }
1597                 }
1598         }
1599         
1600         if (t->spacetype==SPACE_VIEW3D) {
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                                 td->flag |= TD_SKIP;
1630                                 td->factor = 0.0f;
1631                                 restoreElement(td);
1632                         }
1633                         else if ((connected && (td->flag & TD_NOTCONNECTED || td->dist > t->prop_size)) ||
1634                                  (connected == 0 && td->rdist > t->prop_size))
1635                         {
1636                                 /*
1637                                  * The elements are sorted according to their dist member in the array,
1638                                  * that means we can stop when it finds one element outside of the propsize.
1639                                  */
1640                                 td->flag |= TD_NOACTION;
1641                                 td->factor = 0.0f;
1642                                 restoreElement(td);
1643                         }
1644                         else {
1645                                 /* Use rdist for falloff calculations, it is the real distance */
1646                                 td->flag &= ~TD_NOACTION;
1647                                 
1648                                 if (connected)
1649                                         dist= (t->prop_size-td->dist)/t->prop_size;
1650                                 else
1651                                         dist= (t->prop_size-td->rdist)/t->prop_size;
1652
1653                                 /*
1654                                  * Clamp to positive numbers.
1655                                  * Certain corner cases with connectivity and individual centers
1656                                  * can give values of rdist larger than propsize.
1657                                  */
1658                                 if (dist < 0.0f)
1659                                         dist = 0.0f;
1660                                 
1661                                 switch (t->prop_mode) {
1662                                 case PROP_SHARP:
1663                                         td->factor= dist*dist;
1664                                         break;
1665                                 case PROP_SMOOTH:
1666                                         td->factor= 3.0f*dist*dist - 2.0f*dist*dist*dist;
1667                                         break;
1668                                 case PROP_ROOT:
1669                                         td->factor = (float)sqrt(dist);
1670                                         break;
1671                                 case PROP_LIN:
1672                                         td->factor = dist;
1673                                         break;
1674                                 case PROP_CONST:
1675                                         td->factor = 1.0f;
1676                                         break;
1677                                 case PROP_SPHERE:
1678                                         td->factor = (float)sqrt(2*dist - dist * dist);
1679                                         break;
1680                                 case PROP_RANDOM:
1681                                         BLI_srand(BLI_rand()); /* random seed */
1682                                         td->factor = BLI_frand()*dist;
1683                                         break;
1684                                 default:
1685                                         td->factor = 1;
1686                                 }
1687                         }
1688                 }
1689                 switch (t->prop_mode) {
1690                 case PROP_SHARP:
1691                         strcpy(t->proptext, "(Sharp)");
1692                         break;
1693                 case PROP_SMOOTH:
1694                         strcpy(t->proptext, "(Smooth)");
1695                         break;
1696                 case PROP_ROOT:
1697                         strcpy(t->proptext, "(Root)");
1698                         break;
1699                 case PROP_LIN:
1700                         strcpy(t->proptext, "(Linear)");
1701                         break;
1702                 case PROP_CONST:
1703                         strcpy(t->proptext, "(Constant)");
1704                         break;
1705                 case PROP_SPHERE:
1706                         strcpy(t->proptext, "(Sphere)");
1707                         break;
1708                 case PROP_RANDOM:
1709                         strcpy(t->proptext, "(Random)");
1710                         break;
1711                 default:
1712                         t->proptext[0]= '\0';
1713                 }
1714         }
1715         else {
1716                 for (i = 0 ; i < t->total; i++, td++) {
1717                         td->factor = 1.0;
1718                 }
1719                 t->proptext[0]= '\0';
1720         }
1721 }