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