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