Merge branch 'blender2.7'
[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 #include <string.h>
33 #include <math.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "BLI_sys_types.h" /* for intptr_t support */
38
39 #include "DNA_anim_types.h"
40 #include "DNA_armature_types.h"
41 #include "DNA_brush_types.h"
42 #include "DNA_gpencil_types.h"
43 #include "DNA_lattice_types.h"
44 #include "DNA_screen_types.h"
45 #include "DNA_sequence_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_object_types.h"
49 #include "DNA_mesh_types.h"
50 #include "DNA_view3d_types.h"
51 #include "DNA_modifier_types.h"
52 #include "DNA_movieclip_types.h"
53 #include "DNA_mask_types.h"
54 #include "DNA_meta_types.h"
55
56 #include "BLI_math.h"
57 #include "BLI_blenlib.h"
58 #include "BLI_rand.h"
59 #include "BLI_utildefines.h"
60
61 #include "PIL_time.h"
62
63 #include "BLT_translation.h"
64
65 #include "RNA_access.h"
66
67 #include "GPU_immediate.h"
68 #include "GPU_matrix.h"
69
70 #include "BIK_api.h"
71
72 #include "BKE_action.h"
73 #include "BKE_animsys.h"
74 #include "BKE_armature.h"
75 #include "BKE_context.h"
76 #include "BKE_curve.h"
77 #include "BKE_editmesh.h"
78 #include "BKE_fcurve.h"
79 #include "BKE_gpencil.h"
80 #include "BKE_lattice.h"
81 #include "BKE_layer.h"
82 #include "BKE_library.h"
83 #include "BKE_mask.h"
84 #include "BKE_nla.h"
85 #include "BKE_paint.h"
86 #include "BKE_scene.h"
87 #include "BKE_sequencer.h"
88 #include "BKE_tracking.h"
89 #include "BKE_workspace.h"
90
91 #include "DEG_depsgraph.h"
92
93 #include "ED_anim_api.h"
94 #include "ED_armature.h"
95 #include "ED_image.h"
96 #include "ED_keyframing.h"
97 #include "ED_markers.h"
98 #include "ED_mesh.h"
99 #include "ED_object.h"
100 #include "ED_particle.h"
101 #include "ED_screen_types.h"
102 #include "ED_space_api.h"
103 #include "ED_uvedit.h"
104 #include "ED_view3d.h"
105 #include "ED_curve.h" /* for curve_editnurbs */
106 #include "ED_clip.h"
107 #include "ED_screen.h"
108 #include "ED_gpencil.h"
109
110 #include "WM_types.h"
111 #include "WM_api.h"
112
113 #include "RE_engine.h"
114
115 #include "UI_resources.h"
116 #include "UI_view2d.h"
117
118 #include "transform.h"
119
120 /* ************************** Functions *************************** */
121
122 void getViewVector(const TransInfo *t, const float coord[3], float vec[3])
123 {
124         if (t->persp != RV3D_ORTHO) {
125                 sub_v3_v3v3(vec, coord, t->viewinv[3]);
126         }
127         else {
128                 copy_v3_v3(vec, t->viewinv[2]);
129         }
130         normalize_v3(vec);
131 }
132
133 /* ************************** GENERICS **************************** */
134
135
136 static void clipMirrorModifier(TransInfo *t)
137 {
138         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
139                 Object *ob = tc->obedit;
140                 ModifierData *md = ob->modifiers.first;
141                 float tolerance[3] = {0.0f, 0.0f, 0.0f};
142                 int axis = 0;
143
144                 for (; md; md = md->next) {
145                         if ((md->type == eModifierType_Mirror) && (md->mode & eModifierMode_Realtime)) {
146                                 MirrorModifierData *mmd = (MirrorModifierData *) md;
147
148                                 if (mmd->flag & MOD_MIR_CLIPPING) {
149                                         axis = 0;
150                                         if (mmd->flag & MOD_MIR_AXIS_X) {
151                                                 axis |= 1;
152                                                 tolerance[0] = mmd->tolerance;
153                                         }
154                                         if (mmd->flag & MOD_MIR_AXIS_Y) {
155                                                 axis |= 2;
156                                                 tolerance[1] = mmd->tolerance;
157                                         }
158                                         if (mmd->flag & MOD_MIR_AXIS_Z) {
159                                                 axis |= 4;
160                                                 tolerance[2] = mmd->tolerance;
161                                         }
162                                         if (axis) {
163                                                 float mtx[4][4], imtx[4][4];
164                                                 int i;
165
166                                                 if (mmd->mirror_ob) {
167                                                         float obinv[4][4];
168
169                                                         invert_m4_m4(obinv, mmd->mirror_ob->obmat);
170                                                         mul_m4_m4m4(mtx, obinv, ob->obmat);
171                                                         invert_m4_m4(imtx, mtx);
172                                                 }
173
174                                                 TransData *td = tc->data;
175                                                 for (i = 0; i < tc->data_len; i++, td++) {
176                                                         int clip;
177                                                         float loc[3], iloc[3];
178
179                                                         if (td->flag & TD_NOACTION)
180                                                                 break;
181                                                         if (td->loc == NULL)
182                                                                 break;
183
184                                                         if (td->flag & TD_SKIP)
185                                                                 continue;
186
187                                                         copy_v3_v3(loc,  td->loc);
188                                                         copy_v3_v3(iloc, td->iloc);
189
190                                                         if (mmd->mirror_ob) {
191                                                                 mul_m4_v3(mtx, loc);
192                                                                 mul_m4_v3(mtx, iloc);
193                                                         }
194
195                                                         clip = 0;
196                                                         if (axis & 1) {
197                                                                 if (fabsf(iloc[0]) <= tolerance[0] ||
198                                                                     loc[0] * iloc[0] < 0.0f)
199                                                                 {
200                                                                         loc[0] = 0.0f;
201                                                                         clip = 1;
202                                                                 }
203                                                         }
204
205                                                         if (axis & 2) {
206                                                                 if (fabsf(iloc[1]) <= tolerance[1] ||
207                                                                     loc[1] * iloc[1] < 0.0f)
208                                                                 {
209                                                                         loc[1] = 0.0f;
210                                                                         clip = 1;
211                                                                 }
212                                                         }
213                                                         if (axis & 4) {
214                                                                 if (fabsf(iloc[2]) <= tolerance[2] ||
215                                                                     loc[2] * iloc[2] < 0.0f)
216                                                                 {
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
236 /* assumes obedit set to mesh object */
237 static void editbmesh_apply_to_mirror(TransInfo *t)
238 {
239         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
240                 if (tc->mirror.axis_flag) {
241                         TransData *td = tc->data;
242                         BMVert *eve;
243                         int i;
244
245                         for (i = 0; i < tc->data_len; i++, td++) {
246                                 if (td->flag & TD_NOACTION)
247                                         break;
248                                 if (td->loc == NULL)
249                                         break;
250                                 if (td->flag & TD_SKIP)
251                                         continue;
252
253                                 eve = td->extra;
254                                 if (eve) {
255                                         eve->co[0] = -td->loc[0];
256                                         eve->co[1] = td->loc[1];
257                                         eve->co[2] = td->loc[2];
258                                 }
259
260                                 if (td->flag & TD_MIRROR_EDGE) {
261                                         td->loc[0] = 0;
262                                 }
263                         }
264                 }
265         }
266 }
267
268 /* for the realtime animation recording feature, handle overlapping data */
269 static void animrecord_check_state(Scene *scene, ID *id, wmTimer *animtimer)
270 {
271         ScreenAnimData *sad = (animtimer) ? animtimer->customdata : NULL;
272
273         /* sanity checks */
274         if (ELEM(NULL, scene, id, sad))
275                 return;
276
277         /* check if we need a new strip if:
278          * - if animtimer is running
279          * - we're not only keying for available channels
280          * - the option to add new actions for each round is not enabled
281          */
282         if (IS_AUTOKEY_FLAG(scene, INSERTAVAIL) == 0 && (scene->toolsettings->autokey_flag & ANIMRECORD_FLAG_WITHNLA)) {
283                 /* if playback has just looped around, we need to add a new NLA track+strip to allow a clean pass to occur */
284                 if ((sad) && (sad->flag & ANIMPLAY_FLAG_JUMPED)) {
285                         AnimData *adt = BKE_animdata_from_id(id);
286                         const bool is_first = (adt) && (adt->nla_tracks.first == NULL);
287
288                         /* perform push-down manually with some differences
289                          * NOTE: BKE_nla_action_pushdown() sync warning...
290                          */
291                         if ((adt->action) && !(adt->flag & ADT_NLA_EDIT_ON)) {
292                                 float astart, aend;
293
294                                 /* only push down if action is more than 1-2 frames long */
295                                 calc_action_range(adt->action, &astart, &aend, 1);
296                                 if (aend > astart + 2.0f) {
297                                         NlaStrip *strip = BKE_nlastack_add_strip(adt, adt->action);
298
299                                         /* clear reference to action now that we've pushed it onto the stack */
300                                         id_us_min(&adt->action->id);
301                                         adt->action = NULL;
302
303                                         /* adjust blending + extend so that they will behave correctly */
304                                         strip->extendmode = NLASTRIP_EXTEND_NOTHING;
305                                         strip->flag &= ~(NLASTRIP_FLAG_AUTO_BLENDS | NLASTRIP_FLAG_SELECT | NLASTRIP_FLAG_ACTIVE);
306
307                                         /* copy current "action blending" settings from adt to the strip,
308                                          * as it was keyframed with these settings, so omitting them will
309                                          * change the effect  [T54766]
310                                          */
311                                         if (is_first == false) {
312                                                 strip->blendmode = adt->act_blendmode;
313                                                 strip->influence = adt->act_influence;
314
315                                                 if (adt->act_influence < 1.0f) {
316                                                         /* enable "user-controlled" influence (which will insert a default keyframe)
317                                                          * so that the influence doesn't get lost on the new update
318                                                          *
319                                                          * NOTE: An alternative way would have been to instead hack the influence
320                                                          * to not get always get reset to full strength if NLASTRIP_FLAG_USR_INFLUENCE
321                                                          * is disabled but auto-blending isn't being used. However, that approach
322                                                          * is a bit hacky/hard to discover, and may cause backwards compatibility issues,
323                                                          * so it's better to just do it this way.
324                                                          */
325                                                         strip->flag |= NLASTRIP_FLAG_USR_INFLUENCE;
326                                                         BKE_nlastrip_validate_fcurves(strip);
327                                                 }
328                                         }
329
330                                         /* also, adjust the AnimData's action extend mode to be on
331                                          * 'nothing' so that previous result still play
332                                          */
333                                         adt->act_extendmode = NLASTRIP_EXTEND_NOTHING;
334                                 }
335                         }
336                 }
337         }
338 }
339
340 static bool fcu_test_selected(FCurve *fcu)
341 {
342         BezTriple *bezt = fcu->bezt;
343         unsigned int i;
344
345         if (bezt == NULL) /* ignore baked */
346                 return 0;
347
348         for (i = 0; i < fcu->totvert; i++, bezt++) {
349                 if (BEZT_ISSEL_ANY(bezt)) return 1;
350         }
351
352         return 0;
353 }
354
355 /* helper for recalcData() - for Action Editor transforms */
356 static void recalcData_actedit(TransInfo *t)
357 {
358         ViewLayer *view_layer = t->view_layer;
359         SpaceAction *saction = (SpaceAction *)t->sa->spacedata.first;
360
361         bAnimContext ac = {NULL};
362         ListBase anim_data = {NULL, NULL};
363         bAnimListElem *ale;
364         int filter;
365
366         /* initialize relevant anim-context 'context' data from TransInfo data */
367         /* NOTE: sync this with the code in ANIM_animdata_get_context() */
368         ac.bmain = CTX_data_main(t->context);
369         ac.scene = t->scene;
370         ac.view_layer = t->view_layer;
371         ac.obact = OBACT(view_layer);
372         ac.sa = t->sa;
373         ac.ar = t->ar;
374         ac.sl = (t->sa) ? t->sa->spacedata.first : NULL;
375         ac.spacetype = (t->sa) ? t->sa->spacetype : 0;
376         ac.regiontype = (t->ar) ? t->ar->regiontype : 0;
377
378         ANIM_animdata_context_getdata(&ac);
379
380         /* perform flush */
381         if (ELEM(ac.datatype, ANIMCONT_GPENCIL, ANIMCONT_MASK)) {
382                 /* flush transform values back to actual coordinates */
383                 flushTransIntFrameActionData(t);
384         }
385
386         if (ac.datatype != ANIMCONT_MASK) {
387                 /* get animdata blocks visible in editor, assuming that these will be the ones where things changed */
388                 filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_ANIMDATA);
389                 ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
390
391                 /* just tag these animdata-blocks to recalc, assuming that some data there changed
392                  * BUT only do this if realtime updates are enabled
393                  */
394                 if ((saction->flag & SACTION_NOREALTIMEUPDATES) == 0) {
395                         for (ale = anim_data.first; ale; ale = ale->next) {
396                                 /* set refresh tags for objects using this animation */
397                                 ANIM_list_elem_update(CTX_data_main(t->context), t->scene, ale);
398                         }
399                 }
400
401                 /* now free temp channels */
402                 ANIM_animdata_freelist(&anim_data);
403         }
404 }
405 /* helper for recalcData() - for Graph Editor transforms */
406 static void recalcData_graphedit(TransInfo *t)
407 {
408         SpaceIpo *sipo = (SpaceIpo *)t->sa->spacedata.first;
409         ViewLayer *view_layer = t->view_layer;
410
411         ListBase anim_data = {NULL, NULL};
412         bAnimContext ac = {NULL};
413         int filter;
414
415         bAnimListElem *ale;
416         int dosort = 0;
417
418         /* initialize relevant anim-context 'context' data from TransInfo data */
419         /* NOTE: sync this with the code in ANIM_animdata_get_context() */
420         ac.bmain = CTX_data_main(t->context);
421         ac.scene = t->scene;
422         ac.view_layer = t->view_layer;
423         ac.obact = OBACT(view_layer);
424         ac.sa = t->sa;
425         ac.ar = t->ar;
426         ac.sl = (t->sa) ? t->sa->spacedata.first : NULL;
427         ac.spacetype = (t->sa) ? t->sa->spacetype : 0;
428         ac.regiontype = (t->ar) ? t->ar->regiontype : 0;
429
430         ANIM_animdata_context_getdata(&ac);
431
432         /* do the flush first */
433         flushTransGraphData(t);
434
435         /* get curves to check if a re-sort is needed */
436         filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_FOREDIT | ANIMFILTER_CURVE_VISIBLE);
437         ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
438
439         /* now test if there is a need to re-sort */
440         for (ale = anim_data.first; ale; ale = ale->next) {
441                 FCurve *fcu = (FCurve *)ale->key_data;
442
443                 /* ignore FC-Curves without any selected verts */
444                 if (!fcu_test_selected(fcu))
445                         continue;
446
447                 /* watch it: if the time is wrong: do not correct handles yet */
448                 if (test_time_fcurve(fcu))
449                         dosort++;
450                 else
451                         calchandles_fcurve(fcu);
452
453                 /* set refresh tags for objects using this animation,
454                  * BUT only if realtime updates are enabled
455                  */
456                 if ((sipo->flag & SIPO_NOREALTIMEUPDATES) == 0)
457                         ANIM_list_elem_update(CTX_data_main(t->context), t->scene, ale);
458         }
459
460         /* do resort and other updates? */
461         if (dosort) remake_graph_transdata(t, &anim_data);
462
463         /* now free temp channels */
464         ANIM_animdata_freelist(&anim_data);
465 }
466
467 /* helper for recalcData() - for NLA Editor transforms */
468 static void recalcData_nla(TransInfo *t)
469 {
470         SpaceNla *snla = (SpaceNla *)t->sa->spacedata.first;
471         Scene *scene = t->scene;
472         double secf = FPS;
473         int i;
474
475         TransDataContainer *tc = TRANS_DATA_CONTAINER_FIRST_SINGLE(t);
476         TransDataNla *tdn = tc->custom.type.data;
477
478         /* for each strip we've got, perform some additional validation of the values that got set before
479          * using RNA to set the value (which does some special operations when setting these values to make
480          * sure that everything works ok)
481          */
482         for (i = 0; i < tc->data_len; i++, tdn++) {
483                 NlaStrip *strip = tdn->strip;
484                 PointerRNA strip_ptr;
485                 short pExceeded, nExceeded, iter;
486                 int delta_y1, delta_y2;
487
488                 /* if this tdn has no handles, that means it is just a dummy that should be skipped */
489                 if (tdn->handle == 0)
490                         continue;
491
492                 /* set refresh tags for objects using this animation,
493                  * BUT only if realtime updates are enabled
494                  */
495                 if ((snla->flag & SNLA_NOREALTIMEUPDATES) == 0)
496                         ANIM_id_update(CTX_data_main(t->context), tdn->id);
497
498                 /* if canceling transform, just write the values without validating, then move on */
499                 if (t->state == TRANS_CANCEL) {
500                         /* clear the values by directly overwriting the originals, but also need to restore
501                          * endpoints of neighboring transition-strips
502                          */
503
504                         /* start */
505                         strip->start = tdn->h1[0];
506
507                         if ((strip->prev) && (strip->prev->type == NLASTRIP_TYPE_TRANSITION))
508                                 strip->prev->end = tdn->h1[0];
509
510                         /* end */
511                         strip->end = tdn->h2[0];
512
513                         if ((strip->next) && (strip->next->type == NLASTRIP_TYPE_TRANSITION))
514                                 strip->next->start = tdn->h2[0];
515
516                         /* flush transforms to child strips (since this should be a meta) */
517                         BKE_nlameta_flush_transforms(strip);
518
519                         /* restore to original track (if needed) */
520                         if (tdn->oldTrack != tdn->nlt) {
521                                 /* just append to end of list for now, since strips get sorted in special_aftertrans_update() */
522                                 BLI_remlink(&tdn->nlt->strips, strip);
523                                 BLI_addtail(&tdn->oldTrack->strips, strip);
524                         }
525
526                         continue;
527                 }
528
529                 /* firstly, check if the proposed transform locations would overlap with any neighboring strips
530                  * (barring transitions) which are absolute barriers since they are not being moved
531                  *
532                  * this is done as a iterative procedure (done 5 times max for now)
533                  */
534                 for (iter = 0; iter < 5; iter++) {
535                         pExceeded = ((strip->prev) && (strip->prev->type != NLASTRIP_TYPE_TRANSITION) && (tdn->h1[0] < strip->prev->end));
536                         nExceeded = ((strip->next) && (strip->next->type != NLASTRIP_TYPE_TRANSITION) && (tdn->h2[0] > strip->next->start));
537
538                         if ((pExceeded && nExceeded) || (iter == 4)) {
539                                 /* both endpoints exceeded (or iteration ping-pong'd meaning that we need a compromise)
540                                  * - simply crop strip to fit within the bounds of the strips bounding it
541                                  * - if there were no neighbors, clear the transforms (make it default to the strip's current values)
542                                  */
543                                 if (strip->prev && strip->next) {
544                                         tdn->h1[0] = strip->prev->end;
545                                         tdn->h2[0] = strip->next->start;
546                                 }
547                                 else {
548                                         tdn->h1[0] = strip->start;
549                                         tdn->h2[0] = strip->end;
550                                 }
551                         }
552                         else if (nExceeded) {
553                                 /* move backwards */
554                                 float offset = tdn->h2[0] - strip->next->start;
555
556                                 tdn->h1[0] -= offset;
557                                 tdn->h2[0] -= offset;
558                         }
559                         else if (pExceeded) {
560                                 /* more forwards */
561                                 float offset = strip->prev->end - tdn->h1[0];
562
563                                 tdn->h1[0] += offset;
564                                 tdn->h2[0] += offset;
565                         }
566                         else /* all is fine and well */
567                                 break;
568                 }
569
570                 /* handle auto-snapping
571                  * NOTE: only do this when transform is still running, or we can't restore
572                  */
573                 if (t->state != TRANS_CANCEL) {
574                         switch (snla->autosnap) {
575                                 case SACTSNAP_FRAME: /* snap to nearest frame */
576                                 case SACTSNAP_STEP: /* frame step - this is basically the same, since we don't have any remapping going on */
577                                 {
578                                         tdn->h1[0] = floorf(tdn->h1[0] + 0.5f);
579                                         tdn->h2[0] = floorf(tdn->h2[0] + 0.5f);
580                                         break;
581                                 }
582
583                                 case SACTSNAP_SECOND: /* snap to nearest second */
584                                 case SACTSNAP_TSTEP: /* second step - this is basically the same, since we don't have any remapping going on */
585                                 {
586                                         /* This case behaves differently from the rest, since lengths of strips
587                                          * may not be multiples of a second. If we just naively resize adjust
588                                          * the handles, things may not work correctly. Instead, we only snap
589                                          * the first handle, and move the other to fit.
590                                          *
591                                          * FIXME: we do run into problems here when user attempts to negatively
592                                          *        scale the strip, as it then just compresses down and refuses
593                                          *        to expand out the other end.
594                                          */
595                                         float h1_new = (float)(floor(((double)tdn->h1[0] / secf) + 0.5) * secf);
596                                         float delta  = h1_new - tdn->h1[0];
597
598                                         tdn->h1[0] = h1_new;
599                                         tdn->h2[0] += delta;
600                                         break;
601                                 }
602
603                                 case SACTSNAP_MARKER: /* snap to nearest marker */
604                                 {
605                                         tdn->h1[0] = (float)ED_markers_find_nearest_marker_time(&t->scene->markers, tdn->h1[0]);
606                                         tdn->h2[0] = (float)ED_markers_find_nearest_marker_time(&t->scene->markers, tdn->h2[0]);
607                                         break;
608                                 }
609                         }
610                 }
611
612                 /* Use RNA to write the values to ensure that constraints on these are obeyed
613                  * (e.g. for transition strips, the values are taken from the neighbors)
614                  *
615                  * NOTE: we write these twice to avoid truncation errors which can arise when
616                  * moving the strips a large distance using numeric input [#33852]
617                  */
618                 RNA_pointer_create(NULL, &RNA_NlaStrip, strip, &strip_ptr);
619
620                 RNA_float_set(&strip_ptr, "frame_start", tdn->h1[0]);
621                 RNA_float_set(&strip_ptr, "frame_end", tdn->h2[0]);
622
623                 RNA_float_set(&strip_ptr, "frame_start", tdn->h1[0]);
624                 RNA_float_set(&strip_ptr, "frame_end", tdn->h2[0]);
625
626                 /* flush transforms to child strips (since this should be a meta) */
627                 BKE_nlameta_flush_transforms(strip);
628
629
630                 /* now, check if we need to try and move track
631                  * - we need to calculate both, as only one may have been altered by transform if only 1 handle moved
632                  */
633                 delta_y1 = ((int)tdn->h1[1] / NLACHANNEL_STEP(snla) - tdn->trackIndex);
634                 delta_y2 = ((int)tdn->h2[1] / NLACHANNEL_STEP(snla) - tdn->trackIndex);
635
636                 if (delta_y1 || delta_y2) {
637                         NlaTrack *track;
638                         int delta = (delta_y2) ? delta_y2 : delta_y1;
639                         int n;
640
641                         /* move in the requested direction, checking at each layer if there's space for strip to pass through,
642                          * stopping on the last track available or that we're able to fit in
643                          */
644                         if (delta > 0) {
645                                 for (track = tdn->nlt->next, n = 0; (track) && (n < delta); track = track->next, n++) {
646                                         /* check if space in this track for the strip */
647                                         if (BKE_nlatrack_has_space(track, strip->start, strip->end)) {
648                                                 /* move strip to this track */
649                                                 BLI_remlink(&tdn->nlt->strips, strip);
650                                                 BKE_nlatrack_add_strip(track, strip);
651
652                                                 tdn->nlt = track;
653                                                 tdn->trackIndex++;
654                                         }
655                                         else /* can't move any further */
656                                                 break;
657                                 }
658                         }
659                         else {
660                                 /* make delta 'positive' before using it, since we now know to go backwards */
661                                 delta = -delta;
662
663                                 for (track = tdn->nlt->prev, n = 0; (track) && (n < delta); track = track->prev, n++) {
664                                         /* check if space in this track for the strip */
665                                         if (BKE_nlatrack_has_space(track, strip->start, strip->end)) {
666                                                 /* move strip to this track */
667                                                 BLI_remlink(&tdn->nlt->strips, strip);
668                                                 BKE_nlatrack_add_strip(track, strip);
669
670                                                 tdn->nlt = track;
671                                                 tdn->trackIndex--;
672                                         }
673                                         else /* can't move any further */
674                                                 break;
675                                 }
676                         }
677                 }
678         }
679 }
680
681 static void recalcData_mask_common(TransInfo *t)
682 {
683         Mask *mask = CTX_data_edit_mask(t->context);
684
685         flushTransMasking(t);
686
687         DEG_id_tag_update(&mask->id, 0);
688 }
689
690 /* helper for recalcData() - for Image Editor transforms */
691 static void recalcData_image(TransInfo *t)
692 {
693         if (t->options & CTX_MASK) {
694                 recalcData_mask_common(t);
695         }
696         else if (t->options & CTX_PAINT_CURVE) {
697                 flushTransPaintCurve(t);
698         }
699         else if ((t->flag & T_EDIT) && t->obedit_type == OB_MESH) {
700                 SpaceImage *sima = t->sa->spacedata.first;
701
702                 flushTransUVs(t);
703                 if (sima->flag & SI_LIVE_UNWRAP)
704                         ED_uvedit_live_unwrap_re_solve();
705
706                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
707                         if (tc->data_len) {
708                                 DEG_id_tag_update(tc->obedit->data, 0);
709                         }
710                 }
711         }
712 }
713
714 /* helper for recalcData() - for Movie Clip transforms */
715 static void recalcData_spaceclip(TransInfo *t)
716 {
717         SpaceClip *sc = t->sa->spacedata.first;
718
719         if (ED_space_clip_check_show_trackedit(sc)) {
720                 MovieClip *clip = ED_space_clip_get_clip(sc);
721                 ListBase *tracksbase = BKE_tracking_get_active_tracks(&clip->tracking);
722                 MovieTrackingTrack *track;
723                 int framenr = ED_space_clip_get_clip_frame_number(sc);
724
725                 flushTransTracking(t);
726
727                 track = tracksbase->first;
728                 while (track) {
729                         if (TRACK_VIEW_SELECTED(sc, track) && (track->flag & TRACK_LOCKED) == 0) {
730                                 MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
731
732                                 if (t->mode == TFM_TRANSLATION) {
733                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_PAT))
734                                                 BKE_tracking_marker_clamp(marker, CLAMP_PAT_POS);
735                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_SEARCH))
736                                                 BKE_tracking_marker_clamp(marker, CLAMP_SEARCH_POS);
737                                 }
738                                 else if (t->mode == TFM_RESIZE) {
739                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_PAT))
740                                                 BKE_tracking_marker_clamp(marker, CLAMP_PAT_DIM);
741                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_SEARCH))
742                                                 BKE_tracking_marker_clamp(marker, CLAMP_SEARCH_DIM);
743                                 }
744                                 else if (t->mode == TFM_ROTATION) {
745                                         if (TRACK_AREA_SELECTED(track, TRACK_AREA_PAT))
746                                                 BKE_tracking_marker_clamp(marker, CLAMP_PAT_POS);
747                                 }
748                         }
749
750                         track = track->next;
751                 }
752
753                 DEG_id_tag_update(&clip->id, 0);
754         }
755         else if (t->options & CTX_MASK) {
756                 recalcData_mask_common(t);
757         }
758 }
759
760 /* helper for recalcData() - for object transforms, typically in the 3D view */
761 static void recalcData_objects(TransInfo *t)
762 {
763         Base *base = t->view_layer->basact;
764
765         if (t->obedit_type != -1) {
766                 if (ELEM(t->obedit_type, OB_CURVE, OB_SURF)) {
767
768                         if (t->state != TRANS_CANCEL) {
769                                 clipMirrorModifier(t);
770                                 applyProject(t);
771                         }
772
773                         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
774                                 Curve *cu = tc->obedit->data;
775                                 ListBase *nurbs = BKE_curve_editNurbs_get(cu);
776                                 Nurb *nu = nurbs->first;
777
778                                 DEG_id_tag_update(tc->obedit->data, 0);  /* sets recalc flags */
779
780                                 if (t->state == TRANS_CANCEL) {
781                                         while (nu) {
782                                                 BKE_nurb_handles_calc(nu); /* Cant do testhandlesNurb here, it messes up the h1 and h2 flags */
783                                                 nu = nu->next;
784                                         }
785                                 }
786                                 else {
787                                         /* Normal updating */
788                                         while (nu) {
789                                                 BKE_nurb_test_2d(nu);
790                                                 BKE_nurb_handles_calc(nu);
791                                                 nu = nu->next;
792                                         }
793                                 }
794                         }
795                 }
796                 else if (t->obedit_type == OB_LATTICE) {
797
798                         if (t->state != TRANS_CANCEL) {
799                                 applyProject(t);
800                         }
801
802                         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
803                                 Lattice *la = tc->obedit->data;
804                                 DEG_id_tag_update(tc->obedit->data, 0);  /* sets recalc flags */
805                                 if (la->editlatt->latt->flag & LT_OUTSIDE) {
806                                         outside_lattice(la->editlatt->latt);
807                                 }
808                         }
809                 }
810                 else if (t->obedit_type == OB_MESH) {
811                         /* mirror modifier clipping? */
812                         if (t->state != TRANS_CANCEL) {
813                                 /* apply clipping after so we never project past the clip plane [#25423] */
814                                 applyProject(t);
815                                 clipMirrorModifier(t);
816                         }
817                         if ((t->flag & T_NO_MIRROR) == 0 &&
818                             (t->options & CTX_NO_MIRROR) == 0)
819                         {
820                                 editbmesh_apply_to_mirror(t);
821                         }
822
823                         if (t->mode == TFM_EDGE_SLIDE) {
824                                 projectEdgeSlideData(t, false);
825                         }
826                         else if (t->mode == TFM_VERT_SLIDE) {
827                                 projectVertSlideData(t, false);
828                         }
829
830                         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
831                                 DEG_id_tag_update(tc->obedit->data, 0);  /* sets recalc flags */
832                                 BMEditMesh *em = BKE_editmesh_from_object(tc->obedit);
833                                 EDBM_mesh_normals_update(em);
834                                 BKE_editmesh_tessface_calc(em);
835                         }
836                 }
837                 else if (t->obedit_type == OB_ARMATURE) { /* no recalc flag, does pose */
838
839                         if (t->state != TRANS_CANCEL) {
840                                 applyProject(t);
841                         }
842
843                         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
844                                 bArmature *arm = tc->obedit->data;
845                                 ListBase *edbo = arm->edbo;
846                                 EditBone *ebo, *ebo_parent;
847                                 TransData *td = tc->data;
848                                 int i;
849
850                                 /* Ensure all bones are correctly adjusted */
851                                 for (ebo = edbo->first; ebo; ebo = ebo->next) {
852                                         ebo_parent = (ebo->flag & BONE_CONNECTED) ? ebo->parent : NULL;
853
854                                         if (ebo_parent) {
855                                                 /* If this bone has a parent tip that has been moved */
856                                                 if (ebo_parent->flag & BONE_TIPSEL) {
857                                                         copy_v3_v3(ebo->head, ebo_parent->tail);
858                                                         if (t->mode == TFM_BONE_ENVELOPE) ebo->rad_head = ebo_parent->rad_tail;
859                                                 }
860                                                 /* If this bone has a parent tip that has NOT been moved */
861                                                 else {
862                                                         copy_v3_v3(ebo_parent->tail, ebo->head);
863                                                         if (t->mode == TFM_BONE_ENVELOPE) ebo_parent->rad_tail = ebo->rad_head;
864                                                 }
865                                         }
866
867                                         /* on extrude bones, oldlength==0.0f, so we scale radius of points */
868                                         ebo->length = len_v3v3(ebo->head, ebo->tail);
869                                         if (ebo->oldlength == 0.0f) {
870                                                 ebo->rad_head = 0.25f * ebo->length;
871                                                 ebo->rad_tail = 0.10f * ebo->length;
872                                                 ebo->dist = 0.25f * ebo->length;
873                                                 if (ebo->parent) {
874                                                         if (ebo->rad_head > ebo->parent->rad_tail)
875                                                                 ebo->rad_head = ebo->parent->rad_tail;
876                                                 }
877                                         }
878                                         else if (t->mode != TFM_BONE_ENVELOPE) {
879                                                 /* if bones change length, lets do that for the deform distance as well */
880                                                 ebo->dist *= ebo->length / ebo->oldlength;
881                                                 ebo->rad_head *= ebo->length / ebo->oldlength;
882                                                 ebo->rad_tail *= ebo->length / ebo->oldlength;
883                                                 ebo->oldlength = ebo->length;
884
885                                                 if (ebo_parent) {
886                                                         ebo_parent->rad_tail = ebo->rad_head;
887                                                 }
888                                         }
889                                 }
890
891                                 if (!ELEM(t->mode, TFM_BONE_ROLL, TFM_BONE_ENVELOPE, TFM_BONE_ENVELOPE_DIST, TFM_BONESIZE)) {
892                                         /* fix roll */
893                                         for (i = 0; i < tc->data_len; i++, td++) {
894                                                 if (td->extra) {
895                                                         float vec[3], up_axis[3];
896                                                         float qrot[4];
897                                                         float roll;
898
899                                                         ebo = td->extra;
900
901                                                         if (t->state == TRANS_CANCEL) {
902                                                                 /* restore roll */
903                                                                 ebo->roll = td->ival;
904                                                         }
905                                                         else {
906                                                                 copy_v3_v3(up_axis, td->axismtx[2]);
907
908                                                                 sub_v3_v3v3(vec, ebo->tail, ebo->head);
909                                                                 normalize_v3(vec);
910                                                                 rotation_between_vecs_to_quat(qrot, td->axismtx[1], vec);
911                                                                 mul_qt_v3(qrot, up_axis);
912
913                                                                 /* roll has a tendency to flip in certain orientations - [#34283], [#33974] */
914                                                                 roll = ED_armature_ebone_roll_to_vector(ebo, up_axis, false);
915                                                                 ebo->roll = angle_compat_rad(roll, td->ival);
916                                                         }
917                                                 }
918                                         }
919                                 }
920
921                                 if (arm->flag & ARM_MIRROR_EDIT) {
922                                         if (t->state != TRANS_CANCEL) {
923                                                 ED_armature_edit_transform_mirror_update(tc->obedit);
924                                         }
925                                         else {
926                                                 restoreBones(tc);
927                                         }
928                                 }
929                         }
930                 }
931                 else {
932                         if (t->state != TRANS_CANCEL) {
933                                 applyProject(t);
934                         }
935                         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
936                                 if (tc->data_len) {
937                                         DEG_id_tag_update(tc->obedit->data, 0);  /* sets recalc flags */
938                                 }
939                         }
940                 }
941
942         }
943         else if (t->flag & T_POSE) {
944                 GSet *motionpath_updates = BLI_gset_ptr_new("motionpath updates");
945
946                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
947                         Object *ob = tc->poseobj;
948                         bArmature *arm = ob->data;
949
950                         /* if animtimer is running, and the object already has animation data,
951                          * check if the auto-record feature means that we should record 'samples'
952                          * (i.e. uneditable animation values)
953                          *
954                          * context is needed for keying set poll() functions.
955                          */
956                         // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
957                         if ((t->animtimer) && (t->context) && IS_AUTOKEY_ON(t->scene)) {
958                                 int targetless_ik = (t->flag & T_AUTOIK); // XXX this currently doesn't work, since flags aren't set yet!
959
960                                 animrecord_check_state(t->scene, &ob->id, t->animtimer);
961                                 autokeyframe_pose(t->context, t->scene, ob, t->mode, targetless_ik);
962                         }
963
964                         if (motionpath_need_update_pose(t->scene, ob)) {
965                                 BLI_gset_insert(motionpath_updates, ob);
966                         }
967
968                         /* old optimize trick... this enforces to bypass the depgraph */
969                         if (!(arm->flag & ARM_DELAYDEFORM)) {
970                                 DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);  /* sets recalc flags */
971                                 /* transformation of pose may affect IK tree, make sure it is rebuilt */
972                                 BIK_clear_data(ob->pose);
973                         }
974                         else {
975                                 BKE_pose_where_is(t->depsgraph, t->scene, ob);
976                         }
977                 }
978
979                 /* Update motion paths once for all transformed bones in an object. */
980                 GSetIterator gs_iter;
981                 GSET_ITER (gs_iter, motionpath_updates) {
982                         Object *ob = BLI_gsetIterator_getKey(&gs_iter);
983                         ED_pose_recalculate_paths(t->context, t->scene, ob, true);
984                 }
985                 BLI_gset_free(motionpath_updates, NULL);
986         }
987         else if (base && (base->object->mode & OB_MODE_PARTICLE_EDIT) &&
988                  PE_get_current(t->scene, base->object))
989         {
990                 if (t->state != TRANS_CANCEL) {
991                         applyProject(t);
992                 }
993                 flushTransParticles(t);
994         }
995         else {
996                 bool motionpath_update = false;
997
998                 if (t->state != TRANS_CANCEL) {
999                         applyProject(t);
1000                 }
1001
1002                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1003                         TransData *td = tc->data;
1004
1005                         for (int i = 0; i < tc->data_len; i++, td++) {
1006                                 Object *ob = td->ob;
1007
1008                                 if (td->flag & TD_NOACTION)
1009                                         break;
1010
1011                                 if (td->flag & TD_SKIP)
1012                                         continue;
1013
1014                                 /* if animtimer is running, and the object already has animation data,
1015                                  * check if the auto-record feature means that we should record 'samples'
1016                                  * (i.e. uneditable animation values)
1017                                  */
1018                                 // TODO: autokeyframe calls need some setting to specify to add samples (FPoints) instead of keyframes?
1019                                 if ((t->animtimer) && IS_AUTOKEY_ON(t->scene)) {
1020                                         animrecord_check_state(t->scene, &ob->id, t->animtimer);
1021                                         autokeyframe_object(t->context, t->scene, t->view_layer, ob, t->mode);
1022                                 }
1023
1024                                 motionpath_update |= motionpath_need_update_object(t->scene, ob);
1025
1026                                 /* sets recalc flags fully, instead of flushing existing ones
1027                                  * otherwise proxies don't function correctly
1028                                  */
1029                                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM);
1030
1031                                 if (t->flag & T_TEXTURE)
1032                                         DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
1033                         }
1034                 }
1035
1036                 if (motionpath_update) {
1037                         /* Update motion paths once for all transformed objects. */
1038                         ED_objects_recalculate_paths(t->context, t->scene, true);
1039                 }
1040         }
1041 }
1042
1043 static void recalcData_cursor(TransInfo *t)
1044 {
1045         DEG_id_tag_update(&t->scene->id, ID_RECALC_COPY_ON_WRITE);
1046 }
1047
1048 /* helper for recalcData() - for sequencer transforms */
1049 static void recalcData_sequencer(TransInfo *t)
1050 {
1051         TransData *td;
1052         int a;
1053         Sequence *seq_prev = NULL;
1054
1055         TransDataContainer *tc = TRANS_DATA_CONTAINER_FIRST_SINGLE(t);
1056
1057         for (a = 0, td = tc->data; a < tc->data_len; a++, td++) {
1058                 TransDataSeq *tdsq = (TransDataSeq *) td->extra;
1059                 Sequence *seq = tdsq->seq;
1060
1061                 if (seq != seq_prev) {
1062                         if (BKE_sequence_tx_fullupdate_test(seq)) {
1063                                 /* A few effect strip types need a complete recache on transform. */
1064                                 BKE_sequence_invalidate_cache(t->scene, seq);
1065                         }
1066                         else {
1067                                 BKE_sequence_invalidate_dependent(t->scene, seq);
1068                         }
1069                 }
1070
1071                 seq_prev = seq;
1072         }
1073
1074         BKE_sequencer_preprocessed_cache_cleanup();
1075
1076         flushTransSeq(t);
1077 }
1078
1079 /* force recalculation of triangles during transformation */
1080 static void recalcData_gpencil_strokes(TransInfo *t)
1081 {
1082         TransDataContainer *tc = TRANS_DATA_CONTAINER_FIRST_SINGLE(t);
1083
1084         TransData *td = tc->data;
1085         for (int i = 0; i < tc->data_len; i++, td++) {
1086                 bGPDstroke *gps = td->extra;
1087                 if (gps != NULL) {
1088                         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
1089                 }
1090         }
1091 }
1092
1093 /* called for updating while transform acts, once per redraw */
1094 void recalcData(TransInfo *t)
1095 {
1096         /* if tests must match createTransData for correct updates */
1097         if (t->options & CTX_CURSOR) {
1098                 recalcData_cursor(t);
1099         }
1100         else if (t->options & CTX_TEXTURE) {
1101                 recalcData_objects(t);
1102         }
1103         else if (t->options & CTX_EDGE) {
1104                 recalcData_objects(t);
1105         }
1106         else if (t->options & CTX_PAINT_CURVE) {
1107                 flushTransPaintCurve(t);
1108         }
1109         else if (t->options & CTX_GPENCIL_STROKES) {
1110                 /* set recalc triangle cache flag */
1111                 recalcData_gpencil_strokes(t);
1112         }
1113         else if (t->spacetype == SPACE_IMAGE) {
1114                 recalcData_image(t);
1115         }
1116         else if (t->spacetype == SPACE_ACTION) {
1117                 recalcData_actedit(t);
1118         }
1119         else if (t->spacetype == SPACE_NLA) {
1120                 recalcData_nla(t);
1121         }
1122         else if (t->spacetype == SPACE_SEQ) {
1123                 recalcData_sequencer(t);
1124         }
1125         else if (t->spacetype == SPACE_IPO) {
1126                 recalcData_graphedit(t);
1127         }
1128         else if (t->spacetype == SPACE_NODE) {
1129                 flushTransNodes(t);
1130         }
1131         else if (t->spacetype == SPACE_CLIP) {
1132                 recalcData_spaceclip(t);
1133         }
1134         else {
1135                 recalcData_objects(t);
1136         }
1137 }
1138
1139 void drawLine(TransInfo *t, const float center[3], const float dir[3], char axis, short options)
1140 {
1141         float v1[3], v2[3], v3[3];
1142         unsigned char col[3], col2[3];
1143
1144         if (t->spacetype == SPACE_VIEW3D) {
1145                 View3D *v3d = t->view;
1146
1147                 GPU_matrix_push();
1148
1149                 copy_v3_v3(v3, dir);
1150                 mul_v3_fl(v3, v3d->far);
1151
1152                 sub_v3_v3v3(v2, center, v3);
1153                 add_v3_v3v3(v1, center, v3);
1154
1155                 if (options & DRAWLIGHT) {
1156                         col[0] = col[1] = col[2] = 220;
1157                 }
1158                 else {
1159                         UI_GetThemeColor3ubv(TH_GRID, col);
1160                 }
1161                 UI_make_axis_color(col, col2, axis);
1162
1163                 uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_F32, 3, GPU_FETCH_FLOAT);
1164
1165                 immBindBuiltinProgram(GPU_SHADER_3D_UNIFORM_COLOR);
1166                 immUniformColor3ubv(col2);
1167
1168                 immBegin(GPU_PRIM_LINES, 2);
1169                 immVertex3fv(pos, v1);
1170                 immVertex3fv(pos, v2);
1171                 immEnd();
1172
1173                 immUnbindProgram();
1174
1175                 GPU_matrix_pop();
1176         }
1177 }
1178
1179 /**
1180  * Free data before switching to another mode.
1181  */
1182 void resetTransModal(TransInfo *t)
1183 {
1184         freeTransCustomDataForMode(t);
1185 }
1186
1187 void resetTransRestrictions(TransInfo *t)
1188 {
1189         t->flag &= ~T_ALL_RESTRICTIONS;
1190 }
1191
1192 static int initTransInfo_edit_pet_to_flag(const int proportional)
1193 {
1194         switch (proportional) {
1195                 case PROP_EDIT_ON:
1196                         return T_PROP_EDIT;
1197                 case PROP_EDIT_CONNECTED:
1198                         return T_PROP_EDIT | T_PROP_CONNECTED;
1199                 case PROP_EDIT_PROJECTED:
1200                         return T_PROP_EDIT | T_PROP_PROJECTED;
1201                 default:
1202                         return 0;
1203         }
1204 }
1205
1206 void initTransDataContainers_FromObjectData(TransInfo *t, Object *obact, Object **objects, uint objects_len)
1207 {
1208         const eObjectMode object_mode = obact ? obact->mode : OB_MODE_OBJECT;
1209         const short object_type = obact ? obact->type : -1;
1210
1211         if ((object_mode & OB_MODE_EDIT) || (t->options & CTX_GPENCIL_STROKES) ||
1212             ((object_mode & OB_MODE_POSE) && (object_type == OB_ARMATURE)))
1213         {
1214                 if (t->data_container) {
1215                         MEM_freeN(t->data_container);
1216                 }
1217
1218                 bool free_objects = false;
1219                 if (objects == NULL) {
1220                         objects = BKE_view_layer_array_from_objects_in_mode(
1221                                 t->view_layer,
1222                                 (t->spacetype == SPACE_VIEW3D) ? t->view : NULL,
1223                                 &objects_len, {
1224                                     .object_mode = object_mode,
1225                                     .no_dup_data = true,
1226                                 });
1227                         free_objects = true;
1228                 }
1229
1230                 t->data_container = MEM_callocN(sizeof(*t->data_container) * objects_len, __func__);
1231                 t->data_container_len = objects_len;
1232
1233                 for (int i = 0; i < objects_len; i++) {
1234                         TransDataContainer *tc = &t->data_container[i];
1235                         /* TODO, multiple axes. */
1236                         tc->mirror.axis_flag = (
1237                                 ((t->flag & T_NO_MIRROR) == 0) &&
1238                                 ((t->options & CTX_NO_MIRROR) == 0) &&
1239                                 (((Mesh *)objects[i]->data)->editflag & ME_EDIT_MIRROR_X) != 0);
1240
1241                         if (object_mode & OB_MODE_EDIT) {
1242                                 tc->obedit = objects[i];
1243                                 /* Check needed for UV's */
1244                                 if ((t->flag & T_2D_EDIT) == 0) {
1245                                         tc->use_local_mat = true;
1246                                 }
1247                         }
1248                         else if (object_mode & OB_MODE_POSE) {
1249                                 tc->poseobj = objects[i];
1250                                 tc->use_local_mat = true;
1251                         }
1252                         else if (t->options & CTX_GPENCIL_STROKES) {
1253                                 tc->use_local_mat = true;
1254                         }
1255
1256                         if (tc->use_local_mat) {
1257                                 BLI_assert((t->flag & T_2D_EDIT) == 0);
1258                                 copy_m4_m4(tc->mat, objects[i]->obmat);
1259                                 copy_m3_m4(tc->mat3, tc->mat);
1260                                 invert_m4_m4(tc->imat, tc->mat);
1261                                 invert_m3_m3(tc->imat3, tc->mat3);
1262                                 normalize_m3_m3(tc->mat3_unit, tc->mat3);
1263                         }
1264                         /* Otherwise leave as zero. */
1265                 }
1266
1267                 if (free_objects) {
1268                         MEM_freeN(objects);
1269                 }
1270         }
1271 }
1272
1273 /**
1274  * Setup internal data, mouse, vectors
1275  *
1276  * \note \a op and \a event can be NULL
1277  *
1278  * \see #saveTransform does the reverse.
1279  */
1280 void initTransInfo(bContext *C, TransInfo *t, wmOperator *op, const wmEvent *event)
1281 {
1282         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1283         Scene *sce = CTX_data_scene(C);
1284         ViewLayer *view_layer = CTX_data_view_layer(C);
1285         const eObjectMode object_mode = OBACT(view_layer) ? OBACT(view_layer)->mode : OB_MODE_OBJECT;
1286         const short object_type = OBACT(view_layer) ? OBACT(view_layer)->type : -1;
1287         ToolSettings *ts = CTX_data_tool_settings(C);
1288         ARegion *ar = CTX_wm_region(C);
1289         ScrArea *sa = CTX_wm_area(C);
1290
1291         bGPdata *gpd = CTX_data_gpencil_data(C);
1292         PropertyRNA *prop;
1293
1294         t->depsgraph = depsgraph;
1295         t->scene = sce;
1296         t->view_layer = view_layer;
1297         t->sa = sa;
1298         t->ar = ar;
1299         t->settings = ts;
1300         t->reports = op ? op->reports : NULL;
1301
1302         t->helpline = HLP_NONE;
1303
1304         t->flag = 0;
1305
1306         t->obedit_type = ((object_mode == OB_MODE_EDIT) || (object_mode == OB_MODE_EDIT_GPENCIL)) ? object_type : -1;
1307
1308         /* Many kinds of transform only use a single handle. */
1309         if (t->data_container == NULL) {
1310                 t->data_container = MEM_callocN(sizeof(*t->data_container), __func__);
1311                 t->data_container_len = 1;
1312         }
1313
1314         t->redraw = TREDRAW_HARD;  /* redraw first time */
1315
1316         if (event) {
1317                 t->mouse.imval[0] = event->mval[0];
1318                 t->mouse.imval[1] = event->mval[1];
1319         }
1320         else {
1321                 t->mouse.imval[0] = 0;
1322                 t->mouse.imval[1] = 0;
1323         }
1324
1325         t->con.imval[0] = t->mouse.imval[0];
1326         t->con.imval[1] = t->mouse.imval[1];
1327
1328         t->mval[0] = t->mouse.imval[0];
1329         t->mval[1] = t->mouse.imval[1];
1330
1331         t->transform        = NULL;
1332         t->handleEvent      = NULL;
1333
1334         t->data_len_all = 0;
1335
1336         t->val = 0.0f;
1337
1338         zero_v3(t->vec);
1339         zero_v3(t->center_global);
1340
1341         unit_m3(t->mat);
1342
1343         /* if there's an event, we're modal */
1344         if (event) {
1345                 t->flag |= T_MODAL;
1346         }
1347
1348         /* Crease needs edge flag */
1349         if (ELEM(t->mode, TFM_CREASE, TFM_BWEIGHT)) {
1350                 t->options |= CTX_EDGE;
1351         }
1352
1353         t->remove_on_cancel = false;
1354
1355         if (op && (prop = RNA_struct_find_property(op->ptr, "remove_on_cancel")) && RNA_property_is_set(op->ptr, prop)) {
1356                 if (RNA_property_boolean_get(op->ptr, prop)) {
1357                         t->remove_on_cancel = true;
1358                 }
1359         }
1360
1361         /* GPencil editing context */
1362         if (GPENCIL_EDIT_MODE(gpd)) {
1363                 t->options |= CTX_GPENCIL_STROKES;
1364         }
1365
1366         /* Assign the space type, some exceptions for running in different mode */
1367         if (sa == NULL) {
1368                 /* background mode */
1369                 t->spacetype = SPACE_EMPTY;
1370         }
1371         else if ((ar == NULL) && (sa->spacetype == SPACE_VIEW3D)) {
1372                 /* running in the text editor */
1373                 t->spacetype = SPACE_EMPTY;
1374         }
1375         else {
1376                 /* normal operation */
1377                 t->spacetype = sa->spacetype;
1378         }
1379
1380         /* handle T_ALT_TRANSFORM initialization, we may use for different operators */
1381         if (op) {
1382                 const char *prop_id = NULL;
1383                 if (t->mode == TFM_SHRINKFATTEN) {
1384                         prop_id = "use_even_offset";
1385                 }
1386
1387                 if (prop_id && (prop = RNA_struct_find_property(op->ptr, prop_id))) {
1388                         SET_FLAG_FROM_TEST(t->flag, RNA_property_boolean_get(op->ptr, prop), T_ALT_TRANSFORM);
1389                 }
1390         }
1391
1392         if (t->spacetype == SPACE_VIEW3D) {
1393                 View3D *v3d = sa->spacedata.first;
1394                 bScreen *animscreen = ED_screen_animation_playing(CTX_wm_manager(C));
1395
1396                 t->view = v3d;
1397                 t->animtimer = (animscreen) ? animscreen->animtimer : NULL;
1398
1399                 /* turn gizmo off during transform */
1400                 if (t->flag & T_MODAL) {
1401                         t->gizmo_flag = v3d->gizmo_flag;
1402                         v3d->gizmo_flag = V3D_GIZMO_HIDE;
1403                 }
1404
1405                 if (t->scene->toolsettings->transform_flag & SCE_XFORM_AXIS_ALIGN) {
1406                         t->flag |= T_V3D_ALIGN;
1407                 }
1408                 t->around = t->scene->toolsettings->transform_pivot_point;
1409
1410                 /* bend always uses the cursor */
1411                 if (t->mode == TFM_BEND) {
1412                         t->around = V3D_AROUND_CURSOR;
1413                 }
1414
1415                 TransformOrientationSlot *orient_slot = &t->scene->orientation_slots[SCE_ORIENT_DEFAULT];
1416                 t->orientation.user = orient_slot->type;
1417                 t->orientation.custom = BKE_scene_transform_orientation_find(t->scene, orient_slot->index_custom);
1418
1419                 t->orientation.index = 0;
1420                 ARRAY_SET_ITEMS(
1421                         t->orientation.types,
1422                         &t->orientation.user,
1423                         NULL);
1424
1425                 /* Make second orientation local if both are global. */
1426                 if (t->orientation.user == V3D_MANIP_GLOBAL) {
1427                         t->orientation.user_alt = V3D_MANIP_LOCAL;
1428                         t->orientation.types[0] = &t->orientation.user_alt;
1429                         SWAP(short *, t->orientation.types[0], t->orientation.types[1]);
1430                 }
1431
1432                 /* exceptional case */
1433                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1434                         if (ELEM(t->mode, TFM_ROTATION, TFM_RESIZE, TFM_TRACKBALL)) {
1435                                 const bool use_island = transdata_check_local_islands(t, t->around);
1436
1437                                 if ((t->obedit_type != -1) && !use_island) {
1438                                         t->options |= CTX_NO_PET;
1439                                 }
1440                         }
1441                 }
1442
1443                 if (object_mode & OB_MODE_ALL_PAINT) {
1444                         Paint *p = BKE_paint_get_active_from_context(C);
1445                         if (p && p->brush && (p->brush->flag & BRUSH_CURVE)) {
1446                                 t->options |= CTX_PAINT_CURVE;
1447                         }
1448                 }
1449
1450                 /* initialize UV transform from */
1451                 if (op && ((prop = RNA_struct_find_property(op->ptr, "correct_uv")))) {
1452                         if (RNA_property_is_set(op->ptr, prop)) {
1453                                 if (RNA_property_boolean_get(op->ptr, prop)) {
1454                                         t->settings->uvcalc_flag |= UVCALC_TRANSFORM_CORRECT;
1455                                 }
1456                                 else {
1457                                         t->settings->uvcalc_flag &= ~UVCALC_TRANSFORM_CORRECT;
1458                                 }
1459                         }
1460                         else {
1461                                 RNA_property_boolean_set(op->ptr, prop, (t->settings->uvcalc_flag & UVCALC_TRANSFORM_CORRECT) != 0);
1462                         }
1463                 }
1464
1465         }
1466         else if (t->spacetype == SPACE_IMAGE) {
1467                 SpaceImage *sima = sa->spacedata.first;
1468                 // XXX for now, get View2D from the active region
1469                 t->view = &ar->v2d;
1470                 t->around = sima->around;
1471
1472                 if (ED_space_image_show_uvedit(sima, OBACT(t->view_layer))) {
1473                         /* UV transform */
1474                 }
1475                 else if (sima->mode == SI_MODE_MASK) {
1476                         t->options |= CTX_MASK;
1477                 }
1478                 else if (sima->mode == SI_MODE_PAINT) {
1479                         Paint *p = &sce->toolsettings->imapaint.paint;
1480                         if (p->brush && (p->brush->flag & BRUSH_CURVE)) {
1481                                 t->options |= CTX_PAINT_CURVE;
1482                         }
1483                 }
1484                 /* image not in uv edit, nor in mask mode, can happen for some tools */
1485         }
1486         else if (t->spacetype == SPACE_NODE) {
1487                 // XXX for now, get View2D from the active region
1488                 t->view = &ar->v2d;
1489                 t->around = V3D_AROUND_CENTER_BOUNDS;
1490         }
1491         else if (t->spacetype == SPACE_IPO) {
1492                 SpaceIpo *sipo = sa->spacedata.first;
1493                 t->view = &ar->v2d;
1494                 t->around = sipo->around;
1495         }
1496         else if (t->spacetype == SPACE_CLIP) {
1497                 SpaceClip *sclip = sa->spacedata.first;
1498                 t->view = &ar->v2d;
1499                 t->around = sclip->around;
1500
1501                 if (ED_space_clip_check_show_trackedit(sclip))
1502                         t->options |= CTX_MOVIECLIP;
1503                 else if (ED_space_clip_check_show_maskedit(sclip))
1504                         t->options |= CTX_MASK;
1505         }
1506         else {
1507                 if (ar) {
1508                         // XXX for now, get View2D  from the active region
1509                         t->view = &ar->v2d;
1510                         // XXX for now, the center point is the midpoint of the data
1511                 }
1512                 else {
1513                         t->view = NULL;
1514                 }
1515                 t->around = V3D_AROUND_CENTER_BOUNDS;
1516         }
1517
1518         if (op && ((prop = RNA_struct_find_property(op->ptr, "constraint_matrix")) &&
1519                    RNA_property_is_set(op->ptr, prop)))
1520         {
1521                 RNA_property_float_get_array(op->ptr, prop, &t->spacemtx[0][0]);
1522                 t->orientation.user = V3D_MANIP_CUSTOM_MATRIX;
1523                 t->orientation.custom = 0;
1524         }
1525         else if (op && ((prop = RNA_struct_find_property(op->ptr, "constraint_orientation")) &&
1526                         RNA_property_is_set(op->ptr, prop)))
1527         {
1528                 short orientation = RNA_property_enum_get(op->ptr, prop);
1529                 TransformOrientation *custom_orientation = NULL;
1530
1531                 if (orientation >= V3D_MANIP_CUSTOM) {
1532                         if (orientation >= V3D_MANIP_CUSTOM + BIF_countTransformOrientation(C)) {
1533                                 orientation = V3D_MANIP_GLOBAL;
1534                         }
1535                         else {
1536                                 custom_orientation = BKE_scene_transform_orientation_find(
1537                                         t->scene, orientation - V3D_MANIP_CUSTOM);
1538                                 orientation = V3D_MANIP_CUSTOM;
1539                         }
1540                 }
1541
1542                 t->orientation.user = orientation;
1543                 t->orientation.custom = custom_orientation;
1544         }
1545
1546         if (op && ((prop = RNA_struct_find_property(op->ptr, "release_confirm")) &&
1547                    RNA_property_is_set(op->ptr, prop)))
1548         {
1549                 if (RNA_property_boolean_get(op->ptr, prop)) {
1550                         t->flag |= T_RELEASE_CONFIRM;
1551                 }
1552         }
1553         else {
1554                 if (U.flag & USER_RELEASECONFIRM) {
1555                         t->flag |= T_RELEASE_CONFIRM;
1556                 }
1557         }
1558
1559         if (op && ((prop = RNA_struct_find_property(op->ptr, "mirror")) &&
1560                    RNA_property_is_set(op->ptr, prop)))
1561         {
1562                 if (!RNA_property_boolean_get(op->ptr, prop)) {
1563                         t->flag |= T_NO_MIRROR;
1564                 }
1565         }
1566         else if ((t->spacetype == SPACE_VIEW3D) && (t->obedit_type == OB_MESH)) {
1567                 /* pass */
1568         }
1569         else {
1570                 /* Avoid mirroring for unsupported contexts. */
1571                 t->options |= CTX_NO_MIRROR;
1572         }
1573
1574         /* setting PET flag only if property exist in operator. Otherwise, assume it's not supported */
1575         if (op && (prop = RNA_struct_find_property(op->ptr, "proportional"))) {
1576                 if (RNA_property_is_set(op->ptr, prop)) {
1577                         t->flag |= initTransInfo_edit_pet_to_flag(RNA_property_enum_get(op->ptr, prop));
1578                 }
1579                 else {
1580                         /* use settings from scene only if modal */
1581                         if (t->flag & T_MODAL) {
1582                                 if ((t->options & CTX_NO_PET) == 0) {
1583                                         if (t->spacetype == SPACE_IPO) {
1584                                                 t->flag |= initTransInfo_edit_pet_to_flag(ts->proportional_fcurve);
1585                                         }
1586                                         else if (t->spacetype == SPACE_ACTION) {
1587                                                 t->flag |= initTransInfo_edit_pet_to_flag(ts->proportional_action);
1588                                         }
1589                                         else if (t->obedit_type != -1) {
1590                                                 t->flag |= initTransInfo_edit_pet_to_flag(ts->proportional);
1591                                         }
1592                                         else if (t->options & CTX_GPENCIL_STROKES) {
1593                                                 t->flag |= initTransInfo_edit_pet_to_flag(ts->proportional);
1594                                         }
1595                                         else if (t->options & CTX_MASK) {
1596                                                 if (ts->proportional_mask) {
1597                                                         t->flag |= T_PROP_EDIT;
1598
1599                                                         if (ts->proportional == PROP_EDIT_CONNECTED) {
1600                                                                 t->flag |= T_PROP_CONNECTED;
1601                                                         }
1602                                                 }
1603                                         }
1604                                         else if ((t->obedit_type == -1) && ts->proportional_objects) {
1605                                                 t->flag |= T_PROP_EDIT;
1606                                         }
1607                                 }
1608                         }
1609                 }
1610
1611                 if (op && ((prop = RNA_struct_find_property(op->ptr, "proportional_size")) &&
1612                            RNA_property_is_set(op->ptr, prop)))
1613                 {
1614                         t->prop_size = RNA_property_float_get(op->ptr, prop);
1615                 }
1616                 else {
1617                         t->prop_size = ts->proportional_size;
1618                 }
1619
1620
1621                 /* TRANSFORM_FIX_ME rna restrictions */
1622                 if (t->prop_size <= 0.00001f) {
1623                         printf("Proportional size (%f) under 0.00001, resetting to 1!\n", t->prop_size);
1624                         t->prop_size = 1.0f;
1625                 }
1626
1627                 if (op && ((prop = RNA_struct_find_property(op->ptr, "proportional_edit_falloff")) &&
1628                            RNA_property_is_set(op->ptr, prop)))
1629                 {
1630                         t->prop_mode = RNA_property_enum_get(op->ptr, prop);
1631                 }
1632                 else {
1633                         t->prop_mode = ts->prop_mode;
1634                 }
1635         }
1636         else { /* add not pet option to context when not available */
1637                 t->options |= CTX_NO_PET;
1638         }
1639
1640         // Mirror is not supported with PET, turn it off.
1641 #if 0
1642         if (t->flag & T_PROP_EDIT) {
1643                 t->flag &= ~T_MIRROR;
1644         }
1645 #endif
1646
1647         setTransformViewAspect(t, t->aspect);
1648
1649         if (op && (prop = RNA_struct_find_property(op->ptr, "center_override")) && RNA_property_is_set(op->ptr, prop)) {
1650                 RNA_property_float_get_array(op->ptr, prop, t->center_global);
1651                 mul_v3_v3(t->center_global, t->aspect);
1652                 t->flag |= T_OVERRIDE_CENTER;
1653         }
1654
1655         setTransformViewMatrices(t);
1656         initNumInput(&t->num);
1657 }
1658
1659
1660 static void freeTransCustomData(
1661         TransInfo *t, TransDataContainer *tc,
1662         TransCustomData *custom_data)
1663 {
1664         if (custom_data->free_cb) {
1665                 /* Can take over freeing t->data and data_2d etc... */
1666                 custom_data->free_cb(t, tc, custom_data);
1667                 BLI_assert(custom_data->data == NULL);
1668         }
1669         else if ((custom_data->data != NULL) && custom_data->use_free) {
1670                 MEM_freeN(custom_data->data);
1671                 custom_data->data = NULL;
1672         }
1673         /* In case modes are switched in the same transform session. */
1674         custom_data->free_cb = false;
1675         custom_data->use_free = false;
1676 }
1677
1678 static void freeTransCustomDataContainer(TransInfo *t, TransDataContainer *tc, TransCustomDataContainer *tcdc)
1679 {
1680         TransCustomData *custom_data = &tcdc->first_elem;
1681         for (int i = 0; i < TRANS_CUSTOM_DATA_ELEM_MAX; i++, custom_data++) {
1682                 freeTransCustomData(t, tc, custom_data);
1683         }
1684 }
1685
1686 /**
1687  * Needed for mode switching.
1688  */
1689 void freeTransCustomDataForMode(TransInfo *t)
1690 {
1691         freeTransCustomData(t, NULL, &t->custom.mode);
1692         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1693                 freeTransCustomData(t, tc, &tc->custom.mode);
1694         }
1695 }
1696
1697 /* Here I would suggest only TransInfo related issues, like free data & reset vars. Not redraws */
1698 void postTrans(bContext *C, TransInfo *t)
1699 {
1700         if (t->draw_handle_view)
1701                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_view);
1702         if (t->draw_handle_apply)
1703                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_apply);
1704         if (t->draw_handle_pixel)
1705                 ED_region_draw_cb_exit(t->ar->type, t->draw_handle_pixel);
1706         if (t->draw_handle_cursor)
1707                 WM_paint_cursor_end(CTX_wm_manager(C), t->draw_handle_cursor);
1708
1709         if (t->flag & T_MODAL_CURSOR_SET) {
1710                 WM_cursor_modal_restore(CTX_wm_window(C));
1711         }
1712
1713         /* Free all custom-data */
1714         freeTransCustomDataContainer(t, NULL, &t->custom);
1715         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1716                 freeTransCustomDataContainer(t, tc, &tc->custom);
1717         }
1718
1719         /* postTrans can be called when nothing is selected, so data is NULL already */
1720         if (t->data_len_all != 0) {
1721                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1722                         /* free data malloced per trans-data */
1723                         if (ELEM(t->obedit_type, OB_CURVE, OB_SURF) ||
1724                             (t->spacetype == SPACE_IPO))
1725                         {
1726                                 TransData *td = tc->data;
1727                                 for (int a = 0; a < tc->data_len; a++, td++) {
1728                                         if (td->flag & TD_BEZTRIPLE) {
1729                                                 MEM_freeN(td->hdata);
1730                                         }
1731                                 }
1732                         }
1733                         MEM_freeN(tc->data);
1734
1735                         MEM_SAFE_FREE(tc->data_ext);
1736                         MEM_SAFE_FREE(tc->data_2d);
1737                 }
1738         }
1739
1740         MEM_SAFE_FREE(t->data_container);
1741         t->data_container = NULL;
1742
1743         BLI_freelistN(&t->tsnap.points);
1744
1745         if (t->spacetype == SPACE_IMAGE) {
1746                 if (t->options & (CTX_MASK | CTX_PAINT_CURVE)) {
1747                         /* pass */
1748                 }
1749                 else {
1750                         SpaceImage *sima = t->sa->spacedata.first;
1751                         if (sima->flag & SI_LIVE_UNWRAP)
1752                                 ED_uvedit_live_unwrap_end(t->state == TRANS_CANCEL);
1753                 }
1754         }
1755         else if (t->spacetype == SPACE_VIEW3D) {
1756                 View3D *v3d = t->sa->spacedata.first;
1757                 /* restore gizmo */
1758                 if (t->flag & T_MODAL) {
1759                         v3d->gizmo_flag = t->gizmo_flag;
1760                 }
1761         }
1762
1763         if (t->mouse.data) {
1764                 MEM_freeN(t->mouse.data);
1765         }
1766
1767         if (t->rng != NULL) {
1768                 BLI_rng_free(t->rng);
1769         }
1770
1771         freeSnapping(t);
1772 }
1773
1774 void applyTransObjects(TransInfo *t)
1775 {
1776         TransDataContainer *tc = TRANS_DATA_CONTAINER_FIRST_SINGLE(t);
1777
1778         TransData *td;
1779
1780         for (td = tc->data; td < tc->data + tc->data_len; td++) {
1781                 copy_v3_v3(td->iloc, td->loc);
1782                 if (td->ext->rot) {
1783                         copy_v3_v3(td->ext->irot, td->ext->rot);
1784                 }
1785                 if (td->ext->size) {
1786                         copy_v3_v3(td->ext->isize, td->ext->size);
1787                 }
1788         }
1789         recalcData(t);
1790 }
1791
1792 static void restoreElement(TransData *td)
1793 {
1794         /* TransData for crease has no loc */
1795         if (td->loc) {
1796                 copy_v3_v3(td->loc, td->iloc);
1797         }
1798         if (td->val) {
1799                 *td->val = td->ival;
1800         }
1801
1802         if (td->ext && (td->flag & TD_NO_EXT) == 0) {
1803                 if (td->ext->rot) {
1804                         copy_v3_v3(td->ext->rot, td->ext->irot);
1805                 }
1806                 if (td->ext->rotAngle) {
1807                         *td->ext->rotAngle = td->ext->irotAngle;
1808                 }
1809                 if (td->ext->rotAxis) {
1810                         copy_v3_v3(td->ext->rotAxis, td->ext->irotAxis);
1811                 }
1812                 /* XXX, drotAngle & drotAxis not used yet */
1813                 if (td->ext->size) {
1814                         copy_v3_v3(td->ext->size, td->ext->isize);
1815                 }
1816                 if (td->ext->quat) {
1817                         copy_qt_qt(td->ext->quat, td->ext->iquat);
1818                 }
1819         }
1820
1821         if (td->flag & TD_BEZTRIPLE) {
1822                 *(td->hdata->h1) = td->hdata->ih1;
1823                 *(td->hdata->h2) = td->hdata->ih2;
1824         }
1825 }
1826
1827 void restoreTransObjects(TransInfo *t)
1828 {
1829         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1830
1831                 TransData *td;
1832                 TransData2D *td2d;
1833
1834                 for (td = tc->data; td < tc->data + tc->data_len; td++) {
1835                         restoreElement(td);
1836                 }
1837
1838                 for (td2d = tc->data_2d; tc->data_2d && td2d < tc->data_2d + tc->data_len; td2d++) {
1839                         if (td2d->h1) {
1840                                 td2d->h1[0] = td2d->ih1[0];
1841                                 td2d->h1[1] = td2d->ih1[1];
1842                         }
1843                         if (td2d->h2) {
1844                                 td2d->h2[0] = td2d->ih2[0];
1845                                 td2d->h2[1] = td2d->ih2[1];
1846                         }
1847                 }
1848
1849                 unit_m3(t->mat);
1850
1851         }
1852
1853         recalcData(t);
1854 }
1855
1856 void calculateCenter2D(TransInfo *t)
1857 {
1858         BLI_assert(!is_zero_v3(t->aspect));
1859         projectFloatView(t, t->center_global, t->center2d);
1860 }
1861
1862 void calculateCenterLocal(
1863         TransInfo *t, const float center_global[3])
1864 {
1865         /* setting constraint center */
1866         /* note, init functions may over-ride t->center */
1867         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1868                 if (tc->use_local_mat) {
1869                         mul_v3_m4v3(tc->center_local, tc->imat, center_global);
1870                 }
1871                 else {
1872                         copy_v3_v3(tc->center_local, center_global);
1873                 }
1874         }
1875 }
1876
1877 void calculateCenterCursor(TransInfo *t, float r_center[3])
1878 {
1879         const float *cursor = t->scene->cursor.location;
1880         copy_v3_v3(r_center, cursor);
1881
1882         /* If edit or pose mode, move cursor in local space */
1883         if (t->options & CTX_PAINT_CURVE) {
1884                 if (ED_view3d_project_float_global(t->ar, cursor, r_center, V3D_PROJ_TEST_NOP) != V3D_PROJ_RET_OK) {
1885                         r_center[0] = t->ar->winx / 2.0f;
1886                         r_center[1] = t->ar->winy / 2.0f;
1887                 }
1888                 r_center[2] = 0.0f;
1889         }
1890 }
1891
1892 void calculateCenterCursor2D(TransInfo *t, float r_center[2])
1893 {
1894         const float *cursor = NULL;
1895
1896         if (t->spacetype == SPACE_IMAGE) {
1897                 SpaceImage *sima = (SpaceImage *)t->sa->spacedata.first;
1898                 cursor = sima->cursor;
1899         }
1900         else if (t->spacetype == SPACE_CLIP) {
1901                 SpaceClip *space_clip = (SpaceClip *) t->sa->spacedata.first;
1902                 cursor = space_clip->cursor;
1903         }
1904
1905         if (cursor) {
1906                 if (t->options & CTX_MASK) {
1907                         float co[2];
1908
1909                         if (t->spacetype == SPACE_IMAGE) {
1910                                 SpaceImage *sima = (SpaceImage *)t->sa->spacedata.first;
1911                                 BKE_mask_coord_from_image(sima->image, &sima->iuser, co, cursor);
1912                         }
1913                         else if (t->spacetype == SPACE_CLIP) {
1914                                 SpaceClip *space_clip = (SpaceClip *) t->sa->spacedata.first;
1915                                 BKE_mask_coord_from_movieclip(space_clip->clip, &space_clip->user, co, cursor);
1916                         }
1917                         else {
1918                                 BLI_assert(!"Shall not happen");
1919                         }
1920
1921                         r_center[0] = co[0] * t->aspect[0];
1922                         r_center[1] = co[1] * t->aspect[1];
1923                 }
1924                 else if (t->options & CTX_PAINT_CURVE) {
1925                         if (t->spacetype == SPACE_IMAGE) {
1926                                 r_center[0] = UI_view2d_view_to_region_x(&t->ar->v2d, cursor[0]);
1927                                 r_center[1] = UI_view2d_view_to_region_y(&t->ar->v2d, cursor[1]);
1928                         }
1929                 }
1930                 else {
1931                         r_center[0] = cursor[0] * t->aspect[0];
1932                         r_center[1] = cursor[1] * t->aspect[1];
1933                 }
1934         }
1935 }
1936
1937 void calculateCenterCursorGraph2D(TransInfo *t, float r_center[2])
1938 {
1939         SpaceIpo *sipo = (SpaceIpo *)t->sa->spacedata.first;
1940         Scene *scene = t->scene;
1941
1942         /* cursor is combination of current frame, and graph-editor cursor value */
1943         if (sipo->mode == SIPO_MODE_DRIVERS) {
1944                 r_center[0] = sipo->cursorTime;
1945                 r_center[1] = sipo->cursorVal;
1946         }
1947         else {
1948                 r_center[0] = (float)(scene->r.cfra);
1949                 r_center[1] = sipo->cursorVal;
1950         }
1951 }
1952
1953 void calculateCenterMedian(TransInfo *t, float r_center[3])
1954 {
1955         float partial[3] = {0.0f, 0.0f, 0.0f};
1956         int total = 0;
1957
1958         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1959                 for (int i = 0; i < tc->data_len; i++) {
1960                         if (tc->data[i].flag & TD_SELECTED) {
1961                                 if (!(tc->data[i].flag & TD_NOCENTER)) {
1962                                         if (tc->use_local_mat) {
1963                                                 float v[3];
1964                                                 mul_v3_m4v3(v, tc->mat, tc->data[i].center);
1965                                                 add_v3_v3(partial, v);
1966                                         }
1967                                         else {
1968                                                 add_v3_v3(partial, tc->data[i].center);
1969                                         }
1970                                         total++;
1971                                 }
1972                         }
1973                 }
1974         }
1975         if (total) {
1976                 mul_v3_fl(partial, 1.0f / (float)total);
1977         }
1978         copy_v3_v3(r_center, partial);
1979 }
1980
1981 void calculateCenterBound(TransInfo *t, float r_center[3])
1982 {
1983         float max[3], min[3];
1984         bool changed = false;
1985         INIT_MINMAX(min, max);
1986         FOREACH_TRANS_DATA_CONTAINER (t, tc) {
1987                 for (int i = 0; i < tc->data_len; i++) {
1988                         if (tc->data[i].flag & TD_SELECTED) {
1989                                 if (!(tc->data[i].flag & TD_NOCENTER)) {
1990                                         if (tc->use_local_mat) {
1991                                                 float v[3];
1992                                                 mul_v3_m4v3(v, tc->mat, tc->data[i].center);
1993                                                 minmax_v3v3_v3(min, max, v);
1994                                         }
1995                                         else {
1996                                                 minmax_v3v3_v3(min, max, tc->data[i].center);
1997                                         }
1998                                         changed = true;
1999                                 }
2000                         }
2001                 }
2002         }
2003         if (changed) {
2004                 mid_v3_v3v3(r_center, min, max);
2005         }
2006 }
2007
2008 /**
2009  * \param select_only: only get active center from data being transformed.
2010  */
2011 bool calculateCenterActive(TransInfo *t, bool select_only, float r_center[3])
2012 {
2013         TransDataContainer *tc = TRANS_DATA_CONTAINER_FIRST_OK(t);
2014
2015         if (t->spacetype != SPACE_VIEW3D) {
2016                 return false;
2017         }
2018         else if (tc->obedit) {
2019                 if (ED_object_calc_active_center_for_editmode(tc->obedit, select_only, r_center)) {
2020                         mul_m4_v3(tc->obedit->obmat, r_center);
2021                         return true;
2022                 }
2023         }
2024         else if (t->flag & T_POSE) {
2025                 ViewLayer *view_layer = t->view_layer;
2026                 Object *ob = OBACT(view_layer) ;
2027                 if (ED_object_calc_active_center_for_posemode(ob, select_only, r_center)) {
2028                         mul_m4_v3(ob->obmat, r_center);
2029                         return true;
2030                 }
2031         }
2032         else if (t->options & CTX_PAINT_CURVE) {
2033                 Paint *p = BKE_paint_get_active(t->scene, t->view_layer);
2034                 Brush *br = p->brush;
2035                 PaintCurve *pc = br->paint_curve;
2036                 copy_v3_v3(r_center, pc->points[pc->add_index - 1].bez.vec[1]);
2037                 r_center[2] = 0.0f;
2038                 return true;
2039         }
2040         else {
2041                 /* object mode */
2042                 ViewLayer *view_layer = t->view_layer;
2043                 Object *ob = OBACT(view_layer);
2044                 Base *base = BASACT(view_layer);
2045                 if (ob && ((!select_only) || ((base->flag & BASE_SELECTED) != 0))) {
2046                         copy_v3_v3(r_center, ob->obmat[3]);
2047                         return true;
2048                 }
2049         }
2050
2051         return false;
2052 }
2053
2054 static void calculateCenter_FromAround(TransInfo *t, int around, float r_center[3])
2055 {
2056         switch (around) {
2057                 case V3D_AROUND_CENTER_BOUNDS:
2058                         calculateCenterBound(t, r_center);
2059                         break;
2060                 case V3D_AROUND_CENTER_MEDIAN:
2061                         calculateCenterMedian(t, r_center);
2062                         break;
2063                 case V3D_AROUND_CURSOR:
2064                         if (ELEM(t->spacetype, SPACE_IMAGE, SPACE_CLIP))
2065                                 calculateCenterCursor2D(t, r_center);
2066                         else if (t->spacetype == SPACE_IPO)
2067                                 calculateCenterCursorGraph2D(t, r_center);
2068                         else
2069                                 calculateCenterCursor(t, r_center);
2070                         break;
2071                 case V3D_AROUND_LOCAL_ORIGINS:
2072                         /* Individual element center uses median center for helpline and such */
2073                         calculateCenterMedian(t, r_center);
2074                         break;
2075                 case V3D_AROUND_ACTIVE:
2076                 {
2077                         if (calculateCenterActive(t, false, r_center)) {
2078                                 /* pass */
2079                         }
2080                         else {
2081                                 /* fallback */
2082                                 calculateCenterMedian(t, r_center);
2083                         }
2084                         break;
2085                 }
2086         }
2087 }
2088
2089 void calculateCenter(TransInfo *t)
2090 {
2091         if ((t->flag & T_OVERRIDE_CENTER) == 0) {
2092                 calculateCenter_FromAround(t, t->around, t->center_global);
2093         }
2094         calculateCenterLocal(t, t->center_global);
2095
2096         /* avoid calculating again */
2097         {
2098                 TransCenterData *cd = &t->center_cache[t->around];
2099                 copy_v3_v3(cd->global, t->center_global);
2100                 cd->is_set = true;
2101         }
2102
2103         calculateCenter2D(t);
2104
2105         /* for panning from cameraview */
2106         if ((t->flag & T_OBJECT) && (t->flag & T_OVERRIDE_CENTER) == 0) {
2107                 if (t->spacetype == SPACE_VIEW3D && t->ar && t->ar->regiontype == RGN_TYPE_WINDOW) {
2108
2109                         if (t->flag & T_CAMERA) {
2110                                 float axis[3];
2111                                 /* persinv is nasty, use viewinv instead, always right */
2112                                 copy_v3_v3(axis, t->viewinv[2]);
2113                                 normalize_v3(axis);
2114
2115                                 /* 6.0 = 6 grid units */
2116                                 axis[0] = t->center_global[0] - 6.0f * axis[0];
2117                                 axis[1] = t->center_global[1] - 6.0f * axis[1];
2118                                 axis[2] = t->center_global[2] - 6.0f * axis[2];
2119
2120                                 projectFloatView(t, axis, t->center2d);
2121
2122                                 /* rotate only needs correct 2d center, grab needs ED_view3d_calc_zfac() value */
2123                                 if (t->mode == TFM_TRANSLATION) {
2124                                         copy_v3_v3(t->center_global, axis);
2125                                 }
2126                         }
2127                 }
2128         }
2129
2130         if (t->spacetype == SPACE_VIEW3D) {
2131                 /* ED_view3d_calc_zfac() defines a factor for perspective depth correction, used in ED_view3d_win_to_delta() */
2132
2133                 /* zfac is only used convertViewVec only in cases operator was invoked in RGN_TYPE_WINDOW
2134                  * and never used in other cases.
2135                  *
2136                  * We need special case here as well, since ED_view3d_calc_zfac will crash when called
2137                  * for a region different from RGN_TYPE_WINDOW.
2138                  */
2139                 if (t->ar->regiontype == RGN_TYPE_WINDOW) {
2140                         t->zfac = ED_view3d_calc_zfac(t->ar->regiondata, t->center_global, NULL);
2141                 }
2142                 else {
2143                         t->zfac = 0.0f;
2144                 }
2145         }
2146 }
2147
2148 BLI_STATIC_ASSERT(ARRAY_SIZE(((TransInfo *)NULL)->center_cache) == (V3D_AROUND_ACTIVE + 1), "test size");
2149
2150 /**
2151  * Lazy initialize transform center data, when we need to access center values from other types.
2152  */
2153 const TransCenterData *transformCenter_from_type(TransInfo *t, int around)
2154 {
2155         BLI_assert(around <= V3D_AROUND_ACTIVE);
2156         TransCenterData *cd = &t->center_cache[around];
2157         if (cd->is_set == false) {
2158                 calculateCenter_FromAround(t, around, cd->global);
2159                 cd->is_set = true;
2160         }
2161         return cd;
2162 }
2163
2164 void calculatePropRatio(TransInfo *t)
2165 {
2166         int i;
2167         float dist;
2168         const bool connected = (t->flag & T_PROP_CONNECTED) != 0;
2169
2170         t->proptext[0] = '\0';
2171
2172         if (t->flag & T_PROP_EDIT) {
2173                 const char *pet_id = NULL;
2174                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
2175                         TransData *td = tc->data;
2176                         for (i = 0; i < tc->data_len; i++, td++) {
2177                                 if (td->flag & TD_SELECTED) {
2178                                         td->factor = 1.0f;
2179                                 }
2180                                 else if (tc->mirror.axis_flag && (td->loc[0] * tc->mirror.sign) < -0.00001f) {
2181                                         td->flag |= TD_SKIP;
2182                                         td->factor = 0.0f;
2183                                         restoreElement(td);
2184                                 }
2185                                 else if ((connected && (td->flag & TD_NOTCONNECTED || td->dist > t->prop_size)) ||
2186                                          (connected == 0 && td->rdist > t->prop_size))
2187                                 {
2188                                         /*
2189                                          * The elements are sorted according to their dist member in the array,
2190                                          * that means we can stop when it finds one element outside of the propsize.
2191                                          * do not set 'td->flag |= TD_NOACTION', the prop circle is being changed.
2192                                          */
2193
2194                                         td->factor = 0.0f;
2195                                         restoreElement(td);
2196                                 }
2197                                 else {
2198                                         /* Use rdist for falloff calculations, it is the real distance */
2199                                         td->flag &= ~TD_NOACTION;
2200
2201                                         if (connected)
2202                                                 dist = (t->prop_size - td->dist) / t->prop_size;
2203                                         else
2204                                                 dist = (t->prop_size - td->rdist) / t->prop_size;
2205
2206                                         /*
2207                                          * Clamp to positive numbers.
2208                                          * Certain corner cases with connectivity and individual centers
2209                                          * can give values of rdist larger than propsize.
2210                                          */
2211                                         if (dist < 0.0f)
2212                                                 dist = 0.0f;
2213
2214                                         switch (t->prop_mode) {
2215                                                 case PROP_SHARP:
2216                                                         td->factor = dist * dist;
2217                                                         break;
2218                                                 case PROP_SMOOTH:
2219                                                         td->factor = 3.0f * dist * dist - 2.0f * dist * dist * dist;
2220                                                         break;
2221                                                 case PROP_ROOT:
2222                                                         td->factor = sqrtf(dist);
2223                                                         break;
2224                                                 case PROP_LIN:
2225                                                         td->factor = dist;
2226                                                         break;
2227                                                 case PROP_CONST:
2228                                                         td->factor = 1.0f;
2229                                                         break;
2230                                                 case PROP_SPHERE:
2231                                                         td->factor = sqrtf(2 * dist - dist * dist);
2232                                                         break;
2233                                                 case PROP_RANDOM:
2234                                                         if (t->rng == NULL) {
2235                                                                 /* Lazy initialization. */
2236                                                                 uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX);
2237                                                                 t->rng = BLI_rng_new(rng_seed);
2238                                                         }
2239                                                         td->factor = BLI_rng_get_float(t->rng) * dist;
2240                                                         break;
2241                                                 case PROP_INVSQUARE:
2242                                                         td->factor = dist * (2.0f - dist);
2243                                                         break;
2244                                                 default:
2245                                                         td->factor = 1;
2246                                                         break;
2247                                         }
2248                                 }
2249                         }
2250                 }
2251
2252                 switch (t->prop_mode) {
2253                         case PROP_SHARP:
2254                                 pet_id = N_("(Sharp)");
2255                                 break;
2256                         case PROP_SMOOTH:
2257                                 pet_id = N_("(Smooth)");
2258                                 break;
2259                         case PROP_ROOT:
2260                                 pet_id = N_("(Root)");
2261                                 break;
2262                         case PROP_LIN:
2263                                 pet_id = N_("(Linear)");
2264                                 break;
2265                         case PROP_CONST:
2266                                 pet_id = N_("(Constant)");
2267                                 break;
2268                         case PROP_SPHERE:
2269                                 pet_id = N_("(Sphere)");
2270                                 break;
2271                         case PROP_RANDOM:
2272                                 pet_id = N_("(Random)");
2273                                 break;
2274                         case PROP_INVSQUARE:
2275                                 pet_id = N_("(InvSquare)");
2276                                 break;
2277                         default:
2278                                 break;
2279                 }
2280
2281                 if (pet_id) {
2282                         BLI_strncpy(t->proptext, IFACE_(pet_id), sizeof(t->proptext));
2283                 }
2284         }
2285         else {
2286                 FOREACH_TRANS_DATA_CONTAINER (t, tc) {
2287                         TransData *td = tc->data;
2288                         for (i = 0; i < tc->data_len; i++, td++) {
2289                                 td->factor = 1.0;
2290                         }
2291                 }
2292         }
2293 }
2294
2295 /**
2296  * Rotate an element, low level code, ignore protected channels.
2297  * (use for objects or pose-bones)
2298  * Similar to #ElementRotation.
2299  */
2300 void transform_data_ext_rotate(TransData *td, float mat[3][3], bool use_drot)
2301 {
2302         float totmat[3][3];
2303         float smat[3][3];
2304         float fmat[3][3];
2305         float obmat[3][3];
2306
2307         float dmat[3][3];  /* delta rotation */
2308         float dmat_inv[3][3];
2309
2310         mul_m3_m3m3(totmat, mat, td->mtx);
2311         mul_m3_m3m3(smat, td->smtx, mat);
2312
2313         /* logic from BKE_object_rot_to_mat3 */
2314         if (use_drot) {
2315                 if (td->ext->rotOrder > 0) {
2316                         eulO_to_mat3(dmat, td->ext->drot, td->ext->rotOrder);
2317                 }
2318                 else if (td->ext->rotOrder == ROT_MODE_AXISANGLE) {
2319 #if 0
2320                         axis_angle_to_mat3(dmat, td->ext->drotAxis, td->ext->drotAngle);
2321 #else
2322                         unit_m3(dmat);
2323 #endif
2324                 }
2325                 else {
2326                         float tquat[4];
2327                         normalize_qt_qt(tquat, td->ext->dquat);
2328                         quat_to_mat3(dmat, tquat);
2329                 }
2330
2331                 invert_m3_m3(dmat_inv, dmat);
2332         }
2333
2334
2335         if (td->ext->rotOrder == ROT_MODE_QUAT) {
2336                 float quat[4];
2337
2338                 /* calculate the total rotatation */
2339                 quat_to_mat3(obmat, td->ext->iquat);
2340                 if (use_drot) {
2341                         mul_m3_m3m3(obmat, dmat, obmat);
2342                 }
2343
2344                 /* mat = transform, obmat = object rotation */
2345                 mul_m3_m3m3(fmat, smat, obmat);
2346
2347                 if (use_drot) {
2348                         mul_m3_m3m3(fmat, dmat_inv, fmat);
2349                 }
2350
2351                 mat3_to_quat(quat, fmat);
2352
2353                 /* apply */
2354                 copy_qt_qt(td->ext->quat, quat);
2355         }
2356         else if (td->ext->rotOrder == ROT_MODE_AXISANGLE) {
2357                 float axis[3], angle;
2358
2359                 /* calculate the total rotatation */
2360                 axis_angle_to_mat3(obmat, td->ext->irotAxis, td->ext->irotAngle);
2361                 if (use_drot) {
2362                         mul_m3_m3m3(obmat, dmat, obmat);
2363                 }
2364
2365                 /* mat = transform, obmat = object rotation */
2366                 mul_m3_m3m3(fmat, smat, obmat);
2367
2368                 if (use_drot) {
2369                         mul_m3_m3m3(fmat, dmat_inv, fmat);
2370                 }
2371
2372                 mat3_to_axis_angle(axis, &angle, fmat);
2373
2374                 /* apply */
2375                 copy_v3_v3(td->ext->rotAxis, axis);
2376                 *td->ext->rotAngle = angle;
2377         }
2378         else {
2379                 float eul[3];
2380
2381                 /* calculate the total rotatation */
2382                 eulO_to_mat3(obmat, td->ext->irot, td->ext->rotOrder);
2383                 if (use_drot) {
2384                         mul_m3_m3m3(obmat, dmat, obmat);
2385                 }
2386
2387                 /* mat = transform, obmat = object rotation */
2388                 mul_m3_m3m3(fmat, smat, obmat);
2389
2390                 if (use_drot) {
2391                         mul_m3_m3m3(fmat, dmat_inv, fmat);
2392                 }
2393
2394                 mat3_to_compatible_eulO(eul, td->ext->rot, td->ext->rotOrder, fmat);
2395
2396                 /* apply */
2397                 copy_v3_v3(td->ext->rot, eul);
2398         }
2399 }