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