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