301658f5339a69f08fe20952379266951efbc6c2
[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 <ctype.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <math.h> 
38
39 #ifdef HAVE_CONFIG_H
40 #include <config.h>
41 #endif
42
43 #include "MEM_guardedalloc.h"
44
45 #include "BMF_Api.h"
46
47 #include "DNA_action_types.h"
48 #include "DNA_armature_types.h"
49 #include "DNA_constraint_types.h"
50 #include "DNA_ID.h"
51 #include "DNA_mesh_types.h"
52 #include "DNA_meshdata_types.h"
53 #include "DNA_object_types.h"
54 #include "DNA_scene_types.h"
55 #include "DNA_screen_types.h"
56 #include "DNA_space_types.h"
57 #include "DNA_view3d_types.h"
58 #include "DNA_modifier_types.h"
59
60 #include "BLI_blenlib.h"
61 #include "BLI_arithb.h"
62 #include "BLI_editVert.h"
63
64 #include "BKE_action.h"
65 #include "BKE_armature.h"
66 #include "BKE_constraint.h"
67 #include "BKE_deform.h"
68 #include "BKE_depsgraph.h"
69 #include "BKE_global.h"
70 #include "BKE_main.h"
71 #include "BKE_object.h"
72 #include "BKE_subsurf.h"
73 #include "BKE_utildefines.h"
74 #include "BKE_modifier.h"
75
76 #include "BIF_editaction.h"
77 #include "BIF_editmode_undo.h"
78 #include "BIF_editdeform.h"
79 #include "BIF_editarmature.h"
80 #include "BIF_editconstraint.h"
81 #include "BIF_gl.h"
82 #include "BIF_graphics.h"
83 #include "BIF_interface.h"
84 #include "BIF_poseobject.h"
85 #include "BIF_mywindow.h"
86 #include "BIF_resources.h"
87 #include "BIF_screen.h"
88 #include "BIF_space.h"
89 #include "BIF_toolbox.h"
90 #include "BIF_transform.h"
91
92 #include "BDR_editobject.h"
93 #include "BDR_drawobject.h"
94
95 #include "BSE_edit.h"
96 #include "BSE_view.h"
97 #include "BSE_trans_types.h"
98
99 #include "PIL_time.h"
100
101 #include "mydevice.h"
102 #include "blendef.h"
103 #include "nla.h"
104
105 extern  float centre[3], centroid[3];   /* Originally defined in editobject.c */
106
107 /*      Macros  */
108 #define TEST_EDITARMATURE {if(G.obedit==0) return; if( (G.vd->lay & G.obedit->lay)==0 ) return;}
109
110
111 /* **************** tools on Editmode Armature **************** */
112
113 /* converts Bones to EditBone list, used for tools as well */
114 static void make_boneList(ListBase* list, ListBase *bones, EditBone *parent)
115 {
116         EditBone        *eBone;
117         Bone            *curBone;
118         float delta[3];
119         float premat[3][3];
120         float postmat[3][3];
121         float imat[3][3];
122         float difmat[3][3];
123                 
124         for (curBone=bones->first; curBone; curBone=curBone->next){
125                 eBone= MEM_callocN(sizeof(EditBone), "make_editbone");
126                 
127                 /*      Copy relevant data from bone to eBone */
128                 eBone->parent=parent;
129                 strcpy (eBone->name, curBone->name);
130                 eBone->flag = curBone->flag;
131                 
132                 /* fix selection flags */
133                 if(eBone->flag & BONE_SELECTED) {
134                         eBone->flag |= BONE_TIPSEL;
135                         if(eBone->parent && (eBone->flag & BONE_CONNECTED))
136                                 eBone->parent->flag |= BONE_TIPSEL;
137                         else 
138                                 eBone->flag |= BONE_ROOTSEL;
139                 }
140                 
141                 VECCOPY(eBone->head, curBone->arm_head);
142                 VECCOPY(eBone->tail, curBone->arm_tail);                
143                 
144                 eBone->roll= 0.0;
145                 
146                 /* roll fixing */
147                 VecSubf (delta, eBone->tail, eBone->head);
148                 vec_roll_to_mat3(delta, 0.0, postmat);
149                 
150                 Mat3CpyMat4(premat, curBone->arm_mat);
151                 
152                 Mat3Inv(imat, postmat);
153                 Mat3MulMat3(difmat, imat, premat);
154                 
155                 eBone->roll = atan(difmat[2][0]/difmat[2][2]);
156                 if (difmat[0][0]<0.0) eBone->roll +=M_PI;
157                 
158                 /* rest of stuff copy */
159                 eBone->length= curBone->length;
160                 eBone->dist= curBone->dist;
161                 eBone->weight= curBone->weight;
162                 eBone->xwidth= curBone->xwidth;
163                 eBone->zwidth= curBone->zwidth;
164                 eBone->ease1= curBone->ease1;
165                 eBone->ease2= curBone->ease2;
166                 eBone->rad_head= curBone->rad_head;
167                 eBone->rad_tail= curBone->rad_tail;
168                 eBone->segments = curBone->segments;            
169                 eBone->boneclass = curBone->boneclass;
170                 
171                 BLI_addtail (list, eBone);
172                 
173                 /*      Add children if necessary */
174                 if (curBone->childbase.first) 
175                         make_boneList (list, &curBone->childbase, eBone);
176         }
177 }
178
179 /* nasty stuff for converting roll in editbones into bones */
180 /* also sets restposition in armature (arm_mat) */
181 static void fix_bonelist_roll (ListBase *bonelist, ListBase *editbonelist)
182 {
183         Bone *curBone;
184         EditBone *ebone;
185         float premat[3][3];
186         float postmat[3][3];
187         float difmat[3][3];
188         float imat[3][3];
189         float delta[3];
190         
191         for (curBone=bonelist->first; curBone; curBone=curBone->next) {
192                 /* sets local matrix and arm_mat (restpos) */
193                 where_is_armature_bone(curBone, curBone->parent);
194                 
195                 /* Find the associated editbone */
196                 for (ebone = editbonelist->first; ebone; ebone=ebone->next)
197                         if ((Bone*)ebone->temp == curBone)
198                                 break;
199                 
200                 if (ebone) {
201                         /* Get the ebone premat */
202                         VecSubf (delta, ebone->tail, ebone->head);
203                         vec_roll_to_mat3(delta, ebone->roll, premat);
204                         
205                         /* Get the bone postmat */
206                         Mat3CpyMat4(postmat, curBone->arm_mat);
207
208                         Mat3Inv(imat, premat);
209                         Mat3MulMat3(difmat, imat, postmat);
210 #if 0
211                         printf ("Bone %s\n", curBone->name);
212                         printmatrix4 ("premat", premat);
213                         printmatrix4 ("postmat", postmat);
214                         printmatrix4 ("difmat", difmat);
215                         printf ("Roll = %f\n",  (-atan(difmat[2][0]/difmat[2][2]) * (180.0/M_PI)));
216 #endif
217                         curBone->roll = -atan(difmat[2][0]/difmat[2][2]);
218                         
219                         if (difmat[0][0]<0.0) curBone->roll +=M_PI;
220                         
221                         /* and set restposition again */
222                         where_is_armature_bone(curBone, curBone->parent);
223                 }
224                 fix_bonelist_roll (&curBone->childbase, editbonelist);
225         }
226 }
227
228 /* converts the editbones back to the armature */
229 static void editbones_to_armature (ListBase *list, Object *ob)
230 {
231         bArmature *arm;
232         EditBone *eBone;
233         Bone    *newBone;
234         Object *obt;
235         
236         arm = get_armature(ob);
237         if (!list) return;
238         if (!arm) return;
239         
240         /* armature bones */
241         free_bones(arm);
242         
243         /*      Copy the bones from the editData into the armature */
244         for (eBone=list->first;eBone;eBone=eBone->next){
245                 newBone= MEM_callocN (sizeof(Bone), "bone");
246                 eBone->temp= newBone;   /* Associate the real Bones with the EditBones */
247                 
248                 strcpy (newBone->name, eBone->name);
249                 memcpy (newBone->head, eBone->head, sizeof(float)*3);
250                 memcpy (newBone->tail, eBone->tail, sizeof(float)*3);
251                 newBone->flag= eBone->flag;
252                 newBone->roll = 0.0f;
253                 
254                 newBone->weight = eBone->weight;
255                 newBone->dist = eBone->dist;
256                 
257                 newBone->xwidth = eBone->xwidth;
258                 newBone->zwidth = eBone->zwidth;
259                 newBone->ease1= eBone->ease1;
260                 newBone->ease2= eBone->ease2;
261                 newBone->rad_head= eBone->rad_head;
262                 newBone->rad_tail= eBone->rad_tail;
263                 newBone->segments= eBone->segments;
264                 newBone->boneclass = eBone->boneclass;
265                 
266         }
267         
268         /*      Fix parenting in a separate pass to ensure ebone->bone connections
269                 are valid at this point */
270         for (eBone=list->first;eBone;eBone=eBone->next) {
271                 newBone= (Bone*) eBone->temp;
272                 if (eBone->parent){
273                         newBone->parent=(Bone*) eBone->parent->temp;
274                         BLI_addtail (&newBone->parent->childbase,newBone);
275                         
276                         {
277                                 float M_boneRest[3][3];
278                                 float M_parentRest[3][3];
279                                 float iM_parentRest[3][3];
280                                 float   delta[3];
281                                 
282                                 /* Get the parent's  matrix (rotation only) */
283                                 VecSubf (delta, eBone->parent->tail, eBone->parent->head);
284                                 vec_roll_to_mat3(delta, eBone->parent->roll, M_parentRest);
285                                 
286                                 /* Get this bone's  matrix (rotation only) */
287                                 VecSubf (delta, eBone->tail, eBone->head);
288                                 vec_roll_to_mat3(delta, eBone->roll, M_boneRest);
289                                 
290                                 /* Invert the parent matrix */
291                                 Mat3Inv(iM_parentRest, M_parentRest);
292                                 
293                                 /* Get the new head and tail */
294                                 VecSubf (newBone->head, eBone->head, eBone->parent->tail);
295                                 VecSubf (newBone->tail, eBone->tail, eBone->parent->tail);
296
297                                 Mat3MulVecfl(iM_parentRest, newBone->head);
298                                 Mat3MulVecfl(iM_parentRest, newBone->tail);
299                         }
300                 }
301                 /*      ...otherwise add this bone to the armature's bonebase */
302                 else
303                         BLI_addtail (&arm->bonebase,newBone);
304         }
305         
306         /* Make a pass through the new armature to fix rolling */
307         /* also builds restposition again (like where_is_armature) */
308         fix_bonelist_roll (&arm->bonebase, list);
309         
310         /* so all users of this armature should get rebuilt */
311         for(obt= G.main->object.first; obt; obt= obt->id.next) {
312                 if(obt->data==arm)
313                         armature_rebuild_pose(obt, arm);
314         }
315         
316         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
317 }
318
319
320
321 void apply_rot_armature (Object *ob, float mat[3][3])
322 {
323         ListBase        list;
324         EditBone *ebone;
325         bArmature *arm;
326
327         arm = get_armature(ob);
328
329         if (!arm)
330                 return;
331
332         /* Put the armature into editmode */
333         list.first= list.last = NULL;
334         make_boneList(&list, &arm->bonebase, NULL);
335
336         /* Do the rotations */
337         for (ebone = list.first; ebone; ebone=ebone->next){
338                 Mat3MulVecfl(mat, ebone->head);
339                 Mat3MulVecfl(mat, ebone->tail);
340         }
341         
342         /* Turn the list into an armature */
343         editbones_to_armature(&list, ob);
344         
345         /* Free the editbones */
346         if (list.first){
347                 BLI_freelistN (&list);
348         }
349 }
350
351 void join_armature(void)
352 {
353         Object  *ob;
354         Base    *base, *nextbase;
355         ListBase eblist;
356         EditBone *curbone, *next;
357         float   mat[4][4], imat[4][4];
358         
359         /*      Ensure we're not in editmode and that the active object is an armature*/
360         if(G.obedit) return;
361         
362         ob= OBACT;
363         if(ob->type!=OB_ARMATURE) return;
364         
365         /*      Make sure the user wants to continue*/
366         if(okee("Join selected armatures")==0) return;
367         
368         /*      Put the active armature into editmode and join the bones from the other one*/
369
370         enter_editmode();
371         
372         for (base=FIRSTBASE; base; base=nextbase) {
373                 nextbase = base->next;
374                 if (TESTBASE(base)){
375                         if ((base->object->type==OB_ARMATURE) && (base->object!=ob)){
376                                 /* Make a list of editbones */
377                                 eblist.first=eblist.last= NULL;
378                                 make_boneList (&eblist, &((bArmature*)base->object->data)->bonebase,NULL);
379                                 /* Find the difference matrix */
380                                 Mat4Invert(imat, ob->obmat);
381                                 Mat4MulMat4(mat, base->object->obmat, imat);
382                                 
383                                 /* Copy bones from the object to the edit armature */
384                                 for (curbone=eblist.first; curbone; curbone=next){
385                                         next = curbone->next;
386
387                                         unique_editbone_name (curbone->name);
388                                         
389                                         /* Transform the bone */
390                                         {
391                                                 float premat[4][4];
392                                                 float postmat[4][4];
393                                                 float difmat[4][4];
394                                                 float imat[4][4];
395                                                 float temp[3][3];
396                                                 float delta[3];
397                                                 
398                                                 /* Get the premat */
399                                                 VecSubf (delta, curbone->tail, curbone->head);
400                                                 vec_roll_to_mat3(delta, curbone->roll, temp);
401                                                 
402                                                 Mat4MulMat34 (premat, temp, mat);
403                                                 
404                                                 Mat4MulVecfl(mat, curbone->head);
405                                                 Mat4MulVecfl(mat, curbone->tail);
406                                                 
407                                                 /* Get the postmat */
408                                                 VecSubf (delta, curbone->tail, curbone->head);
409                                                 vec_roll_to_mat3(delta, curbone->roll, temp);
410                                                 Mat4CpyMat3(postmat, temp);
411                                                 
412                                                 /* Find the roll */
413                                                 Mat4Invert (imat, premat);
414                                                 Mat4MulMat4 (difmat, postmat, imat);
415                                                 
416                                                 curbone->roll -=atan(difmat[2][0]/difmat[2][2]);
417                                                 
418                                                 if (difmat[0][0]<0)
419                                                         curbone->roll +=M_PI;
420                                                 
421                                         }
422                                         BLI_remlink(&eblist, curbone);
423                                         BLI_addtail(&G.edbo, curbone);
424                                 }
425                                 
426                                 free_and_unlink_base(base);
427                         }
428                 }
429         }
430         
431         DAG_scene_sort(G.scene);        // because we removed object(s)
432         
433         exit_editmode(1);
434         allqueue(REDRAWVIEW3D, 0);
435         allqueue(REDRAWOOPS, 0);
436
437 }
438
439 /* **************** END tools on Editmode Armature **************** */
440 /* **************** PoseMode & EditMode *************************** */
441
442 /* only for opengl selection indices */
443 Bone *get_indexed_bone (Object *ob, int index)
444 {
445         bPoseChannel *pchan;
446         int a= 0;
447         
448         if(ob->pose==NULL) return NULL;
449         index>>=16;             // bone selection codes use left 2 bytes
450         
451         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next, a++) {
452                 if(a==index) return pchan->bone;
453         }
454         return NULL;
455 }
456
457 /* See if there are any selected bones in this buffer */
458 static void *get_bone_from_selectbuffer(Base *base, unsigned int *buffer, short hits, short findunsel)
459 {
460         Object *ob= base->object;
461         Bone *bone;
462         EditBone *ebone;
463         void *firstunSel=NULL, *firstSel=NULL, *data;
464         unsigned int hitresult;
465         short i, takeNext=0, sel;
466         
467         for (i=0; i< hits; i++){
468                 hitresult = buffer[3+(i*4)];
469                 
470                 if (!(hitresult & BONESEL_NOSEL)) {     // -1
471                         if(hitresult & BONESEL_ANY) {   // to avoid including objects in selection
472                                 
473                                 hitresult &= ~(BONESEL_ANY);
474                                 /* Determine what the current bone is */
475                                 if (G.obedit==NULL) {
476                                         /* no singular posemode, so check for correct object */
477                                         if(base->selcol == (hitresult & 0xFFFF)) {
478                                                 bone = get_indexed_bone(ob, hitresult);
479
480                                                 if (findunsel)
481                                                         sel = (bone->flag & BONE_SELECTED);
482                                                 else
483                                                         sel = !(bone->flag & BONE_SELECTED);
484                                                 
485                                                 data = bone;
486                                         }
487                                         else {
488                                                 data= NULL;
489                                                 sel= 0;
490                                         }
491                                 }
492                                 else{
493                                         ebone = BLI_findlink(&G.edbo, hitresult);
494                                         if (findunsel)
495                                                 sel = (ebone->flag & BONE_SELECTED);
496                                         else
497                                                 sel = !(ebone->flag & BONE_SELECTED);
498                                         
499                                         data = ebone;
500                                 }
501                                 
502                                 if(data) {
503                                         if (sel) {
504                                                 if(!firstSel) firstSel= data;
505                                                 takeNext=1;
506                                         }
507                                         else {
508                                                 if (!firstunSel)
509                                                         firstunSel=data;
510                                                 if (takeNext)
511                                                         return data;
512                                         }
513                                 }
514                         }
515                 }
516         }
517         
518         if (firstunSel)
519                 return firstunSel;
520         else 
521                 return firstSel;
522 }
523
524 /* used by posemode as well editmode */
525 static void *get_nearest_bone (short findunsel)
526 {
527         unsigned int buffer[MAXPICKBUF];
528         short hits;
529         
530         persp(PERSP_VIEW);
531         
532         glInitNames();
533         hits= view3d_opengl_select(buffer, MAXPICKBUF, 0, 0, 0, 0);
534
535         if (hits)
536                 return get_bone_from_selectbuffer(BASACT, buffer, hits, findunsel);
537         
538         return NULL;
539 }
540
541
542 /* **************** END PoseMode & EditMode *************************** */
543 /* **************** Posemode stuff ********************** */
544
545 static int select_bonechildren_by_name (Bone *bone, char *name, int select)
546 {
547         Bone *curBone;
548
549         if (!strcmp (bone->name, name)){
550                 if (select)
551                         bone->flag |= BONE_SELECTED;
552                 else
553                         bone->flag &= ~(BONE_SELECTED|BONE_ACTIVE);
554                 return 1;
555         }
556
557         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
558                 if (select_bonechildren_by_name (curBone, name, select))
559                         return 1;
560         }
561
562         return 0;
563 }
564
565 /* called in editaction.c */
566 void select_bone_by_name (bArmature *arm, char *name, int select)
567 {
568         Bone *bone;
569         
570         if (!arm)
571                 return;
572         
573         for (bone=arm->bonebase.first; bone; bone=bone->next)
574                 if (select_bonechildren_by_name (bone, name, select))
575                         break;
576 }
577
578 static void selectconnected_posebonechildren (Object *ob, Bone *bone)
579 {
580         Bone *curBone;
581         
582         if (!(bone->flag & BONE_CONNECTED))
583                 return;
584         
585         select_actionchannel_by_name (ob->action, bone->name, !(G.qual & LR_SHIFTKEY));
586         
587         if (G.qual & LR_SHIFTKEY)
588                 bone->flag &= ~BONE_SELECTED;
589         else
590                 bone->flag |= BONE_SELECTED;
591         
592         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
593                 selectconnected_posebonechildren (ob, curBone);
594         }
595 }
596
597 /* within active object context */
598 void selectconnected_posearmature(void)
599 {
600         Bone *bone, *curBone, *next;
601         Object *ob= OBACT;
602         
603         if(!ob || !ob->pose) return;
604         
605         if (G.qual & LR_SHIFTKEY)
606                 bone= get_nearest_bone(0);
607         else
608                 bone = get_nearest_bone(1);
609         
610         if (!bone)
611                 return;
612         
613         /* Select parents */
614         for (curBone=bone; curBone; curBone=next){
615                 select_actionchannel_by_name (ob->action, curBone->name, !(G.qual & LR_SHIFTKEY));
616                 if (G.qual & LR_SHIFTKEY)
617                         curBone->flag &= ~BONE_SELECTED;
618                 else
619                         curBone->flag |= BONE_SELECTED;
620                 
621                 if (curBone->flag & BONE_CONNECTED)
622                         next=curBone->parent;
623                 else
624                         next=NULL;
625         }
626         
627         /* Select children */
628         for (curBone=bone->childbase.first; curBone; curBone=next){
629                 selectconnected_posebonechildren (ob, curBone);
630         }
631         
632         countall(); // flushes selection!
633
634         allqueue (REDRAWVIEW3D, 0);
635         allqueue(REDRAWBUTSEDIT, 0);
636         allqueue(REDRAWBUTSOBJECT, 0);
637         allqueue (REDRAWACTION, 0);
638         allqueue(REDRAWOOPS, 0);
639         BIF_undo_push("Select connected");
640
641 }
642
643 static int count_bonechildren (Bone *bone, int incount, int flagmask, int allbones){
644         
645         Bone    *curBone;
646         
647         if (!bone)
648                 return incount;
649         
650         if (bone->flag & flagmask || flagmask == 0xFFFFFFFF){
651                 incount++;
652                 if (!allbones)
653                         return incount;
654         }
655         
656         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
657                 incount=count_bonechildren (curBone, incount, flagmask, allbones);
658         }
659         
660         return incount;
661 }
662
663 static int      count_bones (bArmature *arm, int flagmask, int allbones)
664 {
665         int     count=0;
666         Bone    *curBone;
667         
668         if (!arm)
669                 return 0;
670         
671         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next){
672                 count = count_bonechildren (curBone, count, flagmask, allbones);
673         }
674         
675         return count;
676         
677 }
678
679 /* **************** END Posemode stuff ********************** */
680 /* **************** EditMode stuff ********************** */
681
682 /* called in space.c */
683 void selectconnected_armature(void)
684 {
685         EditBone *bone, *curBone, *next;
686
687         if (G.qual & LR_SHIFTKEY)
688                 bone= get_nearest_bone(0);
689         else
690                 bone= get_nearest_bone(1);
691
692         if (!bone)
693                 return;
694
695         /* Select parents */
696         for (curBone=bone; curBone; curBone=next){
697                 if (G.qual & LR_SHIFTKEY){
698                         curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
699                 }
700                 else{
701                         curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
702                 }
703
704                 if (curBone->flag & BONE_CONNECTED)
705                         next=curBone->parent;
706                 else
707                         next=NULL;
708         }
709
710         /* Select children */
711         while (bone){
712                 for (curBone=G.edbo.first; curBone; curBone=next){
713                         next = curBone->next;
714                         if (curBone->parent == bone){
715                                 if (curBone->flag & BONE_CONNECTED){
716                                         if (G.qual & LR_SHIFTKEY)
717                                                 curBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
718                                         else
719                                                 curBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
720                                         bone=curBone;
721                                         break;
722                                 }
723                                 else{ 
724                                         bone=NULL;
725                                         break;
726                                 }
727                         }
728                 }
729                 if (!curBone)
730                         bone=NULL;
731
732         }
733
734         countall(); // flushes selection!
735
736         allqueue (REDRAWVIEW3D, 0);
737         allqueue (REDRAWBUTSEDIT, 0);
738         allqueue(REDRAWBUTSOBJECT, 0);
739         allqueue(REDRAWOOPS, 0);
740         
741         BIF_undo_push("Select connected");
742
743 }
744
745 /* does bones and points */
746 /* note that BONE ROOT only gets drawn for root bones (or without IK) */
747 static EditBone * get_nearest_editbonepoint (int findunsel, int *selmask)
748 {
749         EditBone *ebone;
750         unsigned int buffer[MAXPICKBUF];
751         unsigned int hitresult, besthitresult=BONESEL_NOSEL;
752         int i, mindep= 4;
753         short hits, mval[2];
754
755         persp(PERSP_VIEW);
756
757         glInitNames();
758         
759         getmouseco_areawin(mval);
760         hits= view3d_opengl_select(buffer, MAXPICKBUF, mval[0]-5, mval[1]-5, mval[0]+5, mval[1]+5);
761         if(hits==0)
762                 hits= view3d_opengl_select(buffer, MAXPICKBUF, mval[0]-12, mval[1]-12, mval[0]+12, mval[1]+12);
763                 
764         /* See if there are any selected bones in this group */
765         if (hits) {
766                 
767                 if(hits==1) {
768                         if (!(buffer[3] & BONESEL_NOSEL)) 
769                                 besthitresult= buffer[3];
770                 }
771                 else {
772                         for (i=0; i< hits; i++) {
773                                 hitresult= buffer[3+(i*4)];
774                                 if (!(hitresult & BONESEL_NOSEL)) {
775                                         int dep;
776                                         
777                                         ebone = BLI_findlink(&G.edbo, hitresult & ~BONESEL_ANY);
778                                         
779                                         /* clicks on bone points get advantage */
780                                         if( hitresult & (BONESEL_ROOT|BONESEL_TIP)) {
781                                                 /* but also the unselected one */
782                                                 if(findunsel) {
783                                                         if( (hitresult & BONESEL_ROOT) && (ebone->flag & BONE_ROOTSEL)==0) 
784                                                                 dep= 1;
785                                                         else if( (hitresult & BONESEL_TIP) && (ebone->flag & BONE_TIPSEL)==0) 
786                                                                 dep= 1;
787                                                         else 
788                                                                 dep= 2;
789                                                 }
790                                                 else dep= 2;
791                                         }
792                                         else {
793                                                 /* bone found */
794                                                 if(findunsel) {
795                                                         if((ebone->flag & BONE_SELECTED)==0)
796                                                                 dep= 2;
797                                                         else
798                                                                 dep= 3;
799                                                 }
800                                                 else dep= 3;
801                                         }
802                                         if(dep < mindep) {
803                                                 mindep= dep;
804                                                 besthitresult= hitresult;
805                                         }
806                                 }
807                         }
808                 }
809                 
810                 if (!(besthitresult & BONESEL_NOSEL)) {
811                         
812                         ebone= BLI_findlink(&G.edbo, besthitresult & ~BONESEL_ANY);
813                         
814                         *selmask = 0;
815                         if (besthitresult & BONESEL_ROOT)
816                                 *selmask |= BONE_ROOTSEL;
817                         if (besthitresult & BONESEL_TIP)
818                                 *selmask |= BONE_TIPSEL;
819                         if (besthitresult & BONESEL_BONE)
820                                 *selmask |= BONE_SELECTED;
821                         return ebone;
822                 }
823         }
824         *selmask = 0;
825         return NULL;
826 }
827
828 static void delete_bone(EditBone* exBone)
829 {
830         EditBone        *curBone;
831         
832         /*      Find any bones that refer to this bone  */
833         for (curBone=G.edbo.first;curBone;curBone=curBone->next){
834                 if (curBone->parent==exBone){
835                         curBone->parent=exBone->parent;
836                         curBone->flag &= ~BONE_CONNECTED;
837                 }
838         }
839         
840         BLI_freelinkN (&G.edbo,exBone);
841 }
842
843 static EditBone *editbone_name_exists (char *name);     // proto for below
844
845 /* only editmode! */
846 void delete_armature(void)
847 {
848         EditBone        *curBone, *next;
849         bConstraint *con;
850         
851         TEST_EDITARMATURE;
852         if(okee("Erase selected bone(s)")==0) return;
853         
854         /*  First rase any associated pose channel */
855         if (G.obedit->pose){
856                 bPoseChannel *chan, *next;
857                 for (chan=G.obedit->pose->chanbase.first; chan; chan=next) {
858                         next= chan->next;
859                         curBone = editbone_name_exists (chan->name);
860                         
861                         if (curBone && (curBone->flag&BONE_SELECTED)) {
862                                 free_constraints(&chan->constraints);
863                                 BLI_freelinkN (&G.obedit->pose->chanbase, chan);
864                         }
865                         else {
866                                 for(con= chan->constraints.first; con; con= con->next) {
867                                         char *subtarget = get_con_subtarget_name(con, G.obedit);
868                                         if (subtarget) {
869                                                 curBone = editbone_name_exists (subtarget);
870                                                 if (curBone && (curBone->flag&BONE_SELECTED)) {
871                                                         con->flag |= CONSTRAINT_DISABLE;
872                                                         subtarget[0]= 0;
873                                                 }
874                                         }
875                                 }
876                         }
877                 }
878         }
879         
880         
881         for (curBone=G.edbo.first;curBone;curBone=next){
882                 next=curBone->next;
883                 if (curBone->flag&BONE_SELECTED)
884                         delete_bone(curBone);
885         }
886         
887         
888         allqueue(REDRAWVIEW3D, 0);
889         allqueue(REDRAWBUTSEDIT, 0);
890         allqueue(REDRAWBUTSOBJECT, 0);
891         allqueue(REDRAWOOPS, 0);
892         countall(); // flushes selection!
893         
894         BIF_undo_push("Delete bone(s)");
895 }
896
897 /* context: editmode armature */
898 void mouse_armature(void)
899 {
900         EditBone *nearBone = NULL, *ebone;
901         int     selmask;
902
903         nearBone= get_nearest_editbonepoint(1, &selmask);
904         if (nearBone) {
905                 
906                 if (!(G.qual & LR_SHIFTKEY)) {
907                         deselectall_armature(0);
908                 }
909                 
910                 /* by definition the non-root connected bones have no root point drawn,
911                so a root selection needs to be delivered to the parent tip,
912                countall() (bad location) flushes these flags */
913                 
914                 if(selmask & BONE_SELECTED) {
915                         if(nearBone->parent && (nearBone->flag & BONE_CONNECTED)) {
916                                 /* click in a chain */
917                                 if(G.qual & LR_SHIFTKEY) {
918                                         /* hold shift inverts this bone's selection */
919                                         if(nearBone->flag & BONE_SELECTED) {
920                                                 /* deselect this bone */
921                                                 nearBone->flag &= ~(BONE_TIPSEL|BONE_SELECTED);
922                                                 /* only deselect parent tip if it is not selected */
923                                                 if(!(nearBone->parent->flag & BONE_SELECTED))
924                                                         nearBone->parent->flag &= ~BONE_TIPSEL;
925                                         }
926                                         else {
927                                                 /* select this bone */
928                                                 nearBone->flag |= BONE_TIPSEL;
929                                                 nearBone->parent->flag |= BONE_TIPSEL;
930                                         }
931                                 }
932                                 else {
933                                         /* select this bone */
934                                         nearBone->flag |= BONE_TIPSEL;
935                                         nearBone->parent->flag |= BONE_TIPSEL;
936                                 }
937                         }
938                         else {
939                                 if(G.qual & LR_SHIFTKEY) {
940                                         /* hold shift inverts this bone's selection */
941                                         if(nearBone->flag & BONE_SELECTED)
942                                            nearBone->flag &= ~(BONE_TIPSEL|BONE_ROOTSEL);
943                                         else
944                                                 nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
945                                 }
946                                 else nearBone->flag |= (BONE_TIPSEL|BONE_ROOTSEL);
947                         }
948                 }
949                 else {
950                         if ((G.qual & LR_SHIFTKEY) && (nearBone->flag & selmask))
951                                 nearBone->flag &= ~selmask;
952                         else
953                                 nearBone->flag |= selmask;
954                 }
955
956                 countall(); // flushes selection!
957                 
958                 if(nearBone) {
959                         /* then now check for active status */
960                         for (ebone=G.edbo.first;ebone;ebone=ebone->next) ebone->flag &= ~BONE_ACTIVE;
961                         if(nearBone->flag & BONE_SELECTED) nearBone->flag |= BONE_ACTIVE;
962                 }
963                 
964                 allqueue(REDRAWVIEW3D, 0);
965                 allqueue(REDRAWBUTSEDIT, 0);
966                 allqueue(REDRAWBUTSOBJECT, 0);
967                 allqueue(REDRAWOOPS, 0);
968         }
969
970         rightmouse_transform();
971 }
972
973 void free_editArmature(void)
974 {
975         
976         /*      Clear the editbones list */
977         if (G.edbo.first){
978                 BLI_freelistN (&G.edbo);
979         }
980 }
981
982 void remake_editArmature(void)
983 {
984         if(okee("Reload original data")==0) return;
985         
986         make_editArmature();
987         allqueue(REDRAWVIEW3D, 0);
988         allqueue(REDRAWOOPS, 0);
989         allqueue(REDRAWBUTSHEAD, 0);
990         allqueue(REDRAWBUTSEDIT, 0);
991         allqueue(REDRAWBUTSOBJECT, 0);
992         
993 //      BIF_undo_push("Delete bone");
994
995 }
996
997 /* Put object in EditMode */
998 void make_editArmature(void)
999 {
1000         bArmature       *arm;
1001         
1002         if (G.obedit==0) return;
1003         
1004         free_editArmature();
1005         
1006         arm= get_armature(G.obedit);
1007         if (!arm)
1008                 return;
1009         
1010         make_boneList (&G.edbo, &arm->bonebase,NULL);
1011 }
1012
1013 /* put EditMode back in Object */
1014 void load_editArmature(void)
1015 {
1016         bArmature               *arm;
1017
1018         arm= get_armature(G.obedit);
1019         if (!arm) return;
1020         
1021         editbones_to_armature(&G.edbo, G.obedit);
1022 }
1023
1024 /* toggle==0: deselect
1025    toggle==1: swap 
1026    toggle==2: only active tag
1027 */
1028 void deselectall_armature(int toggle)
1029 {
1030         EditBone        *eBone;
1031         int                     sel=1;
1032
1033         if(toggle==1) {
1034                 /*      Determine if there are any selected bones
1035                         And therefore whether we are selecting or deselecting */
1036                 for (eBone=G.edbo.first;eBone;eBone=eBone->next){
1037                         if (eBone->flag & (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL)){
1038                                 sel=0;
1039                                 break;
1040                         }
1041                 }
1042         }
1043         else sel= toggle;
1044         
1045         /*      Set the flags */
1046         for (eBone=G.edbo.first;eBone;eBone=eBone->next){
1047                 if (sel==1)
1048                         eBone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
1049                 else if (sel==2)
1050                         eBone->flag &= ~(BONE_ACTIVE);
1051                 else
1052                         eBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL | BONE_ACTIVE);
1053         }
1054         
1055         allqueue(REDRAWVIEW3D, 0);
1056         allqueue(REDRAWBUTSEDIT, 0);
1057         allqueue(REDRAWBUTSOBJECT, 0);
1058         allqueue(REDRAWOOPS, 0);
1059         
1060         countall(); // flushes selection!
1061 }
1062
1063 void auto_align_armature(void)
1064 /* Sets the roll value of selected bones so that their zaxes point upwards */
1065 {
1066         EditBone *ebone;
1067         float   xaxis[3]={1.0, 0.0, 0.0}, yaxis[3], zaxis[3]={0.0, 0.0, 1.0};
1068         float   targetmat[3][3], imat[3][3];
1069         float   curmat[3][3], diffmat[3][3];
1070         float   delta[3];
1071         
1072         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1073                 if (ebone->flag & BONE_SELECTED){
1074                         /* Find the current bone matrix */
1075                         VecSubf(delta, ebone->tail, ebone->head);
1076                         vec_roll_to_mat3(delta, 0.0, curmat);
1077                         
1078                         /* Make new matrix based on y axis & z-up */
1079                         VECCOPY (yaxis, curmat[1]);
1080                         
1081                         Mat3One(targetmat);
1082                         VECCOPY (targetmat[0], xaxis);
1083                         VECCOPY (targetmat[1], yaxis);
1084                         VECCOPY (targetmat[2], zaxis);
1085                         Mat3Ortho(targetmat);
1086                         
1087                         /* Find the difference between the two matrices */
1088                         Mat3Inv(imat, targetmat);
1089                         Mat3MulMat3(diffmat, imat, curmat);
1090                         
1091                         ebone->roll = atan(diffmat[2][0]/diffmat[2][2]);
1092                         
1093                 }
1094         }
1095 }
1096
1097 /* **************** undo for armatures ************** */
1098
1099 static void undoBones_to_editBones(void *lbv)
1100 {
1101         ListBase *lb= lbv;
1102         EditBone *ebo, *newebo;
1103         
1104         BLI_freelistN(&G.edbo);
1105         
1106         /* copy  */
1107         for(ebo= lb->first; ebo; ebo= ebo->next) {
1108                 newebo= MEM_dupallocN(ebo);
1109                 ebo->temp= newebo;
1110                 BLI_addtail(&G.edbo, newebo);
1111         }
1112         
1113         /* set pointers */
1114         for(newebo= G.edbo.first; newebo; newebo= newebo->next) {
1115                 if(newebo->parent) newebo->parent= newebo->parent->temp;
1116         }
1117         /* be sure they dont hang ever */
1118         for(newebo= G.edbo.first; newebo; newebo= newebo->next) {
1119                 newebo->temp= NULL;
1120         }
1121 }
1122
1123 static void *editBones_to_undoBones(void)
1124 {
1125         ListBase *lb;
1126         EditBone *ebo, *newebo;
1127         
1128         lb= MEM_callocN(sizeof(ListBase), "listbase undo");
1129         
1130         /* copy  */
1131         for(ebo= G.edbo.first; ebo; ebo= ebo->next) {
1132                 newebo= MEM_dupallocN(ebo);
1133                 ebo->temp= newebo;
1134                 BLI_addtail(lb, newebo);
1135         }
1136         
1137         /* set pointers */
1138         for(newebo= lb->first; newebo; newebo= newebo->next) {
1139                 if(newebo->parent) newebo->parent= newebo->parent->temp;
1140         }
1141         
1142         return lb;
1143 }
1144
1145 static void free_undoBones(void *lbv)
1146 {
1147         ListBase *lb= lbv;
1148         
1149         BLI_freelistN(lb);
1150         MEM_freeN(lb);
1151 }
1152
1153 /* and this is all the undo system needs to know */
1154 void undo_push_armature(char *name)
1155 {
1156         undo_editmode_push(name, free_undoBones, undoBones_to_editBones, editBones_to_undoBones);
1157 }
1158
1159
1160
1161 /* **************** END EditMode stuff ********************** */
1162 /* *************** Adding stuff in editmode *************** */
1163
1164 /* default bone add, returns it selected, but without tail set */
1165 static EditBone *add_editbone(char *name)
1166 {
1167         EditBone *bone= MEM_callocN(sizeof(EditBone), "eBone");
1168         
1169         strcpy (bone->name, name);
1170         unique_editbone_name (bone->name);
1171         
1172         BLI_addtail(&G.edbo, bone);
1173         
1174         bone->flag |= BONE_TIPSEL;
1175         bone->weight= 1.0F;
1176         bone->dist= 0.25F;
1177         bone->xwidth= 0.1;
1178         bone->zwidth= 0.1;
1179         bone->ease1= 1.0;
1180         bone->ease2= 1.0;
1181         bone->rad_head= 0.10;
1182         bone->rad_tail= 0.05;
1183         bone->segments= 1;
1184         
1185         return bone;
1186 }
1187
1188 static void add_primitive_bone(Object *ob)
1189 {
1190         float           obmat[3][3], curs[3], viewmat[3][3], totmat[3][3], imat[3][3];
1191         EditBone        *bone;
1192         
1193         VECCOPY (curs, give_cursor());  
1194
1195         /* Get inverse point for head and orientation for tail */
1196         Mat4Invert(G.obedit->imat, G.obedit->obmat);
1197         Mat4MulVecfl(G.obedit->imat, curs);
1198
1199         Mat3CpyMat4(obmat, G.vd->viewmat);
1200         Mat3CpyMat4(viewmat, G.obedit->obmat);
1201         Mat3MulMat3(totmat, obmat, viewmat);
1202         Mat3Inv(imat, totmat);
1203         
1204         deselectall_armature(0);
1205         
1206         /*      Create a bone   */
1207         bone= add_editbone("Bone");
1208
1209         VECCOPY(bone->head, curs);
1210         VecAddf(bone->tail, bone->head, imat[1]);       // bone with unit length 1
1211         
1212 }
1213
1214 void add_primitiveArmature(int type)
1215 {
1216         if(G.scene->id.lib) return;
1217         
1218         /* this function also comes from an info window */
1219         if ELEM(curarea->spacetype, SPACE_VIEW3D, SPACE_INFO); else return;
1220         if(G.vd==NULL) return;
1221         
1222         G.f &= ~(G_VERTEXPAINT+G_FACESELECT+G_TEXTUREPAINT+G_WEIGHTPAINT);
1223         setcursor_space(SPACE_VIEW3D, CURSOR_STD);
1224
1225         check_editmode(OB_ARMATURE);
1226         
1227         /* If we're not the "obedit", make a new object and enter editmode */
1228         if(G.obedit==NULL) {
1229                 add_object(OB_ARMATURE);
1230                 base_init_from_view3d(BASACT, G.vd);
1231                 G.obedit= BASACT->object;
1232                 
1233                 where_is_object(G.obedit);
1234                 
1235                 make_editArmature();
1236                 setcursor_space(SPACE_VIEW3D, CURSOR_EDIT);
1237         }
1238         
1239         /* no primitive support yet */
1240         add_primitive_bone(G.obedit);
1241         
1242         countall(); // flushes selection!
1243
1244         allqueue(REDRAWALL, 0);
1245         BIF_undo_push("Add primitive");
1246 }
1247
1248 /* the ctrl-click method */
1249 void addvert_armature(void)
1250 {
1251         bArmature *arm= G.obedit->data;
1252         EditBone *ebone, *newbone, *flipbone;
1253         float *curs, mat[3][3],imat[3][3];
1254         int a, to_root= 0;
1255         
1256         TEST_EDITARMATURE;
1257         
1258         /* find the active or selected bone */
1259         for (ebone = G.edbo.first; ebone; ebone=ebone->next)
1260                 if(ebone->flag & (BONE_ACTIVE|BONE_TIPSEL)) break;
1261         
1262         if(ebone==NULL) {
1263                 for (ebone = G.edbo.first; ebone; ebone=ebone->next)
1264                         if(ebone->flag & (BONE_ACTIVE|BONE_ROOTSEL)) break;
1265                 
1266                 if(ebone==NULL) 
1267                         return;
1268                 to_root= 1;
1269         }
1270         
1271         deselectall_armature(0);
1272         
1273         /* we re-use code for mirror editing... */
1274         flipbone= NULL;
1275         if(arm->flag & ARM_MIRROR_EDIT)
1276                 flipbone= armature_bone_get_mirrored(ebone);
1277
1278         for(a=0; a<2; a++) {
1279                 if(a==1) {
1280                         if(flipbone==NULL)
1281                                 break;
1282                         else {
1283                                 SWAP(EditBone *, flipbone, ebone);
1284                         }
1285                 }
1286                 
1287                 newbone= add_editbone(ebone->name);
1288                 newbone->flag |= BONE_ACTIVE;
1289                 
1290                 if(to_root) {
1291                         VECCOPY(newbone->head, ebone->head);
1292                         newbone->rad_head= ebone->rad_tail;
1293                         newbone->parent= ebone->parent;
1294                 }
1295                 else {
1296                         VECCOPY(newbone->head, ebone->tail);
1297                         newbone->rad_head= ebone->rad_tail;
1298                         newbone->parent= ebone;
1299                         newbone->flag |= BONE_CONNECTED;
1300                 }
1301                 
1302                 curs= give_cursor();
1303                 VECCOPY(newbone->tail, curs);
1304                 VecSubf(newbone->tail, newbone->tail, G.obedit->obmat[3]);
1305                 
1306                 if(a==1) 
1307                         newbone->tail[0]= -newbone->tail[0];
1308                 
1309                 Mat3CpyMat4(mat, G.obedit->obmat);
1310                 Mat3Inv(imat, mat);
1311                 Mat3MulVecfl(imat, newbone->tail);
1312                 
1313                 newbone->length= VecLenf(newbone->head, newbone->tail);
1314                 newbone->rad_tail= newbone->length*0.05f;
1315                 newbone->dist= newbone->length*0.1f;
1316                 
1317         }
1318         
1319         
1320         countall();
1321         
1322         BIF_undo_push("Add Bone");
1323         allqueue(REDRAWVIEW3D, 0);
1324         
1325         while(get_mbut()&R_MOUSE);
1326 }
1327
1328
1329 void adduplicate_armature(void)
1330 {
1331         EditBone        *eBone = NULL;
1332         EditBone        *curBone;
1333         EditBone        *firstDup=NULL; /*      The beginning of the duplicated bones in the edbo list */
1334         
1335         countall(); // flushes selection!
1336         
1337         /*      Find the selected bones and duplicate them as needed */
1338         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1339                 if (curBone->flag & BONE_SELECTED){
1340                         
1341                         eBone=MEM_callocN(sizeof(EditBone), "addup_editbone");
1342                         eBone->flag |= BONE_SELECTED;
1343                         
1344                         /*      Copy data from old bone to new bone */
1345                         memcpy (eBone, curBone, sizeof(EditBone));
1346                         
1347                         curBone->temp = eBone;
1348                         eBone->temp = curBone;
1349                         
1350                         unique_editbone_name (eBone->name);
1351                         BLI_addtail (&G.edbo, eBone);
1352                         if (!firstDup)
1353                                 firstDup=eBone;
1354                         
1355                         /* Lets duplicate the list of constraits that the
1356                                 * current bone has.
1357                                 */
1358                         /* temporal removed (ton) */
1359                 }
1360         }
1361
1362         /*      Run though the list and fix the pointers */
1363         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1364                 
1365                 if (curBone->flag & BONE_SELECTED){
1366                         eBone=(EditBone*) curBone->temp;
1367                         
1368                         /*      If this bone has no parent,
1369                         Set the duplicate->parent to NULL
1370                         */
1371                         if (!curBone->parent){
1372                                 eBone->parent = NULL;
1373                         }
1374                         /*      If this bone has a parent that IS selected,
1375                                 Set the duplicate->parent to the curBone->parent->duplicate
1376                                 */
1377                         else if (curBone->parent->flag & BONE_SELECTED){
1378                                 eBone->parent=(EditBone*) curBone->parent->temp;
1379                         }
1380                         /*      If this bone has a parent that IS not selected,
1381                                 Set the duplicate->parent to the curBone->parent
1382                                 */
1383                         else {
1384                                 eBone->parent=(EditBone*) curBone->parent; 
1385                                 eBone->flag &= ~BONE_CONNECTED;
1386                         }
1387                         
1388                         /* Lets try to fix any constraint subtargets that might
1389                                 have been duplicated */
1390                         /* temporal removed (ton) */
1391                         
1392                 }
1393         } 
1394         
1395         /*      Deselect the old bones and select the new ones */
1396         
1397         for (curBone=G.edbo.first; curBone && curBone!=firstDup; curBone=curBone->next){
1398                 curBone->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL | BONE_ACTIVE);
1399         }
1400         
1401         BIF_TransformSetUndo("Add Duplicate");
1402         initTransform(TFM_TRANSLATION, CTX_NO_PET);
1403         Transform();
1404         
1405         allqueue(REDRAWBUTSEDIT, 0);
1406         allqueue(REDRAWBUTSOBJECT, 0);
1407         allqueue(REDRAWOOPS, 0);
1408 }
1409
1410
1411
1412 /* *************** END Adding stuff in editmode *************** */
1413 /* *************** Tools in editmode *********** */
1414
1415
1416 void hide_selected_armature_bones(void)
1417 {
1418         EditBone *ebone;
1419         
1420         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1421                 if(ebone->flag & (BONE_SELECTED)) {
1422                         ebone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
1423                         ebone->flag |= BONE_HIDDEN_A;
1424                 }
1425         }
1426         countall();
1427         allqueue(REDRAWVIEW3D, 0);
1428         allqueue(REDRAWBUTSEDIT, 0);
1429 }
1430
1431 void hide_unselected_armature_bones(void)
1432 {
1433         EditBone *ebone;
1434         
1435         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1436                 if(ebone->flag & (BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL));
1437                 else {
1438                         ebone->flag &= ~BONE_ACTIVE;
1439                         ebone->flag |= BONE_HIDDEN_A;
1440                 }
1441         }
1442         countall();
1443         allqueue(REDRAWVIEW3D, 0);
1444         allqueue(REDRAWBUTSEDIT, 0);
1445 }
1446
1447 void show_all_armature_bones(void)
1448 {
1449         EditBone *ebone;
1450         
1451         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1452                 if(ebone->flag & BONE_HIDDEN_A) {
1453                         ebone->flag |= (BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL);
1454                         ebone->flag &= ~BONE_HIDDEN_A;
1455                 }
1456         }
1457         countall();
1458         allqueue(REDRAWVIEW3D, 0);
1459         allqueue(REDRAWBUTSEDIT, 0);
1460 }
1461
1462 void make_bone_parent(void)
1463 {
1464         EditBone *ebone;
1465         float offset[3];
1466         short val;
1467         
1468         val= pupmenu("Make Parent%t|Connected%x1|Keep Offset%x2");
1469         
1470         if(val<1) return;
1471         
1472         /* find active */
1473         for (ebone = G.edbo.first; ebone; ebone=ebone->next)
1474                 if(ebone->flag & BONE_ACTIVE) break;
1475         if(ebone) {
1476                 EditBone *actbone= ebone, *selbone= NULL;
1477                 
1478                 /* find selected */
1479                 for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1480                         if(ebone->flag & BONE_SELECTED) {
1481                                 if(ebone!=actbone) {
1482                                         if(selbone==NULL) selbone= ebone;
1483                                         else {
1484                                                 error("Need one active and one selected bone");
1485                                                 return;
1486                                         }
1487                                 }
1488                         }
1489                 }
1490                 if(selbone==NULL) {
1491                         /* we make sure bone is connected */
1492                         if(val==1 && actbone->parent) {
1493                                 actbone->flag |= BONE_CONNECTED;
1494                                 VECCOPY(actbone->head, actbone->parent->tail);
1495                                 actbone->rad_head= actbone->parent->rad_tail;
1496                                 countall(); // checks selection
1497                                 allqueue(REDRAWVIEW3D, 0);
1498                                 BIF_undo_push("Connect to Parent");
1499                         }
1500                         else error("Need one active and one selected bone");
1501                 }
1502                 else {
1503                         /* if selbone had a parent we clear parent tip */
1504                         if(selbone->parent && (selbone->flag & BONE_CONNECTED))
1505                            selbone->parent->flag &= ~(BONE_TIPSEL);
1506                         
1507                         selbone->parent= actbone;
1508                         
1509                         /* in actbone tree we cannot have a loop */
1510                         for(ebone= actbone->parent; ebone; ebone= ebone->parent) {
1511                                 if(ebone->parent==selbone) {
1512                                         ebone->parent= NULL;
1513                                         ebone->flag &= ~BONE_CONNECTED;
1514                                 }
1515                         }
1516                         
1517                         if(val==1) {    // connected
1518                                 selbone->flag |= BONE_CONNECTED;
1519                                 VecSubf(offset, actbone->tail, selbone->head);
1520                                 
1521                                 VECCOPY(selbone->head, actbone->tail);
1522                                 selbone->rad_head= actbone->rad_tail;
1523
1524                                 VecAddf(selbone->tail, selbone->tail, offset);
1525                                 
1526                                 // offset for all its children 
1527                                 for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1528                                         EditBone *par;
1529                                         for(par= ebone->parent; par; par= par->parent) {
1530                                                 if(par==selbone) {
1531                                                         VecAddf(ebone->head, ebone->head, offset);
1532                                                         VecAddf(ebone->tail, ebone->tail, offset);
1533                                                         break;
1534                                                 }
1535                                         }
1536                                 }
1537                         }
1538                         else {
1539                                 selbone->flag &= ~BONE_CONNECTED;
1540                         }
1541                         
1542                         countall(); // checks selection
1543                         allqueue(REDRAWVIEW3D, 0);
1544                         allqueue(REDRAWBUTSEDIT, 0);
1545                         allqueue(REDRAWOOPS, 0);
1546                         BIF_undo_push("Make Parent");
1547                 }
1548         }
1549 }
1550
1551 void clear_bone_parent(void)
1552 {
1553         EditBone *ebone;
1554         short val;
1555         
1556         val= pupmenu("Clear Parent%t|Clear Parent%x1|Disconnect Bone%x2");
1557         
1558         if(val<1) return;
1559         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
1560                 if(ebone->flag & BONE_SELECTED) {
1561                         if(ebone->parent) {
1562                                 /* for nice selection */
1563                                 ebone->parent->flag &= ~(BONE_TIPSEL);
1564                                 
1565                                 if(val==1) ebone->parent= NULL;
1566                                 ebone->flag &= ~BONE_CONNECTED;
1567                         }
1568                 }
1569         }
1570         countall(); // checks selection
1571         allqueue(REDRAWVIEW3D, 0);
1572         allqueue(REDRAWBUTSEDIT, 0);
1573         allqueue(REDRAWOOPS, 0);
1574         BIF_undo_push("Clear Parent");
1575 }
1576         
1577
1578 static EditBone *editbone_name_exists (char *name)
1579 {
1580         EditBone        *eBone;
1581         
1582         for (eBone=G.edbo.first; eBone; eBone=eBone->next){
1583                 if (!strcmp (name, eBone->name))
1584                         return eBone;
1585         }
1586         return NULL;
1587 }
1588
1589 /* note: there's a unique_bone_name() too! */
1590 void unique_editbone_name (char *name)
1591 {
1592         char            tempname[64];
1593         int                     number;
1594         char            *dot;
1595         
1596         
1597         if (editbone_name_exists(name)) {
1598                 
1599                 /*      Strip off the suffix, if it's a number */
1600                 number= strlen(name);
1601                 if(number && isdigit(name[number-1])) {
1602                         dot= strrchr(name, '.');        // last occurrance
1603                         if (dot)
1604                                 *dot=0;
1605                 }
1606                 
1607                 for (number = 1; number <=999; number++){
1608                         sprintf (tempname, "%s.%03d", name, number);
1609                         if (!editbone_name_exists(tempname)){
1610                                 strcpy (name, tempname);
1611                                 return;
1612                         }
1613                 }
1614         }
1615 }
1616
1617 /* context; editmode armature */
1618 /* if forked && mirror-edit: makes two bones with flipped names */
1619 void extrude_armature(int forked)
1620 {
1621         bArmature *arm= G.obedit->data;
1622         EditBone *newbone, *ebone, *flipbone, *first=NULL;
1623         int a, totbone= 0, do_extrude;
1624         
1625         TEST_EDITARMATURE;
1626         
1627         /* since we allow root extrude too, we have to make sure selection is OK */
1628         for (ebone = G.edbo.first; ebone; ebone=ebone->next){
1629                 if(ebone->flag & BONE_ROOTSEL) {
1630                         if(ebone->parent && (ebone->flag & BONE_CONNECTED)) {
1631                                 if(ebone->parent->flag & BONE_TIPSEL)
1632                                         ebone->flag &= ~BONE_ROOTSEL;
1633                         }
1634                 }
1635         }
1636         
1637         /* Duplicate the necessary bones */
1638         for (ebone = G.edbo.first; ((ebone) && (ebone!=first)); ebone=ebone->next){
1639                 
1640                 /* we extrude per definition the tip */
1641                 do_extrude= 0;
1642                 if (ebone->flag & (BONE_TIPSEL|BONE_SELECTED))
1643                         do_extrude= 1;
1644                 else if(ebone->flag & BONE_ROOTSEL) {
1645                         /* but, a bone with parent deselected we do the root... */
1646                         if(ebone->parent && (ebone->parent->flag & BONE_TIPSEL));
1647                         else do_extrude= 2;
1648                 }
1649                 
1650                 if (do_extrude) {
1651                         
1652                         /* we re-use code for mirror editing... */
1653                         flipbone= NULL;
1654                         if(arm->flag & ARM_MIRROR_EDIT) {
1655                                 flipbone= armature_bone_get_mirrored(ebone);
1656                                 if (flipbone) {
1657                                         forked= 0;      // we extrude 2 different bones
1658                                         if(flipbone->flag & (BONE_TIPSEL|BONE_ROOTSEL|BONE_SELECTED))
1659                                                 /* don't want this bone to be selected... */
1660                                                 flipbone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
1661                                 }
1662                                 if(flipbone==NULL && forked)
1663                                         flipbone= ebone;
1664                         }
1665                         
1666                         for(a=0; a<2; a++) {
1667                                 if(a==1) {
1668                                         if(flipbone==NULL)
1669                                                 break;
1670                                         else {
1671                                                 SWAP(EditBone *, flipbone, ebone);
1672                                         }
1673                                 }
1674                                 
1675                                 totbone++;
1676                                 newbone = MEM_callocN(sizeof(EditBone), "extrudebone");
1677                                 
1678                                 if(do_extrude==1) {
1679                                         VECCOPY (newbone->head, ebone->tail);
1680                                         VECCOPY (newbone->tail, newbone->head);
1681                                         newbone->parent = ebone;
1682                                         
1683                                         newbone->flag = ebone->flag & BONE_TIPSEL;      // copies it, in case mirrored bone
1684                                 }
1685                                 else {
1686                                         VECCOPY(newbone->head, ebone->head);
1687                                         VECCOPY(newbone->tail, ebone->head);
1688                                         newbone->parent= ebone->parent;
1689                                         
1690                                         newbone->flag= BONE_TIPSEL;
1691                                 }
1692
1693                                 newbone->weight= ebone->weight;
1694                                 newbone->dist= ebone->dist;
1695                                 newbone->xwidth= ebone->xwidth;
1696                                 newbone->zwidth= ebone->zwidth;
1697                                 newbone->ease1= ebone->ease1;
1698                                 newbone->ease2= ebone->ease2;
1699                                 newbone->rad_head= ebone->rad_tail;     // dont copy entire bone...
1700                                 newbone->rad_tail= ebone->rad_tail;
1701                                 newbone->segments= 1;
1702                                 newbone->boneclass= ebone->boneclass;
1703                                 
1704                                 if(newbone->parent) newbone->flag |= BONE_CONNECTED;
1705                                 
1706                                 strcpy (newbone->name, ebone->name);
1707                                 
1708                                 if(flipbone && forked) {        // only set if mirror edit
1709                                         if(strlen(newbone->name)<30) {
1710                                                 if(a==0) strcat(newbone->name, "_L");
1711                                                 else strcat(newbone->name, "_R");
1712                                         }
1713                                 }
1714                                 unique_editbone_name(newbone->name);
1715                                 
1716                                 /* Add the new bone to the list */
1717                                 BLI_addtail(&G.edbo, newbone);
1718                                 if (!first)
1719                                         first = newbone;
1720                                 
1721                                 /* restore ebone if we were flipping */
1722                                 if(a==1 && flipbone) 
1723                                         SWAP(EditBone *, flipbone, ebone);
1724
1725                         }
1726                 }
1727                 
1728                 /* Deselect the old bone */
1729                 ebone->flag &= ~(BONE_TIPSEL|BONE_SELECTED|BONE_ROOTSEL|BONE_ACTIVE);
1730                 
1731         }
1732         /* if only one bone, make this one active */
1733         if(totbone==1 && first) first->flag |= BONE_ACTIVE;
1734         
1735         /* Transform the endpoints */
1736         countall(); // flushes selection!
1737         BIF_TransformSetUndo("Extrude");
1738         initTransform(TFM_TRANSLATION, CTX_NO_PET);
1739         Transform();
1740         
1741         allqueue(REDRAWBUTSEDIT, 0);
1742         allqueue(REDRAWBUTSOBJECT, 0);
1743         allqueue(REDRAWOOPS, 0);
1744 }
1745
1746 /* context; editmode armature */
1747 void subdivide_armature(void)
1748 {
1749         bArmature *arm= G.obedit->data;
1750         EditBone *ebone, *newbone, *tbone, *mbone;
1751         int a;
1752         
1753         for (mbone = G.edbo.last; mbone; mbone= mbone->prev) {
1754                 if(mbone->flag & BONE_SELECTED) {
1755                         
1756                         /* take care of mirrored stuff */
1757                         for(a=0; a<2; a++) {
1758                                 if(a==0) ebone= mbone;
1759                                 else {
1760                                         if(arm->flag & ARM_MIRROR_EDIT)
1761                                                 ebone= armature_bone_get_mirrored(mbone);
1762                                         else ebone= NULL;
1763                                 }
1764                                 if(ebone) {
1765
1766                                         newbone= MEM_mallocN(sizeof(EditBone), "ebone subdiv");
1767                                         *newbone = *ebone;
1768                                         BLI_addtail(&G.edbo, newbone);
1769                                         
1770                                         VecMidf(newbone->head, ebone->head, ebone->tail);
1771                                         VECCOPY(newbone->tail, ebone->tail);
1772                                         VECCOPY(ebone->tail, newbone->head);
1773                                         
1774                                         newbone->rad_head= 0.5*(ebone->rad_head+ebone->rad_tail);
1775                                         ebone->rad_tail= newbone->rad_head;
1776
1777                                         newbone->flag |= BONE_CONNECTED;
1778                                         
1779                                         unique_editbone_name (newbone->name);
1780                                         
1781                                         /* correct parent bones */
1782                                         for (tbone = G.edbo.first; tbone; tbone=tbone->next){
1783                                                 if(tbone->parent==ebone)
1784                                                         tbone->parent= newbone;
1785                                         }
1786                                         newbone->parent= ebone;
1787                                 }
1788                         }
1789                 }
1790         }
1791 }
1792
1793 /* ***************** Pose tools ********************* */
1794
1795 void clear_armature(Object *ob, char mode)
1796 {
1797         bPoseChannel *pchan;
1798         bArmature       *arm;
1799
1800         arm=get_armature(ob);
1801         
1802         if (!arm)
1803                 return;
1804         
1805         for(pchan= ob->pose->chanbase.first; pchan; pchan= pchan->next) {
1806                 if(pchan->bone && (pchan->bone->flag & BONE_SELECTED)) {
1807                         switch (mode){
1808                                 case 'r':
1809                                         pchan->quat[1]=pchan->quat[2]=pchan->quat[3]=0.0F; pchan->quat[0]=1.0F;
1810                                         break;
1811                                 case 'g':
1812                                         pchan->loc[0]=pchan->loc[1]=pchan->loc[2]=0.0F;
1813                                         break;
1814                                 case 's':
1815                                         pchan->size[0]=pchan->size[1]=pchan->size[2]=1.0F;
1816                                         break;
1817                                         
1818                         }
1819                 }
1820         }
1821         
1822         DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
1823         /* no update for this object, this will execute the action again */
1824         /* is weak... like for ipo editing which uses ctime now... */
1825         where_is_pose (ob);
1826         ob->recalc= 0;
1827 }
1828
1829 /* helper for function below */
1830 static int clear_active_flag(Object *ob, Bone *bone, void *data) 
1831 {
1832         bone->flag &= ~BONE_ACTIVE;
1833         return 0;
1834 }
1835
1836
1837 /* called from editview.c, for mode-less pose selection */
1838 int do_pose_selectbuffer(Base *base, unsigned int *buffer, short hits)
1839 {
1840         Object *ob= base->object;
1841         Bone *nearBone;
1842         
1843         if (!ob || !ob->pose) return 0;
1844
1845         nearBone= get_bone_from_selectbuffer(base, buffer, hits, 1);
1846
1847         if (nearBone) {
1848                 if (!(G.qual & LR_SHIFTKEY)){
1849                         deselectall_posearmature(ob, 0);
1850                         nearBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
1851                         select_actionchannel_by_name(ob->action, nearBone->name, 1);
1852                 }
1853                 else {
1854                         if (nearBone->flag & BONE_SELECTED) {
1855                                 /* if not active, we make it active */
1856                                 if((nearBone->flag & BONE_ACTIVE)==0) {
1857                                         bArmature *arm= ob->data;
1858                                         bone_looper(ob, arm->bonebase.first, NULL, clear_active_flag);
1859                                         
1860                                         nearBone->flag |= BONE_ACTIVE;
1861                                 }
1862                                 else {
1863                                         nearBone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
1864                                         select_actionchannel_by_name(ob->action, nearBone->name, 0);
1865                                 }
1866                         }
1867                         else{
1868                                 bArmature *arm= ob->data;
1869                                 bone_looper(ob, arm->bonebase.first, NULL, clear_active_flag);
1870                                 
1871                                 nearBone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
1872                                 select_actionchannel_by_name(ob->action, nearBone->name, 1);
1873                         }
1874                 }
1875                 
1876                 /* in weightpaint we select the associated vertex group too */
1877                 if(G.f & G_WEIGHTPAINT) {
1878                         if(nearBone->flag & BONE_ACTIVE) {
1879                                 vertexgroup_select_by_name(OBACT, nearBone->name);
1880                                 DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA);
1881                         }
1882                 }
1883                 
1884                 allqueue(REDRAWVIEW3D, 0);
1885                 allqueue(REDRAWACTION, 0);
1886                 allqueue(REDRAWIPO, 0);         /* To force action/constraint ipo update */
1887                 allqueue(REDRAWBUTSEDIT, 0);
1888                 allqueue(REDRAWBUTSOBJECT, 0);
1889                 allqueue(REDRAWOOPS, 0);
1890         }
1891         
1892         return nearBone!=NULL;
1893         
1894 }
1895
1896 /*      mode==0: deselect
1897         mode==1: select
1898         mode==2: clear active tag 
1899 */
1900 static void deselect_bonechildren (Object *ob, Bone *bone, int mode)
1901 {
1902         Bone    *curBone;
1903
1904         if (!bone)
1905                 return;
1906
1907         if (mode==0)
1908                 bone->flag &= ~(BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL|BONE_ACTIVE);
1909         else if (mode==1) {
1910                 if(!(bone->flag & BONE_HIDDEN_P))
1911                         bone->flag |= (BONE_SELECTED|BONE_TIPSEL|BONE_ROOTSEL);
1912         }
1913         else bone->flag &= ~BONE_ACTIVE;
1914         
1915         if(mode!=2) select_actionchannel_by_name(ob->action, bone->name, mode);
1916
1917         for (curBone=bone->childbase.first; curBone; curBone=curBone->next){
1918                 deselect_bonechildren(ob, curBone, mode);
1919         }
1920 }
1921
1922 /* test==0: deselect all
1923    test==1: swap select
1924    test==2: only clear active tag 
1925 */
1926 void deselectall_posearmature (Object *ob, int test)
1927 {
1928         bArmature *arm;
1929         Bone *curBone;
1930         int     selectmode= 0;
1931         
1932         /* we call this from outliner too, but with OBACT set OK */
1933         if(!ob || !ob->pose) return;
1934         arm= get_armature(ob);
1935         
1936         /*      Determine if we're selecting or deselecting     */
1937         if (test==1) {
1938                 if (!count_bones (arm, BONE_SELECTED, 0))
1939                         selectmode= 1;
1940         }
1941         else if(test==2)
1942                 selectmode= 2;
1943         
1944         /*      Set the flags accordingly       */
1945         for (curBone=arm->bonebase.first; curBone; curBone=curBone->next)
1946                 deselect_bonechildren (ob, curBone, selectmode);
1947         
1948         allqueue(REDRAWBUTSEDIT, 0);
1949         allqueue(REDRAWBUTSOBJECT, 0);
1950         allqueue(REDRAWVIEW3D, 0);
1951         allqueue(REDRAWOOPS, 0);
1952         allqueue(REDRAWACTION, 0);
1953
1954 }
1955
1956
1957 int bone_looper(Object *ob, Bone *bone, void *data,
1958                         int (*bone_func)(Object *, Bone *, void *)) 
1959 {
1960
1961     /* We want to apply the function bone_func to every bone 
1962      * in an armature -- feed bone_looper the first bone and 
1963      * a pointer to the bone_func and watch it go!. The int count 
1964      * can be useful for counting bones with a certain property
1965      * (e.g. skinnable)
1966      */
1967     int count = 0;
1968
1969     if (bone) {
1970
1971         /* only do bone_func if the bone is non null
1972          */
1973         count += bone_func(ob, bone, data);
1974
1975         /* try to execute bone_func for the first child
1976          */
1977         count += bone_looper(ob, bone->childbase.first, data,
1978                                     bone_func);
1979
1980         /* try to execute bone_func for the next bone at this
1981          * depth of the recursion.
1982          */
1983         count += bone_looper(ob, bone->next, data, bone_func);
1984     }
1985
1986     return count;
1987 }
1988
1989
1990 static int bone_skinnable(Object *ob, Bone *bone, void *data)
1991 {
1992     /* Bones that are deforming
1993      * are regarded to be "skinnable" and are eligible for
1994      * auto-skinning.
1995      *
1996      * This function performs 2 functions:
1997      *
1998      *   a) It returns 1 if the bone is skinnable.
1999      *      If we loop over all bones with this 
2000      *      function, we can count the number of
2001      *      skinnable bones.
2002      *   b) If the pointer data is non null,
2003      *      it is treated like a handle to a
2004      *      bone pointer -- the bone pointer
2005      *      is set to point at this bone, and
2006      *      the pointer the handle points to
2007      *      is incremented to point to the
2008      *      next member of an array of pointers
2009      *      to bones. This way we can loop using
2010      *      this function to construct an array of
2011      *      pointers to bones that point to all
2012      *      skinnable bones.
2013      */
2014     Bone ***hbone;
2015
2016     if (!(bone->flag & BONE_NO_DEFORM)) {
2017                 if (data != NULL) {
2018                         hbone = (Bone ***) data;
2019             **hbone = bone;
2020             ++*hbone;
2021         }
2022         return 1;
2023     }
2024     return 0;
2025 }
2026
2027 static int add_defgroup_unique_bone(Object *ob, Bone *bone, void *data) 
2028 {
2029     /* This group creates a vertex group to ob that has the
2030      * same name as bone (provided the bone is skinnable). 
2031          * If such a vertex group aleady exist the routine exits.
2032      */
2033         if (!(bone->flag & BONE_NO_DEFORM)) {
2034                 if (!get_named_vertexgroup(ob,bone->name)) {
2035                         add_defgroup_name(ob, bone->name);
2036                         return 1;
2037                 }
2038     }
2039     return 0;
2040 }
2041
2042 static int dgroup_skinnable(Object *ob, Bone *bone, void *data) 
2043 {
2044     /* Bones that are deforming
2045      * are regarded to be "skinnable" and are eligible for
2046      * auto-skinning.
2047      *
2048      * This function performs 2 functions:
2049      *
2050      *   a) If the bone is skinnable, it creates 
2051      *      a vertex group for ob that has
2052      *      the name of the skinnable bone
2053      *      (if one doesn't exist already).
2054      *   b) If the pointer data is non null,
2055      *      it is treated like a handle to a
2056      *      bDeformGroup pointer -- the 
2057      *      bDeformGroup pointer is set to point
2058      *      to the deform group with the bone's
2059      *      name, and the pointer the handle 
2060      *      points to is incremented to point to the
2061      *      next member of an array of pointers
2062      *      to bDeformGroups. This way we can loop using
2063      *      this function to construct an array of
2064      *      pointers to bDeformGroups, all with names
2065      *      of skinnable bones.
2066      */
2067     bDeformGroup ***hgroup, *defgroup;
2068
2069    if (!(bone->flag & BONE_NO_DEFORM)) {
2070         if ( !(defgroup = get_named_vertexgroup(ob, bone->name)) ) {
2071             defgroup = add_defgroup_name(ob, bone->name);
2072         }
2073
2074         if (data != NULL) {
2075             hgroup = (bDeformGroup ***) data;
2076             **hgroup = defgroup;
2077             ++*hgroup;
2078         }
2079         return 1;
2080     }
2081     return 0;
2082 }
2083
2084 static void add_verts_to_closest_dgroup(Object *ob, Object *par)
2085 {
2086     /* This function implements a crude form of 
2087      * auto-skinning: vertices are assigned to the
2088      * deformation groups associated with bones based
2089      * on thier proximity to a bone. Every vert is
2090      * given a weight of 1.0 to the weight group
2091      * cooresponding to the bone that it is
2092      * closest to. The vertex may also be assigned to
2093      * a deformation group associated to a bone
2094      * that is within 10% of the mninimum distance
2095      * between the bone and the nearest vert -- the
2096      * cooresponding weight will fall-off to zero
2097      * as the distance approaches the 10% tolerance mark.
2098          * If the mesh has subsurf enabled then the verts
2099          * on the subsurf limit surface is used to generate 
2100          * the weights rather than the verts on the cage
2101          * mesh.
2102          *
2103          * ("Limit surface" = same amount of vertices as mesh, but vertices 
2104      *   moved to the subsurfed position, like for 'optimal').
2105      */
2106
2107     bArmature *arm;
2108     Bone **bonelist, **bonehandle, *bone;
2109     bDeformGroup **dgrouplist, **dgrouphandle, *defgroup;
2110     float *distance;
2111     float   root[3];
2112     float   tip[3];
2113     float real_co[3];
2114         float *subverts = NULL;
2115     float *subvert;
2116     Mesh  *mesh;
2117     MVert *vert;
2118
2119     int numbones, i, j;
2120
2121     /* If the parent object is not an armature exit */
2122     arm = get_armature(par);
2123     if (!arm)
2124         return;
2125
2126     /* count the number of skinnable bones */
2127     numbones = bone_looper(ob, arm->bonebase.first, NULL,
2128                                   bone_skinnable);
2129         
2130     /* create an array of pointer to bones that are skinnable
2131      * and fill it with all of the skinnable bones
2132      */
2133     bonelist = MEM_mallocN(numbones*sizeof(Bone *), "bonelist");
2134     bonehandle = bonelist;
2135     bone_looper(ob, arm->bonebase.first, &bonehandle,
2136                        bone_skinnable);
2137
2138     /* create an array of pointers to the deform groups that
2139      * coorespond to the skinnable bones (creating them
2140      * as necessary.
2141      */
2142     dgrouplist = MEM_mallocN(numbones*sizeof(bDeformGroup *), "dgrouplist");
2143     dgrouphandle = dgrouplist;
2144     bone_looper(ob, arm->bonebase.first, &dgrouphandle,
2145                        dgroup_skinnable);
2146
2147     /* create an array of floats that will be used for each vert
2148      * to hold the distance-factor to each bone.
2149      */
2150     distance = MEM_mallocN(numbones*sizeof(float), "distance");
2151
2152     mesh = (Mesh*)ob->data;
2153
2154         /* Is subsurf on? Lets use the verts on the limit surface then */
2155         if (modifiers_findByType(ob, eModifierType_Subsurf)) {
2156                 subverts = MEM_mallocN(3*mesh->totvert*sizeof(float), "subverts");
2157                 subsurf_calculate_limit_positions(mesh, (void *)subverts);      /* (ton) made void*, dunno how to cast */
2158         }
2159
2160     /* for each vertex in the mesh ...
2161      */
2162     for ( i=0 ; i < mesh->totvert ; ++i ) {
2163         /* get the vert in global coords
2164          */
2165                 
2166                 if (subverts) {
2167                         subvert = subverts + i*3;
2168                         VECCOPY (real_co, subvert);
2169                 }
2170                 else {
2171                         vert = mesh->mvert + i;
2172                         VECCOPY (real_co, vert->co);
2173                 }
2174         Mat4MulVecfl(ob->obmat, real_co);
2175
2176
2177         /* for each skinnable bone ...
2178          */
2179         for (j=0; j < numbones; ++j) {
2180             bone = bonelist[j];
2181
2182             /* get the root of the bone in global coords
2183              */
2184                         VECCOPY(root, bone->arm_head);
2185                         Mat4MulVecfl(par->obmat, root);
2186
2187             /* get the tip of the bone in global coords
2188              */
2189                         VECCOPY(tip, bone->arm_tail);
2190             Mat4MulVecfl(par->obmat, tip);
2191
2192             /* store the distance-factor from the vertex to
2193              * the bone
2194              */
2195                         distance[j]= distfactor_to_bone (real_co, root, tip, bone->rad_head, bone->rad_tail, bone->dist);
2196         }
2197
2198         /* for each deform group ...
2199          */
2200         for (j=0; j < numbones; ++j) {
2201             defgroup = dgrouplist[j];
2202
2203             /* add the vert to the deform group if weight!=0.0
2204              */
2205             if (distance[j]!=0.0)
2206                 add_vert_to_defgroup (ob, defgroup, i, distance[j], WEIGHT_REPLACE);
2207             else
2208                 remove_vert_defgroup (ob, defgroup, i);
2209         }
2210     }
2211
2212     /* free the memory allocated
2213      */
2214     MEM_freeN(bonelist);
2215     MEM_freeN(dgrouplist);
2216     MEM_freeN(distance);
2217         if (subverts) MEM_freeN(subverts);
2218 }
2219
2220 void create_vgroups_from_armature(Object *ob, Object *par)
2221 {
2222         /* Lets try to create some vertex groups 
2223          * based on the bones of the parent armature.
2224          */
2225
2226         bArmature *arm;
2227         short mode;
2228
2229         /* If the parent object is not an armature exit */
2230         arm = get_armature(par);
2231         if (!arm)
2232                 return;
2233
2234         /* Prompt the user on whether/how they want the vertex groups
2235          * added to the child mesh */
2236     mode= pupmenu("Create Vertex Groups? %t|"
2237                                   "Don't Create Groups %x1|"
2238                                   "Name Groups %x2|"
2239                   "Create From Closest Bones %x3");
2240         switch (mode){
2241         case 2:
2242                 /* Traverse the bone list, trying to create empty vertex 
2243                  * groups cooresponding to the bone.
2244                  */
2245                 bone_looper(ob, arm->bonebase.first, NULL,
2246                                         add_defgroup_unique_bone);
2247                 if (ob->type == OB_MESH)
2248                         create_dverts((Mesh*)ob->data);
2249
2250                 break;
2251
2252         case 3:
2253                 /* Traverse the bone list, trying to create vertex groups 
2254                  * that are populated with the vertices for which the
2255                  * bone is closest.
2256                  */
2257                 add_verts_to_closest_dgroup(ob, par);
2258                 break;
2259
2260         }
2261
2262
2263 static int hide_selected_pose_bone(Object *ob, Bone *bone, void *ptr) 
2264 {
2265         if (bone->flag & BONE_SELECTED) {
2266                 bone->flag |= BONE_HIDDEN_P;
2267                 bone->flag &= ~BONE_SELECTED;
2268         }
2269         return 0;
2270 }
2271
2272 /* active object is armature */
2273 void hide_selected_pose_bones(void) 
2274 {
2275         bArmature               *arm;
2276
2277         arm= get_armature (OBACT);
2278
2279         if (!arm)
2280                 return;
2281
2282         bone_looper(OBACT, arm->bonebase.first, NULL, 
2283                                 hide_selected_pose_bone);
2284
2285         allqueue(REDRAWVIEW3D, 0);
2286         allqueue(REDRAWBUTSEDIT, 0);
2287 }
2288
2289 static int hide_unselected_pose_bone(Object *ob, Bone *bone, void *ptr) 
2290 {
2291         if (~bone->flag & BONE_SELECTED) {
2292                 bone->flag |= BONE_HIDDEN_P;
2293         }
2294         return 0;
2295 }
2296
2297 /* active object is armature */
2298 void hide_unselected_pose_bones(void) 
2299 {
2300         bArmature               *arm;
2301
2302         arm=get_armature (OBACT);
2303
2304         if (!arm)
2305                 return;
2306
2307         bone_looper(OBACT, arm->bonebase.first, NULL, 
2308                                 hide_unselected_pose_bone);
2309
2310         allqueue(REDRAWVIEW3D, 0);
2311         allqueue(REDRAWBUTSEDIT, 0);
2312 }
2313
2314 static int show_pose_bone(Object *ob, Bone *bone, void *ptr) 
2315 {
2316         if (bone->flag & BONE_HIDDEN_P) {
2317                 bone->flag &= ~BONE_HIDDEN_P;
2318                 bone->flag |= BONE_SELECTED;
2319         }
2320
2321         return 0;
2322 }
2323
2324 /* active object is armature in posemode */
2325 void show_all_pose_bones(void) 
2326 {
2327         bArmature               *arm;
2328
2329         arm=get_armature (OBACT);
2330
2331         if (!arm)
2332                 return;
2333
2334         bone_looper(OBACT, arm->bonebase.first, NULL, 
2335                                 show_pose_bone);
2336
2337         allqueue(REDRAWVIEW3D, 0);
2338         allqueue(REDRAWBUTSEDIT, 0);
2339 }
2340
2341
2342 /* ************* RENAMING DISASTERS ************ */
2343
2344 /* note: there's a unique_editbone_name() too! */
2345 void unique_bone_name (bArmature *arm, char *name)
2346 {
2347         char            tempname[64];
2348         int                     number;
2349         char            *dot;
2350         
2351         if (get_named_bone(arm, name)) {
2352                 
2353                 /*      Strip off the suffix, if it's a number */
2354                 number= strlen(name);
2355                 if(number && isdigit(name[number-1])) {
2356                         dot= strrchr(name, '.');        // last occurrance
2357                         if (dot)
2358                                 *dot=0;
2359                 }
2360                 
2361                 for (number = 1; number <=999; number++){
2362                         sprintf (tempname, "%s.%03d", name, number);
2363                         if (!get_named_bone(arm, tempname)){
2364                                 strcpy (name, tempname);
2365                                 return;
2366                         }
2367                 }
2368         }
2369 }
2370
2371 #define MAXBONENAME 32
2372 /* helper call for below */
2373 static void constraint_bone_name_fix(Object *ob, ListBase *conlist, char *oldname, char *newname)
2374 {
2375         bConstraint *curcon;
2376         char *subtarget;
2377         
2378         for (curcon = conlist->first; curcon; curcon=curcon->next){
2379                 subtarget = get_con_subtarget_name(curcon, ob);
2380                 if (subtarget)
2381                         if (!strcmp(subtarget, oldname) )
2382                                 BLI_strncpy(subtarget, newname, MAXBONENAME);
2383         }
2384 }
2385
2386 /* called by UI for renaming a bone */
2387 /* warning: make sure the original bone was not renamed yet! */
2388 /* seems messy, but thats what you get with not using pointers but channel names :) */
2389 void armature_bone_rename(bArmature *arm, char *oldnamep, char *newnamep)
2390 {
2391         Object *ob, *modob;
2392         char newname[MAXBONENAME];
2393         char oldname[MAXBONENAME];
2394         
2395         /* names better differ! */
2396         if(strncmp(oldnamep, newnamep, MAXBONENAME)) {
2397                 
2398                 /* we alter newname string... so make copy */
2399                 BLI_strncpy(newname, newnamep, MAXBONENAME);
2400                 /* we use oldname for search... so make copy */
2401                 BLI_strncpy(oldname, oldnamep, MAXBONENAME);
2402                 
2403                 /* now check if we're in editmode, we need to find the unique name */
2404                 if(G.obedit && G.obedit->data==arm) {
2405                         EditBone        *eBone;
2406
2407                         eBone= editbone_name_exists(oldname);
2408                         if(eBone) {
2409                                 unique_editbone_name (newname);
2410                                 BLI_strncpy(eBone->name, newname, MAXBONENAME);
2411                         }
2412                         else return;
2413                 }
2414                 else {
2415                         Bone *bone= get_named_bone (arm, oldname);
2416
2417                         if(bone) {
2418                                 unique_bone_name (arm, newname);
2419                                 BLI_strncpy(bone->name, newname, MAXBONENAME);
2420                         }
2421                         else return;
2422                 }
2423                 
2424                 /* do entire dbase */
2425                 for(ob= G.main->object.first; ob; ob= ob->id.next) {
2426                         /* we have the object using the armature */
2427                         if(arm==ob->data) {
2428                                 Object *cob;
2429                                 bAction  *act;
2430                                 bActionChannel *chan;
2431
2432                                 /* Rename action channel if necessary */
2433                                 act = ob->action;
2434                                 if (act && !act->id.lib){
2435                                         /*      Find the appropriate channel */
2436                                         chan= get_named_actionchannel(act, oldname);
2437                                         if(chan) BLI_strncpy(chan->name, newname, MAXBONENAME);
2438                                 }
2439                 
2440                                 /* Rename the pose channel, if it exists */
2441                                 if (ob->pose) {
2442                                         bPoseChannel *pchan = get_pose_channel(ob->pose, oldname);
2443                                         if (pchan) {
2444                                                 BLI_strncpy (pchan->name, newname, MAXBONENAME);
2445                                         }
2446                                 }
2447                                 
2448                                 /* and actually do the NLA too */
2449                                 /* (todo) */
2450                                 
2451                                 /* Update any object constraints to use the new bone name */
2452                                 for(cob= G.main->object.first; cob; cob= cob->id.next) {
2453                                         if(cob->constraints.first)
2454                                                 constraint_bone_name_fix(ob, &cob->constraints, oldname, newname);
2455                                         if (cob->pose) {
2456                                                 bPoseChannel *pchan;
2457                                                 for (pchan = cob->pose->chanbase.first; pchan; pchan=pchan->next) {
2458                                                         constraint_bone_name_fix(ob, &pchan->constraints, oldname, newname);
2459                                                 }
2460                                         }
2461                                 }
2462                                 
2463                         }
2464                                         
2465                         /* See if an object is parented to this armature */
2466                         if (ob->parent && (ob->parent->data == arm)) {
2467                                 if(ob->partype==PARBONE) {
2468                                         /* bone name in object */
2469                                         if (!strcmp(ob->parsubstr, oldname))
2470                                                 BLI_strncpy(ob->parsubstr, newname, MAXBONENAME);
2471                                 }
2472                         }
2473                         /* or is there an armature deforming object */
2474                         modob = modifiers_isDeformedByArmature(ob);
2475                         if(modob) {
2476                                 bDeformGroup *dg;
2477                                 /* bone name in defgroup */
2478                                 for (dg=ob->defbase.first; dg; dg=dg->next) {
2479                                         if(!strcmp(dg->name, oldname))
2480                                            BLI_strncpy(dg->name, newname, MAXBONENAME);
2481                                 }
2482                         }
2483                 }
2484         }
2485 }
2486
2487 /* context editmode object */
2488 void armature_flip_names(void)
2489 {
2490         EditBone *ebone;
2491         char newname[32];
2492         
2493         for (ebone = G.edbo.first; ebone; ebone=ebone->next) {
2494                 if(ebone->flag & BONE_SELECTED) {
2495                         BLI_strncpy(newname, ebone->name, sizeof(newname));
2496                         bone_flip_name(newname, 1);             // 1 = do strip off number extensions
2497                         armature_bone_rename(G.obedit->data, ebone->name, newname);
2498                 }
2499         }
2500         
2501         allqueue(REDRAWVIEW3D, 0);
2502         allqueue(REDRAWBUTSEDIT, 0);
2503         allqueue(REDRAWBUTSOBJECT, 0);
2504         allqueue (REDRAWACTION, 0);
2505         allqueue(REDRAWOOPS, 0);
2506         BIF_undo_push("Flip names");
2507         
2508 }
2509
2510 /* context; editmode armature */
2511 EditBone *armature_bone_get_mirrored(EditBone *ebo)
2512 {
2513         EditBone *eboflip= NULL;
2514         char name[32];
2515         
2516         BLI_strncpy(name, ebo->name, sizeof(name));
2517         bone_flip_name(name, 0);                // 0 = don't strip off number extensions
2518
2519         for (eboflip=G.edbo.first; eboflip; eboflip=eboflip->next)
2520                 if(ebo!=eboflip)
2521                         if (!strcmp (name, eboflip->name)) break;
2522         
2523         return eboflip;
2524 }
2525