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