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