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