fix for msvc
[blender.git] / source / blender / editors / armature / editarmature.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * Contributor(s): Blender Foundation, 2002-2009 full recode.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <ctype.h>
29 #include <stdlib.h>
30 #include <stddef.h>
31 #include <string.h>
32 #include <math.h> 
33 #include <float.h> 
34
35
36 #include "DNA_anim_types.h"
37 #include "DNA_armature_types.h"
38 #include "DNA_constraint_types.h"
39 #include "DNA_meshdata_types.h"
40 #include "DNA_scene_types.h"
41
42 #include "MEM_guardedalloc.h"
43
44 #include "BLI_blenlib.h"
45 #include "BLI_math.h"
46 #include "BLI_editVert.h"
47 #include "BLI_ghash.h"
48
49 #include "BKE_animsys.h"
50 #include "BKE_action.h"
51 #include "BKE_armature.h"
52 #include "BKE_constraint.h"
53 #include "BKE_context.h"
54 #include "BKE_deform.h"
55 #include "BKE_depsgraph.h"
56 #include "BKE_DerivedMesh.h"
57 #include "BKE_global.h"
58 #include "BKE_idprop.h"
59 #include "BKE_main.h"
60 #include "BKE_object.h"
61 #include "BKE_report.h"
62 #include "BKE_subsurf.h"
63 #include "BKE_modifier.h"
64 #include "DNA_object_types.h"
65
66 #include "BIF_gl.h"
67
68 #include "RNA_access.h"
69 #include "RNA_define.h"
70
71 #include "WM_api.h"
72 #include "WM_types.h"
73
74 #include "ED_armature.h"
75 #include "ED_keyframing.h"
76 #include "ED_mesh.h"
77 #include "ED_object.h"
78 #include "ED_screen.h"
79 #include "ED_util.h"
80 #include "ED_view3d.h"
81
82 #include "UI_interface.h"
83
84 #include "armature_intern.h"
85 #include "meshlaplacian.h"
86
87 #if 0
88 #include "reeb.h"
89 #endif
90
91 /* ************* XXX *************** */
92 static void BIF_undo_push(const char *msg) {}
93 /* ************* XXX *************** */
94
95 /* **************** tools on Editmode Armature **************** */
96
97 /* Sync selection to parent for connected children */
98 void ED_armature_sync_selection(ListBase *edbo)
99 {
100         EditBone *ebo;
101         
102         for (ebo=edbo->first; ebo; ebo= ebo->next) {
103                 /* if bone is not selectable, we shouldn't alter this setting... */
104                 if ((ebo->flag & BONE_UNSELECTABLE) == 0) {
105                         if ((ebo->flag & BONE_CONNECTED) && (ebo->parent)) {
106                                 if (ebo->parent->flag & BONE_TIPSEL)
107                                         ebo->flag |= BONE_ROOTSEL;
108                                 else
109                                         ebo->flag &= ~BONE_ROOTSEL;
110                         }
111                         
112                         if ((ebo->flag & BONE_TIPSEL) && (ebo->flag & BONE_ROOTSEL))
113                                 ebo->flag |= BONE_SELECTED;
114                         else
115                                 ebo->flag &= ~BONE_SELECTED;
116                 }
117         }                               
118 }
119
120 void ED_armature_validate_active(struct bArmature *arm)
121 {
122         EditBone *ebone= arm->act_edbone;
123
124         if(ebone) { 
125                 if(ebone->flag & BONE_HIDDEN_A || (ebone->flag & BONE_SELECTED)==0)
126                         arm->act_edbone= NULL;
127         }
128 }
129
130 static void bone_free(bArmature *arm, EditBone *bone)
131 {
132         if(arm->act_edbone==bone)
133                 arm->act_edbone= NULL;
134
135         if(bone->prop) {
136                 IDP_FreeProperty(bone->prop);
137                 MEM_freeN(bone->prop);
138         }
139
140         BLI_freelinkN(arm->edbo, bone);
141 }
142
143 void ED_armature_edit_bone_remove(bArmature *arm, EditBone *exBone)
144 {
145         EditBone *curBone;
146
147         /* Find any bones that refer to this bone */
148         for (curBone=arm->edbo->first; curBone; curBone=curBone->next) {
149                 if (curBone->parent==exBone) {
150                         curBone->parent=exBone->parent;
151                         curBone->flag &= ~BONE_CONNECTED;
152                 }
153         }
154
155         bone_free(arm, exBone);
156 }
157
158
159 /* converts Bones to EditBone list, used for tools as well */
160 EditBone *make_boneList(ListBase *edbo, ListBase *bones, EditBone *parent, Bone *actBone)
161 {
162         EditBone        *eBone;
163         EditBone        *eBoneAct= NULL;
164         EditBone        *eBoneTest= NULL;
165         Bone            *curBone;
166         float delta[3];
167         float premat[3][3];
168         float postmat[3][3];
169         float imat[3][3];
170         float difmat[3][3];
171                 
172         for (curBone=bones->first; curBone; curBone=curBone->next) {
173                 eBone= MEM_callocN(sizeof(EditBone), "make_editbone");
174                 
175                 /*      Copy relevant data from bone to eBone */
176                 eBone->parent= parent;
177                 BLI_strncpy(eBone->name, curBone->name, 32);
178                 eBone->flag = curBone->flag;
179                 
180                 /* fix selection flags */
181                 if (eBone->flag & BONE_SELECTED) {
182                         eBone->flag |= BONE_TIPSEL;
183                         if (eBone->parent && (eBone->flag & BONE_CONNECTED))
184                                 eBone->parent->flag |= BONE_TIPSEL;
185                         else 
186                                 eBone->flag |= BONE_ROOTSEL;
187                 }
188                 else 
189                         eBone->flag &= ~BONE_ROOTSEL;
190                 
191                 VECCOPY(eBone->head, curBone->arm_head);
192                 VECCOPY(eBone->tail, curBone->arm_tail);                
193                 
194                 eBone->roll= 0.0f;
195                 
196                 /* roll fixing */
197                 sub_v3_v3v3(delta, eBone->tail, eBone->head);
198                 vec_roll_to_mat3(delta, 0.0f, postmat);
199                 
200                 copy_m3_m4(premat, curBone->arm_mat);
201                 
202                 invert_m3_m3(imat, postmat);
203                 mul_m3_m3m3(difmat, imat, premat);
204                 
205                 eBone->roll = (float)atan2(difmat[2][0], difmat[2][2]);
206                 
207                 /* rest of stuff copy */
208                 eBone->length= curBone->length;
209                 eBone->dist= curBone->dist;
210                 eBone->weight= curBone->weight;
211                 eBone->xwidth= curBone->xwidth;
212                 eBone->zwidth= curBone->zwidth;
213                 eBone->ease1= curBone->ease1;
214                 eBone->ease2= curBone->ease2;
215                 eBone->rad_head= curBone->rad_head;
216                 eBone->rad_tail= curBone->rad_tail;
217                 eBone->segments = curBone->segments;            
218                 eBone->layer = curBone->layer;
219
220                 if(curBone->prop)
221                         eBone->prop= IDP_CopyProperty(curBone->prop);
222                 
223                 BLI_addtail(edbo, eBone);
224                 
225                 /*      Add children if necessary */
226                 if (curBone->childbase.first) {
227                         eBoneTest= make_boneList(edbo, &curBone->childbase, eBone, actBone);
228                         if(eBoneTest)
229                                 eBoneAct= eBoneTest;
230                 }
231
232                 if(curBone==actBone)
233                         eBoneAct= eBone;
234         }
235
236         return eBoneAct;
237 }
238
239 /* nasty stuff for converting roll in editbones into bones */
240 /* also sets restposition in armature (arm_mat) */
241 static void fix_bonelist_roll (ListBase *bonelist, ListBase *editbonelist)
242 {
243         Bone *curBone;
244         EditBone *ebone;
245         float premat[3][3];
246         float postmat[3][3];
247         float difmat[3][3];
248         float imat[3][3];
249         float delta[3];
250         
251         for (curBone=bonelist->first; curBone; curBone=curBone->next) {
252                 /* sets local matrix and arm_mat (restpos) */
253                 where_is_armature_bone(curBone, curBone->parent);
254                 
255                 /* Find the associated editbone */
256                 for (ebone = editbonelist->first; ebone; ebone=ebone->next)
257                         if ((Bone*)ebone->temp == curBone)
258                                 break;
259                 
260                 if (ebone) {
261                         /* Get the ebone premat */
262                         sub_v3_v3v3(delta, ebone->tail, ebone->head);
263                         vec_roll_to_mat3(delta, ebone->roll, premat);
264                         
265                         /* Get the bone postmat */
266                         copy_m3_m4(postmat, curBone->arm_mat);
267                         
268                         invert_m3_m3(imat, premat);
269                         mul_m3_m3m3(difmat, imat, postmat);
270 #if 0
271                         printf ("Bone %s\n", curBone->name);
272                         print_m4("premat", premat);
273                         print_m4("postmat", postmat);
274                         print_m4("difmat", difmat);
275                         printf ("Roll = %f\n",  (-atan2(difmat[2][0], difmat[2][2]) * (180.0/M_PI)));
276 #endif
277                         curBone->roll = (float)-atan2(difmat[2][0], difmat[2][2]);
278                         
279                         /* and set restposition again */
280                         where_is_armature_bone(curBone, curBone->parent);
281                 }
282                 fix_bonelist_roll(&curBone->childbase, editbonelist);
283         }
284 }
285
286 /* put EditMode back in Object */
287 void ED_armature_from_edit(Object *obedit)
288 {
289         bArmature *arm= obedit->data;
290         EditBone *eBone, *neBone;
291         Bone    *newBone;
292         Object *obt;
293         
294         /* armature bones */
295         free_bonelist(&arm->bonebase);
296         
297         /* remove zero sized bones, this gives instable restposes */
298         for (eBone=arm->edbo->first; eBone; eBone= neBone) {
299                 float len= len_v3v3(eBone->head, eBone->tail);
300                 neBone= eBone->next;
301                 if (len <= 0.000001f) {         /* FLT_EPSILON is too large? */
302                         EditBone *fBone;
303                         
304                         /*      Find any bones that refer to this bone  */
305                         for (fBone=arm->edbo->first; fBone; fBone= fBone->next) {
306                                 if (fBone->parent==eBone)
307                                         fBone->parent= eBone->parent;
308                         }
309                         if (G.f & G_DEBUG)
310                                 printf("Warning: removed zero sized bone: %s\n", eBone->name);
311                         bone_free(arm, eBone);
312                 }
313         }
314         
315         /*      Copy the bones from the editData into the armature */
316         for (eBone=arm->edbo->first; eBone; eBone=eBone->next) {
317                 newBone= MEM_callocN(sizeof(Bone), "bone");
318                 eBone->temp= newBone;   /* Associate the real Bones with the EditBones */
319                 
320                 BLI_strncpy(newBone->name, eBone->name, 32);
321                 memcpy(newBone->head, eBone->head, sizeof(float)*3);
322                 memcpy(newBone->tail, eBone->tail, sizeof(float)*3);
323                 newBone->flag= eBone->flag;
324                 
325                 if (eBone == arm->act_edbone) {
326                         newBone->flag |= BONE_SELECTED; /* important, editbones can be active with only 1 point selected */
327                         arm->act_edbone= NULL;
328                         arm->act_bone= newBone;
329                 }
330                 newBone->roll = 0.0f;
331                 
332                 newBone->weight = eBone->weight;
333                 newBone->dist = eBone->dist;
334                 
335                 newBone->xwidth = eBone->xwidth;
336                 newBone->zwidth = eBone->zwidth;
337                 newBone->ease1= eBone->ease1;
338                 newBone->ease2= eBone->ease2;
339                 newBone->rad_head= eBone->rad_head;
340                 newBone->rad_tail= eBone->rad_tail;
341                 newBone->segments= eBone->segments;
342                 newBone->layer = eBone->layer;
343                 
344                 if(eBone->prop)
345                         newBone->prop= IDP_CopyProperty(eBone->prop);
346         }
347         
348         /*      Fix parenting in a separate pass to ensure ebone->bone connections
349                 are valid at this point */
350         for (eBone=arm->edbo->first;eBone;eBone=eBone->next) {
351                 newBone= (Bone *)eBone->temp;
352                 if (eBone->parent) {
353                         newBone->parent= (Bone *)eBone->parent->temp;
354                         BLI_addtail(&newBone->parent->childbase, newBone);
355                         
356                         {
357                                 float M_boneRest[3][3];
358                                 float M_parentRest[3][3];
359                                 float iM_parentRest[3][3];
360                                 float   delta[3];
361                                 
362                                 /* Get the parent's  matrix (rotation only) */
363                                 sub_v3_v3v3(delta, eBone->parent->tail, eBone->parent->head);
364                                 vec_roll_to_mat3(delta, eBone->parent->roll, M_parentRest);
365                                 
366                                 /* Get this bone's  matrix (rotation only) */
367                                 sub_v3_v3v3(delta, eBone->tail, eBone->head);
368                                 vec_roll_to_mat3(delta, eBone->roll, M_boneRest);
369                                 
370                                 /* Invert the parent matrix */
371                                 invert_m3_m3(iM_parentRest, M_parentRest);
372                                 
373                                 /* Get the new head and tail */
374                                 sub_v3_v3v3(newBone->head, eBone->head, eBone->parent->tail);
375                                 sub_v3_v3v3(newBone->tail, eBone->tail, eBone->parent->tail);
376                                 
377                                 mul_m3_v3(iM_parentRest, newBone->head);
378                                 mul_m3_v3(iM_parentRest, newBone->tail);
379                         }
380                 }
381                 /*      ...otherwise add this bone to the armature's bonebase */
382                 else
383                         BLI_addtail(&arm->bonebase, newBone);
384         }
385         
386         /* Make a pass through the new armature to fix rolling */
387         /* also builds restposition again (like where_is_armature) */
388         fix_bonelist_roll(&arm->bonebase, arm->edbo);
389         
390         /* so all users of this armature should get rebuilt */
391         for (obt= G.main->object.first; obt; obt= obt->id.next) {
392                 if (obt->data==arm)
393                         armature_rebuild_pose(obt, arm);
394         }
395         
396         DAG_id_flush_update(&obedit->id, OB_RECALC_DATA);
397 }
398
399 void ED_armature_apply_transform(Object *ob, float mat[4][4])
400 {
401         EditBone *ebone;
402         bArmature *arm= ob->data;
403         float scale = mat4_to_scale(mat);       /* store the scale of the matrix here to use on envelopes */
404         
405         /* Put the armature into editmode */
406         ED_armature_to_edit(ob);
407
408         /* Do the rotations */
409         for (ebone = arm->edbo->first; ebone; ebone=ebone->next){
410                 mul_m4_v3(mat, ebone->head);
411                 mul_m4_v3(mat, ebone->tail);
412                 
413                 ebone->rad_head *= scale;
414                 ebone->rad_tail *= scale;
415                 ebone->dist             *= scale;
416         }
417         
418         /* Turn the list into an armature */
419         ED_armature_from_edit(ob);
420         ED_armature_edit_free(ob);
421 }
422
423 /* exported for use in editors/object/ */
424 /* 0 == do center, 1 == center new, 2 == center cursor */
425 void docenter_armature (Scene *scene, Object *ob, float cursor[3], int centermode, int around)
426 {
427         Object *obedit= scene->obedit; // XXX get from context
428         EditBone *ebone;
429         bArmature *arm= ob->data;
430         float cent[3];
431
432         /* Put the armature into editmode */
433         if(ob != obedit) {
434                 ED_armature_to_edit(ob);
435                 obedit= NULL; /* we cant use this so behave as if there is no obedit */
436         }
437
438         /* Find the centerpoint */
439         if (centermode == 2) {
440                 copy_v3_v3(cent, cursor);
441                 invert_m4_m4(ob->imat, ob->obmat);
442                 mul_m4_v3(ob->imat, cent);
443         }
444         else {
445                 if(around==V3D_CENTROID) {
446                         int total= 0;
447                         zero_v3(cent);
448                         for (ebone= arm->edbo->first; ebone; ebone=ebone->next) {
449                                 total+=2;
450                                 add_v3_v3(cent, ebone->head);
451                                 add_v3_v3(cent, ebone->tail);
452                         }
453                         mul_v3_fl(cent, 1.0f/(float)total);
454                 }
455                 else {
456                         float min[3], max[3];
457                         INIT_MINMAX(min, max);
458                         for (ebone= arm->edbo->first; ebone; ebone=ebone->next) {
459                                 DO_MINMAX(ebone->head, min, max);
460                                 DO_MINMAX(ebone->tail, min, max);
461                         }
462                         mid_v3_v3v3(cent, min, max);
463                 }
464         }
465         
466         /* Do the adjustments */
467         for (ebone= arm->edbo->first; ebone; ebone=ebone->next) {
468                 sub_v3_v3(ebone->head, cent);
469                 sub_v3_v3(ebone->tail, cent);
470         }
471         
472         /* Turn the list into an armature */
473         if(obedit==NULL) {
474                 ED_armature_from_edit(ob);
475                 ED_armature_edit_free(ob);
476         }
477
478         /* Adjust object location for new centerpoint */
479         if(centermode && obedit==NULL) {
480                 mul_mat3_m4_v3(ob->obmat, cent); /* ommit translation part */
481                 add_v3_v3(ob->loc, cent);
482         }
483 }
484
485 /* ---------------------- */
486
487 /* checks if an EditBone with a matching name already, returning the matching bone if it exists */
488 static EditBone *editbone_name_exists (ListBase *edbo, const char *name)
489 {
490         return BLI_findstring(edbo, name, offsetof(EditBone, name));
491 }
492
493 /* note: there's a unique_bone_name() too! */
494 void unique_editbone_name (ListBase *edbo, char *name, EditBone *bone)
495 {
496         EditBone *dupli;
497         char    tempname[64];
498         int             number;
499         char    *dot;
500
501         dupli = editbone_name_exists(edbo, name);
502         
503         if (dupli && bone != dupli) {
504                 /*      Strip off the suffix, if it's a number */
505                 number= strlen(name);
506                 if (number && isdigit(name[number-1])) {
507                         dot= strrchr(name, '.');        // last occurrence
508                         if (dot)
509                                 *dot=0;
510                 }
511                 
512                 for (number = 1; number <= 999; number++) {
513                         sprintf(tempname, "%s.%03d", name, number);
514                         if (!editbone_name_exists(edbo, tempname)) {
515                                 BLI_strncpy(name, tempname, 32);
516                                 return;
517                         }
518                 }
519         }
520 }
521
522 /* helper for apply_armature_pose2bones - fixes parenting of objects that are bone-parented to armature */
523 static void applyarmature_fix_boneparents (Scene *scene, Object *armob)
524 {
525         Object workob, *ob;
526         
527         /* go through all objects in database */
528         for (ob= G.main->object.first; ob; ob= ob->id.next) {
529                 /* if parent is bone in this armature, apply corrections */
530                 if ((ob->parent == armob) && (ob->partype == PARBONE)) {
531                         /* apply current transform from parent (not yet destroyed), 
532                          * then calculate new parent inverse matrix
533                          */
534                         object_apply_mat4(ob, ob->obmat);
535                         
536                         what_does_parent(scene, ob, &workob);
537                         invert_m4_m4(ob->parentinv, workob.obmat);
538                 }
539         }
540 }
541
542 /* set the current pose as the restpose */
543 static int apply_armature_pose2bones_exec (bContext *C, wmOperator *op)
544 {
545         Scene *scene= CTX_data_scene(C);
546         Object *ob= CTX_data_active_object(C); // must be active object, not edit-object
547         bArmature *arm= get_armature(ob);
548         bPose *pose;
549         bPoseChannel *pchan;
550         EditBone *curbone;
551         
552         /* don't check if editmode (should be done by caller) */
553         if (ob->type!=OB_ARMATURE)
554                 return OPERATOR_CANCELLED;
555         if (object_data_is_libdata(ob)) {
556                 BKE_report(op->reports, RPT_ERROR, "Cannot apply pose to lib-linked armature."); //error_libdata();
557                 return OPERATOR_CANCELLED;
558         }
559         
560         /* helpful warnings... */
561         // TODO: add warnings to be careful about actions, applying deforms first, etc.
562         
563         /* Get editbones of active armature to alter */
564         ED_armature_to_edit(ob);        
565         
566         /* get pose of active object and move it out of posemode */
567         pose= ob->pose;
568         
569         for (pchan=pose->chanbase.first; pchan; pchan=pchan->next) {
570                 curbone= editbone_name_exists(arm->edbo, pchan->name);
571                 
572                 /* simply copy the head/tail values from pchan over to curbone */
573                 VECCOPY(curbone->head, pchan->pose_head);
574                 VECCOPY(curbone->tail, pchan->pose_tail);
575                 
576                 /* fix roll:
577                  *      1. find auto-calculated roll value for this bone now
578                  *      2. remove this from the 'visual' y-rotation
579                  */
580                 {
581                         float premat[3][3], imat[3][3],pmat[3][3], tmat[3][3];
582                         float delta[3], eul[3];
583                         
584                         /* obtain new auto y-rotation */
585                         sub_v3_v3v3(delta, curbone->tail, curbone->head);
586                         vec_roll_to_mat3(delta, 0.0f, premat);
587                         invert_m3_m3(imat, premat);
588                         
589                         /* get pchan 'visual' matrix */
590                         copy_m3_m4(pmat, pchan->pose_mat);
591                         
592                         /* remove auto from visual and get euler rotation */
593                         mul_m3_m3m3(tmat, imat, pmat);
594                         mat3_to_eul( eul,tmat);
595                         
596                         /* just use this euler-y as new roll value */
597                         curbone->roll= eul[1];
598                 }
599                 
600                 /* clear transform values for pchan */
601                 pchan->loc[0]= pchan->loc[1]= pchan->loc[2]= 0.0f;
602                 pchan->eul[0]= pchan->eul[1]= pchan->eul[2]= 0.0f;
603                 pchan->quat[1]= pchan->quat[2]= pchan->quat[3]= 0.0f;
604                 pchan->quat[0]= pchan->size[0]= pchan->size[1]= pchan->size[2]= 1.0f;
605                 
606                 /* set anim lock */
607                 curbone->flag |= BONE_UNKEYED;
608         }
609         
610         /* convert editbones back to bones, and then free the edit-data */
611         ED_armature_from_edit(ob);
612         ED_armature_edit_free(ob);
613         
614         /* flush positions of posebones */
615         where_is_pose(scene, ob);
616         
617         /* fix parenting of objects which are bone-parented */
618         applyarmature_fix_boneparents(scene, ob);
619         
620         /* note, notifier might evolve */
621         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, ob);
622         
623         return OPERATOR_FINISHED;
624 }
625
626 void POSE_OT_armature_apply (wmOperatorType *ot)
627 {
628         /* identifiers */
629         ot->name= "Apply Pose as Rest Pose";
630         ot->idname= "POSE_OT_armature_apply";
631         ot->description= "Apply the current pose as the new rest pose";
632         
633         /* callbacks */
634         ot->exec= apply_armature_pose2bones_exec;
635         ot->poll= ED_operator_posemode;
636         
637         /* flags */
638         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
639 }
640
641
642 /* set the current pose as the restpose */
643 static int pose_visual_transform_apply_exec (bContext *C, wmOperator *op)
644 {
645         Scene *scene= CTX_data_scene(C);
646         Object *ob= CTX_data_active_object(C); // must be active object, not edit-object
647
648         /* don't check if editmode (should be done by caller) */
649         if (ob->type!=OB_ARMATURE)
650                 return OPERATOR_CANCELLED;
651
652         /* loop over all selected pchans
653          *
654          * TODO, loop over children before parents if multiple bones
655          * at once are to be predictable*/
656         CTX_DATA_BEGIN(C, bPoseChannel *, pchan, selected_pose_bones)
657         {
658                 float delta_mat[4][4], imat[4][4], mat[4][4];
659
660                 where_is_pose_bone(scene, ob, pchan, CFRA, 1);
661
662                 copy_m4_m4(mat, pchan->pose_mat);
663
664                 /* calculate pchan->pose_mat without loc/size/rot & constraints applied */
665                 where_is_pose_bone(scene, ob, pchan, CFRA, 0);
666                 invert_m4_m4(imat, pchan->pose_mat);
667                 mul_m4_m4m4(delta_mat, mat, imat);
668
669                 pchan_apply_mat4(pchan, delta_mat);
670
671                 where_is_pose_bone(scene, ob, pchan, CFRA, 1);
672         }
673         CTX_DATA_END;
674
675         // ob->pose->flag |= (POSE_LOCKED|POSE_DO_UNLOCK);
676         DAG_id_flush_update(&ob->id, OB_RECALC_DATA);
677
678         /* note, notifier might evolve */
679         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, ob);
680
681         return OPERATOR_FINISHED;
682 }
683
684 void POSE_OT_visual_transform_apply (wmOperatorType *ot)
685 {
686         /* identifiers */
687         ot->name= "Apply Visual Transform to Pose";
688         ot->idname= "POSE_OT_visual_transform_apply";
689         ot->description= "Apply final constrained position of pose bones to their transform.";
690         
691         /* callbacks */
692         ot->exec= pose_visual_transform_apply_exec;
693         ot->poll= ED_operator_posemode;
694         
695         /* flags */
696         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
697 }
698
699 /* ---------------------- */
700
701 /* Helper function for armature joining - link fixing */
702 static void joined_armature_fix_links(Object *tarArm, Object *srcArm, bPoseChannel *pchan, EditBone *curbone)
703 {
704         Object *ob;
705         bPose *pose;
706         bPoseChannel *pchant;
707         bConstraint *con;
708         
709         /* let's go through all objects in database */
710         for (ob= G.main->object.first; ob; ob= ob->id.next) {
711                 /* do some object-type specific things */
712                 if (ob->type == OB_ARMATURE) {
713                         pose= ob->pose;
714                         for (pchant= pose->chanbase.first; pchant; pchant= pchant->next) {
715                                 for (con= pchant->constraints.first; con; con= con->next) {
716                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
717                                         ListBase targets = {NULL, NULL};
718                                         bConstraintTarget *ct;
719                                         
720                                         /* constraint targets */
721                                         if (cti && cti->get_constraint_targets) {
722                                                 cti->get_constraint_targets(con, &targets);
723                                                 
724                                                 for (ct= targets.first; ct; ct= ct->next) {
725                                                         if (ct->tar == srcArm) {
726                                                                 if (strcmp(ct->subtarget, "")==0) {
727                                                                         ct->tar = tarArm;
728                                                                 }
729                                                                 else if (strcmp(ct->subtarget, pchan->name)==0) {
730                                                                         ct->tar = tarArm;
731                                                                         strcpy(ct->subtarget, curbone->name);
732                                                                 }
733                                                         }
734                                                 }
735                                                 
736                                                 if (cti->flush_constraint_targets)
737                                                         cti->flush_constraint_targets(con, &targets, 0);
738                                         }
739                                         
740                                         /* action constraint? */
741                                         if (con->type == CONSTRAINT_TYPE_ACTION) {
742                                                 bActionConstraint *data= con->data; // XXX old animation system
743                                                 bAction *act;
744                                                 bActionChannel *achan;
745                                                 
746                                                 if (data->act) {
747                                                         act= data->act;
748                                                         
749                                                         for (achan= act->chanbase.first; achan; achan= achan->next) {
750                                                                 if (strcmp(achan->name, pchan->name)==0)
751                                                                         BLI_strncpy(achan->name, curbone->name, 32);
752                                                         }
753                                                 }
754                                         }
755                                         
756                                 }
757                         }
758                 }
759                         
760                 /* fix object-level constraints */
761                 if (ob != srcArm) {
762                         for (con= ob->constraints.first; con; con= con->next) {
763                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
764                                 ListBase targets = {NULL, NULL};
765                                 bConstraintTarget *ct;
766                                 
767                                 /* constraint targets */
768                                 if (cti && cti->get_constraint_targets) {
769                                         cti->get_constraint_targets(con, &targets);
770                                         
771                                         for (ct= targets.first; ct; ct= ct->next) {
772                                                 if (ct->tar == srcArm) {
773                                                         if (strcmp(ct->subtarget, "")==0) {
774                                                                 ct->tar = tarArm;
775                                                         }
776                                                         else if (strcmp(ct->subtarget, pchan->name)==0) {
777                                                                 ct->tar = tarArm;
778                                                                 strcpy(ct->subtarget, curbone->name);
779                                                         }
780                                                 }
781                                         }
782                                         
783                                         if (cti->flush_constraint_targets)
784                                                 cti->flush_constraint_targets(con, &targets, 0);
785                                 }
786                         }
787                 }
788                 
789                 /* See if an object is parented to this armature */
790                 if (ob->parent && (ob->parent == srcArm)) {
791                         /* Is object parented to a bone of this src armature? */
792                         if (ob->partype==PARBONE) {
793                                 /* bone name in object */
794                                 if (!strcmp(ob->parsubstr, pchan->name))
795                                         BLI_strncpy(ob->parsubstr, curbone->name, 32);
796                         }
797                         
798                         /* make tar armature be new parent */
799                         ob->parent = tarArm;
800                 }
801         }       
802 }
803
804 /* join armature exec is exported for use in object->join objects operator... */
805 int join_armature_exec(bContext *C, wmOperator *op)
806 {
807         Main *bmain= CTX_data_main(C);
808         Scene *scene= CTX_data_scene(C);
809         Object  *ob= CTX_data_active_object(C);
810         bArmature *arm= (ob)? ob->data: NULL;
811         bPose *pose, *opose;
812         bPoseChannel *pchan, *pchann;
813         EditBone *curbone;
814         float   mat[4][4], oimat[4][4];
815         
816         /*      Ensure we're not in editmode and that the active object is an armature*/
817         if (!ob || ob->type!=OB_ARMATURE)
818                 return OPERATOR_CANCELLED;
819         if (!arm || arm->edbo)
820                 return OPERATOR_CANCELLED;
821         
822         /* Get editbones of active armature to add editbones to */
823         ED_armature_to_edit(ob);
824         
825         /* get pose of active object and move it out of posemode */
826         pose= ob->pose;
827         ob->mode &= ~OB_MODE_POSE;
828
829         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
830                 if ((base->object->type==OB_ARMATURE) && (base->object!=ob)) {
831                         bArmature *curarm= base->object->data;
832                         
833                         /* Make a list of editbones in current armature */
834                         ED_armature_to_edit(base->object);
835                         
836                         /* Get Pose of current armature */
837                         opose= base->object->pose;
838                         base->object->mode &= ~OB_MODE_POSE;
839                         //BASACT->flag &= ~OB_MODE_POSE;
840                         
841                         /* Find the difference matrix */
842                         invert_m4_m4(oimat, ob->obmat);
843                         mul_m4_m4m4(mat, base->object->obmat, oimat);
844                         
845                         /* Copy bones and posechannels from the object to the edit armature */
846                         for (pchan=opose->chanbase.first; pchan; pchan=pchann) {
847                                 pchann= pchan->next;
848                                 curbone= editbone_name_exists(curarm->edbo, pchan->name);
849                                 
850                                 /* Get new name */
851                                 unique_editbone_name(arm->edbo, curbone->name, NULL);
852                                 
853                                 /* Transform the bone */
854                                 {
855                                         float premat[4][4];
856                                         float postmat[4][4];
857                                         float difmat[4][4];
858                                         float imat[4][4];
859                                         float temp[3][3];
860                                         float delta[3];
861                                         
862                                         /* Get the premat */
863                                         sub_v3_v3v3(delta, curbone->tail, curbone->head);
864                                         vec_roll_to_mat3(delta, curbone->roll, temp);
865                                         
866                                         unit_m4(premat); /* Mat4MulMat34 only sets 3x3 part */
867                                         mul_m4_m3m4(premat, temp, mat);
868                                         
869                                         mul_m4_v3(mat, curbone->head);
870                                         mul_m4_v3(mat, curbone->tail);
871                                         
872                                         /* Get the postmat */
873                                         sub_v3_v3v3(delta, curbone->tail, curbone->head);
874                                         vec_roll_to_mat3(delta, curbone->roll, temp);
875                                         copy_m4_m3(postmat, temp);
876                                         
877                                         /* Find the roll */
878                                         invert_m4_m4(imat, premat);
879                                         mul_m4_m4m4(difmat, postmat, imat);
880                                         
881                                         curbone->roll -= (float)atan2(difmat[2][0], difmat[2][2]);
882                                 }
883                                 
884                                 /* Fix Constraints and Other Links to this Bone and Armature */
885                                 joined_armature_fix_links(ob, base->object, pchan, curbone);
886                                 
887                                 /* Rename pchan */
888                                 BLI_strncpy(pchan->name, curbone->name, sizeof(pchan->name));
889                                 
890                                 /* Jump Ship! */
891                                 BLI_remlink(curarm->edbo, curbone);
892                                 BLI_addtail(arm->edbo, curbone);
893                                 
894                                 BLI_remlink(&opose->chanbase, pchan);
895                                 BLI_addtail(&pose->chanbase, pchan);
896                                 free_pose_channels_hash(opose);
897                                 free_pose_channels_hash(pose);
898                         }
899                         
900                         ED_base_object_free_and_unlink(bmain, scene, base);
901                 }
902         }
903         CTX_DATA_END;
904         
905         DAG_scene_sort(bmain, scene);   // because we removed object(s)
906
907         ED_armature_from_edit(ob);
908         ED_armature_edit_free(ob);
909
910         WM_event_add_notifier(C, NC_SCENE|ND_OB_ACTIVE, scene);
911         
912         return OPERATOR_FINISHED;
913 }
914
915 /* ---------------------- */
916
917 /* Helper function for armature separating - link fixing */
918 static void separated_armature_fix_links(Object *origArm, Object *newArm)
919 {
920         Object *ob;
921         bPoseChannel *pchan, *pcha, *pchb;
922         bConstraint *con;
923         ListBase *opchans, *npchans;
924         
925         /* get reference to list of bones in original and new armatures  */
926         opchans= &origArm->pose->chanbase;
927         npchans= &newArm->pose->chanbase;
928         
929         /* let's go through all objects in database */
930         for (ob= G.main->object.first; ob; ob= ob->id.next) {
931                 /* do some object-type specific things */
932                 if (ob->type == OB_ARMATURE) {
933                         for (pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
934                                 for (con= pchan->constraints.first; con; con= con->next) {
935                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
936                                         ListBase targets = {NULL, NULL};
937                                         bConstraintTarget *ct;
938                                         
939                                         /* constraint targets */
940                                         if (cti && cti->get_constraint_targets) {
941                                                 cti->get_constraint_targets(con, &targets);
942                                                 
943                                                 for (ct= targets.first; ct; ct= ct->next) {
944                                                         /* any targets which point to original armature are redirected to the new one only if:
945                                                          *      - the target isn't origArm/newArm itself
946                                                          *      - the target is one that can be found in newArm/origArm
947                                                          */
948                                                         if ((ct->tar == origArm) && (ct->subtarget[0] != 0)) {
949                                                                 for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
950                                                                         /* check if either one matches */
951                                                                         if ( (strcmp(pcha->name, ct->subtarget)==0) ||
952                                                                                  (strcmp(pchb->name, ct->subtarget)==0) )
953                                                                         {
954                                                                                 ct->tar= newArm;
955                                                                                 break;
956                                                                         }
957                                                                         
958                                                                         /* check if both ends have met (to stop checking) */
959                                                                         if (pcha == pchb) break;
960                                                                 }                                                               
961                                                         }
962                                                         else if ((ct->tar == newArm) && (ct->subtarget[0] != 0)) {
963                                                                 for (pcha=opchans->first, pchb=opchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
964                                                                         /* check if either one matches */
965                                                                         if ( (strcmp(pcha->name, ct->subtarget)==0) ||
966                                                                                  (strcmp(pchb->name, ct->subtarget)==0) )
967                                                                         {
968                                                                                 ct->tar= origArm;
969                                                                                 break;
970                                                                         }
971                                                                         
972                                                                         /* check if both ends have met (to stop checking) */
973                                                                         if (pcha == pchb) break;
974                                                                 }                                                               
975                                                         }
976                                                 }
977                                                 
978                                                 if (cti->flush_constraint_targets)
979                                                         cti->flush_constraint_targets(con, &targets, 0);
980                                         }
981                                 }
982                         }
983                 }
984                         
985                 /* fix object-level constraints */
986                 if (ob != origArm) {
987                         for (con= ob->constraints.first; con; con= con->next) {
988                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
989                                 ListBase targets = {NULL, NULL};
990                                 bConstraintTarget *ct;
991                                 
992                                 /* constraint targets */
993                                 if (cti && cti->get_constraint_targets) {
994                                         cti->get_constraint_targets(con, &targets);
995                                         
996                                         for (ct= targets.first; ct; ct= ct->next) {
997                                                 /* any targets which point to original armature are redirected to the new one only if:
998                                                  *      - the target isn't origArm/newArm itself
999                                                  *      - the target is one that can be found in newArm/origArm
1000                                                  */
1001                                                 if ((ct->tar == origArm) && (ct->subtarget[0] != 0)) {
1002                                                         for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
1003                                                                 /* check if either one matches */
1004                                                                 if ( (strcmp(pcha->name, ct->subtarget)==0) ||
1005                                                                          (strcmp(pchb->name, ct->subtarget)==0) )
1006                                                                 {
1007                                                                         ct->tar= newArm;
1008                                                                         break;
1009                                                                 }
1010                                                                 
1011                                                                 /* check if both ends have met (to stop checking) */
1012                                                                 if (pcha == pchb) break;
1013                                                         }                                                               
1014                                                 }
1015                                                 else if ((ct->tar == newArm) && (ct->subtarget[0] != 0)) {
1016                                                         for (pcha=opchans->first, pchb=opchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
1017                                                                 /* check if either one matches */
1018                                                                 if ( (strcmp(pcha->name, ct->subtarget)==0) ||
1019                                                                          (strcmp(pchb->name, ct->subtarget)==0) )
1020                                                                 {
1021                                                                         ct->tar= origArm;
1022                                                                         break;
1023                                                                 }
1024                                                                 
1025                                                                 /* check if both ends have met (to stop checking) */
1026                                                                 if (pcha == pchb) break;
1027                                                         }                                                               
1028                                                 }
1029                                         }
1030                                         
1031                                         if (cti->flush_constraint_targets)
1032                                                 cti->flush_constraint_targets(con, &targets, 0);
1033                                 }
1034                         }
1035                 }
1036                 
1037                 /* See if an object is parented to this armature */
1038                 if ((ob->parent) && (ob->parent == origArm)) {
1039                         /* Is object parented to a bone of this src armature? */
1040                         if (ob->partype==PARBONE) {
1041                                 /* bone name in object */
1042                                 for (pcha=npchans->first, pchb=npchans->last; pcha && pchb; pcha=pcha->next, pchb=pchb->prev) {
1043                                         /* check if either one matches */
1044                                         if ( (strcmp(pcha->name, ob->parsubstr)==0) ||
1045                                                  (strcmp(pchb->name, ob->parsubstr)==0) )
1046                                         {
1047                                                 ob->parent= newArm;
1048                                                 break;
1049                                         }
1050                                         
1051                                         /* check if both ends have met (to stop checking) */
1052                                         if (pcha == pchb) break;
1053                                 }
1054                         }
1055                 }
1056         }       
1057 }
1058
1059 /* Helper function for armature separating - remove certain bones from the given armature 
1060  *      sel: remove selected bones from the armature, otherwise the unselected bones are removed
1061  *  (ob is not in editmode)
1062  */
1063 static void separate_armature_bones (Scene *scene, Object *ob, short sel) 
1064 {
1065         bArmature *arm= (bArmature *)ob->data;
1066         bPoseChannel *pchan, *pchann;
1067         EditBone *curbone;
1068         
1069         /* make local set of editbones to manipulate here */
1070         ED_armature_to_edit(ob);
1071         
1072         /* go through pose-channels, checking if a bone should be removed */
1073         for (pchan=ob->pose->chanbase.first; pchan; pchan=pchann) {
1074                 pchann= pchan->next;
1075                 curbone= editbone_name_exists(arm->edbo, pchan->name);
1076                 
1077                 /* check if bone needs to be removed */
1078                 if ( (sel && (curbone->flag & BONE_SELECTED)) ||
1079                          (!sel && !(curbone->flag & BONE_SELECTED)) )
1080                 {
1081                         EditBone *ebo;
1082                         bPoseChannel *pchn;
1083                         
1084                         /* clear the bone->parent var of any bone that had this as its parent  */
1085                         for (ebo= arm->edbo->first; ebo; ebo= ebo->next) {
1086                                 if (ebo->parent == curbone) {
1087                                         ebo->parent= NULL;
1088                                         ebo->temp= NULL; /* this is needed to prevent random crashes with in ED_armature_from_edit */
1089                                         ebo->flag &= ~BONE_CONNECTED;
1090                                 }
1091                         }
1092                         
1093                         /* clear the pchan->parent var of any pchan that had this as its parent */
1094                         for (pchn= ob->pose->chanbase.first; pchn; pchn=pchn->next) {
1095                                 if (pchn->parent == pchan)
1096                                         pchn->parent= NULL;
1097                         }
1098                         
1099                         /* free any of the extra-data this pchan might have */
1100                         free_pose_channel(pchan);
1101                         free_pose_channels_hash(ob->pose);
1102                         
1103                         /* get rid of unneeded bone */
1104                         bone_free(arm, curbone);
1105                         BLI_freelinkN(&ob->pose->chanbase, pchan);
1106                 }
1107         }
1108         
1109         /* exit editmode (recalculates pchans too) */
1110         ED_armature_from_edit(ob);
1111         ED_armature_edit_free(ob);
1112 }
1113
1114 /* separate selected bones into their armature */
1115 static int separate_armature_exec (bContext *C, wmOperator *op)
1116 {
1117         Main *bmain= CTX_data_main(C);
1118         Scene *scene= CTX_data_scene(C);
1119         Object *obedit= CTX_data_edit_object(C);
1120         Object *oldob, *newob;
1121         Base *oldbase, *newbase;
1122         bArmature *arm;
1123         
1124         /* sanity checks */
1125         if (obedit == NULL)
1126                 return OPERATOR_CANCELLED;
1127         arm= obedit->data;
1128         
1129         /* set wait cursor in case this takes a while */
1130         WM_cursor_wait(1);
1131         
1132         /* we are going to do this as follows (unlike every other instance of separate):
1133          *      1. exit editmode +posemode for active armature/base. Take note of what this is.
1134          *      2. duplicate base - BASACT is the new one now
1135          *      3. for each of the two armatures, enter editmode -> remove appropriate bones -> exit editmode + recalc
1136          *      4. fix constraint links
1137          *      5. make original armature active and enter editmode
1138          */
1139         
1140         /* 1) only edit-base selected */
1141         // TODO: use context iterators for this?
1142         CTX_DATA_BEGIN(C, Base *, base, visible_bases) {
1143                 if (base->object==obedit) base->flag |= 1;
1144                 else base->flag &= ~1;
1145         }
1146         CTX_DATA_END;
1147         
1148         /* 1) store starting settings and exit editmode */
1149         oldob= obedit;
1150         oldbase= BASACT;
1151         oldob->mode &= ~OB_MODE_POSE;
1152         //oldbase->flag &= ~OB_POSEMODE;
1153         
1154         ED_armature_from_edit(obedit);
1155         ED_armature_edit_free(obedit);
1156         
1157         /* 2) duplicate base */
1158         newbase= ED_object_add_duplicate(bmain, scene, oldbase, USER_DUP_ARM); /* only duplicate linked armature */
1159         newob= newbase->object;         
1160         newbase->flag &= ~SELECT;
1161         
1162         
1163         /* 3) remove bones that shouldn't still be around on both armatures */
1164         separate_armature_bones(scene, oldob, 1);
1165         separate_armature_bones(scene, newob, 0);
1166         
1167         
1168         /* 4) fix links before depsgraph flushes */ // err... or after?
1169         separated_armature_fix_links(oldob, newob);
1170         
1171         DAG_id_flush_update(&oldob->id, OB_RECALC_DATA);        /* this is the original one */
1172         DAG_id_flush_update(&newob->id, OB_RECALC_DATA);        /* this is the separated one */
1173         
1174         
1175         /* 5) restore original conditions */
1176         obedit= oldob;
1177         
1178         ED_armature_to_edit(obedit);
1179         
1180         /* note, notifier might evolve */
1181         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, obedit);
1182         
1183         /* recalc/redraw + cleanup */
1184         WM_cursor_wait(0);
1185         
1186         return OPERATOR_FINISHED;
1187 }
1188
1189 void ARMATURE_OT_separate (wmOperatorType *ot)
1190 {
1191         /* identifiers */
1192         ot->name= "Separate Bones";
1193         ot->idname= "ARMATURE_OT_separate";
1194         ot->description= "Isolate selected bones into a separate armature";
1195         
1196         /* callbacks */
1197         ot->invoke= WM_operator_confirm;
1198         ot->exec= separate_armature_exec;
1199         ot->poll= ED_operator_editarmature;
1200         
1201         /* flags */
1202         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1203 }
1204
1205 /* **************** END tools on Editmode Armature **************** */
1206 /* **************** PoseMode & EditMode *************************** */
1207
1208 /* only for opengl selection indices */
1209 Bone *get_indexed_bone (Object *ob, int index)
1210 {
1211         bPoseChannel *pchan;
1212         int a= 0;
1213         
1214         if(ob->pose==NULL) return NULL;
1215         index>>=16;             // bone selection codes use left 2 bytes
1216         
1217         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next, a++) {
1218                 if(a==index) return pchan->bone;
1219         }
1220         return NULL;
1221 }
1222
1223 /* See if there are any selected bones in this buffer */
1224 /* only bones from base are checked on */
1225 static void *get_bone_from_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, short hits, short findunsel)
1226 {
1227         Object *obedit= scene->obedit; // XXX get from context
1228         Bone *bone;
1229         EditBone *ebone;
1230         void *firstunSel=NULL, *firstSel=NULL, *data;
1231         unsigned int hitresult;
1232         short i, takeNext=0, sel;
1233         
1234         for (i=0; i< hits; i++){
1235                 hitresult = buffer[3+(i*4)];
1236                 
1237                 if (!(hitresult & BONESEL_NOSEL)) {     // -1
1238                         if(hitresult & BONESEL_ANY) {   // to avoid including objects in selection
1239                                 
1240                                 hitresult &= ~(BONESEL_ANY);
1241                                 /* Determine what the current bone is */
1242                                 if (obedit==NULL || base->object!=obedit) {
1243                                         /* no singular posemode, so check for correct object */
1244                                         if(base->selcol == (hitresult & 0xFFFF)) {
1245                                                 bone = get_indexed_bone(base->object, hitresult);
1246                                                 
1247                                                 if (findunsel)
1248                                                         sel = (bone->flag & BONE_SELECTED);
1249                                                 else
1250                                                         sel = !(bone->flag & BONE_SELECTED);
1251                                                 
1252                                                 data = bone;
1253                                         }
1254                                         else {
1255                                                 data= NULL;
1256                                                 sel= 0;
1257                                         }
1258                                 }
1259                                 else{
1260                                         bArmature *arm= obedit->data;
1261                                         
1262                                         ebone = BLI_findlink(arm->edbo, hitresult);
1263                                         if (findunsel)
1264                                                 sel = (ebone->flag & BONE_SELECTED);
1265                                         else
1266                                                 sel = !(ebone->flag & BONE_SELECTED);
1267                                         
1268                                         data = ebone;
1269                                 }
1270                                 
1271                                 if(data) {
1272                                         if (sel) {
1273                                                 if(!firstSel) firstSel= data;
1274                                                 takeNext=1;
1275                                         }
1276                                         else {
1277                                                 if (!firstunSel)
1278                                                         firstunSel=data;
1279                                                 if (takeNext)
1280                                                         return data;
1281                                         }
1282                                 }
1283                         }
1284                 }
1285         }
1286         
1287         if (firstunSel)
1288                 return firstunSel;
1289         else 
1290                 return firstSel;
1291 }
1292
1293
1294
1295 /* used by posemode as well editmode */
1296 /* only checks scene->basact! */
1297 /* x and y are mouse coords (area space) */
1298 static void *get_nearest_bone (bContext *C, short findunsel, int x, int y)
1299 {
1300         ViewContext vc;
1301         rcti rect;
1302         unsigned int buffer[MAXPICKBUF];
1303         short hits;
1304         
1305         view3d_set_viewcontext(C, &vc);
1306         
1307         // rect.xmin= ... mouseco!
1308         rect.xmin= rect.xmax= x;
1309         rect.ymin= rect.ymax= y;
1310         
1311         glInitNames();
1312         hits= view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect);
1313
1314         if (hits>0)
1315                 return get_bone_from_selectbuffer(vc.scene, vc.scene->basact, buffer, hits, findunsel);
1316         
1317         return NULL;
1318 }
1319
1320 /* helper for setflag_sel_bone() */
1321 static void bone_setflag (int *bone, int flag, short mode)
1322 {
1323         if (bone && flag) {
1324                 /* exception for inverse flags */
1325                 if (flag == BONE_NO_DEFORM) {
1326                         if (mode == 2)
1327                                 *bone |= flag;
1328                         else if (mode == 1)
1329                                 *bone &= ~flag;
1330                         else
1331                                 *bone ^= flag;
1332                 }
1333                 else {
1334                         if (mode == 2)
1335                                 *bone &= ~flag;
1336                         else if (mode == 1)
1337                                 *bone |= flag;
1338                         else
1339                                 *bone ^= flag;
1340                 }
1341         }
1342 }
1343
1344 /* Get the first available child of an editbone */
1345 static EditBone *editbone_get_child(bArmature *arm, EditBone *pabone, short use_visibility)
1346 {
1347         EditBone *curbone, *chbone=NULL;
1348         
1349         for (curbone= arm->edbo->first; curbone; curbone= curbone->next) {
1350                 if (curbone->parent == pabone) {
1351                         if (use_visibility) {
1352                                 if ((arm->layer & curbone->layer) && !(pabone->flag & BONE_HIDDEN_A))
1353                                         chbone = curbone;
1354                         }
1355                         else
1356                                 chbone = curbone;
1357                 }
1358         }
1359         
1360         return chbone;
1361 }
1362
1363 /* callback for posemode setflag */
1364 static int pose_setflag_exec (bContext *C, wmOperator *op)
1365 {
1366         int flag= RNA_enum_get(op->ptr, "type");
1367         int mode= RNA_enum_get(op->ptr, "mode");
1368         
1369         /* loop over all selected pchans */
1370         CTX_DATA_BEGIN(C, bPoseChannel *, pchan, selected_pose_bones) 
1371         {
1372                 bone_setflag(&pchan->bone->flag, flag, mode);
1373         }
1374         CTX_DATA_END;
1375         
1376         /* note, notifier might evolve */
1377         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, CTX_data_active_object(C));
1378         
1379         return OPERATOR_FINISHED;
1380 }
1381
1382 /* callback for editbones setflag */
1383 static int armature_bones_setflag_exec (bContext *C, wmOperator *op)
1384 {
1385         int flag= RNA_enum_get(op->ptr, "type");
1386         int mode= RNA_enum_get(op->ptr, "mode");
1387         
1388         /* loop over all selected pchans */
1389         CTX_DATA_BEGIN(C, EditBone *, ebone, selected_bones) 
1390         {
1391                 bone_setflag(&ebone->flag, flag, mode);
1392         }
1393         CTX_DATA_END;
1394         
1395         /* note, notifier might evolve */
1396         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, CTX_data_edit_object(C));
1397         
1398         return OPERATOR_FINISHED;
1399 }
1400
1401 /* settings that can be changed */
1402 static EnumPropertyItem prop_bone_setting_types[] = {
1403         {BONE_DRAWWIRE, "DRAWWIRE", 0, "Draw Wire", ""},
1404         {BONE_NO_DEFORM, "DEFORM", 0, "Deform", ""},
1405         {BONE_MULT_VG_ENV, "MULT_VG", 0, "Multiply Vertex Groups", ""},
1406         {BONE_HINGE, "HINGE", 0, "Hinge", ""},
1407         {BONE_NO_SCALE, "NO_SCALE", 0, "No Scale", ""},
1408         {BONE_EDITMODE_LOCKED, "LOCKED", 0, "Locked", "(For EditMode only)"},
1409         {0, NULL, 0, NULL, NULL}
1410 };
1411
1412 /* ways that settings can be changed */
1413 static EnumPropertyItem prop_bone_setting_modes[] = {
1414         {0, "CLEAR", 0, "Clear", ""},
1415         {1, "ENABLE", 0, "Enable", ""},
1416         {2, "TOGGLE", 0, "Toggle", ""},
1417         {0, NULL, 0, NULL, NULL}
1418 };
1419
1420
1421 void ARMATURE_OT_flags_set (wmOperatorType *ot)
1422 {
1423         /* identifiers */
1424         ot->name= "Set Bone Flags";
1425         ot->idname= "ARMATURE_OT_flags_set";
1426         ot->description= "Set flags for armature bones";
1427         
1428         /* callbacks */
1429         ot->invoke= WM_menu_invoke;
1430         ot->exec= armature_bones_setflag_exec;
1431         ot->poll= ED_operator_editarmature;
1432         
1433         /* flags */
1434         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1435         
1436         /* properties */
1437         ot->prop= RNA_def_enum(ot->srna, "type", prop_bone_setting_types, 0, "Type", "");
1438         RNA_def_enum(ot->srna, "mode", prop_bone_setting_modes, 0, "Mode", "");
1439 }
1440
1441 void POSE_OT_flags_set (wmOperatorType *ot)
1442 {
1443         /* identifiers */
1444         ot->name= "Set Bone Flags";
1445         ot->idname= "POSE_OT_flags_set";
1446         ot->description= "Set flags for armature bones";
1447         
1448         /* callbacks */
1449         ot->invoke= WM_menu_invoke;
1450         ot->exec= pose_setflag_exec;
1451         ot->poll= ED_operator_posemode;
1452         
1453         /* flags */
1454         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1455         
1456         /* properties */
1457         ot->prop= RNA_def_enum(ot->srna, "type", prop_bone_setting_types, 0, "Type", "");
1458         RNA_def_enum(ot->srna, "mode", prop_bone_setting_modes, 0, "Mode", "");
1459 }
1460
1461
1462 /* **************** END PoseMode & EditMode *************************** */
1463 /* **************** Posemode stuff ********************** */
1464
1465
1466 static void selectconnected_posebonechildren (Object *ob, Bone *bone, int extend)
1467 {
1468         Bone *curBone;
1469         
1470         /* stop when unconnected child is encontered, or when unselectable bone is encountered */
1471         if (!(bone->flag & BONE_CONNECTED) || (bone->flag & BONE_UNSELECTABLE))
1472                 return;
1473         
1474                 // XXX old cruft! use notifiers instead
1475         //select_actionchannel_by_name (ob->action, bone->name, !(shift));
1476         
1477         if (extend)
1478                 bone->flag &= ~BONE_SELECTED;
1479         else
1480                 bone->flag |= BONE_SELECTED;
1481         
1482         for (curBone=bone->childbase.first; curBone; curBone=curBone->next)
1483                 selectconnected_posebonechildren(ob, curBone, extend);
1484 }
1485
1486 /* within active object context */
1487 /* previously known as "selectconnected_posearmature" */
1488 static int pose_select_connected_invoke(bContext *C, wmOperator *op, wmEvent *event)
1489 {  
1490         ARegion *ar= CTX_wm_region(C);
1491         Object *ob= CTX_data_edit_object(C);
1492         Bone *bone, *curBone, *next= NULL;
1493         int extend= RNA_boolean_get(op->ptr, "extend");
1494         int x, y;
1495         
1496         x= event->x - ar->winrct.xmin;
1497         y= event->y - ar->winrct.ymin;
1498
1499         view3d_operator_needs_opengl(C);
1500         
1501         if (extend)
1502                 bone= get_nearest_bone(C, 0, x, y);
1503         else
1504                 bone= get_nearest_bone(C, 1, x, y);
1505         
1506         if (!bone)
1507                 return OPERATOR_CANCELLED;
1508         
1509         /* Select parents */
1510         for (curBone=bone; curBone; curBone=next){
1511                 /* ignore bone if cannot be selected */
1512                 if ((curBone->flag & BONE_UNSELECTABLE) == 0) { 
1513                                 // XXX old cruft! use notifiers instead
1514                         //select_actionchannel_by_name (ob->action, curBone->name, !(shift));
1515                         
1516                         if (extend)
1517                                 curBone->flag &= ~BONE_SELECTED;
1518                         else
1519                                 curBone->flag |= BONE_SELECTED;
1520                         
1521                         if (curBone->flag & BONE_CONNECTED)
1522                                 next=curBone->parent;
1523                         else
1524                                 next=NULL;
1525                 }
1526                 else
1527                         next= NULL;
1528         }
1529         
1530         /* Select children */
1531         for (curBone=bone->childbase.first; curBone; curBone=next)
1532                 selectconnected_posebonechildren(ob, curBone, extend);
1533         
1534         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, ob);
1535
1536         return OPERATOR_FINISHED;
1537 }
1538
1539 static int pose_select_linked_poll(bContext *C)
1540 {
1541         return ( ED_operator_view3d_active(C) && ED_operator_posemode(C) );
1542 }
1543
1544 void POSE_OT_select_linked(wmOperatorType *ot)
1545 {
1546         /* identifiers */
1547         ot->name= "Select Connected";
1548         ot->idname= "POSE_OT_select_linked";
1549         
1550         /* api callbacks */
1551         ot->exec= NULL;
1552         ot->invoke= pose_select_connected_invoke;
1553         ot->poll= pose_select_linked_poll;
1554         
1555         /* flags */
1556         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1557         
1558         /* props */     
1559         RNA_def_boolean(ot->srna, "extend", FALSE, "Extend", "Extend selection instead of deselecting everything first.");
1560 }
1561
1562 /* **************** END Posemode stuff ********************** */
1563 /* **************** EditMode stuff ********************** */
1564
1565 /* called in space.c */
1566 /* previously "selectconnected_armature" */
1567 static int armature_select_linked_invoke(bContext *C, wmOperator *op, wmEvent *event)
1568 {
1569         bArmature *arm;
1570         EditBone *bone, *curBone, *next;
1571         int extend= RNA_boolean_get(op->ptr, "extend");
1572         int x, y;
1573         ARegion *ar;
1574         Object *obedit= CTX_data_edit_object(C);
1575         arm= obedit->data;
1576         ar= CTX_wm_region(C);
1577
1578         x= event->x - ar->winrct.xmin;
1579         y= event->y - ar->winrct.ymin;
1580
1581         view3d_operator_needs_opengl(C);
1582
1583         if (extend)
1584                 bone= get_nearest_bone(C, 0, x, y);
1585         else
1586                 bone= get_nearest_bone(C, 1, x, y);
1587
1588         if (!bone)
1589                 return OPERATOR_CANCELLED;
1590
1591         /* Select parents */
1592         for (curBone=bone; curBone; curBone=next) {
1593                 if ((curBone->flag & BONE_UNSELECTABLE) == 0) {
1594                         if (extend) {
1595                                 curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1596                         }
1597                         else{
1598                                 curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1599                         }
1600                 }
1601                 
1602                 if (curBone->flag & BONE_CONNECTED)
1603                         next=curBone->parent;
1604                 else
1605                         next=NULL;
1606         }
1607
1608         /* Select children */
1609         while (bone) {
1610                 for (curBone=arm->edbo->first; curBone; curBone=next) {
1611                         next = curBone->next;
1612                         if ((curBone->parent == bone) && (curBone->flag & BONE_UNSELECTABLE)==0) {
1613                                 if (curBone->flag & BONE_CONNECTED) {
1614                                         if (extend)
1615                                                 curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1616                                         else
1617                                                 curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1618                                         bone=curBone;
1619                                         break;
1620                                 }
1621                                 else { 
1622                                         bone=NULL;
1623                                         break;
1624                                 }
1625                         }
1626                 }
1627                 if (!curBone)
1628                         bone=NULL;
1629         }
1630         
1631         ED_armature_sync_selection(arm->edbo);
1632         
1633         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
1634         
1635         return OPERATOR_FINISHED;
1636 }
1637
1638 static int armature_select_linked_poll(bContext *C)
1639 {
1640         return ( ED_operator_view3d_active(C) && ED_operator_editarmature(C) );
1641 }
1642
1643 void ARMATURE_OT_select_linked(wmOperatorType *ot)
1644 {
1645         /* identifiers */
1646         ot->name= "Select Connected";
1647         ot->idname= "ARMATURE_OT_select_linked";
1648         
1649         /* api callbacks */
1650         ot->exec= NULL;
1651         ot->invoke= armature_select_linked_invoke;
1652         ot->poll= armature_select_linked_poll;
1653         
1654         /* flags */
1655         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1656         
1657         /* properties s*/
1658         RNA_def_boolean(ot->srna, "extend", FALSE, "Extend", "Extend selection instead of deselecting everything first.");
1659 }
1660
1661 /* does bones and points */
1662 /* note that BONE ROOT only gets drawn for root bones (or without IK) */
1663 static EditBone *get_nearest_editbonepoint (ViewContext *vc, short mval[2], ListBase *edbo, int findunsel, int *selmask)
1664 {
1665         EditBone *ebone;
1666         rcti rect;
1667         unsigned int buffer[MAXPICKBUF];
1668         unsigned int hitresult, besthitresult=BONESEL_NOSEL;
1669         int i, mindep= 4;
1670         short hits;
1671
1672         glInitNames();
1673         
1674         rect.xmin= mval[0]-5;
1675         rect.xmax= mval[0]+5;
1676         rect.ymin= mval[1]-5;
1677         rect.ymax= mval[1]+5;
1678         
1679         hits= view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect);
1680         if(hits==0) {
1681                 rect.xmin= mval[0]-12;
1682                 rect.xmax= mval[0]+12;
1683                 rect.ymin= mval[1]-12;
1684                 rect.ymax= mval[1]+12;
1685                 hits= view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect);
1686         }
1687         /* See if there are any selected bones in this group */
1688         if (hits>0) {
1689                 
1690                 if(hits==1) {
1691                         if (!(buffer[3] & BONESEL_NOSEL)) 
1692                                 besthitresult= buffer[3];
1693                 }
1694                 else {
1695                         for (i=0; i< hits; i++) {
1696                                 hitresult= buffer[3+(i*4)];
1697                                 if (!(hitresult & BONESEL_NOSEL)) {
1698                                         int dep;
1699                                         
1700                                         ebone = BLI_findlink(edbo, hitresult & ~BONESEL_ANY);
1701                                         
1702                                         /* clicks on bone points get advantage */
1703                                         if( hitresult & (BONESEL_ROOT|BONESEL_TIP)) {
1704                                                 /* but also the unselected one */
1705                                                 if(findunsel) {
1706                                                         if( (hitresult & BONESEL_ROOT) && (ebone->flag & BONE_ROOTSEL)==0) 
1707                                                                 dep= 1;
1708                                                         else if( (hitresult & BONESEL_TIP) && (ebone->flag & BONE_TIPSEL)==0) 
1709                                                                 dep= 1;
1710                                                         else 
1711                                                                 dep= 2;
1712                                                 }
1713                                                 else dep= 2;
1714                                         }
1715                                         else {
1716                                                 /* bone found */
1717                                                 if(findunsel) {
1718                                                         if((ebone->flag & BONE_SELECTED)==0)
1719                                                                 dep= 2;
1720                                                         else
1721                                                                 dep= 3;
1722                                                 }
1723                                                 else dep= 3;
1724                                         }
1725                                         if(dep < mindep) {
1726                                                 mindep= dep;
1727                                                 besthitresult= hitresult;
1728                                         }
1729                                 }
1730                         }
1731                 }
1732                 
1733                 if (!(besthitresult & BONESEL_NOSEL)) {
1734                         
1735                         ebone= BLI_findlink(edbo, besthitresult & ~BONESEL_ANY);
1736                         
1737                         *selmask = 0;
1738                         if (besthitresult & BONESEL_ROOT)
1739                                 *selmask |= BONE_ROOTSEL;
1740                         if (besthitresult & BONESEL_TIP)
1741                                 *selmask |= BONE_TIPSEL;
1742                         if (besthitresult & BONESEL_BONE)
1743                                 *selmask |= BONE_SELECTED;
1744                         return ebone;
1745                 }
1746         }
1747         *selmask = 0;
1748         return NULL;
1749 }
1750
1751 /* context: editmode armature */
1752 EditBone *ED_armature_bone_get_mirrored(ListBase *edbo, EditBone *ebo)
1753 {
1754         EditBone *eboflip= NULL;
1755         char name[32];
1756         
1757         if (ebo == NULL)
1758                 return NULL;
1759
1760         flip_side_name(name, ebo->name, FALSE);
1761         
1762         for (eboflip= edbo->first; eboflip; eboflip=eboflip->next) {
1763                 if (ebo != eboflip) {
1764                         if (!strcmp (name, eboflip->name)) 
1765                                 break;
1766                 }
1767         }
1768         
1769         return eboflip;
1770 }
1771
1772
1773 /* previously delete_armature */
1774 /* only editmode! */
1775 static int armature_delete_selected_exec(bContext *C, wmOperator *op)
1776 {
1777         bArmature *arm;
1778         EditBone        *curBone, *next;
1779         bConstraint *con;
1780         Object *obedit= CTX_data_edit_object(C); // XXX get from context
1781         arm = obedit->data;
1782
1783         /* cancel if nothing selected */
1784         if (CTX_DATA_COUNT(C, selected_bones) == 0)
1785                 return OPERATOR_CANCELLED;
1786         
1787         /* Select mirrored bones */
1788         if (arm->flag & ARM_MIRROR_EDIT) {
1789                 for (curBone=arm->edbo->first; curBone; curBone=curBone->next) {
1790                         if (arm->layer & curBone->layer) {
1791                                 if (curBone->flag & BONE_SELECTED) {
1792                                         next = ED_armature_bone_get_mirrored(arm->edbo, curBone);
1793                                         if (next)
1794                                                 next->flag |= BONE_SELECTED;
1795                                 }
1796                         }
1797                 }
1798         }
1799         
1800         /*  First erase any associated pose channel */
1801         if (obedit->pose) {
1802                 bPoseChannel *pchan, *next;
1803                 for (pchan=obedit->pose->chanbase.first; pchan; pchan=next) {
1804                         next= pchan->next;
1805                         curBone = editbone_name_exists(arm->edbo, pchan->name);
1806                         
1807                         if (curBone && (curBone->flag & BONE_SELECTED) && (arm->layer & curBone->layer)) {
1808                                 free_pose_channel(pchan);
1809                                 free_pose_channels_hash(obedit->pose);
1810                                 BLI_freelinkN (&obedit->pose->chanbase, pchan);
1811                         }
1812                         else {
1813                                 for (con= pchan->constraints.first; con; con= con->next) {
1814                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1815                                         ListBase targets = {NULL, NULL};
1816                                         bConstraintTarget *ct;
1817                                         
1818                                         if (cti && cti->get_constraint_targets) {
1819                                                 cti->get_constraint_targets(con, &targets);
1820                                                 
1821                                                 for (ct= targets.first; ct; ct= ct->next) {
1822                                                         if (ct->tar == obedit) {
1823                                                                 if (ct->subtarget[0]) {
1824                                                                         curBone = editbone_name_exists(arm->edbo, ct->subtarget);
1825                                                                         if (curBone && (curBone->flag & BONE_SELECTED) && (arm->layer & curBone->layer)) {
1826                                                                                 con->flag |= CONSTRAINT_DISABLE;
1827                                                                                 ct->subtarget[0]= 0;
1828                                                                         }
1829                                                                 }
1830                                                         }
1831                                                 }
1832                                                 
1833                                                 if (cti->flush_constraint_targets)
1834                                                         cti->flush_constraint_targets(con, &targets, 0);
1835                                         }
1836                                 }
1837                         }
1838                 }
1839         }
1840         
1841         
1842         for (curBone=arm->edbo->first;curBone;curBone=next) {
1843                 next=curBone->next;
1844                 if (arm->layer & curBone->layer) {
1845                         if (curBone->flag & BONE_SELECTED) {
1846                                 if(curBone==arm->act_edbone) arm->act_edbone= NULL;
1847                                 ED_armature_edit_bone_remove(arm, curBone);
1848                         }
1849                 }
1850         }
1851         
1852         
1853         ED_armature_sync_selection(arm->edbo);
1854
1855         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
1856
1857         return OPERATOR_FINISHED;
1858 }
1859
1860 void ARMATURE_OT_delete(wmOperatorType *ot)
1861 {
1862         /* identifiers */
1863         ot->name= "Delete Selected Bone(s)";
1864         ot->idname= "ARMATURE_OT_delete";
1865         
1866         /* api callbacks */
1867         ot->invoke = WM_operator_confirm;
1868         ot->exec = armature_delete_selected_exec;
1869         ot->poll = ED_operator_editarmature;
1870         
1871         /* flags */
1872         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1873 }
1874
1875 /* toggle==0: deselect
1876  * toggle==1: swap (based on test)
1877  * toggle==2: only active tag
1878  * toggle==3: swap (no test)
1879  */
1880 void ED_armature_deselectall(Object *obedit, int toggle, int doundo)
1881 {
1882         bArmature *arm= obedit->data;
1883         EditBone        *eBone;
1884         int                     sel=1;
1885         
1886         if(toggle==1) {
1887                 /*      Determine if there are any selected bones
1888                 And therefore whether we are selecting or deselecting */
1889                 for (eBone=arm->edbo->first;eBone;eBone=eBone->next){
1890                         //                      if(arm->layer & eBone->layer) {
1891                         if (eBone->flag & (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL)){
1892                                 sel=0;
1893                                 break;
1894                         }
1895                         //                      }
1896                 }
1897         }
1898         else sel= toggle;
1899         
1900         if(sel==2) {
1901                 arm->act_edbone= NULL;
1902         } else {
1903                 /*      Set the flags */
1904                 for (eBone=arm->edbo->first;eBone;eBone=eBone->next) {
1905                         if (sel==3) {
1906                                 /* invert selection of bone */
1907                                 if ((arm->layer & eBone->layer) && (eBone->flag & BONE_HIDDEN_A)==0) {
1908                                         eBone->flag ^= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1909                                         if(arm->act_edbone==eBone)
1910                                                 arm->act_edbone= NULL;
1911                                 }
1912                         }
1913                         else if (sel==1) {
1914                                 /* select bone */
1915                                 if(arm->layer & eBone->layer && (eBone->flag & BONE_HIDDEN_A)==0) {
1916                                         eBone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1917                                         if(eBone->parent)
1918                                                 eBone->parent->flag |= (BONE_TIPSEL);
1919                                 }
1920                         }
1921                         else {
1922                                 /* deselect bone */
1923                                 eBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1924                                 if(arm->act_edbone==eBone)
1925                                         arm->act_edbone= NULL;
1926                         }
1927                 }
1928         }
1929         
1930         ED_armature_sync_selection(arm->edbo);
1931 }
1932
1933
1934 /* context: editmode armature in view3d */
1935 int mouse_armature(bContext *C, short mval[2], int extend)
1936 {
1937         Object *obedit= CTX_data_edit_object(C);
1938         bArmature *arm= obedit->data;
1939         ViewContext vc;
1940         EditBone *nearBone = NULL;
1941         int     selmask;
1942
1943         view3d_set_viewcontext(C, &vc);
1944         
1945         BIF_sk_selectStroke(C, mval, extend);
1946         
1947         nearBone= get_nearest_editbonepoint(&vc, mval, arm->edbo, 1, &selmask);
1948         if (nearBone) {
1949
1950                 if (!extend)
1951                         ED_armature_deselectall(obedit, 0, 0);
1952                 
1953                 /* by definition the non-root connected bones have no root point drawn,
1954                    so a root selection needs to be delivered to the parent tip */
1955                 
1956                 if(selmask & BONE_SELECTED) {
1957                         if(nearBone->parent && (nearBone->flag & BONE_CONNECTED)) {
1958                                 /* click in a chain */
1959                                 if(extend) {
1960                                         /* hold shift inverts this bone's selection */
1961                                         if(nearBone->flag & BONE_SELECTED) {
1962                                                 /* deselect this bone */
1963                                                 nearBone->flag &= ~(BONE_TIPSEL|BONE_SELECTED);
1964                                                 /* only deselect parent tip if it is not selected */
1965                                                 if(!(nearBone->parent->flag & BONE_SELECTED))
1966                                                         nearBone->parent->flag &= ~BONE_TIPSEL;
1967                                         }
1968                                         else {
1969                                                 /* select this bone */
1970                                                 nearBone->flag |= BONE_TIPSEL;
1971                                                 nearBone->parent->flag |= BONE_TIPSEL;
1972                                         }
1973                                 }
1974                                 else {
1975                                         /* select this bone */
1976                                         nearBone->flag |= BONE_TIPSEL;
1977                                         nearBone->parent->flag |= BONE_TIPSEL;
1978                                 }
1979                         }
1980                         else {
1981                                 if(extend) {
1982                                         /* hold shift inverts this bone's selection */
1983                                         if(nearBone->flag & BONE_SELECTED)
1984                                            nearBone->flag &= ~(BONE_TIPSEL|BONE_ROOTSEL);
1985                                         else
1986                                                 nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
1987                                 }
1988                                 else nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
1989                         }
1990                 }
1991                 else {
1992                         if (extend && (nearBone->flag & selmask))
1993                                 nearBone->flag &= ~selmask;
1994                         else
1995                                 nearBone->flag |= selmask;
1996                 }
1997                 
1998                 ED_armature_sync_selection(arm->edbo);
1999                 
2000                 if(nearBone) {
2001                         /* then now check for active status */
2002                         if(nearBone->flag & BONE_SELECTED) arm->act_edbone= nearBone;
2003                 }
2004                 
2005                 WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, vc.obedit);
2006                 return 1;
2007         }
2008
2009         return 0;
2010 }
2011
2012 void ED_armature_edit_free(struct Object *ob)
2013 {
2014         bArmature *arm= ob->data;
2015         EditBone *eBone;
2016         
2017         /*      Clear the editbones list */
2018         if (arm->edbo) {
2019                 if (arm->edbo->first) {
2020                         for (eBone=arm->edbo->first; eBone; eBone=eBone->next) {
2021                                 if (eBone->prop) {
2022                                         IDP_FreeProperty(eBone->prop);
2023                                         MEM_freeN(eBone->prop);
2024                                 }
2025                         }
2026
2027                         BLI_freelistN(arm->edbo);
2028                 }
2029                 MEM_freeN(arm->edbo);
2030                 arm->edbo= NULL;
2031         }
2032 }
2033
2034 /* Put armature in EditMode */
2035 void ED_armature_to_edit(Object *ob)
2036 {
2037         bArmature *arm= ob->data;
2038         
2039         ED_armature_edit_free(ob);
2040         arm->edbo= MEM_callocN(sizeof(ListBase), "edbo armature");
2041         arm->act_edbone= make_boneList(arm->edbo, &arm->bonebase, NULL, arm->act_bone);
2042         arm->act_bone= NULL;
2043
2044 //      BIF_freeTemplates(); /* force template update when entering editmode */
2045 }
2046
2047
2048 /* adjust bone roll to align Z axis with vector
2049  * vec is in local space and is normalized
2050  */
2051 float ED_rollBoneToVector(EditBone *bone, float new_up_axis[3])
2052 {
2053         float mat[3][3], nor[3], up_axis[3], vec[3];
2054         float roll;
2055
2056         sub_v3_v3v3(nor, bone->tail, bone->head);
2057         
2058         vec_roll_to_mat3(nor, 0, mat);
2059         VECCOPY(up_axis, mat[2]);
2060         
2061         roll = angle_normalized_v3v3(new_up_axis, up_axis);
2062         
2063         cross_v3_v3v3(vec, up_axis, new_up_axis);
2064         
2065         if (dot_v3v3(vec, nor) < 0)
2066         {
2067                 roll = -roll;
2068         }
2069         
2070         return roll;
2071 }
2072
2073
2074 /* Set roll value for given bone -> Z-Axis Point up (original method) */
2075 static void auto_align_ebone_zaxisup(Scene *scene, View3D *v3d, EditBone *ebone)
2076 {
2077         float   delta[3], curmat[3][3];
2078         float   xaxis[3]={1.0f, 0.0f, 0.0f}, yaxis[3], zaxis[3]={0.0f, 0.0f, 1.0f};
2079         float   targetmat[3][3], imat[3][3], diffmat[3][3];
2080         
2081         /* Find the current bone matrix */
2082         sub_v3_v3v3(delta, ebone->tail, ebone->head);
2083         vec_roll_to_mat3(delta, 0.0f, curmat);
2084         
2085         /* Make new matrix based on y axis & z-up */
2086         VECCOPY(yaxis, curmat[1]);
2087         
2088         unit_m3(targetmat);
2089         VECCOPY(targetmat[0], xaxis);
2090         VECCOPY(targetmat[1], yaxis);
2091         VECCOPY(targetmat[2], zaxis);
2092         normalize_m3(targetmat);
2093         
2094         /* Find the difference between the two matrices */
2095         invert_m3_m3(imat, targetmat);
2096         mul_m3_m3m3(diffmat, imat, curmat);
2097         
2098         // old-method... let's see if using mat3_to_vec_roll is more accurate
2099         //ebone->roll = atan2(diffmat[2][0], diffmat[2][2]);  
2100         mat3_to_vec_roll(diffmat, delta, &ebone->roll);
2101 }
2102
2103 void auto_align_ebone_topoint(EditBone *ebone, float *cursor)
2104 {
2105         float   delta[3], curmat[3][3];
2106         float   mat[4][4], tmat[4][4], imat[4][4];
2107         float   rmat[4][4], rot[3];
2108         float   vec[3];
2109
2110         /* find the current bone matrix as a 4x4 matrix (in Armature Space) */
2111         sub_v3_v3v3(delta, ebone->tail, ebone->head);
2112         vec_roll_to_mat3(delta, ebone->roll, curmat);
2113         copy_m4_m3(mat, curmat);
2114         VECCOPY(mat[3], ebone->head);
2115         
2116         /* multiply bone-matrix by object matrix (so that bone-matrix is in WorldSpace) */
2117         invert_m4_m4(imat, mat);
2118         
2119         /* find position of cursor relative to bone */
2120         mul_v3_m4v3(vec, imat, cursor);
2121         
2122         /* check that cursor is in usable position */
2123         if ((IS_EQ(vec[0], 0)==0) && (IS_EQ(vec[2], 0)==0)) {
2124                 /* Compute a rotation matrix around y */
2125                 rot[1] = (float)atan2(vec[0], vec[2]);
2126                 rot[0] = rot[2] = 0.0f;
2127                 eul_to_mat4( rmat,rot);
2128                 
2129                 /* Multiply the bone matrix by rotation matrix. This should be new bone-matrix */
2130                 mul_m4_m4m4(tmat, rmat, mat);
2131                 copy_m3_m4(curmat, tmat);
2132                 
2133                 /* Now convert from new bone-matrix, back to a roll value (in radians) */
2134                 mat3_to_vec_roll(curmat, delta, &ebone->roll);
2135         }
2136 }
2137
2138 static void auto_align_ebone_tocursor(Scene *scene, View3D *v3d, EditBone *ebone)
2139 {
2140         float cursor_local[3];
2141         float   *cursor= give_cursor(scene, v3d);
2142         float imat[3][3];
2143
2144         copy_m3_m4(imat, scene->obedit->obmat);
2145         invert_m3(imat);
2146         copy_v3_v3(cursor_local, cursor);
2147         mul_m3_v3(imat, cursor_local);
2148         auto_align_ebone_topoint(ebone, cursor_local);
2149 }
2150
2151 static EnumPropertyItem prop_calc_roll_types[] = {
2152         {0, "GLOBALUP", 0, "Z-Axis Up", ""},
2153         {1, "CURSOR", 0, "Z-Axis to Cursor", ""},
2154         {0, NULL, 0, NULL, NULL}
2155 };
2156
2157 static int armature_calc_roll_exec(bContext *C, wmOperator *op) 
2158 {
2159         Scene *scene= CTX_data_scene(C);
2160         View3D *v3d= CTX_wm_view3d(C);
2161         Object *ob= CTX_data_edit_object(C);
2162         void (*roll_func)(Scene *, View3D *, EditBone *) = NULL;
2163         
2164         /* specific method used to calculate roll depends on mode */
2165         switch (RNA_enum_get(op->ptr, "type")) {
2166                 case 1:  /* Z-Axis point towards cursor */
2167                         roll_func= auto_align_ebone_tocursor;
2168                         break;
2169                 default: /* Z-Axis Point Up */
2170                         roll_func= auto_align_ebone_zaxisup;
2171                         break;
2172         }
2173         
2174         /* recalculate roll on selected bones */
2175         CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones) {
2176                 /* roll func is a callback which assumes that all is well */
2177                 roll_func(scene, v3d, ebone);
2178         }
2179         CTX_DATA_END;
2180         
2181
2182         /* note, notifier might evolve */
2183         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, ob);
2184         
2185         return OPERATOR_FINISHED;
2186 }
2187
2188 void ARMATURE_OT_calculate_roll(wmOperatorType *ot)
2189 {
2190         /* identifiers */
2191         ot->name= "Recalculate Roll";
2192         ot->idname= "ARMATURE_OT_calculate_roll";
2193         
2194         /* api callbacks */
2195         ot->invoke = WM_menu_invoke;
2196         ot->exec = armature_calc_roll_exec;
2197         ot->poll = ED_operator_editarmature;
2198         
2199         /* flags */
2200         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2201         
2202         /* properties */
2203         ot->prop= RNA_def_enum(ot->srna, "type", prop_calc_roll_types, 0, "Type", "");
2204 }
2205
2206 /* **************** undo for armatures ************** */
2207
2208 typedef struct UndoArmature {
2209         EditBone *act_edbone;
2210         ListBase lb;
2211 } UndoArmature;
2212
2213 static void undoBones_to_editBones(void *uarmv, void *armv)
2214 {
2215         UndoArmature *uarm= uarmv;
2216         bArmature *arm= armv;
2217         EditBone *ebo, *newebo;
2218         
2219         BLI_freelistN(arm->edbo);
2220         
2221         /* copy  */
2222         for(ebo= uarm->lb.first; ebo; ebo= ebo->next) {
2223                 newebo= MEM_dupallocN(ebo);
2224                 ebo->temp= newebo;
2225                 BLI_addtail(arm->edbo, newebo);
2226         }
2227         
2228         /* active bone */
2229         if(uarm->act_edbone) {
2230                 ebo= uarm->act_edbone;
2231                 arm->act_edbone= ebo->temp;
2232         }
2233
2234         /* set pointers */
2235         for(newebo= arm->edbo->first; newebo; newebo= newebo->next) {
2236                 if(newebo->parent) newebo->parent= newebo->parent->temp;
2237         }
2238         /* be sure they dont hang ever */
2239         for(newebo= arm->edbo->first; newebo; newebo= newebo->next) {
2240                 newebo->temp= NULL;
2241         }
2242 }
2243
2244 static void *editBones_to_undoBones(void *armv)
2245 {
2246         bArmature *arm= armv;
2247         UndoArmature *uarm;
2248         EditBone *ebo, *newebo;
2249         
2250         uarm= MEM_callocN(sizeof(UndoArmature), "listbase undo");
2251         
2252         /* copy */
2253         for(ebo= arm->edbo->first; ebo; ebo= ebo->next) {
2254                 newebo= MEM_dupallocN(ebo);
2255                 ebo->temp= newebo;
2256                 BLI_addtail(&uarm->lb, newebo);
2257         }
2258         
2259         /* active bone */
2260         if(arm->act_edbone) {
2261                 ebo= arm->act_edbone;
2262                 uarm->act_edbone= ebo->temp;
2263         }
2264
2265         /* set pointers */
2266         for(newebo= uarm->lb.first; newebo; newebo= newebo->next) {
2267                 if(newebo->parent) newebo->parent= newebo->parent->temp;
2268         }
2269         
2270         return uarm;
2271 }
2272
2273 static void free_undoBones(void *uarmv)
2274 {
2275         UndoArmature *uarm= uarmv;
2276         
2277         BLI_freelistN(&uarm->lb);
2278         MEM_freeN(uarm);
2279 }
2280
2281 static void *get_armature_edit(bContext *C)
2282 {
2283         Object *obedit= CTX_data_edit_object(C);
2284         if(obedit && obedit->type==OB_ARMATURE) {
2285                 return obedit->data;
2286         }
2287         return NULL;
2288 }
2289
2290 /* and this is all the undo system needs to know */
2291 void undo_push_armature(bContext *C, char *name)
2292 {
2293         // XXX solve getdata()
2294         undo_editmode_push(C, name, get_armature_edit, free_undoBones, undoBones_to_editBones, editBones_to_undoBones, NULL);
2295 }
2296
2297
2298
2299 /* **************** END EditMode stuff ********************** */
2300 /* *************** Adding stuff in editmode *************** */
2301
2302 /* default bone add, returns it selected, but without tail set */
2303 EditBone *ED_armature_edit_bone_add(bArmature *arm, char *name)
2304 {
2305         EditBone *bone= MEM_callocN(sizeof(EditBone), "eBone");
2306         
2307         BLI_strncpy(bone->name, name, 32);
2308         unique_editbone_name(arm->edbo, bone->name, NULL);
2309         
2310         BLI_addtail(arm->edbo, bone);
2311         
2312         bone->flag |= BONE_TIPSEL;
2313         bone->weight= 1.0f;
2314         bone->dist= 0.25f;
2315         bone->xwidth= 0.1f;
2316         bone->zwidth= 0.1f;
2317         bone->ease1= 1.0f;
2318         bone->ease2= 1.0f;
2319         bone->rad_head= 0.10f;
2320         bone->rad_tail= 0.05f;
2321         bone->segments= 1;
2322         bone->layer= arm->layer;
2323         
2324         return bone;
2325 }
2326
2327 /* v3d and rv3d are allowed to be NULL */
2328 void add_primitive_bone(Scene *scene, View3D *v3d, RegionView3D *rv3d)
2329 {
2330         Object *obedit= scene->obedit; // XXX get from context
2331         float           obmat[3][3], curs[3], viewmat[3][3], totmat[3][3], imat[3][3];
2332         EditBone        *bone;
2333
2334         /* Get inverse point for head and orientation for tail */
2335         invert_m4_m4(obedit->imat, obedit->obmat);
2336         mul_v3_m4v3(curs, obedit->imat, give_cursor(scene, v3d));
2337
2338         if (rv3d && (U.flag & USER_ADD_VIEWALIGNED))
2339                 copy_m3_m4(obmat, rv3d->viewmat);
2340         else unit_m3(obmat);
2341         
2342         copy_m3_m4(viewmat, obedit->obmat);
2343         mul_m3_m3m3(totmat, obmat, viewmat);
2344         invert_m3_m3(imat, totmat);
2345         
2346         ED_armature_deselectall(obedit, 0, 0);
2347         
2348         /*      Create a bone   */
2349         bone= ED_armature_edit_bone_add(obedit->data, "Bone");
2350
2351         copy_v3_v3(bone->head, curs);
2352         
2353         if (rv3d && (U.flag & USER_ADD_VIEWALIGNED))
2354                 add_v3_v3v3(bone->tail, bone->head, imat[1]);   // bone with unit length 1
2355         else
2356                 add_v3_v3v3(bone->tail, bone->head, imat[2]);   // bone with unit length 1, pointing up Z
2357         
2358 }
2359
2360
2361 /* previously addvert_armature */
2362 /* the ctrl-click method */
2363 static int armature_click_extrude_exec(bContext *C, wmOperator *op)
2364 {
2365         View3D *v3d;
2366         bArmature *arm;
2367         EditBone *ebone, *newbone, *flipbone;
2368         float *curs, mat[3][3],imat[3][3];
2369         int a, to_root= 0;
2370         Object *obedit;
2371         Scene *scene;
2372
2373         scene = CTX_data_scene(C);
2374         v3d= CTX_wm_view3d(C);
2375         obedit= CTX_data_edit_object(C);
2376         arm= obedit->data;
2377         
2378         /* find the active or selected bone */
2379         for (ebone = arm->edbo->first; ebone; ebone=ebone->next) {
2380                 if (EBONE_VISIBLE(arm, ebone)) {
2381                         if (ebone->flag & BONE_TIPSEL || arm->act_edbone == ebone)
2382                                 break;
2383                 }
2384         }
2385         
2386         if (ebone==NULL) {
2387                 for (ebone = arm->edbo->first; ebone; ebone=ebone->next) {
2388                         if (EBONE_VISIBLE(arm, ebone)) {
2389                                 if (ebone->flag & BONE_ROOTSEL || arm->act_edbone == ebone)
2390                                         break;
2391                         }
2392                 }
2393                 if (ebone == NULL) 
2394                         return OPERATOR_CANCELLED;
2395                 
2396                 to_root= 1;
2397         }
2398         
2399         ED_armature_deselectall(obedit, 0, 0);
2400         
2401         /* we re-use code for mirror editing... */
2402         flipbone= NULL;
2403         if (arm->flag & ARM_MIRROR_EDIT)
2404                 flipbone= ED_armature_bone_get_mirrored(arm->edbo, ebone);
2405
2406         for (a=0; a<2; a++) {
2407                 if (a==1) {
2408                         if (flipbone==NULL)
2409                                 break;
2410                         else {
2411                                 SWAP(EditBone *, flipbone, ebone);
2412                         }
2413                 }
2414                 
2415                 newbone= ED_armature_edit_bone_add(arm, ebone->name);
2416                 arm->act_edbone= newbone;
2417                 
2418                 if (to_root) {
2419                         VECCOPY(newbone->head, ebone->head);
2420                         newbone->rad_head= ebone->rad_tail;
2421                         newbone->parent= ebone->parent;
2422                 }
2423                 else {
2424                         VECCOPY(newbone->head, ebone->tail);
2425                         newbone->rad_head= ebone->rad_tail;
2426                         newbone->parent= ebone;
2427                         newbone->flag |= BONE_CONNECTED;
2428                 }
2429                 
2430                 curs= give_cursor(scene, v3d);
2431                 VECCOPY(newbone->tail, curs);
2432                 sub_v3_v3v3(newbone->tail, newbone->tail, obedit->obmat[3]);
2433                 
2434                 if (a==1) 
2435                         newbone->tail[0]= -newbone->tail[0];
2436                 
2437                 copy_m3_m4(mat, obedit->obmat);
2438                 invert_m3_m3(imat, mat);
2439                 mul_m3_v3(imat, newbone->tail);
2440                 
2441                 newbone->length= len_v3v3(newbone->head, newbone->tail);
2442                 newbone->rad_tail= newbone->length*0.05f;
2443                 newbone->dist= newbone->length*0.25f;
2444                 
2445         }
2446         
2447         ED_armature_sync_selection(arm->edbo);
2448
2449         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
2450         
2451         return OPERATOR_FINISHED;
2452 }
2453
2454 static int armature_click_extrude_invoke(bContext *C, wmOperator *op, wmEvent *event)
2455 {
2456         /* TODO most of this code is copied from set3dcursor_invoke,
2457            it would be better to reuse code in set3dcursor_invoke */
2458
2459         /* temporarily change 3d cursor position */
2460         Scene *scene;
2461         ARegion *ar;
2462         View3D *v3d;
2463         RegionView3D *rv3d;
2464         float dx, dy, fz, *fp = NULL, dvec[3], oldcurs[3];
2465         short mx, my, mval[2];
2466         int retv;
2467
2468         scene= CTX_data_scene(C);
2469         ar= CTX_wm_region(C);
2470         v3d = CTX_wm_view3d(C);
2471         rv3d= CTX_wm_region_view3d(C);
2472         
2473         fp= give_cursor(scene, v3d);
2474         
2475         VECCOPY(oldcurs, fp);
2476         
2477         mx= event->x - ar->winrct.xmin;
2478         my= event->y - ar->winrct.ymin;
2479         project_short_noclip(ar, fp, mval);
2480         
2481         initgrabz(rv3d, fp[0], fp[1], fp[2]);
2482         
2483         if(mval[0]!=IS_CLIPPED) {
2484                 
2485                 window_to_3d_delta(ar, dvec, mval[0]-mx, mval[1]-my);
2486                 sub_v3_v3v3(fp, fp, dvec);
2487         }
2488         else {
2489                 
2490                 dx= ((float)(mx-(ar->winx/2)))*rv3d->zfac/(ar->winx/2);
2491                 dy= ((float)(my-(ar->winy/2)))*rv3d->zfac/(ar->winy/2);
2492                 
2493                 fz= rv3d->persmat[0][3]*fp[0]+ rv3d->persmat[1][3]*fp[1]+ rv3d->persmat[2][3]*fp[2]+ rv3d->persmat[3][3];
2494                 fz= fz/rv3d->zfac;
2495                 
2496                 fp[0]= (rv3d->persinv[0][0]*dx + rv3d->persinv[1][0]*dy+ rv3d->persinv[2][0]*fz)-rv3d->ofs[0];
2497                 fp[1]= (rv3d->persinv[0][1]*dx + rv3d->persinv[1][1]*dy+ rv3d->persinv[2][1]*fz)-rv3d->ofs[1];
2498                 fp[2]= (rv3d->persinv[0][2]*dx + rv3d->persinv[1][2]*dy+ rv3d->persinv[2][2]*fz)-rv3d->ofs[2];
2499         }
2500
2501         /* extrude to the where new cursor is and store the operation result */
2502         retv= armature_click_extrude_exec(C, op);
2503
2504         /* restore previous 3d cursor position */
2505         VECCOPY(fp, oldcurs);
2506
2507         return retv;
2508 }
2509
2510 void ARMATURE_OT_click_extrude(wmOperatorType *ot)
2511 {
2512         /* identifiers */
2513         ot->name= "Click-Extrude";
2514         ot->idname= "ARMATURE_OT_click_extrude";
2515         
2516         /* api callbacks */
2517         ot->invoke = armature_click_extrude_invoke;
2518         ot->exec = armature_click_extrude_exec;
2519         ot->poll = ED_operator_editarmature;
2520         
2521         /* flags */
2522         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2523
2524         /* props */
2525 }
2526
2527 /* adds an EditBone between the nominated locations (should be in the right space) */
2528 static EditBone *add_points_bone (Object *obedit, float head[], float tail[]) 
2529 {
2530         EditBone *ebo;
2531         
2532         ebo= ED_armature_edit_bone_add(obedit->data, "Bone");
2533         
2534         VECCOPY(ebo->head, head);
2535         VECCOPY(ebo->tail, tail);
2536         
2537         return ebo;
2538 }
2539
2540
2541 static EditBone *get_named_editbone(ListBase *edbo, char *name)
2542 {
2543         EditBone  *eBone;
2544
2545         if (name) {
2546                 for (eBone=edbo->first; eBone; eBone=eBone->next) {
2547                         if (!strcmp(name, eBone->name))
2548                                 return eBone;
2549                 }
2550         }
2551
2552         return NULL;
2553 }
2554
2555 /* Call this before doing any duplications
2556  * */
2557 void preEditBoneDuplicate(ListBase *editbones)
2558 {
2559         EditBone *eBone;
2560         
2561         /* clear temp */
2562         for (eBone = editbones->first; eBone; eBone = eBone->next)
2563         {
2564                 eBone->temp = NULL;
2565         }
2566 }
2567
2568 /*
2569  * Note: When duplicating cross objects, editbones here is the list of bones
2570  * from the SOURCE object but ob is the DESTINATION object
2571  * */
2572 void updateDuplicateSubtargetObjects(EditBone *dupBone, ListBase *editbones, Object *src_ob, Object *dst_ob)
2573 {
2574         /* If an edit bone has been duplicated, lets
2575          * update it's constraints if the subtarget
2576          * they point to has also been duplicated
2577          */
2578         EditBone     *oldtarget, *newtarget;
2579         bPoseChannel *pchan;
2580         bConstraint  *curcon;
2581         ListBase     *conlist;
2582         
2583         if ( (pchan = verify_pose_channel(dst_ob->pose, dupBone->name)) ) {
2584                 if ( (conlist = &pchan->constraints) ) {
2585                         for (curcon = conlist->first; curcon; curcon=curcon->next) {
2586                                 /* does this constraint have a subtarget in
2587                                  * this armature?
2588                                  */
2589                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(curcon);
2590                                 ListBase targets = {NULL, NULL};
2591                                 bConstraintTarget *ct;
2592                                 
2593                                 if (cti && cti->get_constraint_targets) {
2594                                         cti->get_constraint_targets(curcon, &targets);
2595                                         
2596                                         for (ct= targets.first; ct; ct= ct->next) {
2597                                                 if ((ct->tar == src_ob) && (ct->subtarget[0])) {
2598                                                         ct->tar = dst_ob; /* update target */ 
2599                                                         oldtarget = get_named_editbone(editbones, ct->subtarget);
2600                                                         if (oldtarget) {
2601                                                                 /* was the subtarget bone duplicated too? If
2602                                                                  * so, update the constraint to point at the 
2603                                                                  * duplicate of the old subtarget.
2604                                                                  */
2605                                                                 if (oldtarget->temp) {
2606                                                                         newtarget = (EditBone *) oldtarget->temp;
2607                                                                         strcpy(ct->subtarget, newtarget->name);
2608                                                                 }
2609                                                         }
2610                                                 }
2611                                         }
2612                                         
2613                                         if (cti->flush_constraint_targets)
2614                                                 cti->flush_constraint_targets(curcon, &targets, 0);
2615                                 }
2616                         }
2617                 }
2618         }
2619 }
2620
2621 void updateDuplicateSubtarget(EditBone *dupBone, ListBase *editbones, Object *ob)
2622 {
2623         updateDuplicateSubtargetObjects(dupBone, editbones, ob, ob);
2624 }
2625
2626
2627 EditBone *duplicateEditBoneObjects(EditBone *curBone, char *name, ListBase *editbones, Object *src_ob, Object *dst_ob)
2628 {
2629         EditBone *eBone = MEM_mallocN(sizeof(EditBone), "addup_editbone");
2630         
2631         /*      Copy data from old bone to new bone */
2632         memcpy(eBone, curBone, sizeof(EditBone));
2633         
2634         curBone->temp = eBone;
2635         eBone->temp = curBone;
2636         
2637         if (name != NULL)
2638         {
2639                 BLI_strncpy(eBone->name, name, 32);
2640         }
2641
2642         unique_editbone_name(editbones, eBone->name, NULL);
2643         BLI_addtail(editbones, eBone);
2644         
2645         /* copy the ID property */
2646         if(curBone->prop)
2647                 eBone->prop= IDP_CopyProperty(curBone->prop);
2648
2649         /* Lets duplicate the list of constraints that the
2650          * current bone has.
2651          */
2652         if (src_ob->pose) {
2653                 bPoseChannel *chanold, *channew;
2654                 
2655                 chanold = verify_pose_channel(src_ob->pose, curBone->name);
2656                 if (chanold) {
2657                         /* WARNING: this creates a new posechannel, but there will not be an attached bone
2658                          *              yet as the new bones created here are still 'EditBones' not 'Bones'.
2659                          */
2660                         channew= verify_pose_channel(dst_ob->pose, eBone->name);
2661
2662                         if(channew) {
2663                                 duplicate_pose_channel_data(channew, chanold);
2664                         }
2665                 }
2666         }
2667         
2668         return eBone;
2669 }
2670
2671 EditBone *duplicateEditBone(EditBone *curBone, char *name, ListBase *editbones, Object *ob)
2672 {
2673         return duplicateEditBoneObjects(curBone, name, editbones, ob, ob);
2674 }
2675
2676 /* previously adduplicate_armature */
2677 static int armature_duplicate_selected_exec(bContext *C, wmOperator *op)
2678 {
2679         bArmature *arm;
2680         EditBone        *eBone = NULL;
2681         EditBone        *curBone;
2682         EditBone        *firstDup=NULL; /*      The beginning of the duplicated bones in the edbo list */
2683
2684         Object *obedit= CTX_data_edit_object(C);
2685         arm= obedit->data;
2686
2687         /* cancel if nothing selected */
2688         if (CTX_DATA_COUNT(C, selected_bones) == 0)
2689           return OPERATOR_CANCELLED;
2690         
2691         ED_armature_sync_selection(arm->edbo); // XXX why is this needed?
2692
2693         preEditBoneDuplicate(arm->edbo);
2694
2695         /* Select mirrored bones */
2696         if (arm->flag & ARM_MIRROR_EDIT) {
2697                 for (curBone=arm->edbo->first; curBone; curBone=curBone->next) {
2698                         if (EBONE_VISIBLE(arm, curBone)) {
2699                                 if (curBone->flag & BONE_SELECTED) {
2700                                         eBone = ED_armature_bone_get_mirrored(arm->edbo, curBone);
2701                                         if (eBone)
2702                                                 eBone->flag |= BONE_SELECTED;
2703                                 }
2704                         }
2705                 }
2706         }
2707
2708         
2709         /*      Find the selected bones and duplicate them as needed */
2710         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2711                 if (EBONE_VISIBLE(arm, curBone)) {
2712                         if (curBone->flag & BONE_SELECTED) {
2713                                 
2714                                 eBone= duplicateEditBone(curBone, curBone->name, arm->edbo, obedit);
2715                                 
2716                                 if (!firstDup)
2717                                         firstDup=eBone;
2718
2719                         }
2720                 }
2721         }
2722
2723         /*      Run though the list and fix the pointers */
2724         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2725                 if (EBONE_VISIBLE(arm, curBone)) {
2726                         if (curBone->flag & BONE_SELECTED) {
2727                                 eBone=(EditBone*) curBone->temp;
2728                                 
2729                                 if (!curBone->parent) {
2730                                         /* If this bone has no parent,
2731                                          * Set the duplicate->parent to NULL
2732                                          */
2733                                         eBone->parent = NULL;
2734                                 }
2735                                 else if (curBone->parent->temp) {
2736                                         /* If this bone has a parent that was duplicated,
2737                                          * Set the duplicate->parent to the curBone->parent->temp
2738                                          */
2739                                         eBone->parent= (EditBone *)curBone->parent->temp;
2740                                 }
2741                                 else {
2742                                         /* If this bone has a parent that IS not selected,
2743                                          * Set the duplicate->parent to the curBone->parent
2744                                          */
2745                                         eBone->parent=(EditBone*) curBone->parent; 
2746                                         eBone->flag &= ~BONE_CONNECTED;
2747                                 }
2748                                 
2749                                 /* Lets try to fix any constraint subtargets that might
2750                                  * have been duplicated 
2751                                  */
2752                                 updateDuplicateSubtarget(eBone, arm->edbo, obedit);
2753                         }
2754                 }
2755         } 
2756         
2757         /* correct the active bone */
2758         if(arm->act_edbone) {
2759                 eBone= arm->act_edbone;
2760                 if(eBone->temp)
2761                         arm->act_edbone= eBone->temp;
2762         }
2763
2764         /*      Deselect the old bones and select the new ones */
2765         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2766                 if (EBONE_VISIBLE(arm, curBone))
2767                         curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
2768         }
2769
2770         ED_armature_validate_active(arm);
2771
2772         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
2773         
2774         return OPERATOR_FINISHED;
2775 }
2776
2777
2778 void ARMATURE_OT_duplicate(wmOperatorType *ot)
2779 {
2780         /* identifiers */
2781         ot->name= "Duplicate Selected Bone(s)";
2782         ot->idname= "ARMATURE_OT_duplicate";
2783         
2784         /* api callbacks */
2785         ot->exec = armature_duplicate_selected_exec;
2786         ot->poll = ED_operator_editarmature;
2787         
2788         /* flags */
2789         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2790 }
2791
2792
2793 /* *************** END Adding stuff in editmode *************** */
2794 /* ************** Add/Remove stuff in editmode **************** */
2795
2796 /* temporary data-structure for merge/fill bones */
2797 typedef struct EditBonePoint {
2798         struct EditBonePoint *next, *prev;
2799         
2800         EditBone *head_owner;           /* EditBone which uses this point as a 'head' point */
2801         EditBone *tail_owner;           /* EditBone which uses this point as a 'tail' point */
2802         
2803         float vec[3];                           /* the actual location of the point in local/EditMode space */
2804 } EditBonePoint;
2805
2806 /* find chain-tips (i.e. bones without children) */
2807 static void chains_find_tips (ListBase *edbo, ListBase *list)
2808 {
2809         EditBone *curBone, *ebo;
2810         LinkData *ld;
2811         
2812         /* note: this is potentially very slow ... there's got to be a better way */
2813         for (curBone= edbo->first; curBone; curBone= curBone->next) {
2814                 short stop= 0;
2815                 
2816                 /* is this bone contained within any existing chain? (skip if so) */
2817                 for (ld= list->first; ld; ld= ld->next) {
2818                         for (ebo= ld->data; ebo; ebo= ebo->parent) {
2819                                 if (ebo == curBone) {
2820                                         stop= 1;
2821                                         break;
2822                                 }
2823                         }
2824                         
2825                         if (stop) break;
2826                 }
2827                 /* skip current bone if it is part of an existing chain */
2828                 if (stop) continue;
2829                 
2830                 /* is any existing chain part of the chain formed by this bone? */
2831                 stop= 0;
2832                 for (ebo= curBone->parent; ebo; ebo= ebo->parent) {
2833                         for (ld= list->first; ld; ld= ld->next) {
2834                                 if (ld->data == ebo) {
2835                                         ld->data= curBone;
2836                                         stop= 1;
2837                                         break;
2838                                 }
2839                         }
2840                         
2841                         if (stop) break;
2842                 }
2843                 /* current bone has already been added to a chain? */
2844                 if (stop) continue;
2845                 
2846                 /* add current bone to a new chain */
2847                 ld= MEM_callocN(sizeof(LinkData), "BoneChain");
2848                 ld->data= curBone;
2849                 BLI_addtail(list, ld);
2850         }
2851 }
2852
2853 /* --------------------- */
2854
2855 static void fill_add_joint (EditBone *ebo, short eb_tail, ListBase *points)
2856 {
2857         EditBonePoint *ebp;
2858         float vec[3];
2859         short found= 0;
2860         
2861         if (eb_tail) {
2862                 VECCOPY(vec, ebo->tail);
2863         }
2864         else {
2865                 VECCOPY(vec, ebo->head);
2866         }
2867         
2868         for (ebp= points->first; ebp; ebp= ebp->next) {
2869                 if (equals_v3v3(ebp->vec, vec)) {                       
2870                         if (eb_tail) {
2871                                 if ((ebp->head_owner) && (ebp->head_owner->parent == ebo)) {
2872                                         /* so this bone's tail owner is this bone */
2873                                         ebp->tail_owner= ebo;
2874                                         found= 1;
2875                                         break;
2876                                 }
2877                         }
2878                         else {
2879                                 if ((ebp->tail_owner) && (ebo->parent == ebp->tail_owner)) {
2880                                         /* so this bone's head owner is this bone */
2881                                         ebp->head_owner= ebo;
2882                                         found = 1;
2883                                         break;
2884                                 }
2885                         }
2886                 }
2887         }
2888         
2889         /* allocate a new point if no existing point was related */
2890         if (found == 0) {
2891                 ebp= MEM_callocN(sizeof(EditBonePoint), "EditBonePoint");
2892                 
2893                 if (eb_tail) {
2894                         VECCOPY(ebp->vec, ebo->tail);
2895                         ebp->tail_owner= ebo;
2896                 }
2897                 else {
2898                         VECCOPY(ebp->vec, ebo->head);
2899                         ebp->head_owner= ebo;
2900                 }
2901                 
2902                 BLI_addtail(points, ebp);
2903         }
2904 }
2905
2906 /* bone adding between selected joints */
2907 static int armature_fill_bones_exec (bContext *C, wmOperator *op)
2908 {
2909         Object *obedit= CTX_data_edit_object(C);
2910         bArmature *arm= (obedit) ? obedit->data : NULL;
2911         Scene *scene= CTX_data_scene(C);
2912         View3D *v3d= CTX_wm_view3d(C);
2913         EditBone *newbone=NULL;
2914         ListBase points = {NULL, NULL};
2915         int count;
2916         
2917         /* sanity checks */
2918         if ELEM(NULL, obedit, arm)
2919                 return OPERATOR_CANCELLED;
2920         
2921         /* loop over all bones, and only consider if visible */
2922         CTX_DATA_BEGIN(C, EditBone *, ebone, visible_bones)
2923         {
2924                 if (!(ebone->flag & BONE_CONNECTED) && (ebone->flag & BONE_ROOTSEL))
2925                         fill_add_joint(ebone, 0, &points);
2926                 if (ebone->flag & BONE_TIPSEL) 
2927                         fill_add_joint(ebone, 1, &points);
2928         }
2929         CTX_DATA_END;
2930         
2931         /* the number of joints d