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