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