Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / transform / transform_conversions.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_conversions.c
29  *  \ingroup edtransform
30  */
31
32 #include <string.h>
33 #include <math.h>
34 #include <limits.h>
35
36 #include "DNA_anim_types.h"
37 #include "DNA_brush_types.h"
38 #include "DNA_armature_types.h"
39 #include "DNA_lattice_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meta_types.h"
42 #include "DNA_node_types.h"
43 #include "DNA_screen_types.h"
44 #include "DNA_space_types.h"
45 #include "DNA_sequence_types.h"
46 #include "DNA_view3d_types.h"
47 #include "DNA_constraint_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_meshdata_types.h"
50 #include "DNA_gpencil_types.h"
51 #include "DNA_movieclip_types.h"
52 #include "DNA_mask_types.h"
53
54 #include "MEM_guardedalloc.h"
55
56 #include "BLI_math.h"
57 #include "BLI_utildefines.h"
58 #include "BLI_listbase.h"
59 #include "BLI_linklist_stack.h"
60 #include "BLI_string.h"
61 #include "BLI_bitmap.h"
62 #include "BLI_rect.h"
63
64 #include "BKE_DerivedMesh.h"
65 #include "BKE_action.h"
66 #include "BKE_armature.h"
67 #include "BKE_constraint.h"
68 #include "BKE_context.h"
69 #include "BKE_crazyspace.h"
70 #include "BKE_curve.h"
71 #include "BKE_fcurve.h"
72 #include "BKE_global.h"
73 #include "BKE_gpencil.h"
74 #include "BKE_layer.h"
75 #include "BKE_key.h"
76 #include "BKE_main.h"
77 #include "BKE_mesh.h"
78 #include "BKE_mesh_mapping.h"
79 #include "BKE_modifier.h"
80 #include "BKE_movieclip.h"
81 #include "BKE_nla.h"
82 #include "BKE_node.h"
83 #include "BKE_object.h"
84 #include "BKE_particle.h"
85 #include "BKE_paint.h"
86 #include "BKE_pointcache.h"
87 #include "BKE_report.h"
88 #include "BKE_rigidbody.h"
89 #include "BKE_scene.h"
90 #include "BKE_sequencer.h"
91 #include "BKE_editmesh.h"
92 #include "BKE_tracking.h"
93 #include "BKE_mask.h"
94
95 #include "BIK_api.h"
96
97 #include "ED_anim_api.h"
98 #include "ED_armature.h"
99 #include "ED_particle.h"
100 #include "ED_image.h"
101 #include "ED_keyframing.h"
102 #include "ED_keyframes_edit.h"
103 #include "ED_object.h"
104 #include "ED_markers.h"
105 #include "ED_mesh.h"
106 #include "ED_node.h"
107 #include "ED_uvedit.h"
108 #include "ED_clip.h"
109 #include "ED_mask.h"
110 #include "ED_gpencil.h"
111
112 #include "WM_api.h"  /* for WM_event_add_notifier to deal with stabilization nodes */
113 #include "WM_types.h"
114
115 #include "UI_view2d.h"
116 #include "UI_interface.h"
117
118 #include "RNA_access.h"
119
120 #include "DEG_depsgraph.h"
121 #include "DEG_depsgraph_build.h"
122
123 #include "transform.h"
124 #include "bmesh.h"
125
126 /**
127  * Transforming around ourselves is no use, fallback to individual origins,
128  * useful for curve/armatures.
129  */
130 static void transform_around_single_fallback(TransInfo *t)
131 {
132         if ((t->total == 1) &&
133             (ELEM(t->around, V3D_AROUND_CENTER_BOUNDS, V3D_AROUND_CENTER_MEAN, V3D_AROUND_ACTIVE)) &&
134             (ELEM(t->mode, TFM_RESIZE, TFM_ROTATION, TFM_TRACKBALL)))
135         {
136                 t->around = V3D_AROUND_LOCAL_ORIGINS;
137         }
138 }
139
140 /* when transforming islands */
141 struct TransIslandData {
142         float co[3];
143         float axismtx[3][3];
144 };
145
146 /* local function prototype - for Object/Bone Constraints */
147 static bool constraints_list_needinv(TransInfo *t, ListBase *list);
148
149 /* ************************** Functions *************************** */
150
151 static int trans_data_compare_dist(const void *a, const void *b)
152 {
153         const TransData *td_a = (const TransData *)a;
154         const TransData *td_b = (const TransData *)b;
155
156         if      (td_a->dist < td_b->dist) return -1;
157         else if (td_a->dist > td_b->dist) return  1;
158         else                              return  0;
159 }
160
161 static int trans_data_compare_rdist(const void *a, const void *b)
162 {
163         const TransData *td_a = (const TransData *)a;
164         const TransData *td_b = (const TransData *)b;
165
166         if      (td_a->rdist < td_b->rdist) return -1;
167         else if (td_a->rdist > td_b->rdist) return  1;
168         else                                return  0;
169 }
170
171 void sort_trans_data_dist(TransInfo *t)
172 {
173         TransData *start = t->data;
174         int i;
175
176         for (i = 0; i < t->total && start->flag & TD_SELECTED; i++)
177                 start++;
178         
179         if (i < t->total) {
180                 if (t->flag & T_PROP_CONNECTED)
181                         qsort(start, t->total - i, sizeof(TransData), trans_data_compare_dist);
182                 else
183                         qsort(start, t->total - i, sizeof(TransData), trans_data_compare_rdist);
184         }
185 }
186
187 static void sort_trans_data(TransInfo *t)
188 {
189         TransData *sel, *unsel;
190         TransData temp;
191         unsel = t->data;
192         sel = t->data;
193         sel += t->total - 1;
194         while (sel > unsel) {
195                 while (unsel->flag & TD_SELECTED) {
196                         unsel++;
197                         if (unsel == sel) {
198                                 return;
199                         }
200                 }
201                 while (!(sel->flag & TD_SELECTED)) {
202                         sel--;
203                         if (unsel == sel) {
204                                 return;
205                         }
206                 }
207                 temp = *unsel;
208                 *unsel = *sel;
209                 *sel = temp;
210                 sel--;
211                 unsel++;
212         }
213 }
214
215 /* distance calculated from not-selected vertex to nearest selected vertex
216  * warning; this is loops inside loop, has minor N^2 issues, but by sorting list it is OK */
217 static void set_prop_dist(TransInfo *t, const bool with_dist)
218 {
219         TransData *tob;
220         int a;
221
222         float _proj_vec[3];
223         const float *proj_vec = NULL;
224
225         /* support for face-islands */
226         const bool use_island = transdata_check_local_islands(t, t->around);
227
228         if (t->flag & T_PROP_PROJECTED) {
229                 if (t->spacetype == SPACE_VIEW3D && t->ar && t->ar->regiontype == RGN_TYPE_WINDOW) {
230                         RegionView3D *rv3d = t->ar->regiondata;
231                         normalize_v3_v3(_proj_vec, rv3d->viewinv[2]);
232                         proj_vec = _proj_vec;
233                 }
234         }
235
236         for (a = 0, tob = t->data; a < t->total; a++, tob++) {
237
238                 tob->rdist = 0.0f; // init, it was mallocced
239
240                 if ((tob->flag & TD_SELECTED) == 0) {
241                         TransData *td;
242                         int i;
243                         float dist_sq, vec[3];
244
245                         tob->rdist = -1.0f; // signal for next loop
246
247                         for (i = 0, td = t->data; i < t->total; i++, td++) {
248                                 if (td->flag & TD_SELECTED) {
249                                         if (use_island) {
250                                                 sub_v3_v3v3(vec, tob->iloc, td->iloc);
251                                         }
252                                         else {
253                                                 sub_v3_v3v3(vec, tob->center, td->center);
254                                         }
255                                         mul_m3_v3(tob->mtx, vec);
256
257                                         if (proj_vec) {
258                                                 float vec_p[3];
259                                                 project_v3_v3v3(vec_p, vec, proj_vec);
260                                                 sub_v3_v3(vec, vec_p);
261                                         }
262
263                                         dist_sq = len_squared_v3(vec);
264                                         if ((tob->rdist == -1.0f) || (dist_sq < SQUARE(tob->rdist))) {
265                                                 tob->rdist = sqrtf(dist_sq);
266                                                 if (use_island) {
267                                                         copy_v3_v3(tob->center, td->center);
268                                                         copy_m3_m3(tob->axismtx, td->axismtx);
269                                                 }
270                                         }
271                                 }
272                                 else {
273                                         break;  /* by definition transdata has selected items in beginning */
274                                 }
275                         }
276                         if (with_dist) {
277                                 tob->dist = tob->rdist;
278                         }
279                 }
280         }
281 }
282
283 /* ************************** CONVERSIONS ************************* */
284
285 /* ********************* texture space ********* */
286
287 static void createTransTexspace(TransInfo *t)
288 {
289         ViewLayer *view_layer = t->view_layer;
290         TransData *td;
291         Object *ob;
292         ID *id;
293         short *texflag;
294
295         ob = OBACT(view_layer);
296
297         if (ob == NULL) { // Shouldn't logically happen, but still...
298                 t->total = 0;
299                 return;
300         }
301
302         id = ob->data;
303         if (id == NULL || !ELEM(GS(id->name), ID_ME, ID_CU, ID_MB)) {
304                 BKE_report(t->reports, RPT_ERROR, "Unsupported object type for text-space transform");
305                 t->total = 0;
306                 return;
307         }
308
309         if (BKE_object_obdata_is_libdata(ob)) {
310                 BKE_report(t->reports, RPT_ERROR, "Linked data can't text-space transform");
311                 t->total = 0;
312                 return;
313         }
314
315         t->total = 1;
316         td = t->data = MEM_callocN(sizeof(TransData), "TransTexspace");
317         td->ext = t->ext = MEM_callocN(sizeof(TransDataExtension), "TransTexspace");
318
319         td->flag = TD_SELECTED;
320         copy_v3_v3(td->center, ob->obmat[3]);
321         td->ob = ob;
322
323         copy_m3_m4(td->mtx, ob->obmat);
324         copy_m3_m4(td->axismtx, ob->obmat);
325         normalize_m3(td->axismtx);
326         pseudoinverse_m3_m3(td->smtx, td->mtx, PSEUDOINVERSE_EPSILON);
327
328         if (BKE_object_obdata_texspace_get(ob, &texflag, &td->loc, &td->ext->size, &td->ext->rot)) {
329                 ob->dtx |= OB_TEXSPACE;
330                 *texflag &= ~ME_AUTOSPACE;
331         }
332
333         copy_v3_v3(td->iloc, td->loc);
334         copy_v3_v3(td->ext->irot, td->ext->rot);
335         copy_v3_v3(td->ext->isize, td->ext->size);
336 }
337
338 /* ********************* edge (for crease) ***** */
339
340 static void createTransEdge(TransInfo *t)
341 {
342         BMEditMesh *em = BKE_editmesh_from_object(t->obedit);
343         TransData *td = NULL;
344         BMEdge *eed;
345         BMIter iter;
346         float mtx[3][3], smtx[3][3];
347         int count = 0, countsel = 0;
348         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
349         int cd_edge_float_offset;
350
351         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
352                 if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN)) {
353                         if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) countsel++;
354                         if (is_prop_edit) count++;
355                 }
356         }
357
358         if (countsel == 0)
359                 return;
360
361         if (is_prop_edit) {
362                 t->total = count;
363         }
364         else {
365                 t->total = countsel;
366         }
367
368         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransCrease");
369
370         copy_m3_m4(mtx, t->obedit->obmat);
371         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
372
373         /* create data we need */
374         if (t->mode == TFM_BWEIGHT) {
375                 BM_mesh_cd_flag_ensure(em->bm, BKE_mesh_from_object(t->obedit), ME_CDFLAG_EDGE_BWEIGHT);
376                 cd_edge_float_offset = CustomData_get_offset(&em->bm->edata, CD_BWEIGHT);
377         }
378         else { //if (t->mode == TFM_CREASE) {
379                 BLI_assert(t->mode == TFM_CREASE);
380                 BM_mesh_cd_flag_ensure(em->bm, BKE_mesh_from_object(t->obedit), ME_CDFLAG_EDGE_CREASE);
381                 cd_edge_float_offset = CustomData_get_offset(&em->bm->edata, CD_CREASE);
382         }
383
384         BLI_assert(cd_edge_float_offset != -1);
385
386         BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
387                 if (!BM_elem_flag_test(eed, BM_ELEM_HIDDEN) && (BM_elem_flag_test(eed, BM_ELEM_SELECT) || is_prop_edit)) {
388                         float *fl_ptr;
389                         /* need to set center for center calculations */
390                         mid_v3_v3v3(td->center, eed->v1->co, eed->v2->co);
391
392                         td->loc = NULL;
393                         if (BM_elem_flag_test(eed, BM_ELEM_SELECT))
394                                 td->flag = TD_SELECTED;
395                         else
396                                 td->flag = 0;
397
398                         copy_m3_m3(td->smtx, smtx);
399                         copy_m3_m3(td->mtx, mtx);
400
401                         td->ext = NULL;
402
403                         fl_ptr = BM_ELEM_CD_GET_VOID_P(eed, cd_edge_float_offset);
404                         td->val  =  fl_ptr;
405                         td->ival = *fl_ptr;
406
407                         td++;
408                 }
409         }
410 }
411
412 /* ********************* pose mode ************* */
413
414 static bKinematicConstraint *has_targetless_ik(bPoseChannel *pchan)
415 {
416         bConstraint *con = pchan->constraints.first;
417
418         for (; con; con = con->next) {
419                 if (con->type == CONSTRAINT_TYPE_KINEMATIC && (con->enforce != 0.0f)) {
420                         bKinematicConstraint *data = con->data;
421
422                         if (data->tar == NULL)
423                                 return data;
424                         if (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0)
425                                 return data;
426                 }
427         }
428         return NULL;
429 }
430
431 static short apply_targetless_ik(Object *ob)
432 {
433         bPoseChannel *pchan, *parchan, *chanlist[256];
434         bKinematicConstraint *data;
435         int segcount, apply = 0;
436
437         /* now we got a difficult situation... we have to find the
438          * target-less IK pchans, and apply transformation to the all
439          * pchans that were in the chain */
440
441         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
442                 data = has_targetless_ik(pchan);
443                 if (data && (data->flag & CONSTRAINT_IK_AUTO)) {
444
445                         /* fill the array with the bones of the chain (armature.c does same, keep it synced) */
446                         segcount = 0;
447
448                         /* exclude tip from chain? */
449                         if (!(data->flag & CONSTRAINT_IK_TIP))
450                                 parchan = pchan->parent;
451                         else
452                                 parchan = pchan;
453
454                         /* Find the chain's root & count the segments needed */
455                         for (; parchan; parchan = parchan->parent) {
456                                 chanlist[segcount] = parchan;
457                                 segcount++;
458
459                                 if (segcount == data->rootbone || segcount > 255) break;  // 255 is weak
460                         }
461                         for (; segcount; segcount--) {
462                                 Bone *bone;
463                                 float rmat[4][4] /*, tmat[4][4], imat[4][4]*/;
464
465                                 /* pose_mat(b) = pose_mat(b-1) * offs_bone * channel * constraint * IK  */
466                                 /* we put in channel the entire result of rmat = (channel * constraint * IK) */
467                                 /* pose_mat(b) = pose_mat(b-1) * offs_bone * rmat  */
468                                 /* rmat = pose_mat(b) * inv(pose_mat(b-1) * offs_bone ) */
469
470                                 parchan = chanlist[segcount - 1];
471                                 bone = parchan->bone;
472                                 bone->flag |= BONE_TRANSFORM;   /* ensures it gets an auto key inserted */
473
474                                 BKE_armature_mat_pose_to_bone(parchan, parchan->pose_mat, rmat);
475
476                                 /* apply and decompose, doesn't work for constraints or non-uniform scale well */
477                                 {
478                                         float rmat3[3][3], qrmat[3][3], imat3[3][3], smat[3][3];
479                                         
480                                         copy_m3_m4(rmat3, rmat);
481                                         
482                                         /* rotation */
483                                         /* [#22409] is partially caused by this, as slight numeric error introduced during
484                                          * the solving process leads to locked-axis values changing. However, we cannot modify
485                                          * the values here, or else there are huge discrepancies between IK-solver (interactive)
486                                          * and applied poses.
487                                          */
488                                         if (parchan->rotmode > 0)
489                                                 mat3_to_eulO(parchan->eul, parchan->rotmode, rmat3);
490                                         else if (parchan->rotmode == ROT_MODE_AXISANGLE)
491                                                 mat3_to_axis_angle(parchan->rotAxis, &parchan->rotAngle, rmat3);
492                                         else
493                                                 mat3_to_quat(parchan->quat, rmat3);
494                                         
495                                         /* for size, remove rotation */
496                                         /* causes problems with some constraints (so apply only if needed) */
497                                         if (data->flag & CONSTRAINT_IK_STRETCH) {
498                                                 if (parchan->rotmode > 0)
499                                                         eulO_to_mat3(qrmat, parchan->eul, parchan->rotmode);
500                                                 else if (parchan->rotmode == ROT_MODE_AXISANGLE)
501                                                         axis_angle_to_mat3(qrmat, parchan->rotAxis, parchan->rotAngle);
502                                                 else
503                                                         quat_to_mat3(qrmat, parchan->quat);
504                                                 
505                                                 invert_m3_m3(imat3, qrmat);
506                                                 mul_m3_m3m3(smat, rmat3, imat3);
507                                                 mat3_to_size(parchan->size, smat);
508                                         }
509                                         
510                                         /* causes problems with some constraints (e.g. childof), so disable this */
511                                         /* as it is IK shouldn't affect location directly */
512                                         /* copy_v3_v3(parchan->loc, rmat[3]); */
513                                 }
514
515                         }
516
517                         apply = 1;
518                         data->flag &= ~CONSTRAINT_IK_AUTO;
519                 }
520         }
521
522         return apply;
523 }
524
525 static void add_pose_transdata(TransInfo *t, bPoseChannel *pchan, Object *ob, TransData *td)
526 {
527         Bone *bone = pchan->bone;
528         float pmat[3][3], omat[3][3];
529         float cmat[3][3], tmat[3][3];
530         float vec[3];
531
532         copy_v3_v3(vec, pchan->pose_mat[3]);
533         copy_v3_v3(td->center, vec);
534
535         td->ob = ob;
536         td->flag = TD_SELECTED;
537         if (bone->flag & BONE_HINGE_CHILD_TRANSFORM) {
538                 td->flag |= TD_NOCENTER;
539         }
540
541         if (bone->flag & BONE_TRANSFORM_CHILD) {
542                 td->flag |= TD_NOCENTER;
543                 td->flag |= TD_NO_LOC;
544         }
545
546         td->protectflag = pchan->protectflag;
547
548         td->loc = pchan->loc;
549         copy_v3_v3(td->iloc, pchan->loc);
550
551         td->ext->size = pchan->size;
552         copy_v3_v3(td->ext->isize, pchan->size);
553
554         if (pchan->rotmode > 0) {
555                 td->ext->rot = pchan->eul;
556                 td->ext->rotAxis = NULL;
557                 td->ext->rotAngle = NULL;
558                 td->ext->quat = NULL;
559                 
560                 copy_v3_v3(td->ext->irot, pchan->eul);
561         }
562         else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
563                 td->ext->rot = NULL;
564                 td->ext->rotAxis = pchan->rotAxis;
565                 td->ext->rotAngle = &pchan->rotAngle;
566                 td->ext->quat = NULL;
567                 
568                 td->ext->irotAngle = pchan->rotAngle;
569                 copy_v3_v3(td->ext->irotAxis, pchan->rotAxis);
570         }
571         else {
572                 td->ext->rot = NULL;
573                 td->ext->rotAxis = NULL;
574                 td->ext->rotAngle = NULL;
575                 td->ext->quat = pchan->quat;
576                 
577                 copy_qt_qt(td->ext->iquat, pchan->quat);
578         }
579         td->ext->rotOrder = pchan->rotmode;
580
581
582         /* proper way to get parent transform + own transform + constraints transform */
583         copy_m3_m4(omat, ob->obmat);
584
585         /* New code, using "generic" BKE_pchan_to_pose_mat(). */
586         {
587                 float rotscale_mat[4][4], loc_mat[4][4];
588                 float rpmat[3][3];
589
590                 BKE_pchan_to_pose_mat(pchan, rotscale_mat, loc_mat);
591                 if (t->mode == TFM_TRANSLATION)
592                         copy_m3_m4(pmat, loc_mat);
593                 else
594                         copy_m3_m4(pmat, rotscale_mat);
595
596                 /* Grrr! Exceptional case: When translating pose bones that are either Hinge or NoLocal,
597                  * and want align snapping, we just need both loc_mat and rotscale_mat.
598                  * So simply always store rotscale mat in td->ext, and always use it to apply rotations...
599                  * Ugly to need such hacks! :/ */
600                 copy_m3_m4(rpmat, rotscale_mat);
601
602                 if (constraints_list_needinv(t, &pchan->constraints)) {
603                         copy_m3_m4(tmat, pchan->constinv);
604                         invert_m3_m3(cmat, tmat);
605                         mul_m3_series(td->mtx, cmat, omat, pmat);
606                         mul_m3_series(td->ext->r_mtx, cmat, omat, rpmat);
607                 }
608                 else {
609                         mul_m3_series(td->mtx, omat, pmat);
610                         mul_m3_series(td->ext->r_mtx, omat, rpmat);
611                 }
612                 invert_m3_m3(td->ext->r_smtx, td->ext->r_mtx);
613         }
614
615         pseudoinverse_m3_m3(td->smtx, td->mtx, PSEUDOINVERSE_EPSILON);
616
617         /* exceptional case: rotate the pose bone which also applies transformation
618          * when a parentless bone has BONE_NO_LOCAL_LOCATION [] */
619         if (!ELEM(t->mode, TFM_TRANSLATION, TFM_RESIZE) && (pchan->bone->flag & BONE_NO_LOCAL_LOCATION)) {
620                 if (pchan->parent) {
621                         /* same as td->smtx but without pchan->bone->bone_mat */
622                         td->flag |= TD_PBONE_LOCAL_MTX_C;
623                         mul_m3_m3m3(td->ext->l_smtx, pchan->bone->bone_mat, td->smtx);
624                 }
625                 else {
626                         td->flag |= TD_PBONE_LOCAL_MTX_P;
627                 }
628         }
629         
630         /* for axismat we use bone's own transform */
631         copy_m3_m4(pmat, pchan->pose_mat);
632         mul_m3_m3m3(td->axismtx, omat, pmat);
633         normalize_m3(td->axismtx);
634
635         if (ELEM(t->mode, TFM_BONESIZE, TFM_BONE_ENVELOPE_DIST)) {
636                 bArmature *arm = t->poseobj->data;
637
638                 if ((t->mode == TFM_BONE_ENVELOPE_DIST) || (arm->drawtype == ARM_ENVELOPE)) {
639                         td->loc = NULL;
640                         td->val = &bone->dist;
641                         td->ival = bone->dist;
642                 }
643                 else {
644                         // abusive storage of scale in the loc pointer :)
645                         td->loc = &bone->xwidth;
646                         copy_v3_v3(td->iloc, td->loc);
647                         td->val = NULL;
648                 }
649         }
650
651         /* in this case we can do target-less IK grabbing */
652         if (t->mode == TFM_TRANSLATION) {
653                 bKinematicConstraint *data = has_targetless_ik(pchan);
654                 if (data) {
655                         if (data->flag & CONSTRAINT_IK_TIP) {
656                                 copy_v3_v3(data->grabtarget, pchan->pose_tail);
657                         }
658                         else {
659                                 copy_v3_v3(data->grabtarget, pchan->pose_head);
660                         }
661                         td->loc = data->grabtarget;
662                         copy_v3_v3(td->iloc, td->loc);
663                         data->flag |= CONSTRAINT_IK_AUTO;
664
665                         /* only object matrix correction */
666                         copy_m3_m3(td->mtx, omat);
667                         pseudoinverse_m3_m3(td->smtx, td->mtx, PSEUDOINVERSE_EPSILON);
668                 }
669         }
670
671         /* store reference to first constraint */
672         td->con = pchan->constraints.first;
673 }
674
675 static void bone_children_clear_transflag(int mode, short around, ListBase *lb)
676 {
677         Bone *bone = lb->first;
678
679         for (; bone; bone = bone->next) {
680                 if ((bone->flag & BONE_HINGE) && (bone->flag & BONE_CONNECTED)) {
681                         bone->flag |= BONE_HINGE_CHILD_TRANSFORM;
682                 }
683                 else if ((bone->flag & BONE_TRANSFORM) &&
684                          (mode == TFM_ROTATION || mode == TFM_TRACKBALL) &&
685                          (around == V3D_AROUND_LOCAL_ORIGINS))
686                 {
687                         bone->flag |= BONE_TRANSFORM_CHILD;
688                 }
689                 else {
690                         bone->flag &= ~BONE_TRANSFORM;
691                 }
692
693                 bone_children_clear_transflag(mode, around, &bone->childbase);
694         }
695 }
696
697 /* sets transform flags in the bones
698  * returns total number of bones with BONE_TRANSFORM */
699 int count_set_pose_transflags(int *out_mode, short around, Object *ob)
700 {
701         bArmature *arm = ob->data;
702         bPoseChannel *pchan;
703         Bone *bone;
704         int mode = *out_mode;
705         int total = 0;
706
707         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
708                 bone = pchan->bone;
709                 if (PBONE_VISIBLE(arm, bone)) {
710                         if ((bone->flag & BONE_SELECTED))
711                                 bone->flag |= BONE_TRANSFORM;
712                         else
713                                 bone->flag &= ~BONE_TRANSFORM;
714                         
715                         bone->flag &= ~BONE_HINGE_CHILD_TRANSFORM;
716                         bone->flag &= ~BONE_TRANSFORM_CHILD;
717                 }
718                 else
719                         bone->flag &= ~BONE_TRANSFORM;
720         }
721
722         /* make sure no bone can be transformed when a parent is transformed */
723         /* since pchans are depsgraph sorted, the parents are in beginning of list */
724         if (!ELEM(mode, TFM_BONESIZE, TFM_BONE_ENVELOPE_DIST)) {
725                 for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
726                         bone = pchan->bone;
727                         if (bone->flag & BONE_TRANSFORM)
728                                 bone_children_clear_transflag(mode, around, &bone->childbase);
729                 }
730         }
731         /* now count, and check if we have autoIK or have to switch from translate to rotate */
732         bool has_translation = false, has_rotation = false;
733
734         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
735                 bone = pchan->bone;
736                 if (bone->flag & BONE_TRANSFORM) {
737                         total++;
738                         
739                         if (mode == TFM_TRANSLATION) {
740                                 if (has_targetless_ik(pchan) == NULL) {
741                                         if (pchan->parent && (pchan->bone->flag & BONE_CONNECTED)) {
742                                                 if (pchan->bone->flag & BONE_HINGE_CHILD_TRANSFORM)
743                                                         has_translation = true;
744                                         }
745                                         else {
746                                                 if ((pchan->protectflag & OB_LOCK_LOC) != OB_LOCK_LOC)
747                                                         has_translation = true;
748                                         }
749                                         if ((pchan->protectflag & OB_LOCK_ROT) != OB_LOCK_ROT)
750                                                 has_rotation = true;
751                                 }
752                                 else
753                                         has_translation = true;
754                         }
755                 }
756         }
757
758         /* if there are no translatable bones, do rotation */
759         if (mode == TFM_TRANSLATION && !has_translation) {
760                 if (has_rotation) {
761                         *out_mode = TFM_ROTATION;
762                 }
763                 else {
764                         *out_mode = TFM_RESIZE;
765                 }
766         }
767
768         return total;
769 }
770
771
772 /* -------- Auto-IK ---------- */
773
774 /* adjust pose-channel's auto-ik chainlen */
775 static bool pchan_autoik_adjust(bPoseChannel *pchan, short chainlen)
776 {
777         bConstraint *con;
778         bool changed = false;
779
780         /* don't bother to search if no valid constraints */
781         if ((pchan->constflag & (PCHAN_HAS_IK | PCHAN_HAS_TARGET)) == 0) {
782                 return changed;
783         }
784
785         /* check if pchan has ik-constraint */
786         for (con = pchan->constraints.first; con; con = con->next) {
787                 if (con->type == CONSTRAINT_TYPE_KINEMATIC && (con->enforce != 0.0f)) {
788                         bKinematicConstraint *data = con->data;
789
790                         /* only accept if a temporary one (for auto-ik) */
791                         if (data->flag & CONSTRAINT_IK_TEMP) {
792                                 /* chainlen is new chainlen, but is limited by maximum chainlen */
793                                 const int old_rootbone = data->rootbone;
794                                 if ((chainlen == 0) || (chainlen > data->max_rootbone)) {
795                                         data->rootbone = data->max_rootbone;
796                                 }
797                                 else {
798                                         data->rootbone = chainlen;
799                                 }
800                                 changed |= (data->rootbone != old_rootbone);
801                         }
802                 }
803         }
804
805         return changed;
806 }
807
808 /* change the chain-length of auto-ik */
809 void transform_autoik_update(TransInfo *t, short mode)
810 {
811         short *chainlen = &t->settings->autoik_chainlen;
812         bPoseChannel *pchan;
813
814         /* mode determines what change to apply to chainlen */
815         if (mode == 1) {
816                 /* mode=1 is from WHEELMOUSEDOWN... increases len */
817                 (*chainlen)++;
818         }
819         else if (mode == -1) {
820                 /* mode==-1 is from WHEELMOUSEUP... decreases len */
821                 if (*chainlen > 0) {
822                         (*chainlen)--;
823                 }
824                 else {
825                         /* IK length did not change, skip updates. */
826                         return;
827                 }
828         }
829
830         /* sanity checks (don't assume t->poseobj is set, or that it is an armature) */
831         if (ELEM(NULL, t->poseobj, t->poseobj->pose))
832                 return;
833
834         /* apply to all pose-channels */
835         bool changed = false;
836         for (pchan = t->poseobj->pose->chanbase.first; pchan; pchan = pchan->next) {
837                 changed |= pchan_autoik_adjust(pchan, *chainlen);
838         }
839
840         if (changed) {
841                 /* TODO(sergey): Consider doing partial update only. */
842                 DEG_relations_tag_update(G.main);
843         }
844 }
845
846 /* frees temporal IKs */
847 static void pose_grab_with_ik_clear(Object *ob)
848 {
849         bKinematicConstraint *data;
850         bPoseChannel *pchan;
851         bConstraint *con, *next;
852         bool relations_changed = false;
853
854         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
855                 /* clear all temporary lock flags */
856                 pchan->ikflag &= ~(BONE_IK_NO_XDOF_TEMP | BONE_IK_NO_YDOF_TEMP | BONE_IK_NO_ZDOF_TEMP);
857                 
858                 pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_TARGET);
859                 
860                 /* remove all temporary IK-constraints added */
861                 for (con = pchan->constraints.first; con; con = next) {
862                         next = con->next;
863                         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
864                                 data = con->data;
865                                 if (data->flag & CONSTRAINT_IK_TEMP) {
866                                         relations_changed = true;
867
868                                         /* iTaSC needs clear for removed constraints */
869                                         BIK_clear_data(ob->pose);
870
871                                         BLI_remlink(&pchan->constraints, con);
872                                         MEM_freeN(con->data);
873                                         MEM_freeN(con);
874                                         continue;
875                                 }
876                                 pchan->constflag |= PCHAN_HAS_IK;
877                                 if (data->tar == NULL || (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0))
878                                         pchan->constflag |= PCHAN_HAS_TARGET;
879                         }
880                 }
881         }
882
883         if (relations_changed) {
884                 /* TODO(sergey): Consider doing partial update only. */
885                 DEG_relations_tag_update(G.main);
886         }
887 }
888
889 /* adds the IK to pchan - returns if added */
890 static short pose_grab_with_ik_add(bPoseChannel *pchan)
891 {
892         bKinematicConstraint *targetless = NULL;
893         bKinematicConstraint *data;
894         bConstraint *con;
895
896         /* Sanity check */
897         if (pchan == NULL)
898                 return 0;
899
900         /* Rule: not if there's already an IK on this channel */
901         for (con = pchan->constraints.first; con; con = con->next) {
902                 if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
903                         data = con->data;
904                         
905                         if (data->tar == NULL || (data->tar->type == OB_ARMATURE && data->subtarget[0] == '\0')) {
906                                 /* make reference to constraint to base things off later (if it's the last targetless constraint encountered) */
907                                 targetless = (bKinematicConstraint *)con->data;
908                                 
909                                 /* but, if this is a targetless IK, we make it auto anyway (for the children loop) */
910                                 if (con->enforce != 0.0f) {
911                                         data->flag |= CONSTRAINT_IK_AUTO;
912                                         
913                                         /* if no chain length has been specified, just make things obey standard rotation locks too */
914                                         if (data->rootbone == 0) {
915                                                 for (; pchan; pchan = pchan->parent) {
916                                                         /* here, we set ik-settings for bone from pchan->protectflag */
917                                                         // XXX: careful with quats/axis-angle rotations where we're locking 4d components
918                                                         if (pchan->protectflag & OB_LOCK_ROTX) pchan->ikflag |= BONE_IK_NO_XDOF_TEMP;
919                                                         if (pchan->protectflag & OB_LOCK_ROTY) pchan->ikflag |= BONE_IK_NO_YDOF_TEMP;
920                                                         if (pchan->protectflag & OB_LOCK_ROTZ) pchan->ikflag |= BONE_IK_NO_ZDOF_TEMP;
921                                                 }
922                                         }
923                                         
924                                         return 0; 
925                                 }
926                         }
927                         
928                         if ((con->flag & CONSTRAINT_DISABLE) == 0 && (con->enforce != 0.0f))
929                                 return 0;
930                 }
931         }
932
933         con = BKE_constraint_add_for_pose(NULL, pchan, "TempConstraint", CONSTRAINT_TYPE_KINEMATIC);
934         pchan->constflag |= (PCHAN_HAS_IK | PCHAN_HAS_TARGET);    /* for draw, but also for detecting while pose solving */
935         data = con->data;
936         if (targetless) {
937                 /* if exists, use values from last targetless (but disabled) IK-constraint as base */
938                 *data = *targetless;
939         }
940         else
941                 data->flag = CONSTRAINT_IK_TIP;
942         data->flag |= CONSTRAINT_IK_TEMP | CONSTRAINT_IK_AUTO | CONSTRAINT_IK_POS;
943         copy_v3_v3(data->grabtarget, pchan->pose_tail);
944         data->rootbone = 0; /* watch-it! has to be 0 here, since we're still on the same bone for the first time through the loop [#25885] */
945         
946         /* we only include bones that are part of a continual connected chain */
947         do {
948                 /* here, we set ik-settings for bone from pchan->protectflag */
949                 // XXX: careful with quats/axis-angle rotations where we're locking 4d components
950                 if (pchan->protectflag & OB_LOCK_ROTX) pchan->ikflag |= BONE_IK_NO_XDOF_TEMP;
951                 if (pchan->protectflag & OB_LOCK_ROTY) pchan->ikflag |= BONE_IK_NO_YDOF_TEMP;
952                 if (pchan->protectflag & OB_LOCK_ROTZ) pchan->ikflag |= BONE_IK_NO_ZDOF_TEMP;
953                 
954                 /* now we count this pchan as being included */
955                 data->rootbone++;
956                 
957                 /* continue to parent, but only if we're connected to it */
958                 if (pchan->bone->flag & BONE_CONNECTED)
959                         pchan = pchan->parent;
960                 else
961                         pchan = NULL;
962         } while (pchan);
963
964         /* make a copy of maximum chain-length */
965         data->max_rootbone = data->rootbone;
966
967         return 1;
968 }
969
970 /* bone is a candidate to get IK, but we don't do it if it has children connected */
971 static short pose_grab_with_ik_children(bPose *pose, Bone *bone)
972 {
973         Bone *bonec;
974         short wentdeeper = 0, added = 0;
975
976         /* go deeper if children & children are connected */
977         for (bonec = bone->childbase.first; bonec; bonec = bonec->next) {
978                 if (bonec->flag & BONE_CONNECTED) {
979                         wentdeeper = 1;
980                         added += pose_grab_with_ik_children(pose, bonec);
981                 }
982         }
983         if (wentdeeper == 0) {
984                 bPoseChannel *pchan = BKE_pose_channel_find_name(pose, bone->name);
985                 if (pchan)
986                         added += pose_grab_with_ik_add(pchan);
987         }
988
989         return added;
990 }
991
992 /* main call which adds temporal IK chains */
993 static short pose_grab_with_ik(Object *ob)
994 {
995         bArmature *arm;
996         bPoseChannel *pchan, *parent;
997         Bone *bonec;
998         short tot_ik = 0;
999
1000         if ((ob == NULL) || (ob->pose == NULL) || (ob->mode & OB_MODE_POSE) == 0)
1001                 return 0;
1002
1003         arm = ob->data;
1004
1005         /* Rule: allow multiple Bones (but they must be selected, and only one ik-solver per chain should get added) */
1006         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1007                 if (pchan->bone->layer & arm->layer) {
1008                         if (pchan->bone->flag & BONE_SELECTED) {
1009                                 /* Rule: no IK for solitatry (unconnected) bones */
1010                                 for (bonec = pchan->bone->childbase.first; bonec; bonec = bonec->next) {
1011                                         if (bonec->flag & BONE_CONNECTED) {
1012                                                 break;
1013                                         }
1014                                 }
1015                                 if ((pchan->bone->flag & BONE_CONNECTED) == 0 && (bonec == NULL))
1016                                         continue;
1017
1018                                 /* rule: if selected Bone is not a root bone, it gets a temporal IK */
1019                                 if (pchan->parent) {
1020                                         /* only adds if there's no IK yet (and no parent bone was selected) */
1021                                         for (parent = pchan->parent; parent; parent = parent->parent) {
1022                                                 if (parent->bone->flag & BONE_SELECTED)
1023                                                         break;
1024                                         }
1025                                         if (parent == NULL)
1026                                                 tot_ik += pose_grab_with_ik_add(pchan);
1027                                 }
1028                                 else {
1029                                         /* rule: go over the children and add IK to the tips */
1030                                         tot_ik += pose_grab_with_ik_children(ob->pose, pchan->bone);
1031                                 }
1032                         }
1033                 }
1034         }
1035
1036         /* iTaSC needs clear for new IK constraints */
1037         if (tot_ik) {
1038                 BIK_clear_data(ob->pose);
1039                 /* TODO(sergey): Consuder doing partial update only. */
1040                 DEG_relations_tag_update(G.main);
1041         }
1042
1043         return (tot_ik) ? 1 : 0;
1044 }
1045
1046
1047 /* only called with pose mode active object now */
1048 static void createTransPose(TransInfo *t, Object *ob)
1049 {
1050         bArmature *arm;
1051         bPoseChannel *pchan;
1052         TransData *td;
1053         TransDataExtension *tdx;
1054         short ik_on = 0;
1055         int i;
1056
1057         t->total = 0;
1058
1059         /* check validity of state */
1060         arm = BKE_armature_from_object(ob);
1061         if ((arm == NULL) || (ob->pose == NULL)) return;
1062
1063         if (arm->flag & ARM_RESTPOS) {
1064                 if (ELEM(t->mode, TFM_DUMMY, TFM_BONESIZE) == 0) {
1065                         BKE_report(t->reports, RPT_ERROR, "Cannot change Pose when 'Rest Position' is enabled");
1066                         return;
1067                 }
1068         }
1069
1070         /* do we need to add temporal IK chains? */
1071         if ((arm->flag & ARM_AUTO_IK) && t->mode == TFM_TRANSLATION) {
1072                 ik_on = pose_grab_with_ik(ob);
1073                 if (ik_on) t->flag |= T_AUTOIK;
1074         }
1075
1076         /* set flags and count total (warning, can change transform to rotate) */
1077         t->total = count_set_pose_transflags(&t->mode, t->around, ob);
1078
1079         if (t->total == 0) return;
1080
1081         t->flag |= T_POSE;
1082         t->poseobj = ob; /* we also allow non-active objects to be transformed, in weightpaint */
1083
1084         /* disable PET, its not usable in pose mode yet [#32444] */
1085         t->flag &= ~T_PROP_EDIT_ALL;
1086
1087         /* init trans data */
1088         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransPoseBone");
1089         tdx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension), "TransPoseBoneExt");
1090         for (i = 0; i < t->total; i++, td++, tdx++) {
1091                 td->ext = tdx;
1092                 td->val = NULL;
1093         }
1094
1095         /* use pose channels to fill trans data */
1096         td = t->data;
1097         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1098                 if (pchan->bone->flag & BONE_TRANSFORM) {
1099                         add_pose_transdata(t, pchan, ob, td);
1100                         td++;
1101                 }
1102         }
1103
1104         if (td != (t->data + t->total)) {
1105                 BKE_report(t->reports, RPT_DEBUG, "Bone selection count error");
1106         }
1107
1108         /* initialize initial auto=ik chainlen's? */
1109         if (ik_on) transform_autoik_update(t, 0);
1110 }
1111
1112 void restoreBones(TransInfo *t)
1113 {
1114         bArmature *arm = t->obedit->data;
1115         BoneInitData *bid = t->custom.type.data;
1116         EditBone *ebo;
1117
1118         while (bid->bone) {
1119                 ebo = bid->bone;
1120                 
1121                 ebo->dist = bid->dist;
1122                 ebo->rad_tail = bid->rad_tail;
1123                 ebo->roll = bid->roll;
1124                 ebo->xwidth = bid->xwidth;
1125                 ebo->zwidth = bid->zwidth;
1126                 copy_v3_v3(ebo->head, bid->head);
1127                 copy_v3_v3(ebo->tail, bid->tail);
1128                 
1129                 if (arm->flag & ARM_MIRROR_EDIT) {
1130                         EditBone *ebo_child;
1131
1132                         /* Also move connected ebo_child, in case ebo_child's name aren't mirrored properly */
1133                         for (ebo_child = arm->edbo->first; ebo_child; ebo_child = ebo_child->next) {
1134                                 if ((ebo_child->flag & BONE_CONNECTED) && (ebo_child->parent == ebo)) {
1135                                         copy_v3_v3(ebo_child->head, ebo->tail);
1136                                         ebo_child->rad_head = ebo->rad_tail;
1137                                 }
1138                         }
1139
1140                         /* Also move connected parent, in case parent's name isn't mirrored properly */
1141                         if ((ebo->flag & BONE_CONNECTED) && ebo->parent) {
1142                                 EditBone *parent = ebo->parent;
1143                                 copy_v3_v3(parent->tail, ebo->head);
1144                                 parent->rad_tail = ebo->rad_head;
1145                         }
1146                 }
1147                 
1148                 bid++;
1149         }
1150 }
1151
1152
1153 /* ********************* armature ************** */
1154 static void createTransArmatureVerts(TransInfo *t)
1155 {
1156         EditBone *ebo, *eboflip;
1157         bArmature *arm = t->obedit->data;
1158         ListBase *edbo = arm->edbo;
1159         TransData *td, *td_old;
1160         float mtx[3][3], smtx[3][3], bonemat[3][3];
1161         bool mirror = ((arm->flag & ARM_MIRROR_EDIT) != 0);
1162         int total_mirrored = 0, i;
1163         int oldtot;
1164         BoneInitData *bid;
1165         
1166         t->total = 0;
1167         for (ebo = edbo->first; ebo; ebo = ebo->next) {
1168                 oldtot = t->total;
1169
1170                 if (EBONE_VISIBLE(arm, ebo) && !(ebo->flag & BONE_EDITMODE_LOCKED)) {
1171                         if (ELEM(t->mode, TFM_BONESIZE, TFM_BONE_ENVELOPE_DIST)) {
1172                                 if (ebo->flag & BONE_SELECTED)
1173                                         t->total++;
1174                         }
1175                         else if (t->mode == TFM_BONE_ROLL) {
1176                                 if (ebo->flag & BONE_SELECTED)
1177                                         t->total++;
1178                         }
1179                         else {
1180                                 if (ebo->flag & BONE_TIPSEL)
1181                                         t->total++;
1182                                 if (ebo->flag & BONE_ROOTSEL)
1183                                         t->total++;
1184                         }
1185                 }
1186
1187                 if (mirror && (oldtot < t->total)) {
1188                         eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebo);
1189                         if (eboflip)
1190                                 total_mirrored++;
1191                 }
1192         }
1193
1194         if (!t->total) return;
1195
1196         transform_around_single_fallback(t);
1197
1198         copy_m3_m4(mtx, t->obedit->obmat);
1199         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1200
1201         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransEditBone");
1202
1203         if (mirror) {
1204                 t->custom.type.data = bid = MEM_mallocN((total_mirrored + 1) * sizeof(BoneInitData), "BoneInitData");
1205                 t->custom.type.use_free = true;
1206         }
1207
1208         i = 0;
1209
1210         for (ebo = edbo->first; ebo; ebo = ebo->next) {
1211                 td_old = td;
1212                 ebo->oldlength = ebo->length;   // length==0.0 on extrude, used for scaling radius of bone points
1213
1214                 if (EBONE_VISIBLE(arm, ebo) && !(ebo->flag & BONE_EDITMODE_LOCKED)) {
1215                         if (t->mode == TFM_BONE_ENVELOPE) {
1216                                 if (ebo->flag & BONE_ROOTSEL) {
1217                                         td->val = &ebo->rad_head;
1218                                         td->ival = *td->val;
1219
1220                                         copy_v3_v3(td->center, ebo->head);
1221                                         td->flag = TD_SELECTED;
1222
1223                                         copy_m3_m3(td->smtx, smtx);
1224                                         copy_m3_m3(td->mtx, mtx);
1225
1226                                         td->loc = NULL;
1227                                         td->ext = NULL;
1228                                         td->ob = t->obedit;
1229
1230                                         td++;
1231                                 }
1232                                 if (ebo->flag & BONE_TIPSEL) {
1233                                         td->val = &ebo->rad_tail;
1234                                         td->ival = *td->val;
1235                                         copy_v3_v3(td->center, ebo->tail);
1236                                         td->flag = TD_SELECTED;
1237
1238                                         copy_m3_m3(td->smtx, smtx);
1239                                         copy_m3_m3(td->mtx, mtx);
1240
1241                                         td->loc = NULL;
1242                                         td->ext = NULL;
1243                                         td->ob = t->obedit;
1244
1245                                         td++;
1246                                 }
1247
1248                         }
1249                         else if (ELEM(t->mode, TFM_BONESIZE, TFM_BONE_ENVELOPE_DIST)) {
1250                                 if (ebo->flag & BONE_SELECTED) {
1251                                         if ((t->mode == TFM_BONE_ENVELOPE_DIST) || (arm->drawtype == ARM_ENVELOPE)) {
1252                                                 td->loc = NULL;
1253                                                 td->val = &ebo->dist;
1254                                                 td->ival = ebo->dist;
1255                                         }
1256                                         else {
1257                                                 // abusive storage of scale in the loc pointer :)
1258                                                 td->loc = &ebo->xwidth;
1259                                                 copy_v3_v3(td->iloc, td->loc);
1260                                                 td->val = NULL;
1261                                         }
1262                                         copy_v3_v3(td->center, ebo->head);
1263                                         td->flag = TD_SELECTED;
1264
1265                                         /* use local bone matrix */
1266                                         ED_armature_ebone_to_mat3(ebo, bonemat);
1267                                         mul_m3_m3m3(td->mtx, mtx, bonemat);
1268                                         invert_m3_m3(td->smtx, td->mtx);
1269
1270                                         copy_m3_m3(td->axismtx, td->mtx);
1271                                         normalize_m3(td->axismtx);
1272
1273                                         td->ext = NULL;
1274                                         td->ob = t->obedit;
1275
1276                                         td++;
1277                                 }
1278                         }
1279                         else if (t->mode == TFM_BONE_ROLL) {
1280                                 if (ebo->flag & BONE_SELECTED) {
1281                                         td->loc = NULL;
1282                                         td->val = &(ebo->roll);
1283                                         td->ival = ebo->roll;
1284
1285                                         copy_v3_v3(td->center, ebo->head);
1286                                         td->flag = TD_SELECTED;
1287
1288                                         td->ext = NULL;
1289                                         td->ob = t->obedit;
1290
1291                                         td++;
1292                                 }
1293                         }
1294                         else {
1295                                 if (ebo->flag & BONE_TIPSEL) {
1296                                         copy_v3_v3(td->iloc, ebo->tail);
1297
1298                                         /* Don't allow single selected tips to have a modified center,
1299                                          * causes problem with snapping (see T45974).
1300                                          * However, in rotation mode, we want to keep that 'rotate bone around root with
1301                                          * only its tip selected' behavior (see T46325). */
1302                                         if ((t->around == V3D_AROUND_LOCAL_ORIGINS) &&
1303                                             ((t->mode == TFM_ROTATION) || (ebo->flag & BONE_ROOTSEL)))
1304                                         {
1305                                                 copy_v3_v3(td->center, ebo->head);
1306                                         }
1307                                         else {
1308                                                 copy_v3_v3(td->center, td->iloc);
1309                                         }
1310
1311                                         td->loc = ebo->tail;
1312                                         td->flag = TD_SELECTED;
1313                                         if (ebo->flag & BONE_EDITMODE_LOCKED)
1314                                                 td->protectflag = OB_LOCK_LOC | OB_LOCK_ROT | OB_LOCK_SCALE;
1315
1316                                         copy_m3_m3(td->smtx, smtx);
1317                                         copy_m3_m3(td->mtx, mtx);
1318
1319                                         ED_armature_ebone_to_mat3(ebo, td->axismtx);
1320
1321                                         if ((ebo->flag & BONE_ROOTSEL) == 0) {
1322                                                 td->extra = ebo;
1323                                                 td->ival = ebo->roll;
1324                                         }
1325
1326                                         td->ext = NULL;
1327                                         td->val = NULL;
1328                                         td->ob = t->obedit;
1329
1330                                         td++;
1331                                 }
1332                                 if (ebo->flag & BONE_ROOTSEL) {
1333                                         copy_v3_v3(td->iloc, ebo->head);
1334                                         copy_v3_v3(td->center, td->iloc);
1335                                         td->loc = ebo->head;
1336                                         td->flag = TD_SELECTED;
1337                                         if (ebo->flag & BONE_EDITMODE_LOCKED)
1338                                                 td->protectflag = OB_LOCK_LOC | OB_LOCK_ROT | OB_LOCK_SCALE;
1339
1340                                         copy_m3_m3(td->smtx, smtx);
1341                                         copy_m3_m3(td->mtx, mtx);
1342
1343                                         ED_armature_ebone_to_mat3(ebo, td->axismtx);
1344
1345                                         td->extra = ebo; /* to fix roll */
1346                                         td->ival = ebo->roll;
1347
1348                                         td->ext = NULL;
1349                                         td->val = NULL;
1350                                         td->ob = t->obedit;
1351
1352                                         td++;
1353                                 }
1354                         }
1355                 }
1356
1357                 if (mirror && (td_old != td)) {
1358                         eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebo);
1359                         if (eboflip) {
1360                                 bid[i].bone = eboflip;
1361                                 bid[i].dist = eboflip->dist;
1362                                 bid[i].rad_tail = eboflip->rad_tail;
1363                                 bid[i].roll = eboflip->roll;
1364                                 bid[i].xwidth = eboflip->xwidth;
1365                                 bid[i].zwidth = eboflip->zwidth;
1366                                 copy_v3_v3(bid[i].head, eboflip->head);
1367                                 copy_v3_v3(bid[i].tail, eboflip->tail);
1368                                 i++;
1369                         }
1370                 }
1371         }
1372
1373         if (mirror) {
1374                 /* trick to terminate iteration */
1375                 bid[total_mirrored].bone = NULL;
1376         }
1377 }
1378
1379 /* ********************* meta elements ********* */
1380
1381 static void createTransMBallVerts(TransInfo *t)
1382 {
1383         MetaBall *mb = (MetaBall *)t->obedit->data;
1384         MetaElem *ml;
1385         TransData *td;
1386         TransDataExtension *tx;
1387         float mtx[3][3], smtx[3][3];
1388         int count = 0, countsel = 0;
1389         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1390
1391         /* count totals */
1392         for (ml = mb->editelems->first; ml; ml = ml->next) {
1393                 if (ml->flag & SELECT) countsel++;
1394                 if (is_prop_edit) count++;
1395         }
1396
1397         /* note: in prop mode we need at least 1 selected */
1398         if (countsel == 0) return;
1399
1400         if (is_prop_edit) t->total = count;
1401         else t->total = countsel;
1402
1403         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(MBall EditMode)");
1404         tx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension), "MetaElement_TransExtension");
1405
1406         copy_m3_m4(mtx, t->obedit->obmat);
1407         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1408
1409         for (ml = mb->editelems->first; ml; ml = ml->next) {
1410                 if (is_prop_edit || (ml->flag & SELECT)) {
1411                         td->loc = &ml->x;
1412                         copy_v3_v3(td->iloc, td->loc);
1413                         copy_v3_v3(td->center, td->loc);
1414
1415                         quat_to_mat3(td->axismtx, ml->quat);
1416
1417                         if (ml->flag & SELECT) td->flag = TD_SELECTED | TD_USEQUAT | TD_SINGLESIZE;
1418                         else td->flag = TD_USEQUAT;
1419
1420                         copy_m3_m3(td->smtx, smtx);
1421                         copy_m3_m3(td->mtx, mtx);
1422
1423                         td->ext = tx;
1424
1425                         /* Radius of MetaElem (mass of MetaElem influence) */
1426                         if (ml->flag & MB_SCALE_RAD) {
1427                                 td->val = &ml->rad;
1428                                 td->ival = ml->rad;
1429                         }
1430                         else {
1431                                 td->val = &ml->s;
1432                                 td->ival = ml->s;
1433                         }
1434
1435                         /* expx/expy/expz determine "shape" of some MetaElem types */
1436                         tx->size = &ml->expx;
1437                         tx->isize[0] = ml->expx;
1438                         tx->isize[1] = ml->expy;
1439                         tx->isize[2] = ml->expz;
1440
1441                         /* quat is used for rotation of MetaElem */
1442                         tx->quat = ml->quat;
1443                         copy_qt_qt(tx->iquat, ml->quat);
1444
1445                         tx->rot = NULL;
1446
1447                         td++;
1448                         tx++;
1449                 }
1450         }
1451 }
1452
1453 /* ********************* curve/surface ********* */
1454
1455 static void calc_distanceCurveVerts(TransData *head, TransData *tail)
1456 {
1457         TransData *td, *td_near = NULL;
1458         for (td = head; td <= tail; td++) {
1459                 if (td->flag & TD_SELECTED) {
1460                         td_near = td;
1461                         td->dist = 0.0f;
1462                 }
1463                 else if (td_near) {
1464                         float dist;
1465                         dist = len_v3v3(td_near->center, td->center);
1466                         if (dist < (td - 1)->dist) {
1467                                 td->dist = (td - 1)->dist;
1468                         }
1469                         else {
1470                                 td->dist = dist;
1471                         }
1472                 }
1473                 else {
1474                         td->dist = FLT_MAX;
1475                         td->flag |= TD_NOTCONNECTED;
1476                 }
1477         }
1478         td_near = NULL;
1479         for (td = tail; td >= head; td--) {
1480                 if (td->flag & TD_SELECTED) {
1481                         td_near = td;
1482                         td->dist = 0.0f;
1483                 }
1484                 else if (td_near) {
1485                         float dist;
1486                         dist = len_v3v3(td_near->center, td->center);
1487                         if (td->flag & TD_NOTCONNECTED || dist < td->dist || (td + 1)->dist < td->dist) {
1488                                 td->flag &= ~TD_NOTCONNECTED;
1489                                 if (dist < (td + 1)->dist) {
1490                                         td->dist = (td + 1)->dist;
1491                                 }
1492                                 else {
1493                                         td->dist = dist;
1494                                 }
1495                         }
1496                 }
1497         }
1498 }
1499
1500 /* Utility function for getting the handle data from bezier's */
1501 static TransDataCurveHandleFlags *initTransDataCurveHandles(TransData *td, struct BezTriple *bezt)
1502 {
1503         TransDataCurveHandleFlags *hdata;
1504         td->flag |= TD_BEZTRIPLE;
1505         hdata = td->hdata = MEM_mallocN(sizeof(TransDataCurveHandleFlags), "CuHandle Data");
1506         hdata->ih1 = bezt->h1;
1507         hdata->h1 = &bezt->h1;
1508         hdata->ih2 = bezt->h2; /* in case the second is not selected */
1509         hdata->h2 = &bezt->h2;
1510         return hdata;
1511 }
1512
1513 /**
1514  * For the purpose of transform code we need to behave as if handles are selected,
1515  * even when they aren't (see special case below).
1516  */
1517 static int bezt_select_to_transform_triple_flag(
1518         const BezTriple *bezt, const bool hide_handles)
1519 {
1520         int flag = 0;
1521
1522         if (hide_handles) {
1523                 if (bezt->f2 & SELECT) {
1524                         flag = (1 << 0) | (1 << 1) | (1 << 2);
1525                 }
1526         }
1527         else {
1528                 flag = (
1529                         ((bezt->f1 & SELECT) ? (1 << 0) : 0) |
1530                         ((bezt->f2 & SELECT) ? (1 << 1) : 0) |
1531                         ((bezt->f3 & SELECT) ? (1 << 2) : 0)
1532                 );
1533         }
1534
1535         /* Special case for auto & aligned handles:
1536          * When a center point is being moved without the handles,
1537          * leaving the handles stationary makes no sense and only causes strange behavior,
1538          * where one handle is arbitrarily anchored, the other one is aligned and lengthened
1539          * based on where the center point is moved. Also a bug when cancelling, see: T52007.
1540          *
1541          * A more 'correct' solution could be to store handle locations in 'TransDataCurveHandleFlags'.
1542          * However that doesn't resolve odd behavior, so best transform the handles in this case.
1543          */
1544         if ((flag != ((1 << 0) | (1 << 1) | (1 << 2))) && (flag & (1 << 1))) {
1545                 if (ELEM(bezt->h1, HD_AUTO, HD_ALIGN) &&
1546                     ELEM(bezt->h2, HD_AUTO, HD_ALIGN))
1547                 {
1548                         flag = (1 << 0) | (1 << 1) | (1 << 2);
1549                 }
1550         }
1551
1552         return flag;
1553 }
1554
1555 static void createTransCurveVerts(TransInfo *t)
1556 {
1557         Curve *cu = t->obedit->data;
1558         TransData *td = NULL;
1559         Nurb *nu;
1560         BezTriple *bezt;
1561         BPoint *bp;
1562         float mtx[3][3], smtx[3][3];
1563         int a;
1564         int count = 0, countsel = 0;
1565         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1566         short hide_handles = (cu->drawflag & CU_HIDE_HANDLES);
1567         ListBase *nurbs;
1568
1569         /* to be sure */
1570         if (cu->editnurb == NULL) return;
1571
1572 #define SEL_F1 (1 << 0)
1573 #define SEL_F2 (1 << 1)
1574 #define SEL_F3 (1 << 2)
1575
1576         /* count total of vertices, check identical as in 2nd loop for making transdata! */
1577         nurbs = BKE_curve_editNurbs_get(cu);
1578         for (nu = nurbs->first; nu; nu = nu->next) {
1579                 if (nu->type == CU_BEZIER) {
1580                         for (a = 0, bezt = nu->bezt; a < nu->pntsu; a++, bezt++) {
1581                                 if (bezt->hide == 0) {
1582                                         const int bezt_tx = bezt_select_to_transform_triple_flag(bezt, hide_handles);
1583                                         if (bezt_tx & SEL_F1) { countsel++; }
1584                                         if (bezt_tx & SEL_F2) { countsel++; }
1585                                         if (bezt_tx & SEL_F3) { countsel++; }
1586                                         if (is_prop_edit) count += 3;
1587
1588                                 }
1589                         }
1590                 }
1591                 else {
1592                         for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a > 0; a--, bp++) {
1593                                 if (bp->hide == 0) {
1594                                         if (is_prop_edit) count++;
1595                                         if (bp->f1 & SELECT) countsel++;
1596                                 }
1597                         }
1598                 }
1599         }
1600         /* note: in prop mode we need at least 1 selected */
1601         if (countsel == 0) return;
1602
1603         if (is_prop_edit) t->total = count;
1604         else t->total = countsel;
1605         t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Curve EditMode)");
1606
1607         transform_around_single_fallback(t);
1608
1609         copy_m3_m4(mtx, t->obedit->obmat);
1610         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1611
1612         td = t->data;
1613         for (nu = nurbs->first; nu; nu = nu->next) {
1614                 if (nu->type == CU_BEZIER) {
1615                         TransData *head, *tail;
1616                         head = tail = td;
1617                         for (a = 0, bezt = nu->bezt; a < nu->pntsu; a++, bezt++) {
1618                                 if (bezt->hide == 0) {
1619                                         TransDataCurveHandleFlags *hdata = NULL;
1620                                         float axismtx[3][3];
1621
1622                                         if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1623                                                 float normal[3], plane[3];
1624
1625                                                 BKE_nurb_bezt_calc_normal(nu, bezt, normal);
1626                                                 BKE_nurb_bezt_calc_plane(nu, bezt, plane);
1627
1628                                                 if (createSpaceNormalTangent(axismtx, normal, plane)) {
1629                                                         /* pass */
1630                                                 }
1631                                                 else {
1632                                                         normalize_v3(normal);
1633                                                         axis_dominant_v3_to_m3(axismtx, normal);
1634                                                         invert_m3(axismtx);
1635                                                 }
1636                                         }
1637
1638                                         /* Elements that will be transform (not always a match to selection). */
1639                                         const int bezt_tx = bezt_select_to_transform_triple_flag(bezt, hide_handles);
1640
1641                                         if (is_prop_edit || bezt_tx & SEL_F1) {
1642                                                 copy_v3_v3(td->iloc, bezt->vec[0]);
1643                                                 td->loc = bezt->vec[0];
1644                                                 copy_v3_v3(td->center, bezt->vec[(hide_handles ||
1645                                                                                   (t->around == V3D_AROUND_LOCAL_ORIGINS) ||
1646                                                                                   (bezt->f2 & SELECT)) ? 1 : 0]);
1647                                                 if (hide_handles) {
1648                                                         if (bezt->f2 & SELECT) td->flag = TD_SELECTED;
1649                                                         else td->flag = 0;
1650                                                 }
1651                                                 else {
1652                                                         if (bezt->f1 & SELECT) td->flag = TD_SELECTED;
1653                                                         else td->flag = 0;
1654                                                 }
1655                                                 td->ext = NULL;
1656                                                 td->val = NULL;
1657
1658                                                 hdata = initTransDataCurveHandles(td, bezt);
1659
1660                                                 copy_m3_m3(td->smtx, smtx);
1661                                                 copy_m3_m3(td->mtx, mtx);
1662                                                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1663                                                         copy_m3_m3(td->axismtx, axismtx);
1664                                                 }
1665
1666                                                 td++;
1667                                                 count++;
1668                                                 tail++;
1669                                         }
1670
1671                                         /* This is the Curve Point, the other two are handles */
1672                                         if (is_prop_edit || bezt_tx & SEL_F2) {
1673                                                 copy_v3_v3(td->iloc, bezt->vec[1]);
1674                                                 td->loc = bezt->vec[1];
1675                                                 copy_v3_v3(td->center, td->loc);
1676                                                 if (bezt->f2 & SELECT) td->flag = TD_SELECTED;
1677                                                 else td->flag = 0;
1678                                                 td->ext = NULL;
1679
1680                                                 if (t->mode == TFM_CURVE_SHRINKFATTEN) { /* || t->mode==TFM_RESIZE) {*/ /* TODO - make points scale */
1681                                                         td->val = &(bezt->radius);
1682                                                         td->ival = bezt->radius;
1683                                                 }
1684                                                 else if (t->mode == TFM_TILT) {
1685                                                         td->val = &(bezt->alfa);
1686                                                         td->ival = bezt->alfa;
1687                                                 }
1688                                                 else {
1689                                                         td->val = NULL;
1690                                                 }
1691
1692                                                 copy_m3_m3(td->smtx, smtx);
1693                                                 copy_m3_m3(td->mtx, mtx);
1694                                                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1695                                                         copy_m3_m3(td->axismtx, axismtx);
1696                                                 }
1697
1698                                                 if ((bezt_tx & SEL_F1) == 0 && (bezt_tx & SEL_F3) == 0)
1699                                                         /* If the middle is selected but the sides arnt, this is needed */
1700                                                         if (hdata == NULL) { /* if the handle was not saved by the previous handle */
1701                                                                 hdata = initTransDataCurveHandles(td, bezt);
1702                                                         }
1703
1704                                                 td++;
1705                                                 count++;
1706                                                 tail++;
1707                                         }
1708                                         if (is_prop_edit || bezt_tx & SEL_F3) {
1709                                                 copy_v3_v3(td->iloc, bezt->vec[2]);
1710                                                 td->loc = bezt->vec[2];
1711                                                 copy_v3_v3(td->center, bezt->vec[(hide_handles ||
1712                                                                                   (t->around == V3D_AROUND_LOCAL_ORIGINS) ||
1713                                                                                   (bezt->f2 & SELECT)) ? 1 : 2]);
1714                                                 if (hide_handles) {
1715                                                         if (bezt->f2 & SELECT) td->flag = TD_SELECTED;
1716                                                         else td->flag = 0;
1717                                                 }
1718                                                 else {
1719                                                         if (bezt->f3 & SELECT) td->flag = TD_SELECTED;
1720                                                         else td->flag = 0;
1721                                                 }
1722                                                 td->ext = NULL;
1723                                                 td->val = NULL;
1724
1725                                                 if (hdata == NULL) { /* if the handle was not saved by the previous handle */
1726                                                         hdata = initTransDataCurveHandles(td, bezt);
1727                                                 }
1728
1729                                                 copy_m3_m3(td->smtx, smtx);
1730                                                 copy_m3_m3(td->mtx, mtx);
1731                                                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1732                                                         copy_m3_m3(td->axismtx, axismtx);
1733                                                 }
1734
1735                                                 td++;
1736                                                 count++;
1737                                                 tail++;
1738                                         }
1739
1740                                         (void)hdata;  /* quiet warning */
1741                                 }
1742                                 else if (is_prop_edit && head != tail) {
1743                                         calc_distanceCurveVerts(head, tail - 1);
1744                                         head = tail;
1745                                 }
1746                         }
1747                         if (is_prop_edit && head != tail)
1748                                 calc_distanceCurveVerts(head, tail - 1);
1749
1750                         /* TODO - in the case of tilt and radius we can also avoid allocating the initTransDataCurveHandles
1751                          * but for now just don't change handle types */
1752                         if (ELEM(t->mode, TFM_CURVE_SHRINKFATTEN, TFM_TILT, TFM_DUMMY) == 0) {
1753                                 /* sets the handles based on their selection, do this after the data is copied to the TransData */
1754                                 BKE_nurb_handles_test(nu, !hide_handles);
1755                         }
1756                 }
1757                 else {
1758                         TransData *head, *tail;
1759                         head = tail = td;
1760                         for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a > 0; a--, bp++) {
1761                                 if (bp->hide == 0) {
1762                                         if (is_prop_edit || (bp->f1 & SELECT)) {
1763                                                 float axismtx[3][3];
1764
1765                                                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1766                                                         if (nu->pntsv == 1) {
1767                                                                 float normal[3], plane[3];
1768
1769                                                                 BKE_nurb_bpoint_calc_normal(nu, bp, normal);
1770                                                                 BKE_nurb_bpoint_calc_plane(nu, bp, plane);
1771
1772                                                                 if (createSpaceNormalTangent(axismtx, normal, plane)) {
1773                                                                         /* pass */
1774                                                                 }
1775                                                                 else {
1776                                                                         normalize_v3(normal);
1777                                                                         axis_dominant_v3_to_m3(axismtx, normal);
1778                                                                         invert_m3(axismtx);
1779                                                                 }
1780                                                         }
1781                                                 }
1782
1783                                                 copy_v3_v3(td->iloc, bp->vec);
1784                                                 td->loc = bp->vec;
1785                                                 copy_v3_v3(td->center, td->loc);
1786                                                 if (bp->f1 & SELECT) td->flag = TD_SELECTED;
1787                                                 else td->flag = 0;
1788                                                 td->ext = NULL;
1789
1790                                                 if (t->mode == TFM_CURVE_SHRINKFATTEN || t->mode == TFM_RESIZE) {
1791                                                         td->val = &(bp->radius);
1792                                                         td->ival = bp->radius;
1793                                                 }
1794                                                 else {
1795                                                         td->val = &(bp->alfa);
1796                                                         td->ival = bp->alfa;
1797                                                 }
1798
1799                                                 copy_m3_m3(td->smtx, smtx);
1800                                                 copy_m3_m3(td->mtx, mtx);
1801                                                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1802                                                         if (nu->pntsv == 1) {
1803                                                                 copy_m3_m3(td->axismtx, axismtx);
1804                                                         }
1805                                                 }
1806
1807                                                 td++;
1808                                                 count++;
1809                                                 tail++;
1810                                         }
1811                                 }
1812                                 else if (is_prop_edit && head != tail) {
1813                                         calc_distanceCurveVerts(head, tail - 1);
1814                                         head = tail;
1815                                 }
1816                         }
1817                         if (is_prop_edit && head != tail)
1818                                 calc_distanceCurveVerts(head, tail - 1);
1819                 }
1820         }
1821
1822 #undef SEL_F1
1823 #undef SEL_F2
1824 #undef SEL_F3
1825 }
1826
1827 /* ********************* lattice *************** */
1828
1829 static void createTransLatticeVerts(TransInfo *t)
1830 {
1831         Lattice *latt = ((Lattice *)t->obedit->data)->editlatt->latt;
1832         TransData *td = NULL;
1833         BPoint *bp;
1834         float mtx[3][3], smtx[3][3];
1835         int a;
1836         int count = 0, countsel = 0;
1837         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1838
1839         bp = latt->def;
1840         a  = latt->pntsu * latt->pntsv * latt->pntsw;
1841         while (a--) {
1842                 if (bp->hide == 0) {
1843                         if (bp->f1 & SELECT) countsel++;
1844                         if (is_prop_edit) count++;
1845                 }
1846                 bp++;
1847         }
1848
1849         /* note: in prop mode we need at least 1 selected */
1850         if (countsel == 0) return;
1851
1852         if (is_prop_edit) t->total = count;
1853         else t->total = countsel;
1854         t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Lattice EditMode)");
1855
1856         copy_m3_m4(mtx, t->obedit->obmat);
1857         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1858
1859         td = t->data;
1860         bp = latt->def;
1861         a  = latt->pntsu * latt->pntsv * latt->pntsw;
1862         while (a--) {
1863                 if (is_prop_edit || (bp->f1 & SELECT)) {
1864                         if (bp->hide == 0) {
1865                                 copy_v3_v3(td->iloc, bp->vec);
1866                                 td->loc = bp->vec;
1867                                 copy_v3_v3(td->center, td->loc);
1868                                 if (bp->f1 & SELECT) {
1869                                         td->flag = TD_SELECTED;
1870                                 }
1871                                 else {
1872                                         td->flag = 0;
1873                                 }
1874                                 copy_m3_m3(td->smtx, smtx);
1875                                 copy_m3_m3(td->mtx, mtx);
1876
1877                                 td->ext = NULL;
1878                                 td->val = NULL;
1879
1880                                 td++;
1881                                 count++;
1882                         }
1883                 }
1884                 bp++;
1885         }
1886 }
1887
1888 /* ******************* particle edit **************** */
1889 static void createTransParticleVerts(bContext *C, TransInfo *t)
1890 {
1891         TransData *td = NULL;
1892         TransDataExtension *tx;
1893         Object *ob = CTX_data_active_object(C);
1894         ParticleEditSettings *pset = PE_settings(t->scene);
1895         PTCacheEdit *edit = PE_get_current(t->scene, t->view_layer, ob);
1896         ParticleSystem *psys = NULL;
1897         ParticleSystemModifierData *psmd = NULL;
1898         PTCacheEditPoint *point;
1899         PTCacheEditKey *key;
1900         float mat[4][4];
1901         int i, k, transformparticle;
1902         int count = 0, hasselected = 0;
1903         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1904
1905         if (edit == NULL || t->settings->particle.selectmode == SCE_SELECT_PATH) return;
1906
1907         psys = edit->psys;
1908
1909         if (psys)
1910                 psmd = psys_get_modifier(ob, psys);
1911
1912         for (i = 0, point = edit->points; i < edit->totpoint; i++, point++) {
1913                 point->flag &= ~PEP_TRANSFORM;
1914                 transformparticle = 0;
1915
1916                 if ((point->flag & PEP_HIDE) == 0) {
1917                         for (k = 0, key = point->keys; k < point->totkey; k++, key++) {
1918                                 if ((key->flag & PEK_HIDE) == 0) {
1919                                         if (key->flag & PEK_SELECT) {
1920                                                 hasselected = 1;
1921                                                 transformparticle = 1;
1922                                         }
1923                                         else if (is_prop_edit)
1924                                                 transformparticle = 1;
1925                                 }
1926                         }
1927                 }
1928
1929                 if (transformparticle) {
1930                         count += point->totkey;
1931                         point->flag |= PEP_TRANSFORM;
1932                 }
1933         }
1934
1935         /* note: in prop mode we need at least 1 selected */
1936         if (hasselected == 0) return;
1937
1938         t->total = count;
1939         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Particle Mode)");
1940
1941         if (t->mode == TFM_BAKE_TIME)
1942                 tx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension), "Particle_TransExtension");
1943         else
1944                 tx = t->ext = NULL;
1945
1946         unit_m4(mat);
1947
1948         invert_m4_m4(ob->imat, ob->obmat);
1949
1950         for (i = 0, point = edit->points; i < edit->totpoint; i++, point++) {
1951                 TransData *head, *tail;
1952                 head = tail = td;
1953
1954                 if (!(point->flag & PEP_TRANSFORM)) continue;
1955
1956                 if (psys && !(psys->flag & PSYS_GLOBAL_HAIR))
1957                         psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, psys->particles + i, mat);
1958
1959                 for (k = 0, key = point->keys; k < point->totkey; k++, key++) {
1960                         if (key->flag & PEK_USE_WCO) {
1961                                 copy_v3_v3(key->world_co, key->co);
1962                                 mul_m4_v3(mat, key->world_co);
1963                                 td->loc = key->world_co;
1964                         }
1965                         else
1966                                 td->loc = key->co;
1967
1968                         copy_v3_v3(td->iloc, td->loc);
1969                         copy_v3_v3(td->center, td->loc);
1970
1971                         if (key->flag & PEK_SELECT)
1972                                 td->flag |= TD_SELECTED;
1973                         else if (!is_prop_edit)
1974                                 td->flag |= TD_SKIP;
1975
1976                         unit_m3(td->mtx);
1977                         unit_m3(td->smtx);
1978
1979                         /* don't allow moving roots */
1980                         if (k == 0 && pset->flag & PE_LOCK_FIRST && (!psys || !(psys->flag & PSYS_GLOBAL_HAIR)))
1981                                 td->protectflag |= OB_LOCK_LOC;
1982
1983                         td->ob = ob;
1984                         td->ext = tx;
1985                         if (t->mode == TFM_BAKE_TIME) {
1986                                 td->val = key->time;
1987                                 td->ival = *(key->time);
1988                                 /* abuse size and quat for min/max values */
1989                                 td->flag |= TD_NO_EXT;
1990                                 if (k == 0) tx->size = NULL;
1991                                 else tx->size = (key - 1)->time;
1992
1993                                 if (k == point->totkey - 1) tx->quat = NULL;
1994                                 else tx->quat = (key + 1)->time;
1995                         }
1996
1997                         td++;
1998                         if (tx)
1999                                 tx++;
2000                         tail++;
2001                 }
2002                 if (is_prop_edit && head != tail)
2003                         calc_distanceCurveVerts(head, tail - 1);
2004         }
2005 }
2006
2007 void flushTransParticles(TransInfo *t)
2008 {
2009         Scene *scene = t->scene;
2010         ViewLayer *view_layer = t->view_layer;
2011         Object *ob = OBACT(view_layer);
2012         PTCacheEdit *edit = PE_get_current(scene, view_layer, ob);
2013         ParticleSystem *psys = edit->psys;
2014         ParticleSystemModifierData *psmd = NULL;
2015         PTCacheEditPoint *point;
2016         PTCacheEditKey *key;
2017         TransData *td;
2018         float mat[4][4], imat[4][4], co[3];
2019         int i, k;
2020         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
2021
2022         if (psys)
2023                 psmd = psys_get_modifier(ob, psys);
2024
2025         /* we do transform in world space, so flush world space position
2026          * back to particle local space (only for hair particles) */
2027         td = t->data;
2028         for (i = 0, point = edit->points; i < edit->totpoint; i++, point++, td++) {
2029                 if (!(point->flag & PEP_TRANSFORM)) continue;
2030
2031                 if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) {
2032                         psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, psys->particles + i, mat);
2033                         invert_m4_m4(imat, mat);
2034
2035                         for (k = 0, key = point->keys; k < point->totkey; k++, key++) {
2036                                 copy_v3_v3(co, key->world_co);
2037                                 mul_m4_v3(imat, co);
2038
2039
2040                                 /* optimization for proportional edit */
2041                                 if (!is_prop_edit || !compare_v3v3(key->co, co, 0.0001f)) {
2042                                         copy_v3_v3(key->co, co);
2043                                         point->flag |= PEP_EDIT_RECALC;
2044                                 }
2045                         }
2046                 }
2047                 else
2048                         point->flag |= PEP_EDIT_RECALC;
2049         }
2050
2051         EvaluationContext eval_ctx;
2052         CTX_data_eval_ctx(t->context, &eval_ctx);
2053         PE_update_object(&eval_ctx, scene, view_layer, OBACT(view_layer), 1);
2054 }
2055
2056 /* ********************* mesh ****************** */
2057
2058 static bool bmesh_test_dist_add(
2059         BMVert *v, BMVert *v_other,
2060         float *dists, const float *dists_prev,
2061         /* optionally track original index */
2062         int *index, const int *index_prev,
2063         float mtx[3][3])
2064 {
2065         if ((BM_elem_flag_test(v_other, BM_ELEM_SELECT) == 0) &&
2066             (BM_elem_flag_test(v_other, BM_ELEM_HIDDEN) == 0))
2067         {
2068                 const int i = BM_elem_index_get(v);
2069                 const int i_other = BM_elem_index_get(v_other);
2070                 float vec[3];
2071                 float dist_other;
2072                 sub_v3_v3v3(vec, v->co, v_other->co);
2073                 mul_m3_v3(mtx, vec);
2074
2075                 dist_other = dists_prev[i] + len_v3(vec);
2076                 if (dist_other < dists[i_other]) {
2077                         dists[i_other] = dist_other;
2078                         if (index != NULL) {
2079                                 index[i_other] = index_prev[i];
2080                         }
2081                         return true;
2082                 }
2083         }
2084
2085         return false;
2086 }
2087
2088 /**
2089  * \param mtx: Measure disatnce in this space.
2090  * \param dists: Store the closest connected distance to selected vertices.
2091  * \param index: Optionally store the original index we're measuring the distance to (can be NULL).
2092  */
2093 static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float *dists, int *index)
2094 {
2095         BLI_LINKSTACK_DECLARE(queue, BMVert *);
2096
2097         /* any BM_ELEM_TAG'd vertex is in 'queue_next', so we don't add in twice */
2098         BLI_LINKSTACK_DECLARE(queue_next, BMVert *);
2099
2100         BLI_LINKSTACK_INIT(queue);
2101         BLI_LINKSTACK_INIT(queue_next);
2102
2103         {
2104                 BMIter viter;
2105                 BMVert *v;
2106                 int i;
2107
2108                 BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
2109                         float dist;
2110                         BM_elem_index_set(v, i); /* set_inline */
2111                         BM_elem_flag_disable(v, BM_ELEM_TAG);
2112
2113                         if (BM_elem_flag_test(v, BM_ELEM_SELECT) == 0 || BM_elem_flag_test(v, BM_ELEM_HIDDEN)) {
2114                                 dist = FLT_MAX;
2115                                 if (index != NULL) {
2116                                         index[i] = i;
2117                                 }
2118                         }
2119                         else {
2120                                 BLI_LINKSTACK_PUSH(queue, v);
2121                                 dist = 0.0f;
2122                                 if (index != NULL) {
2123                                         index[i] = i;
2124                                 }
2125                         }
2126
2127                         dists[i] = dist;
2128                 }
2129                 bm->elem_index_dirty &= ~BM_VERT;
2130         }
2131
2132         /* need to be very careful of feedback loops here, store previous dist's to avoid feedback */
2133         float *dists_prev = MEM_dupallocN(dists);
2134         int *index_prev = MEM_dupallocN(index);  /* may be NULL */
2135
2136         do {
2137                 BMVert *v;
2138                 LinkNode *lnk;
2139
2140                 /* this is correct but slow to do each iteration,
2141                  * instead sync the dist's while clearing BM_ELEM_TAG (below) */
2142 #if 0
2143                 memcpy(dists_prev, dists, sizeof(float) * bm->totvert);
2144 #endif
2145
2146                 while ((v = BLI_LINKSTACK_POP(queue))) {
2147                         BLI_assert(dists[BM_elem_index_get(v)] != FLT_MAX);
2148
2149                         /* connected edge-verts */
2150                         if (v->e != NULL) {
2151                                 BMEdge *e_iter, *e_first;
2152
2153                                 e_iter = e_first = v->e;
2154
2155                                 /* would normally use BM_EDGES_OF_VERT, but this runs so often,
2156                                  * its faster to iterate on the data directly */
2157                                 do {
2158
2159                                         if (BM_elem_flag_test(e_iter, BM_ELEM_HIDDEN) == 0) {
2160
2161                                                 /* edge distance */
2162                                                 {
2163                                                         BMVert *v_other = BM_edge_other_vert(e_iter, v);
2164                                                         if (bmesh_test_dist_add(v, v_other, dists, dists_prev, index, index_prev, mtx)) {
2165                                                                 if (BM_elem_flag_test(v_other, BM_ELEM_TAG) == 0) {
2166                                                                         BM_elem_flag_enable(v_other, BM_ELEM_TAG);
2167                                                                         BLI_LINKSTACK_PUSH(queue_next, v_other);
2168                                                                 }
2169                                                         }
2170                                                 }
2171
2172                                                 /* face distance */
2173                                                 if (e_iter->l) {
2174                                                         BMLoop *l_iter_radial, *l_first_radial;
2175                                                         /**
2176                                                          * imaginary edge diagonally across quad,
2177                                                          * \note, this takes advantage of the rules of winding that we
2178                                                          * know 2 or more of a verts edges wont reference the same face twice.
2179                                                          * Also, if the edge is hidden, the face will be hidden too.
2180                                                          */
2181                                                         l_iter_radial = l_first_radial = e_iter->l;
2182
2183                                                         do {
2184                                                                 if ((l_iter_radial->v == v) &&
2185                                                                     (l_iter_radial->f->len == 4) &&
2186                                                                     (BM_elem_flag_test(l_iter_radial->f, BM_ELEM_HIDDEN) == 0))
2187                                                                 {
2188                                                                         BMVert *v_other = l_iter_radial->next->next->v;
2189                                                                         if (bmesh_test_dist_add(v, v_other, dists, dists_prev, index, index_prev, mtx)) {
2190                                                                                 if (BM_elem_flag_test(v_other, BM_ELEM_TAG) == 0) {
2191                                                                                         BM_elem_flag_enable(v_other, BM_ELEM_TAG);
2192                                                                                         BLI_LINKSTACK_PUSH(queue_next, v_other);
2193                                                                                 }
2194                                                                         }
2195                                                                 }
2196                                                         } while ((l_iter_radial = l_iter_radial->radial_next) != l_first_radial);
2197                                                 }
2198                                         }
2199                                 } while ((e_iter = BM_DISK_EDGE_NEXT(e_iter, v)) != e_first);
2200                         }
2201                 }
2202
2203
2204                 /* clear for the next loop */
2205                 for (lnk = queue_next; lnk; lnk = lnk->next) {
2206                         BMVert *v_link = lnk->link;
2207                         const int i = BM_elem_index_get(v_link);
2208
2209                         BM_elem_flag_disable(v_link, BM_ELEM_TAG);
2210
2211                         /* keep in sync, avoid having to do full memcpy each iteration */
2212                         dists_prev[i] = dists[i];
2213                         if (index != NULL) {
2214                                 index_prev[i] = index[i];
2215                         }
2216                 }
2217
2218                 BLI_LINKSTACK_SWAP(queue, queue_next);
2219
2220                 /* none should be tagged now since 'queue_next' is empty */
2221                 BLI_assert(BM_iter_mesh_count_flag(BM_VERTS_OF_MESH, bm, BM_ELEM_TAG, true) == 0);
2222
2223         } while (BLI_LINKSTACK_SIZE(queue));
2224
2225         BLI_LINKSTACK_FREE(queue);
2226         BLI_LINKSTACK_FREE(queue_next);
2227
2228         MEM_freeN(dists_prev);
2229         if (index_prev != NULL) {
2230                 MEM_freeN(index_prev);
2231         }
2232 }
2233
2234 static struct TransIslandData *editmesh_islands_info_calc(
2235         BMEditMesh *em, int *r_island_tot, int **r_island_vert_map,
2236         bool calc_single_islands)
2237 {
2238         BMesh *bm = em->bm;
2239         struct TransIslandData *trans_islands;
2240         char htype;
2241         char itype;
2242         int i;
2243
2244         /* group vars */
2245         int *groups_array;
2246         int (*group_index)[2];
2247         int group_tot;
2248         void **ele_array;
2249
2250         int *vert_map;
2251
2252         if (em->selectmode & (SCE_SELECT_VERTEX | SCE_SELECT_EDGE)) {
2253                 groups_array = MEM_mallocN(sizeof(*groups_array) * bm->totedgesel, __func__);
2254                 group_tot = BM_mesh_calc_edge_groups(bm, groups_array, &group_index,
2255                                                      NULL, NULL,
2256                                                      BM_ELEM_SELECT);
2257
2258                 htype = BM_EDGE;
2259                 itype = BM_VERTS_OF_EDGE;
2260
2261         }
2262         else {  /* (bm->selectmode & SCE_SELECT_FACE) */
2263                 groups_array = MEM_mallocN(sizeof(*groups_array) * bm->totfacesel, __func__);
2264                 group_tot = BM_mesh_calc_face_groups(bm, groups_array, &group_index,
2265                                                      NULL, NULL,
2266                                                      BM_ELEM_SELECT, BM_VERT);
2267
2268                 htype = BM_FACE;
2269                 itype = BM_VERTS_OF_FACE;
2270         }
2271
2272
2273         trans_islands = MEM_mallocN(sizeof(*trans_islands) * group_tot, __func__);
2274
2275         vert_map = MEM_mallocN(sizeof(*vert_map) * bm->totvert, __func__);
2276         /* we shouldn't need this, but with incorrect selection flushing
2277          * its possible we have a selected vertex thats not in a face, for now best not crash in that case. */
2278         copy_vn_i(vert_map, bm->totvert, -1);
2279
2280         BM_mesh_elem_table_ensure(bm, htype);
2281         ele_array = (htype == BM_FACE) ? (void **)bm->ftable : (void **)bm->etable;
2282
2283         BM_mesh_elem_index_ensure(bm, BM_VERT);
2284
2285         /* may be an edge OR a face array */
2286         for (i = 0; i < group_tot; i++) {
2287                 BMEditSelection ese = {NULL};
2288
2289                 const int fg_sta = group_index[i][0];
2290                 const int fg_len = group_index[i][1];
2291                 float co[3], no[3], tangent[3];
2292                 int j;
2293
2294                 zero_v3(co);
2295                 zero_v3(no);
2296                 zero_v3(tangent);
2297
2298                 ese.htype = htype;
2299
2300                 /* loop on each face in this group:
2301                  * - assign r_vert_map
2302                  * - calculate (co, no)
2303                  */
2304                 for (j = 0; j < fg_len; j++) {
2305                         float tmp_co[3], tmp_no[3], tmp_tangent[3];
2306
2307                         ese.ele = ele_array[groups_array[fg_sta + j]];
2308
2309                         BM_editselection_center(&ese, tmp_co);
2310                         BM_editselection_normal(&ese, tmp_no);
2311                         BM_editselection_plane(&ese, tmp_tangent);
2312
2313                         add_v3_v3(co, tmp_co);
2314                         add_v3_v3(no, tmp_no);
2315                         add_v3_v3(tangent, tmp_tangent);
2316
2317                         {
2318                                 /* setup vertex map */
2319                                 BMIter iter;
2320                                 BMVert *v;
2321
2322                                 /* connected edge-verts */
2323                                 BM_ITER_ELEM (v, &iter, ese.ele, itype) {
2324                                         vert_map[BM_elem_index_get(v)] = i;
2325                                 }
2326                         }
2327                 }
2328
2329                 mul_v3_v3fl(trans_islands[i].co, co, 1.0f / (float)fg_len);
2330
2331                 if (createSpaceNormalTangent(trans_islands[i].axismtx, no, tangent)) {
2332                         /* pass */
2333                 }
2334                 else {
2335                         if (normalize_v3(no) != 0.0f) {
2336                                 axis_dominant_v3_to_m3(trans_islands[i].axismtx, no);
2337                                 invert_m3(trans_islands[i].axismtx);
2338                         }
2339                         else {
2340                                 unit_m3(trans_islands[i].axismtx);
2341                         }
2342                 }
2343         }
2344
2345         MEM_freeN(groups_array);
2346         MEM_freeN(group_index);
2347
2348         /* for PET we need islands of 1 so connected vertices can use it with V3D_AROUND_LOCAL_ORIGINS */
2349         if (calc_single_islands) {
2350                 BMIter viter;
2351                 BMVert *v;
2352                 int group_tot_single = 0;
2353
2354                 BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
2355                         if (BM_elem_flag_test(v, BM_ELEM_SELECT) && (vert_map[i] == -1)) {
2356                                 group_tot_single += 1;
2357                         }
2358                 }
2359
2360                 if (group_tot_single != 0) {
2361                         trans_islands = MEM_reallocN(trans_islands, sizeof(*trans_islands) * (group_tot + group_tot_single));
2362
2363                         BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
2364                                 if (BM_elem_flag_test(v, BM_ELEM_SELECT) && (vert_map[i] == -1)) {
2365                                         struct TransIslandData *v_island = &trans_islands[group_tot];
2366                                         vert_map[i] = group_tot;
2367
2368                                         copy_v3_v3(v_island->co, v->co);
2369
2370                                         if (is_zero_v3(v->no) != 0.0f) {
2371                                                 axis_dominant_v3_to_m3(v_island->axismtx, v->no);
2372                                                 invert_m3(v_island->axismtx);
2373                                         }
2374                                         else {
2375                                                 unit_m3(v_island->axismtx);
2376                                         }
2377
2378                                         group_tot += 1;
2379                                 }
2380                         }
2381                 }
2382         }
2383
2384         *r_island_tot = group_tot;
2385         *r_island_vert_map = vert_map;
2386
2387         return trans_islands;
2388 }
2389
2390 /* way to overwrite what data is edited with transform */
2391 static void VertsToTransData(TransInfo *t, TransData *td, TransDataExtension *tx,
2392                              BMEditMesh *em, BMVert *eve, float *bweight,
2393                              struct TransIslandData *v_island)
2394 {
2395         float *no, _no[3];
2396         BLI_assert(BM_elem_flag_test(eve, BM_ELEM_HIDDEN) == 0);
2397
2398         td->flag = 0;
2399         //if (key)
2400         //      td->loc = key->co;
2401         //else
2402         td->loc = eve->co;
2403         copy_v3_v3(td->iloc, td->loc);
2404
2405         if ((t->mode == TFM_SHRINKFATTEN) &&
2406             (em->selectmode & SCE_SELECT_FACE) &&
2407             BM_elem_flag_test(eve, BM_ELEM_SELECT) &&
2408             (BM_vert_calc_normal_ex(eve, BM_ELEM_SELECT, _no)))
2409         {
2410                 no = _no;
2411         }
2412         else {
2413                 no = eve->no;
2414         }
2415
2416         if (v_island) {
2417                 copy_v3_v3(td->center, v_island->co);
2418                 copy_m3_m3(td->axismtx, v_island->axismtx);
2419         }
2420         else if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
2421                 copy_v3_v3(td->center, td->loc);
2422                 createSpaceNormal(td->axismtx, no);
2423         }
2424         else {
2425                 copy_v3_v3(td->center, td->loc);
2426
2427                 /* Setting normals */
2428                 copy_v3_v3(td->axismtx[2], no);
2429                 td->axismtx[0][0]        =
2430                     td->axismtx[0][1]    =
2431                     td->axismtx[0][2]    =
2432                     td->axismtx[1][0]    =
2433                     td->axismtx[1][1]    =
2434                     td->axismtx[1][2]    = 0.0f;
2435         }
2436
2437
2438         td->ext = NULL;
2439         td->val = NULL;
2440         td->extra = NULL;
2441         if (t->mode == TFM_BWEIGHT) {
2442                 td->val  =  bweight;
2443                 td->ival = *bweight;
2444         }
2445         else if (t->mode == TFM_SKIN_RESIZE) {
2446                 MVertSkin *vs = CustomData_bmesh_get(&em->bm->vdata,
2447                                                      eve->head.data,
2448                                                      CD_MVERT_SKIN);
2449                 /* skin node size */
2450                 td->ext = tx;
2451                 copy_v3_v3(tx->isize, vs->radius);
2452                 tx->size = vs->radius;
2453                 td->val = vs->radius;
2454         }
2455         else if (t->mode == TFM_SHRINKFATTEN) {
2456                 td->ext = tx;
2457                 tx->isize[0] = BM_vert_calc_shell_factor_ex(eve, no, BM_ELEM_SELECT);
2458         }
2459 }
2460
2461 static void createTransEditVerts(TransInfo *t)
2462 {
2463         TransData *tob = NULL;
2464         TransDataExtension *tx = NULL;
2465         EvaluationContext eval_ctx;
2466         BMEditMesh *em = BKE_editmesh_from_object(t->obedit);
2467         Mesh *me = t->obedit->data;
2468         BMesh *bm = em->bm;
2469         BMVert *eve;
2470         BMIter iter;
2471         float (*mappedcos)[3] = NULL, (*quats)[4] = NULL;
2472         float mtx[3][3], smtx[3][3], (*defmats)[3][3] = NULL, (*defcos)[3] = NULL;
2473         float *dists = NULL;
2474         int a;
2475         const int prop_mode = (t->flag & T_PROP_EDIT) ? (t->flag & T_PROP_EDIT_ALL) : 0;
2476         int mirror = 0;
2477         int cd_vert_bweight_offset = -1;
2478         bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
2479
2480         struct TransIslandData *island_info = NULL;
2481         int island_info_tot;
2482         int *island_vert_map = NULL;
2483
2484         DEG_evaluation_context_init_from_scene(&eval_ctx,
2485                                                t->scene, t->view_layer, t->engine_type,
2486                                                DAG_EVAL_VIEWPORT);
2487
2488         /* Even for translation this is needed because of island-orientation, see: T51651. */
2489         const bool is_island_center = (t->around == V3D_AROUND_LOCAL_ORIGINS);
2490         /* Original index of our connected vertex when connected distances are calculated.
2491          * Optional, allocate if needed. */
2492         int *dists_index = NULL;
2493
2494         if (t->flag & T_MIRROR) {
2495                 EDBM_verts_mirror_cache_begin(em, 0, false, (t->flag & T_PROP_EDIT) == 0, use_topology);
2496                 mirror = 1;
2497         }
2498
2499         /**
2500          * Quick check if we can transform.
2501          *
2502          * \note ignore modes here, even in edge/face modes, transform data is created by selected vertices.
2503          * \note in prop mode we need at least 1 selected.
2504          */
2505         if (bm->totvertsel == 0) {
2506                 goto cleanup;
2507         }
2508
2509         if (t->mode == TFM_BWEIGHT) {
2510                 BM_mesh_cd_flag_ensure(bm, BKE_mesh_from_object(t->obedit), ME_CDFLAG_VERT_BWEIGHT);
2511                 cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT);
2512         }
2513
2514         if (prop_mode) {
2515                 unsigned int count = 0;
2516                 BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
2517                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
2518                                 count++;
2519                         }
2520                 }
2521
2522                 t->total = count;
2523
2524                 /* allocating scratch arrays */
2525                 if (prop_mode & T_PROP_CONNECTED) {
2526                         dists = MEM_mallocN(em->bm->totvert * sizeof(float), __func__);
2527                         if (is_island_center) {
2528                                 dists_index =  MEM_mallocN(em->bm->totvert * sizeof(int), __func__);
2529                         }
2530                 }
2531         }
2532         else {
2533                 t->total = bm->totvertsel;
2534         }
2535
2536         tob = t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Mesh EditMode)");
2537         if (ELEM(t->mode, TFM_SKIN_RESIZE, TFM_SHRINKFATTEN)) {
2538                 /* warning, this is overkill, we only need 2 extra floats,
2539                  * but this stores loads of extra stuff, for TFM_SHRINKFATTEN its even more overkill
2540                  * since we may not use the 'alt' transform mode to maintain shell thickness,
2541                  * but with generic transform code its hard to lazy init vars */
2542                 tx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension),
2543                                           "TransObData ext");
2544         }
2545
2546         copy_m3_m4(mtx, t->obedit->obmat);
2547         /* we use a pseudoinverse so that when one of the axes is scaled to 0,
2548          * matrix inversion still works and we can still moving along the other */
2549         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
2550
2551         if (prop_mode & T_PROP_CONNECTED) {
2552                 editmesh_set_connectivity_distance(em->bm, mtx, dists, dists_index);
2553         }
2554
2555         if (is_island_center) {
2556                 /* In this specific case, near-by vertices will need to know the island of the nearest connected vertex. */
2557                 const bool calc_single_islands = (
2558                         (prop_mode & T_PROP_CONNECTED) &&
2559                         (t->around == V3D_AROUND_LOCAL_ORIGINS) &&
2560                         (em->selectmode & SCE_SELECT_VERTEX));
2561
2562                 island_info = editmesh_islands_info_calc(em, &island_info_tot, &island_vert_map, calc_single_islands);
2563         }
2564
2565         /* detect CrazySpace [tm] */
2566         if (modifiers_getCageIndex(t->scene, t->obedit, NULL, 1) != -1) {
2567                 int totleft = -1;
2568                 if (modifiers_isCorrectableDeformed(t->scene, t->obedit)) {
2569                         /* check if we can use deform matrices for modifier from the
2570                          * start up to stack, they are more accurate than quats */
2571                         totleft = BKE_crazyspace_get_first_deform_matrices_editbmesh(&eval_ctx, t->scene, t->obedit, em, &defmats, &defcos);
2572                 }
2573
2574                 /* if we still have more modifiers, also do crazyspace
2575                  * correction with quats, relative to the coordinates after
2576                  * the modifiers that support deform matrices (defcos) */
2577
2578 #if 0   /* TODO, fix crazyspace+extrude so it can be enabled for general use - campbell */
2579                 if ((totleft > 0) || (totleft == -1))
2580 #else
2581                 if (totleft > 0)
2582 #endif
2583                 {
2584                         mappedcos = BKE_crazyspace_get_mapped_editverts(&eval_ctx, t->scene, t->obedit);
2585                         quats = MEM_mallocN(em->bm->totvert * sizeof(*quats), "crazy quats");
2586                         BKE_crazyspace_set_quats_editmesh(em, defcos, mappedcos, quats, !prop_mode);
2587                         if (mappedcos)
2588                                 MEM_freeN(mappedcos);
2589                 }
2590
2591                 if (defcos) {
2592                         MEM_freeN(defcos);
2593                 }
2594         }
2595
2596         /* find out which half we do */
2597         if (mirror) {
2598                 BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
2599                         if (BM_elem_flag_test(eve, BM_ELEM_SELECT) && eve->co[0] != 0.0f) {
2600                                 if (eve->co[0] < 0.0f) {
2601                                         t->mirror = -1;
2602                                         mirror = -1;
2603                                 }
2604                                 break;
2605                         }
2606                 }
2607         }
2608
2609         BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, a) {
2610                 if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
2611                         if (prop_mode || BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
2612                                 struct TransIslandData *v_island = NULL;
2613                                 float *bweight = (cd_vert_bweight_offset != -1) ? BM_ELEM_CD_GET_VOID_P(eve, cd_vert_bweight_offset) : NULL;
2614
2615                                 if (island_info) {
2616                                         const int connected_index = (dists_index && dists_index[a] != -1) ? dists_index[a] : a;
2617                                         v_island = (island_vert_map[connected_index] != -1) ?
2618                                                    &island_info[island_vert_map[connected_index]] : NULL;
2619                                 }
2620
2621
2622                                 VertsToTransData(t, tob, tx, em, eve, bweight, v_island);
2623                                 if (tx)
2624                                         tx++;
2625
2626                                 /* selected */
2627                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT))
2628                                         tob->flag |= TD_SELECTED;
2629
2630                                 if (prop_mode) {
2631                                         if (prop_mode & T_PROP_CONNECTED) {
2632                                                 tob->dist = dists[a];
2633                                         }
2634                                         else {
2635                                                 tob->flag |= TD_NOTCONNECTED;
2636                                                 tob->dist = FLT_MAX;
2637                                         }
2638                                 }
2639
2640                                 /* CrazySpace */
2641                                 if (defmats || (quats && BM_elem_flag_test(eve, BM_ELEM_TAG))) {
2642                                         float mat[3][3], qmat[3][3], imat[3][3];
2643
2644                                         /* use both or either quat and defmat correction */
2645                                         if (quats && BM_elem_flag_test(eve, BM_ELEM_TAG)) {
2646                                                 quat_to_mat3(qmat, quats[BM_elem_index_get(eve)]);
2647
2648                                                 if (defmats)
2649                                                         mul_m3_series(mat, defmats[a], qmat, mtx);
2650                                                 else
2651                                                         mul_m3_m3m3(mat, mtx, qmat);
2652                                         }
2653                                         else
2654                                                 mul_m3_m3m3(mat, mtx, defmats[a]);
2655
2656                                         invert_m3_m3(imat, mat);
2657
2658                                         copy_m3_m3(tob->smtx, imat);
2659                                         copy_m3_m3(tob->mtx, mat);
2660                                 }
2661                                 else {
2662                                         copy_m3_m3(tob->smtx, smtx);
2663                                         copy_m3_m3(tob->mtx, mtx);
2664                                 }
2665
2666                                 /* Mirror? */
2667                                 if ((mirror > 0 && tob->iloc[0] > 0.0f) || (mirror < 0 && tob->iloc[0] < 0.0f)) {
2668                                         BMVert *vmir = EDBM_verts_mirror_get(em, eve); //t->obedit, em, eve, tob->iloc, a);
2669                                         if (vmir && vmir != eve) {
2670                                                 tob->extra = vmir;
2671                                         }
2672                                 }
2673                                 tob++;
2674                         }
2675                 }
2676         }
2677         
2678         if (island_info) {
2679                 MEM_freeN(island_info);
2680                 MEM_freeN(island_vert_map);
2681         }
2682
2683         if (mirror != 0) {
2684                 tob = t->data;
2685                 for (a = 0; a < t->total; a++, tob++) {
2686                         if (ABS(tob->loc[0]) <= 0.00001f) {
2687                                 tob->flag |= TD_MIRROR_EDGE;
2688                         }
2689                 }
2690         }
2691
2692 cleanup:
2693         /* crazy space free */
2694         if (quats)
2695                 MEM_freeN(quats);
2696         if (defmats)
2697                 MEM_freeN(defmats);
2698         if (dists)
2699                 MEM_freeN(dists);
2700         if (dists_index)
2701                 MEM_freeN(dists_index);
2702
2703         if (t->flag & T_MIRROR) {
2704                 EDBM_verts_mirror_cache_end(em);
2705         }
2706 }
2707
2708 /* *** NODE EDITOR *** */
2709 void flushTransNodes(TransInfo *t)
2710 {
2711         const float dpi_fac = UI_DPI_FAC;
2712         int a;
2713         TransData *td;
2714         TransData2D *td2d;
2715         
2716         applyGridAbsolute(t);
2717         
2718         /* flush to 2d vector from internally used 3d vector */
2719         for (a = 0, td = t->data, td2d = t->data2d; a < t->total; a++, td++, td2d++) {
2720                 bNode *node = td->extra;
2721                 float locx, locy;
2722
2723                 /* weirdo - but the node system is a mix of free 2d elements and dpi sensitive UI */
2724 #ifdef USE_NODE_CENTER
2725                 locx = (td2d->loc[0] - (BLI_rctf_size_x(&node->totr)) * +0.5f) / dpi_fac;
2726                 locy = (td2d->loc[1] - (BLI_rctf_size_y(&node->totr)) * -0.5f) / dpi_fac;
2727 #else
2728                 locx = td2d->loc[0] / dpi_fac;
2729                 locy = td2d->loc[1] / dpi_fac;
2730 #endif
2731                 
2732                 /* account for parents (nested nodes) */
2733                 if (node->parent) {
2734                         nodeFromView(node->parent, locx, locy, &node->locx, &node->locy);
2735                 }
2736                 else {
2737                         node->locx = locx;
2738                         node->locy = locy;
2739                 }
2740         }
2741         
2742         /* handle intersection with noodles */
2743         if (t->total == 1) {
2744                 ED_node_link_intersect_test(t->sa, 1);
2745         }
2746 }
2747
2748 /* *** SEQUENCE EDITOR *** */
2749
2750 /* commented _only_ because the meta may have animation data which
2751  * needs moving too [#28158] */
2752
2753 #define SEQ_TX_NESTED_METAS
2754
2755 BLI_INLINE void trans_update_seq(Scene *sce, Sequence *seq, int old_start, int sel_flag)
2756 {
2757         if (seq->depth == 0) {
2758                 /* Calculate this strip and all nested strips.
2759                  * Children are ALWAYS transformed first so we don't need to do this in another loop.
2760                  */
2761                 BKE_sequence_calc(sce, seq);
2762         }
2763         else {
2764                 BKE_sequence_calc_disp(sce, seq);
2765         }
2766
2767         if (sel_flag == SELECT)
2768                 BKE_sequencer_offset_animdata(sce, seq, seq->start - old_start);
2769 }
2770
2771 void flushTransSeq(TransInfo *t)
2772 {
2773         ListBase *seqbasep = BKE_sequencer_editing_get(t->scene, false)->seqbasep; /* Editing null check already done */
2774         int a, new_frame;
2775         TransData *td = NULL;
2776         TransData2D *td2d = NULL;
2777         TransDataSeq *tdsq = NULL;