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