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