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