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