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