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