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