When a bone is renamed, all constraints that point to it are
[blender.git] / source / blender / src / editarmature.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL/BL DUAL 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. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): none yet.
29  *
30  * ***** END GPL/BL DUAL LICENSE BLOCK *****
31  * editarmature.c: Interface for creating and posing armature objects
32  */
33
34 #include <stdlib.h>
35 #include <string.h>
36 #include <math.h>
37
38 #ifdef HAVE_CONFIG_H
39 #include <config.h>
40 #endif
41
42 #ifdef WIN32
43 #include "BLI_winstuff.h"
44 #endif
45
46 #include "MEM_guardedalloc.h"
47
48 #include "BMF_Api.h"
49
50 #include "DNA_action_types.h"
51 #include "DNA_armature_types.h"
52 #include "DNA_mesh_types.h"
53 #include "DNA_object_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_screen_types.h"
56 #include "DNA_space_types.h"
57 #include "DNA_view3d_types.h"
58
59 #include "BLI_blenlib.h"
60 #include "BLI_arithb.h"
61 #include "BLI_editVert.h"
62
63 #include "BKE_utildefines.h"
64 #include "BKE_action.h"
65 #include "BKE_armature.h"
66 #include "BKE_constraint.h"
67 #include "BKE_global.h"
68 #include "BKE_object.h"
69 #include "BKE_subsurf.h"
70
71 #include "BIF_gl.h"
72 #include "BIF_graphics.h"
73 #include "BIF_interface.h"
74 #include "BIF_resources.h"
75 #include "BIF_screen.h"
76 #include "BIF_space.h"
77 #include "BIF_toolbox.h"
78 #include "BIF_editarmature.h"
79 #include "BIF_poseobject.h"
80 #include "BIF_mywindow.h"
81 #include "BIF_editdeform.h"
82
83 #include "BDR_editobject.h"
84 #include "BDR_drawobject.h"
85
86 #include "BSE_edit.h"
87 #include "BSE_view.h"
88 #include "BSE_trans_types.h"
89 #include "BSE_editaction.h"
90
91 #include "mydevice.h"
92 #include "blendef.h"
93 #include "nla.h"
94
95 /*  >>>>> FIXME: ARG!  Colours should be defined in a header somewhere! */
96 /*      Note, these came from drawobject.c  They really should be in a nice header file somewhere */
97 #define B_YELLOW        0x77FFFF
98 #define B_PURPLE        0xFF70FF
99
100 #define B_CYAN          0xFFFF00
101 #define B_AQUA          0xFFBB55 /* 0xFF8833*/
102
103 extern  int tottrans;                                   /* Originally defined in editobject.c */
104 extern  struct TransOb *transmain;                              /* Originally defined in editobject.c */
105 extern  float centre[3], centroid[3];   /* Originally defined in editobject.c */
106
107 /*      Macros  */
108 #define TEST_EDITARMATURE {if(G.obedit==0) return; if( (G.vd->lay & G.obedit->lay)==0 ) return;}
109
110 /* Local Function Prototypes */
111 static void editbones_to_armature (ListBase *bones, Object *ob);
112
113 static void fix_bonelist_roll (ListBase *bonelist, ListBase *editbonelist);
114 static int      select_bonechildren_by_name (struct Bone *bone, char *name, int select);
115
116 static void draw_boneverti (float x, float y, float z, float size, int flag);
117 static void draw_bone (int armflag, int boneflag, unsigned int id, char *name, float length);
118 static void draw_bonechildren (struct Bone *bone, int flag, unsigned int *index);
119 static void add_bone_input (struct Object *ob);
120 static void make_boneList(struct ListBase* list, struct ListBase *bones, struct EditBone *parent);
121 static void make_bone_menu_children (struct Bone *bone, char *str, int *index);
122 static void delete_bone(struct EditBone* exBone);
123 static void clear_armature_children (struct Bone *bone, struct bPose *pose, char mode);
124
125 static int      count_bones (struct bArmature *arm, int flagmask, int allbones);
126
127 static int      count_bonechildren (struct Bone *bone, int incount, int flagmask, int allbones);
128 static int      add_trans_bonechildren (struct Object* ob, struct Bone* bone, struct TransOb* buffer, int index, char mode);
129 static void deselect_bonechildren (struct Bone *bone, int mode);
130 static void selectconnected_posebonechildren (struct Bone *bone);
131
132 static int      editbone_name_exists (char* name);
133
134 static void *get_nearest_bone (int findunsel);
135 static EditBone * get_nearest_editbonepoint (int findunsel, int *selmask);
136
137 static Bone *get_first_selected_bonechildren (Bone *bone);
138
139
140 /* Functions */
141
142
143
144 void apply_rot_armature (Object *ob, float mat[3][3]){
145         ListBase        list;
146         EditBone *ebone;
147         bArmature *arm;
148
149         arm = get_armature(ob);
150
151         if (!arm)
152                 return;
153
154         /* Put the armature into editmode */
155         list.first= list.last = NULL;
156         make_boneList(&list, &arm->bonebase, NULL);
157
158         /* Do the rotations */
159         for (ebone = list.first; ebone; ebone=ebone->next){
160         
161                 {
162
163                         /* Fixme: This is essentially duplicated from join_armature */
164
165                         float premat[4][4];
166                         float postmat[4][4];
167                         float difmat[4][4];
168                         float imat[4][4];
169                         float temp[4][4];
170                         float delta[3];
171                         float rmat[4][4];
172                         
173                         Mat4CpyMat3 (rmat, mat);
174                         /* Get the premat */
175                         VecSubf (delta, ebone->tail, ebone->head);
176                         make_boneMatrixvr(temp, delta, ebone->roll);
177                         Mat4MulMat4 (premat, temp, rmat);
178                         
179                         Mat4MulVecfl(rmat, ebone->head);
180                         Mat4MulVecfl(rmat, ebone->tail);
181                         
182                         /* Get the postmat */
183                         VecSubf (delta, ebone->tail, ebone->head);
184                         make_boneMatrixvr(postmat, delta, ebone->roll);
185                         
186                         /* Find the roll */
187                         Mat4Invert (imat, premat);
188                         Mat4MulMat4 (difmat, postmat, imat);
189                         
190 #if 0
191                         printmatrix4 ("Difmat", difmat);
192 #endif
193                         ebone->roll -=atan(difmat[2][0]/difmat[2][2]);
194                         
195                         if (difmat[0][0]<0)
196                                 ebone->roll +=M_PI;
197                         
198                 }
199
200                 
201         }
202         
203         /* Turn the list into an armature */
204         editbones_to_armature(&list, ob);
205         
206         /* Free the editbones */
207         if (list.first){
208                 BLI_freelistN (&list);
209         }
210
211 }
212
213
214
215 static Bone *get_first_selected_bonechildren (Bone *bone)
216 {
217         Bone *curbone, *result;
218
219         if (bone->flag & BONE_SELECTED)
220                 return bone;
221
222         for (curbone = bone->childbase.first; curbone; curbone=curbone->next){
223                 result = get_first_selected_bonechildren(curbone);
224                 if (result)
225                         return result;
226         };
227
228         return NULL;
229 }
230
231 Bone *get_first_selected_bone (void)
232 {
233         Bone *curbone, *result;
234         bArmature *arm;
235
236         arm = get_armature(OBACT);
237         if (!arm)
238                 return NULL;
239
240         for (curbone = arm->bonebase.first; curbone; curbone=curbone->next){
241                 result = get_first_selected_bonechildren(curbone);
242                 if (result)
243                         return result;
244         }
245
246         return NULL;
247 }
248
249 void clever_numbuts_posearmature (void)
250 {
251         /* heh -- 'clever numbuts'! */
252         bArmature *arm;
253         Bone *bone;
254         bPoseChannel *chan;
255
256         arm = get_armature(OBACT);
257         if (!arm)
258                 return;
259
260         bone = get_first_selected_bone();
261
262         if (!bone)
263                 return;
264
265         add_numbut(0, NUM|FLO, "Loc X:", -G.vd->far, G.vd->far, bone->loc, 0);
266         add_numbut(1, NUM|FLO, "Loc Y:", -G.vd->far, G.vd->far, bone->loc+1, 0);
267         add_numbut(2, NUM|FLO, "Loc Z:", -G.vd->far, G.vd->far, bone->loc+2, 0);
268
269         add_numbut(3, NUM|FLO, "Quat X:", -G.vd->far, G.vd->far, bone->quat, 0);
270         add_numbut(4, NUM|FLO, "Quat Y:", -G.vd->far, G.vd->far, bone->quat+1, 0);
271         add_numbut(5, NUM|FLO, "Quat Z:", -G.vd->far, G.vd->far, bone->quat+2, 0);
272         add_numbut(6, NUM|FLO, "Quat W:", -G.vd->far, G.vd->far, bone->quat+3, 0);
273
274         add_numbut(7, NUM|FLO, "Size X:", -G.vd->far, G.vd->far, bone->size, 0);
275         add_numbut(8, NUM|FLO, "Size Y:", -G.vd->far, G.vd->far, bone->size+1, 0);
276         add_numbut(9, NUM|FLO, "Size Z:", -G.vd->far, G.vd->far, bone->size+2, 0);
277
278         do_clever_numbuts("Active Bone", 10, REDRAW);
279
280         /* This is similar to code in special_trans_update */
281         
282         if (!G.obpose->pose) G.obpose->pose= MEM_callocN(sizeof(bPose), "pose");
283         chan = MEM_callocN (sizeof (bPoseChannel), "transPoseChannel");
284
285         chan->flag |= POSE_LOC|POSE_ROT|POSE_SIZE;
286         memcpy (chan->loc, bone->loc, sizeof (chan->loc));
287         memcpy (chan->quat, bone->quat, sizeof (chan->quat));
288         memcpy (chan->size, bone->size, sizeof (chan->size));
289         strcpy (chan->name, bone->name);
290         
291         set_pose_channel (G.obpose->pose, chan);
292         
293 }
294
295 void clever_numbuts_armature (void)
296 {
297         EditBone *ebone, *child;
298         
299         ebone= G.edbo.first;
300
301         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
302                 if (ebone->flag & BONE_SELECTED)
303                         break;
304         }
305
306         if (!ebone)
307                 return;
308
309         add_numbut(0, NUM|FLO, "Root X:", -G.vd->far, G.vd->far, ebone->head, 0);
310         add_numbut(1, NUM|FLO, "Root Y:", -G.vd->far, G.vd->far, ebone->head+1, 0);
311         add_numbut(2, NUM|FLO, "Root Z:", -G.vd->far, G.vd->far, ebone->head+2, 0);
312
313         add_numbut(3, NUM|FLO, "Tip X:", -G.vd->far, G.vd->far, ebone->tail, 0);
314         add_numbut(4, NUM|FLO, "Tip Y:", -G.vd->far, G.vd->far, ebone->tail+1, 0);
315         add_numbut(5, NUM|FLO, "Tip Z:", -G.vd->far, G.vd->far, ebone->tail+2, 0);
316
317         /* Convert roll to degrees */
318         ebone->roll *= (180.0F/M_PI);
319         add_numbut(6, NUM|FLO, "Roll:", -G.vd->far, G.vd->far, &ebone->roll, 0);
320
321         do_clever_numbuts("Active Bone", 7, REDRAW);
322
323         /* Convert roll to radians */
324         ebone->roll /= (180.0F/M_PI);
325
326         //      Update our parent
327         if (ebone->parent && ebone->flag & BONE_IK_TOPARENT){
328                 VECCOPY (ebone->parent->tail, ebone->head);
329         }
330
331         //      Update our children if necessary
332         for (child = G.edbo.first; child; child=child->next){
333                 if (child->parent == ebone && child->flag & BONE_IK_TOPARENT){
334                         VECCOPY (child->head, ebone->tail);
335                 }
336         }
337 }
338
339 void select_bone_by_name (bArmature *arm, char *name, int select)
340 {
341         Bone *bone;
342
343         if (!arm)
344                 return;
345
346         for (bone=arm->bonebase.first; bone; bone=bone->next)
347                 if (select_bonechildren_by_name (bone, name, select))
348                         break;
349 }
350
351 static int select_bonechildren_by_name (Bone *bone, char *name, int select)
352 {
353         Bone *curBone;
354
355         if (!strcmp (bone->name, name)){
356                 if (select)
357                         bone->flag |= BONE_SELECTED;
358                 else
359                         bone->flag &= ~BONE_SELECTED;
360                 return 1;
361         }
362
363         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
364                 if (select_bonechildren_by_name (curBone, name, select))
365                         return 1;
366         }
367
368         return 0;
369 }
370 void selectconnected_armature(void)
371 {
372         EditBone *bone, *curBone, *next;
373
374         if (G.qual & LR_SHIFTKEY)
375                 bone= get_nearest_bone(0);
376         else
377                 bone= get_nearest_bone(1);
378
379         if (!bone)
380                 return;
381
382         /* Select parents */
383         for (curBone=bone; curBone; curBone=next){
384                 if (G.qual & LR_SHIFTKEY){
385                         curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
386                 }
387                 else{
388                         curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
389                 }
390
391                 if (curBone->flag & BONE_IK_TOPARENT)
392                         next=curBone->parent;
393                 else
394                         next=NULL;
395         }
396
397         /* Select children */
398         while (bone){
399                 for (curBone=G.edbo.first; curBone; curBone=next){
400                         next = curBone->next;
401                         if (curBone->parent == bone){
402                                 if (curBone->flag & BONE_IK_TOPARENT){
403                                         if (G.qual & LR_SHIFTKEY)
404                                                 curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
405                                         else
406                                                 curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
407                                         bone=curBone;
408                                         break;
409                                 }
410                                 else{ 
411                                         bone=NULL;
412                                         break;
413                                 }
414                         }
415                 }
416                 if (!curBone)
417                         bone=NULL;
418
419         }
420
421         countall();
422         allqueue (REDRAWVIEW3D, 0);
423
424 }
425
426 void selectconnected_posearmature(void)
427 {
428         Bone *bone, *curBone, *next;
429
430         if (G.qual & LR_SHIFTKEY)
431                 bone= get_nearest_bone(0);
432         else
433                 bone = get_nearest_bone(1);
434
435         if (!bone)
436                 return;
437
438         /* Select parents */
439         for (curBone=bone; curBone; curBone=next){
440                 select_actionchannel_by_name (G.obpose->action, curBone->name, !(G.qual & LR_SHIFTKEY));
441                 if (G.qual & LR_SHIFTKEY)
442                         curBone->flag &= ~BONE_SELECTED;
443                 else
444                         curBone->flag |= BONE_SELECTED;
445
446                 if (curBone->flag & BONE_IK_TOPARENT)
447                         next=curBone->parent;
448                 else
449                         next=NULL;
450         }
451
452         /* Select children */
453         for (curBone=bone->childbase.first; curBone; curBone=next){
454                 selectconnected_posebonechildren (curBone);
455         }
456         
457         countall();
458         allqueue (REDRAWVIEW3D, 0);
459         allqueue (REDRAWACTION, 0);
460 }
461
462 static void selectconnected_posebonechildren (Bone *bone)
463 {
464         Bone *curBone;
465
466         if (!(bone->flag & BONE_IK_TOPARENT))
467                 return;
468
469         select_actionchannel_by_name (G.obpose->action, bone->name, !(G.qual & LR_SHIFTKEY));
470
471         if (G.qual & LR_SHIFTKEY)
472                 bone->flag &= ~BONE_SELECTED;
473         else
474                 bone->flag |= BONE_SELECTED;
475
476         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
477                 selectconnected_posebonechildren (curBone);
478         }
479 }
480
481
482 char *make_bone_menu (bArmature *arm)
483 {
484         char *menustr=NULL;
485         Bone *curBone;
486         int             size;
487         int             index=0;
488         
489
490         //      Count the bones
491         size = (count_bones (arm, 0xFFFFFFFF, 1)*48) + 256;
492         menustr = MEM_callocN(size, "bonemenu");
493
494         sprintf (menustr, "Select Bone%%t");
495
496         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
497                 make_bone_menu_children (curBone, menustr, &index);
498         }
499
500         return menustr;
501 }
502
503 static void make_bone_menu_children (Bone *bone, char *str, int *index)
504 {
505         Bone *curBone;
506
507         sprintf (str, "%s|%s%%x%d", str, bone->name, *index);
508         (*index) ++;
509
510         for (curBone=bone->childbase.first; curBone; curBone=curBone->next)
511                 make_bone_menu_children (curBone, str, index);
512 }
513
514 void free_editArmature(void)
515 {
516
517         /*      Clear the editbones list */
518         if (G.edbo.first){
519                 BLI_freelistN (&G.edbo);
520         }
521 }
522
523 static EditBone * get_nearest_editbonepoint (int findunsel, int *selmask){
524         EditBone        *ebone;
525         unsigned int buffer[MAXPICKBUF];
526         short           hits;
527         int              i, takeNext=0;
528         int             sel;
529         unsigned int    hitresult, hitbone, firstunSel=-1;
530
531         persp(PERSP_VIEW);
532
533         glInitNames();
534         hits= selectprojektie(buffer, 0, 0, 0, 0);
535
536         /* See if there are any selected bones in this group */
537         if (hits){
538                 for (i=0; i< hits; i++){
539                         hitresult = buffer[3+(i*4)];
540                         if (!(hitresult&BONESEL_NOSEL)){
541
542                                 /* Determine which points are selected */
543                                 hitbone = hitresult & ~(BONESEL_ROOT|BONESEL_TIP);
544
545                                 /* Determine what the current bone is */
546                                 ebone = BLI_findlink(&G.edbo, hitbone);
547
548                                 /* See if it is selected */
549                                 sel = 0;
550                                 if ((hitresult & (BONESEL_TIP|BONESEL_ROOT)) == (BONESEL_TIP|BONESEL_ROOT))
551                                         sel = (ebone->flag & (BONE_TIPSEL| BONE_ROOTSEL)) == (BONE_TIPSEL|BONE_ROOTSEL) ? 1 : 0;
552                                 else if (hitresult & BONESEL_TIP)
553                                         sel |= ebone->flag & BONE_TIPSEL;
554                                 else if (hitresult & BONESEL_ROOT)
555                                         sel |= ebone->flag & BONE_ROOTSEL;
556                                 if (!findunsel)
557                                         sel = !sel;
558                         
559                                 if (sel)
560                                         takeNext=1;
561                                 else{
562                                         if (firstunSel == -1)
563                                                 firstunSel = hitresult;
564                                         if (takeNext){
565                                                 *selmask =0;
566                                                 if (hitresult & BONESEL_ROOT)
567                                                         *selmask |= BONE_ROOTSEL;
568                                                 if (hitresult & BONESEL_TIP)
569                                                         *selmask |= BONE_TIPSEL;
570                                                 return ebone;
571                                         }
572                                 }
573                         }
574                 }
575
576                 if (firstunSel != -1){
577                         *selmask = 0;
578                         if (firstunSel & BONESEL_ROOT)
579                                 *selmask |= BONE_ROOTSEL;
580                         if (firstunSel & BONESEL_TIP)
581                                 *selmask |= BONE_TIPSEL;
582                         return BLI_findlink(&G.edbo, firstunSel & ~(BONESEL_ROOT|BONESEL_TIP));
583                 }
584 #if 1
585                 else{
586                         *selmask = 0;
587                         if (buffer[3] & BONESEL_ROOT)
588                                 *selmask |= BONE_ROOTSEL;
589                         if (buffer[3] & BONESEL_TIP)
590                                 *selmask |= BONE_TIPSEL;
591 #if 1
592                         return BLI_findlink(&G.edbo, buffer[3] & ~(BONESEL_ROOT|BONESEL_TIP));
593 #else
594                         return NULL;
595 #endif
596                 }
597 #endif
598         }
599
600         *selmask = 0;
601         return NULL;
602 }
603
604 static void * get_nearest_bone (int findunsel){
605         void            *firstunSel=NULL, *data;
606         unsigned int buffer[MAXPICKBUF];
607         short           hits;
608         int              i, takeNext=0;
609         int             sel;
610         unsigned int    hitresult;
611         Bone *bone;
612         EditBone *ebone;
613
614         persp(PERSP_VIEW);
615
616         glInitNames();
617         hits= selectprojektie(buffer, 0, 0, 0, 0);
618
619
620         /* See if there are any selected bones in this group */
621         if (hits){
622                 for (i=0; i< hits; i++){
623                         hitresult = buffer[3+(i*4)];
624                         if (!(hitresult&BONESEL_NOSEL)){
625
626                                 /* Determine which points are selected */
627                                 hitresult &= ~(BONESEL_ROOT|BONESEL_TIP);
628
629                                 /* Determine what the current bone is */
630                                 if (!G.obedit){
631                                         bone = get_indexed_bone(OBACT->data, hitresult);
632                                         if (findunsel)
633                                                 sel = (bone->flag & BONE_SELECTED);
634                                         else
635                                                 sel = !(bone->flag & BONE_SELECTED);                                    
636                                         data = bone;
637                                 }
638                                 else{
639                                         ebone = BLI_findlink(&G.edbo, hitresult);
640                                         if (findunsel)
641                                                 sel = (ebone->flag & BONE_SELECTED);
642                                         else
643                                                 sel = !(ebone->flag & BONE_SELECTED);
644                                         
645                                         data = ebone;
646                                 }
647                                 
648                                 if (sel)
649                                         takeNext=1;
650                                 else{
651                                         if (!firstunSel)
652                                                 firstunSel=data;
653                                         if (takeNext)
654                                                 return data;
655                                 }
656                         }
657                 }
658
659                 if (firstunSel)
660                         return firstunSel;
661 #if 1
662                 else{
663 #if 1
664                         if (G.obedit)
665                                 return BLI_findlink(&G.edbo, buffer[3] & ~(BONESEL_ROOT|BONESEL_TIP));
666                         else
667                                 return get_indexed_bone(OBACT->data, buffer[3] & ~(BONESEL_ROOT|BONESEL_TIP));
668 #else
669                         return NULL;
670 #endif
671                 }
672 #endif
673         }
674
675         return NULL;
676 }
677
678 void delete_armature(void)
679 {
680         EditBone        *curBone, *next;
681         
682         TEST_EDITARMATURE;
683         if(okee("Erase selected")==0) return;
684         
685         for (curBone=G.edbo.first;curBone;curBone=next){
686                 next=curBone->next;
687                 if (curBone->flag&BONE_SELECTED)
688                         delete_bone(curBone);
689         }
690         
691         
692         allqueue(REDRAWVIEW3D, 0);
693         allqueue(REDRAWBUTSEDIT, 0);
694         allqueue(REDRAWBUTSOBJECT, 0);
695         countall();
696 }
697
698
699 static void delete_bone(EditBone* exBone)
700 {
701         EditBone        *curBone;
702         bPoseChannel *chan;
703         
704         /*      Find any bones that refer to this bone  */
705         for (curBone=G.edbo.first;curBone;curBone=curBone->next){
706                 if (curBone->parent==exBone){
707                         curBone->parent=exBone->parent;
708                         curBone->flag &= ~BONE_IK_TOPARENT;
709                 }
710         }
711         
712         /*  Erase any associated pose channel */
713         if (G.obedit->pose){
714                 for (chan=G.obedit->pose->chanbase.first; chan; chan=chan->next){
715                         if (!strcmp (chan->name, exBone->name)){
716                                 free_constraints(&chan->constraints);
717                                 BLI_freelinkN (&G.obedit->pose->chanbase, chan);
718                                 break;
719                         }
720                 }
721         }
722
723
724         allqueue(REDRAWBUTSOBJECT, 0);
725         allqueue(REDRAWBUTSEDIT, 0);
726
727         BLI_freelinkN (&G.edbo,exBone);
728 }
729
730 void remake_editArmature(void)
731 {
732         if(okee("Reload Original data")==0) return;
733         
734         make_editArmature();
735         allqueue(REDRAWVIEW3D, 0);
736         allqueue(REDRAWBUTSHEAD, 0);
737         allqueue(REDRAWBUTSOBJECT, 0);
738         allqueue(REDRAWBUTSEDIT, 0);
739 }
740
741 void mouse_armature(void)
742 {
743         EditBone*       nearBone = NULL;
744         int     selmask;
745
746         nearBone=get_nearest_editbonepoint(1, &selmask);
747
748         if (nearBone){
749                 if ((G.qual & LR_SHIFTKEY) && (nearBone->flag & selmask))
750                         nearBone->flag &= ~selmask;
751                 else
752                         nearBone->flag |= selmask;
753
754                 if (!(G.qual & LR_SHIFTKEY)){
755                         deselectall_armature();
756                         nearBone->flag |= selmask;
757                 }
758                 allqueue(REDRAWVIEW3D, 0);
759                 allqueue(REDRAWBUTSEDIT, 0);
760                 allqueue(REDRAWBUTSOBJECT, 0);
761         };
762         countall();
763         rightmouse_transform();
764 }
765
766 void make_editArmature(void)
767 {
768         bArmature       *arm;
769         
770         if (G.obedit==0)
771                 return;
772         
773         free_editArmature();
774         
775         arm= get_armature(G.obedit);
776         if (!arm)
777                 return;
778         
779         make_boneList (&G.edbo, &arm->bonebase,NULL);
780 }
781
782 static void editbones_to_armature (ListBase *list, Object *ob)
783 {
784         bArmature *arm;
785         EditBone *eBone;
786         Bone    *newBone;
787
788         arm = get_armature(ob);
789         if (!list)
790                 return;
791         if (!arm)
792                 return;
793
794         free_bones(arm);
795         
796
797         /*      Copy the bones from the editData into the armature*/
798         for (eBone=list->first;eBone;eBone=eBone->next){
799                 newBone=MEM_callocN (sizeof(Bone), "bone");
800                 eBone->temp= newBone;   /* Associate the real Bones with the EditBones */
801                 
802                 strcpy (newBone->name, eBone->name);
803                 memcpy (newBone->head, eBone->head, sizeof(float)*3);
804                 memcpy (newBone->tail, eBone->tail, sizeof(float)*3);
805                 newBone->flag=eBone->flag &~(BONE_SELECTED|BONE_HILIGHTED);
806 //              newBone->roll=eBone->roll;
807                 newBone->roll = 0.0F;
808
809                 /*      >>>>> FIXME: This isn't a very good system: a lot of
810                                         pointless copying involved.  To be investigated
811                                         once things are working better.
812                 */
813
814                 newBone->weight = eBone->weight;
815                 newBone->dist = eBone->dist;
816                 newBone->boneclass = eBone->boneclass;
817
818                 memcpy (newBone->loc, eBone->loc, sizeof(eBone->loc));
819                 memcpy (newBone->dloc, eBone->dloc, sizeof(eBone->dloc));
820 /*              memcpy (newBone->orig, eBone->orig, sizeof(eBone->orig));*/
821                 memcpy (newBone->size, eBone->size, sizeof(eBone->size));
822                 memcpy (newBone->dsize, eBone->dsize, sizeof(eBone->dsize));
823                 memcpy (newBone->quat, eBone->quat, sizeof(eBone->quat));
824                 memcpy (newBone->dquat, eBone->dquat, sizeof(eBone->dquat));
825                 memcpy (newBone->obmat, eBone->obmat, sizeof(eBone->obmat));
826         }
827
828         /*      Fix parenting in a separate pass to ensure ebone->bone connections
829                 are valid at this point */
830         for (eBone=list->first;eBone;eBone=eBone->next){
831                 newBone= (Bone*) eBone->temp;
832                 if (eBone->parent){
833                         newBone->parent=(Bone*) eBone->parent->temp;
834                         BLI_addtail (&newBone->parent->childbase,newBone);
835
836                         {
837                                 float M_boneRest[4][4];
838                                 float M_parentRest[4][4];
839                                 float iM_parentRest[4][4];
840                                 float   delta[3];
841                         
842                                 /* Get the parent's global matrix (rotation only)*/
843                                 VecSubf (delta, eBone->parent->tail, eBone->parent->head);
844                                 make_boneMatrixvr(M_parentRest, delta, eBone->parent->roll);
845
846                                 /* Get this bone's global matrix (rotation only)*/
847                                 VecSubf (delta, eBone->tail, eBone->head);
848                                 make_boneMatrixvr(M_boneRest, delta, eBone->roll);
849
850                                 /* Invert the parent matrix */
851                                 Mat4Invert (iM_parentRest, M_parentRest);
852
853                                 /* Get the new head and tail */
854                                 VecSubf (newBone->head, eBone->head, eBone->parent->tail);
855                                 VecSubf (newBone->tail, eBone->tail, eBone->parent->tail);
856
857                                 Mat4MulVecfl(iM_parentRest, newBone->head);
858                                 Mat4MulVecfl(iM_parentRest, newBone->tail);
859         
860
861                         }
862
863                 }
864                 /*      ...otherwise add this bone to the armature's bonebase */
865                 else
866                         BLI_addtail (&arm->bonebase,newBone);
867         }
868
869         /* Make a pass through the new armature to fix rolling */
870         fix_bonelist_roll (&arm->bonebase, list);
871         /* Get rid of pose channels that may have belonged to deleted bones */
872         collect_pose_garbage(ob);
873         /* Ensure all bones have channels */
874         apply_pose_armature(arm, ob->pose, 0);
875
876         /* Calculate and cache the inverse restposition matrices (needed for deformation)*/
877         precalc_bonelist_irestmats(&arm->bonebase);
878 }
879
880
881 void load_editArmature(void)
882 {
883         bArmature               *arm;
884
885         arm=get_armature(G.obedit);
886         if (!arm)
887                 return;
888         
889 #if 1
890         editbones_to_armature(&G.edbo, G.obedit);
891 #else
892         free_bones(arm);
893         
894
895         /*      Copy the bones from the editData into the armature*/
896         for (eBone=G.edbo.first;eBone;eBone=eBone->next){
897                 newBone=MEM_callocN (sizeof(Bone), "bone");
898                 eBone->temp= newBone;   /* Associate the real Bones with the EditBones */
899                 
900                 strcpy (newBone->name, eBone->name);
901                 memcpy (newBone->head, eBone->head, sizeof(float)*3);
902                 memcpy (newBone->tail, eBone->tail, sizeof(float)*3);
903                 newBone->flag=eBone->flag &~(BONE_SELECTED|BONE_HILIGHTED);
904         //      newBone->roll=eBone->roll;
905                 newBone->roll = 0.0F;
906
907                 /*      >>>>> FIXME: This isn't a very good system: a lot of
908                                         pointless copying involved.  To be investigated
909                                         once things are working better.
910                 */
911
912                 newBone->weight = eBone->weight;
913                 newBone->dist = eBone->dist;
914                 newBone->boneclass = eBone->boneclass;
915
916                 memcpy (newBone->loc, eBone->loc, sizeof(eBone->loc));
917                 memcpy (newBone->dloc, eBone->dloc, sizeof(eBone->dloc));
918 /*              memcpy (newBone->orig, eBone->orig, sizeof(eBone->orig));*/
919                 memcpy (newBone->size, eBone->size, sizeof(eBone->size));
920                 memcpy (newBone->dsize, eBone->dsize, sizeof(eBone->dsize));
921                 memcpy (newBone->quat, eBone->quat, sizeof(eBone->quat));
922                 memcpy (newBone->dquat, eBone->dquat, sizeof(eBone->dquat));
923                 memcpy (newBone->obmat, eBone->obmat, sizeof(eBone->obmat));
924         }
925
926         /*      Fix parenting in a separate pass to ensure ebone->bone connections
927                 are valid at this point */
928         for (eBone=G.edbo.first;eBone;eBone=eBone->next){
929                 newBone= (Bone*) eBone->temp;
930                 if (eBone->parent){
931                         newBone->parent=(Bone*) eBone->parent->temp;
932                         BLI_addtail (&newBone->parent->childbase,newBone);
933
934                         {
935                                 float M_boneRest[4][4];
936                                 float M_parentRest[4][4];
937                                 float M_relativeBone[4][4];
938                                 float iM_parentRest[4][4];
939                                 float   delta[3];
940                         
941                                 /* Get the parent's global matrix (rotation only)*/
942                                 VecSubf (delta, eBone->parent->tail, eBone->parent->head);
943                                 make_boneMatrixvr(M_parentRest, delta, eBone->parent->roll);
944
945                                 /* Get this bone's global matrix (rotation only)*/
946                                 VecSubf (delta, eBone->tail, eBone->head);
947                                 make_boneMatrixvr(M_boneRest, delta, eBone->roll);
948
949                                 /* Invert the parent matrix */
950                                 Mat4Invert (iM_parentRest, M_parentRest);
951
952                                 /* Get the new head and tail */
953                                 VecSubf (newBone->head, eBone->head, eBone->parent->tail);
954                                 VecSubf (newBone->tail, eBone->tail, eBone->parent->tail);
955
956                                 Mat4MulVecfl(iM_parentRest, newBone->head);
957                                 Mat4MulVecfl(iM_parentRest, newBone->tail);
958         
959
960                         }
961
962                 }
963                 /*      ...otherwise add this bone to the armature's bonebase */
964                 else
965                         BLI_addtail (&arm->bonebase,newBone);
966         }
967
968         /* Make a pass through the new armature to fix rolling */
969         fix_bonelist_roll (&arm->bonebase, &G.edbo);
970
971         /* Get rid of pose channels that may have belonged to deleted bones */
972         collect_pose_garbage(G.obedit);
973 #endif
974 }
975
976 static void fix_bonelist_roll (ListBase *bonelist, ListBase *editbonelist)
977 {
978         Bone *curBone;
979         EditBone *ebone;
980
981         for (curBone=bonelist->first; curBone; curBone=curBone->next){
982                 
983                 /* Fix this bone's roll */
984 #if 1
985                 {
986                         float premat[4][4];
987                         float postmat[4][4];
988                         float difmat[4][4];
989                         float imat[4][4];
990                         float delta[3];
991
992                         /* Find the associated editbone */
993                         for (ebone = editbonelist->first; ebone; ebone=ebone->next)
994                                 if ((Bone*)ebone->temp == curBone)
995                                         break;
996                         
997                                 if (ebone){
998                                         /* Get the premat */
999                                         VecSubf (delta, ebone->tail, ebone->head);
1000                                         make_boneMatrixvr(premat, delta, ebone->roll);
1001                                         
1002                                         /* Get the postmat */
1003                                         get_objectspace_bone_matrix(curBone, postmat, 1, 0);
1004                                         postmat[3][0]=postmat[3][1]=postmat[3][2]=0.0F;
1005 #if 1
1006                                         Mat4Invert (imat, premat);
1007                                         Mat4MulMat4 (difmat, postmat, imat);
1008 #else
1009                                         Mat4Invert (imat, postmat);
1010                                         Mat4MulMat4 (difmat, premat, imat);
1011 #endif
1012 #if 0
1013                                         printf ("Bone %s\n", curBone->name);
1014                                         printmatrix4 ("premat", premat);
1015                                         printmatrix4 ("postmat", postmat);
1016                                         printmatrix4 ("difmat", difmat);
1017                                         printf ("Roll = %f\n",  (-atan(difmat[2][0]/difmat[2][2]) * (180.0/M_PI)));
1018 #endif
1019                                         curBone->roll = -atan(difmat[2][0]/difmat[2][2]);
1020                                         
1021                                         if (difmat[0][0]<0)
1022                                                 curBone->roll +=M_PI;
1023                                         
1024                                 }
1025                 }
1026 #endif
1027                 
1028                 fix_bonelist_roll (&curBone->childbase, editbonelist);
1029         }
1030 }
1031
1032 void make_bone_parent(void)
1033 {
1034 /*      error ("Bone Parenting not yet implemented");   */
1035         return;
1036 }
1037
1038 static void make_boneList(ListBase* list, ListBase *bones, EditBone *parent)
1039 {
1040         EditBone        *eBone;
1041         Bone            *curBone;
1042         
1043         for (curBone=bones->first; curBone; curBone=curBone->next){
1044                 eBone=MEM_callocN(sizeof(EditBone),"make_editbone");
1045                 
1046                 /*      Copy relevant data from bone to eBone */
1047                 eBone->parent=parent;
1048                 strcpy (eBone->name, curBone->name);
1049                 eBone->flag = curBone->flag & ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1050
1051                 /* Print bone matrix before and after */
1052
1053                 get_bone_root_pos(curBone, eBone->head, 0);
1054                 get_bone_tip_pos(curBone, eBone->tail, 0);
1055 //              eBone->roll=curBone->roll;
1056                 eBone->roll=0;
1057
1058 #if 1
1059                 {
1060                         float delta[3];
1061                         float premat[4][4];
1062                         float postmat[4][4];
1063                         float imat[4][4];
1064                         float difmat[4][4];
1065
1066                         VecSubf (delta, eBone->tail, eBone->head);
1067                         make_boneMatrixvr(postmat, delta, eBone->roll);
1068
1069                         get_objectspace_bone_matrix(curBone, premat, 1, 0);
1070
1071 #if 0
1072                         Mat4Invert (imat, premat);
1073                         Mat4MulMat4 (difmat, postmat, imat);
1074 #else
1075                         Mat4Invert (imat, postmat);
1076                         Mat4MulMat4 (difmat, premat, imat);
1077 #endif
1078 #if 0
1079                         printf ("Bone %s\n", curBone->name);
1080                         printmatrix4 ("diffmat", difmat);
1081                         printf ("Roll : atan of %f / %f = %f\n", difmat[2][0], difmat[2][2], (float)atan(difmat[2][0]/difmat[2][2])*(180.0F/M_PI));
1082 #endif
1083                         eBone->roll = atan(difmat[2][0]/difmat[2][2]);
1084
1085                          if (difmat[0][0]<0)
1086                                 eBone->roll +=M_PI;
1087                 }
1088 #endif          
1089                 eBone->dist= curBone->dist;
1090                 eBone->weight= curBone->weight;
1091                 eBone->boneclass = curBone->boneclass;
1092                 memcpy (eBone->loc, curBone->loc, sizeof(curBone->loc));
1093                 memcpy (eBone->dloc, curBone->dloc, sizeof(curBone->dloc));
1094                 /*              memcpy (eBone->orig, curBone->orig, sizeof(curBone->orig));*/
1095                 memcpy (eBone->size, curBone->size, sizeof(curBone->size));
1096                 memcpy (eBone->dsize, curBone->dsize, sizeof(curBone->dsize));
1097                 memcpy (eBone->quat, curBone->quat, sizeof(curBone->quat));
1098                 memcpy (eBone->dquat, curBone->dquat, sizeof(curBone->dquat));
1099                 memcpy (eBone->obmat, curBone->obmat, sizeof(curBone->obmat));
1100                 
1101
1102                 BLI_addtail (list, eBone);
1103                 
1104                 /*      Add children if necessary */
1105                 if (curBone->childbase.first) 
1106                         make_boneList (list, &curBone->childbase, eBone);
1107         }
1108         
1109
1110 }
1111
1112 #if 0
1113 static EditVert*         add_armatureVert (float *loc)
1114 {
1115         EditVert*       vert=NULL;
1116
1117         vert = MEM_callocN (sizeof (EditVert), "armaturevert");
1118         if (vert){
1119                 VECCOPY (vert->co, loc);
1120                 BLI_addtail (&G.edve,vert);
1121         }
1122
1123         return vert;
1124
1125 }
1126
1127 static EditVert* get_armatureVert (float *loc)
1128 {
1129         EditVert*       vert;
1130
1131         for (vert=G.edve.first;vert;vert=vert->next){
1132                 if ((vert->co[0]==loc[0])&&(vert->co[1]==loc[1])&&(vert->co[2]==loc[2])){
1133                         return (vert);
1134                 }
1135         }
1136
1137         return add_armatureVert (loc);
1138 }
1139 #endif
1140
1141 void draw_armature(Object *ob)
1142 {
1143         bArmature       *arm;
1144         Bone            *bone;
1145         EditBone        *eBone;
1146         unsigned int    index;
1147         float           delta[3],offset[3];
1148         float           bmat[4][4];
1149         float   length;
1150         
1151         if (ob==NULL) return;
1152         
1153         arm= ob->data; 
1154         if (arm==NULL) return;
1155
1156         if (!(ob->lay & G.vd->lay))
1157                 return;
1158
1159         if (arm->flag & ARM_DRAWXRAY) {
1160                 if(G.zbuf) glDisable(GL_DEPTH_TEST);
1161         }
1162
1163         /* If we're in editmode, draw the Global edit data */
1164         if(ob==G.obedit || (G.obedit && ob->data==G.obedit->data)) {
1165                 cpack (0x000000);
1166                 
1167                 arm->flag |= ARM_EDITMODE;
1168                 for (eBone=G.edbo.first, index=0; eBone; eBone=eBone->next, index++){
1169                         if (ob==G.obedit){
1170         //                      if ((eBone->flag&(BONE_TIPSEL | BONE_ROOTSEL))==(BONE_TIPSEL|BONE_ROOTSEL))
1171         //                              cpack (B_YELLOW);
1172         //                      else
1173                                         cpack (B_PURPLE);
1174                         }
1175                         else cpack (0x000000);
1176                         
1177                         glPushMatrix();
1178                         
1179                         /*      Compose the parent transforms (i.e. their translations) */
1180                         VECCOPY (offset,eBone->head);
1181
1182                         glTranslatef (offset[0],offset[1],offset[2]);
1183                         
1184                         delta[0]=eBone->tail[0]-eBone->head[0]; 
1185                         delta[1]=eBone->tail[1]-eBone->head[1]; 
1186                         delta[2]=eBone->tail[2]-eBone->head[2];
1187                         
1188                         length = sqrt (delta[0]*delta[0] + delta[1]*delta[1] +delta[2]*delta[2]);
1189
1190                         make_boneMatrixvr(bmat, delta, eBone->roll);
1191                         glMultMatrixf (bmat);
1192                         draw_bone (arm->flag, eBone->flag, index, eBone->name, length);
1193
1194                         glPopMatrix();
1195                         if (eBone->parent){
1196                                 glLoadName (-1);
1197                                 setlinestyle(3);
1198                                 
1199                                 glBegin(GL_LINES);
1200                                 glVertex3fv(eBone->parent->tail);
1201                                 glVertex3fv(eBone->head);
1202                                 glEnd();
1203
1204                                 setlinestyle(0);
1205                         }
1206                 };
1207                 arm->flag &= ~ARM_EDITMODE;
1208                 cpack (B_YELLOW);
1209                 
1210         }
1211         else{
1212                 /*      Draw hierarchical bone list (non-edit data) */
1213
1214                 /* Ensure we're using the mose recent pose */
1215                 if (!ob->pose)
1216                         ob->pose=MEM_callocN (sizeof(bPose), "pose");
1217
1218 #if 1   /* Activate if there are problems with action lag */
1219                 apply_pose_armature(arm, ob->pose, 0);
1220                 where_is_armature (ob);
1221 #endif
1222
1223                 if (G.obpose == ob){
1224                         arm->flag |= ARM_POSEMODE;
1225 #if 0   /* Depreciated interactive ik goal drawing */
1226                         if (arm->chainbase.first){
1227                                 glPushMatrix();
1228                                 glTranslatef(((PoseChain*)arm->chainbase.first)->goal[0],
1229                                         ((PoseChain*)arm->chainbase.first)->goal[1],
1230                                         ((PoseChain*)arm->chainbase.first)->goal[2]);
1231                                 drawaxes(1.0);
1232                                 glPopMatrix();
1233                         }
1234 #endif
1235                 }
1236                 index = 0;
1237                 for (bone=arm->bonebase.first; bone; bone=bone->next) {
1238                         glPushMatrix();
1239                         draw_bonechildren(bone, arm->flag, &index);
1240                         glPopMatrix();
1241                         if (arm->flag & ARM_POSEMODE)
1242                                 cpack (B_CYAN);
1243                 }
1244
1245                 arm->flag &= ~ARM_POSEMODE; 
1246         }
1247
1248         if (arm->flag & ARM_DRAWXRAY) {
1249                 if(G.zbuf) glEnable(GL_DEPTH_TEST);
1250         }
1251 }
1252
1253 static void draw_boneverti (float x, float y, float z, float size, int flag)
1254 {
1255         GLUquadricObj   *qobj;
1256
1257         size*=0.05;
1258
1259 /*
1260                 Ultimately dots should be drawn in screenspace
1261                 For now we'll just draw them any old way.
1262 */
1263         glPushMatrix();
1264
1265         glTranslatef(x, y, z);
1266
1267         qobj    = gluNewQuadric(); 
1268         gluQuadricDrawStyle(qobj, GLU_SILHOUETTE); 
1269         gluPartialDisk( qobj, 0,  1.0F*size, 32, 1, 360.0, 360.0);
1270
1271         glRotatef (90, 0, 1, 0);
1272         gluPartialDisk( qobj, 0,  1.0F*size, 32, 1, 360.0, 360.0);
1273
1274         glRotatef (90, 1, 0, 0);
1275         gluPartialDisk( qobj, 0,  1.0F*size, 32, 1, 360.0, 360.0);
1276
1277         gluDeleteQuadric(qobj);  
1278
1279         glPopMatrix();
1280 }
1281
1282 static void draw_bonechildren (Bone *bone, int flag, unsigned int *index)
1283 {
1284         Bone *cbone;
1285         float   delta[3];
1286         float   length;
1287         float M_objectspacemat[4][4];
1288
1289         if (bone==NULL) return;
1290         
1291         if (flag & ARM_POSEMODE){
1292                 if (bone->flag & BONE_SELECTED)
1293                         cpack (B_CYAN);
1294                 else
1295                         cpack (B_AQUA);
1296         }
1297         
1298         //      Draw a line from our root to the parent's tip
1299         if (bone->parent && !(bone->flag & (BONE_IK_TOPARENT|BONE_HIDDEN)) ){
1300                 float childMat[4][4];
1301                 float boneMat[4][4];
1302                 float tip[3], root[3];
1303                 get_objectspace_bone_matrix(bone->parent, boneMat, 0, 1);
1304                 get_objectspace_bone_matrix(bone, childMat, 1, 1);
1305                 
1306                 VECCOPY (tip, boneMat[3]);
1307                 VECCOPY (root, childMat[3]);
1308                 
1309                 if (flag & ARM_POSEMODE)
1310                         glLoadName (-1);
1311                 setlinestyle(3);
1312                 glBegin(GL_LINES);
1313                 glVertex3fv(tip);
1314                 glVertex3fv(root);
1315                 glEnd();
1316                 setlinestyle(0);
1317         }
1318         
1319         
1320         /* Draw this bone in objectspace */
1321         delta[0]=bone->tail[0]-bone->head[0];
1322         delta[1]=bone->tail[1]-bone->head[1];
1323         delta[2]=bone->tail[2]-bone->head[2];
1324         length = sqrt (delta[0]*delta[0] + delta[1]*delta[1] + delta[2]*delta[2] );
1325         
1326         /* Incorporates offset, rest rotation, user rotation and parent coordinates*/
1327         get_objectspace_bone_matrix(bone, M_objectspacemat, 1, 1);
1328         
1329         if (!(bone->flag & BONE_HIDDEN)){
1330                 glPushMatrix();
1331                 glMultMatrixf(M_objectspacemat);
1332                 
1333                 
1334                 if (flag & ARM_POSEMODE)
1335                         draw_bone(flag, (bone->parent && bone->parent->flag & BONE_HIDDEN) ? (bone->flag & ~BONE_IK_TOPARENT) : (bone->flag), *index, bone->name, length);
1336                 else
1337                         draw_bone(flag, (bone->parent && bone->parent->flag & BONE_HIDDEN) ? (bone->flag & ~BONE_IK_TOPARENT) : (bone->flag), -1, bone->name, length);
1338                 glPopMatrix();
1339         }
1340         (*index)++;
1341
1342         /* Draw the children */
1343         for (cbone= bone->childbase.first; cbone; cbone=cbone->next){
1344                 draw_bonechildren (cbone, flag, index);
1345         }
1346 }
1347
1348 static void draw_bone (int armflag, int boneflag, unsigned int id, char *name, float length)
1349 {
1350         float vec[2];
1351         float   bulge;
1352         float   pointsize;
1353         /* 
1354         FIXME: This routine should probably draw the bones in screenspace using
1355         the projected start & end points of the transformed bone 
1356         */
1357         
1358         pointsize = length;
1359         if (pointsize<0.1)
1360                 pointsize=0.1;
1361
1362         /*      Draw a 3d octahedral bone       */
1363         
1364         bulge=length*0.1;
1365
1366         if (id!=-1)
1367                 glLoadName((GLuint) id );
1368
1369         glPushMatrix();
1370
1371         /*      Draw root point if we have no IK parent */
1372         if (!(boneflag & BONE_IK_TOPARENT)){
1373                 if (id != -1)
1374                         glLoadName (id | BONESEL_ROOT);
1375                 if (armflag & ARM_EDITMODE){
1376                         if (boneflag & BONE_ROOTSEL)
1377                                 cpack (B_YELLOW);
1378                         else
1379                                 cpack (B_PURPLE);
1380                 }
1381                 draw_boneverti (0, 0, 0, pointsize, 0);
1382         }
1383
1384         /*      Draw tip point (for selection only )*/
1385
1386         if (id != -1)
1387                 glLoadName (id | BONESEL_TIP);
1388         
1389         if (armflag & ARM_EDITMODE){
1390                 if (boneflag & BONE_TIPSEL)
1391                         cpack (B_YELLOW);
1392                 else
1393                         cpack (B_PURPLE);
1394         }
1395         
1396         draw_boneverti (0, length, 0, pointsize, 0);
1397
1398         if (id != -1){
1399                 if (armflag & ARM_POSEMODE)
1400                         glLoadName((GLuint) id);
1401                 else{
1402 #if 1   /* Bones not selectable in editmode */  
1403                         glLoadName((GLuint) -1);
1404 #else
1405                         glLoadName ((GLuint) id|BONESEL_TIP|BONESEL_ROOT);
1406 #endif
1407                 }
1408         }
1409         
1410         
1411         if (armflag & ARM_EDITMODE){
1412                 if (boneflag & BONE_SELECTED)
1413                         cpack (B_YELLOW);
1414                 else
1415                         cpack (B_PURPLE);
1416         }
1417         
1418         /*      Draw additional axes */
1419         if (armflag & ARM_DRAWAXES){
1420                 drawaxes(length*0.25F);
1421         }
1422         
1423         /*      Section 1*/
1424         glBegin(GL_LINE_STRIP);
1425         vec[0]= vec[1]= 0;
1426         glVertex2fv(vec);
1427         
1428         vec[0]= -bulge; vec[1]= bulge;
1429         glVertex2fv(vec);
1430         
1431         vec[0]= 0; vec[1]= length;
1432         glVertex2fv(vec);
1433         
1434         vec[0]= bulge; vec[1]= bulge;
1435         glVertex2fv(vec);
1436         
1437         vec[0]= 0; vec[1]= 0;
1438         glVertex2fv(vec);
1439         glEnd();
1440         
1441         /*      Section 2*/
1442         glRotatef(90,0,1,0);
1443         glBegin(GL_LINE_STRIP);
1444         vec[0]= vec[1]= 0;
1445         glVertex2fv(vec);
1446         
1447         vec[0]= -bulge; vec[1]= bulge;
1448         glVertex2fv(vec);
1449         
1450         vec[0]= 0; vec[1]= length;
1451         glVertex2fv(vec);
1452         
1453         vec[0]= bulge; vec[1]= bulge;
1454         glVertex2fv(vec);
1455         
1456         vec[0]= 0; vec[1]= 0;
1457         glVertex2fv(vec);
1458         glEnd();
1459         
1460         /*      Square*/
1461         glTranslatef (0,bulge,0);
1462         glRotatef(45,0,1,0);
1463         glRotatef(90,1,0,0);
1464         glBegin(GL_LINE_STRIP);
1465         
1466         vec[0]= -bulge*.707;vec[1]=-bulge*.707;
1467         glVertex2fv(vec);
1468         
1469         vec[0]= bulge*.707;vec[1]= -bulge*.707;
1470         glVertex2fv(vec);
1471         
1472         vec[0]= bulge*.707;vec[1]= bulge*.707;
1473         glVertex2fv(vec);
1474         
1475         vec[0]= -bulge*.707;vec[1]= bulge*.707;
1476         glVertex2fv(vec);
1477         
1478         vec[0]= vec[1]= -bulge*.707;
1479         glVertex2fv(vec);
1480         glEnd();
1481         
1482
1483         glPopMatrix();
1484
1485         /*      Draw the bone name */
1486         if (armflag & ARM_DRAWNAMES){
1487                 glRasterPos3f(0,  length/2.0,  0);
1488                 BMF_DrawString(G.font, " ");
1489                 BMF_DrawString(G.font, name);
1490         }
1491 }
1492
1493
1494
1495 void add_primitiveArmature(int type)
1496 {
1497         if(G.scene->id.lib) return;
1498         
1499         /* this function also comes from an info window */
1500         if ELEM(curarea->spacetype, SPACE_VIEW3D, SPACE_INFO); else return;
1501         if(G.vd==NULL) return;
1502         
1503         G.f &= ~(G_VERTEXPAINT+G_FACESELECT+G_TEXTUREPAINT+G_WEIGHTPAINT);
1504         setcursor_space(SPACE_VIEW3D, CURSOR_STD);
1505
1506         check_editmode(OB_ARMATURE);
1507         
1508         /* If we're not the "obedit", make a new object and enter editmode */
1509         if(G.obedit==NULL) {
1510                 add_object(OB_ARMATURE);
1511                 base_init_from_view3d(BASACT, G.vd);
1512                 G.obedit= BASACT->object;
1513                 
1514                 where_is_object(G.obedit);
1515                 
1516                 make_editArmature();
1517                 setcursor_space(SPACE_VIEW3D, CURSOR_EDIT);
1518         }
1519         
1520         switch (type){
1521         default:
1522                 add_bone_input (G.obedit);      
1523                 break;
1524         };
1525         
1526         countall();
1527
1528         allqueue(REDRAWALL, 0);
1529 }
1530
1531 static void add_bone_input (Object *ob)
1532 /*
1533         FUNCTION: 
1534         Creates a bone chain under user input.
1535         As the user clicks to accept each bone,
1536         a new bone is started as the child and IK
1537         child of the previous bone.  Pressing ESC
1538         cancels the current bone and leaves bone
1539         adding mode.
1540
1541 */
1542 {
1543         float           *cursLoc, cent[3], dx, dy;
1544         float           mat[3][3], curs[3],     cmat[3][3], imat[3][3], rmat[4][4], itmat[4][4];
1545         short           xo, yo, mval[2], afbreek=0;
1546         short           val;
1547         float           restmat[4][4], tempVec[4];
1548         EditBone        *bone;
1549         EditBone        *parent;
1550         unsigned short          event;
1551         float           angle, scale;
1552         float           length, lengths;
1553         float   newEnd[4];
1554         int                     addbones=1;
1555         float           dvec[3], dvecp[3];
1556         
1557         cursLoc= give_cursor();
1558         
1559         VECCOPY (curs,cursLoc);
1560         
1561         while (addbones>0){
1562                 afbreek=0;
1563                 /*      Create an inverse matrix */
1564                 Mat3CpyMat4(mat, G.obedit->obmat);
1565                 VECCOPY(cent, curs);
1566                 cent[0]-= G.obedit->obmat[3][0];
1567                 cent[1]-= G.obedit->obmat[3][1];
1568                 cent[2]-= G.obedit->obmat[3][2];
1569                 
1570                 Mat3CpyMat4(imat, G.vd->viewmat);
1571                 Mat3MulVecfl(imat, cent);
1572                 
1573                 Mat3MulMat3(cmat, imat, mat);
1574                 Mat3Inv(imat,cmat);
1575                 
1576                 /*      Create a temporary bone */
1577                 bone= MEM_callocN(sizeof(EditBone), "eBone");
1578                 
1579                 /*      If we're the child of something, set that up now */
1580                 if (addbones>1){
1581                         parent=G.edbo.last;
1582                         bone->parent=parent;
1583                         bone->flag|=BONE_IK_TOPARENT;
1584                 }
1585                 
1586                 strcpy (bone->name,"Bone");
1587                 unique_editbone_name (bone->name);
1588         
1589                 BLI_addtail(&G.edbo, bone);
1590         
1591                 bone->flag |= BONE_QUATROT;
1592                 bone->flag |= (BONE_SELECTED);
1593                 deselectall_armature();
1594                 bone->flag |= BONE_SELECTED|BONE_HILIGHTED|BONE_TIPSEL|BONE_ROOTSEL;
1595                 
1596                 bone->weight= 1.0F;
1597                 bone->dist= 1.0F;
1598                 bone->boneclass = BONE_SKINNABLE;
1599
1600                 /*      Project cursor center to screenspace. */
1601                 getmouseco_areawin(mval);
1602                 xo= mval[0];
1603                 yo= mval[1];
1604                 window_to_3d(dvecp, xo, yo);
1605
1606                 while (1) {
1607
1608                         getmouseco_areawin(mval);
1609                         window_to_3d(dvec, mval[0], mval[1]);
1610
1611                         scale=1000;
1612
1613                         dx=     ((float)mval[0]-(float)xo)*scale;
1614                         dy= ((float)mval[1]-(float)yo)*scale;
1615         
1616                         /*              Calc bone length*/
1617                         lengths= sqrt((dx*dx)+(dy*dy));
1618                         length = sqrt(((dvec[0]-dvecp[0])*(dvec[0]-dvecp[0]))+((dvec[1]-dvecp[1])*(dvec[1]-dvecp[1]))+((dvec[2]-dvecp[2])*(dvec[2]-dvecp[2])));
1619
1620                         /*              Find rotation around screen normal */
1621                         if (lengths>0.0F) {
1622                                 angle= acos(dy/lengths);
1623                                 if (dx<0.0F)
1624                                         angle*= -1.0F;
1625                         }
1626                         else angle= 0.0F;
1627                         
1628                         /*              FIXME:  Is there a blender-defined way of making rot and trans matrices? */
1629                         rmat[0][0]= cos (angle);
1630                         rmat[0][1]= -sin (angle);
1631                         rmat[0][2]= 0.0F;
1632                         rmat[0][3]= 0.0F;
1633                         rmat[1][0]= sin (angle);
1634                         rmat[1][1]= cos (angle);
1635                         rmat[1][2]= 0.0F;
1636                         rmat[1][3]= 0.0F;
1637                         rmat[2][0]= 0.0F;
1638                         rmat[2][1]= 0.0F;
1639                         rmat[2][2]= 1.0F;
1640                         rmat[2][3]= 0.0F;
1641                         rmat[3][0]= cent[0];
1642                         rmat[3][1]= cent[1];
1643                         rmat[3][2]= cent[2];
1644                         rmat[3][3]= 1.0F;
1645                         
1646                         /*              Rotate object's inversemat by the bone's rotation
1647                         to get the coordinate space of the bone */
1648                         Mat4CpyMat3     (itmat, imat);
1649                         Mat4MulMat4 (restmat, rmat, itmat);
1650                         
1651                         /*      Find the bone head */
1652                         tempVec[0]=0; tempVec[1]=0.0F; tempVec[2]=0.0F; tempVec[3]=1.0F;
1653                         Mat4MulVec4fl (restmat, tempVec);
1654                         VECCOPY (bone->head, tempVec);
1655                         
1656                         /*      Find the bone tail */
1657                         tempVec[0]=0; tempVec[1]=length; tempVec[2]=0.0F; tempVec[3]=1.0F;
1658                         Mat4MulVec4fl (restmat, tempVec);
1659                         VECCOPY (bone->tail, tempVec);
1660                         
1661                         /*      IF we're a child of something, add the parents' translates      */
1662                         
1663                         /*      Offset of child is new cursor*/
1664
1665                         VECCOPY (newEnd,bone->tail); newEnd[3]=1;
1666
1667                         /*      Set the bone's transformations  */
1668                         Mat4One (bone->obmat);
1669                         bone->size[0]=bone->size[1]=bone->size[2]=1.0F;
1670
1671                         force_draw();
1672                         while(qtest()) {
1673                                 event= extern_qread(&val);
1674                                 if(val) {
1675                                         switch(event) {
1676                                         case ESCKEY:
1677                                         case RIGHTMOUSE:
1678                                                 BLI_freelinkN (&G.edbo,bone);
1679                                                 afbreek=1;
1680                                                 addbones=0;
1681                                                 break;
1682                                         case LEFTMOUSE:
1683                                         case MIDDLEMOUSE:
1684                                         case SPACEKEY:
1685                                         case RETKEY:
1686                                                 afbreek= 1;
1687                                                                                         
1688                                                 Mat4MulVec4fl (G.obedit->obmat,newEnd);
1689                                                 
1690                                                 curs[0]=newEnd[0];
1691                                                 curs[1]=newEnd[1];
1692                                                 curs[2]=newEnd[2];
1693                                                 addbones++;
1694                                                 break;
1695                                         }       /*      End of case*/
1696                                 }       /*      End of if (val)*/
1697                                 if(afbreek) break;
1698                         }       /*      Endd of Qtest loop      */
1699
1700                 if(afbreek) break;
1701                 }/*     End of positioning loop (while)*/
1702         }       /*      End of bone adding loop*/
1703         
1704         countall();
1705
1706 }
1707
1708 void attach_bone_to_parent_cb(void *bonev, void *arg2_unused)
1709 {
1710         EditBone *curBone= bonev;
1711         attach_bone_to_parent(curBone);
1712 }
1713
1714 void attach_bone_to_parent(EditBone *bone)
1715 {
1716         EditBone *curbone;
1717
1718         if (bone->flag & BONE_IK_TOPARENT) {
1719
1720                 /* See if there are any other bones that refer to the same 
1721                  * parent and disconnect them 
1722                  */
1723                 for (curbone = G.edbo.first; curbone; curbone=curbone->next){
1724                         if (curbone!=bone){
1725                                 if (curbone->parent && 
1726                                         (curbone->parent == bone->parent) && 
1727                                         (curbone->flag & BONE_IK_TOPARENT))
1728                                         curbone->flag &= ~BONE_IK_TOPARENT;
1729                         }
1730                 }
1731
1732         /* Attach this bone to its parent */
1733                 VECCOPY(bone->head, bone->parent->tail);
1734         }
1735 }
1736
1737 void deselectall_armature(void)
1738 /*      Actually, it toggles selection, deselecting
1739         everything if anything is selected */
1740 {
1741         EditBone        *eBone;
1742         int                     sel=1;
1743         
1744         
1745         /*      Determine if there are any selected bones
1746                 And therefore whether we are selecting or deselecting */
1747         for (eBone=G.edbo.first;eBone;eBone=eBone->next){
1748                 if (eBone->flag & (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL)){
1749                         sel=0;
1750                         break;
1751                 };
1752         };
1753         
1754         /*      Set the flags */
1755         for (eBone=G.edbo.first;eBone;eBone=eBone->next){
1756                 if (sel)
1757                         eBone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1758                 else
1759                         eBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1760         };
1761         allqueue(REDRAWVIEW3D, 0);
1762         allqueue(REDRAWBUTSEDIT, 0);
1763         allqueue(REDRAWBUTSHEAD, 0);
1764         allqueue(REDRAWBUTSOBJECT, 0);
1765         countall();
1766 }
1767
1768 void join_armature(void)
1769 {
1770         
1771         Object  *ob;
1772         Base    *base, *nextbase;
1773         ListBase eblist;
1774         EditBone *curbone, *next;
1775         float   mat[4][4], imat[4][4];
1776         
1777         /*      Ensure we're not in editmode and that the active object is an armature*/
1778         if(G.obedit) return;
1779         
1780         ob= OBACT;
1781         if(ob->type!=OB_ARMATURE) return;
1782         
1783         /*      Make sure the user wants to continue*/
1784         if(okee("Join selected Armatures")==0) return;
1785         
1786         /*      Put the active armature into editmode and join the bones from the other one*/
1787 #if 1
1788         enter_editmode();
1789 #else
1790         baselist.first=baselist.last=0;
1791         make_boneList(&baselist, &((bArmature*)ob->data)->bonebase, NULL);
1792 #endif
1793         
1794         for (base=FIRSTBASE; base; base=nextbase) {
1795                 nextbase = base->next;
1796                 if (TESTBASE(base)){
1797                         if ((base->object->type==OB_ARMATURE) && (base->object!=ob)){
1798                                 /* Make a list of editbones */
1799                                 eblist.first=eblist.last=0;
1800                                 make_boneList (&eblist, &((bArmature*)base->object->data)->bonebase,NULL);
1801                                 /* Find the difference matrix */
1802                                 Mat4Invert(imat, ob->obmat);
1803                                 Mat4MulMat4(mat, base->object->obmat, imat);
1804                                 
1805                                 /* Copy bones from the object to the edit armature */
1806                                 for (curbone=eblist.first; curbone; curbone=next){
1807                                         next = curbone->next;
1808                                         
1809                                         /* Blank out tranformation data */
1810                                         curbone->loc[0]=curbone->loc[1]=curbone->loc[2]=0.0F;
1811                                         curbone->size[0]=curbone->size[1]=curbone->size[2]=1.0F;
1812                                         curbone->quat[0]=curbone->quat[1]=curbone->quat[2]=curbone->quat[3]=0.0F;
1813                                         
1814                                         unique_editbone_name (curbone->name);
1815                                         
1816                                         /* Transform the bone */
1817                                         {
1818                                                 float premat[4][4];
1819                                                 float postmat[4][4];
1820                                                 float difmat[4][4];
1821                                                 float imat[4][4];
1822                                                 float temp[4][4];
1823                                                 float delta[3];
1824
1825                                                 /* Get the premat */
1826                                                 VecSubf (delta, curbone->tail, curbone->head);
1827                                                 make_boneMatrixvr(temp, delta, curbone->roll);
1828                                                 Mat4MulMat4 (premat, temp, mat);
1829
1830                                                 Mat4MulVecfl(mat, curbone->head);
1831                                                 Mat4MulVecfl(mat, curbone->tail);
1832
1833                                                 /* Get the postmat */
1834                                                 VecSubf (delta, curbone->tail, curbone->head);
1835                                                 make_boneMatrixvr(postmat, delta, curbone->roll);
1836                                                 
1837                                                 /* Find the roll */
1838                                                 Mat4Invert (imat, premat);
1839                                                 Mat4MulMat4 (difmat, postmat, imat);
1840                                                 
1841                                                 curbone->roll -=atan(difmat[2][0]/difmat[2][2]);
1842                                                 
1843                                                 if (difmat[0][0]<0)
1844                                                         curbone->roll +=M_PI;
1845
1846                                         }
1847 #if 1
1848                                         BLI_remlink(&eblist, curbone);
1849                                         BLI_addtail(&G.edbo, curbone);
1850 #else
1851                                         BLI_remlink(&eblist, curbone);
1852                                         BLI_addtail(&baselist, curbone);
1853 #endif
1854                                 }
1855                                 
1856                                 free_and_unlink_base(base);
1857                         }
1858                 }
1859         }
1860         
1861 #if 1
1862         exit_editmode(1);
1863 #else
1864         editbones_to_armature(&baselist, ob);
1865         if (baselist.first){
1866                 BLI_freelistN (&baselist);
1867         }
1868 #endif
1869         allqueue(REDRAWVIEW3D, 0);
1870
1871 }
1872
1873
1874 static int      editbone_name_exists (char *name){
1875         EditBone        *eBone;
1876         
1877         for (eBone=G.edbo.first; eBone; eBone=eBone->next){
1878                 if (!strcmp (name, eBone->name))
1879                         return 1;
1880         }
1881         
1882         return 0;
1883                 
1884 }
1885
1886 void unique_editbone_name (char *name){
1887         char            tempname[64];
1888         int                     number;
1889         char            *dot;
1890         
1891         
1892         if (editbone_name_exists(name)){
1893                 /*      Strip off the suffix */
1894                 dot=strchr(name, '.');
1895                 if (dot)
1896                         *dot=0;
1897                 
1898                 for (number = 1; number <=999; number++){
1899                         sprintf (tempname, "%s.%03d", name, number);
1900                         if (!editbone_name_exists(tempname)){
1901                                 strcpy (name, tempname);
1902                                 return;
1903                         }
1904                 }
1905         }
1906 }
1907
1908 void extrude_armature(void)
1909 {
1910         EditBone *newbone, *curbone, *first=NULL, *partest;
1911         
1912         TEST_EDITARMATURE;
1913         
1914         
1915         if(okee("Extrude Bone Segments")==0) return;
1916         
1917         /* Duplicate the necessary bones */
1918         for (curbone = G.edbo.first; ((curbone) && (curbone!=first)); curbone=curbone->next){
1919                 if (curbone->flag & (BONE_TIPSEL|BONE_SELECTED)){
1920                         newbone = MEM_callocN(sizeof(EditBone), "extrudebone");
1921                         
1922                         
1923                         VECCOPY (newbone->head, curbone->tail);
1924                         VECCOPY (newbone->tail, newbone->head);
1925                         newbone->parent = curbone;
1926                         newbone->flag = BONE_TIPSEL;
1927                         newbone->flag |= BONE_QUATROT;
1928                         newbone->weight= curbone->weight;
1929                         newbone->dist= curbone->dist;
1930                         newbone->boneclass= curbone->boneclass;
1931
1932                         Mat4One(newbone->obmat);
1933                         
1934                         /* See if there are any ik children of the parent */
1935                         for (partest = G.edbo.first; partest; partest=partest->next){
1936                                 if ((partest->parent == curbone) && (partest->flag & BONE_IK_TOPARENT))
1937                                         break;
1938                         }
1939                         
1940                         if (!partest)
1941                                 newbone->flag |= BONE_IK_TOPARENT;
1942                         
1943                         strcpy (newbone->name, curbone->name);
1944                         unique_editbone_name(newbone->name);
1945                         
1946                         /* Add the new bone to the list */
1947                         BLI_addtail(&G.edbo, newbone);
1948                         if (!first)
1949                                 first = newbone;
1950                 }
1951                 
1952                 /* Deselect the old bone */
1953                 curbone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL);
1954                 
1955         }
1956         
1957         /* Transform the endpoints */
1958         countall();
1959         transform('g');         
1960         allqueue(REDRAWBUTSEDIT, 0);
1961         allqueue(REDRAWBUTSOBJECT, 0);
1962 }
1963
1964 void addvert_armature(void)
1965 {
1966 /*      
1967         I haven't decided if it will be possible to add bones in this way.
1968         For the moment, we'll use Extrude, or explicit parenting.
1969         */
1970 }
1971
1972
1973
1974
1975
1976 void adduplicate_armature(void)
1977 {
1978         EditBone        *eBone = NULL;
1979         EditBone        *curBone;
1980         EditBone        *firstDup=NULL; /*      The beginning of the duplicated bones in the edbo list */
1981
1982         countall();
1983
1984         /*      Find the selected bones and duplicate them as needed */
1985         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1986                 if (curBone->flag & BONE_SELECTED){
1987
1988                         eBone=MEM_callocN(sizeof(EditBone), "addup_editbone");
1989                         eBone->flag |= BONE_SELECTED;
1990
1991                         /*      Copy data from old bone to new bone */
1992                         memcpy (eBone, curBone, sizeof(EditBone));
1993
1994                         /* Blank out tranformation data */
1995                         eBone->loc[0]=eBone->loc[1]=eBone->loc[2]=0.0F;
1996                         eBone->size[0]=eBone->size[1]=eBone->size[2]=1.0F;
1997                         eBone->quat[0]=eBone->quat[1]=eBone->quat[2]=eBone->quat[3]=0.0F;
1998
1999                         curBone->temp = eBone;
2000                         eBone->temp = curBone;
2001
2002                         unique_editbone_name (eBone->name);
2003                         BLI_addtail (&G.edbo, eBone);
2004                         if (!firstDup)
2005                                 firstDup=eBone;
2006                 }
2007         }
2008
2009         if (eBone){
2010                 /*      Fix the head and tail */        
2011                 if (eBone->parent && !eBone->parent->flag & BONE_SELECTED){
2012                         VecSubf (eBone->tail, eBone->tail, eBone->head);
2013                         VecSubf (eBone->head, eBone->head, eBone->head);
2014                 }
2015         }
2016
2017         /*      Run though the list and fix the pointers */
2018         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
2019
2020                 if (curBone->flag & BONE_SELECTED){
2021                         eBone=(EditBone*) curBone->temp;
2022
2023                         /*      If this bone has no parent,
2024                                         Set the duplicate->parent to NULL
2025                         */
2026                         if (!curBone->parent){
2027                                 eBone->parent = NULL;
2028                         }
2029                         /*      If this bone has a parent that IS selected,
2030                                         Set the duplicate->parent to the curBone->parent->duplicate
2031                         */
2032                          else if (curBone->parent->flag & BONE_SELECTED){
2033                                 eBone->parent=(EditBone*) curBone->parent->temp;
2034                         }
2035                         /*      If this bone has a parent that IS not selected,
2036                                         Set the duplicate->parent to the curBone->parent
2037                         */
2038                          else {
2039                                 eBone->parent=(EditBone*) curBone->parent; 
2040                                 eBone->flag &= ~BONE_IK_TOPARENT;
2041                         }
2042                          
2043                 }
2044         } 
2045         
2046         /*      Deselect the old bones and select the new ones */
2047
2048         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
2049                 curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
2050         }
2051
2052
2053         transform('g');
2054         allqueue(REDRAWBUTSEDIT, 0);
2055         allqueue(REDRAWBUTSOBJECT, 0);
2056 }
2057
2058 /*
2059  *
2060  *      POSING FUNCTIONS: Maybe move these to a separate file at some point
2061  *
2062  *
2063  */
2064
2065
2066 void clear_armature(Object *ob, char mode){
2067         Bone    *curBone;
2068         bArmature       *arm;
2069
2070         arm=get_armature(ob);
2071         
2072         if (!arm)
2073                 return;
2074
2075         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
2076                 clear_armature_children (curBone, ob->pose, mode);
2077         }
2078
2079         where_is_armature (ob);
2080
2081 }
2082
2083 static void clear_armature_children (Bone *bone, bPose *pose, char mode){
2084         Bone                    *curBone;
2085         bPoseChannel    *chan;
2086         if (!bone)
2087                 return;
2088         
2089         chan = verify_pose_channel (pose, bone->name);
2090
2091         if (!chan)
2092                 return;
2093
2094         if (bone->flag & BONE_SELECTED){
2095                 switch (mode){
2096                 case 'r':
2097                         chan->quat[1]=chan->quat[2]=chan->quat[3]=0.0F; chan->quat[0]=1.0F;
2098                         break;
2099                 case 'g':
2100                         chan->loc[0]=chan->loc[1]=chan->loc[2]=0.0F;
2101                         break;
2102                 case 's':
2103                         chan->size[0]=chan->size[1]=chan->size[2]=1.0F;
2104                         break;
2105                         
2106                 }
2107         }
2108
2109         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
2110                 clear_armature_children (curBone, pose, mode);
2111         }
2112
2113 }
2114
2115 void mousepose_armature(void)
2116 /*
2117         Handles right-clicking for selection
2118         of bones in armature pose modes.
2119 */
2120 {
2121         Bone            *nearBone;
2122
2123         if (!G.obpose)
2124                 return;
2125
2126         nearBone = get_nearest_bone(1);
2127
2128         if (nearBone){
2129                 if (!(G.qual & LR_SHIFTKEY)){
2130                         deselectall_posearmature(0);
2131                         nearBone->flag|=BONE_SELECTED;
2132                         select_actionchannel_by_name(G.obpose->action, nearBone->name, 1);
2133                 }
2134                 else {
2135                         if (nearBone->flag & BONE_SELECTED){
2136                                 nearBone->flag &= ~BONE_SELECTED;
2137                                 select_actionchannel_by_name(G.obpose->action, nearBone->name, 0);
2138                         }
2139                         else{
2140                                 nearBone->flag |= BONE_SELECTED;
2141                                 select_actionchannel_by_name(G.obpose->action, nearBone->name, 1);
2142                         }
2143                 };
2144         }
2145
2146         allqueue(REDRAWVIEW3D, 0);
2147         allqueue(REDRAWACTION, 0);
2148         allqueue(REDRAWIPO, 0);         /* To force action ipo update */
2149         allqueue(REDRAWBUTSOBJECT, 0);
2150
2151 //      countall();
2152         rightmouse_transform();
2153         
2154 }
2155
2156 void make_trans_bones (char mode)
2157 /*      Used in pose mode       */
2158 {
2159         bArmature               *arm;
2160         Bone                    *curBone;
2161         int                             count=0;
2162
2163         transmain=NULL;
2164
2165         arm=get_armature (G.obpose);
2166         if (!arm)
2167                 return;
2168
2169         if (arm->flag & ARM_RESTPOS){
2170                 notice ("Transformation not possible while Rest Position is enabled");
2171                 return;
2172         }
2173
2174
2175         if (!(G.obpose->lay & G.vd->lay))
2176                 return;
2177
2178
2179         centroid[0]=centroid[1]=centroid[2]=0;
2180
2181         apply_pose_armature(arm, G.obpose->pose, 0);
2182         where_is_armature (G.obpose);
2183
2184         /*      Allocate memory for the transformation record */
2185         tottrans= count_bones (arm, BONE_SELECTED, 0);
2186
2187         if (!tottrans)
2188                 return;
2189
2190         transmain= MEM_callocN(tottrans*sizeof(TransOb), "bonetransmain");
2191
2192         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
2193                 count = add_trans_bonechildren (G.obpose, curBone, transmain, count, mode);
2194         }
2195         
2196         tottrans=count;
2197         
2198         if (tottrans){
2199                 centroid[0]/=tottrans;
2200                 centroid[1]/=tottrans;
2201                 centroid[2]/=tottrans;
2202                 Mat4MulVecfl (G.obpose->obmat, centroid);
2203         }
2204         else{
2205                 MEM_freeN (transmain);
2206         }
2207         return;
2208
2209 }
2210
2211 static int      count_bones (bArmature *arm, int flagmask, int allbones)
2212 {
2213         int     count=0;
2214         Bone    *curBone;
2215
2216         if (!arm)
2217                 return 0;
2218
2219         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
2220                 count = count_bonechildren (curBone, count, flagmask, allbones);
2221         }
2222
2223         return count;
2224
2225 }
2226
2227 static int count_bonechildren (Bone *bone, int incount, int flagmask, int allbones){
2228
2229         Bone    *curBone;
2230
2231         if (!bone)
2232                 return incount;
2233
2234         if (bone->flag & flagmask || flagmask == 0xFFFFFFFF){
2235                 incount++;
2236                 if (!allbones)
2237                         return incount;
2238         }
2239
2240         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
2241                 incount=count_bonechildren (curBone, incount, flagmask, allbones);
2242         }
2243
2244         return incount;
2245 }
2246
2247
2248 static int add_trans_bonechildren (Object* ob, Bone* bone, TransOb* buffer, int index, char mode)
2249 {
2250         Bone    *curBone;
2251         TransOb *curOb;
2252         float   parmat[4][4], tempmat[4][4];
2253         float tempobmat[4][4];
2254         float vec[3];
2255         if (!bone)
2256                 return index;
2257
2258         
2259         
2260         /* We don't let IK children get "grabbed" */
2261         if (bone->flag & BONE_SELECTED){
2262                 if (!((mode=='g' || mode=='G') && (bone->flag & BONE_IK_TOPARENT))){
2263                         
2264                         get_bone_root_pos (bone, vec, 1);
2265                 
2266                         VecAddf (centroid, centroid, vec);
2267                         
2268                         curOb=&buffer[index];
2269                         
2270                         curOb->ob = ob;
2271                         curOb->rot=NULL;
2272
2273                         curOb->quat= bone->quat;
2274                         curOb->size= bone->size;
2275                         curOb->loc = bone->loc;
2276
2277                         curOb->data = bone; //  FIXME: Dangerous
2278                         
2279                         memcpy (curOb->oldquat, bone->quat, sizeof (bone->quat));
2280                         memcpy (curOb->oldsize, bone->size, sizeof (bone->size));
2281                         memcpy (curOb->oldloc, bone->loc, sizeof (bone->loc));
2282
2283 #if 0
2284                         if (bone->parent)
2285                                 get_objectspace_bone_matrix(bone->parent, tempmat, 1, 1);
2286                         else
2287                                 Mat4One (tempmat);
2288 #else
2289                         /* Get the matrix of this bone minus the usertransform */
2290                         Mat4CpyMat4 (tempobmat, bone->obmat);
2291                         Mat4One (bone->obmat);
2292                         get_objectspace_bone_matrix(bone, tempmat, 1, 1);
2293                         Mat4CpyMat4 (bone->obmat, tempobmat);
2294
2295                         
2296 #endif
2297
2298 #if 1
2299                         Mat4MulMat4 (parmat, tempmat, ob->obmat);       /* Original */
2300
2301                         /* Get world transform */
2302                         get_objectspace_bone_matrix(bone, tempmat, 1, 1);
2303                         if (ob->parent){
2304                                 where_is_object(ob->parent);
2305                                 Mat4MulSerie (tempobmat, ob->parent->obmat, ob->obmat, tempmat, NULL, NULL, NULL, NULL, NULL);
2306                         }
2307                         else
2308                                 Mat4MulSerie (tempobmat, ob->obmat, tempmat, NULL, NULL, NULL, NULL, NULL, NULL);
2309                         Mat3CpyMat4 (curOb->axismat, tempobmat);
2310                         Mat3Ortho(curOb->axismat);
2311
2312 #else
2313                         Mat4MulMat4 (parmat, ob->obmat, tempmat);
2314 #endif
2315                         Mat3CpyMat4 (curOb->parmat, parmat);
2316                         Mat3Inv (curOb->parinv, curOb->parmat);
2317
2318                         Mat3CpyMat4 (curOb->obmat, bone->obmat);
2319                         Mat3Inv (curOb->obinv, curOb->obmat);
2320                         
2321                         index++;
2322                         return index;
2323                 }
2324
2325         }
2326         
2327         /*      Recursively search  */
2328         for (curBone = bone->childbase.first; curBone; curBone=curBone->next){
2329                 index=add_trans_bonechildren (ob, curBone, buffer, index, mode);
2330         }
2331
2332         return index;
2333 }
2334
2335 static void deselect_bonechildren (Bone *bone, int mode)
2336 {
2337         Bone    *curBone;
2338
2339         if (!bone)
2340                 return;
2341
2342         if (mode==0)
2343                 bone->flag &= ~BONE_SELECTED;
2344         else if (!(bone->flag & BONE_HIDDEN))
2345                 bone->flag |= BONE_SELECTED;
2346
2347         select_actionchannel_by_name(G.obpose->action, bone->name, mode);
2348
2349         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
2350                 deselect_bonechildren(curBone, mode);
2351         }
2352 }
2353
2354
2355 void deselectall_posearmature (int test){
2356         int     selectmode      =       0;
2357         Bone*   curBone;
2358         
2359         /*      Determine if we're selecting or deselecting     */
2360         if (test){
2361                 if (!count_bones (get_armature(G.obpose), BONE_SELECTED, 0))
2362                         selectmode = 1;
2363         }
2364         
2365         /*      Set the flags accordingly       */
2366         for (curBone=get_armature(G.obpose)->bonebase.first; curBone; curBone=curBone->next)
2367                 deselect_bonechildren (curBone, selectmode);
2368         
2369         allqueue(REDRAWVIEW3D, 0);
2370         allqueue(REDRAWACTION, 0);
2371
2372 }
2373
2374 void auto_align_armature(void)
2375 /* Sets the roll value of selected bones so that their zaxes point upwards */
2376 {
2377         EditBone *ebone;
2378         float   xaxis[3]={1.0, 0.0, 0.0}, yaxis[3], zaxis[3]={0.0, 0.0, 1.0};
2379         float   targetmat[4][4], imat[4][4];
2380         float   curmat[4][4], diffmat[4][4];
2381         float   delta[3];
2382
2383         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
2384                 if (ebone->flag & BONE_SELECTED){
2385                         /* Find the current bone matrix */
2386                         VecSubf(delta, ebone->tail, ebone->head);
2387                         make_boneMatrixvr (curmat, delta, 0.0);
2388                         
2389                         /* Make new matrix based on y axis & z-up */
2390                         VECCOPY (yaxis, curmat[1]);
2391
2392                         Mat4One(targetmat);
2393                         VECCOPY (targetmat[0], xaxis);
2394                         VECCOPY (targetmat[1], yaxis);
2395                         VECCOPY (targetmat[2], zaxis);
2396                         Mat4Ortho(targetmat);
2397
2398                         /* Find the difference between the two matrices */
2399
2400                         Mat4Invert (imat, targetmat);
2401                         Mat4MulMat4(diffmat, curmat, imat);
2402
2403                         ebone->roll = atan(diffmat[2][0]/diffmat[2][2]);
2404                         
2405                 }
2406         }
2407
2408
2409 int bone_looper(Object *ob, Bone *bone, void *data,
2410                         int (*bone_func)(Object *, Bone *, void *)) {
2411
2412     /* We want to apply the function bone_func to every bone 
2413      * in an armature -- feed bone_looper the first bone and 
2414      * a pointer to the bone_func and watch it go!. The int count 
2415      * can be useful for counting bones with a certain property
2416      * (e.g. skinnable)
2417      */
2418     int count = 0;
2419
2420     if (bone) {
2421
2422         /* only do bone_func if the bone is non null
2423          */
2424         count += bone_func(ob, bone, data);
2425
2426         /* try to execute bone_func for the first child
2427          */
2428         count += bone_looper(ob, bone->childbase.first, data,
2429                                     bone_func);
2430
2431         /* try to execute bone_func for the next bone at this
2432          * depth of the recursion.
2433          */
2434         count += bone_looper(ob, bone->next, data, bone_func);
2435     }
2436
2437     return count;
2438 }
2439
2440 int bone_skinnable(Object *ob, Bone *bone, void *data)
2441 {
2442     /* Bones that are not of boneclass BONE_UNSKINNABLE
2443      * are regarded to be "skinnable" and are eligible for
2444      * auto-skinning.
2445      *
2446      * This function performs 2 functions:
2447      *
2448      *   a) It returns 1 if the bone is skinnable.
2449      *      If we loop over all bones with this 
2450      *      function, we can count the number of
2451      *      skinnable bones.
2452      *   b) If the pointer data is non null,
2453      *      it is treated like a handle to a
2454      *      bone pointer -- the bone pointer
2455      *      is set to point at this bone, and
2456      *      the pointer the handle points to
2457      *      is incremented to point to the
2458      *      next member of an array of pointers
2459      *      to bones. This way we can loop using
2460      *      this function to construct an array of
2461      *      pointers to bones that point to all
2462      *      skinnable bones.
2463      */
2464     Bone ***hbone;
2465
2466     if ( bone->boneclass != BONE_UNSKINNABLE ) {
2467                 if (data != NULL) {
2468                         hbone = (Bone ***) data;
2469             **hbone = bone;
2470             ++*hbone;
2471         }
2472         return 1;
2473     }
2474     return 0;
2475 }
2476
2477 int add_defgroup_unique_bone(Object *ob, Bone *bone, void *data) {
2478     /* This group creates a vertex group to ob that has the
2479      * same name as bone (provided the bone is skinnable). 
2480          * If such a vertex group aleady exist the routine exits.
2481      */
2482         if ( bone_skinnable(ob, bone, NULL) ) {
2483                 if (!get_named_vertexgroup(ob,bone->name)) {
2484                         add_defgroup_name(ob, bone->name);
2485                         return 1;
2486                 }
2487     }
2488     return 0;
2489 }
2490
2491 int dgroup_skinnable(Object *ob, Bone *bone, void *data) {
2492     /* Bones that are not of boneclass BONE_UNSKINNABLE
2493      * are regarded to be "skinnable" and are eligible for
2494      * auto-skinning.
2495      *
2496      * This function performs 2 functions:
2497      *
2498      *   a) If the bone is skinnable, it creates 
2499      *      a vertex group for ob that has
2500      *      the name of the skinnable bone
2501      *      (if one doesn't exist already).
2502      *   b) If the pointer data is non null,
2503      *      it is treated like a handle to a
2504      *      bDeformGroup pointer -- the 
2505      *      bDeformGroup pointer is set to point
2506      *      to the deform group with the bone's
2507      *      name, and the pointer the handle 
2508      *      points to is incremented to point to the
2509      *      next member of an array of pointers
2510      *      to bDeformGroups. This way we can loop using
2511      *      this function to construct an array of
2512      *      pointers to bDeformGroups, all with names
2513      *      of skinnable bones.
2514      */
2515     bDeformGroup ***hgroup, *defgroup;
2516
2517     if ( bone->boneclass != BONE_UNSKINNABLE ) {
2518         if ( !(defgroup = get_named_vertexgroup(ob, bone->name)) ) {
2519             defgroup = add_defgroup_name(ob, bone->name);
2520         }
2521
2522         if (data != NULL) {
2523             hgroup = (bDeformGroup ***) data;
2524             **hgroup = defgroup;
2525             ++*hgroup;
2526         }
2527         return 1;
2528     }
2529     return 0;
2530 }
2531
2532 void add_verts_to_closest_dgroup(Object *ob, Object *par)
2533 {
2534     /* This function implements a crude form of 
2535      * auto-skinning: vertices are assigned to the
2536      * deformation groups associated with bones based
2537      * on thier proximity to a bone. Every vert is
2538      * given a weight of 1.0 to the weight group
2539      * cooresponding to the bone that it is
2540      * closest to. The vertex may also be assigned to
2541      * a deformation group associated to a bone
2542      * that is within 10% of the mninimum distance
2543      * between the bone and the nearest vert -- the
2544      * cooresponding weight will fall-off to zero
2545      * as the distance approaches the 10% tolerance mark.
2546          * If the mesh has subsurf enabled then the verts
2547          * on the subsurf limit surface is used to generate 
2548          * the weights rather than the verts on the cage
2549          * mesh.
2550      */
2551
2552     bArmature *arm;
2553     Bone **bonelist, **bonehandle, *bone;
2554     bDeformGroup **dgrouplist, **dgrouphandle, *defgroup;
2555     float *distance, mindist = 0.0, weight = 0.0;
2556     float   root[3];
2557     float   tip[3];
2558     float real_co[3];
2559         float *subverts = NULL;
2560     float *subvert;
2561     Mesh  *mesh;
2562     MVert *vert;
2563
2564     int numbones, i, j;
2565
2566     /* If the parent object is not an armature exit */
2567     arm = get_armature(par);
2568     if (!arm)
2569         return;
2570
2571     /* count the number of skinnable bones */
2572     numbones = bone_looper(ob, arm->bonebase.first, NULL,
2573                                   bone_skinnable);
2574
2575     /* create an array of pointer to bones that are skinnable
2576      * and fill it with all of the skinnable bones
2577      */
2578     bonelist = MEM_mallocN(numbones*sizeof(Bone *), "bonelist");
2579     bonehandle = bonelist;
2580     bone_looper(ob, arm->bonebase.first, &bonehandle,
2581                        bone_skinnable);
2582
2583     /* create an array of pointers to the deform groups that
2584      * coorespond to the skinnable bones (creating them
2585      * as necessary.
2586      */
2587     dgrouplist = MEM_mallocN(numbones*sizeof(bDeformGroup *), "dgrouplist");
2588     dgrouphandle = dgrouplist;
2589     bone_looper(ob, arm->bonebase.first, &dgrouphandle,
2590                        dgroup_skinnable);
2591
2592     /* create an array of floats that will be used for each vert
2593      * to hold the distance to each bone.
2594      */
2595     distance = MEM_mallocN(numbones*sizeof(float), "distance");
2596
2597     mesh = (Mesh*)ob->data;
2598
2599         /* Is subsurf on? Lets use the verts on the limit surface then */
2600         if ( (mesh->flag&ME_SUBSURF) && (mesh->subdiv > 0) ) {
2601                 subverts = MEM_mallocN(3*mesh->totvert*sizeof(float), "subverts");
2602                 subsurf_calculate_limit_positions(mesh, (void *)subverts);      /* (ton) made void*, dunno how to cast */
2603         }
2604
2605     /* for each vertex in the mesh ...
2606      */
2607     for ( i=0 ; i < mesh->totvert ; ++i ) {
2608         /* get the vert in global coords
2609          */
2610                 
2611                 if (subverts) {
2612                         subvert = subverts + i*3;
2613                         VECCOPY (real_co, subvert);
2614                 }
2615                 else {
2616                         vert = mesh->mvert + i;
2617                         VECCOPY (real_co, vert->co);
2618                 }
2619         Mat4MulVecfl(ob->obmat, real_co);
2620
2621
2622         /* for each skinnable bone ...
2623          */
2624         for (j=0; j < numbones; ++j) {
2625             bone = bonelist[j];
2626
2627             /* get the root of the bone in global coords
2628              */
2629             get_bone_root_pos (bone, root, 0);
2630             Mat4MulVecfl(par->obmat, root);
2631
2632             /* get the tip of the bone in global coords
2633              */
2634             get_bone_tip_pos (bone, tip, 0);
2635             Mat4MulVecfl(par->obmat, tip);
2636
2637             /* store the distance from the bone to
2638              * the vert
2639              */
2640             distance[j] = dist_to_bone(real_co, root, tip);
2641
2642             /* if this is the first bone, or if this
2643              * bone is less than mindist, then set this
2644              * distance to mindist
2645              */
2646             if (j == 0) {
2647                 mindist = distance[j];
2648             }
2649             else if (distance[j] < mindist) {
2650                 mindist = distance[j];
2651             }
2652         }
2653
2654         /* for each deform group ...
2655          */
2656         for (j=0; j < numbones; ++j) {
2657             defgroup = dgrouplist[j];
2658
2659             /* if the cooresponding bone is the closest one
2660              * add the vert to the deform group with weight 1
2661              */
2662             if (distance[j] <= mindist) {
2663                 add_vert_to_defgroup (ob, defgroup, i, 1.0, WEIGHT_REPLACE);
2664             }
2665
2666             /* if the cooresponding bone is within 10% of the
2667              * nearest distance, add the vert to the
2668              * deform group with a weight that declines with
2669              * distance
2670              */
2671             else if (distance[j] <= mindist*1.10) {
2672                 if (mindist > 0)
2673                     weight = 1.0 - (distance[j] - mindist) / (mindist * 0.10);
2674                 add_vert_to_defgroup (ob, defgroup, i, weight, WEIGHT_REPLACE);
2675             }
2676             
2677             /* if the cooresponding bone is outside of the 10% tolerance
2678              * then remove the vert from the weight group (if it is
2679              * in that group)
2680              */
2681             else {
2682                 remove_vert_defgroup (ob, defgroup, i);
2683             }
2684         }
2685     }
2686
2687     /* free the memory allocated
2688      */
2689     MEM_freeN(bonelist);
2690     MEM_freeN(dgrouplist);
2691     MEM_freeN(distance);
2692         if (subverts) MEM_freeN(subverts);
2693 }
2694
2695 void create_vgroups_from_armature(Object *ob, Object *par)
2696 {
2697         /* Lets try to create some vertex groups 
2698          * based on the bones of the parent armature.
2699          */
2700
2701         bArmature *arm;
2702         short mode;
2703
2704         /* If the parent object is not an armature exit */
2705         arm = get_armature(par);
2706         if (!arm)
2707                 return;
2708
2709         /* Prompt the user on whether/how they want the vertex groups
2710          * added to the child mesh */
2711     mode= pupmenu("Create Vertex Groups? %t|"
2712                                   "Don't Create Groups %x1|"
2713                                   "Name Groups %x2|"
2714                   "Create From Closest Bones %x3");
2715         switch (mode){
2716         case 2:
2717                 /* Traverse the bone list, trying to create empty vertex 
2718                  * groups cooresponding to the bone.
2719                  */
2720                 bone_looper(ob, arm->bonebase.first, NULL,
2721                                         add_defgroup_unique_bone);
2722                 if (ob->type == OB_MESH)
2723                         create_dverts((Mesh*)ob->data);
2724
2725                 break;
2726
2727         case 3:
2728                 /* Traverse the bone list, trying to create vertex groups 
2729                  * that are populated with the vertices for which the
2730                  * bone is closest.
2731                  */
2732                 add_verts_to_closest_dgroup(ob, par);
2733                 break;
2734
2735         }
2736
2737
2738 int hide_selected_pose_bone(Object *ob, Bone *bone, void *ptr) {
2739         if (bone->flag & BONE_SELECTED) {
2740                 bone->flag |= BONE_HIDDEN;
2741                 bone->flag &= ~BONE_SELECTED;
2742         }
2743         return 0;
2744 }
2745
2746 void hide_selected_pose_bones(void) {
2747         bArmature               *arm;
2748
2749         arm=get_armature (G.obpose);
2750
2751         if (!arm)
2752                 return;
2753
2754         bone_looper(G.obpose, arm->bonebase.first, NULL, 
2755                                 hide_selected_pose_bone);
2756
2757         force_draw();
2758 }
2759
2760 int hide_unselected_pose_bone(Object *ob, Bone *bone, void *ptr) {
2761         if (~bone->flag & BONE_SELECTED) {
2762                 bone->flag |= BONE_HIDDEN;
2763         }
2764         return 0;
2765 }
2766
2767 void hide_unselected_pose_bones(void) {
2768         bArmature               *arm;
2769
2770         arm=get_armature (G.obpose);
2771
2772         if (!arm)
2773                 return;
2774
2775         bone_looper(G.obpose, arm->bonebase.first, NULL, 
2776                                 hide_unselected_pose_bone);
2777
2778         force_draw();
2779 }
2780
2781 int show_pose_bone(Object *ob, Bone *bone, void *ptr) {
2782         if (bone->flag & BONE_HIDDEN) {
2783                 bone->flag &= ~BONE_HIDDEN;
2784                 bone->flag |= BONE_SELECTED;
2785         }
2786
2787         return 0;
2788 }
2789
2790 void show_all_pose_bones(void) {
2791         bArmature               *arm;
2792
2793         arm=get_armature (G.obpose);
2794
2795         if (!arm)
2796                 return;
2797
2798         bone_looper(G.obpose, arm->bonebase.first, NULL, 
2799                                 show_pose_bone);
2800
2801         force_draw();
2802 }
2803
2804 int is_delay_deform(void)
2805 {
2806         bArmature               *arm;
2807
2808         arm=get_armature (G.obpose);
2809
2810         if (!arm)
2811                 return 0;
2812
2813         return (arm->flag & ARM_DELAYDEFORM);
2814 }