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