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