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