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