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