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