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