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