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