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