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