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