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