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