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