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