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