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