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