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