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