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