Gave all armature operators descriptions (for tooltips and API
[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         bArmature *arm;
1213         
1214         /* sanity checks */
1215         if (obedit == NULL)
1216                 return OPERATOR_CANCELLED;
1217         arm= obedit->data;
1218         
1219         /* set wait cursor in case this takes a while */
1220         WM_cursor_wait(1);
1221         
1222         /* we are going to do this as follows (unlike every other instance of separate):
1223          *      1. exit editmode +posemode for active armature/base. Take note of what this is.
1224          *      2. duplicate base - BASACT is the new one now
1225          *      3. for each of the two armatures, enter editmode -> remove appropriate bones -> exit editmode + recalc
1226          *      4. fix constraint links
1227          *      5. make original armature active and enter editmode
1228          */
1229         
1230         /* 1) only edit-base selected */
1231         // TODO: use context iterators for this?
1232         CTX_DATA_BEGIN(C, Base *, base, visible_bases) {
1233                 if (base->object==obedit) base->flag |= 1;
1234                 else base->flag &= ~1;
1235         }
1236         CTX_DATA_END;
1237         
1238         /* 1) store starting settings and exit editmode */
1239         oldob= obedit;
1240         oldbase= BASACT;
1241         oldob->mode &= ~OB_MODE_POSE;
1242         //oldbase->flag &= ~OB_POSEMODE;
1243         
1244         ED_armature_from_edit(obedit);
1245         ED_armature_edit_free(obedit);
1246         
1247         /* 2) duplicate base */
1248         newbase= ED_object_add_duplicate(bmain, scene, oldbase, USER_DUP_ARM); /* only duplicate linked armature */
1249         newob= newbase->object;         
1250         newbase->flag &= ~SELECT;
1251         
1252         
1253         /* 3) remove bones that shouldn't still be around on both armatures */
1254         separate_armature_bones(oldob, 1);
1255         separate_armature_bones(newob, 0);
1256         
1257         
1258         /* 4) fix links before depsgraph flushes */ // err... or after?
1259         separated_armature_fix_links(oldob, newob);
1260         
1261         DAG_id_tag_update(&oldob->id, OB_RECALC_DATA);  /* this is the original one */
1262         DAG_id_tag_update(&newob->id, OB_RECALC_DATA);  /* this is the separated one */
1263         
1264         
1265         /* 5) restore original conditions */
1266         obedit= oldob;
1267         
1268         ED_armature_to_edit(obedit);
1269         
1270         /* note, notifier might evolve */
1271         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, obedit);
1272         
1273         /* recalc/redraw + cleanup */
1274         WM_cursor_wait(0);
1275         
1276         return OPERATOR_FINISHED;
1277 }
1278
1279 void ARMATURE_OT_separate (wmOperatorType *ot)
1280 {
1281         /* identifiers */
1282         ot->name= "Separate Bones";
1283         ot->idname= "ARMATURE_OT_separate";
1284         ot->description= "Isolate selected bones into a separate armature";
1285         
1286         /* callbacks */
1287         ot->invoke= WM_operator_confirm;
1288         ot->exec= separate_armature_exec;
1289         ot->poll= ED_operator_editarmature;
1290         
1291         /* flags */
1292         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1293 }
1294
1295 /* **************** END tools on Editmode Armature **************** */
1296 /* **************** PoseMode & EditMode *************************** */
1297
1298 /* only for opengl selection indices */
1299 Bone *get_indexed_bone (Object *ob, int index)
1300 {
1301         bPoseChannel *pchan;
1302         if(ob->pose==NULL) return NULL;
1303         index>>=16;             // bone selection codes use left 2 bytes
1304         
1305         pchan= BLI_findlink(&ob->pose->chanbase, index);
1306         return pchan ? pchan->bone : NULL;
1307 }
1308
1309 /* See if there are any selected bones in this buffer */
1310 /* only bones from base are checked on */
1311 static void *get_bone_from_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, short hits, short findunsel)
1312 {
1313         Object *obedit= scene->obedit; // XXX get from context
1314         Bone *bone;
1315         EditBone *ebone;
1316         void *firstunSel=NULL, *firstSel=NULL, *data;
1317         unsigned int hitresult;
1318         short i, takeNext=0, sel;
1319         
1320         for (i=0; i< hits; i++){
1321                 hitresult = buffer[3+(i*4)];
1322                 
1323                 if (!(hitresult & BONESEL_NOSEL)) {     // -1
1324                         if(hitresult & BONESEL_ANY) {   // to avoid including objects in selection
1325                                 
1326                                 hitresult &= ~(BONESEL_ANY);
1327                                 /* Determine what the current bone is */
1328                                 if (obedit==NULL || base->object!=obedit) {
1329                                         /* no singular posemode, so check for correct object */
1330                                         if(base->selcol == (hitresult & 0xFFFF)) {
1331                                                 bone = get_indexed_bone(base->object, hitresult);
1332                                                 
1333                                                 if (findunsel)
1334                                                         sel = (bone->flag & BONE_SELECTED);
1335                                                 else
1336                                                         sel = !(bone->flag & BONE_SELECTED);
1337                                                 
1338                                                 data = bone;
1339                                         }
1340                                         else {
1341                                                 data= NULL;
1342                                                 sel= 0;
1343                                         }
1344                                 }
1345                                 else{
1346                                         bArmature *arm= obedit->data;
1347                                         
1348                                         ebone = BLI_findlink(arm->edbo, hitresult);
1349                                         if (findunsel)
1350                                                 sel = (ebone->flag & BONE_SELECTED);
1351                                         else
1352                                                 sel = !(ebone->flag & BONE_SELECTED);
1353                                         
1354                                         data = ebone;
1355                                 }
1356                                 
1357                                 if(data) {
1358                                         if (sel) {
1359                                                 if(!firstSel) firstSel= data;
1360                                                 takeNext=1;
1361                                         }
1362                                         else {
1363                                                 if (!firstunSel)
1364                                                         firstunSel=data;
1365                                                 if (takeNext)
1366                                                         return data;
1367                                         }
1368                                 }
1369                         }
1370                 }
1371         }
1372         
1373         if (firstunSel)
1374                 return firstunSel;
1375         else 
1376                 return firstSel;
1377 }
1378
1379
1380
1381 /* used by posemode as well editmode */
1382 /* only checks scene->basact! */
1383 /* x and y are mouse coords (area space) */
1384 static void *get_nearest_bone (bContext *C, short findunsel, int x, int y)
1385 {
1386         ViewContext vc;
1387         rcti rect;
1388         unsigned int buffer[MAXPICKBUF];
1389         short hits;
1390         
1391         view3d_set_viewcontext(C, &vc);
1392         
1393         // rect.xmin= ... mouseco!
1394         rect.xmin= rect.xmax= x;
1395         rect.ymin= rect.ymax= y;
1396         
1397         glInitNames();
1398         hits= view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect);
1399
1400         if (hits>0)
1401                 return get_bone_from_selectbuffer(vc.scene, vc.scene->basact, buffer, hits, findunsel);
1402         
1403         return NULL;
1404 }
1405
1406 /* helper for setflag_sel_bone() */
1407 static void bone_setflag (int *bone, int flag, short mode)
1408 {
1409         if (bone && flag) {
1410                 /* exception for inverse flags */
1411                 if (flag == BONE_NO_DEFORM) {
1412                         if (mode == 2)
1413                                 *bone |= flag;
1414                         else if (mode == 1)
1415                                 *bone &= ~flag;
1416                         else
1417                                 *bone ^= flag;
1418                 }
1419                 else {
1420                         if (mode == 2)
1421                                 *bone &= ~flag;
1422                         else if (mode == 1)
1423                                 *bone |= flag;
1424                         else
1425                                 *bone ^= flag;
1426                 }
1427         }
1428 }
1429
1430 /* Get the first available child of an editbone */
1431 static EditBone *editbone_get_child(bArmature *arm, EditBone *pabone, short use_visibility)
1432 {
1433         EditBone *curbone, *chbone=NULL;
1434         
1435         for (curbone= arm->edbo->first; curbone; curbone= curbone->next) {
1436                 if (curbone->parent == pabone) {
1437                         if (use_visibility) {
1438                                 if ((arm->layer & curbone->layer) && !(pabone->flag & BONE_HIDDEN_A)) {
1439                                         chbone = curbone;
1440                                 }
1441                         }
1442                         else
1443                                 chbone = curbone;
1444                 }
1445         }
1446         
1447         return chbone;
1448 }
1449
1450 /* callback for posemode setflag */
1451 static int pose_setflag_exec (bContext *C, wmOperator *op)
1452 {
1453         int flag= RNA_enum_get(op->ptr, "type");
1454         int mode= RNA_enum_get(op->ptr, "mode");
1455         
1456         /* loop over all selected pchans */
1457         CTX_DATA_BEGIN(C, bPoseChannel *, pchan, selected_pose_bones) 
1458         {
1459                 bone_setflag(&pchan->bone->flag, flag, mode);
1460         }
1461         CTX_DATA_END;
1462         
1463         /* note, notifier might evolve */
1464         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, ED_object_pose_armature(CTX_data_active_object(C)));
1465         
1466         return OPERATOR_FINISHED;
1467 }
1468
1469 /* callback for editbones setflag */
1470 static int armature_bones_setflag_exec (bContext *C, wmOperator *op)
1471 {
1472         int flag= RNA_enum_get(op->ptr, "type");
1473         int mode= RNA_enum_get(op->ptr, "mode");
1474         
1475         /* loop over all selected pchans */
1476         CTX_DATA_BEGIN(C, EditBone *, ebone, selected_bones) 
1477         {
1478                 bone_setflag(&ebone->flag, flag, mode);
1479         }
1480         CTX_DATA_END;
1481         
1482         /* note, notifier might evolve */
1483         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, CTX_data_edit_object(C));
1484         
1485         return OPERATOR_FINISHED;
1486 }
1487
1488 /* settings that can be changed */
1489 static EnumPropertyItem prop_bone_setting_types[] = {
1490         {BONE_DRAWWIRE, "DRAWWIRE", 0, "Draw Wire", ""},
1491         {BONE_NO_DEFORM, "DEFORM", 0, "Deform", ""},
1492         {BONE_MULT_VG_ENV, "MULT_VG", 0, "Multiply Vertex Groups", ""},
1493         {BONE_HINGE, "HINGE", 0, "Hinge", ""},
1494         {BONE_NO_SCALE, "NO_SCALE", 0, "No Scale", ""},
1495         {BONE_EDITMODE_LOCKED, "LOCKED", 0, "Locked", "(For EditMode only)"},
1496         {0, NULL, 0, NULL, NULL}
1497 };
1498
1499 /* ways that settings can be changed */
1500 static EnumPropertyItem prop_bone_setting_modes[] = {
1501         {0, "CLEAR", 0, "Clear", ""},
1502         {1, "ENABLE", 0, "Enable", ""},
1503         {2, "TOGGLE", 0, "Toggle", ""},
1504         {0, NULL, 0, NULL, NULL}
1505 };
1506
1507
1508 void ARMATURE_OT_flags_set (wmOperatorType *ot)
1509 {
1510         /* identifiers */
1511         ot->name= "Set Bone Flags";
1512         ot->idname= "ARMATURE_OT_flags_set";
1513         ot->description= "Set flags for armature bones";
1514         
1515         /* callbacks */
1516         ot->invoke= WM_menu_invoke;
1517         ot->exec= armature_bones_setflag_exec;
1518         ot->poll= ED_operator_editarmature;
1519         
1520         /* flags */
1521         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1522         
1523         /* properties */
1524         ot->prop= RNA_def_enum(ot->srna, "type", prop_bone_setting_types, 0, "Type", "");
1525         RNA_def_enum(ot->srna, "mode", prop_bone_setting_modes, 0, "Mode", "");
1526 }
1527
1528 void POSE_OT_flags_set (wmOperatorType *ot)
1529 {
1530         /* identifiers */
1531         ot->name= "Set Bone Flags";
1532         ot->idname= "POSE_OT_flags_set";
1533         ot->description= "Set flags for armature bones";
1534         
1535         /* callbacks */
1536         ot->invoke= WM_menu_invoke;
1537         ot->exec= pose_setflag_exec;
1538         ot->poll= ED_operator_posemode;
1539         
1540         /* flags */
1541         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1542         
1543         /* properties */
1544         ot->prop= RNA_def_enum(ot->srna, "type", prop_bone_setting_types, 0, "Type", "");
1545         RNA_def_enum(ot->srna, "mode", prop_bone_setting_modes, 0, "Mode", "");
1546 }
1547
1548
1549 /* **************** END PoseMode & EditMode *************************** */
1550 /* **************** Posemode stuff ********************** */
1551
1552
1553 static void selectconnected_posebonechildren (Object *ob, Bone *bone, int extend)
1554 {
1555         Bone *curBone;
1556         
1557         /* stop when unconnected child is encontered, or when unselectable bone is encountered */
1558         if (!(bone->flag & BONE_CONNECTED) || (bone->flag & BONE_UNSELECTABLE))
1559                 return;
1560         
1561                 // XXX old cruft! use notifiers instead
1562         //select_actionchannel_by_name (ob->action, bone->name, !(shift));
1563         
1564         if (extend)
1565                 bone->flag &= ~BONE_SELECTED;
1566         else
1567                 bone->flag |= BONE_SELECTED;
1568         
1569         for (curBone=bone->childbase.first; curBone; curBone=curBone->next)
1570                 selectconnected_posebonechildren(ob, curBone, extend);
1571 }
1572
1573 /* within active object context */
1574 /* previously known as "selectconnected_posearmature" */
1575 static int pose_select_connected_invoke(bContext *C, wmOperator *op, wmEvent *event)
1576 {  
1577         ARegion *ar= CTX_wm_region(C);
1578         Object *ob= CTX_data_edit_object(C);
1579         Bone *bone, *curBone, *next= NULL;
1580         int extend= RNA_boolean_get(op->ptr, "extend");
1581         int x, y;
1582         
1583         x= event->x - ar->winrct.xmin;
1584         y= event->y - ar->winrct.ymin;
1585
1586         view3d_operator_needs_opengl(C);
1587         
1588         if (extend)
1589                 bone= get_nearest_bone(C, 0, x, y);
1590         else
1591                 bone= get_nearest_bone(C, 1, x, y);
1592         
1593         if (!bone)
1594                 return OPERATOR_CANCELLED;
1595         
1596         /* Select parents */
1597         for (curBone=bone; curBone; curBone=next){
1598                 /* ignore bone if cannot be selected */
1599                 if ((curBone->flag & BONE_UNSELECTABLE) == 0) { 
1600                                 // XXX old cruft! use notifiers instead
1601                         //select_actionchannel_by_name (ob->action, curBone->name, !(shift));
1602                         
1603                         if (extend)
1604                                 curBone->flag &= ~BONE_SELECTED;
1605                         else
1606                                 curBone->flag |= BONE_SELECTED;
1607                         
1608                         if (curBone->flag & BONE_CONNECTED)
1609                                 next=curBone->parent;
1610                         else
1611                                 next=NULL;
1612                 }
1613                 else
1614                         next= NULL;
1615         }
1616         
1617         /* Select children */
1618         for (curBone=bone->childbase.first; curBone; curBone=next)
1619                 selectconnected_posebonechildren(ob, curBone, extend);
1620         
1621         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, ob);
1622
1623         return OPERATOR_FINISHED;
1624 }
1625
1626 static int pose_select_linked_poll(bContext *C)
1627 {
1628         return ( ED_operator_view3d_active(C) && ED_operator_posemode(C) );
1629 }
1630
1631 void POSE_OT_select_linked(wmOperatorType *ot)
1632 {
1633         /* identifiers */
1634         ot->name= "Select Connected";
1635         ot->idname= "POSE_OT_select_linked";
1636         ot->description= "Select bones related to selected ones by parent/child relationships";
1637         
1638         /* api callbacks */
1639         ot->exec= NULL;
1640         ot->invoke= pose_select_connected_invoke;
1641         ot->poll= pose_select_linked_poll;
1642         
1643         /* flags */
1644         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1645         
1646         /* props */     
1647         RNA_def_boolean(ot->srna, "extend", FALSE, "Extend", "Extend selection instead of deselecting everything first.");
1648 }
1649
1650 /* **************** END Posemode stuff ********************** */
1651 /* **************** EditMode stuff ********************** */
1652
1653 /* called in space.c */
1654 /* previously "selectconnected_armature" */
1655 static int armature_select_linked_invoke(bContext *C, wmOperator *op, wmEvent *event)
1656 {
1657         bArmature *arm;
1658         EditBone *bone, *curBone, *next;
1659         int extend= RNA_boolean_get(op->ptr, "extend");
1660         int x, y;
1661         ARegion *ar;
1662         Object *obedit= CTX_data_edit_object(C);
1663         arm= obedit->data;
1664         ar= CTX_wm_region(C);
1665
1666         x= event->x - ar->winrct.xmin;
1667         y= event->y - ar->winrct.ymin;
1668
1669         view3d_operator_needs_opengl(C);
1670
1671         if (extend)
1672                 bone= get_nearest_bone(C, 0, x, y);
1673         else
1674                 bone= get_nearest_bone(C, 1, x, y);
1675
1676         if (!bone)
1677                 return OPERATOR_CANCELLED;
1678
1679         /* Select parents */
1680         for (curBone=bone; curBone; curBone=next) {
1681                 if ((curBone->flag & BONE_UNSELECTABLE) == 0) {
1682                         if (extend) {
1683                                 curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1684                         }
1685                         else{
1686                                 curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1687                         }
1688                 }
1689                 
1690                 if (curBone->flag & BONE_CONNECTED)
1691                         next=curBone->parent;
1692                 else
1693                         next=NULL;
1694         }
1695
1696         /* Select children */
1697         while (bone) {
1698                 for (curBone=arm->edbo->first; curBone; curBone=next) {
1699                         next = curBone->next;
1700                         if ((curBone->parent == bone) && (curBone->flag & BONE_UNSELECTABLE)==0) {
1701                                 if (curBone->flag & BONE_CONNECTED) {
1702                                         if (extend)
1703                                                 curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1704                                         else
1705                                                 curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1706                                         bone=curBone;
1707                                         break;
1708                                 }
1709                                 else { 
1710                                         bone=NULL;
1711                                         break;
1712                                 }
1713                         }
1714                 }
1715                 if (!curBone)
1716                         bone=NULL;
1717         }
1718         
1719         ED_armature_sync_selection(arm->edbo);
1720         
1721         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
1722         
1723         return OPERATOR_FINISHED;
1724 }
1725
1726 static int armature_select_linked_poll(bContext *C)
1727 {
1728         return ( ED_operator_view3d_active(C) && ED_operator_editarmature(C) );
1729 }
1730
1731 void ARMATURE_OT_select_linked(wmOperatorType *ot)
1732 {
1733         /* identifiers */
1734         ot->name= "Select Connected";
1735         ot->idname= "ARMATURE_OT_select_linked";
1736         ot->description= "Select bones related to selected ones by parent/child relationships";
1737         
1738         /* api callbacks */
1739         ot->exec= NULL;
1740         ot->invoke= armature_select_linked_invoke;
1741         ot->poll= armature_select_linked_poll;
1742         
1743         /* flags */
1744         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1745         
1746         /* properties s*/
1747         RNA_def_boolean(ot->srna, "extend", FALSE, "Extend", "Extend selection instead of deselecting everything first.");
1748 }
1749
1750 /* does bones and points */
1751 /* note that BONE ROOT only gets drawn for root bones (or without IK) */
1752 static EditBone *get_nearest_editbonepoint (ViewContext *vc, short mval[2], ListBase *edbo, int findunsel, int *selmask)
1753 {
1754         EditBone *ebone;
1755         rcti rect;
1756         unsigned int buffer[MAXPICKBUF];
1757         unsigned int hitresult, besthitresult=BONESEL_NOSEL;
1758         int i, mindep= 4;
1759         short hits;
1760
1761         glInitNames();
1762         
1763         rect.xmin= mval[0]-5;
1764         rect.xmax= mval[0]+5;
1765         rect.ymin= mval[1]-5;
1766         rect.ymax= mval[1]+5;
1767         
1768         hits= view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect);
1769         if(hits==0) {
1770                 rect.xmin= mval[0]-12;
1771                 rect.xmax= mval[0]+12;
1772                 rect.ymin= mval[1]-12;
1773                 rect.ymax= mval[1]+12;
1774                 hits= view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect);
1775         }
1776         /* See if there are any selected bones in this group */
1777         if (hits>0) {
1778                 
1779                 if(hits==1) {
1780                         if (!(buffer[3] & BONESEL_NOSEL)) 
1781                                 besthitresult= buffer[3];
1782                 }
1783                 else {
1784                         for (i=0; i< hits; i++) {
1785                                 hitresult= buffer[3+(i*4)];
1786                                 if (!(hitresult & BONESEL_NOSEL)) {
1787                                         int dep;
1788                                         
1789                                         ebone = BLI_findlink(edbo, hitresult & ~BONESEL_ANY);
1790                                         
1791                                         /* clicks on bone points get advantage */
1792                                         if( hitresult & (BONESEL_ROOT|BONESEL_TIP)) {
1793                                                 /* but also the unselected one */
1794                                                 if(findunsel) {
1795                                                         if( (hitresult & BONESEL_ROOT) && (ebone->flag & BONE_ROOTSEL)==0) 
1796                                                                 dep= 1;
1797                                                         else if( (hitresult & BONESEL_TIP) && (ebone->flag & BONE_TIPSEL)==0) 
1798                                                                 dep= 1;
1799                                                         else 
1800                                                                 dep= 2;
1801                                                 }
1802                                                 else dep= 2;
1803                                         }
1804                                         else {
1805                                                 /* bone found */
1806                                                 if(findunsel) {
1807                                                         if((ebone->flag & BONE_SELECTED)==0)
1808                                                                 dep= 2;
1809                                                         else
1810                                                                 dep= 3;
1811                                                 }
1812                                                 else dep= 3;
1813                                         }
1814                                         if(dep < mindep) {
1815                                                 mindep= dep;
1816                                                 besthitresult= hitresult;
1817                                         }
1818                                 }
1819                         }
1820                 }
1821                 
1822                 if (!(besthitresult & BONESEL_NOSEL)) {
1823                         
1824                         ebone= BLI_findlink(edbo, besthitresult & ~BONESEL_ANY);
1825                         
1826                         *selmask = 0;
1827                         if (besthitresult & BONESEL_ROOT)
1828                                 *selmask |= BONE_ROOTSEL;
1829                         if (besthitresult & BONESEL_TIP)
1830                                 *selmask |= BONE_TIPSEL;
1831                         if (besthitresult & BONESEL_BONE)
1832                                 *selmask |= BONE_SELECTED;
1833                         return ebone;
1834                 }
1835         }
1836         *selmask = 0;
1837         return NULL;
1838 }
1839
1840 /* previously delete_armature */
1841 /* only editmode! */
1842 static int armature_delete_selected_exec(bContext *C, wmOperator *UNUSED(op))
1843 {
1844         bArmature *arm;
1845         EditBone        *curBone, *ebone_next;
1846         bConstraint *con;
1847         Object *obedit= CTX_data_edit_object(C); // XXX get from context
1848         arm = obedit->data;
1849
1850         /* cancel if nothing selected */
1851         if (CTX_DATA_COUNT(C, selected_bones) == 0)
1852                 return OPERATOR_CANCELLED;
1853         
1854         armature_select_mirrored(arm);
1855         
1856         /*  First erase any associated pose channel */
1857         if (obedit->pose) {
1858                 bPoseChannel *pchan, *pchan_next;
1859                 for (pchan=obedit->pose->chanbase.first; pchan; pchan= pchan_next) {
1860                         pchan_next= pchan->next;
1861                         curBone = editbone_name_exists(arm->edbo, pchan->name);
1862                         
1863                         if (curBone && (curBone->flag & BONE_SELECTED) && (arm->layer & curBone->layer)) {
1864                                 free_pose_channel(pchan);
1865                                 free_pose_channels_hash(obedit->pose);
1866                                 BLI_freelinkN (&obedit->pose->chanbase, pchan);
1867                         }
1868                         else {
1869                                 for (con= pchan->constraints.first; con; con= con->next) {
1870                                         bConstraintTypeInfo *cti= constraint_get_typeinfo(con);
1871                                         ListBase targets = {NULL, NULL};
1872                                         bConstraintTarget *ct;
1873                                         
1874                                         if (cti && cti->get_constraint_targets) {
1875                                                 cti->get_constraint_targets(con, &targets);
1876                                                 
1877                                                 for (ct= targets.first; ct; ct= ct->next) {
1878                                                         if (ct->tar == obedit) {
1879                                                                 if (ct->subtarget[0]) {
1880                                                                         curBone = editbone_name_exists(arm->edbo, ct->subtarget);
1881                                                                         if (curBone && (curBone->flag & BONE_SELECTED) && (arm->layer & curBone->layer)) {
1882                                                                                 con->flag |= CONSTRAINT_DISABLE;
1883                                                                                 ct->subtarget[0]= 0;
1884                                                                         }
1885                                                                 }
1886                                                         }
1887                                                 }
1888                                                 
1889                                                 if (cti->flush_constraint_targets)
1890                                                         cti->flush_constraint_targets(con, &targets, 0);
1891                                         }
1892                                 }
1893                         }
1894                 }
1895         }
1896         
1897         
1898         for (curBone=arm->edbo->first; curBone; curBone= ebone_next) {
1899                 ebone_next= curBone->next;
1900                 if (arm->layer & curBone->layer) {
1901                         if (curBone->flag & BONE_SELECTED) {
1902                                 if(curBone==arm->act_edbone) arm->act_edbone= NULL;
1903                                 ED_armature_edit_bone_remove(arm, curBone);
1904                         }
1905                 }
1906         }
1907         
1908         
1909         ED_armature_sync_selection(arm->edbo);
1910
1911         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
1912
1913         return OPERATOR_FINISHED;
1914 }
1915
1916 void ARMATURE_OT_delete(wmOperatorType *ot)
1917 {
1918         /* identifiers */
1919         ot->name= "Delete Selected Bone(s)";
1920         ot->idname= "ARMATURE_OT_delete";
1921         ot->description= "Remove selected bones from the armature";
1922         
1923         /* api callbacks */
1924         ot->invoke = WM_operator_confirm;
1925         ot->exec = armature_delete_selected_exec;
1926         ot->poll = ED_operator_editarmature;
1927         
1928         /* flags */
1929         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1930 }
1931
1932 /* toggle==0: deselect
1933  * toggle==1: swap (based on test)
1934  * toggle==2: swap (no test), CURRENTLY UNUSED
1935  */
1936 void ED_armature_deselect_all(Object *obedit, int toggle)
1937 {
1938         bArmature *arm= obedit->data;
1939         EditBone        *eBone;
1940         int                     sel=1;
1941         
1942         if(toggle==1) {
1943                 /*      Determine if there are any selected bones
1944                 And therefore whether we are selecting or deselecting */
1945                 for (eBone=arm->edbo->first;eBone;eBone=eBone->next){
1946                         //                      if(arm->layer & eBone->layer) {
1947                         if (eBone->flag & (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL)){
1948                                 sel=0;
1949                                 break;
1950                         }
1951                         //                      }
1952                 }
1953         }
1954         else sel= toggle;
1955         
1956         /*      Set the flags */
1957         for (eBone=arm->edbo->first;eBone;eBone=eBone->next) {
1958                 if (sel==2) {
1959                         /* invert selection of bone */
1960                         if(EBONE_VISIBLE(arm, eBone)) {
1961                                 eBone->flag ^= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1962                                 if(arm->act_edbone==eBone)
1963                                         arm->act_edbone= NULL;
1964                         }
1965                 }
1966                 else if (sel==1) {
1967                         /* select bone */
1968                         if(EBONE_VISIBLE(arm, eBone)) {
1969                                 eBone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1970                                 if(eBone->parent)
1971                                         eBone->parent->flag |= (BONE_TIPSEL);
1972                         }
1973                 }
1974                 else {
1975                         /* deselect bone */
1976                         eBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1977                         if(arm->act_edbone==eBone)
1978                                 arm->act_edbone= NULL;
1979                 }
1980         }
1981         
1982         ED_armature_sync_selection(arm->edbo);
1983 }
1984
1985 void ED_armature_deselect_all_visible(Object *obedit)
1986 {
1987         bArmature *arm= obedit->data;
1988         EditBone        *ebone;
1989
1990         for (ebone= arm->edbo->first; ebone; ebone= ebone->next) {
1991                 /* first and foremost, bone must be visible and selected */
1992                 if (EBONE_VISIBLE(arm, ebone) && (ebone->flag & BONE_UNSELECTABLE)==0) {
1993                         ebone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1994                 }
1995         }
1996
1997         ED_armature_sync_selection(arm->edbo);
1998 }
1999
2000 /* accounts for connected parents */
2001 static int ebone_select_flag(EditBone *ebone)
2002 {
2003         if(ebone->parent && (ebone->flag & BONE_CONNECTED)) {
2004                 return ((ebone->parent->flag & BONE_TIPSEL) ? BONE_ROOTSEL : 0) | (ebone->flag & (BONE_SELECTED|BONE_TIPSEL));
2005         }
2006         else {
2007                 return ebone->flag & (BONE_SELECTED|BONE_ROOTSEL|BONE_TIPSEL);
2008         }
2009 }
2010
2011 /* context: editmode armature in view3d */
2012 int mouse_armature(bContext *C, short mval[2], int extend)
2013 {
2014         Object *obedit= CTX_data_edit_object(C);
2015         bArmature *arm= obedit->data;
2016         ViewContext vc;
2017         EditBone *nearBone = NULL;
2018         int     selmask;
2019
2020         view3d_set_viewcontext(C, &vc);
2021         
2022         BIF_sk_selectStroke(C, mval, extend);
2023         
2024         nearBone= get_nearest_editbonepoint(&vc, mval, arm->edbo, 1, &selmask);
2025         if (nearBone) {
2026
2027                 if (!extend)
2028                         ED_armature_deselect_all(obedit, 0);
2029                 
2030                 /* by definition the non-root connected bones have no root point drawn,
2031                    so a root selection needs to be delivered to the parent tip */
2032                 
2033                 if(selmask & BONE_SELECTED) {
2034                         if(nearBone->parent && (nearBone->flag & BONE_CONNECTED)) {
2035                                 /* click in a chain */
2036                                 if(extend) {
2037                                         /* hold shift inverts this bone's selection */
2038                                         if(nearBone->flag & BONE_SELECTED) {
2039                                                 /* deselect this bone */
2040                                                 nearBone->flag &= ~(BONE_TIPSEL|BONE_SELECTED);
2041                                                 /* only deselect parent tip if it is not selected */
2042                                                 if(!(nearBone->parent->flag & BONE_SELECTED))
2043                                                         nearBone->parent->flag &= ~BONE_TIPSEL;
2044                                         }
2045                                         else {
2046                                                 /* select this bone */
2047                                                 nearBone->flag |= BONE_TIPSEL;
2048                                                 nearBone->parent->flag |= BONE_TIPSEL;
2049                                         }
2050                                 }
2051                                 else {
2052                                         /* select this bone */
2053                                         nearBone->flag |= BONE_TIPSEL;
2054                                         nearBone->parent->flag |= BONE_TIPSEL;
2055                                 }
2056                         }
2057                         else {
2058                                 if(extend) {
2059                                         /* hold shift inverts this bone's selection */
2060                                         if(nearBone->flag & BONE_SELECTED)
2061                                            nearBone->flag &= ~(BONE_TIPSEL|BONE_ROOTSEL);
2062                                         else
2063                                                 nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
2064                                 }
2065                                 else nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
2066                         }
2067                 }
2068                 else {
2069                         if (extend && (nearBone->flag & selmask))
2070                                 nearBone->flag &= ~selmask;
2071                         else
2072                                 nearBone->flag |= selmask;
2073                 }
2074                 
2075                 ED_armature_sync_selection(arm->edbo);
2076                 
2077                 if(nearBone) {
2078                         /* then now check for active status */
2079                         if(ebone_select_flag(nearBone)) {
2080                                 arm->act_edbone= nearBone;
2081                         }
2082                 }
2083                 
2084                 WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, vc.obedit);
2085                 return 1;
2086         }
2087
2088         return 0;
2089 }
2090
2091 void ED_armature_edit_free(struct Object *ob)
2092 {
2093         bArmature *arm= ob->data;
2094         EditBone *eBone;
2095         
2096         /*      Clear the editbones list */
2097         if (arm->edbo) {
2098                 if (arm->edbo->first) {
2099                         for (eBone=arm->edbo->first; eBone; eBone=eBone->next) {
2100                                 if (eBone->prop) {
2101                                         IDP_FreeProperty(eBone->prop);
2102                                         MEM_freeN(eBone->prop);
2103                                 }
2104                         }
2105
2106                         BLI_freelistN(arm->edbo);
2107                 }
2108                 MEM_freeN(arm->edbo);
2109                 arm->edbo= NULL;
2110         }
2111 }
2112
2113 /* Put armature in EditMode */
2114 void ED_armature_to_edit(Object *ob)
2115 {
2116         bArmature *arm= ob->data;
2117         
2118         ED_armature_edit_free(ob);
2119         arm->edbo= MEM_callocN(sizeof(ListBase), "edbo armature");
2120         arm->act_edbone= make_boneList(arm->edbo, &arm->bonebase, NULL, arm->act_bone);
2121         arm->act_bone= NULL;
2122
2123 //      BIF_freeTemplates(); /* force template update when entering editmode */
2124 }
2125
2126
2127 /* adjust bone roll to align Z axis with vector
2128  * vec is in local space and is normalized
2129  */
2130
2131 float ED_rollBoneToVector(EditBone *bone, const float align_axis[3], const short axis_only)
2132 {
2133         float mat[3][3], nor[3];
2134
2135         sub_v3_v3v3(nor, bone->tail, bone->head);
2136         vec_roll_to_mat3(nor, 0.0f, mat);
2137
2138         /* check the bone isnt aligned with the axis */
2139         if(!is_zero_v3(align_axis) && angle_v3v3(align_axis, mat[2]) > FLT_EPSILON) {
2140                 float vec[3], align_axis_proj[3], roll;
2141
2142                 /* project the new_up_axis along the normal */
2143                 project_v3_v3v3(vec, align_axis, nor);
2144                 sub_v3_v3v3(align_axis_proj, align_axis, vec);
2145                 
2146                 if(axis_only) {
2147                         if(angle_v3v3(align_axis_proj, mat[2]) > M_PI/2) {
2148                                 negate_v3(align_axis_proj);
2149                         }
2150                 }
2151                 
2152                 roll = angle_v3v3(align_axis_proj, mat[2]);
2153                 
2154                 cross_v3_v3v3(vec, mat[2], align_axis_proj);
2155                 
2156                 if (dot_v3v3(vec, nor) < 0) {
2157                         roll = -roll;
2158                 }
2159
2160                 return roll;
2161         }
2162
2163         return 0.0f;
2164 }
2165
2166
2167 static EnumPropertyItem prop_calc_roll_types[] = {
2168         {0, "X", 0, "X Axis", ""},
2169         {1, "Y", 0, "Y Axis", ""},
2170         {2, "Z", 0, "Z Axis", ""},
2171         {5, "ACTIVE", 0, "Active Bone", ""},
2172         {6, "VIEW", 0, "View Axis", ""},
2173         {7, "CURSOR", 0, "Cursor", ""},
2174         {0, NULL, 0, NULL, NULL}
2175 };
2176
2177
2178 static int armature_calc_roll_exec(bContext *C, wmOperator *op) 
2179 {
2180         Object *ob= CTX_data_edit_object(C);
2181         const short type= RNA_enum_get(op->ptr, "type");
2182         const short axis_only= RNA_boolean_get(op->ptr, "axis_only");
2183         const short axis_flip= RNA_boolean_get(op->ptr, "axis_flip");
2184
2185         float imat[3][3];
2186
2187         bArmature *arm= ob->data;
2188         EditBone *ebone;
2189
2190         copy_m3_m4(imat, ob->obmat);
2191         invert_m3(imat);
2192
2193         if(type==7) { /* Cursor */
2194                 Scene *scene= CTX_data_scene(C);
2195                 View3D *v3d= CTX_wm_view3d(C); /* can be NULL */
2196                 float cursor_local[3];
2197                 float   *cursor= give_cursor(scene, v3d);
2198         
2199
2200                 copy_v3_v3(cursor_local, cursor);
2201                 mul_m3_v3(imat, cursor_local);
2202
2203                 /* cursor */
2204                 for(ebone= arm->edbo->first; ebone; ebone= ebone->next) {
2205                         if(EBONE_VISIBLE(arm, ebone) && EBONE_EDITABLE(ebone)) {
2206                                 float cursor_rel[3];
2207                                 sub_v3_v3v3(cursor_rel, cursor_local, ebone->head);
2208                                 if(axis_flip) negate_v3(cursor_rel);
2209                                 ebone->roll= ED_rollBoneToVector(ebone, cursor_rel, axis_only);
2210                         }
2211                 }
2212         }
2213         else {
2214                 float vec[3]= {0.0f, 0.0f, 0.0f};
2215                 if(type==6) { /* View */
2216                         RegionView3D *rv3d= CTX_wm_region_view3d(C);
2217                         if(rv3d==NULL) {
2218                                 BKE_report(op->reports, RPT_ERROR, "No region view3d available");
2219                                 return OPERATOR_CANCELLED;
2220                         }
2221
2222                         copy_v3_v3(vec, rv3d->viewinv[2]);
2223                         mul_m3_v3(imat, vec);
2224                 }
2225                 else if (type==5) {
2226                         bArmature *arm= ob->data;
2227                         EditBone *ebone= (EditBone *)arm->act_edbone;
2228                         float mat[3][3], nor[3];
2229
2230                         if(ebone==NULL) {
2231                                 BKE_report(op->reports, RPT_ERROR, "No active bone set");
2232                                 return OPERATOR_CANCELLED;
2233                         }
2234
2235                         sub_v3_v3v3(nor, ebone->tail, ebone->head);
2236                         vec_roll_to_mat3(nor, ebone->roll, mat);                        
2237                         copy_v3_v3(vec, mat[2]);
2238                 }
2239                 else { /* Axis */
2240                         assert(type >= 0 && type <= 5);
2241                         if(type<3)      vec[type]= 1.0f; 
2242                         else            vec[type-2]= -1.0f; 
2243                         mul_m3_v3(imat, vec);
2244                 }
2245
2246                 if(axis_flip) negate_v3(vec);
2247
2248                 for(ebone= arm->edbo->first; ebone; ebone= ebone->next) {
2249                         if(EBONE_VISIBLE(arm, ebone) && EBONE_EDITABLE(ebone)) {
2250                                 /* roll func is a callback which assumes that all is well */
2251                                 ebone->roll= ED_rollBoneToVector(ebone, vec, axis_only);
2252                         }
2253                 }
2254         }
2255
2256         if (arm->flag & ARM_MIRROR_EDIT) {
2257                 for(ebone= arm->edbo->first; ebone; ebone= ebone->next) {
2258                         if((EBONE_VISIBLE(arm, ebone) && EBONE_EDITABLE(ebone)) == 0) {
2259                                 EditBone *ebone_mirr= ED_armature_bone_get_mirrored(arm->edbo, ebone);
2260                                 if (ebone_mirr && (EBONE_VISIBLE(arm, ebone_mirr) && EBONE_EDITABLE(ebone_mirr))) {
2261                                         ebone->roll= -ebone_mirr->roll;
2262                                 }
2263                         }
2264                 }
2265         }
2266
2267         /* note, notifier might evolve */
2268         WM_event_add_notifier(C, NC_OBJECT|ND_POSE, ob);
2269         
2270         return OPERATOR_FINISHED;
2271 }
2272
2273 void ARMATURE_OT_calculate_roll(wmOperatorType *ot)
2274 {
2275         /* identifiers */
2276         ot->name= "Recalculate Roll";
2277         ot->idname= "ARMATURE_OT_calculate_roll";
2278         ot->description= "Automatically fix alignment of select bones' axes";
2279         
2280         /* api callbacks */
2281         ot->invoke = WM_menu_invoke;
2282         ot->exec = armature_calc_roll_exec;
2283         ot->poll = ED_operator_editarmature;
2284         
2285         /* flags */
2286         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2287
2288         /* properties */
2289         ot->prop= RNA_def_enum(ot->srna, "type", prop_calc_roll_types, 0, "Type", "");
2290         RNA_def_boolean(ot->srna, "axis_flip", 0, "Flip Axis", "Negate the alignment axis.");
2291         RNA_def_boolean(ot->srna, "axis_only", 0, "Shortest Rotation", "Ignore the axis direction, use the shortest rotation to align.");
2292 }
2293
2294 /* **************** undo for armatures ************** */
2295
2296 typedef struct UndoArmature {
2297         EditBone *act_edbone;
2298         ListBase lb;
2299 } UndoArmature;
2300
2301 static void undoBones_to_editBones(void *uarmv, void *armv)
2302 {
2303         UndoArmature *uarm= uarmv;
2304         bArmature *arm= armv;
2305         EditBone *ebo, *newebo;
2306         
2307         BLI_freelistN(arm->edbo);
2308         
2309         /* copy  */
2310         for(ebo= uarm->lb.first; ebo; ebo= ebo->next) {
2311                 newebo= MEM_dupallocN(ebo);
2312                 ebo->temp= newebo;
2313                 BLI_addtail(arm->edbo, newebo);
2314         }
2315         
2316         /* active bone */
2317         if(uarm->act_edbone) {
2318                 ebo= uarm->act_edbone;
2319                 arm->act_edbone= ebo->temp;
2320         }
2321         else
2322                 arm->act_edbone= NULL;
2323
2324         /* set pointers */
2325         for(newebo= arm->edbo->first; newebo; newebo= newebo->next) {
2326                 if(newebo->parent) newebo->parent= newebo->parent->temp;
2327         }
2328         /* be sure they dont hang ever */
2329         for(newebo= arm->edbo->first; newebo; newebo= newebo->next) {
2330                 newebo->temp= NULL;
2331         }
2332 }
2333
2334 static void *editBones_to_undoBones(void *armv)
2335 {
2336         bArmature *arm= armv;
2337         UndoArmature *uarm;
2338         EditBone *ebo, *newebo;
2339         
2340         uarm= MEM_callocN(sizeof(UndoArmature), "listbase undo");
2341         
2342         /* copy */
2343         for(ebo= arm->edbo->first; ebo; ebo= ebo->next) {
2344                 newebo= MEM_dupallocN(ebo);
2345                 ebo->temp= newebo;
2346                 BLI_addtail(&uarm->lb, newebo);
2347         }
2348         
2349         /* active bone */
2350         if(arm->act_edbone) {
2351                 ebo= arm->act_edbone;
2352                 uarm->act_edbone= ebo->temp;
2353         }
2354
2355         /* set pointers */
2356         for(newebo= uarm->lb.first; newebo; newebo= newebo->next) {
2357                 if(newebo->parent) newebo->parent= newebo->parent->temp;
2358         }
2359         
2360         return uarm;
2361 }
2362
2363 static void free_undoBones(void *uarmv)
2364 {
2365         UndoArmature *uarm= uarmv;
2366         
2367         BLI_freelistN(&uarm->lb);
2368         MEM_freeN(uarm);
2369 }
2370
2371 static void *get_armature_edit(bContext *C)
2372 {
2373         Object *obedit= CTX_data_edit_object(C);
2374         if(obedit && obedit->type==OB_ARMATURE) {
2375                 return obedit->data;
2376         }
2377         return NULL;
2378 }
2379
2380 /* and this is all the undo system needs to know */
2381 void undo_push_armature(bContext *C, const char *name)
2382 {
2383         // XXX solve getdata()
2384         undo_editmode_push(C, name, get_armature_edit, free_undoBones, undoBones_to_editBones, editBones_to_undoBones, NULL);
2385 }
2386
2387
2388
2389 /* **************** END EditMode stuff ********************** */
2390 /* *************** Adding stuff in editmode *************** */
2391
2392 /* default bone add, returns it selected, but without tail set */
2393 EditBone *ED_armature_edit_bone_add(bArmature *arm, const char *name)
2394 {
2395         EditBone *bone= MEM_callocN(sizeof(EditBone), "eBone");
2396         
2397         BLI_strncpy(bone->name, name, sizeof(bone->name));
2398         unique_editbone_name(arm->edbo, bone->name, NULL);
2399         
2400         BLI_addtail(arm->edbo, bone);
2401         
2402         bone->flag |= BONE_TIPSEL;
2403         bone->weight= 1.0f;
2404         bone->dist= 0.25f;
2405         bone->xwidth= 0.1f;
2406         bone->zwidth= 0.1f;
2407         bone->ease1= 1.0f;
2408         bone->ease2= 1.0f;
2409         bone->rad_head= 0.10f;
2410         bone->rad_tail= 0.05f;
2411         bone->segments= 1;
2412         bone->layer= arm->layer;
2413         
2414         return bone;
2415 }
2416
2417 /* v3d and rv3d are allowed to be NULL */
2418 void add_primitive_bone(Scene *scene, View3D *v3d, RegionView3D *rv3d)
2419 {
2420         Object *obedit= scene->obedit; // XXX get from context
2421         float           obmat[3][3], curs[3], viewmat[3][3], totmat[3][3], imat[3][3];
2422         EditBone        *bone;
2423
2424         /* Get inverse point for head and orientation for tail */
2425         invert_m4_m4(obedit->imat, obedit->obmat);
2426         mul_v3_m4v3(curs, obedit->imat, give_cursor(scene, v3d));
2427
2428         if (rv3d && (U.flag & USER_ADD_VIEWALIGNED))
2429                 copy_m3_m4(obmat, rv3d->viewmat);
2430         else unit_m3(obmat);
2431         
2432         copy_m3_m4(viewmat, obedit->obmat);
2433         mul_m3_m3m3(totmat, obmat, viewmat);
2434         invert_m3_m3(imat, totmat);
2435         
2436         ED_armature_deselect_all(obedit, 0);
2437         
2438         /*      Create a bone   */
2439         bone= ED_armature_edit_bone_add(obedit->data, "Bone");
2440
2441         copy_v3_v3(bone->head, curs);
2442         
2443         if (rv3d && (U.flag & USER_ADD_VIEWALIGNED))
2444                 add_v3_v3v3(bone->tail, bone->head, imat[1]);   // bone with unit length 1
2445         else
2446                 add_v3_v3v3(bone->tail, bone->head, imat[2]);   // bone with unit length 1, pointing up Z
2447         
2448 }
2449
2450
2451 /* previously addvert_armature */
2452 /* the ctrl-click method */
2453 static int armature_click_extrude_exec(bContext *C, wmOperator *UNUSED(op))
2454 {
2455         View3D *v3d;
2456         bArmature *arm;
2457         EditBone *ebone, *newbone, *flipbone;
2458         float *curs, mat[3][3],imat[3][3];
2459         int a, to_root= 0;
2460         Object *obedit;
2461         Scene *scene;
2462
2463         scene = CTX_data_scene(C);
2464         v3d= CTX_wm_view3d(C);
2465         obedit= CTX_data_edit_object(C);
2466         arm= obedit->data;
2467         
2468         /* find the active or selected bone */
2469         for (ebone = arm->edbo->first; ebone; ebone=ebone->next) {
2470                 if (EBONE_VISIBLE(arm, ebone)) {
2471                         if (ebone->flag & BONE_TIPSEL || arm->act_edbone == ebone)
2472                                 break;
2473                 }
2474         }
2475         
2476         if (ebone==NULL) {
2477                 for (ebone = arm->edbo->first; ebone; ebone=ebone->next) {
2478                         if (EBONE_VISIBLE(arm, ebone)) {
2479                                 if (ebone->flag & BONE_ROOTSEL || arm->act_edbone == ebone)
2480                                         break;
2481                         }
2482                 }
2483                 if (ebone == NULL) 
2484                         return OPERATOR_CANCELLED;
2485                 
2486                 to_root= 1;
2487         }
2488         
2489         ED_armature_deselect_all(obedit, 0);
2490         
2491         /* we re-use code for mirror editing... */
2492         flipbone= NULL;
2493         if (arm->flag & ARM_MIRROR_EDIT)
2494                 flipbone= ED_armature_bone_get_mirrored(arm->edbo, ebone);
2495
2496         for (a=0; a<2; a++) {
2497                 if (a==1) {
2498                         if (flipbone==NULL)
2499                                 break;
2500                         else {
2501                                 SWAP(EditBone *, flipbone, ebone);
2502                         }
2503                 }
2504                 
2505                 newbone= ED_armature_edit_bone_add(arm, ebone->name);
2506                 arm->act_edbone= newbone;
2507                 
2508                 if (to_root) {
2509                         copy_v3_v3(newbone->head, ebone->head);
2510                         newbone->rad_head= ebone->rad_tail;
2511                         newbone->parent= ebone->parent;
2512                 }
2513                 else {
2514                         copy_v3_v3(newbone->head, ebone->tail);
2515                         newbone->rad_head= ebone->rad_tail;
2516                         newbone->parent= ebone;
2517                         newbone->flag |= BONE_CONNECTED;
2518                 }
2519                 
2520                 curs= give_cursor(scene, v3d);
2521                 copy_v3_v3(newbone->tail, curs);
2522                 sub_v3_v3v3(newbone->tail, newbone->tail, obedit->obmat[3]);
2523                 
2524                 if (a==1) 
2525                         newbone->tail[0]= -newbone->tail[0];
2526                 
2527                 copy_m3_m4(mat, obedit->obmat);
2528                 invert_m3_m3(imat, mat);
2529                 mul_m3_v3(imat, newbone->tail);
2530                 
2531                 newbone->length= len_v3v3(newbone->head, newbone->tail);
2532                 newbone->rad_tail= newbone->length*0.05f;
2533                 newbone->dist= newbone->length*0.25f;
2534                 
2535         }
2536         
2537         ED_armature_sync_selection(arm->edbo);
2538
2539         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
2540         
2541         return OPERATOR_FINISHED;
2542 }
2543
2544 static int armature_click_extrude_invoke(bContext *C, wmOperator *op, wmEvent *event)
2545 {
2546         /* TODO most of this code is copied from set3dcursor_invoke,
2547            it would be better to reuse code in set3dcursor_invoke */
2548
2549         /* temporarily change 3d cursor position */
2550         Scene *scene;
2551         ARegion *ar;
2552         View3D *v3d;
2553         RegionView3D *rv3d;
2554         float dx, dy, fz, *fp = NULL, dvec[3], oldcurs[3];
2555         short mx, my, mval[2];
2556         int retv;
2557
2558         scene= CTX_data_scene(C);
2559         ar= CTX_wm_region(C);
2560         v3d = CTX_wm_view3d(C);
2561         rv3d= CTX_wm_region_view3d(C);
2562         
2563         fp= give_cursor(scene, v3d);
2564         
2565         copy_v3_v3(oldcurs, fp);
2566         
2567         mx= event->x - ar->winrct.xmin;
2568         my= event->y - ar->winrct.ymin;
2569         project_short_noclip(ar, fp, mval);
2570         
2571         initgrabz(rv3d, fp[0], fp[1], fp[2]);
2572         
2573         if(mval[0]!=IS_CLIPPED) {
2574                 
2575                 window_to_3d_delta(ar, dvec, mval[0]-mx, mval[1]-my);
2576                 sub_v3_v3v3(fp, fp, dvec);
2577         }
2578         else {
2579                 
2580                 dx= ((float)(mx-(ar->winx/2)))*rv3d->zfac/(ar->winx/2);
2581                 dy= ((float)(my-(ar->winy/2)))*rv3d->zfac/(ar->winy/2);
2582                 
2583                 fz= rv3d->persmat[0][3]*fp[0]+ rv3d->persmat[1][3]*fp[1]+ rv3d->persmat[2][3]*fp[2]+ rv3d->persmat[3][3];
2584                 fz= fz/rv3d->zfac;
2585                 
2586                 fp[0]= (rv3d->persinv[0][0]*dx + rv3d->persinv[1][0]*dy+ rv3d->persinv[2][0]*fz)-rv3d->ofs[0];
2587                 fp[1]= (rv3d->persinv[0][1]*dx + rv3d->persinv[1][1]*dy+ rv3d->persinv[2][1]*fz)-rv3d->ofs[1];
2588                 fp[2]= (rv3d->persinv[0][2]*dx + rv3d->persinv[1][2]*dy+ rv3d->persinv[2][2]*fz)-rv3d->ofs[2];
2589         }
2590
2591         /* extrude to the where new cursor is and store the operation result */
2592         retv= armature_click_extrude_exec(C, op);
2593
2594         /* restore previous 3d cursor position */
2595         copy_v3_v3(fp, oldcurs);
2596
2597         return retv;
2598 }
2599
2600 void ARMATURE_OT_click_extrude(wmOperatorType *ot)
2601 {
2602         /* identifiers */
2603         ot->name= "Click-Extrude";
2604         ot->idname= "ARMATURE_OT_click_extrude";
2605         ot->description= "Create a new bone going from the last selected joint to the mouse position";
2606         
2607         /* api callbacks */
2608         ot->invoke = armature_click_extrude_invoke;
2609         ot->exec = armature_click_extrude_exec;
2610         ot->poll = ED_operator_editarmature;
2611         
2612         /* flags */
2613         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2614
2615         /* props */
2616 }
2617
2618 /* adds an EditBone between the nominated locations (should be in the right space) */
2619 static EditBone *add_points_bone (Object *obedit, float head[], float tail[]) 
2620 {
2621         EditBone *ebo;
2622         
2623         ebo= ED_armature_edit_bone_add(obedit->data, "Bone");
2624         
2625         copy_v3_v3(ebo->head, head);
2626         copy_v3_v3(ebo->tail, tail);
2627         
2628         return ebo;
2629 }
2630
2631
2632 static EditBone *get_named_editbone(ListBase *edbo, char *name)
2633 {
2634         EditBone  *eBone;
2635
2636         if (name) {
2637                 for (eBone=edbo->first; eBone; eBone=eBone->next) {
2638                         if (!strcmp(name, eBone->name))
2639                                 return eBone;
2640                 }
2641         }
2642
2643         return NULL;
2644 }
2645
2646 /* Call this before doing any duplications
2647  * */
2648 void preEditBoneDuplicate(ListBase *editbones)
2649 {
2650         EditBone *eBone;
2651         
2652         /* clear temp */
2653         for (eBone = editbones->first; eBone; eBone = eBone->next)
2654         {
2655                 eBone->temp = NULL;
2656         }
2657 }
2658
2659 /*
2660  * Note: When duplicating cross objects, editbones here is the list of bones
2661  * from the SOURCE object but ob is the DESTINATION object
2662  * */
2663 void updateDuplicateSubtargetObjects(EditBone *dupBone, ListBase *editbones, Object *src_ob, Object *dst_ob)
2664 {
2665         /* If an edit bone has been duplicated, lets
2666          * update it's constraints if the subtarget
2667          * they point to has also been duplicated
2668          */
2669         EditBone     *oldtarget, *newtarget;
2670         bPoseChannel *pchan;
2671         bConstraint  *curcon;
2672         ListBase     *conlist;
2673         
2674         if ( (pchan = verify_pose_channel(dst_ob->pose, dupBone->name)) ) {
2675                 if ( (conlist = &pchan->constraints) ) {
2676                         for (curcon = conlist->first; curcon; curcon=curcon->next) {
2677                                 /* does this constraint have a subtarget in
2678                                  * this armature?
2679                                  */
2680                                 bConstraintTypeInfo *cti= constraint_get_typeinfo(curcon);
2681                                 ListBase targets = {NULL, NULL};
2682                                 bConstraintTarget *ct;
2683                                 
2684                                 if (cti && cti->get_constraint_targets) {
2685                                         cti->get_constraint_targets(curcon, &targets);
2686                                         
2687                                         for (ct= targets.first; ct; ct= ct->next) {
2688                                                 if ((ct->tar == src_ob) && (ct->subtarget[0])) {
2689                                                         ct->tar = dst_ob; /* update target */ 
2690                                                         oldtarget = get_named_editbone(editbones, ct->subtarget);
2691                                                         if (oldtarget) {
2692                                                                 /* was the subtarget bone duplicated too? If
2693                                                                  * so, update the constraint to point at the 
2694                                                                  * duplicate of the old subtarget.
2695                                                                  */
2696                                                                 if (oldtarget->temp) {
2697                                                                         newtarget = (EditBone *) oldtarget->temp;
2698                                                                         strcpy(ct->subtarget, newtarget->name);
2699                                                                 }
2700                                                         }
2701                                                 }
2702                                         }
2703                                         
2704                                         if (cti->flush_constraint_targets)
2705                                                 cti->flush_constraint_targets(curcon, &targets, 0);
2706                                 }
2707                         }
2708                 }
2709         }
2710 }
2711
2712 void updateDuplicateSubtarget(EditBone *dupBone, ListBase *editbones, Object *ob)
2713 {
2714         updateDuplicateSubtargetObjects(dupBone, editbones, ob, ob);
2715 }
2716
2717
2718 EditBone *duplicateEditBoneObjects(EditBone *curBone, char *name, ListBase *editbones, Object *src_ob, Object *dst_ob)
2719 {
2720         EditBone *eBone = MEM_mallocN(sizeof(EditBone), "addup_editbone");
2721         
2722         /*      Copy data from old bone to new bone */
2723         memcpy(eBone, curBone, sizeof(EditBone));
2724         
2725         curBone->temp = eBone;
2726         eBone->temp = curBone;
2727         
2728         if (name != NULL)
2729         {
2730                 BLI_strncpy(eBone->name, name, sizeof(eBone->name));
2731         }
2732
2733         unique_editbone_name(editbones, eBone->name, NULL);
2734         BLI_addtail(editbones, eBone);
2735         
2736         /* copy the ID property */
2737         if(curBone->prop)
2738                 eBone->prop= IDP_CopyProperty(curBone->prop);
2739
2740         /* Lets duplicate the list of constraints that the
2741          * current bone has.
2742          */
2743         if (src_ob->pose) {
2744                 bPoseChannel *chanold, *channew;
2745                 
2746                 chanold = verify_pose_channel(src_ob->pose, curBone->name);
2747                 if (chanold) {
2748                         /* WARNING: this creates a new posechannel, but there will not be an attached bone
2749                          *              yet as the new bones created here are still 'EditBones' not 'Bones'.
2750                          */
2751                         channew= verify_pose_channel(dst_ob->pose, eBone->name);
2752
2753                         if(channew) {
2754                                 duplicate_pose_channel_data(channew, chanold);
2755                         }
2756                 }
2757         }
2758         
2759         return eBone;
2760 }
2761
2762 EditBone *duplicateEditBone(EditBone *curBone, char *name, ListBase *editbones, Object *ob)
2763 {
2764         return duplicateEditBoneObjects(curBone, name, editbones, ob, ob);
2765 }
2766
2767 /* previously adduplicate_armature */
2768 static int armature_duplicate_selected_exec(bContext *C, wmOperator *UNUSED(op))
2769 {
2770         bArmature *arm;
2771         EditBone        *eBone = NULL;
2772         EditBone        *curBone;
2773         EditBone        *firstDup=NULL; /*      The beginning of the duplicated bones in the edbo list */
2774
2775         Object *obedit= CTX_data_edit_object(C);
2776         arm= obedit->data;
2777
2778         /* cancel if nothing selected */
2779         if (CTX_DATA_COUNT(C, selected_bones) == 0)
2780           return OPERATOR_CANCELLED;
2781         
2782         ED_armature_sync_selection(arm->edbo); // XXX why is this needed?
2783
2784         preEditBoneDuplicate(arm->edbo);
2785
2786         /* Select mirrored bones */
2787         if (arm->flag & ARM_MIRROR_EDIT) {
2788                 for (curBone=arm->edbo->first; curBone; curBone=curBone->next) {
2789                         if (EBONE_VISIBLE(arm, curBone)) {
2790                                 if (curBone->flag & BONE_SELECTED) {
2791                                         eBone = ED_armature_bone_get_mirrored(arm->edbo, curBone);
2792                                         if (eBone)
2793                                                 eBone->flag |= BONE_SELECTED;
2794                                 }
2795                         }
2796                 }
2797         }
2798
2799         
2800         /*      Find the selected bones and duplicate them as needed */
2801         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2802                 if (EBONE_VISIBLE(arm, curBone)) {
2803                         if (curBone->flag & BONE_SELECTED) {
2804                                 
2805                                 eBone= duplicateEditBone(curBone, curBone->name, arm->edbo, obedit);
2806                                 
2807                                 if (!firstDup)
2808                                         firstDup=eBone;
2809
2810                         }
2811                 }
2812         }
2813
2814         /*      Run though the list and fix the pointers */
2815         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2816                 if (EBONE_VISIBLE(arm, curBone)) {
2817                         if (curBone->flag & BONE_SELECTED) {
2818                                 eBone=(EditBone*) curBone->temp;
2819                                 
2820                                 if (!curBone->parent) {
2821                                         /* If this bone has no parent,
2822                                          * Set the duplicate->parent to NULL
2823                                          */
2824                                         eBone->parent = NULL;
2825                                 }
2826                                 else if (curBone->parent->temp) {
2827                                         /* If this bone has a parent that was duplicated,
2828                                          * Set the duplicate->parent to the curBone->parent->temp
2829                                          */
2830                                         eBone->parent= (EditBone *)curBone->parent->temp;
2831                                 }
2832                                 else {
2833                                         /* If this bone has a parent that IS not selected,
2834                                          * Set the duplicate->parent to the curBone->parent
2835                                          */
2836                                         eBone->parent=(EditBone*) curBone->parent; 
2837                                         eBone->flag &= ~BONE_CONNECTED;
2838                                 }
2839                                 
2840                                 /* Lets try to fix any constraint subtargets that might
2841                                  * have been duplicated 
2842                                  */
2843                                 updateDuplicateSubtarget(eBone, arm->edbo, obedit);
2844                         }
2845                 }
2846         } 
2847         
2848         /* correct the active bone */
2849         if(arm->act_edbone) {
2850                 eBone= arm->act_edbone;
2851                 if(eBone->temp)
2852                         arm->act_edbone= eBone->temp;
2853         }
2854
2855         /*      Deselect the old bones and select the new ones */
2856         for (curBone=arm->edbo->first; curBone && curBone!=firstDup; curBone=curBone->next) {
2857                 if (EBONE_VISIBLE(arm, curBone))
2858                         curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
2859         }
2860
2861         ED_armature_validate_active(arm);
2862
2863         WM_event_add_notifier(C, NC_OBJECT|ND_BONE_SELECT, obedit);
2864         
2865         return OPERATOR_FINISHED;
2866 }
2867
2868
2869 void ARMATURE_OT_duplicate(wmOperatorType *ot)
2870 {
2871         /* identifiers */
2872         ot->name= "Duplicate Selected Bone(s)";
2873         ot->idname= "ARMATURE_OT_duplicate";
2874         ot->description= "Make copies of the selected bones within the same armature";
2875         
2876         /* api callbacks */
2877         ot->exec = armature_duplicate_selected_exec;
2878         ot->poll = ED_operator_editarmature;
2879         
2880         /* flags */
2881         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2882 }
2883
2884
2885 /* *************** END Adding stuff in editmode *************** */
2886 /* ************** Add/Remove stuff in editmode **************** */
2887
2888 /* temporary data-structure for merge/fill bones */
2889 typedef struct EditBonePoint {
2890         struct EditBonePoint *next, *prev;
2891         
2892         EditBone *head_owner;           /* EditBone which uses this point as a 'head' point */
2893         EditBone *tail_owner;           /* EditBone which uses this point as a 'tail' point */
2894         
2895         float vec[3];                           /* the actual location of the point in local/EditMode space */
2896 } EditBonePoint;
2897
2898 /* find chain-tips (i.e. bones without children) */
2899 static void chains_find_tips (ListBase *edbo, ListBase *list)
2900 {
2901         EditBone *curBone, *ebo;
2902         LinkData *ld;
2903         
2904         /* note: this is potentially very slow ... there's got to be a better way */
2905         for (curBone= edbo->first; curBone; curBone= curBone->next) {
2906                 short stop= 0;
2907                 
2908                 /* is this bone contained within any existing chain? (skip if so) */
2909                 for (ld= list->first; ld; ld= ld->next) {
2910                         for (ebo= ld->data; ebo; ebo= ebo->parent) {
2911                                 if (ebo == curBone) {
2912                                         stop= 1;
2913                                         break;
2914                                 }
2915                         }
2916                         
2917                         if (stop) break;
2918                 }
2919                 /* skip current bone if it is part of an existing chain */
2920                 if (stop) continue;
2921                 
2922            &