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