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