Rename any instance of scene layer or render layer in code with view layer
[blender.git] / source / blender / editors / armature / armature_relations.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  * Operators for relations between bones and for transferring bones between armature objects
26  */
27
28 /** \file blender/editors/armature/armature_relations.c
29  *  \ingroup edarmature
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "DNA_anim_types.h"
35 #include "DNA_armature_types.h"
36 #include "DNA_constraint_types.h"
37 #include "DNA_object_types.h"
38 #include "DNA_scene_types.h"
39
40 #include "BLI_blenlib.h"
41 #include "BLI_ghash.h"
42 #include "BLI_math.h"
43
44 #include "BLT_translation.h"
45
46 #include "BKE_action.h"
47 #include "BKE_animsys.h"
48 #include "BKE_constraint.h"
49 #include "BKE_context.h"
50 #include "BKE_fcurve.h"
51 #include "BKE_global.h"
52 #include "BKE_layer.h"
53 #include "BKE_main.h"
54 #include "BKE_report.h"
55
56 #include "DEG_depsgraph.h"
57 #include "DEG_depsgraph_build.h"
58
59 #include "RNA_access.h"
60 #include "RNA_define.h"
61
62 #include "WM_api.h"
63 #include "WM_types.h"
64
65 #include "ED_armature.h"
66 #include "ED_object.h"
67 #include "ED_screen.h"
68
69 #include "UI_interface.h"
70 #include "UI_resources.h"
71
72 #include "armature_intern.h"
73
74 /* *************************************** Join *************************************** */
75 /* NOTE: no operator define here as this is exported to the Object-level operator */
76
77 static void joined_armature_fix_links_constraints(
78         Object *tarArm, Object *srcArm, bPoseChannel *pchan, EditBone *curbone,
79         ListBase *lb)
80 {
81         bConstraint *con;
82
83         for (con = lb->first; con; con = con->next) {
84                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
85                 ListBase targets = {NULL, NULL};
86                 bConstraintTarget *ct;
87
88                 /* constraint targets */
89                 if (cti && cti->get_constraint_targets) {
90                         cti->get_constraint_targets(con, &targets);
91
92                         for (ct = targets.first; ct; ct = ct->next) {
93                                 if (ct->tar == srcArm) {
94                                         if (ct->subtarget[0] == '\0') {
95                                                 ct->tar = tarArm;
96                                         }
97                                         else if (STREQ(ct->subtarget, pchan->name)) {
98                                                 ct->tar = tarArm;
99                                                 BLI_strncpy(ct->subtarget, curbone->name, sizeof(ct->subtarget));
100                                         }
101                                 }
102                         }
103
104                         if (cti->flush_constraint_targets)
105                                 cti->flush_constraint_targets(con, &targets, 0);
106                 }
107
108                 /* action constraint? (pose constraints only) */
109                 if (con->type == CONSTRAINT_TYPE_ACTION) {
110                         bActionConstraint *data = con->data;
111
112                         if (data->act) {
113                                 BKE_action_fix_paths_rename(&tarArm->id, data->act, "pose.bones[", 
114                                                             pchan->name, curbone->name, 0, 0, false);
115                         }
116                 }
117
118         }
119 }
120
121 /* userdata for joined_armature_fix_animdata_cb() */
122 typedef struct tJoinArmature_AdtFixData {
123         Object *srcArm;
124         Object *tarArm;
125         
126         GHash *names_map;
127 } tJoinArmature_AdtFixData;
128
129 /* Callback to pass to void BKE_animdata_main_cb() for fixing driver ID's to point to the new ID */
130 /* FIXME: For now, we only care about drivers here. When editing rigs, it's very rare to have animation
131  *        on the rigs being edited already, so it should be safe to skip these.
132  */
133 static void joined_armature_fix_animdata_cb(ID *id, AnimData *adt, void *user_data)
134 {
135         tJoinArmature_AdtFixData *afd = (tJoinArmature_AdtFixData *)user_data;
136         ID *src_id = &afd->srcArm->id;
137         ID *dst_id = &afd->tarArm->id;
138         
139         GHashIterator gh_iter;
140         FCurve *fcu;
141         
142         /* Fix paths - If this is the target object, it will have some "dirty" paths */
143         if (id == src_id) {
144                 /* Fix drivers */
145                 for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
146                         /* skip driver if it doesn't affect the bones */
147                         if (strstr(fcu->rna_path, "pose.bones[") == NULL) {
148                                 continue;
149                         }
150                         
151                         // FIXME: this is too crude... it just does everything!
152                         GHASH_ITER(gh_iter, afd->names_map) {
153                                 const char *old_name = BLI_ghashIterator_getKey(&gh_iter);
154                                 const char *new_name = BLI_ghashIterator_getValue(&gh_iter);
155                                 
156                                 /* only remap if changed; this still means there will be some waste if there aren't many drivers/keys */
157                                 if (!STREQ(old_name, new_name) && strstr(fcu->rna_path, old_name)) {
158                                         fcu->rna_path = BKE_animsys_fix_rna_path_rename(id, fcu->rna_path, "pose.bones",
159                                                                                         old_name, new_name, 0, 0, false);
160                                         
161                                         /* we don't want to apply a second remapping on this driver now, 
162                                          * so stop trying names, but keep fixing drivers
163                                          */
164                                         break;
165                                 }
166                         }
167                 }
168         }
169         
170         
171         /* Driver targets */
172         for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
173                 ChannelDriver *driver = fcu->driver;
174                 DriverVar *dvar;
175                 
176                 /* Fix driver references to invalid ID's */
177                 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
178                         /* only change the used targets, since the others will need fixing manually anyway */
179                         DRIVER_TARGETS_USED_LOOPER(dvar)
180                         {
181                                 /* change the ID's used... */
182                                 if (dtar->id == src_id) {
183                                         dtar->id = dst_id;
184                                         
185                                         /* also check on the subtarget...
186                                          * XXX: We duplicate the logic from drivers_path_rename_fix() here, with our own
187                                          *      little twists so that we know that it isn't going to clobber the wrong data
188                                          */
189                                         if ((dtar->rna_path && strstr(dtar->rna_path, "pose.bones[")) || (dtar->pchan_name[0])) {
190                                                 GHASH_ITER(gh_iter, afd->names_map) {
191                                                         const char *old_name = BLI_ghashIterator_getKey(&gh_iter);
192                                                         const char *new_name = BLI_ghashIterator_getValue(&gh_iter);
193                                                         
194                                                         /* only remap if changed */
195                                                         if (!STREQ(old_name, new_name)) {
196                                                                 if ((dtar->rna_path) && strstr(dtar->rna_path, old_name)) {
197                                                                         /* Fix up path */
198                                                                         dtar->rna_path = BKE_animsys_fix_rna_path_rename(id, dtar->rna_path, "pose.bones",
199                                                                                                                          old_name, new_name, 0, 0, false);
200                                                                         break; /* no need to try any more names for bone path */
201                                                                 }
202                                                                 else if (STREQ(dtar->pchan_name, old_name)) {
203                                                                         /* Change target bone name */
204                                                                         BLI_strncpy(dtar->pchan_name, new_name, sizeof(dtar->pchan_name));
205                                                                         break; /* no need to try any more names for bone subtarget */
206                                                                 }
207                                                         }
208                                                 }
209                                         }
210                                 }
211                         }
212                         DRIVER_TARGETS_LOOPER_END
213                 }
214         }
215 }
216
217 /* Helper function for armature joining - link fixing */
218 static void joined_armature_fix_links(Main *bmain, Object *tarArm, Object *srcArm, bPoseChannel *pchan, EditBone *curbone)
219 {
220         Object *ob;
221         bPose *pose;
222         bPoseChannel *pchant;
223         
224         /* let's go through all objects in database */
225         for (ob = bmain->object.first; ob; ob = ob->id.next) {
226                 /* do some object-type specific things */
227                 if (ob->type == OB_ARMATURE) {
228                         pose = ob->pose;
229                         for (pchant = pose->chanbase.first; pchant; pchant = pchant->next) {
230                                 joined_armature_fix_links_constraints(tarArm, srcArm, pchan, curbone, &pchant->constraints);
231                         }
232                 }
233                         
234                 /* fix object-level constraints */
235                 if (ob != srcArm) {
236                         joined_armature_fix_links_constraints(tarArm, srcArm, pchan, curbone, &ob->constraints);
237                 }
238                 
239                 /* See if an object is parented to this armature */
240                 if (ob->parent && (ob->parent == srcArm)) {
241                         /* Is object parented to a bone of this src armature? */
242                         if (ob->partype == PARBONE) {
243                                 /* bone name in object */
244                                 if (STREQ(ob->parsubstr, pchan->name)) {
245                                         BLI_strncpy(ob->parsubstr, curbone->name, sizeof(ob->parsubstr));
246                                 }
247                         }
248                         
249                         /* make tar armature be new parent */
250                         ob->parent = tarArm;
251                 }
252         }
253 }
254
255 /* join armature exec is exported for use in object->join objects operator... */
256 int join_armature_exec(bContext *C, wmOperator *op)
257 {
258         Main *bmain = CTX_data_main(C);
259         Scene *scene = CTX_data_scene(C);
260         Object  *ob = CTX_data_active_object(C);
261         bArmature *arm = (ob) ? ob->data : NULL;
262         bPose *pose, *opose;
263         bPoseChannel *pchan, *pchann;
264         EditBone *curbone;
265         float mat[4][4], oimat[4][4];
266         bool ok = false;
267         
268         /*      Ensure we're not in editmode and that the active object is an armature*/
269         if (!ob || ob->type != OB_ARMATURE)
270                 return OPERATOR_CANCELLED;
271         if (!arm || arm->edbo)
272                 return OPERATOR_CANCELLED;
273         
274         CTX_DATA_BEGIN(C, Base *, base, selected_editable_bases)
275         {
276                 if (base->object == ob) {
277                         ok = true;
278                         break;
279                 }
280         }
281         CTX_DATA_END;
282
283         /* that way the active object is always selected */
284         if (ok == false) {
285                 BKE_report(op->reports, RPT_WARNING, "Active object is not a selected armature");
286                 return OPERATOR_CANCELLED;
287         }
288
289         /* Get editbones of active armature to add editbones to */
290         ED_armature_to_edit(arm);
291         
292         /* get pose of active object and move it out of posemode */
293         pose = ob->pose;
294         ob->mode &= ~OB_MODE_POSE;
295
296         CTX_DATA_BEGIN(C, Base *, base, selected_editable_bases)
297         {
298                 if ((base->object->type == OB_ARMATURE) && (base->object != ob)) {
299                         tJoinArmature_AdtFixData afd = {NULL};
300                         bArmature *curarm = base->object->data;
301                         
302                         /* we assume that each armature datablock is only used in a single place */
303                         BLI_assert(ob->data != base->object->data);
304                         
305                         /* init callback data for fixing up AnimData links later */
306                         afd.srcArm = base->object;
307                         afd.tarArm = ob;
308                         afd.names_map = BLI_ghash_str_new("join_armature_adt_fix");
309                         
310                         /* Make a list of editbones in current armature */
311                         ED_armature_to_edit(base->object->data);
312                         
313                         /* Get Pose of current armature */
314                         opose = base->object->pose;
315                         base->object->mode &= ~OB_MODE_POSE;
316                         //BASACT->flag &= ~OB_MODE_POSE;
317                         
318                         /* Find the difference matrix */
319                         invert_m4_m4(oimat, ob->obmat);
320                         mul_m4_m4m4(mat, oimat, base->object->obmat);
321                         
322                         /* Copy bones and posechannels from the object to the edit armature */
323                         for (pchan = opose->chanbase.first; pchan; pchan = pchann) {
324                                 pchann = pchan->next;
325                                 curbone = ED_armature_bone_find_name(curarm->edbo, pchan->name);
326                                 
327                                 /* Get new name */
328                                 unique_editbone_name(arm->edbo, curbone->name, NULL);
329                                 BLI_ghash_insert(afd.names_map, BLI_strdup(pchan->name), curbone->name);
330                                 
331                                 /* Transform the bone */
332                                 {
333                                         float premat[4][4];
334                                         float postmat[4][4];
335                                         float difmat[4][4];
336                                         float imat[4][4];
337                                         float temp[3][3];
338                                         
339                                         /* Get the premat */
340                                         ED_armature_ebone_to_mat3(curbone, temp);
341                                         
342                                         unit_m4(premat); /* mul_m4_m3m4 only sets 3x3 part */
343                                         mul_m4_m3m4(premat, temp, mat);
344                                         
345                                         mul_m4_v3(mat, curbone->head);
346                                         mul_m4_v3(mat, curbone->tail);
347                                         
348                                         /* Get the postmat */
349                                         ED_armature_ebone_to_mat3(curbone, temp);
350                                         copy_m4_m3(postmat, temp);
351                                         
352                                         /* Find the roll */
353                                         invert_m4_m4(imat, premat);
354                                         mul_m4_m4m4(difmat, imat, postmat);
355                                         
356                                         curbone->roll -= atan2f(difmat[2][0], difmat[2][2]);
357                                 }
358                                 
359                                 /* Fix Constraints and Other Links to this Bone and Armature */
360                                 joined_armature_fix_links(bmain, ob, base->object, pchan, curbone);
361                                 
362                                 /* Rename pchan */
363                                 BLI_strncpy(pchan->name, curbone->name, sizeof(pchan->name));
364                                 
365                                 /* Jump Ship! */
366                                 BLI_remlink(curarm->edbo, curbone);
367                                 BLI_addtail(arm->edbo, curbone);
368                                 
369                                 BLI_remlink(&opose->chanbase, pchan);
370                                 BLI_addtail(&pose->chanbase, pchan);
371                                 BKE_pose_channels_hash_free(opose);
372                                 BKE_pose_channels_hash_free(pose);
373                         }
374                         
375                         /* Fix all the drivers (and animation data) */
376                         BKE_animdata_main_cb(bmain, joined_armature_fix_animdata_cb, &afd);
377                         BLI_ghash_free(afd.names_map, MEM_freeN, NULL);
378                         
379                         /* Only copy over animdata now, after all the remapping has been done, 
380                          * so that we don't have to worry about ambiguities re which armature
381                          * a bone came from!
382                          */
383                         if (base->object->adt) {
384                                 if (ob->adt == NULL) {
385                                         /* no animdata, so just use a copy of the whole thing */
386                                         ob->adt = BKE_animdata_copy(bmain, base->object->adt, false);
387                                 }
388                                 else {
389                                         /* merge in data - we'll fix the drivers manually */
390                                         BKE_animdata_merge_copy(&ob->id, &base->object->id, ADT_MERGECOPY_KEEP_DST, false);
391                                 }
392                         }
393                         
394                         if (curarm->adt) {
395                                 if (arm->adt == NULL) {
396                                         /* no animdata, so just use a copy of the whole thing */
397                                         arm->adt = BKE_animdata_copy(bmain, curarm->adt, false);
398                                 }
399                                 else {
400                                         /* merge in data - we'll fix the drivers manually */
401                                         BKE_animdata_merge_copy(&arm->id, &curarm->id, ADT_MERGECOPY_KEEP_DST, false);
402                                 }
403                         }
404                         
405                         /* Free the old object data */
406                         ED_object_base_free_and_unlink(bmain, scene, base->object);
407                 }
408         }
409         CTX_DATA_END;
410         
411         DEG_relations_tag_update(bmain);  /* because we removed object(s) */
412
413         ED_armature_from_edit(arm);
414         ED_armature_edit_free(arm);
415
416         WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
417         
418         return OPERATOR_FINISHED;
419 }
420
421 /* *********************************** Separate *********************************************** */
422
423 /* Helper function for armature separating - link fixing */
424 static void separated_armature_fix_links(Object *origArm, Object *newArm)
425 {
426         Object *ob;
427         bPoseChannel *pchan;
428         bConstraint *con;
429         ListBase *opchans, *npchans;
430         
431         /* get reference to list of bones in original and new armatures  */
432         opchans = &origArm->pose->chanbase;
433         npchans = &newArm->pose->chanbase;
434         
435         /* let's go through all objects in database */
436         for (ob = G.main->object.first; ob; ob = ob->id.next) {
437                 /* do some object-type specific things */
438                 if (ob->type == OB_ARMATURE) {
439                         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
440                                 for (con = pchan->constraints.first; con; con = con->next) {
441                                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
442                                         ListBase targets = {NULL, NULL};
443                                         bConstraintTarget *ct;
444                                         
445                                         /* constraint targets */
446                                         if (cti && cti->get_constraint_targets) {
447                                                 cti->get_constraint_targets(con, &targets);
448                                                 
449                                                 for (ct = targets.first; ct; ct = ct->next) {
450                                                         /* any targets which point to original armature are redirected to the new one only if:
451                                                          *      - the target isn't origArm/newArm itself
452                                                          *      - the target is one that can be found in newArm/origArm
453                                                          */
454                                                         if (ct->subtarget[0] != 0) {
455                                                                 if (ct->tar == origArm) {
456                                                                         if (BLI_findstring(npchans, ct->subtarget, offsetof(bPoseChannel, name))) {
457                                                                                 ct->tar = newArm;
458                                                                         }
459                                                                 }
460                                                                 else if (ct->tar == newArm) {
461                                                                         if (BLI_findstring(opchans, ct->subtarget, offsetof(bPoseChannel, name))) {
462                                                                                 ct->tar = origArm;
463                                                                         }
464                                                                 }
465                                                         }
466                                                 }
467
468                                                 if (cti->flush_constraint_targets) {
469                                                         cti->flush_constraint_targets(con, &targets, 0);
470                                                 }
471                                         }
472                                 }
473                         }
474                 }
475                         
476                 /* fix object-level constraints */
477                 if (ob != origArm) {
478                         for (con = ob->constraints.first; con; con = con->next) {
479                                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
480                                 ListBase targets = {NULL, NULL};
481                                 bConstraintTarget *ct;
482                                 
483                                 /* constraint targets */
484                                 if (cti && cti->get_constraint_targets) {
485                                         cti->get_constraint_targets(con, &targets);
486                                         
487                                         for (ct = targets.first; ct; ct = ct->next) {
488                                                 /* any targets which point to original armature are redirected to the new one only if:
489                                                  *      - the target isn't origArm/newArm itself
490                                                  *      - the target is one that can be found in newArm/origArm
491                                                  */
492                                                 if (ct->subtarget[0] != '\0') {
493                                                         if (ct->tar == origArm) {
494                                                                 if (BLI_findstring(npchans, ct->subtarget, offsetof(bPoseChannel, name))) {
495                                                                         ct->tar = newArm;
496                                                                 }
497                                                         }
498                                                         else if (ct->tar == newArm) {
499                                                                 if (BLI_findstring(opchans, ct->subtarget, offsetof(bPoseChannel, name))) {
500                                                                         ct->tar = origArm;
501                                                                 }
502                                                         }
503                                                 }
504                                         }
505                                         
506                                         if (cti->flush_constraint_targets) {
507                                                 cti->flush_constraint_targets(con, &targets, 0);
508                                         }
509                                 }
510                         }
511                 }
512                 
513                 /* See if an object is parented to this armature */
514                 if (ob->parent && (ob->parent == origArm)) {
515                         /* Is object parented to a bone of this src armature? */
516                         if ((ob->partype == PARBONE) && (ob->parsubstr[0] != '\0')) {
517                                 if (BLI_findstring(npchans, ob->parsubstr, offsetof(bPoseChannel, name))) {
518                                         ob->parent = newArm;
519                                 }
520                         }
521                 }
522         }
523 }
524
525 /* Helper function for armature separating - remove certain bones from the given armature 
526  *      sel: remove selected bones from the armature, otherwise the unselected bones are removed
527  *  (ob is not in editmode)
528  */
529 static void separate_armature_bones(Object *ob, short sel) 
530 {
531         bArmature *arm = (bArmature *)ob->data;
532         bPoseChannel *pchan, *pchann;
533         EditBone *curbone;
534         
535         /* make local set of editbones to manipulate here */
536         ED_armature_to_edit(arm);
537         
538         /* go through pose-channels, checking if a bone should be removed */
539         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchann) {
540                 pchann = pchan->next;
541                 curbone = ED_armature_bone_find_name(arm->edbo, pchan->name);
542                 
543                 /* check if bone needs to be removed */
544                 if ( (sel && (curbone->flag & BONE_SELECTED)) ||
545                      (!sel && !(curbone->flag & BONE_SELECTED)) )
546                 {
547                         EditBone *ebo;
548                         bPoseChannel *pchn;
549                         
550                         /* clear the bone->parent var of any bone that had this as its parent  */
551                         for (ebo = arm->edbo->first; ebo; ebo = ebo->next) {
552                                 if (ebo->parent == curbone) {
553                                         ebo->parent = NULL;
554                                         ebo->temp.p = NULL; /* this is needed to prevent random crashes with in ED_armature_from_edit */
555                                         ebo->flag &= ~BONE_CONNECTED;
556                                 }
557                         }
558                         
559                         /* clear the pchan->parent var of any pchan that had this as its parent */
560                         for (pchn = ob->pose->chanbase.first; pchn; pchn = pchn->next) {
561                                 if (pchn->parent == pchan)
562                                         pchn->parent = NULL;
563                         }
564                         
565                         /* free any of the extra-data this pchan might have */
566                         BKE_pose_channel_free(pchan);
567                         BKE_pose_channels_hash_free(ob->pose);
568                         
569                         /* get rid of unneeded bone */
570                         bone_free(arm, curbone);
571                         BLI_freelinkN(&ob->pose->chanbase, pchan);
572                 }
573         }
574         
575         /* exit editmode (recalculates pchans too) */
576         ED_armature_from_edit(ob->data);
577         ED_armature_edit_free(ob->data);
578 }
579
580 /* separate selected bones into their armature */
581 static int separate_armature_exec(bContext *C, wmOperator *op)
582 {
583         Main *bmain = CTX_data_main(C);
584         Scene *scene = CTX_data_scene(C);
585         ViewLayer *sl = CTX_data_view_layer(C);
586         Object *obedit = CTX_data_edit_object(C);
587         Object *oldob, *newob;
588         Base *oldbase, *newbase;
589         
590         /* sanity checks */
591         if (obedit == NULL)
592                 return OPERATOR_CANCELLED;
593         
594         /* set wait cursor in case this takes a while */
595         WM_cursor_wait(1);
596         
597         /* we are going to do this as follows (unlike every other instance of separate):
598          *      1. exit editmode +posemode for active armature/base. Take note of what this is.
599          *      2. duplicate base - BASACT is the new one now
600          *      3. for each of the two armatures, enter editmode -> remove appropriate bones -> exit editmode + recalc
601          *      4. fix constraint links
602          *      5. make original armature active and enter editmode
603          */
604
605         /* 1) only edit-base selected */
606         /* TODO: use context iterators for this? */
607         CTX_DATA_BEGIN(C, Base *, base, visible_bases)
608         {
609                 if (base->object == obedit) {
610                         ED_object_base_select(base, BA_SELECT);
611                 }
612                 else {
613                         ED_object_base_select(base, BA_DESELECT);
614                 }
615         }
616         CTX_DATA_END;
617         
618         /* 1) store starting settings and exit editmode */
619         oldob = obedit;
620         oldbase = sl->basact;
621         oldob->mode &= ~OB_MODE_POSE;
622         //oldbase->flag &= ~OB_POSEMODE;
623         
624         ED_armature_from_edit(obedit->data);
625         ED_armature_edit_free(obedit->data);
626         
627         /* 2) duplicate base */
628         newbase = ED_object_add_duplicate(bmain, scene, sl, oldbase, USER_DUP_ARM); /* only duplicate linked armature */
629         DEG_relations_tag_update(bmain);
630
631         newob = newbase->object;
632         newbase->flag &= ~BASE_SELECTED;
633
634
635         /* 3) remove bones that shouldn't still be around on both armatures */
636         separate_armature_bones(oldob, 1);
637         separate_armature_bones(newob, 0);
638         
639         
640         /* 4) fix links before depsgraph flushes */ // err... or after?
641         separated_armature_fix_links(oldob, newob);
642         
643         DEG_id_tag_update(&oldob->id, OB_RECALC_DATA);  /* this is the original one */
644         DEG_id_tag_update(&newob->id, OB_RECALC_DATA);  /* this is the separated one */
645         
646         
647         /* 5) restore original conditions */
648         obedit = oldob;
649         
650         ED_armature_to_edit(obedit->data);
651         
652         /* parents tips remain selected when connected children are removed. */
653         ED_armature_deselect_all(obedit);
654
655         BKE_report(op->reports, RPT_INFO, "Separated bones");
656
657         /* note, notifier might evolve */
658         WM_event_add_notifier(C, NC_OBJECT | ND_POSE, obedit);
659         
660         /* recalc/redraw + cleanup */
661         WM_cursor_wait(0);
662         
663         return OPERATOR_FINISHED;
664 }
665
666 void ARMATURE_OT_separate(wmOperatorType *ot)
667 {
668         /* identifiers */
669         ot->name = "Separate Bones";
670         ot->idname = "ARMATURE_OT_separate";
671         ot->description = "Isolate selected bones into a separate armature";
672         
673         /* callbacks */
674         ot->invoke = WM_operator_confirm;
675         ot->exec = separate_armature_exec;
676         ot->poll = ED_operator_editarmature;
677         
678         /* flags */
679         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
680 }
681
682 /* ******************************************** Parenting ************************************************* */
683
684 /* armature parenting options */
685 #define ARM_PAR_CONNECT 1
686 #define ARM_PAR_OFFSET  2
687
688
689 /* check for null, before calling! */
690 static void bone_connect_to_existing_parent(EditBone *bone)
691 {
692         bone->flag |= BONE_CONNECTED;
693         copy_v3_v3(bone->head, bone->parent->tail);
694         bone->rad_head = bone->parent->rad_tail;
695 }
696
697 static void bone_connect_to_new_parent(ListBase *edbo, EditBone *selbone, EditBone *actbone, short mode)
698 {
699         EditBone *ebone;
700         float offset[3];
701         
702         if ((selbone->parent) && (selbone->flag & BONE_CONNECTED))
703                 selbone->parent->flag &= ~(BONE_TIPSEL);
704         
705         /* make actbone the parent of selbone */
706         selbone->parent = actbone;
707         
708         /* in actbone tree we cannot have a loop */
709         for (ebone = actbone->parent; ebone; ebone = ebone->parent) {
710                 if (ebone->parent == selbone) {
711                         ebone->parent = NULL;
712                         ebone->flag &= ~BONE_CONNECTED;
713                 }
714         }
715         
716         if (mode == ARM_PAR_CONNECT) {
717                 /* Connected: Child bones will be moved to the parent tip */
718                 selbone->flag |= BONE_CONNECTED;
719                 sub_v3_v3v3(offset, actbone->tail, selbone->head);
720                 
721                 copy_v3_v3(selbone->head, actbone->tail);
722                 selbone->rad_head = actbone->rad_tail;
723                 
724                 add_v3_v3(selbone->tail, offset);
725                 
726                 /* offset for all its children */
727                 for (ebone = edbo->first; ebone; ebone = ebone->next) {
728                         EditBone *par;
729                         
730                         for (par = ebone->parent; par; par = par->parent) {
731                                 if (par == selbone) {
732                                         add_v3_v3(ebone->head, offset);
733                                         add_v3_v3(ebone->tail, offset);
734                                         break;
735                                 }
736                         }
737                 }
738         }
739         else {
740                 /* Offset: Child bones will retain their distance from the parent tip */
741                 selbone->flag &= ~BONE_CONNECTED;
742         }
743 }
744
745
746 static const EnumPropertyItem prop_editarm_make_parent_types[] = {
747         {ARM_PAR_CONNECT, "CONNECTED", 0, "Connected", ""},
748         {ARM_PAR_OFFSET, "OFFSET", 0, "Keep Offset", ""},
749         {0, NULL, 0, NULL, NULL}
750 };
751
752 static int armature_parent_set_exec(bContext *C, wmOperator *op) 
753 {
754         Object *ob = CTX_data_edit_object(C);
755         bArmature *arm = (bArmature *)ob->data;
756         EditBone *actbone = CTX_data_active_bone(C);
757         EditBone *actmirb = NULL;
758         short val = RNA_enum_get(op->ptr, "type");
759         
760         /* there must be an active bone */
761         if (actbone == NULL) {
762                 BKE_report(op->reports, RPT_ERROR, "Operation requires an active bone");
763                 return OPERATOR_CANCELLED;
764         }
765         else if (arm->flag & ARM_MIRROR_EDIT) {
766                 /* For X-Axis Mirror Editing option, we may need a mirror copy of actbone
767                  * - if there's a mirrored copy of selbone, try to find a mirrored copy of actbone 
768                  *   (i.e.  selbone="child.L" and actbone="parent.L", find "child.R" and "parent.R").
769                  * This is useful for arm-chains, for example parenting lower arm to upper arm
770                  * - if there's no mirrored copy of actbone (i.e. actbone = "parent.C" or "parent")
771                  *   then just use actbone. Useful when doing upper arm to spine.
772                  */
773                 actmirb = ED_armature_bone_get_mirrored(arm->edbo, actbone);
774                 if (actmirb == NULL) 
775                         actmirb = actbone;
776         }
777         
778         /* if there is only 1 selected bone, we assume that that is the active bone, 
779          * since a user will need to have clicked on a bone (thus selecting it) to make it active
780          */
781         if (CTX_DATA_COUNT(C, selected_editable_bones) <= 1) {
782                 /* When only the active bone is selected, and it has a parent,
783                  * connect it to the parent, as that is the only possible outcome. 
784                  */
785                 if (actbone->parent) {
786                         bone_connect_to_existing_parent(actbone);
787                         
788                         if ((arm->flag & ARM_MIRROR_EDIT) && (actmirb->parent))
789                                 bone_connect_to_existing_parent(actmirb);
790                 }
791         }
792         else {
793                 /* Parent 'selected' bones to the active one
794                  * - the context iterator contains both selected bones and their mirrored copies,
795                  *   so we assume that unselected bones are mirrored copies of some selected bone
796                  * - since the active one (and/or its mirror) will also be selected, we also need 
797                  *  to check that we are not trying to operate on them, since such an operation
798                  *      would cause errors
799                  */
800                 
801                 /* parent selected bones to the active one */
802                 CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones)
803                 {
804                         if (ELEM(ebone, actbone, actmirb) == 0) {
805                                 if (ebone->flag & BONE_SELECTED) 
806                                         bone_connect_to_new_parent(arm->edbo, ebone, actbone, val);
807                                 else
808                                         bone_connect_to_new_parent(arm->edbo, ebone, actmirb, val);
809                         }
810                 }
811                 CTX_DATA_END;
812         }
813         
814
815         /* note, notifier might evolve */
816         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
817         
818         return OPERATOR_FINISHED;
819 }
820
821 static int armature_parent_set_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
822 {
823         EditBone *actbone = CTX_data_active_bone(C);
824         uiPopupMenu *pup = UI_popup_menu_begin(C, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Make Parent"), ICON_NONE);
825         uiLayout *layout = UI_popup_menu_layout(pup);
826         int allchildbones = 0;
827         
828         CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones)
829         {
830                 if (ebone != actbone) {
831                         if (ebone->parent != actbone) allchildbones = 1;
832                 }
833         }
834         CTX_DATA_END;
835
836         uiItemEnumO(layout, "ARMATURE_OT_parent_set", NULL, 0, "type", ARM_PAR_CONNECT);
837         
838         /* ob becomes parent, make the associated menus */
839         if (allchildbones)
840                 uiItemEnumO(layout, "ARMATURE_OT_parent_set", NULL, 0, "type", ARM_PAR_OFFSET);
841                 
842         UI_popup_menu_end(C, pup);
843         
844         return OPERATOR_INTERFACE;
845 }
846
847 void ARMATURE_OT_parent_set(wmOperatorType *ot)
848 {
849         /* identifiers */
850         ot->name = "Make Parent";
851         ot->idname = "ARMATURE_OT_parent_set";
852         ot->description = "Set the active bone as the parent of the selected bones";
853         
854         /* api callbacks */
855         ot->invoke = armature_parent_set_invoke;
856         ot->exec = armature_parent_set_exec;
857         ot->poll = ED_operator_editarmature;
858         
859         /* flags */
860         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
861         
862         RNA_def_enum(ot->srna, "type", prop_editarm_make_parent_types, 0, "ParentType", "Type of parenting");
863 }
864
865
866
867 static const EnumPropertyItem prop_editarm_clear_parent_types[] = {
868         {1, "CLEAR", 0, "Clear Parent", ""},
869         {2, "DISCONNECT", 0, "Disconnect Bone", ""},
870         {0, NULL, 0, NULL, NULL}
871 };
872
873 static void editbone_clear_parent(EditBone *ebone, int mode)
874 {
875         if (ebone->parent) {
876                 /* for nice selection */
877                 ebone->parent->flag &= ~(BONE_TIPSEL);
878         }
879         
880         if (mode == 1) ebone->parent = NULL;
881         ebone->flag &= ~BONE_CONNECTED;
882 }
883
884 static int armature_parent_clear_exec(bContext *C, wmOperator *op) 
885 {
886         Object *ob = CTX_data_edit_object(C);
887         bArmature *arm = (bArmature *)ob->data;
888         int val = RNA_enum_get(op->ptr, "type");
889                 
890         CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones)
891         {
892                 editbone_clear_parent(ebone, val);
893         }
894         CTX_DATA_END;
895         
896         ED_armature_sync_selection(arm->edbo);
897
898         /* note, notifier might evolve */
899         WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
900         
901         return OPERATOR_FINISHED;
902 }
903
904 void ARMATURE_OT_parent_clear(wmOperatorType *ot)
905 {
906         /* identifiers */
907         ot->name = "Clear Parent";
908         ot->idname = "ARMATURE_OT_parent_clear";
909         ot->description = "Remove the parent-child relationship between selected bones and their parents";
910         
911         /* api callbacks */
912         ot->invoke = WM_menu_invoke;
913         ot->exec = armature_parent_clear_exec;
914         ot->poll = ED_operator_editarmature;
915         
916         /* flags */
917         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
918         
919         ot->prop = RNA_def_enum(ot->srna, "type", prop_editarm_clear_parent_types, 0, "ClearType", "What way to clear parenting");
920 }
921