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