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