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