Cleanup: remove redundant doxygen \file argument
[blender.git] / source / blender / editors / armature / armature_relations.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  * Operators for relations between bones and for transferring bones between armature objects
19  */
20
21 /** \file \ingroup edarmature
22  */
23
24 #include "MEM_guardedalloc.h"
25
26 #include "DNA_anim_types.h"
27 #include "DNA_armature_types.h"
28 #include "DNA_constraint_types.h"
29 #include "DNA_object_types.h"
30 #include "DNA_scene_types.h"
31
32 #include "BLI_blenlib.h"
33 #include "BLI_ghash.h"
34 #include "BLI_math.h"
35
36 #include "BLT_translation.h"
37
38 #include "BKE_action.h"
39 #include "BKE_animsys.h"
40 #include "BKE_constraint.h"
41 #include "BKE_context.h"
42 #include "BKE_fcurve.h"
43 #include "BKE_layer.h"
44 #include "BKE_main.h"
45 #include "BKE_report.h"
46
47 #include "DEG_depsgraph.h"
48 #include "DEG_depsgraph_build.h"
49
50 #include "RNA_access.h"
51 #include "RNA_define.h"
52
53 #include "WM_api.h"
54 #include "WM_types.h"
55
56 #include "ED_armature.h"
57 #include "ED_object.h"
58 #include "ED_screen.h"
59
60 #include "UI_interface.h"
61 #include "UI_resources.h"
62
63 #include "armature_intern.h"
64
65 /* *************************************** Join *************************************** */
66 /* NOTE: no operator define here as this is exported to the Object-level operator */
67
68 static void joined_armature_fix_links_constraints(
69         Object *tarArm, Object *srcArm, bPoseChannel *pchan, EditBone *curbone,
70         ListBase *lb)
71 {
72         bConstraint *con;
73
74         for (con = lb->first; con; con = con->next) {
75                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
76                 ListBase targets = {NULL, NULL};
77                 bConstraintTarget *ct;
78
79                 /* constraint targets */
80                 if (cti && cti->get_constraint_targets) {
81                         cti->get_constraint_targets(con, &targets);
82
83                         for (ct = targets.first; ct; ct = ct->next) {
84                                 if (ct->tar == srcArm) {
85                                         if (ct->subtarget[0] == '\0') {
86                                                 ct->tar = tarArm;
87                                         }
88                                         else if (STREQ(ct->subtarget, pchan->name)) {
89                                                 ct->tar = tarArm;
90                                                 BLI_strncpy(ct->subtarget, curbone->name, sizeof(ct->subtarget));
91                                         }
92                                 }
93                         }
94
95                         if (cti->flush_constraint_targets)
96                                 cti->flush_constraint_targets(con, &targets, 0);
97                 }
98
99                 /* action constraint? (pose constraints only) */
100                 if (con->type == CONSTRAINT_TYPE_ACTION) {
101                         bActionConstraint *data = con->data;
102
103                         if (data->act) {
104                                 BKE_action_fix_paths_rename(&tarArm->id, data->act, "pose.bones[",
105                                                             pchan->name, curbone->name, 0, 0, false);
106                         }
107                 }
108
109         }
110 }
111
112 /* userdata for joined_armature_fix_animdata_cb() */
113 typedef struct tJoinArmature_AdtFixData {
114         Object *srcArm;
115         Object *tarArm;
116
117         GHash *names_map;
118 } tJoinArmature_AdtFixData;
119
120 /* Callback to pass to BKE_animdata_main_cb() for fixing driver ID's to point to the new ID */
121 /* FIXME: For now, we only care about drivers here. When editing rigs, it's very rare to have animation
122  *        on the rigs being edited already, so it should be safe to skip these.
123  */
124 static void joined_armature_fix_animdata_cb(ID *id, FCurve *fcu, void *user_data)
125 {
126         tJoinArmature_AdtFixData *afd = (tJoinArmature_AdtFixData *)user_data;
127         ID *src_id = &afd->srcArm->id;
128         ID *dst_id = &afd->tarArm->id;
129
130         GHashIterator gh_iter;
131
132         /* Fix paths - If this is the target object, it will have some "dirty" paths */
133         if ((id == src_id) && strstr(fcu->rna_path, "pose.bones[")) {
134                 GHASH_ITER(gh_iter, afd->names_map) {
135                         const char *old_name = BLI_ghashIterator_getKey(&gh_iter);
136                         const char *new_name = BLI_ghashIterator_getValue(&gh_iter);
137
138                         /* only remap if changed; this still means there will be some
139                          * waste if there aren't many drivers/keys */
140                         if (!STREQ(old_name, new_name) && strstr(fcu->rna_path, old_name)) {
141                                 fcu->rna_path = BKE_animsys_fix_rna_path_rename(id, fcu->rna_path, "pose.bones",
142                                                                                 old_name, new_name, 0, 0, false);
143
144                                 /* we don't want to apply a second remapping on this driver now,
145                                  * so stop trying names, but keep fixing drivers
146                                  */
147                                 break;
148                         }
149                 }
150         }
151
152
153         /* Driver targets */
154         if (fcu->driver) {
155                 ChannelDriver *driver = fcu->driver;
156                 DriverVar *dvar;
157
158                 /* Fix driver references to invalid ID's */
159                 for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
160                         /* only change the used targets, since the others will need fixing manually anyway */
161                         DRIVER_TARGETS_USED_LOOPER_BEGIN(dvar)
162                         {
163                                 /* change the ID's used... */
164                                 if (dtar->id == src_id) {
165                                         dtar->id = dst_id;
166
167                                         /* also check on the subtarget...
168                                          * XXX: We duplicate the logic from drivers_path_rename_fix() here, with our own
169                                          *      little twists so that we know that it isn't going to clobber the wrong data
170                                          */
171                                         if ((dtar->rna_path && strstr(dtar->rna_path, "pose.bones[")) || (dtar->pchan_name[0])) {
172                                                 GHASH_ITER(gh_iter, afd->names_map) {
173                                                         const char *old_name = BLI_ghashIterator_getKey(&gh_iter);
174                                                         const char *new_name = BLI_ghashIterator_getValue(&gh_iter);
175
176                                                         /* only remap if changed */
177                                                         if (!STREQ(old_name, new_name)) {
178                                                                 if ((dtar->rna_path) && strstr(dtar->rna_path, old_name)) {
179                                                                         /* Fix up path */
180                                                                         dtar->rna_path = BKE_animsys_fix_rna_path_rename(id, dtar->rna_path, "pose.bones",
181                                                                                                                          old_name, new_name, 0, 0, false);
182                                                                         break; /* no need to try any more names for bone path */
183                                                                 }
184                                                                 else if (STREQ(dtar->pchan_name, old_name)) {
185                                                                         /* Change target bone name */
186                                                                         BLI_strncpy(dtar->pchan_name, new_name, sizeof(dtar->pchan_name));
187                                                                         break; /* no need to try any more names for bone subtarget */
188                                                                 }
189                                                         }
190                                                 }
191                                         }
192                                 }
193                         }
194                         DRIVER_TARGETS_LOOPER_END;
195                 }
196         }
197 }
198
199 /* Helper function for armature joining - link fixing */
200 static void joined_armature_fix_links(Main *bmain, Object *tarArm, Object *srcArm, bPoseChannel *pchan, EditBone *curbone)
201 {
202         Object *ob;
203         bPose *pose;
204         bPoseChannel *pchant;
205
206         /* let's go through all objects in database */
207         for (ob = bmain->object.first; ob; ob = ob->id.next) {
208                 /* do some object-type specific things */
209                 if (ob->type == OB_ARMATURE) {
210                         pose = ob->pose;
211                         for (pchant = pose->chanbase.first; pchant; pchant = pchant->next) {
212                                 joined_armature_fix_links_constraints(tarArm, srcArm, pchan, curbone, &pchant->constraints);
213                         }
214                 }
215
216                 /* fix object-level constraints */
217                 if (ob != srcArm) {
218                         joined_armature_fix_links_constraints(tarArm, srcArm, pchan, curbone, &ob->constraints);
219                 }
220
221                 /* See if an object is parented to this armature */
222                 if (ob->parent && (ob->parent == srcArm)) {
223                         /* Is object parented to a bone of this src armature? */
224                         if (ob->partype == PARBONE) {
225                                 /* bone name in object */
226                                 if (STREQ(ob->parsubstr, pchan->name)) {
227                                         BLI_strncpy(ob->parsubstr, curbone->name, sizeof(ob->parsubstr));
228                                 }
229                         }
230
231                         /* make tar armature be new parent */
232                         ob->parent = tarArm;
233                 }
234         }
235 }
236
237 /* join armature exec is exported for use in object->join objects operator... */
238 int join_armature_exec(bContext *C, wmOperator *op)
239 {
240         Main *bmain = CTX_data_main(C);
241         Scene *scene = CTX_data_scene(C);
242         Object  *ob_active = CTX_data_active_object(C);
243         bArmature *arm = (ob_active) ? ob_active->data : NULL;
244         bPose *pose, *opose;
245         bPoseChannel *pchan, *pchann;
246         EditBone *curbone;
247         float mat[4][4], oimat[4][4];
248         bool ok = false;
249
250         /*      Ensure we're not in editmode and that the active object is an armature*/
251         if (!ob_active || ob_active->type != OB_ARMATURE)
252                 return OPERATOR_CANCELLED;
253         if (!arm || arm->edbo)
254                 return OPERATOR_CANCELLED;
255
256         CTX_DATA_BEGIN(C, Object *, ob_iter, selected_editable_objects)
257         {
258                 if (ob_iter == ob_active) {
259                         ok = true;
260                         break;
261                 }
262         }
263         CTX_DATA_END;
264
265         /* that way the active object is always selected */
266         if (ok == false) {
267                 BKE_report(op->reports, RPT_WARNING, "Active object is not a selected armature");
268                 return OPERATOR_CANCELLED;
269         }
270
271         /* Get editbones of active armature to add editbones to */
272         ED_armature_to_edit(arm);
273
274         /* get pose of active object and move it out of posemode */
275         pose = ob_active->pose;
276         ob_active->mode &= ~OB_MODE_POSE;
277
278         CTX_DATA_BEGIN(C, Object *, ob_iter, selected_editable_objects)
279         {
280                 if ((ob_iter->type == OB_ARMATURE) && (ob_iter != ob_active)) {
281                         tJoinArmature_AdtFixData afd = {NULL};
282                         bArmature *curarm = ob_iter->data;
283
284                         /* we assume that each armature datablock is only used in a single place */
285                         BLI_assert(ob_active->data != ob_iter->data);
286
287                         /* init callback data for fixing up AnimData links later */
288                         afd.srcArm = ob_iter;
289                         afd.tarArm = ob_active;
290                         afd.names_map = BLI_ghash_str_new("join_armature_adt_fix");
291
292                         /* Make a list of editbones in current armature */
293                         ED_armature_to_edit(ob_iter->data);
294
295                         /* Get Pose of current armature */
296                         opose = ob_iter->pose;
297                         ob_iter->mode &= ~OB_MODE_POSE;
298                         //BASACT->flag &= ~OB_MODE_POSE;
299
300                         /* Find the difference matrix */
301                         invert_m4_m4(oimat, ob_active->obmat);
302                         mul_m4_m4m4(mat, oimat, ob_iter->obmat);
303
304                         /* Copy bones and posechannels from the object to the edit armature */
305                         for (pchan = opose->chanbase.first; pchan; pchan = pchann) {
306                                 pchann = pchan->next;
307                                 curbone = ED_armature_ebone_find_name(curarm->edbo, pchan->name);
308
309                                 /* Get new name */
310                                 ED_armature_ebone_unique_name(arm->edbo, curbone->name, NULL);
311                                 BLI_ghash_insert(afd.names_map, BLI_strdup(pchan->name), curbone->name);
312
313                                 /* Transform the bone */
314                                 {
315                                         float premat[4][4];
316                                         float postmat[4][4];
317                                         float difmat[4][4];
318                                         float imat[4][4];
319                                         float temp[3][3];
320
321                                         /* Get the premat */
322                                         ED_armature_ebone_to_mat3(curbone, temp);
323
324                                         unit_m4(premat); /* mul_m4_m3m4 only sets 3x3 part */
325                                         mul_m4_m3m4(premat, temp, mat);
326
327                                         mul_m4_v3(mat, curbone->head);
328                                         mul_m4_v3(mat, curbone->tail);
329
330                                         /* Get the postmat */
331                                         ED_armature_ebone_to_mat3(curbone, temp);
332                                         copy_m4_m3(postmat, temp);
333
334                                         /* Find the roll */
335                                         invert_m4_m4(imat, premat);
336                                         mul_m4_m4m4(difmat, imat, postmat);
337
338                                         curbone->roll -= atan2f(difmat[2][0], difmat[2][2]);
339                                 }
340
341                                 /* Fix Constraints and Other Links to this Bone and Armature */
342                                 joined_armature_fix_links(bmain, ob_active, ob_iter, pchan, curbone);
343
344                                 /* Rename pchan */
345                                 BLI_strncpy(pchan->name, curbone->name, sizeof(pchan->name));
346
347                                 /* Jump Ship! */
348                                 BLI_remlink(curarm->edbo, curbone);
349                                 BLI_addtail(arm->edbo, curbone);
350
351                                 BLI_remlink(&opose->chanbase, pchan);
352                                 BLI_addtail(&pose->chanbase, pchan);
353                                 BKE_pose_channels_hash_free(opose);
354                                 BKE_pose_channels_hash_free(pose);
355                         }
356
357                         /* Fix all the drivers (and animation data) */
358                         BKE_fcurves_main_cb(bmain, joined_armature_fix_animdata_cb, &afd);
359                         BLI_ghash_free(afd.names_map, MEM_freeN, NULL);
360
361                         /* Only copy over animdata now, after all the remapping has been done,
362                          * so that we don't have to worry about ambiguities re which armature
363                          * a bone came from!
364                          */
365                         if (ob_iter->adt) {
366                                 if (ob_active->adt == NULL) {
367                                         /* no animdata, so just use a copy of the whole thing */
368                                         ob_active->adt = BKE_animdata_copy(bmain, ob_iter->adt, 0);
369                                 }
370                                 else {
371                                         /* merge in data - we'll fix the drivers manually */
372                                         BKE_animdata_merge_copy(bmain, &ob_active->id, &ob_iter->id, ADT_MERGECOPY_KEEP_DST, false);
373                                 }
374                         }
375
376                         if (curarm->adt) {
377                                 if (arm->adt == NULL) {
378                                         /* no animdata, so just use a copy of the whole thing */
379                                         arm->adt = BKE_animdata_copy(bmain, curarm->adt, 0);
380                                 }
381                                 else {
382                                         /* merge in data - we'll fix the drivers manually */
383                                         BKE_animdata_merge_copy(bmain, &arm->id, &curarm->id, ADT_MERGECOPY_KEEP_DST, false);
384                                 }
385                         }
386
387                         /* Free the old object data */
388                         ED_object_base_free_and_unlink(bmain, scene, ob_iter);
389                 }
390         }
391         CTX_DATA_END;
392
393         DEG_relations_tag_update(bmain);  /* because we removed object(s) */
394
395         ED_armature_from_edit(bmain, arm);
396         ED_armature_edit_free(arm);
397
398         DEG_id_tag_update(&scene->id, ID_RECALC_SELECT);
399         WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
400
401         return OPERATOR_FINISHED;
402 }
403
404 /* *********************************** Separate *********************************************** */
405
406 /* Helper function for armature separating - link fixing */
407 static void separated_armature_fix_links(Main *bmain, Object *origArm, Object *newArm)
408 {
409         Object *ob;
410         bPoseChannel *pchan;
411         bConstraint *con;
412         ListBase *opchans, *npchans;
413
414         /* get reference to list of bones in original and new armatures  */
415         opchans = &origArm->pose->chanbase;
416         npchans = &newArm->pose->chanbase;
417
418         /* let's go through all objects in database */
419         for (ob = bmain->object.first; ob; ob = ob->id.next) {
420                 /* do some object-type specific things */
421                 if (ob->type == OB_ARMATURE) {
422                         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
423                                 for (con = pchan->constraints.first; con; con = con->next) {
424                                         const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
425                                         ListBase targets = {NULL, NULL};
426                                         bConstraintTarget *ct;
427
428                                         /* constraint targets */
429                                         if (cti && cti->get_constraint_targets) {
430                                                 cti->get_constraint_targets(con, &targets);
431
432                                                 for (ct = targets.first; ct; ct = ct->next) {
433                                                         /* any targets which point to original armature are redirected to the new one only if:
434                                                          * - the target isn't origArm/newArm itself
435                                                          * - the target is one that can be found in newArm/origArm
436                                                          */
437                                                         if (ct->subtarget[0] != 0) {
438                                                                 if (ct->tar == origArm) {
439                                                                         if (BLI_findstring(npchans, ct->subtarget, offsetof(bPoseChannel, name))) {
440                                                                                 ct->tar = newArm;
441                                                                         }
442                                                                 }
443                                                                 else if (ct->tar == newArm) {
444                                                                         if (BLI_findstring(opchans, ct->subtarget, offsetof(bPoseChannel, name))) {
445                                                                                 ct->tar = origArm;
446                                                                         }
447                                                                 }
448                                                         }
449                                                 }
450
451                                                 if (cti->flush_constraint_targets) {
452                                                         cti->flush_constraint_targets(con, &targets, 0);
453                                                 }
454                                         }
455                                 }
456                         }
457                 }
458
459                 /* fix object-level constraints */
460                 if (ob != origArm) {
461                         for (con = ob->constraints.first; con; con = con->next) {
462                                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
463                                 ListBase targets = {NULL, NULL};
464                                 bConstraintTarget *ct;
465
466                                 /* constraint targets */
467                                 if (cti && cti->get_constraint_targets) {
468                                         cti->get_constraint_targets(con, &targets);
469
470                                         for (ct = targets.first; ct; ct = ct->next) {
471                                                 /* any targets which point to original armature are redirected to the new one only if:
472                                                  * - the target isn't origArm/newArm itself
473                                                  * - the target is one that can be found in newArm/origArm
474                                                  */
475                                                 if (ct->subtarget[0] != '\0') {
476                                                         if (ct->tar == origArm) {
477                                                                 if (BLI_findstring(npchans, ct->subtarget, offsetof(bPoseChannel, name))) {
478                                                                         ct->tar = newArm;
479                                                                 }
480                                                         }
481                                                         else if (ct->tar == newArm) {
482                                                                 if (BLI_findstring(opchans, ct->subtarget, offsetof(bPoseChannel, name))) {
483                                                                         ct->tar = origArm;
484                                                                 }
485                                                         }
486                                                 }
487                                         }
488
489                                         if (cti->flush_constraint_targets) {
490                                                 cti->flush_constraint_targets(con, &targets, 0);
491                                         }
492                                 }
493                         }
494                 }
495
496                 /* See if an object is parented to this armature */
497                 if (ob->parent && (ob->parent == origArm)) {
498                         /* Is object parented to a bone of this src armature? */
499                         if ((ob->partype == PARBONE) && (ob->parsubstr[0] != '\0')) {
500                                 if (BLI_findstring(npchans, ob->parsubstr, offsetof(bPoseChannel, name))) {
501                                         ob->parent = newArm;
502                                 }
503                         }
504                 }
505         }
506 }
507
508 /* Helper function for armature separating - remove certain bones from the given armature
509  * sel: remove selected bones from the armature, otherwise the unselected bones are removed
510  * (ob is not in editmode)
511  */
512 static void separate_armature_bones(Main *bmain, Object *ob, short sel)
513 {
514         bArmature *arm = (bArmature *)ob->data;
515         bPoseChannel *pchan, *pchann;
516         EditBone *curbone;
517
518         /* make local set of editbones to manipulate here */
519         ED_armature_to_edit(arm);
520
521         /* go through pose-channels, checking if a bone should be removed */
522         for (pchan = ob->pose->chanbase.first; pchan; pchan = pchann) {
523                 pchann = pchan->next;
524                 curbone = ED_armature_ebone_find_name(arm->edbo, pchan->name);
525
526                 /* check if bone needs to be removed */
527                 if ( (sel && (curbone->flag & BONE_SELECTED)) ||
528                      (!sel && !(curbone->flag & BONE_SELECTED)) )
529                 {
530                         EditBone *ebo;
531                         bPoseChannel *pchn;
532
533                         /* clear the bone->parent var of any bone that had this as its parent  */
534                         for (ebo = arm->edbo->first; ebo; ebo = ebo->next) {
535                                 if (ebo->parent == curbone) {
536                                         ebo->parent = NULL;
537                                         /* this is needed to prevent random crashes with in ED_armature_from_edit */
538                                         ebo->temp.p = NULL;
539                                         ebo->flag &= ~BONE_CONNECTED;
540                                 }
541                         }
542
543                         /* clear the pchan->parent var of any pchan that had this as its parent */
544                         for (pchn = ob->pose->chanbase.first; pchn; pchn = pchn->next) {
545                                 if (pchn->parent == pchan) {
546                                         pchn->parent = NULL;
547                                 }
548                                 if (pchn->bbone_next == pchan) {
549                                         pchn->bbone_next = NULL;
550                                 }
551                                 if (pchn->bbone_prev == pchan) {
552                                         pchn->bbone_prev = NULL;
553                                 }
554                         }
555
556                         /* free any of the extra-data this pchan might have */
557                         BKE_pose_channel_free(pchan);
558                         BKE_pose_channels_hash_free(ob->pose);
559
560                         /* get rid of unneeded bone */
561                         bone_free(arm, curbone);
562                         BLI_freelinkN(&ob->pose->chanbase, pchan);
563                 }
564         }
565
566         /* exit editmode (recalculates pchans too) */
567         ED_armature_from_edit(bmain, ob->data);
568         ED_armature_edit_free(ob->data);
569 }
570
571 /* separate selected bones into their armature */
572 static int separate_armature_exec(bContext *C, wmOperator *op)
573 {
574         Main *bmain = CTX_data_main(C);
575         Scene *scene = CTX_data_scene(C);
576         ViewLayer *view_layer = CTX_data_view_layer(C);
577         bool ok = false;
578
579         /* set wait cursor in case this takes a while */
580         WM_cursor_wait(1);
581
582         uint bases_len = 0;
583         Base **bases = BKE_view_layer_array_from_bases_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &bases_len);
584
585         CTX_DATA_BEGIN(C, Base *, base, visible_bases)
586         {
587                 ED_object_base_select(base, BA_DESELECT);
588         }
589         CTX_DATA_END;
590
591         for (uint base_index = 0; base_index < bases_len; base_index++) {
592                 Base *base_iter = bases[base_index];
593                 Object *obedit = base_iter->object;
594
595                 Object *oldob, *newob;
596                 Base *oldbase, *newbase;
597
598                 /* we are going to do this as follows (unlike every other instance of separate):
599                  * 1. exit editmode +posemode for active armature/base. Take note of what this is.
600                  * 2. duplicate base - BASACT is the new one now
601                  * 3. for each of the two armatures, enter editmode -> remove appropriate bones -> exit editmode + recalc
602                  * 4. fix constraint links
603                  * 5. make original armature active and enter editmode
604                  */
605
606                 /* 1) only edit-base selected */
607                 ED_object_base_select(base_iter, BA_SELECT);
608
609                 /* 1) store starting settings and exit editmode */
610                 oldob = obedit;
611                 oldbase = base_iter;
612                 oldob->mode &= ~OB_MODE_POSE;
613                 //oldbase->flag &= ~OB_POSEMODE;
614
615                 ED_armature_from_edit(bmain, obedit->data);
616                 ED_armature_edit_free(obedit->data);
617
618                 /* 2) duplicate base */
619
620                 /* only duplicate linked armature */
621                 newbase = ED_object_add_duplicate(bmain, scene, view_layer, oldbase, USER_DUP_ARM);
622
623                 DEG_relations_tag_update(bmain);
624
625                 newob = newbase->object;
626                 newbase->flag &= ~BASE_SELECTED;
627
628
629                 /* 3) remove bones that shouldn't still be around on both armatures */
630                 separate_armature_bones(bmain, oldob, 1);
631                 separate_armature_bones(bmain, newob, 0);
632
633
634                 /* 4) fix links before depsgraph flushes */ // err... or after?
635                 separated_armature_fix_links(bmain, oldob, newob);
636
637                 DEG_id_tag_update(&oldob->id, ID_RECALC_GEOMETRY);  /* this is the original one */
638                 DEG_id_tag_update(&newob->id, ID_RECALC_GEOMETRY);  /* this is the separated one */
639
640
641                 /* 5) restore original conditions */
642                 obedit = oldob;
643
644                 ED_armature_to_edit(obedit->data);
645
646                 /* parents tips remain selected when connected children are removed. */
647                 ED_armature_edit_deselect_all(obedit);
648
649                 ok = true;
650
651                 /* note, notifier might evolve */
652                 WM_event_add_notifier(C, NC_OBJECT | ND_POSE, obedit);
653         }
654         MEM_freeN(bases);
655
656         /* recalc/redraw + cleanup */
657         WM_cursor_wait(0);
658
659         if (ok) {
660                 BKE_report(op->reports, RPT_INFO, "Separated bones");
661         }
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_ebone_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         ViewLayer *view_layer = CTX_data_view_layer(C);
887         const int val = RNA_enum_get(op->ptr, "type");
888
889         CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones)
890         {
891                 editbone_clear_parent(ebone, val);
892         }
893         CTX_DATA_END;
894
895         uint objects_len = 0;
896         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, CTX_wm_view3d(C), &objects_len);
897         for (uint ob_index = 0; ob_index < objects_len; ob_index++) {
898                 Object *ob = objects[ob_index];
899                 bArmature *arm = ob->data;
900                 bool changed = false;
901
902                 for (EditBone *ebone = arm->edbo->first; ebone; ebone = ebone->next) {
903                         if (EBONE_EDITABLE(ebone)) {
904                                 changed = true;
905                                 break;
906                         }
907                 }
908
909                 if (!changed) {
910                         continue;
911                 }
912
913                 ED_armature_edit_sync_selection(arm->edbo);
914
915                 /* Note, notifier might evolve. */
916                 WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
917         }
918         MEM_freeN(objects);
919
920         return OPERATOR_FINISHED;
921 }
922
923 void ARMATURE_OT_parent_clear(wmOperatorType *ot)
924 {
925         /* identifiers */
926         ot->name = "Clear Parent";
927         ot->idname = "ARMATURE_OT_parent_clear";
928         ot->description = "Remove the parent-child relationship between selected bones and their parents";
929
930         /* api callbacks */
931         ot->invoke = WM_menu_invoke;
932         ot->exec = armature_parent_clear_exec;
933         ot->poll = ED_operator_editarmature;
934
935         /* flags */
936         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
937
938         ot->prop = RNA_def_enum(ot->srna, "type", prop_editarm_clear_parent_types, 0, "ClearType", "What way to clear parenting");
939 }