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