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