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