Fix T50026: "Only Insert Needed" doesn't work when using Trackball rotation
[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         bool need_dependency_update = false;
832
833         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
834                 /* clear all temporary lock flags */
835                 pchan->ikflag &= ~(BONE_IK_NO_XDOF_TEMP | BONE_IK_NO_YDOF_TEMP | BONE_IK_NO_ZDOF_TEMP);
836                 
837                 pchan->constflag &= ~(PCHAN_HAS_IK | PCHAN_HAS_TARGET);
838                 
839                 /* remove all temporary IK-constraints added */
840                 for (con = pchan->constraints.first; con; con = next) {
841                         next = con->next;
842                         if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
843                                 data = con->data;
844                                 if (data->flag & CONSTRAINT_IK_TEMP) {
845                                         /* iTaSC needs clear for removed constraints */
846                                         need_dependency_update = true;
847                                         BIK_clear_data(ob->pose);
848
849                                         BLI_remlink(&pchan->constraints, con);
850                                         MEM_freeN(con->data);
851                                         MEM_freeN(con);
852                                         continue;
853                                 }
854                                 pchan->constflag |= PCHAN_HAS_IK;
855                                 if (data->tar == NULL || (data->tar->type == OB_ARMATURE && data->subtarget[0] == 0))
856                                         pchan->constflag |= PCHAN_HAS_TARGET;
857                         }
858                 }
859         }
860
861 #ifdef WITH_LEGACY_DEPSGRAPH
862         if (!DEG_depsgraph_use_legacy() && need_dependency_update)
863 #endif
864         {
865                 /* TODO(sergey): Consider doing partial update only. */
866                 DAG_relations_tag_update(G.main);
867         }
868 }
869
870 /* adds the IK to pchan - returns if added */
871 static short pose_grab_with_ik_add(bPoseChannel *pchan)
872 {
873         bKinematicConstraint *targetless = NULL;
874         bKinematicConstraint *data;
875         bConstraint *con;
876
877         /* Sanity check */
878         if (pchan == NULL)
879                 return 0;
880
881         /* Rule: not if there's already an IK on this channel */
882         for (con = pchan->constraints.first; con; con = con->next) {
883                 if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
884                         data = con->data;
885                         
886                         if (data->tar == NULL || (data->tar->type == OB_ARMATURE && data->subtarget[0] == '\0')) {
887                                 /* make reference to constraint to base things off later (if it's the last targetless constraint encountered) */
888                                 targetless = (bKinematicConstraint *)con->data;
889                                 
890                                 /* but, if this is a targetless IK, we make it auto anyway (for the children loop) */
891                                 if (con->enforce != 0.0f) {
892                                         data->flag |= CONSTRAINT_IK_AUTO;
893                                         
894                                         /* if no chain length has been specified, just make things obey standard rotation locks too */
895                                         if (data->rootbone == 0) {
896                                                 for (; pchan; pchan = pchan->parent) {
897                                                         /* here, we set ik-settings for bone from pchan->protectflag */
898                                                         // XXX: careful with quats/axis-angle rotations where we're locking 4d components
899                                                         if (pchan->protectflag & OB_LOCK_ROTX) pchan->ikflag |= BONE_IK_NO_XDOF_TEMP;
900                                                         if (pchan->protectflag & OB_LOCK_ROTY) pchan->ikflag |= BONE_IK_NO_YDOF_TEMP;
901                                                         if (pchan->protectflag & OB_LOCK_ROTZ) pchan->ikflag |= BONE_IK_NO_ZDOF_TEMP;
902                                                 }
903                                         }
904                                         
905                                         return 0; 
906                                 }
907                         }
908                         
909                         if ((con->flag & CONSTRAINT_DISABLE) == 0 && (con->enforce != 0.0f))
910                                 return 0;
911                 }
912         }
913
914         con = BKE_constraint_add_for_pose(NULL, pchan, "TempConstraint", CONSTRAINT_TYPE_KINEMATIC);
915         pchan->constflag |= (PCHAN_HAS_IK | PCHAN_HAS_TARGET);    /* for draw, but also for detecting while pose solving */
916         data = con->data;
917         if (targetless) {
918                 /* if exists, use values from last targetless (but disabled) IK-constraint as base */
919                 *data = *targetless;
920         }
921         else
922                 data->flag = CONSTRAINT_IK_TIP;
923         data->flag |= CONSTRAINT_IK_TEMP | CONSTRAINT_IK_AUTO | CONSTRAINT_IK_POS;
924         copy_v3_v3(data->grabtarget, pchan->pose_tail);
925         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] */
926         
927         /* we only include bones that are part of a continual connected chain */
928         do {
929                 /* here, we set ik-settings for bone from pchan->protectflag */
930                 // XXX: careful with quats/axis-angle rotations where we're locking 4d components
931                 if (pchan->protectflag & OB_LOCK_ROTX) pchan->ikflag |= BONE_IK_NO_XDOF_TEMP;
932                 if (pchan->protectflag & OB_LOCK_ROTY) pchan->ikflag |= BONE_IK_NO_YDOF_TEMP;
933                 if (pchan->protectflag & OB_LOCK_ROTZ) pchan->ikflag |= BONE_IK_NO_ZDOF_TEMP;
934                 
935                 /* now we count this pchan as being included */
936                 data->rootbone++;
937                 
938                 /* continue to parent, but only if we're connected to it */
939                 if (pchan->bone->flag & BONE_CONNECTED)
940                         pchan = pchan->parent;
941                 else
942                         pchan = NULL;
943         } while (pchan);
944
945         /* make a copy of maximum chain-length */
946         data->max_rootbone = data->rootbone;
947
948         return 1;
949 }
950
951 /* bone is a candidate to get IK, but we don't do it if it has children connected */
952 static short pose_grab_with_ik_children(bPose *pose, Bone *bone)
953 {
954         Bone *bonec;
955         short wentdeeper = 0, added = 0;
956
957         /* go deeper if children & children are connected */
958         for (bonec = bone->childbase.first; bonec; bonec = bonec->next) {
959                 if (bonec->flag & BONE_CONNECTED) {
960                         wentdeeper = 1;
961                         added += pose_grab_with_ik_children(pose, bonec);
962                 }
963         }
964         if (wentdeeper == 0) {
965                 bPoseChannel *pchan = BKE_pose_channel_find_name(pose, bone->name);
966                 if (pchan)
967                         added += pose_grab_with_ik_add(pchan);
968         }
969
970         return added;
971 }
972
973 /* main call which adds temporal IK chains */
974 static short pose_grab_with_ik(Object *ob)
975 {
976         bArmature *arm;
977         bPoseChannel *pchan, *parent;
978         Bone *bonec;
979         short tot_ik = 0;
980
981         if ((ob == NULL) || (ob->pose == NULL) || (ob->mode & OB_MODE_POSE) == 0)
982                 return 0;
983
984         arm = ob->data;
985
986         /* Rule: allow multiple Bones (but they must be selected, and only one ik-solver per chain should get added) */
987         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
988                 if (pchan->bone->layer & arm->layer) {
989                         if (pchan->bone->flag & BONE_SELECTED) {
990                                 /* Rule: no IK for solitatry (unconnected) bones */
991                                 for (bonec = pchan->bone->childbase.first; bonec; bonec = bonec->next) {
992                                         if (bonec->flag & BONE_CONNECTED) {
993                                                 break;
994                                         }
995                                 }
996                                 if ((pchan->bone->flag & BONE_CONNECTED) == 0 && (bonec == NULL))
997                                         continue;
998
999                                 /* rule: if selected Bone is not a root bone, it gets a temporal IK */
1000                                 if (pchan->parent) {
1001                                         /* only adds if there's no IK yet (and no parent bone was selected) */
1002                                         for (parent = pchan->parent; parent; parent = parent->parent) {
1003                                                 if (parent->bone->flag & BONE_SELECTED)
1004                                                         break;
1005                                         }
1006                                         if (parent == NULL)
1007                                                 tot_ik += pose_grab_with_ik_add(pchan);
1008                                 }
1009                                 else {
1010                                         /* rule: go over the children and add IK to the tips */
1011                                         tot_ik += pose_grab_with_ik_children(ob->pose, pchan->bone);
1012                                 }
1013                         }
1014                 }
1015         }
1016
1017         /* iTaSC needs clear for new IK constraints */
1018         if (tot_ik) {
1019                 BIK_clear_data(ob->pose);
1020 #ifdef WITH_LEGACY_DEPSGRAPH
1021                 if (!DEG_depsgraph_use_legacy())
1022 #endif
1023                 {
1024                         /* TODO(sergey): Consuder doing partial update only. */
1025                         DAG_relations_tag_update(G.main);
1026                 }
1027         }
1028
1029         return (tot_ik) ? 1 : 0;
1030 }
1031
1032
1033 /* only called with pose mode active object now */
1034 static void createTransPose(TransInfo *t, Object *ob)
1035 {
1036         bArmature *arm;
1037         bPoseChannel *pchan;
1038         TransData *td;
1039         TransDataExtension *tdx;
1040         short ik_on = 0;
1041         int i;
1042
1043         t->total = 0;
1044
1045         /* check validity of state */
1046         arm = BKE_armature_from_object(ob);
1047         if ((arm == NULL) || (ob->pose == NULL)) return;
1048
1049         if (arm->flag & ARM_RESTPOS) {
1050                 if (ELEM(t->mode, TFM_DUMMY, TFM_BONESIZE) == 0) {
1051                         BKE_report(t->reports, RPT_ERROR, "Cannot change Pose when 'Rest Position' is enabled");
1052                         return;
1053                 }
1054         }
1055
1056         /* do we need to add temporal IK chains? */
1057         if ((arm->flag & ARM_AUTO_IK) && t->mode == TFM_TRANSLATION) {
1058                 ik_on = pose_grab_with_ik(ob);
1059                 if (ik_on) t->flag |= T_AUTOIK;
1060         }
1061
1062         /* set flags and count total (warning, can change transform to rotate) */
1063         t->total = count_set_pose_transflags(&t->mode, t->around, ob);
1064
1065         if (t->total == 0) return;
1066
1067         t->flag |= T_POSE;
1068         t->poseobj = ob; /* we also allow non-active objects to be transformed, in weightpaint */
1069
1070         /* disable PET, its not usable in pose mode yet [#32444] */
1071         t->flag &= ~T_PROP_EDIT_ALL;
1072
1073         /* init trans data */
1074         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransPoseBone");
1075         tdx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension), "TransPoseBoneExt");
1076         for (i = 0; i < t->total; i++, td++, tdx++) {
1077                 td->ext = tdx;
1078                 td->val = NULL;
1079         }
1080
1081         /* use pose channels to fill trans data */
1082         td = t->data;
1083         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
1084                 if (pchan->bone->flag & BONE_TRANSFORM) {
1085                         add_pose_transdata(t, pchan, ob, td);
1086                         td++;
1087                 }
1088         }
1089
1090         if (td != (t->data + t->total)) {
1091                 BKE_report(t->reports, RPT_DEBUG, "Bone selection count error");
1092         }
1093
1094         /* initialize initial auto=ik chainlen's? */
1095         if (ik_on) transform_autoik_update(t, 0);
1096 }
1097
1098 void restoreBones(TransInfo *t)
1099 {
1100         bArmature *arm = t->obedit->data;
1101         BoneInitData *bid = t->custom.type.data;
1102         EditBone *ebo;
1103
1104         while (bid->bone) {
1105                 ebo = bid->bone;
1106                 
1107                 ebo->dist = bid->dist;
1108                 ebo->rad_tail = bid->rad_tail;
1109                 ebo->roll = bid->roll;
1110                 ebo->xwidth = bid->xwidth;
1111                 ebo->zwidth = bid->zwidth;
1112                 copy_v3_v3(ebo->head, bid->head);
1113                 copy_v3_v3(ebo->tail, bid->tail);
1114                 
1115                 if (arm->flag & ARM_MIRROR_EDIT) {
1116                         EditBone *ebo_child;
1117
1118                         /* Also move connected ebo_child, in case ebo_child's name aren't mirrored properly */
1119                         for (ebo_child = arm->edbo->first; ebo_child; ebo_child = ebo_child->next) {
1120                                 if ((ebo_child->flag & BONE_CONNECTED) && (ebo_child->parent == ebo)) {
1121                                         copy_v3_v3(ebo_child->head, ebo->tail);
1122                                         ebo_child->rad_head = ebo->rad_tail;
1123                                 }
1124                         }
1125
1126                         /* Also move connected parent, in case parent's name isn't mirrored properly */
1127                         if ((ebo->flag & BONE_CONNECTED) && ebo->parent) {
1128                                 EditBone *parent = ebo->parent;
1129                                 copy_v3_v3(parent->tail, ebo->head);
1130                                 parent->rad_tail = ebo->rad_head;
1131                         }
1132                 }
1133                 
1134                 bid++;
1135         }
1136 }
1137
1138
1139 /* ********************* armature ************** */
1140 static void createTransArmatureVerts(TransInfo *t)
1141 {
1142         EditBone *ebo, *eboflip;
1143         bArmature *arm = t->obedit->data;
1144         ListBase *edbo = arm->edbo;
1145         TransData *td, *td_old;
1146         float mtx[3][3], smtx[3][3], bonemat[3][3];
1147         bool mirror = ((arm->flag & ARM_MIRROR_EDIT) != 0);
1148         int total_mirrored = 0, i;
1149         int oldtot;
1150         BoneInitData *bid;
1151         
1152         t->total = 0;
1153         for (ebo = edbo->first; ebo; ebo = ebo->next) {
1154                 oldtot = t->total;
1155
1156                 if (EBONE_VISIBLE(arm, ebo) && !(ebo->flag & BONE_EDITMODE_LOCKED)) {
1157                         if (ELEM(t->mode, TFM_BONESIZE, TFM_BONE_ENVELOPE_DIST)) {
1158                                 if (ebo->flag & BONE_SELECTED)
1159                                         t->total++;
1160                         }
1161                         else if (t->mode == TFM_BONE_ROLL) {
1162                                 if (ebo->flag & BONE_SELECTED)
1163                                         t->total++;
1164                         }
1165                         else {
1166                                 if (ebo->flag & BONE_TIPSEL)
1167                                         t->total++;
1168                                 if (ebo->flag & BONE_ROOTSEL)
1169                                         t->total++;
1170                         }
1171                 }
1172
1173                 if (mirror && (oldtot < t->total)) {
1174                         eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebo);
1175                         if (eboflip)
1176                                 total_mirrored++;
1177                 }
1178         }
1179
1180         if (!t->total) return;
1181
1182         transform_around_single_fallback(t);
1183
1184         copy_m3_m4(mtx, t->obedit->obmat);
1185         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1186
1187         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransEditBone");
1188
1189         if (mirror) {
1190                 t->custom.type.data = bid = MEM_mallocN((total_mirrored + 1) * sizeof(BoneInitData), "BoneInitData");
1191                 t->custom.type.use_free = true;
1192         }
1193
1194         i = 0;
1195
1196         for (ebo = edbo->first; ebo; ebo = ebo->next) {
1197                 td_old = td;
1198                 ebo->oldlength = ebo->length;   // length==0.0 on extrude, used for scaling radius of bone points
1199
1200                 if (EBONE_VISIBLE(arm, ebo) && !(ebo->flag & BONE_EDITMODE_LOCKED)) {
1201                         if (t->mode == TFM_BONE_ENVELOPE) {
1202                                 if (ebo->flag & BONE_ROOTSEL) {
1203                                         td->val = &ebo->rad_head;
1204                                         td->ival = *td->val;
1205
1206                                         copy_v3_v3(td->center, ebo->head);
1207                                         td->flag = TD_SELECTED;
1208
1209                                         copy_m3_m3(td->smtx, smtx);
1210                                         copy_m3_m3(td->mtx, mtx);
1211
1212                                         td->loc = NULL;
1213                                         td->ext = NULL;
1214                                         td->ob = t->obedit;
1215
1216                                         td++;
1217                                 }
1218                                 if (ebo->flag & BONE_TIPSEL) {
1219                                         td->val = &ebo->rad_tail;
1220                                         td->ival = *td->val;
1221                                         copy_v3_v3(td->center, ebo->tail);
1222                                         td->flag = TD_SELECTED;
1223
1224                                         copy_m3_m3(td->smtx, smtx);
1225                                         copy_m3_m3(td->mtx, mtx);
1226
1227                                         td->loc = NULL;
1228                                         td->ext = NULL;
1229                                         td->ob = t->obedit;
1230
1231                                         td++;
1232                                 }
1233
1234                         }
1235                         else if (ELEM(t->mode, TFM_BONESIZE, TFM_BONE_ENVELOPE_DIST)) {
1236                                 if (ebo->flag & BONE_SELECTED) {
1237                                         if ((t->mode == TFM_BONE_ENVELOPE_DIST) || (arm->drawtype == ARM_ENVELOPE)) {
1238                                                 td->loc = NULL;
1239                                                 td->val = &ebo->dist;
1240                                                 td->ival = ebo->dist;
1241                                         }
1242                                         else {
1243                                                 // abusive storage of scale in the loc pointer :)
1244                                                 td->loc = &ebo->xwidth;
1245                                                 copy_v3_v3(td->iloc, td->loc);
1246                                                 td->val = NULL;
1247                                         }
1248                                         copy_v3_v3(td->center, ebo->head);
1249                                         td->flag = TD_SELECTED;
1250
1251                                         /* use local bone matrix */
1252                                         ED_armature_ebone_to_mat3(ebo, bonemat);
1253                                         mul_m3_m3m3(td->mtx, mtx, bonemat);
1254                                         invert_m3_m3(td->smtx, td->mtx);
1255
1256                                         copy_m3_m3(td->axismtx, td->mtx);
1257                                         normalize_m3(td->axismtx);
1258
1259                                         td->ext = NULL;
1260                                         td->ob = t->obedit;
1261
1262                                         td++;
1263                                 }
1264                         }
1265                         else if (t->mode == TFM_BONE_ROLL) {
1266                                 if (ebo->flag & BONE_SELECTED) {
1267                                         td->loc = NULL;
1268                                         td->val = &(ebo->roll);
1269                                         td->ival = ebo->roll;
1270
1271                                         copy_v3_v3(td->center, ebo->head);
1272                                         td->flag = TD_SELECTED;
1273
1274                                         td->ext = NULL;
1275                                         td->ob = t->obedit;
1276
1277                                         td++;
1278                                 }
1279                         }
1280                         else {
1281                                 if (ebo->flag & BONE_TIPSEL) {
1282                                         copy_v3_v3(td->iloc, ebo->tail);
1283
1284                                         /* Don't allow single selected tips to have a modified center,
1285                                          * causes problem with snapping (see T45974).
1286                                          * However, in rotation mode, we want to keep that 'rotate bone around root with
1287                                          * only its tip selected' behavior (see T46325). */
1288                                         if ((t->around == V3D_AROUND_LOCAL_ORIGINS) &&
1289                                             ((t->mode == TFM_ROTATION) || (ebo->flag & BONE_ROOTSEL)))
1290                                         {
1291                                                 copy_v3_v3(td->center, ebo->head);
1292                                         }
1293                                         else {
1294                                                 copy_v3_v3(td->center, td->iloc);
1295                                         }
1296
1297                                         td->loc = ebo->tail;
1298                                         td->flag = TD_SELECTED;
1299                                         if (ebo->flag & BONE_EDITMODE_LOCKED)
1300                                                 td->protectflag = OB_LOCK_LOC | OB_LOCK_ROT | OB_LOCK_SCALE;
1301
1302                                         copy_m3_m3(td->smtx, smtx);
1303                                         copy_m3_m3(td->mtx, mtx);
1304
1305                                         ED_armature_ebone_to_mat3(ebo, td->axismtx);
1306
1307                                         if ((ebo->flag & BONE_ROOTSEL) == 0) {
1308                                                 td->extra = ebo;
1309                                                 td->ival = ebo->roll;
1310                                         }
1311
1312                                         td->ext = NULL;
1313                                         td->val = NULL;
1314                                         td->ob = t->obedit;
1315
1316                                         td++;
1317                                 }
1318                                 if (ebo->flag & BONE_ROOTSEL) {
1319                                         copy_v3_v3(td->iloc, ebo->head);
1320                                         copy_v3_v3(td->center, td->iloc);
1321                                         td->loc = ebo->head;
1322                                         td->flag = TD_SELECTED;
1323                                         if (ebo->flag & BONE_EDITMODE_LOCKED)
1324                                                 td->protectflag = OB_LOCK_LOC | OB_LOCK_ROT | OB_LOCK_SCALE;
1325
1326                                         copy_m3_m3(td->smtx, smtx);
1327                                         copy_m3_m3(td->mtx, mtx);
1328
1329                                         ED_armature_ebone_to_mat3(ebo, td->axismtx);
1330
1331                                         td->extra = ebo; /* to fix roll */
1332                                         td->ival = ebo->roll;
1333
1334                                         td->ext = NULL;
1335                                         td->val = NULL;
1336                                         td->ob = t->obedit;
1337
1338                                         td++;
1339                                 }
1340                         }
1341                 }
1342
1343                 if (mirror && (td_old != td)) {
1344                         eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebo);
1345                         if (eboflip) {
1346                                 bid[i].bone = eboflip;
1347                                 bid[i].dist = eboflip->dist;
1348                                 bid[i].rad_tail = eboflip->rad_tail;
1349                                 bid[i].roll = eboflip->roll;
1350                                 bid[i].xwidth = eboflip->xwidth;
1351                                 bid[i].zwidth = eboflip->zwidth;
1352                                 copy_v3_v3(bid[i].head, eboflip->head);
1353                                 copy_v3_v3(bid[i].tail, eboflip->tail);
1354                                 i++;
1355                         }
1356                 }
1357         }
1358
1359         if (mirror) {
1360                 /* trick to terminate iteration */
1361                 bid[total_mirrored].bone = NULL;
1362         }
1363 }
1364
1365 /* ********************* meta elements ********* */
1366
1367 static void createTransMBallVerts(TransInfo *t)
1368 {
1369         MetaBall *mb = (MetaBall *)t->obedit->data;
1370         MetaElem *ml;
1371         TransData *td;
1372         TransDataExtension *tx;
1373         float mtx[3][3], smtx[3][3];
1374         int count = 0, countsel = 0;
1375         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1376
1377         /* count totals */
1378         for (ml = mb->editelems->first; ml; ml = ml->next) {
1379                 if (ml->flag & SELECT) countsel++;
1380                 if (is_prop_edit) count++;
1381         }
1382
1383         /* note: in prop mode we need at least 1 selected */
1384         if (countsel == 0) return;
1385
1386         if (is_prop_edit) t->total = count;
1387         else t->total = countsel;
1388
1389         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(MBall EditMode)");
1390         tx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension), "MetaElement_TransExtension");
1391
1392         copy_m3_m4(mtx, t->obedit->obmat);
1393         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1394
1395         for (ml = mb->editelems->first; ml; ml = ml->next) {
1396                 if (is_prop_edit || (ml->flag & SELECT)) {
1397                         td->loc = &ml->x;
1398                         copy_v3_v3(td->iloc, td->loc);
1399                         copy_v3_v3(td->center, td->loc);
1400
1401                         quat_to_mat3(td->axismtx, ml->quat);
1402
1403                         if (ml->flag & SELECT) td->flag = TD_SELECTED | TD_USEQUAT | TD_SINGLESIZE;
1404                         else td->flag = TD_USEQUAT;
1405
1406                         copy_m3_m3(td->smtx, smtx);
1407                         copy_m3_m3(td->mtx, mtx);
1408
1409                         td->ext = tx;
1410
1411                         /* Radius of MetaElem (mass of MetaElem influence) */
1412                         if (ml->flag & MB_SCALE_RAD) {
1413                                 td->val = &ml->rad;
1414                                 td->ival = ml->rad;
1415                         }
1416                         else {
1417                                 td->val = &ml->s;
1418                                 td->ival = ml->s;
1419                         }
1420
1421                         /* expx/expy/expz determine "shape" of some MetaElem types */
1422                         tx->size = &ml->expx;
1423                         tx->isize[0] = ml->expx;
1424                         tx->isize[1] = ml->expy;
1425                         tx->isize[2] = ml->expz;
1426
1427                         /* quat is used for rotation of MetaElem */
1428                         tx->quat = ml->quat;
1429                         copy_qt_qt(tx->iquat, ml->quat);
1430
1431                         tx->rot = NULL;
1432
1433                         td++;
1434                         tx++;
1435                 }
1436         }
1437 }
1438
1439 /* ********************* curve/surface ********* */
1440
1441 static void calc_distanceCurveVerts(TransData *head, TransData *tail)
1442 {
1443         TransData *td, *td_near = NULL;
1444         for (td = head; td <= tail; td++) {
1445                 if (td->flag & TD_SELECTED) {
1446                         td_near = td;
1447                         td->dist = 0.0f;
1448                 }
1449                 else if (td_near) {
1450                         float dist;
1451                         dist = len_v3v3(td_near->center, td->center);
1452                         if (dist < (td - 1)->dist) {
1453                                 td->dist = (td - 1)->dist;
1454                         }
1455                         else {
1456                                 td->dist = dist;
1457                         }
1458                 }
1459                 else {
1460                         td->dist = FLT_MAX;
1461                         td->flag |= TD_NOTCONNECTED;
1462                 }
1463         }
1464         td_near = NULL;
1465         for (td = tail; td >= head; td--) {
1466                 if (td->flag & TD_SELECTED) {
1467                         td_near = td;
1468                         td->dist = 0.0f;
1469                 }
1470                 else if (td_near) {
1471                         float dist;
1472                         dist = len_v3v3(td_near->center, td->center);
1473                         if (td->flag & TD_NOTCONNECTED || dist < td->dist || (td + 1)->dist < td->dist) {
1474                                 td->flag &= ~TD_NOTCONNECTED;
1475                                 if (dist < (td + 1)->dist) {
1476                                         td->dist = (td + 1)->dist;
1477                                 }
1478                                 else {
1479                                         td->dist = dist;
1480                                 }
1481                         }
1482                 }
1483         }
1484 }
1485
1486 /* Utility function for getting the handle data from bezier's */
1487 static TransDataCurveHandleFlags *initTransDataCurveHandles(TransData *td, struct BezTriple *bezt)
1488 {
1489         TransDataCurveHandleFlags *hdata;
1490         td->flag |= TD_BEZTRIPLE;
1491         hdata = td->hdata = MEM_mallocN(sizeof(TransDataCurveHandleFlags), "CuHandle Data");
1492         hdata->ih1 = bezt->h1;
1493         hdata->h1 = &bezt->h1;
1494         hdata->ih2 = bezt->h2; /* in case the second is not selected */
1495         hdata->h2 = &bezt->h2;
1496         return hdata;
1497 }
1498
1499 static void createTransCurveVerts(TransInfo *t)
1500 {
1501         Curve *cu = t->obedit->data;
1502         TransData *td = NULL;
1503         Nurb *nu;
1504         BezTriple *bezt;
1505         BPoint *bp;
1506         float mtx[3][3], smtx[3][3];
1507         int a;
1508         int count = 0, countsel = 0;
1509         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1510         short hide_handles = (cu->drawflag & CU_HIDE_HANDLES);
1511         ListBase *nurbs;
1512
1513         /* to be sure */
1514         if (cu->editnurb == NULL) return;
1515
1516         /* count total of vertices, check identical as in 2nd loop for making transdata! */
1517         nurbs = BKE_curve_editNurbs_get(cu);
1518         for (nu = nurbs->first; nu; nu = nu->next) {
1519                 if (nu->type == CU_BEZIER) {
1520                         for (a = 0, bezt = nu->bezt; a < nu->pntsu; a++, bezt++) {
1521                                 if (bezt->hide == 0) {
1522                                         if (hide_handles) {
1523                                                 if (bezt->f2 & SELECT) countsel += 3;
1524                                                 if (is_prop_edit) count += 3;
1525                                         }
1526                                         else {
1527                                                 if (bezt->f1 & SELECT) countsel++;
1528                                                 if (bezt->f2 & SELECT) countsel++;
1529                                                 if (bezt->f3 & SELECT) countsel++;
1530                                                 if (is_prop_edit) count += 3;
1531                                         }
1532                                 }
1533                         }
1534                 }
1535                 else {
1536                         for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a > 0; a--, bp++) {
1537                                 if (bp->hide == 0) {
1538                                         if (is_prop_edit) count++;
1539                                         if (bp->f1 & SELECT) countsel++;
1540                                 }
1541                         }
1542                 }
1543         }
1544         /* note: in prop mode we need at least 1 selected */
1545         if (countsel == 0) return;
1546
1547         if (is_prop_edit) t->total = count;
1548         else t->total = countsel;
1549         t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Curve EditMode)");
1550
1551         transform_around_single_fallback(t);
1552
1553         copy_m3_m4(mtx, t->obedit->obmat);
1554         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1555
1556         td = t->data;
1557         for (nu = nurbs->first; nu; nu = nu->next) {
1558                 if (nu->type == CU_BEZIER) {
1559                         TransData *head, *tail;
1560                         head = tail = td;
1561                         for (a = 0, bezt = nu->bezt; a < nu->pntsu; a++, bezt++) {
1562                                 if (bezt->hide == 0) {
1563                                         TransDataCurveHandleFlags *hdata = NULL;
1564                                         float axismtx[3][3];
1565
1566                                         if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1567                                                 float normal[3], plane[3];
1568
1569                                                 BKE_nurb_bezt_calc_normal(nu, bezt, normal);
1570                                                 BKE_nurb_bezt_calc_plane(nu, bezt, plane);
1571
1572                                                 if (createSpaceNormalTangent(axismtx, normal, plane)) {
1573                                                         /* pass */
1574                                                 }
1575                                                 else {
1576                                                         normalize_v3(normal);
1577                                                         axis_dominant_v3_to_m3(axismtx, normal);
1578                                                         invert_m3(axismtx);
1579                                                 }
1580                                         }
1581
1582                                         if (is_prop_edit ||
1583                                             ((bezt->f2 & SELECT) && hide_handles) ||
1584                                             ((bezt->f1 & SELECT) && hide_handles == 0))
1585                                         {
1586                                                 copy_v3_v3(td->iloc, bezt->vec[0]);
1587                                                 td->loc = bezt->vec[0];
1588                                                 copy_v3_v3(td->center, bezt->vec[(hide_handles ||
1589                                                                                   (t->around == V3D_AROUND_LOCAL_ORIGINS) ||
1590                                                                                   (bezt->f2 & SELECT)) ? 1 : 0]);
1591                                                 if (hide_handles) {
1592                                                         if (bezt->f2 & SELECT) td->flag = TD_SELECTED;
1593                                                         else td->flag = 0;
1594                                                 }
1595                                                 else {
1596                                                         if (bezt->f1 & SELECT) td->flag = TD_SELECTED;
1597                                                         else td->flag = 0;
1598                                                 }
1599                                                 td->ext = NULL;
1600                                                 td->val = NULL;
1601
1602                                                 hdata = initTransDataCurveHandles(td, bezt);
1603
1604                                                 copy_m3_m3(td->smtx, smtx);
1605                                                 copy_m3_m3(td->mtx, mtx);
1606                                                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1607                                                         copy_m3_m3(td->axismtx, axismtx);
1608                                                 }
1609
1610                                                 td++;
1611                                                 count++;
1612                                                 tail++;
1613                                         }
1614
1615                                         /* This is the Curve Point, the other two are handles */
1616                                         if (is_prop_edit || (bezt->f2 & SELECT)) {
1617                                                 copy_v3_v3(td->iloc, bezt->vec[1]);
1618                                                 td->loc = bezt->vec[1];
1619                                                 copy_v3_v3(td->center, td->loc);
1620                                                 if (bezt->f2 & SELECT) td->flag = TD_SELECTED;
1621                                                 else td->flag = 0;
1622                                                 td->ext = NULL;
1623
1624                                                 if (t->mode == TFM_CURVE_SHRINKFATTEN) { /* || t->mode==TFM_RESIZE) {*/ /* TODO - make points scale */
1625                                                         td->val = &(bezt->radius);
1626                                                         td->ival = bezt->radius;
1627                                                 }
1628                                                 else if (t->mode == TFM_TILT) {
1629                                                         td->val = &(bezt->alfa);
1630                                                         td->ival = bezt->alfa;
1631                                                 }
1632                                                 else {
1633                                                         td->val = NULL;
1634                                                 }
1635
1636                                                 copy_m3_m3(td->smtx, smtx);
1637                                                 copy_m3_m3(td->mtx, mtx);
1638                                                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1639                                                         copy_m3_m3(td->axismtx, axismtx);
1640                                                 }
1641
1642                                                 if ((bezt->f1 & SELECT) == 0 && (bezt->f3 & SELECT) == 0)
1643                                                         /* If the middle is selected but the sides arnt, this is needed */
1644                                                         if (hdata == NULL) { /* if the handle was not saved by the previous handle */
1645                                                                 hdata = initTransDataCurveHandles(td, bezt);
1646                                                         }
1647
1648                                                 td++;
1649                                                 count++;
1650                                                 tail++;
1651                                         }
1652                                         if (is_prop_edit ||
1653                                             ((bezt->f2 & SELECT) && hide_handles) ||
1654                                             ((bezt->f3 & SELECT) && hide_handles == 0))
1655                                         {
1656                                                 copy_v3_v3(td->iloc, bezt->vec[2]);
1657                                                 td->loc = bezt->vec[2];
1658                                                 copy_v3_v3(td->center, bezt->vec[(hide_handles ||
1659                                                                                   (t->around == V3D_AROUND_LOCAL_ORIGINS) ||
1660                                                                                   (bezt->f2 & SELECT)) ? 1 : 2]);
1661                                                 if (hide_handles) {
1662                                                         if (bezt->f2 & SELECT) td->flag = TD_SELECTED;
1663                                                         else td->flag = 0;
1664                                                 }
1665                                                 else {
1666                                                         if (bezt->f3 & SELECT) td->flag = TD_SELECTED;
1667                                                         else td->flag = 0;
1668                                                 }
1669                                                 td->ext = NULL;
1670                                                 td->val = NULL;
1671
1672                                                 if (hdata == NULL) { /* if the handle was not saved by the previous handle */
1673                                                         hdata = initTransDataCurveHandles(td, bezt);
1674                                                 }
1675
1676                                                 copy_m3_m3(td->smtx, smtx);
1677                                                 copy_m3_m3(td->mtx, mtx);
1678                                                 if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
1679                                                         copy_m3_m3(td->axismtx, axismtx);
1680                                                 }
1681
1682                                                 td++;
1683                                                 count++;
1684                                                 tail++;
1685                                         }
1686
1687                                         (void)hdata;  /* quiet warning */
1688                                 }
1689                                 else if (is_prop_edit && head != tail) {
1690                                         calc_distanceCurveVerts(head, tail - 1);
1691                                         head = tail;
1692                                 }
1693                         }
1694                         if (is_prop_edit && head != tail)
1695                                 calc_distanceCurveVerts(head, tail - 1);
1696
1697                         /* TODO - in the case of tilt and radius we can also avoid allocating the initTransDataCurveHandles
1698                          * but for now just don't change handle types */
1699                         if (ELEM(t->mode, TFM_CURVE_SHRINKFATTEN, TFM_TILT, TFM_DUMMY) == 0) {
1700                                 /* sets the handles based on their selection, do this after the data is copied to the TransData */
1701                                 BKE_nurb_handles_test(nu, !hide_handles);
1702                         }
1703                 }
1704                 else {
1705                         TransData *head, *tail;
1706                         head = tail = td;
1707                         for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a > 0; a--, bp++) {
1708                                 if (bp->hide == 0) {
1709                                         if (is_prop_edit || (bp->f1 & SELECT)) {
1710                                                 copy_v3_v3(td->iloc, bp->vec);
1711                                                 td->loc = bp->vec;
1712                                                 copy_v3_v3(td->center, td->loc);
1713                                                 if (bp->f1 & SELECT) td->flag = TD_SELECTED;
1714                                                 else td->flag = 0;
1715                                                 td->ext = NULL;
1716
1717                                                 if (t->mode == TFM_CURVE_SHRINKFATTEN || t->mode == TFM_RESIZE) {
1718                                                         td->val = &(bp->radius);
1719                                                         td->ival = bp->radius;
1720                                                 }
1721                                                 else {
1722                                                         td->val = &(bp->alfa);
1723                                                         td->ival = bp->alfa;
1724                                                 }
1725
1726                                                 copy_m3_m3(td->smtx, smtx);
1727                                                 copy_m3_m3(td->mtx, mtx);
1728
1729                                                 td++;
1730                                                 count++;
1731                                                 tail++;
1732                                         }
1733                                 }
1734                                 else if (is_prop_edit && head != tail) {
1735                                         calc_distanceCurveVerts(head, tail - 1);
1736                                         head = tail;
1737                                 }
1738                         }
1739                         if (is_prop_edit && head != tail)
1740                                 calc_distanceCurveVerts(head, tail - 1);
1741                 }
1742         }
1743 }
1744
1745 /* ********************* lattice *************** */
1746
1747 static void createTransLatticeVerts(TransInfo *t)
1748 {
1749         Lattice *latt = ((Lattice *)t->obedit->data)->editlatt->latt;
1750         TransData *td = NULL;
1751         BPoint *bp;
1752         float mtx[3][3], smtx[3][3];
1753         int a;
1754         int count = 0, countsel = 0;
1755         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1756
1757         bp = latt->def;
1758         a  = latt->pntsu * latt->pntsv * latt->pntsw;
1759         while (a--) {
1760                 if (bp->hide == 0) {
1761                         if (bp->f1 & SELECT) countsel++;
1762                         if (is_prop_edit) count++;
1763                 }
1764                 bp++;
1765         }
1766
1767         /* note: in prop mode we need at least 1 selected */
1768         if (countsel == 0) return;
1769
1770         if (is_prop_edit) t->total = count;
1771         else t->total = countsel;
1772         t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Lattice EditMode)");
1773
1774         copy_m3_m4(mtx, t->obedit->obmat);
1775         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
1776
1777         td = t->data;
1778         bp = latt->def;
1779         a  = latt->pntsu * latt->pntsv * latt->pntsw;
1780         while (a--) {
1781                 if (is_prop_edit || (bp->f1 & SELECT)) {
1782                         if (bp->hide == 0) {
1783                                 copy_v3_v3(td->iloc, bp->vec);
1784                                 td->loc = bp->vec;
1785                                 copy_v3_v3(td->center, td->loc);
1786                                 if (bp->f1 & SELECT) {
1787                                         td->flag = TD_SELECTED;
1788                                 }
1789                                 else {
1790                                         td->flag = 0;
1791                                 }
1792                                 copy_m3_m3(td->smtx, smtx);
1793                                 copy_m3_m3(td->mtx, mtx);
1794
1795                                 td->ext = NULL;
1796                                 td->val = NULL;
1797
1798                                 td++;
1799                                 count++;
1800                         }
1801                 }
1802                 bp++;
1803         }
1804 }
1805
1806 /* ******************* particle edit **************** */
1807 static void createTransParticleVerts(bContext *C, TransInfo *t)
1808 {
1809         TransData *td = NULL;
1810         TransDataExtension *tx;
1811         Base *base = CTX_data_active_base(C);
1812         Object *ob = CTX_data_active_object(C);
1813         ParticleEditSettings *pset = PE_settings(t->scene);
1814         PTCacheEdit *edit = PE_get_current(t->scene, ob);
1815         ParticleSystem *psys = NULL;
1816         ParticleSystemModifierData *psmd = NULL;
1817         PTCacheEditPoint *point;
1818         PTCacheEditKey *key;
1819         float mat[4][4];
1820         int i, k, transformparticle;
1821         int count = 0, hasselected = 0;
1822         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1823
1824         if (edit == NULL || t->settings->particle.selectmode == SCE_SELECT_PATH) return;
1825
1826         psys = edit->psys;
1827
1828         if (psys)
1829                 psmd = psys_get_modifier(ob, psys);
1830
1831         base->flag |= BA_HAS_RECALC_DATA;
1832
1833         for (i = 0, point = edit->points; i < edit->totpoint; i++, point++) {
1834                 point->flag &= ~PEP_TRANSFORM;
1835                 transformparticle = 0;
1836
1837                 if ((point->flag & PEP_HIDE) == 0) {
1838                         for (k = 0, key = point->keys; k < point->totkey; k++, key++) {
1839                                 if ((key->flag & PEK_HIDE) == 0) {
1840                                         if (key->flag & PEK_SELECT) {
1841                                                 hasselected = 1;
1842                                                 transformparticle = 1;
1843                                         }
1844                                         else if (is_prop_edit)
1845                                                 transformparticle = 1;
1846                                 }
1847                         }
1848                 }
1849
1850                 if (transformparticle) {
1851                         count += point->totkey;
1852                         point->flag |= PEP_TRANSFORM;
1853                 }
1854         }
1855
1856         /* note: in prop mode we need at least 1 selected */
1857         if (hasselected == 0) return;
1858
1859         t->total = count;
1860         td = t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Particle Mode)");
1861
1862         if (t->mode == TFM_BAKE_TIME)
1863                 tx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension), "Particle_TransExtension");
1864         else
1865                 tx = t->ext = NULL;
1866
1867         unit_m4(mat);
1868
1869         invert_m4_m4(ob->imat, ob->obmat);
1870
1871         for (i = 0, point = edit->points; i < edit->totpoint; i++, point++) {
1872                 TransData *head, *tail;
1873                 head = tail = td;
1874
1875                 if (!(point->flag & PEP_TRANSFORM)) continue;
1876
1877                 if (psys && !(psys->flag & PSYS_GLOBAL_HAIR))
1878                         psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, psys->particles + i, mat);
1879
1880                 for (k = 0, key = point->keys; k < point->totkey; k++, key++) {
1881                         if (key->flag & PEK_USE_WCO) {
1882                                 copy_v3_v3(key->world_co, key->co);
1883                                 mul_m4_v3(mat, key->world_co);
1884                                 td->loc = key->world_co;
1885                         }
1886                         else
1887                                 td->loc = key->co;
1888
1889                         copy_v3_v3(td->iloc, td->loc);
1890                         copy_v3_v3(td->center, td->loc);
1891
1892                         if (key->flag & PEK_SELECT)
1893                                 td->flag |= TD_SELECTED;
1894                         else if (!is_prop_edit)
1895                                 td->flag |= TD_SKIP;
1896
1897                         unit_m3(td->mtx);
1898                         unit_m3(td->smtx);
1899
1900                         /* don't allow moving roots */
1901                         if (k == 0 && pset->flag & PE_LOCK_FIRST && (!psys || !(psys->flag & PSYS_GLOBAL_HAIR)))
1902                                 td->protectflag |= OB_LOCK_LOC;
1903
1904                         td->ob = ob;
1905                         td->ext = tx;
1906                         if (t->mode == TFM_BAKE_TIME) {
1907                                 td->val = key->time;
1908                                 td->ival = *(key->time);
1909                                 /* abuse size and quat for min/max values */
1910                                 td->flag |= TD_NO_EXT;
1911                                 if (k == 0) tx->size = NULL;
1912                                 else tx->size = (key - 1)->time;
1913
1914                                 if (k == point->totkey - 1) tx->quat = NULL;
1915                                 else tx->quat = (key + 1)->time;
1916                         }
1917
1918                         td++;
1919                         if (tx)
1920                                 tx++;
1921                         tail++;
1922                 }
1923                 if (is_prop_edit && head != tail)
1924                         calc_distanceCurveVerts(head, tail - 1);
1925         }
1926 }
1927
1928 void flushTransParticles(TransInfo *t)
1929 {
1930         Scene *scene = t->scene;
1931         Object *ob = OBACT;
1932         PTCacheEdit *edit = PE_get_current(scene, ob);
1933         ParticleSystem *psys = edit->psys;
1934         ParticleSystemModifierData *psmd = NULL;
1935         PTCacheEditPoint *point;
1936         PTCacheEditKey *key;
1937         TransData *td;
1938         float mat[4][4], imat[4][4], co[3];
1939         int i, k;
1940         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
1941
1942         if (psys)
1943                 psmd = psys_get_modifier(ob, psys);
1944
1945         /* we do transform in world space, so flush world space position
1946          * back to particle local space (only for hair particles) */
1947         td = t->data;
1948         for (i = 0, point = edit->points; i < edit->totpoint; i++, point++, td++) {
1949                 if (!(point->flag & PEP_TRANSFORM)) continue;
1950
1951                 if (psys && !(psys->flag & PSYS_GLOBAL_HAIR)) {
1952                         psys_mat_hair_to_global(ob, psmd->dm_final, psys->part->from, psys->particles + i, mat);
1953                         invert_m4_m4(imat, mat);
1954
1955                         for (k = 0, key = point->keys; k < point->totkey; k++, key++) {
1956                                 copy_v3_v3(co, key->world_co);
1957                                 mul_m4_v3(imat, co);
1958
1959
1960                                 /* optimization for proportional edit */
1961                                 if (!is_prop_edit || !compare_v3v3(key->co, co, 0.0001f)) {
1962                                         copy_v3_v3(key->co, co);
1963                                         point->flag |= PEP_EDIT_RECALC;
1964                                 }
1965                         }
1966                 }
1967                 else
1968                         point->flag |= PEP_EDIT_RECALC;
1969         }
1970
1971         PE_update_object(scene, OBACT, 1);
1972 }
1973
1974 /* ********************* mesh ****************** */
1975
1976 static bool bmesh_test_dist_add(BMVert *v, BMVert *v_other,
1977                                 float *dists, const float *dists_prev,
1978                                 float mtx[3][3])
1979 {
1980         if ((BM_elem_flag_test(v_other, BM_ELEM_SELECT) == 0) &&
1981             (BM_elem_flag_test(v_other, BM_ELEM_HIDDEN) == 0))
1982         {
1983                 const int i = BM_elem_index_get(v);
1984                 const int i_other = BM_elem_index_get(v_other);
1985                 float vec[3];
1986                 float dist_other;
1987                 sub_v3_v3v3(vec, v->co, v_other->co);
1988                 mul_m3_v3(mtx, vec);
1989
1990                 dist_other = dists_prev[i] + len_v3(vec);
1991                 if (dist_other < dists[i_other]) {
1992                         dists[i_other] = dist_other;
1993                         return true;
1994                 }
1995         }
1996
1997         return false;
1998 }
1999
2000 static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float *dists)
2001 {
2002         /* need to be very careful of feedback loops here, store previous dist's to avoid feedback */
2003         float *dists_prev = MEM_mallocN(bm->totvert * sizeof(float), __func__);
2004
2005         BLI_LINKSTACK_DECLARE(queue, BMVert *);
2006
2007         /* any BM_ELEM_TAG'd vertex is in 'queue_next', so we don't add in twice */
2008         BLI_LINKSTACK_DECLARE(queue_next, BMVert *);
2009
2010         BLI_LINKSTACK_INIT(queue);
2011         BLI_LINKSTACK_INIT(queue_next);
2012
2013         {
2014                 BMIter viter;
2015                 BMVert *v;
2016                 int i;
2017
2018                 BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
2019                         float dist;
2020                         BM_elem_index_set(v, i); /* set_inline */
2021                         BM_elem_flag_disable(v, BM_ELEM_TAG);
2022
2023                         if (BM_elem_flag_test(v, BM_ELEM_SELECT) == 0 || BM_elem_flag_test(v, BM_ELEM_HIDDEN)) {
2024                                 dist = FLT_MAX;
2025                         }
2026                         else {
2027                                 BLI_LINKSTACK_PUSH(queue, v);
2028                                 dist = 0.0f;
2029                         }
2030
2031                         dists[i] = dists_prev[i] = dist;
2032                 }
2033                 bm->elem_index_dirty &= ~BM_VERT;
2034         }
2035
2036         do {
2037                 BMVert *v;
2038                 LinkNode *lnk;
2039
2040                 /* this is correct but slow to do each iteration,
2041                  * instead sync the dist's while clearing BM_ELEM_TAG (below) */
2042 #if 0
2043                 memcpy(dists_prev, dists, sizeof(float) * bm->totvert);
2044 #endif
2045
2046                 while ((v = BLI_LINKSTACK_POP(queue))) {
2047                         BLI_assert(dists[BM_elem_index_get(v)] != FLT_MAX);
2048
2049                         /* connected edge-verts */
2050                         if (v->e != NULL) {
2051                                 BMEdge *e_iter, *e_first;
2052
2053                                 e_iter = e_first = v->e;
2054
2055                                 /* would normally use BM_EDGES_OF_VERT, but this runs so often,
2056                                  * its faster to iterate on the data directly */
2057                                 do {
2058
2059                                         if (BM_elem_flag_test(e_iter, BM_ELEM_HIDDEN) == 0) {
2060
2061                                                 /* edge distance */
2062                                                 {
2063                                                         BMVert *v_other = BM_edge_other_vert(e_iter, v);
2064                                                         if (bmesh_test_dist_add(v, v_other, dists, dists_prev, mtx)) {
2065                                                                 if (BM_elem_flag_test(v_other, BM_ELEM_TAG) == 0) {
2066                                                                         BM_elem_flag_enable(v_other, BM_ELEM_TAG);
2067                                                                         BLI_LINKSTACK_PUSH(queue_next, v_other);
2068                                                                 }
2069                                                         }
2070                                                 }
2071
2072                                                 /* face distance */
2073                                                 if (e_iter->l) {
2074                                                         BMLoop *l_iter_radial, *l_first_radial;
2075                                                         /**
2076                                                          * imaginary edge diagonally across quad,
2077                                                          * \note, this takes advantage of the rules of winding that we
2078                                                          * know 2 or more of a verts edges wont reference the same face twice.
2079                                                          * Also, if the edge is hidden, the face will be hidden too.
2080                                                          */
2081                                                         l_iter_radial = l_first_radial = e_iter->l;
2082
2083                                                         do {
2084                                                                 if ((l_iter_radial->v == v) &&
2085                                                                     (l_iter_radial->f->len == 4) &&
2086                                                                     (BM_elem_flag_test(l_iter_radial->f, BM_ELEM_HIDDEN) == 0))
2087                                                                 {
2088                                                                         BMVert *v_other = l_iter_radial->next->next->v;
2089                                                                         if (bmesh_test_dist_add(v, v_other, dists, dists_prev, mtx)) {
2090                                                                                 if (BM_elem_flag_test(v_other, BM_ELEM_TAG) == 0) {
2091                                                                                         BM_elem_flag_enable(v_other, BM_ELEM_TAG);
2092                                                                                         BLI_LINKSTACK_PUSH(queue_next, v_other);
2093                                                                                 }
2094                                                                         }
2095                                                                 }
2096                                                         } while ((l_iter_radial = l_iter_radial->radial_next) != l_first_radial);
2097                                                 }
2098                                         }
2099                                 } while ((e_iter = BM_DISK_EDGE_NEXT(e_iter, v)) != e_first);
2100                         }
2101                 }
2102
2103
2104                 /* clear for the next loop */
2105                 for (lnk = queue_next; lnk; lnk = lnk->next) {
2106                         BMVert *v_link = lnk->link;
2107                         const int i = BM_elem_index_get(v_link);
2108
2109                         BM_elem_flag_disable(v_link, BM_ELEM_TAG);
2110
2111                         /* keep in sync, avoid having to do full memcpy each iteration */
2112                         dists_prev[i] = dists[i];
2113                 }
2114
2115                 BLI_LINKSTACK_SWAP(queue, queue_next);
2116
2117                 /* none should be tagged now since 'queue_next' is empty */
2118                 BLI_assert(BM_iter_mesh_count_flag(BM_VERTS_OF_MESH, bm, BM_ELEM_TAG, true) == 0);
2119
2120         } while (BLI_LINKSTACK_SIZE(queue));
2121
2122         BLI_LINKSTACK_FREE(queue);
2123         BLI_LINKSTACK_FREE(queue_next);
2124
2125         MEM_freeN(dists_prev);
2126 }
2127
2128 static struct TransIslandData *editmesh_islands_info_calc(BMEditMesh *em, int *r_island_tot, int **r_island_vert_map)
2129 {
2130         BMesh *bm = em->bm;
2131         struct TransIslandData *trans_islands;
2132         char htype;
2133         char itype;
2134         int i;
2135
2136         /* group vars */
2137         int *groups_array;
2138         int (*group_index)[2];
2139         int group_tot;
2140         void **ele_array;
2141
2142         int *vert_map;
2143
2144         if (em->selectmode & (SCE_SELECT_VERTEX | SCE_SELECT_EDGE)) {
2145                 groups_array = MEM_mallocN(sizeof(*groups_array) * bm->totedgesel, __func__);
2146                 group_tot = BM_mesh_calc_edge_groups(bm, groups_array, &group_index,
2147                                                      NULL, NULL,
2148                                                      BM_ELEM_SELECT);
2149
2150                 htype = BM_EDGE;
2151                 itype = BM_VERTS_OF_EDGE;
2152
2153         }
2154         else {  /* (bm->selectmode & SCE_SELECT_FACE) */
2155                 groups_array = MEM_mallocN(sizeof(*groups_array) * bm->totfacesel, __func__);
2156                 group_tot = BM_mesh_calc_face_groups(bm, groups_array, &group_index,
2157                                                      NULL, NULL,
2158                                                      BM_ELEM_SELECT, BM_VERT);
2159
2160                 htype = BM_FACE;
2161                 itype = BM_VERTS_OF_FACE;
2162         }
2163
2164
2165         trans_islands = MEM_mallocN(sizeof(*trans_islands) * group_tot, __func__);
2166
2167         vert_map = MEM_mallocN(sizeof(*vert_map) * bm->totvert, __func__);
2168         /* we shouldn't need this, but with incorrect selection flushing
2169          * its possible we have a selected vertex thats not in a face, for now best not crash in that case. */
2170         copy_vn_i(vert_map, bm->totvert, -1);
2171
2172         BM_mesh_elem_table_ensure(bm, htype);
2173         ele_array = (htype == BM_FACE) ? (void **)bm->ftable : (void **)bm->etable;
2174
2175         BM_mesh_elem_index_ensure(bm, BM_VERT);
2176
2177         /* may be an edge OR a face array */
2178         for (i = 0; i < group_tot; i++) {
2179                 BMEditSelection ese = {NULL};
2180
2181                 const int fg_sta = group_index[i][0];
2182                 const int fg_len = group_index[i][1];
2183                 float co[3], no[3], tangent[3];
2184                 int j;
2185
2186                 zero_v3(co);
2187                 zero_v3(no);
2188                 zero_v3(tangent);
2189
2190                 ese.htype = htype;
2191
2192                 /* loop on each face in this group:
2193                  * - assign r_vert_map
2194                  * - calculate (co, no)
2195                  */
2196                 for (j = 0; j < fg_len; j++) {
2197                         float tmp_co[3], tmp_no[3], tmp_tangent[3];
2198
2199                         ese.ele = ele_array[groups_array[fg_sta + j]];
2200
2201                         BM_editselection_center(&ese, tmp_co);
2202                         BM_editselection_normal(&ese, tmp_no);
2203                         BM_editselection_plane(&ese, tmp_tangent);
2204
2205                         add_v3_v3(co, tmp_co);
2206                         add_v3_v3(no, tmp_no);
2207                         add_v3_v3(tangent, tmp_tangent);
2208
2209                         {
2210                                 /* setup vertex map */
2211                                 BMIter iter;
2212                                 BMVert *v;
2213
2214                                 /* connected edge-verts */
2215                                 BM_ITER_ELEM (v, &iter, ese.ele, itype) {
2216                                         vert_map[BM_elem_index_get(v)] = i;
2217                                 }
2218                         }
2219                 }
2220
2221                 mul_v3_v3fl(trans_islands[i].co, co, 1.0f / (float)fg_len);
2222
2223                 if (createSpaceNormalTangent(trans_islands[i].axismtx, no, tangent)) {
2224                         /* pass */
2225                 }
2226                 else {
2227                         if (normalize_v3(no) != 0.0f) {
2228                                 axis_dominant_v3_to_m3(trans_islands[i].axismtx, no);
2229                                 invert_m3(trans_islands[i].axismtx);
2230                         }
2231                         else {
2232                                 unit_m3(trans_islands[i].axismtx);
2233                         }
2234                 }
2235         }
2236
2237         MEM_freeN(groups_array);
2238         MEM_freeN(group_index);
2239
2240         *r_island_tot = group_tot;
2241         *r_island_vert_map = vert_map;
2242
2243         return trans_islands;
2244 }
2245
2246 /* way to overwrite what data is edited with transform */
2247 static void VertsToTransData(TransInfo *t, TransData *td, TransDataExtension *tx,
2248                              BMEditMesh *em, BMVert *eve, float *bweight,
2249                              struct TransIslandData *v_island)
2250 {
2251         float *no, _no[3];
2252         BLI_assert(BM_elem_flag_test(eve, BM_ELEM_HIDDEN) == 0);
2253
2254         td->flag = 0;
2255         //if (key)
2256         //      td->loc = key->co;
2257         //else
2258         td->loc = eve->co;
2259         copy_v3_v3(td->iloc, td->loc);
2260
2261         if ((t->mode == TFM_SHRINKFATTEN) &&
2262             (em->selectmode & SCE_SELECT_FACE) &&
2263             BM_elem_flag_test(eve, BM_ELEM_SELECT) &&
2264             (BM_vert_calc_normal_ex(eve, BM_ELEM_SELECT, _no)))
2265         {
2266                 no = _no;
2267         }
2268         else {
2269                 no = eve->no;
2270         }
2271
2272         if (v_island) {
2273                 copy_v3_v3(td->center, v_island->co);
2274                 copy_m3_m3(td->axismtx, v_island->axismtx);
2275         }
2276         else if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
2277                 copy_v3_v3(td->center, td->loc);
2278                 createSpaceNormal(td->axismtx, no);
2279         }
2280         else {
2281                 copy_v3_v3(td->center, td->loc);
2282
2283                 /* Setting normals */
2284                 copy_v3_v3(td->axismtx[2], no);
2285                 td->axismtx[0][0]        =
2286                     td->axismtx[0][1]    =
2287                     td->axismtx[0][2]    =
2288                     td->axismtx[1][0]    =
2289                     td->axismtx[1][1]    =
2290                     td->axismtx[1][2]    = 0.0f;
2291         }
2292
2293
2294         td->ext = NULL;
2295         td->val = NULL;
2296         td->extra = NULL;
2297         if (t->mode == TFM_BWEIGHT) {
2298                 td->val  =  bweight;
2299                 td->ival = *bweight;
2300         }
2301         else if (t->mode == TFM_SKIN_RESIZE) {
2302                 MVertSkin *vs = CustomData_bmesh_get(&em->bm->vdata,
2303                                                      eve->head.data,
2304                                                      CD_MVERT_SKIN);
2305                 /* skin node size */
2306                 td->ext = tx;
2307                 copy_v3_v3(tx->isize, vs->radius);
2308                 tx->size = vs->radius;
2309                 td->val = vs->radius;
2310         }
2311         else if (t->mode == TFM_SHRINKFATTEN) {
2312                 td->ext = tx;
2313                 tx->isize[0] = BM_vert_calc_shell_factor_ex(eve, no, BM_ELEM_SELECT);
2314         }
2315 }
2316
2317 static void createTransEditVerts(TransInfo *t)
2318 {
2319         TransData *tob = NULL;
2320         TransDataExtension *tx = NULL;
2321         BMEditMesh *em = BKE_editmesh_from_object(t->obedit);
2322         Mesh *me = t->obedit->data;
2323         BMesh *bm = em->bm;
2324         BMVert *eve;
2325         BMIter iter;
2326         float (*mappedcos)[3] = NULL, (*quats)[4] = NULL;
2327         float mtx[3][3], smtx[3][3], (*defmats)[3][3] = NULL, (*defcos)[3] = NULL;
2328         float *dists = NULL;
2329         int a;
2330         const int prop_mode = (t->flag & T_PROP_EDIT) ? (t->flag & T_PROP_EDIT_ALL) : 0;
2331         int mirror = 0;
2332         int cd_vert_bweight_offset = -1;
2333         bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
2334
2335         struct TransIslandData *island_info = NULL;
2336         int island_info_tot;
2337         int *island_vert_map = NULL;
2338
2339         if (t->flag & T_MIRROR) {
2340                 EDBM_verts_mirror_cache_begin(em, 0, false, (t->flag & T_PROP_EDIT) == 0, use_topology);
2341                 mirror = 1;
2342         }
2343
2344         /**
2345          * Quick check if we can transform.
2346          *
2347          * \note ignore modes here, even in edge/face modes, transform data is created by selected vertices.
2348          * \note in prop mode we need at least 1 selected.
2349          */
2350         if (bm->totvertsel == 0) {
2351                 goto cleanup;
2352         }
2353
2354         if (t->mode == TFM_BWEIGHT) {
2355                 BM_mesh_cd_flag_ensure(bm, BKE_mesh_from_object(t->obedit), ME_CDFLAG_VERT_BWEIGHT);
2356                 cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT);
2357         }
2358
2359         if (prop_mode) {
2360                 unsigned int count = 0;
2361                 BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
2362                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
2363                                 count++;
2364                         }
2365                 }
2366
2367                 t->total = count;
2368
2369                 /* allocating scratch arrays */
2370                 if (prop_mode & T_PROP_CONNECTED)
2371                         dists = MEM_mallocN(em->bm->totvert * sizeof(float), "scratch nears");
2372         }
2373         else {
2374                 t->total = bm->totvertsel;
2375         }
2376
2377         tob = t->data = MEM_callocN(t->total * sizeof(TransData), "TransObData(Mesh EditMode)");
2378         if (ELEM(t->mode, TFM_SKIN_RESIZE, TFM_SHRINKFATTEN)) {
2379                 /* warning, this is overkill, we only need 2 extra floats,
2380                  * but this stores loads of extra stuff, for TFM_SHRINKFATTEN its even more overkill
2381                  * since we may not use the 'alt' transform mode to maintain shell thickness,
2382                  * but with generic transform code its hard to lazy init vars */
2383                 tx = t->ext = MEM_callocN(t->total * sizeof(TransDataExtension),
2384                                           "TransObData ext");
2385         }
2386
2387         copy_m3_m4(mtx, t->obedit->obmat);
2388         /* we use a pseudoinverse so that when one of the axes is scaled to 0,
2389          * matrix inversion still works and we can still moving along the other */
2390         pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
2391
2392         if (prop_mode & T_PROP_CONNECTED) {
2393                 editmesh_set_connectivity_distance(em->bm, mtx, dists);
2394         }
2395
2396         if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
2397                 island_info = editmesh_islands_info_calc(em, &island_info_tot, &island_vert_map);
2398         }
2399
2400         /* detect CrazySpace [tm] */
2401         if (modifiers_getCageIndex(t->scene, t->obedit, NULL, 1) != -1) {
2402                 int totleft = -1;
2403                 if (modifiers_isCorrectableDeformed(t->scene, t->obedit)) {
2404                         /* check if we can use deform matrices for modifier from the
2405                          * start up to stack, they are more accurate than quats */
2406                         totleft = BKE_crazyspace_get_first_deform_matrices_editbmesh(t->scene, t->obedit, em, &defmats, &defcos);
2407                 }
2408
2409                 /* if we still have more modifiers, also do crazyspace
2410                  * correction with quats, relative to the coordinates after
2411                  * the modifiers that support deform matrices (defcos) */
2412
2413 #if 0   /* TODO, fix crazyspace+extrude so it can be enabled for general use - campbell */
2414                 if ((totleft > 0) || (totleft == -1))
2415 #else
2416                 if (totleft > 0)
2417 #endif
2418                 {
2419                         mappedcos = BKE_crazyspace_get_mapped_editverts(t->scene, t->obedit);
2420                         quats = MEM_mallocN(em->bm->totvert * sizeof(*quats), "crazy quats");
2421                         BKE_crazyspace_set_quats_editmesh(em, defcos, mappedcos, quats, !prop_mode);
2422                         if (mappedcos)
2423                                 MEM_freeN(mappedcos);
2424                 }
2425
2426                 if (defcos) {
2427                         MEM_freeN(defcos);
2428                 }
2429         }
2430
2431         /* find out which half we do */
2432         if (mirror) {
2433                 BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
2434                         if (BM_elem_flag_test(eve, BM_ELEM_SELECT) && eve->co[0] != 0.0f) {
2435                                 if (eve->co[0] < 0.0f) {
2436                                         t->mirror = -1;
2437                                         mirror = -1;
2438                                 }
2439                                 break;
2440                         }
2441                 }
2442         }
2443
2444         BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, a) {
2445                 if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
2446                         if (prop_mode || BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
2447                                 struct TransIslandData *v_island = (island_info && island_vert_map[a] != -1) ?
2448                                                                    &island_info[island_vert_map[a]] : NULL;
2449                                 float *bweight = (cd_vert_bweight_offset != -1) ? BM_ELEM_CD_GET_VOID_P(eve, cd_vert_bweight_offset) : NULL;
2450
2451                                 VertsToTransData(t, tob, tx, em, eve, bweight, v_island);
2452                                 if (tx)
2453                                         tx++;
2454
2455                                 /* selected */
2456                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT))
2457                                         tob->flag |= TD_SELECTED;
2458
2459                                 if (prop_mode) {
2460                                         if (prop_mode & T_PROP_CONNECTED) {
2461                                                 tob->dist = dists[a];
2462                                         }
2463                                         else {
2464                                                 tob->flag |= TD_NOTCONNECTED;
2465                                                 tob->dist = FLT_MAX;
2466                                         }
2467                                 }
2468
2469                                 /* CrazySpace */
2470                                 if (defmats || (quats && BM_elem_flag_test(eve, BM_ELEM_TAG))) {
2471                                         float mat[3][3], qmat[3][3], imat[3][3];
2472
2473                                         /* use both or either quat and defmat correction */
2474                                         if (quats && BM_elem_flag_test(eve, BM_ELEM_TAG)) {
2475                                                 quat_to_mat3(qmat, quats[BM_elem_index_get(eve)]);
2476
2477                                                 if (defmats)
2478                                                         mul_m3_series(mat, defmats[a], qmat, mtx);
2479                                                 else
2480                                                         mul_m3_m3m3(mat, mtx, qmat);
2481                                         }
2482                                         else
2483                                                 mul_m3_m3m3(mat, mtx, defmats[a]);
2484
2485                                         invert_m3_m3(imat, mat);
2486
2487                                         copy_m3_m3(tob->smtx, imat);
2488                                         copy_m3_m3(tob->mtx, mat);
2489                                 }
2490                                 else {
2491                                         copy_m3_m3(tob->smtx, smtx);
2492                                         copy_m3_m3(tob->mtx, mtx);
2493                                 }
2494
2495                                 /* Mirror? */
2496                                 if ((mirror > 0 && tob->iloc[0] > 0.0f) || (mirror < 0 && tob->iloc[0] < 0.0f)) {
2497                                         BMVert *vmir = EDBM_verts_mirror_get(em, eve); //t->obedit, em, eve, tob->iloc, a);
2498                                         if (vmir && vmir != eve) {
2499                                                 tob->extra = vmir;
2500                                         }
2501                                 }
2502                                 tob++;
2503                         }
2504                 }
2505         }
2506         
2507         if (island_info) {
2508                 MEM_freeN(island_info);
2509                 MEM_freeN(island_vert_map);
2510         }
2511
2512         if (mirror != 0) {
2513                 tob = t->data;
2514                 for (a = 0; a < t->total; a++, tob++) {
2515                         if (ABS(tob->loc[0]) <= 0.00001f) {
2516                                 tob->flag |= TD_MIRROR_EDGE;
2517                         }
2518                 }
2519         }
2520
2521 cleanup:
2522         /* crazy space free */
2523         if (quats)
2524                 MEM_freeN(quats);
2525         if (defmats)
2526                 MEM_freeN(defmats);
2527         if (dists)
2528                 MEM_freeN(dists);
2529
2530         if (t->flag & T_MIRROR) {
2531                 EDBM_verts_mirror_cache_end(em);
2532         }
2533 }
2534
2535 /* *** NODE EDITOR *** */
2536 void flushTransNodes(TransInfo *t)
2537 {
2538         const float dpi_fac = UI_DPI_FAC;
2539         int a;
2540         TransData *td;
2541         TransData2D *td2d;
2542         
2543         applyGridAbsolute(t);
2544         
2545         /* flush to 2d vector from internally used 3d vector */
2546         for (a = 0, td = t->data, td2d = t->data2d; a < t->total; a++, td++, td2d++) {
2547                 bNode *node = td->extra;
2548                 float locx, locy;
2549
2550                 /* weirdo - but the node system is a mix of free 2d elements and dpi sensitive UI */
2551 #ifdef USE_NODE_CENTER
2552                 locx = (td2d->loc[0] - (BLI_rctf_size_x(&node->totr)) * +0.5f) / dpi_fac;
2553                 locy = (td2d->loc[1] - (BLI_rctf_size_y(&node->totr)) * -0.5f) / dpi_fac;
2554 #else
2555                 locx = td2d->loc[0] / dpi_fac;
2556                 locy = td2d->loc[1] / dpi_fac;
2557 #endif
2558                 
2559                 /* account for parents (nested nodes) */
2560                 if (node->parent) {
2561                         nodeFromView(node->parent, locx, locy, &node->locx, &node->locy);
2562                 }
2563                 else {
2564                         node->locx = locx;
2565                         node->locy = locy;
2566                 }
2567         }
2568         
2569         /* handle intersection with noodles */
2570         if (t->total == 1) {
2571                 ED_node_link_intersect_test(t->sa, 1);
2572         }
2573 }
2574
2575 /* *** SEQUENCE EDITOR *** */
2576
2577 /* commented _only_ because the meta may have animation data which
2578  * needs moving too [#28158] */
2579
2580 #define SEQ_TX_NESTED_METAS
2581
2582 BLI_INLINE void trans_update_seq(Scene *sce, Sequence *seq, int old_start, int sel_flag)
2583 {
2584         if (seq->depth == 0) {
2585                 /* Calculate this strip and all nested strips.
2586                  * Children are ALWAYS transformed first so we don't need to do this in another loop.
2587                  */
2588                 BKE_sequence_calc(sce, seq);
2589         }
2590         else {
2591                 BKE_sequence_calc_disp(sce, seq);
2592         }
2593
2594         if (sel_flag == SELECT)
2595                 BKE_sequencer_offset_animdata(sce, seq, seq->start - old_start);
2596 }
2597
2598 void flushTransSeq(TransInfo *t)
2599 {
2600         ListBase *seqbasep = BKE_sequencer_editing_get(t->scene, false)->seqbasep; /* Editing null check already done */
2601         int a, new_frame;
2602         TransData *td = NULL;
2603         TransData2D *td2d = NULL;
2604         TransDataSeq *tdsq = NULL;
2605         Sequence *seq;
2606
2607
2608
2609         /* prevent updating the same seq twice
2610          * if the transdata order is changed this will mess up
2611          * but so will TransDataSeq */
2612         Sequence *seq_prev = NULL;
2613         int old_start_prev = 0, sel_flag_prev = 0;
2614
2615         /* flush to 2d vector from internally used 3d vector */
2616         for (a = 0, td = t->data, td2d = t->data2d; a < t->total; a++, td++, td2d++) {
2617                 int old_start;
2618                 tdsq = (TransDataSeq *)td->extra;
2619                 seq = tdsq->seq;
2620                 old_start = seq->start;
2621                 new_frame = iroundf(td2d->loc[0]);
2622
2623                 switch (tdsq->sel_flag) {
2624                         case SELECT:
2625 #ifdef SEQ_TX_NESTED_METAS
2626                                 if ((seq->depth != 0 || BKE_sequence_tx_test(seq))) /* for meta's, their children move */
2627                                         seq->start = new_frame - tdsq->start_offset;
2628 #else
2629                                 if (seq->type != SEQ_TYPE_META && (seq->depth != 0 || seq_tx_test(seq))) /* for meta's, their children move */
2630                                         seq->start = new_frame - tdsq->start_offset;
2631 #endif
2632                                 if (seq->depth == 0) {
2633                                         seq->machine = iroundf(td2d->loc[1]);
2634                                         CLAMP(seq->machine, 1, MAXSEQ);
2635                                 }
2636                                 break;
2637                         case SEQ_LEFTSEL: /* no vertical transform  */
2638                                 BKE_sequence_tx_set_final_left(seq, new_frame);
2639                                 BKE_sequence_tx_handle_xlimits(seq, tdsq->flag & SEQ_LEFTSEL, tdsq->flag & SEQ_RIGHTSEL);
2640                                 BKE_sequence_single_fix(seq); /* todo - move this into aftertrans update? - old seq tx needed it anyway */
2641                                 break;
2642                         case SEQ_RIGHTSEL: /* no vertical transform  */
2643                                 BKE_sequence_tx_set_final_right(seq, new_frame);
2644                                 BKE_sequence_tx_handle_xlimits(seq, tdsq->flag & SEQ_LEFTSEL, tdsq->flag & SEQ_RIGHTSEL);
2645                                 BKE_sequence_single_fix(seq); /* todo - move this into aftertrans update? - old seq tx needed it anyway */
2646                                 break;
2647                 }
2648
2649                 /* Update *previous* seq! Else, we would update a seq after its first transform, and if it has more than one
2650                  * (like e.g. SEQ_LEFTSEL and SEQ_RIGHTSEL), the others are not updated! See T38469.
2651                  */
2652                 if (seq != seq_prev) {
2653                         if (seq_prev) {
2654                                 trans_update_seq(t->scene, seq_prev, old_start_prev, sel_flag_prev);
2655                         }
2656
2657                         seq_prev = seq;
2658                         old_start_prev = old_start;
2659                         sel_flag_prev = tdsq->sel_flag;
2660                 }
2661                 else {
2662                         /* We want to accumulate *all* sel_flags for this seq! */
2663                         sel_flag_prev |= tdsq->sel_flag;
2664                 }
2665         }
2666
2667         /* Don't forget to update the last seq! */
2668         if (seq_prev) {
2669                 trans_update_seq(t->scene, seq_prev, old_start_prev, sel_flag_prev);
2670         }
2671
2672
2673         if (ELEM(t->mode, TFM_SEQ_SLIDE, TFM_TIME_TRANSLATE)) { /* originally TFM_TIME_EXTEND, transform changes */
2674                 /* Special annoying case here, need to calc metas with TFM_TIME_EXTEND only */
2675
2676                 /* calc all meta's then effects [#27953] */
2677                 for (seq = seqbasep->first; seq; seq = seq->next) {
2678                         if (seq->type == SEQ_TYPE_META && seq->flag & SELECT) {
2679                                 BKE_sequence_calc(t->scene, seq);
2680                         }
2681                 }
2682                 for (seq = seqbasep->first; seq; seq = seq->next) {
2683                         if (seq->seq1 || seq->seq2 || seq->seq3) {
2684                                 BKE_sequence_calc(t->scene, seq);
2685                         }
2686                 }
2687
2688                 /* update effects inside meta's */
2689                 for (a = 0, seq_prev = NULL, td = t->data, td2d = t->data2d;
2690                      a < t->total;
2691                      a++, td++, td2d++, seq_prev = seq)
2692                 {
2693                         tdsq = (TransDataSeq *)td->extra;
2694                         seq = tdsq->seq;
2695                         if ((seq != seq_prev) && (seq->depth != 0)) {
2696                                 if (seq->seq1 || seq->seq2 || seq->seq3) {
2697                                         BKE_sequence_calc(t->scene, seq);
2698                                 }
2699                         }
2700                 }
2701         }
2702
2703         /* need to do the overlap check in a new loop otherwise adjacent strips
2704          * will not be updated and we'll get false positives */
2705         seq_prev = NULL;
2706         for (a = 0, td = t->data, td2d = t->data2d; a < t->total; a++, td++, td2d++) {
2707
2708                 tdsq = (TransDataSeq *)td->extra;
2709                 seq = tdsq->seq;
2710
2711                 if (seq != seq_prev) {
2712                         if (seq->depth == 0) {
2713                                 /* test overlap, displayes red outline */
2714                                 seq->flag &= ~SEQ_OVERLAP;
2715                                 if (BKE_sequence_test_overlap(seqbasep, seq)) {
2716                                         seq->flag |= SEQ_OVERLAP;
2717                                 }
2718                         }
2719                 }
2720                 seq_prev = seq;
2721         }
2722 }
2723
2724 /* ********************* UV ****************** */
2725
2726 static void UVsToTransData(
2727         const float aspect[2], TransData *td, TransData2D *td2d,
2728         float *uv, const float *center, bool selected)
2729 {
2730         /* uv coords are scaled by aspects. this is needed for rotations and
2731          * proportional editing to be consistent with the stretched uv coords
2732          * that are displayed. this also means that for display and numinput,
2733          * and when the uv coords are flushed, these are converted each time */
2734         td2d->loc[0] = uv[0] * aspect[0];
2735         td2d->loc[1] = uv[1] * aspect[1];
2736         td2d->loc[2] = 0.0f;
2737         td2d->loc2d = uv;
2738
2739         td->flag = 0;
2740         td->loc = td2d->loc;
2741         copy_v2_v2(td->center, center ? center : td->loc);
2742         td->center[2] = 0.0f;
2743         copy_v3_v3(td->iloc, td->loc);
2744
2745         memset(td->axismtx, 0, sizeof(td->axismtx));
2746         td->axismtx[2][2] = 1.0f;
2747
2748         td->ext = NULL; td->val = NULL;
2749
2750         if (selected) {
2751                 td->flag |= TD_SELECTED;
2752                 td->dist = 0.0;
2753         }
2754         else {
2755                 td->dist = FLT_MAX;
2756         }
2757         unit_m3(td->mtx);
2758         unit_m3(td->smtx);
2759 }
2760
2761 static void createTransUVs(bContext *C, TransInfo *t)
2762 {
2763         SpaceImage *sima = CTX_wm_space_image(C);
2764         Image *ima = CTX_data_edit_image(C);
2765         Scene *scene = t->scene;
2766         ToolSettings *ts = CTX_data_tool_settings(C);
2767         TransData *td = NULL;
2768         TransData2D *td2d = NULL;
2769         BMEditMesh *em = BKE_editmesh_from_object(t->obedit);
2770         BMFace *efa;
2771         BMIter iter, liter;
2772         UvElementMap *elementmap = NULL;
2773         BLI_bitmap *island_enabled = NULL;
2774         struct { float co[2]; int co_num; } *island_center = NULL;
2775         int count = 0, countsel = 0, count_rejected = 0;
2776         const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
2777         const bool is_prop_connected = (t->flag & T_PROP_CONNECTED) != 0;
2778         const bool is_island_center = (t->around == V3D_AROUND_LOCAL_ORIGINS);
2779         const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
2780         const int cd_poly_tex_offset = CustomData_get_offset(&em->bm->pdata, CD_MTEXPOLY);
2781
2782         if (!ED_space_image_show_uvedit(sima, t->obedit))
2783                 return;
2784
2785         /* count */
2786         if (is_prop_connected || is_island_center) {
2787                 /* create element map with island information */
2788                 const bool&nbs