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