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