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