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