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