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