Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / object / object_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-2008 full recode
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/object/object_relations.c
27  *  \ingroup edobj
28  */
29
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_anim_types.h"
38 #include "DNA_armature_types.h"
39 #include "DNA_mesh_types.h"
40 #include "DNA_constraint_types.h"
41 #include "DNA_group_types.h"
42 #include "DNA_lamp_types.h"
43 #include "DNA_lattice_types.h"
44 #include "DNA_material_types.h"
45 #include "DNA_meta_types.h"
46 #include "DNA_particle_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_world_types.h"
49 #include "DNA_object_types.h"
50 #include "DNA_vfont_types.h"
51 #include "DNA_gpencil_types.h"
52
53 #include "BLI_math.h"
54 #include "BLI_listbase.h"
55 #include "BLI_linklist.h"
56 #include "BLI_string.h"
57 #include "BLI_kdtree.h"
58 #include "BLI_utildefines.h"
59
60 #include "BLT_translation.h"
61
62 #include "BKE_action.h"
63 #include "BKE_animsys.h"
64 #include "BKE_armature.h"
65 #include "BKE_camera.h"
66 #include "BKE_collection.h"
67 #include "BKE_context.h"
68 #include "BKE_constraint.h"
69 #include "BKE_curve.h"
70 #include "BKE_DerivedMesh.h"
71 #include "BKE_displist.h"
72 #include "BKE_global.h"
73 #include "BKE_fcurve.h"
74 #include "BKE_idprop.h"
75 #include "BKE_lamp.h"
76 #include "BKE_lattice.h"
77 #include "BKE_layer.h"
78 #include "BKE_library.h"
79 #include "BKE_library_override.h"
80 #include "BKE_library_query.h"
81 #include "BKE_library_remap.h"
82 #include "BKE_lightprobe.h"
83 #include "BKE_main.h"
84 #include "BKE_material.h"
85 #include "BKE_mball.h"
86 #include "BKE_mesh.h"
87 #include "BKE_modifier.h"
88 #include "BKE_node.h"
89 #include "BKE_object.h"
90 #include "BKE_report.h"
91 #include "BKE_scene.h"
92 #include "BKE_speaker.h"
93 #include "BKE_texture.h"
94 #include "BKE_editmesh.h"
95
96 #include "DEG_depsgraph.h"
97 #include "DEG_depsgraph_build.h"
98
99 #include "WM_api.h"
100 #include "WM_types.h"
101
102 #include "UI_interface.h"
103 #include "UI_resources.h"
104
105 #include "RNA_access.h"
106 #include "RNA_define.h"
107 #include "RNA_enum_types.h"
108
109 #include "ED_armature.h"
110 #include "ED_curve.h"
111 #include "ED_keyframing.h"
112 #include "ED_object.h"
113 #include "ED_mesh.h"
114 #include "ED_screen.h"
115 #include "ED_view3d.h"
116
117 #include "object_intern.h"
118
119 /*********************** Make Vertex Parent Operator ************************/
120
121 static int vertex_parent_set_poll(bContext *C)
122 {
123         return ED_operator_editmesh(C) || ED_operator_editsurfcurve(C) || ED_operator_editlattice(C);
124 }
125
126 static int vertex_parent_set_exec(bContext *C, wmOperator *op)
127 {
128         Main *bmain = CTX_data_main(C);
129         Scene *scene = CTX_data_scene(C);
130         Depsgraph *depsgraph = CTX_data_depsgraph(C);
131         ViewLayer *view_layer = CTX_data_view_layer(C);
132         Object *obedit = CTX_data_edit_object(C);
133         BMVert *eve;
134         BMIter iter;
135         Curve *cu;
136         Nurb *nu;
137         BezTriple *bezt;
138         BPoint *bp;
139         Object *par;
140         int a, v1 = 0, v2 = 0, v3 = 0, v4 = 0, nr = 1;
141
142         /* we need 1 to 3 selected vertices */
143
144         if (obedit->type == OB_MESH) {
145                 Mesh *me = obedit->data;
146                 BMEditMesh *em;
147
148                 EDBM_mesh_load(bmain, obedit);
149                 EDBM_mesh_make(obedit, scene->toolsettings->selectmode, true);
150
151                 DEG_id_tag_update(obedit->data, 0);
152
153                 em = me->edit_btmesh;
154
155                 EDBM_mesh_normals_update(em);
156                 BKE_editmesh_tessface_calc(em);
157
158                 /* derivedMesh might be needed for solving parenting,
159                  * so re-create it here */
160                 makeDerivedMesh(depsgraph, scene, obedit, em, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX, false);
161
162                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
163                         if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
164                                 if (v1 == 0) v1 = nr;
165                                 else if (v2 == 0) v2 = nr;
166                                 else if (v3 == 0) v3 = nr;
167                                 else if (v4 == 0) v4 = nr;
168                                 else break;
169                         }
170                         nr++;
171                 }
172         }
173         else if (ELEM(obedit->type, OB_SURF, OB_CURVE)) {
174                 ListBase *editnurb = object_editcurve_get(obedit);
175
176                 cu = obedit->data;
177
178                 nu = editnurb->first;
179                 while (nu) {
180                         if (nu->type == CU_BEZIER) {
181                                 bezt = nu->bezt;
182                                 a = nu->pntsu;
183                                 while (a--) {
184                                         if (BEZT_ISSEL_ANY_HIDDENHANDLES(cu, bezt)) {
185                                                 if (v1 == 0) v1 = nr;
186                                                 else if (v2 == 0) v2 = nr;
187                                                 else if (v3 == 0) v3 = nr;
188                                                 else if (v4 == 0) v4 = nr;
189                                                 else break;
190                                         }
191                                         nr++;
192                                         bezt++;
193                                 }
194                         }
195                         else {
196                                 bp = nu->bp;
197                                 a = nu->pntsu * nu->pntsv;
198                                 while (a--) {
199                                         if (bp->f1 & SELECT) {
200                                                 if (v1 == 0) v1 = nr;
201                                                 else if (v2 == 0) v2 = nr;
202                                                 else if (v3 == 0) v3 = nr;
203                                                 else if (v4 == 0) v4 = nr;
204                                                 else break;
205                                         }
206                                         nr++;
207                                         bp++;
208                                 }
209                         }
210                         nu = nu->next;
211                 }
212         }
213         else if (obedit->type == OB_LATTICE) {
214                 Lattice *lt = obedit->data;
215
216                 a = lt->editlatt->latt->pntsu * lt->editlatt->latt->pntsv * lt->editlatt->latt->pntsw;
217                 bp = lt->editlatt->latt->def;
218                 while (a--) {
219                         if (bp->f1 & SELECT) {
220                                 if (v1 == 0) v1 = nr;
221                                 else if (v2 == 0) v2 = nr;
222                                 else if (v3 == 0) v3 = nr;
223                                 else if (v4 == 0) v4 = nr;
224                                 else break;
225                         }
226                         nr++;
227                         bp++;
228                 }
229         }
230
231         if (v4 || !((v1 && v2 == 0 && v3 == 0) || (v1 && v2 && v3))) {
232                 BKE_report(op->reports, RPT_ERROR, "Select either 1 or 3 vertices to parent to");
233                 return OPERATOR_CANCELLED;
234         }
235
236         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
237         {
238                 if (ob != obedit) {
239                         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
240                         par = obedit->parent;
241
242                         if (BKE_object_parent_loop_check(par, ob)) {
243                                 BKE_report(op->reports, RPT_ERROR, "Loop in parents");
244                         }
245                         else {
246                                 Object workob;
247
248                                 ob->parent = BASACT(view_layer)->object;
249                                 if (v3) {
250                                         ob->partype = PARVERT3;
251                                         ob->par1 = v1 - 1;
252                                         ob->par2 = v2 - 1;
253                                         ob->par3 = v3 - 1;
254
255                                         /* inverse parent matrix */
256                                         BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
257                                         invert_m4_m4(ob->parentinv, workob.obmat);
258                                 }
259                                 else {
260                                         ob->partype = PARVERT1;
261                                         ob->par1 = v1 - 1;
262
263                                         /* inverse parent matrix */
264                                         BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
265                                         invert_m4_m4(ob->parentinv, workob.obmat);
266                                 }
267                         }
268                 }
269         }
270         CTX_DATA_END;
271
272         DEG_relations_tag_update(bmain);
273
274         WM_event_add_notifier(C, NC_OBJECT, NULL);
275
276         return OPERATOR_FINISHED;
277 }
278
279 void OBJECT_OT_vertex_parent_set(wmOperatorType *ot)
280 {
281         /* identifiers */
282         ot->name = "Make Vertex Parent";
283         ot->description = "Parent selected objects to the selected vertices";
284         ot->idname = "OBJECT_OT_vertex_parent_set";
285
286         /* api callbacks */
287         ot->invoke = WM_operator_confirm;
288         ot->poll = vertex_parent_set_poll;
289         ot->exec = vertex_parent_set_exec;
290
291         /* flags */
292         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
293 }
294
295 /********************** Make Proxy Operator *************************/
296
297 /* set the object to proxify */
298 static int make_proxy_invoke(bContext *C, wmOperator *op, const wmEvent *event)
299 {
300         Scene *scene = CTX_data_scene(C);
301         Object *ob = ED_object_active_context(C);
302
303         /* sanity checks */
304         if (!scene || ID_IS_LINKED(scene) || !ob)
305                 return OPERATOR_CANCELLED;
306
307         /* Get object to work on - use a menu if we need to... */
308         if (ob->dup_group && ID_IS_LINKED(ob->dup_group)) {
309                 /* gives menu with list of objects in group */
310                 /* proxy_group_objects_menu(C, op, ob, ob->dup_group); */
311                 WM_enum_search_invoke(C, op, event);
312                 return OPERATOR_CANCELLED;
313         }
314         else if (ID_IS_LINKED(ob)) {
315                 uiPopupMenu *pup = UI_popup_menu_begin(C, IFACE_("OK?"), ICON_QUESTION);
316                 uiLayout *layout = UI_popup_menu_layout(pup);
317
318                 /* create operator menu item with relevant properties filled in */
319                 PointerRNA opptr_dummy;
320                 uiItemFullO_ptr(layout, op->type, op->type->name, ICON_NONE, NULL,
321                                 WM_OP_EXEC_REGION_WIN, 0, &opptr_dummy);
322
323                 /* present the menu and be done... */
324                 UI_popup_menu_end(C, pup);
325
326                 /* this invoke just calls another instance of this operator... */
327                 return OPERATOR_INTERFACE;
328         }
329         else {
330                 /* error.. cannot continue */
331                 BKE_report(op->reports, RPT_ERROR, "Can only make proxy for a referenced object or collection");
332                 return OPERATOR_CANCELLED;
333         }
334
335 }
336
337 static int make_proxy_exec(bContext *C, wmOperator *op)
338 {
339         Main *bmain = CTX_data_main(C);
340         Object *ob, *gob = ED_object_active_context(C);
341         Scene *scene = CTX_data_scene(C);
342         ViewLayer *view_layer = CTX_data_view_layer(C);
343
344         if (gob->dup_group != NULL) {
345                 const ListBase dup_group_objects = BKE_collection_object_cache_get(gob->dup_group);
346                 Base *base = BLI_findlink(&dup_group_objects, RNA_enum_get(op->ptr, "object"));
347                 ob = base->object;
348         }
349         else {
350                 ob = gob;
351         }
352
353         if (ob) {
354                 Object *newob;
355                 char name[MAX_ID_NAME + 4];
356
357                 BLI_snprintf(name, sizeof(name), "%s_proxy", ((ID *)(gob ? gob : ob))->name + 2);
358
359                 /* Add new object for the proxy */
360                 newob = BKE_object_add_from(bmain, scene, view_layer, OB_EMPTY, name, gob ? gob : ob);
361
362                 /* set layers OK */
363                 BKE_object_make_proxy(newob, ob, gob);
364
365                 /* Set back pointer immediately so dependency graph knows that this is
366                  * is a proxy and will act accordingly. Otherwise correctness of graph
367                  * will depend on order of bases.
368                  *
369                  * TODO(sergey): We really need to get rid of this bi-directional links
370                  * in proxies with something like static overrides.
371                  */
372                 newob->proxy->proxy_from = newob;
373
374                 /* depsgraph flushes are needed for the new data */
375                 DEG_relations_tag_update(bmain);
376                 DEG_id_tag_update(&newob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
377                 WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, newob);
378         }
379         else {
380                 BKE_report(op->reports, RPT_ERROR, "No object to make proxy for");
381                 return OPERATOR_CANCELLED;
382         }
383
384         return OPERATOR_FINISHED;
385 }
386
387 /* Generic itemf's for operators that take library args */
388 static const EnumPropertyItem *proxy_collection_object_itemf(bContext *C, PointerRNA *UNUSED(ptr),
389                                                              PropertyRNA *UNUSED(prop), bool *r_free)
390 {
391         EnumPropertyItem item_tmp = {0}, *item = NULL;
392         int totitem = 0;
393         int i = 0;
394         Object *ob = ED_object_active_context(C);
395
396         if (!ob || !ob->dup_group)
397                 return DummyRNA_DEFAULT_items;
398
399         /* find the object to affect */
400         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(ob->dup_group, object)
401         {
402                 item_tmp.identifier = item_tmp.name = object->id.name + 2;
403                 item_tmp.value = i++;
404                 RNA_enum_item_add(&item, &totitem, &item_tmp);
405         }
406         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
407
408         RNA_enum_item_end(&item, &totitem);
409         *r_free = true;
410
411         return item;
412 }
413
414 void OBJECT_OT_proxy_make(wmOperatorType *ot)
415 {
416         PropertyRNA *prop;
417
418         /* identifiers */
419         ot->name = "Make Proxy";
420         ot->idname = "OBJECT_OT_proxy_make";
421         ot->description = "Add empty object to become local replacement data of a library-linked object";
422
423         /* callbacks */
424         ot->invoke = make_proxy_invoke;
425         ot->exec = make_proxy_exec;
426         ot->poll = ED_operator_object_active;
427
428         /* flags */
429         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
430
431         /* properties */
432         /* XXX, relies on hard coded ID at the moment */
433         prop = RNA_def_enum(ot->srna, "object", DummyRNA_DEFAULT_items, 0, "Proxy Object",
434                             "Name of lib-linked/collection object to make a proxy for");
435         RNA_def_enum_funcs(prop, proxy_collection_object_itemf);
436         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
437         ot->prop = prop;
438 }
439
440 /********************** Clear Parent Operator ******************* */
441
442 typedef enum eObClearParentTypes {
443         CLEAR_PARENT_ALL = 0,
444         CLEAR_PARENT_KEEP_TRANSFORM,
445         CLEAR_PARENT_INVERSE
446 } eObClearParentTypes;
447
448 EnumPropertyItem prop_clear_parent_types[] = {
449         {CLEAR_PARENT_ALL, "CLEAR", 0, "Clear Parent",
450          "Completely clear the parenting relationship, including involved modifiers if any"},
451         {CLEAR_PARENT_KEEP_TRANSFORM, "CLEAR_KEEP_TRANSFORM", 0, "Clear and Keep Transformation",
452          "As 'Clear Parent', but keep the current visual transformations of the object"},
453         {CLEAR_PARENT_INVERSE, "CLEAR_INVERSE", 0, "Clear Parent Inverse",
454          "Reset the transform corrections applied to the parenting relationship, does not remove parenting itself"},
455         {0, NULL, 0, NULL, NULL}
456 };
457
458 /* Helper for ED_object_parent_clear() - Remove deform-modifiers associated with parent */
459 static void object_remove_parent_deform_modifiers(Object *ob, const Object *par)
460 {
461         if (ELEM(par->type, OB_ARMATURE, OB_LATTICE, OB_CURVE)) {
462                 ModifierData *md, *mdn;
463
464                 /* assume that we only need to remove the first instance of matching deform modifier here */
465                 for (md = ob->modifiers.first; md; md = mdn) {
466                         bool free = false;
467
468                         mdn = md->next;
469
470                         /* need to match types (modifier + parent) and references */
471                         if ((md->type == eModifierType_Armature) && (par->type == OB_ARMATURE)) {
472                                 ArmatureModifierData *amd = (ArmatureModifierData *)md;
473                                 if (amd->object == par) {
474                                         free = true;
475                                 }
476                         }
477                         else if ((md->type == eModifierType_Lattice) && (par->type == OB_LATTICE)) {
478                                 LatticeModifierData *lmd = (LatticeModifierData *)md;
479                                 if (lmd->object == par) {
480                                         free = true;
481                                 }
482                         }
483                         else if ((md->type == eModifierType_Curve) && (par->type == OB_CURVE)) {
484                                 CurveModifierData *cmd = (CurveModifierData *)md;
485                                 if (cmd->object == par) {
486                                         free = true;
487                                 }
488                         }
489
490                         /* free modifier if match */
491                         if (free) {
492                                 BLI_remlink(&ob->modifiers, md);
493                                 modifier_free(md);
494                         }
495                 }
496         }
497 }
498
499 void ED_object_parent_clear(Object *ob, const int type)
500 {
501         if (ob->parent == NULL)
502                 return;
503
504         switch (type) {
505                 case CLEAR_PARENT_ALL:
506                 {
507                         /* for deformers, remove corresponding modifiers to prevent a large number of modifiers building up */
508                         object_remove_parent_deform_modifiers(ob, ob->parent);
509
510                         /* clear parenting relationship completely */
511                         ob->parent = NULL;
512                         break;
513                 }
514                 case CLEAR_PARENT_KEEP_TRANSFORM:
515                 {
516                         /* remove parent, and apply the parented transform result as object's local transforms */
517                         ob->parent = NULL;
518                         BKE_object_apply_mat4(ob, ob->obmat, true, false);
519                         break;
520                 }
521                 case CLEAR_PARENT_INVERSE:
522                 {
523                         /* object stays parented, but the parent inverse (i.e. offset from parent to retain binding state)
524                          * is cleared. In other words: nothing to do here! */
525                         break;
526                 }
527         }
528
529         /* Always clear parentinv matrix for sake of consistency, see T41950. */
530         unit_m4(ob->parentinv);
531
532         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
533 }
534
535 /* note, poll should check for editable scene */
536 static int parent_clear_exec(bContext *C, wmOperator *op)
537 {
538         Main *bmain = CTX_data_main(C);
539         const int type = RNA_enum_get(op->ptr, "type");
540
541         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
542         {
543                 ED_object_parent_clear(ob, type);
544         }
545         CTX_DATA_END;
546
547         DEG_relations_tag_update(bmain);
548         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
549         WM_event_add_notifier(C, NC_OBJECT | ND_PARENT, NULL);
550         return OPERATOR_FINISHED;
551 }
552
553 void OBJECT_OT_parent_clear(wmOperatorType *ot)
554 {
555         /* identifiers */
556         ot->name = "Clear Parent";
557         ot->description = "Clear the object's parenting";
558         ot->idname = "OBJECT_OT_parent_clear";
559
560         /* api callbacks */
561         ot->invoke = WM_menu_invoke;
562         ot->exec = parent_clear_exec;
563
564         ot->poll = ED_operator_object_active_editable;
565
566         /* flags */
567         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
568
569         ot->prop = RNA_def_enum(ot->srna, "type", prop_clear_parent_types, CLEAR_PARENT_ALL, "Type", "");
570 }
571
572 /* ******************** Make Parent Operator *********************** */
573
574 void ED_object_parent(Object *ob, Object *par, const int type, const char *substr)
575 {
576         /* Always clear parentinv matrix for sake of consistency, see T41950. */
577         unit_m4(ob->parentinv);
578
579         if (!par || BKE_object_parent_loop_check(par, ob)) {
580                 ob->parent = NULL;
581                 ob->partype = PAROBJECT;
582                 ob->parsubstr[0] = 0;
583                 return;
584         }
585
586         /* Other partypes are deprecated, do not use here! */
587         BLI_assert(ELEM(type & PARTYPE, PAROBJECT, PARSKEL, PARVERT1, PARVERT3, PARBONE));
588
589         /* this could use some more checks */
590
591         ob->parent = par;
592         ob->partype &= ~PARTYPE;
593         ob->partype |= type;
594         BLI_strncpy(ob->parsubstr, substr, sizeof(ob->parsubstr));
595 }
596
597 /* Operator Property */
598 EnumPropertyItem prop_make_parent_types[] = {
599         {PAR_OBJECT, "OBJECT", 0, "Object", ""},
600         {PAR_ARMATURE, "ARMATURE", 0, "Armature Deform", ""},
601         {PAR_ARMATURE_NAME, "ARMATURE_NAME", 0, "   With Empty Groups", ""},
602         {PAR_ARMATURE_AUTO, "ARMATURE_AUTO", 0, "   With Automatic Weights", ""},
603         {PAR_ARMATURE_ENVELOPE, "ARMATURE_ENVELOPE", 0, "   With Envelope Weights", ""},
604         {PAR_BONE, "BONE", 0, "Bone", ""},
605         {PAR_BONE_RELATIVE, "BONE_RELATIVE", 0, "Bone Relative", ""},
606         {PAR_CURVE, "CURVE", 0, "Curve Deform", ""},
607         {PAR_FOLLOW, "FOLLOW", 0, "Follow Path", ""},
608         {PAR_PATH_CONST, "PATH_CONST", 0, "Path Constraint", ""},
609         {PAR_LATTICE, "LATTICE", 0, "Lattice Deform", ""},
610         {PAR_VERTEX, "VERTEX", 0, "Vertex", ""},
611         {PAR_VERTEX_TRI, "VERTEX_TRI", 0, "Vertex (Triangle)", ""},
612         {0, NULL, 0, NULL, NULL}
613 };
614
615 bool ED_object_parent_set(ReportList *reports, const bContext *C, Scene *scene, Object *ob, Object *par,
616                           int partype, const bool xmirror, const bool keep_transform, const int vert_par[3])
617 {
618         Main *bmain = CTX_data_main(C);
619         Depsgraph *depsgraph = CTX_data_depsgraph(C);
620         bPoseChannel *pchan = NULL;
621         const bool pararm = ELEM(partype, PAR_ARMATURE, PAR_ARMATURE_NAME, PAR_ARMATURE_ENVELOPE, PAR_ARMATURE_AUTO);
622
623         DEG_id_tag_update(&par->id, OB_RECALC_OB);
624
625         /* preconditions */
626         if (partype == PAR_FOLLOW || partype == PAR_PATH_CONST) {
627                 if (par->type != OB_CURVE)
628                         return 0;
629                 else {
630                         Curve *cu = par->data;
631
632                         if ((cu->flag & CU_PATH) == 0) {
633                                 cu->flag |= CU_PATH | CU_FOLLOW;
634                                 BKE_displist_make_curveTypes(depsgraph, scene, par, 0);  /* force creation of path data */
635                         }
636                         else {
637                                 cu->flag |= CU_FOLLOW;
638                         }
639
640                         /* if follow, add F-Curve for ctime (i.e. "eval_time") so that path-follow works */
641                         if (partype == PAR_FOLLOW) {
642                                 /* get or create F-Curve */
643                                 bAction *act = verify_adt_action(bmain, &cu->id, 1);
644                                 FCurve *fcu = verify_fcurve(act, NULL, NULL, "eval_time", 0, 1);
645
646                                 /* setup dummy 'generator' modifier here to get 1-1 correspondence still working */
647                                 if (!fcu->bezt && !fcu->fpt && !fcu->modifiers.first)
648                                         add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR, fcu);
649                         }
650
651                         /* fall back on regular parenting now (for follow only) */
652                         if (partype == PAR_FOLLOW)
653                                 partype = PAR_OBJECT;
654                 }
655         }
656         else if (ELEM(partype, PAR_BONE, PAR_BONE_RELATIVE)) {
657                 pchan = BKE_pose_channel_active(par);
658
659                 if (pchan == NULL) {
660                         BKE_report(reports, RPT_ERROR, "No active bone");
661                         return false;
662                 }
663         }
664
665         if (ob != par) {
666                 if (BKE_object_parent_loop_check(par, ob)) {
667                         BKE_report(reports, RPT_ERROR, "Loop in parents");
668                         return false;
669                 }
670                 else {
671                         Object workob;
672
673                         /* apply transformation of previous parenting */
674                         if (keep_transform) {
675                                 /* was removed because of bug [#23577],
676                                  * but this can be handy in some cases too [#32616], so make optional */
677                                 BKE_object_apply_mat4(ob, ob->obmat, false, false);
678                         }
679
680                         /* set the parent (except for follow-path constraint option) */
681                         if (partype != PAR_PATH_CONST) {
682                                 ob->parent = par;
683                                 /* Always clear parentinv matrix for sake of consistency, see T41950. */
684                                 unit_m4(ob->parentinv);
685                         }
686
687                         /* handle types */
688                         if (pchan)
689                                 BLI_strncpy(ob->parsubstr, pchan->name, sizeof(ob->parsubstr));
690                         else
691                                 ob->parsubstr[0] = 0;
692
693                         if (partype == PAR_PATH_CONST) {
694                                 /* don't do anything here, since this is not technically "parenting" */
695                         }
696                         else if (ELEM(partype, PAR_CURVE, PAR_LATTICE) || (pararm)) {
697                                 /* partype is now set to PAROBJECT so that invisible 'virtual' modifiers don't need to be created
698                                  * NOTE: the old (2.4x) method was to set ob->partype = PARSKEL, creating the virtual modifiers
699                                  */
700                                 ob->partype = PAROBJECT;  /* note, dna define, not operator property */
701                                 /* ob->partype = PARSKEL; */  /* note, dna define, not operator property */
702
703                                 /* BUT, to keep the deforms, we need a modifier, and then we need to set the object that it uses
704                                  * - We need to ensure that the modifier we're adding doesn't already exist, so we check this by
705                                  *   assuming that the parent is selected too...
706                                  */
707                                 /* XXX currently this should only happen for meshes, curves, surfaces,
708                                  * and lattices - this stuff isn't available for metas yet */
709                                 if (ELEM(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
710                                         ModifierData *md;
711
712                                         switch (partype) {
713                                                 case PAR_CURVE: /* curve deform */
714                                                         if (modifiers_isDeformedByCurve(ob) != par) {
715                                                                 md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Curve);
716                                                                 if (md) {
717                                                                         ((CurveModifierData *)md)->object = par;
718                                                                 }
719                                                                 if (par->curve_cache && par->curve_cache->path == NULL) {
720                                                                         DEG_id_tag_update(&par->id, OB_RECALC_DATA);
721                                                                 }
722                                                         }
723                                                         break;
724                                                 case PAR_LATTICE: /* lattice deform */
725                                                         if (modifiers_isDeformedByLattice(ob) != par) {
726                                                                 md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Lattice);
727                                                                 if (md) {
728                                                                         ((LatticeModifierData *)md)->object = par;
729                                                                 }
730                                                         }
731                                                         break;
732                                                 default: /* armature deform */
733                                                         if (modifiers_isDeformedByArmature(ob) != par) {
734                                                                 md = ED_object_modifier_add(reports, bmain, scene, ob, NULL, eModifierType_Armature);
735                                                                 if (md) {
736                                                                         ((ArmatureModifierData *)md)->object = par;
737                                                                 }
738                                                         }
739                                                         break;
740                                         }
741                                 }
742                         }
743                         else if (partype == PAR_BONE) {
744                                 ob->partype = PARBONE;  /* note, dna define, not operator property */
745                                 if (pchan->bone)
746                                         pchan->bone->flag &= ~BONE_RELATIVE_PARENTING;
747                         }
748                         else if (partype == PAR_BONE_RELATIVE) {
749                                 ob->partype = PARBONE;  /* note, dna define, not operator property */
750                                 if (pchan->bone)
751                                         pchan->bone->flag |= BONE_RELATIVE_PARENTING;
752                         }
753                         else if (partype == PAR_VERTEX) {
754                                 ob->partype = PARVERT1;
755                                 ob->par1 = vert_par[0];
756                         }
757                         else if (partype == PAR_VERTEX_TRI) {
758                                 ob->partype = PARVERT3;
759                                 copy_v3_v3_int(&ob->par1, vert_par);
760                         }
761                         else {
762                                 ob->partype = PAROBJECT;  /* note, dna define, not operator property */
763                         }
764
765                         /* constraint */
766                         if (partype == PAR_PATH_CONST) {
767                                 bConstraint *con;
768                                 bFollowPathConstraint *data;
769                                 float cmat[4][4], vec[3];
770
771                                 con = BKE_constraint_add_for_object(ob, "AutoPath", CONSTRAINT_TYPE_FOLLOWPATH);
772
773                                 data = con->data;
774                                 data->tar = par;
775
776                                 BKE_constraint_target_matrix_get(depsgraph, scene, con, 0, CONSTRAINT_OBTYPE_OBJECT, NULL, cmat, scene->r.cfra);
777                                 sub_v3_v3v3(vec, ob->obmat[3], cmat[3]);
778
779                                 copy_v3_v3(ob->loc, vec);
780                         }
781                         else if (pararm && (ob->type == OB_MESH) && (par->type == OB_ARMATURE)) {
782                                 if (partype == PAR_ARMATURE_NAME) {
783                                         ED_object_vgroup_calc_from_armature(reports, depsgraph, scene, ob, par, ARM_GROUPS_NAME, false);
784                                 }
785                                 else if (partype == PAR_ARMATURE_ENVELOPE) {
786                                         ED_object_vgroup_calc_from_armature(reports, depsgraph, scene, ob, par, ARM_GROUPS_ENVELOPE, xmirror);
787                                 }
788                                 else if (partype == PAR_ARMATURE_AUTO) {
789                                         WM_cursor_wait(1);
790                                         ED_object_vgroup_calc_from_armature(reports, depsgraph, scene, ob, par, ARM_GROUPS_AUTO, xmirror);
791                                         WM_cursor_wait(0);
792                                 }
793                                 /* get corrected inverse */
794                                 ob->partype = PAROBJECT;
795                                 BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
796
797                                 invert_m4_m4(ob->parentinv, workob.obmat);
798                         }
799                         else {
800                                 /* calculate inverse parent matrix */
801                                 BKE_object_workob_calc_parent(depsgraph, scene, ob, &workob);
802                                 invert_m4_m4(ob->parentinv, workob.obmat);
803                         }
804
805                         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
806                 }
807         }
808
809         return true;
810 }
811
812
813
814 static void parent_set_vert_find(KDTree *tree, Object *child, int vert_par[3], bool is_tri)
815 {
816         const float *co_find = child->obmat[3];
817         if (is_tri) {
818                 KDTreeNearest nearest[3];
819                 int tot;
820
821                 tot = BLI_kdtree_find_nearest_n(tree, co_find, nearest, 3);
822                 BLI_assert(tot == 3);
823                 UNUSED_VARS(tot);
824
825                 vert_par[0] = nearest[0].index;
826                 vert_par[1] = nearest[1].index;
827                 vert_par[2] = nearest[2].index;
828
829                 BLI_assert(min_iii(UNPACK3(vert_par)) >= 0);
830         }
831         else {
832                 vert_par[0] = BLI_kdtree_find_nearest(tree, co_find, NULL);
833                 BLI_assert(vert_par[0] >= 0);
834                 vert_par[1] = 0;
835                 vert_par[2] = 0;
836         }
837 }
838
839 static int parent_set_exec(bContext *C, wmOperator *op)
840 {
841         Main *bmain = CTX_data_main(C);
842         Scene *scene = CTX_data_scene(C);
843         Object *par = ED_object_active_context(C);
844         int partype = RNA_enum_get(op->ptr, "type");
845         const bool xmirror = RNA_boolean_get(op->ptr, "xmirror");
846         const bool keep_transform = RNA_boolean_get(op->ptr, "keep_transform");
847         bool ok = true;
848
849         /* vertex parent (kdtree) */
850         const bool is_vert_par = ELEM(partype, PAR_VERTEX, PAR_VERTEX_TRI);
851         const bool is_tri = partype == PAR_VERTEX_TRI;
852         int tree_tot;
853         struct KDTree *tree = NULL;
854         int vert_par[3] = {0, 0, 0};
855         const int *vert_par_p = is_vert_par ? vert_par : NULL;
856
857
858         if (is_vert_par) {
859                 tree = BKE_object_as_kdtree(par, &tree_tot);
860                 BLI_assert(tree != NULL);
861
862                 if (tree_tot < (is_tri ? 3 : 1)) {
863                         BKE_report(op->reports, RPT_ERROR, "Not enough vertices for vertex-parent");
864                         ok = false;
865                 }
866         }
867
868         if (ok) {
869                 /* Non vertex-parent */
870                 CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
871                 {
872                         if (is_vert_par) {
873                                 parent_set_vert_find(tree, ob, vert_par, is_tri);
874                         }
875
876                         if (!ED_object_parent_set(op->reports, C, scene, ob, par, partype, xmirror, keep_transform, vert_par_p)) {
877                                 ok = false;
878                                 break;
879                         }
880                 }
881                 CTX_DATA_END;
882         }
883
884         if (is_vert_par) {
885                 BLI_kdtree_free(tree);
886         }
887
888         if (!ok)
889                 return OPERATOR_CANCELLED;
890
891         DEG_relations_tag_update(bmain);
892         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
893         WM_event_add_notifier(C, NC_OBJECT | ND_PARENT, NULL);
894
895         return OPERATOR_FINISHED;
896 }
897
898
899 static int parent_set_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
900 {
901         Object *ob = ED_object_active_context(C);
902         uiPopupMenu *pup = UI_popup_menu_begin(C, IFACE_("Set Parent To"), ICON_NONE);
903         uiLayout *layout = UI_popup_menu_layout(pup);
904
905         wmOperatorType *ot = WM_operatortype_find("OBJECT_OT_parent_set", true);
906         PointerRNA opptr;
907
908 #if 0
909         uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_OBJECT);
910 #else
911         uiItemFullO_ptr(layout, ot, IFACE_("Object"), ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
912         RNA_enum_set(&opptr, "type", PAR_OBJECT);
913         RNA_boolean_set(&opptr, "keep_transform", false);
914
915         uiItemFullO_ptr(
916                 layout, ot, IFACE_("Object (Keep Transform)"), ICON_NONE,
917                 NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
918         RNA_enum_set(&opptr, "type", PAR_OBJECT);
919         RNA_boolean_set(&opptr, "keep_transform", true);
920 #endif
921         /* ob becomes parent, make the associated menus */
922         if (ob->type == OB_ARMATURE) {
923                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE);
924                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_NAME);
925                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_ENVELOPE);
926                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_ARMATURE_AUTO);
927                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_BONE);
928                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_BONE_RELATIVE);
929         }
930         else if (ob->type == OB_CURVE) {
931                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_CURVE);
932                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_FOLLOW);
933                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_PATH_CONST);
934         }
935         else if (ob->type == OB_LATTICE) {
936                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_LATTICE);
937         }
938
939         /* vertex parenting */
940         if (OB_TYPE_SUPPORT_PARVERT(ob->type)) {
941                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_VERTEX);
942                 uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_VERTEX_TRI);
943         }
944
945         UI_popup_menu_end(C, pup);
946
947         return OPERATOR_INTERFACE;
948 }
949
950 static bool parent_set_draw_check_prop(PointerRNA *ptr, PropertyRNA *prop)
951 {
952         const char *prop_id = RNA_property_identifier(prop);
953         const int type = RNA_enum_get(ptr, "type");
954
955         /* Only show XMirror for PAR_ARMATURE_ENVELOPE and PAR_ARMATURE_AUTO! */
956         if (STREQ(prop_id, "xmirror")) {
957                 if (ELEM(type, PAR_ARMATURE_ENVELOPE, PAR_ARMATURE_AUTO))
958                         return true;
959                 else
960                         return false;
961         }
962
963         return true;
964 }
965
966 static void parent_set_ui(bContext *C, wmOperator *op)
967 {
968         uiLayout *layout = op->layout;
969         wmWindowManager *wm = CTX_wm_manager(C);
970         PointerRNA ptr;
971
972         RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr);
973
974         /* Main auto-draw call. */
975         uiDefAutoButsRNA(layout, &ptr, parent_set_draw_check_prop, UI_BUT_LABEL_ALIGN_NONE, false);
976 }
977
978 void OBJECT_OT_parent_set(wmOperatorType *ot)
979 {
980         /* identifiers */
981         ot->name = "Make Parent";
982         ot->description = "Set the object's parenting";
983         ot->idname = "OBJECT_OT_parent_set";
984
985         /* api callbacks */
986         ot->invoke = parent_set_invoke;
987         ot->exec = parent_set_exec;
988         ot->poll = ED_operator_object_active;
989         ot->ui = parent_set_ui;
990
991         /* flags */
992         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
993
994         ot->prop = RNA_def_enum(ot->srna, "type", prop_make_parent_types, 0, "Type", "");
995         RNA_def_boolean(ot->srna, "xmirror", false, "X Mirror",
996                         "Apply weights symmetrically along X axis, for Envelope/Automatic vertex groups creation");
997         RNA_def_boolean(ot->srna, "keep_transform", false, "Keep Transform",
998                         "Apply transformation before parenting");
999 }
1000
1001 /* ************ Make Parent Without Inverse Operator ******************* */
1002
1003 static int parent_noinv_set_exec(bContext *C, wmOperator *op)
1004 {
1005         Main *bmain = CTX_data_main(C);
1006         Object *par = ED_object_active_context(C);
1007
1008         DEG_id_tag_update(&par->id, OB_RECALC_OB);
1009
1010         /* context iterator */
1011         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1012         {
1013                 if (ob != par) {
1014                         if (BKE_object_parent_loop_check(par, ob)) {
1015                                 BKE_report(op->reports, RPT_ERROR, "Loop in parents");
1016                         }
1017                         else {
1018                                 /* clear inverse matrix and also the object location */
1019                                 unit_m4(ob->parentinv);
1020                                 memset(ob->loc, 0, 3 * sizeof(float));
1021
1022                                 /* set recalc flags */
1023                                 DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
1024
1025                                 /* set parenting type for object - object only... */
1026                                 ob->parent = par;
1027                                 ob->partype = PAROBJECT; /* note, dna define, not operator property */
1028                         }
1029                 }
1030         }
1031         CTX_DATA_END;
1032
1033         DEG_relations_tag_update(bmain);
1034         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1035
1036         return OPERATOR_FINISHED;
1037 }
1038
1039 void OBJECT_OT_parent_no_inverse_set(wmOperatorType *ot)
1040 {
1041         /* identifiers */
1042         ot->name = "Make Parent without Inverse";
1043         ot->description = "Set the object's parenting without setting the inverse parent correction";
1044         ot->idname = "OBJECT_OT_parent_no_inverse_set";
1045
1046         /* api callbacks */
1047         ot->invoke = WM_operator_confirm;
1048         ot->exec = parent_noinv_set_exec;
1049         ot->poll = ED_operator_object_active_editable;
1050
1051         /* flags */
1052         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1053 }
1054
1055 /************************ Clear Slow Parent Operator *********************/
1056
1057 static int object_slow_parent_clear_exec(bContext *C, wmOperator *UNUSED(op))
1058 {
1059         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1060         Scene *scene = CTX_data_scene(C);
1061
1062         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1063         {
1064                 if (ob->parent) {
1065                         if (ob->partype & PARSLOW) {
1066                                 ob->partype -= PARSLOW;
1067                                 BKE_object_where_is_calc(depsgraph, scene, ob);
1068                                 ob->partype |= PARSLOW;
1069                                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1070                         }
1071                 }
1072         }
1073         CTX_DATA_END;
1074
1075         WM_event_add_notifier(C, NC_SCENE, scene);
1076
1077         return OPERATOR_FINISHED;
1078 }
1079
1080 void OBJECT_OT_slow_parent_clear(wmOperatorType *ot)
1081 {
1082         /* identifiers */
1083         ot->name = "Clear Slow Parent";
1084         ot->description = "Clear the object's slow parent";
1085         ot->idname = "OBJECT_OT_slow_parent_clear";
1086
1087         /* api callbacks */
1088         ot->invoke = WM_operator_confirm;
1089         ot->exec = object_slow_parent_clear_exec;
1090         ot->poll = ED_operator_view3d_active;
1091
1092         /* flags */
1093         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1094 }
1095
1096 /********************** Make Slow Parent Operator *********************/
1097
1098 static int object_slow_parent_set_exec(bContext *C, wmOperator *UNUSED(op))
1099 {
1100         Scene *scene = CTX_data_scene(C);
1101
1102         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1103         {
1104                 if (ob->parent)
1105                         ob->partype |= PARSLOW;
1106
1107                 DEG_id_tag_update(&ob->id, OB_RECALC_OB);
1108         }
1109         CTX_DATA_END;
1110
1111         WM_event_add_notifier(C, NC_SCENE, scene);
1112
1113         return OPERATOR_FINISHED;
1114 }
1115
1116 void OBJECT_OT_slow_parent_set(wmOperatorType *ot)
1117 {
1118         /* identifiers */
1119         ot->name = "Set Slow Parent";
1120         ot->description = "Set the object's slow parent";
1121         ot->idname = "OBJECT_OT_slow_parent_set";
1122
1123         /* api callbacks */
1124         ot->invoke = WM_operator_confirm;
1125         ot->exec = object_slow_parent_set_exec;
1126         ot->poll = ED_operator_view3d_active;
1127
1128         /* flags */
1129         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1130 }
1131
1132 /* ******************** Clear Track Operator ******************* */
1133
1134 enum {
1135         CLEAR_TRACK                = 1,
1136         CLEAR_TRACK_KEEP_TRANSFORM = 2,
1137 };
1138
1139 static const EnumPropertyItem prop_clear_track_types[] = {
1140         {CLEAR_TRACK, "CLEAR", 0, "Clear Track", ""},
1141         {CLEAR_TRACK_KEEP_TRANSFORM, "CLEAR_KEEP_TRANSFORM", 0, "Clear and Keep Transformation (Clear Track)", ""},
1142         {0, NULL, 0, NULL, NULL}
1143 };
1144
1145 /* note, poll should check for editable scene */
1146 static int object_track_clear_exec(bContext *C, wmOperator *op)
1147 {
1148         Main *bmain = CTX_data_main(C);
1149         const int type = RNA_enum_get(op->ptr, "type");
1150
1151         if (CTX_data_edit_object(C)) {
1152                 BKE_report(op->reports, RPT_ERROR, "Operation cannot be performed in edit mode");
1153                 return OPERATOR_CANCELLED;
1154         }
1155         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1156         {
1157                 bConstraint *con, *pcon;
1158
1159                 /* remove track-object for old track */
1160                 ob->track = NULL;
1161                 DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1162
1163                 /* also remove all tracking constraints */
1164                 for (con = ob->constraints.last; con; con = pcon) {
1165                         pcon = con->prev;
1166                         if (ELEM(con->type, CONSTRAINT_TYPE_TRACKTO, CONSTRAINT_TYPE_LOCKTRACK, CONSTRAINT_TYPE_DAMPTRACK))
1167                                 BKE_constraint_remove(&ob->constraints, con);
1168                 }
1169
1170                 if (type == CLEAR_TRACK_KEEP_TRANSFORM)
1171                         BKE_object_apply_mat4(ob, ob->obmat, true, true);
1172         }
1173         CTX_DATA_END;
1174
1175         DEG_relations_tag_update(bmain);
1176         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1177
1178         return OPERATOR_FINISHED;
1179 }
1180
1181 void OBJECT_OT_track_clear(wmOperatorType *ot)
1182 {
1183         /* identifiers */
1184         ot->name = "Clear Track";
1185         ot->description = "Clear tracking constraint or flag from object";
1186         ot->idname = "OBJECT_OT_track_clear";
1187
1188         /* api callbacks */
1189         ot->invoke = WM_menu_invoke;
1190         ot->exec = object_track_clear_exec;
1191
1192         ot->poll = ED_operator_objectmode;
1193
1194         /* flags */
1195         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1196
1197         ot->prop = RNA_def_enum(ot->srna, "type", prop_clear_track_types, 0, "Type", "");
1198 }
1199
1200 /************************** Make Track Operator *****************************/
1201
1202 enum {
1203         CREATE_TRACK_DAMPTRACK = 1,
1204         CREATE_TRACK_TRACKTO   = 2,
1205         CREATE_TRACK_LOCKTRACK = 3,
1206 };
1207
1208 static const EnumPropertyItem prop_make_track_types[] = {
1209         {CREATE_TRACK_DAMPTRACK, "DAMPTRACK", 0, "Damped Track Constraint", ""},
1210         {CREATE_TRACK_TRACKTO, "TRACKTO", 0, "Track To Constraint", ""},
1211         {CREATE_TRACK_LOCKTRACK, "LOCKTRACK", 0, "Lock Track Constraint", ""},
1212         {0, NULL, 0, NULL, NULL}
1213 };
1214
1215 static int track_set_exec(bContext *C, wmOperator *op)
1216 {
1217         Main *bmain = CTX_data_main(C);
1218         Object *obact = ED_object_active_context(C);
1219
1220         const int type = RNA_enum_get(op->ptr, "type");
1221
1222         switch (type) {
1223                 case CREATE_TRACK_DAMPTRACK:
1224                 {
1225                         bConstraint *con;
1226                         bDampTrackConstraint *data;
1227
1228                         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1229                         {
1230                                 if (ob != obact) {
1231                                         con = BKE_constraint_add_for_object(ob, "AutoTrack", CONSTRAINT_TYPE_DAMPTRACK);
1232
1233                                         data = con->data;
1234                                         data->tar = obact;
1235                                         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1236
1237                                         /* Lamp, Camera and Speaker track differently by default */
1238                                         if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1239                                                 data->trackflag = TRACK_nZ;
1240                                         }
1241                                 }
1242                         }
1243                         CTX_DATA_END;
1244                         break;
1245                 }
1246                 case CREATE_TRACK_TRACKTO:
1247                 {
1248                         bConstraint *con;
1249                         bTrackToConstraint *data;
1250
1251                         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1252                         {
1253                                 if (ob != obact) {
1254                                         con = BKE_constraint_add_for_object(ob, "AutoTrack", CONSTRAINT_TYPE_TRACKTO);
1255
1256                                         data = con->data;
1257                                         data->tar = obact;
1258                                         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1259
1260                                         /* Lamp, Camera and Speaker track differently by default */
1261                                         if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1262                                                 data->reserved1 = TRACK_nZ;
1263                                                 data->reserved2 = UP_Y;
1264                                         }
1265                                 }
1266                         }
1267                         CTX_DATA_END;
1268                         break;
1269                 }
1270                 case CREATE_TRACK_LOCKTRACK:
1271                 {
1272                         bConstraint *con;
1273                         bLockTrackConstraint *data;
1274
1275                         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1276                         {
1277                                 if (ob != obact) {
1278                                         con = BKE_constraint_add_for_object(ob, "AutoTrack", CONSTRAINT_TYPE_LOCKTRACK);
1279
1280                                         data = con->data;
1281                                         data->tar = obact;
1282                                         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1283
1284                                         /* Lamp, Camera and Speaker track differently by default */
1285                                         if (ELEM(ob->type, OB_LAMP, OB_CAMERA, OB_SPEAKER)) {
1286                                                 data->trackflag = TRACK_nZ;
1287                                                 data->lockflag = LOCK_Y;
1288                                         }
1289                                 }
1290                         }
1291                         CTX_DATA_END;
1292                         break;
1293                 }
1294         }
1295
1296         DEG_relations_tag_update(bmain);
1297         WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, NULL);
1298
1299         return OPERATOR_FINISHED;
1300 }
1301
1302 void OBJECT_OT_track_set(wmOperatorType *ot)
1303 {
1304         /* identifiers */
1305         ot->name = "Make Track";
1306         ot->description = "Make the object track another object, using various methods/constraints";
1307         ot->idname = "OBJECT_OT_track_set";
1308
1309         /* api callbacks */
1310         ot->invoke = WM_menu_invoke;
1311         ot->exec = track_set_exec;
1312
1313         ot->poll = ED_operator_objectmode;
1314
1315         /* flags */
1316         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1317
1318         /* properties */
1319         ot->prop = RNA_def_enum(ot->srna, "type", prop_make_track_types, 0, "Type", "");
1320 }
1321
1322 /************************** Link to Scene Operator *****************************/
1323
1324 #if 0
1325 static void link_to_scene(Main *UNUSED(bmain), unsigned short UNUSED(nr))
1326 {
1327         Scene *sce = (Scene *) BLI_findlink(&bmain->scene, G.curscreen->scenenr - 1);
1328         Base *base, *nbase;
1329
1330         if (sce == NULL) return;
1331         if (sce->id.lib) return;
1332
1333         for (base = FIRSTBASE; base; base = base->next) {
1334                 if (TESTBASE(v3d, base)) {
1335                         nbase = MEM_mallocN(sizeof(Base), "newbase");
1336                         *nbase = *base;
1337                         BLI_addhead(&(sce->base), nbase);
1338                         id_us_plus((ID *)base->object);
1339                 }
1340         }
1341 }
1342 #endif
1343
1344 static int make_links_scene_exec(bContext *C, wmOperator *op)
1345 {
1346         Main *bmain = CTX_data_main(C);
1347         Scene *scene_to = BLI_findlink(&bmain->scene, RNA_enum_get(op->ptr, "scene"));
1348
1349         if (scene_to == NULL) {
1350                 BKE_report(op->reports, RPT_ERROR, "Could not find scene");
1351                 return OPERATOR_CANCELLED;
1352         }
1353
1354         if (scene_to == CTX_data_scene(C)) {
1355                 BKE_report(op->reports, RPT_ERROR, "Cannot link objects into the same scene");
1356                 return OPERATOR_CANCELLED;
1357         }
1358
1359         if (ID_IS_LINKED(scene_to)) {
1360                 BKE_report(op->reports, RPT_ERROR, "Cannot link objects into a linked scene");
1361                 return OPERATOR_CANCELLED;
1362         }
1363
1364         Collection *collection_to = BKE_collection_master(scene_to);
1365         CTX_DATA_BEGIN (C, Base *, base, selected_bases)
1366         {
1367                 BKE_collection_object_add(bmain, collection_to, base->object);
1368         }
1369         CTX_DATA_END;
1370
1371         /* redraw the 3D view because the object center points are colored differently */
1372         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, NULL);
1373
1374         /* one day multiple scenes will be visible, then we should have some update function for them */
1375         return OPERATOR_FINISHED;
1376 }
1377
1378 enum {
1379         MAKE_LINKS_OBDATA     = 1,
1380         MAKE_LINKS_MATERIALS  = 2,
1381         MAKE_LINKS_ANIMDATA   = 3,
1382         MAKE_LINKS_GROUP      = 4,
1383         MAKE_LINKS_DUPLICOLLECTION = 5,
1384         MAKE_LINKS_MODIFIERS  = 6,
1385         MAKE_LINKS_FONTS      = 7,
1386 };
1387
1388 /* Return true if make link data is allowed, false otherwise */
1389 static bool allow_make_links_data(const int type, Object *ob_src, Object *ob_dst)
1390 {
1391         switch (type) {
1392                 case MAKE_LINKS_OBDATA:
1393                         if (ob_src->type == ob_dst->type && ob_src->type != OB_EMPTY) {
1394                                 return true;
1395                         }
1396                         break;
1397                 case MAKE_LINKS_MATERIALS:
1398                         if (OB_TYPE_SUPPORT_MATERIAL(ob_src->type) && OB_TYPE_SUPPORT_MATERIAL(ob_dst->type)) {
1399                                 return true;
1400                         }
1401                         break;
1402                 case MAKE_LINKS_ANIMDATA:
1403                 case MAKE_LINKS_GROUP:
1404                 case MAKE_LINKS_DUPLICOLLECTION:
1405                         return true;
1406                 case MAKE_LINKS_MODIFIERS:
1407                         if (!ELEM(OB_EMPTY, ob_src->type, ob_dst->type)) {
1408                                 return true;
1409                         }
1410                         break;
1411                 case MAKE_LINKS_FONTS:
1412                         if ((ob_src->data != ob_dst->data) && (ob_src->type == OB_FONT) && (ob_dst->type == OB_FONT)) {
1413                                 return true;
1414                         }
1415                         break;
1416         }
1417         return false;
1418 }
1419
1420 static int make_links_data_exec(bContext *C, wmOperator *op)
1421 {
1422         Main *bmain = CTX_data_main(C);
1423         const int type = RNA_enum_get(op->ptr, "type");
1424         Object *ob_src;
1425         ID *obdata_id;
1426         int a;
1427
1428         /* collection */
1429         LinkNode *ob_collections = NULL;
1430         bool is_cycle = false;
1431         bool is_lib = false;
1432
1433         ob_src = ED_object_active_context(C);
1434
1435         /* avoid searching all collections in source object each time */
1436         if (type == MAKE_LINKS_GROUP) {
1437                 ob_collections = BKE_object_groups(bmain, ob_src);
1438         }
1439
1440         CTX_DATA_BEGIN (C, Base *, base_dst, selected_editable_bases)
1441         {
1442                 Object *ob_dst = base_dst->object;
1443
1444                 if (ob_src != ob_dst) {
1445                         if (allow_make_links_data(type, ob_src, ob_dst)) {
1446                                 obdata_id = ob_dst->data;
1447
1448                                 switch (type) {
1449                                         case MAKE_LINKS_OBDATA: /* obdata */
1450                                                 id_us_min(obdata_id);
1451
1452                                                 obdata_id = ob_src->data;
1453                                                 id_us_plus(obdata_id);
1454                                                 ob_dst->data = obdata_id;
1455
1456                                                 /* if amount of material indices changed: */
1457                                                 test_object_materials(bmain, ob_dst, ob_dst->data);
1458
1459                                                 DEG_id_tag_update(&ob_dst->id, OB_RECALC_DATA);
1460                                                 break;
1461                                         case MAKE_LINKS_MATERIALS:
1462                                                 /* new approach, using functions from kernel */
1463                                                 for (a = 0; a < ob_src->totcol; a++) {
1464                                                         Material *ma = give_current_material(ob_src, a + 1);
1465                                                         assign_material(bmain, ob_dst, ma, a + 1, BKE_MAT_ASSIGN_USERPREF); /* also works with ma==NULL */
1466                                                 }
1467                                                 DEG_id_tag_update(&ob_dst->id, OB_RECALC_DATA);
1468                                                 break;
1469                                         case MAKE_LINKS_ANIMDATA:
1470                                                 BKE_animdata_copy_id(bmain, (ID *)ob_dst, (ID *)ob_src, false, true);
1471                                                 if (ob_dst->data && ob_src->data) {
1472                                                         if (ID_IS_LINKED(obdata_id)) {
1473                                                                 is_lib = true;
1474                                                                 break;
1475                                                         }
1476                                                         BKE_animdata_copy_id(bmain, (ID *)ob_dst->data, (ID *)ob_src->data, false, true);
1477                                                 }
1478                                                 DEG_id_tag_update(&ob_dst->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1479                                                 break;
1480                                         case MAKE_LINKS_GROUP:
1481                                         {
1482                                                 LinkNode *collection_node;
1483
1484                                                 /* first clear collections */
1485                                                 BKE_object_groups_clear(bmain, ob_dst);
1486
1487                                                 /* now add in the collections from the link nodes */
1488                                                 for (collection_node = ob_collections; collection_node; collection_node = collection_node->next) {
1489                                                         if (ob_dst->dup_group != collection_node->link) {
1490                                                                 BKE_collection_object_add(bmain, collection_node->link, ob_dst);
1491                                                         }
1492                                                         else {
1493                                                                 is_cycle = true;
1494                                                         }
1495                                                 }
1496                                                 break;
1497                                         }
1498                                         case MAKE_LINKS_DUPLICOLLECTION:
1499                                                 ob_dst->dup_group = ob_src->dup_group;
1500                                                 if (ob_dst->dup_group) {
1501                                                         id_us_plus(&ob_dst->dup_group->id);
1502                                                         ob_dst->transflag |= OB_DUPLICOLLECTION;
1503                                                 }
1504                                                 break;
1505                                         case MAKE_LINKS_MODIFIERS:
1506                                                 BKE_object_link_modifiers(ob_dst, ob_src);
1507                                                 DEG_id_tag_update(&ob_dst->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1508                                                 break;
1509                                         case MAKE_LINKS_FONTS:
1510                                         {
1511                                                 Curve *cu_src = ob_src->data;
1512                                                 Curve *cu_dst = ob_dst->data;
1513
1514                                                 if (ID_IS_LINKED(obdata_id)) {
1515                                                         is_lib = true;
1516                                                         break;
1517                                                 }
1518
1519                                                 if (cu_dst->vfont)
1520                                                         id_us_min(&cu_dst->vfont->id);
1521                                                 cu_dst->vfont = cu_src->vfont;
1522                                                 id_us_plus((ID *)cu_dst->vfont);
1523                                                 if (cu_dst->vfontb)
1524                                                         id_us_min(&cu_dst->vfontb->id);
1525                                                 cu_dst->vfontb = cu_src->vfontb;
1526                                                 id_us_plus((ID *)cu_dst->vfontb);
1527                                                 if (cu_dst->vfonti)
1528                                                         id_us_min(&cu_dst->vfonti->id);
1529                                                 cu_dst->vfonti = cu_src->vfonti;
1530                                                 id_us_plus((ID *)cu_dst->vfonti);
1531                                                 if (cu_dst->vfontbi)
1532                                                         id_us_min(&cu_dst->vfontbi->id);
1533                                                 cu_dst->vfontbi = cu_src->vfontbi;
1534                                                 id_us_plus((ID *)cu_dst->vfontbi);
1535
1536                                                 DEG_id_tag_update(&ob_dst->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
1537                                                 break;
1538                                         }
1539                                 }
1540                         }
1541                 }
1542         }
1543         CTX_DATA_END;
1544
1545         if (type == MAKE_LINKS_GROUP) {
1546                 if (ob_collections) {
1547                         BLI_linklist_free(ob_collections, NULL);
1548                 }
1549
1550                 if (is_cycle) {
1551                         BKE_report(op->reports, RPT_WARNING, "Skipped some collections because of cycle detected");
1552                 }
1553         }
1554
1555         if (is_lib) {
1556                 BKE_report(op->reports, RPT_WARNING, "Skipped editing library object data");
1557         }
1558
1559         DEG_relations_tag_update(bmain);
1560         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
1561         WM_event_add_notifier(C, NC_ANIMATION | ND_NLA_ACTCHANGE, CTX_wm_view3d(C));
1562         WM_event_add_notifier(C, NC_OBJECT, NULL);
1563
1564         return OPERATOR_FINISHED;
1565 }
1566
1567
1568 void OBJECT_OT_make_links_scene(wmOperatorType *ot)
1569 {
1570         PropertyRNA *prop;
1571
1572         /* identifiers */
1573         ot->name = "Link Objects to Scene";
1574         ot->description = "Link selection to another scene";
1575         ot->idname = "OBJECT_OT_make_links_scene";
1576
1577         /* api callbacks */
1578         ot->invoke = WM_enum_search_invoke;
1579         ot->exec = make_links_scene_exec;
1580         /* better not run the poll check */
1581
1582         /* flags */
1583         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1584
1585         /* properties */
1586         prop = RNA_def_enum(ot->srna, "scene", DummyRNA_NULL_items, 0, "Scene", "");
1587         RNA_def_enum_funcs(prop, RNA_scene_local_itemf);
1588         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
1589         ot->prop = prop;
1590 }
1591
1592 void OBJECT_OT_make_links_data(wmOperatorType *ot)
1593 {
1594         static const EnumPropertyItem make_links_items[] = {
1595                 {MAKE_LINKS_OBDATA,     "OBDATA", 0, "Object Data", ""},
1596                 {MAKE_LINKS_MATERIALS,  "MATERIAL", 0, "Materials", ""},
1597                 {MAKE_LINKS_ANIMDATA,   "ANIMATION", 0, "Animation Data", ""},
1598                 {MAKE_LINKS_GROUP,      "GROUPS", 0, "Group", ""},
1599                 {MAKE_LINKS_DUPLICOLLECTION, "DUPLICOLLECTION", 0, "DupliGroup", ""},
1600                 {MAKE_LINKS_MODIFIERS,  "MODIFIERS", 0, "Modifiers", ""},
1601                 {MAKE_LINKS_FONTS,      "FONTS", 0, "Fonts", ""},
1602                 {0, NULL, 0, NULL, NULL}};
1603
1604         /* identifiers */
1605         ot->name = "Link Data";
1606         ot->description = "Apply active object links to other selected objects";
1607         ot->idname = "OBJECT_OT_make_links_data";
1608
1609         /* api callbacks */
1610         ot->exec = make_links_data_exec;
1611         ot->poll = ED_operator_object_active;
1612
1613         /* flags */
1614         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1615
1616         /* properties */
1617         ot->prop = RNA_def_enum(ot->srna, "type", make_links_items, 0, "Type", "");
1618 }
1619
1620
1621 /**************************** Make Single User ********************************/
1622
1623 static Object *single_object_users_object(Main *bmain, Scene *scene, Object *ob)
1624 {
1625         /* base gets copy of object */
1626         Object *obn = ID_NEW_SET(ob, BKE_object_copy(bmain, ob));
1627
1628         /* remap gpencil parenting */
1629
1630         if (scene->gpd) {
1631                 bGPdata *gpd = scene->gpd;
1632                 for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
1633                         if (gpl->parent == ob) {
1634                                 gpl->parent = obn;
1635                         }
1636                 }
1637         }
1638
1639         id_us_plus(&obn->id);
1640         id_us_min(&ob->id);
1641         return obn;
1642 }
1643
1644 static void libblock_relink_collection(Collection *collection)
1645 {
1646         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
1647                 BKE_libblock_relink_to_newid(&cob->ob->id);
1648         }
1649
1650         for (CollectionChild *child = collection->children.first; child; child = child->next) {
1651                 libblock_relink_collection(child->collection);
1652         }
1653 }
1654
1655 static void single_object_users_collection(Main *bmain, Scene *scene, Collection *collection, const int flag, const bool copy_collections)
1656 {
1657         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
1658                 Object *ob = cob->ob;
1659                 /* an object may be in more than one collection */
1660                 if ((ob->id.newid == NULL) && ((ob->flag & flag) == flag)) {
1661                         if (!ID_IS_LINKED(ob) && ob->id.us > 1) {
1662                                 cob->ob = single_object_users_object(bmain, scene, cob->ob);
1663                         }
1664                 }
1665         }
1666
1667         for (CollectionChild *child = collection->children.first; child; child = child->next) {
1668                 single_object_users_collection(bmain, scene, child->collection, flag, copy_collections);
1669         }
1670 }
1671
1672 /* Warning, sets ID->newid pointers of objects and collections, but does not clear them. */
1673 static void single_object_users(Main *bmain, Scene *scene, View3D *v3d, const int flag, const bool copy_collections)
1674 {
1675         Collection *collection, *collectionn;
1676
1677         /* duplicate all the objects of the scene */
1678         Collection *master_collection = BKE_collection_master(scene);
1679         single_object_users_collection(bmain, scene, master_collection, flag, copy_collections);
1680
1681         /* loop over ViewLayers and assign the pointers accordingly */
1682         for (ViewLayer *view_layer = scene->view_layers.first; view_layer; view_layer = view_layer->next) {
1683                 for (Base *base = view_layer->object_bases.first; base; base = base->next) {
1684                         ID_NEW_REMAP(base->object);
1685                 }
1686         }
1687
1688         /* duplicate collections that consist entirely of duplicated objects */
1689         for (collection = bmain->collection.first; collection; collection = collection->id.next) {
1690                 if (copy_collections) {
1691                         bool all_duplicated = true;
1692                         bool any_duplicated = false;
1693
1694                         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
1695                                 any_duplicated = true;
1696                                 if (cob->ob->id.newid == NULL) {
1697                                         all_duplicated = false;
1698                                         break;
1699                                 }
1700                         }
1701
1702                         if (any_duplicated && all_duplicated) {
1703                                 // TODO: test if this works, with child collections ..
1704                                 collectionn = ID_NEW_SET(collection, BKE_collection_copy(bmain, NULL, collection));
1705
1706                                 for (CollectionObject *cob = collectionn->gobject.first; cob; cob = cob->next) {
1707                                         cob->ob = (Object *)cob->ob->id.newid;
1708                                 }
1709                         }
1710                 }
1711         }
1712
1713         /* collection pointers in scene */
1714         BKE_scene_groups_relink(scene);
1715
1716         ID_NEW_REMAP(scene->camera);
1717         if (v3d) ID_NEW_REMAP(v3d->camera);
1718
1719         /* object and collection pointers */
1720         libblock_relink_collection(master_collection);
1721 }
1722
1723 /* not an especially efficient function, only added so the single user
1724  * button can be functional.*/
1725 void ED_object_single_user(Main *bmain, Scene *scene, Object *ob)
1726 {
1727         FOREACH_SCENE_OBJECT_BEGIN(scene, ob_iter)
1728         {
1729                 ob_iter->flag &= ~OB_DONE;
1730         }
1731         FOREACH_SCENE_OBJECT_END;
1732
1733         /* tag only the one object */
1734         ob->flag |= OB_DONE;
1735
1736         single_object_users(bmain, scene, NULL, OB_DONE, false);
1737         BKE_main_id_clear_newpoins(bmain);
1738 }
1739
1740 static void new_id_matar(Main *bmain, Material **matar, const int totcol)
1741 {
1742         ID *id;
1743         int a;
1744
1745         for (a = 0; a < totcol; a++) {
1746                 id = (ID *)matar[a];
1747                 if (id && !ID_IS_LINKED(id)) {
1748                         if (id->newid) {
1749                                 matar[a] = (Material *)id->newid;
1750                                 id_us_plus(id->newid);
1751                                 id_us_min(id);
1752                         }
1753                         else if (id->us > 1) {
1754                                 matar[a] = ID_NEW_SET(id, BKE_material_copy(bmain, matar[a]));
1755                                 id_us_min(id);
1756                         }
1757                 }
1758         }
1759 }
1760
1761 static void single_obdata_users(Main *bmain, Scene *scene, ViewLayer *view_layer, const int flag)
1762 {
1763         Lamp *la;
1764         Curve *cu;
1765         /* Camera *cam; */
1766         Mesh *me;
1767         Lattice *lat;
1768         ID *id;
1769
1770         FOREACH_OBJECT_FLAG_BEGIN(scene, view_layer, flag, ob)
1771         {
1772                 if (!ID_IS_LINKED(ob)) {
1773                         id = ob->data;
1774
1775                         if (id && id->us > 1 && !ID_IS_LINKED(id)) {
1776                                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1777
1778                                 switch (ob->type) {
1779                                         case OB_LAMP:
1780                                                 ob->data = la = ID_NEW_SET(ob->data, BKE_lamp_copy(bmain, ob->data));
1781                                                 break;
1782                                         case OB_CAMERA:
1783                                                 ob->data = ID_NEW_SET(ob->data, BKE_camera_copy(bmain, ob->data));
1784                                                 break;
1785                                         case OB_MESH:
1786                                                 /* Needed to remap texcomesh below. */
1787                                                 me = ob->data = ID_NEW_SET(ob->data, BKE_mesh_copy(bmain, ob->data));
1788                                                 if (me->key)  /* We do not need to set me->key->id.newid here... */
1789                                                         BKE_animdata_copy_id_action(bmain, (ID *)me->key, false);
1790                                                 break;
1791                                         case OB_MBALL:
1792                                                 ob->data = ID_NEW_SET(ob->data, BKE_mball_copy(bmain, ob->data));
1793                                                 break;
1794                                         case OB_CURVE:
1795                                         case OB_SURF:
1796                                         case OB_FONT:
1797                                                 ob->data = cu = ID_NEW_SET(ob->data, BKE_curve_copy(bmain, ob->data));
1798                                                 ID_NEW_REMAP(cu->bevobj);
1799                                                 ID_NEW_REMAP(cu->taperobj);
1800                                                 if (cu->key)  /* We do not need to set cu->key->id.newid here... */
1801                                                         BKE_animdata_copy_id_action(bmain, (ID *)cu->key, false);
1802                                                 break;
1803                                         case OB_LATTICE:
1804                                                 ob->data = lat = ID_NEW_SET(ob->data, BKE_lattice_copy(bmain, ob->data));
1805                                                 if (lat->key)  /* We do not need to set lat->key->id.newid here... */
1806                                                         BKE_animdata_copy_id_action(bmain, (ID *)lat->key, false);
1807                                                 break;
1808                                         case OB_ARMATURE:
1809                                                 DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1810                                                 ob->data = ID_NEW_SET(ob->data, BKE_armature_copy(bmain, ob->data));
1811                                                 BKE_pose_rebuild(ob, ob->data);
1812                                                 break;
1813                                         case OB_SPEAKER:
1814                                                 ob->data = ID_NEW_SET(ob->data, BKE_speaker_copy(bmain, ob->data));
1815                                                 break;
1816                                         case OB_LIGHTPROBE:
1817                                                 ob->data = ID_NEW_SET(ob->data, BKE_lightprobe_copy(bmain, ob->data));
1818                                                 break;
1819                                         default:
1820                                                 printf("ERROR %s: can't copy %s\n", __func__, id->name);
1821                                                 BLI_assert(!"This should never happen.");
1822
1823                                                 /* We need to end the FOREACH_OBJECT_FLAG_BEGIN iterator to prevent memory leak. */
1824                                                 BKE_scene_objects_iterator_end(&iter_macro);
1825                                                 return;
1826                                 }
1827
1828                                 /* Copy animation data after object data became local,
1829                                  * otherwise old and new object data will share the same
1830                                  * AnimData structure, which is not what we want.
1831                                  *                                             (sergey)
1832                                  */
1833                                 BKE_animdata_copy_id_action(bmain, (ID *)ob->data, false);
1834
1835                                 id_us_min(id);
1836                         }
1837                 }
1838         }
1839         FOREACH_OBJECT_FLAG_END;
1840
1841         me = bmain->mesh.first;
1842         while (me) {
1843                 ID_NEW_REMAP(me->texcomesh);
1844                 me = me->id.next;
1845         }
1846 }
1847
1848 static void single_object_action_users(Main *bmain, Scene *scene, ViewLayer *view_layer, const int flag)
1849 {
1850         FOREACH_OBJECT_FLAG_BEGIN(scene, view_layer, flag, ob)
1851         {
1852                 if (!ID_IS_LINKED(ob)) {
1853                         DEG_id_tag_update(&ob->id, OB_RECALC_DATA);
1854                         BKE_animdata_copy_id_action(bmain, &ob->id, false);
1855                 }
1856         }
1857         FOREACH_OBJECT_FLAG_END;
1858 }
1859
1860 static void single_mat_users(Main *bmain, Scene *scene, ViewLayer *view_layer, const int flag)
1861 {
1862         Material *ma, *man;
1863         int a;
1864
1865         FOREACH_OBJECT_FLAG_BEGIN(scene, view_layer, flag, ob)
1866         {
1867                 if (!ID_IS_LINKED(ob)) {
1868                         for (a = 1; a <= ob->totcol; a++) {
1869                                 ma = give_current_material(ob, a);
1870                                 if (ma) {
1871                                         /* do not test for LIB_TAG_NEW or use newid: this functions guaranteed delivers single_users! */
1872
1873                                         if (ma->id.us > 1) {
1874                                                 man = BKE_material_copy(bmain, ma);
1875                                                 BKE_animdata_copy_id_action(bmain, &man->id, false);
1876
1877                                                 man->id.us = 0;
1878                                                 assign_material(bmain, ob, man, a, BKE_MAT_ASSIGN_USERPREF);
1879                                         }
1880                                 }
1881                         }
1882                 }
1883         }
1884         FOREACH_OBJECT_FLAG_END;
1885 }
1886
1887 static void single_mat_users_expand(Main *bmain)
1888 {
1889         /* only when 'parent' blocks are LIB_TAG_NEW */
1890         Object *ob;
1891         Mesh *me;
1892         Curve *cu;
1893         MetaBall *mb;
1894
1895         for (ob = bmain->object.first; ob; ob = ob->id.next)
1896                 if (ob->id.tag & LIB_TAG_NEW)
1897                         new_id_matar(bmain, ob->mat, ob->totcol);
1898
1899         for (me = bmain->mesh.first; me; me = me->id.next)
1900                 if (me->id.tag & LIB_TAG_NEW)
1901                         new_id_matar(bmain, me->mat, me->totcol);
1902
1903         for (cu = bmain->curve.first; cu; cu = cu->id.next)
1904                 if (cu->id.tag & LIB_TAG_NEW)
1905                         new_id_matar(bmain, cu->mat, cu->totcol);
1906
1907         for (mb = bmain->mball.first; mb; mb = mb->id.next)
1908                 if (mb->id.tag & LIB_TAG_NEW)
1909                         new_id_matar(bmain, mb->mat, mb->totcol);
1910 }
1911
1912 /* used for copying scenes */
1913 void ED_object_single_users(Main *bmain, Scene *scene, const bool full, const bool copy_collections)
1914 {
1915         single_object_users(bmain, scene, NULL, 0, copy_collections);
1916
1917         if (full) {
1918                 single_obdata_users(bmain, scene, NULL, 0);
1919                 single_object_action_users(bmain, scene, NULL, 0);
1920                 single_mat_users_expand(bmain);
1921         }
1922
1923         /* Relink nodetrees' pointers that have been duplicated. */
1924         FOREACH_NODETREE(bmain, ntree, id)
1925         {
1926                 /* This is a bit convoluted, we want to root ntree of copied IDs and only those,
1927                  * so we first check that old ID has been copied and that ntree is root tree of old ID,
1928                  * then get root tree of new ID and remap its pointers to new ID... */
1929                 if (id->newid && (&ntree->id != id)) {
1930                         ntree = ntreeFromID(id->newid);
1931                         BKE_libblock_relink_to_newid(&ntree->id);
1932                 }
1933         } FOREACH_NODETREE_END
1934
1935         /* Relink datablock pointer properties */
1936         {
1937                 IDP_RelinkProperty(scene->id.properties);
1938
1939                 FOREACH_SCENE_OBJECT_BEGIN(scene, ob)
1940                 {
1941                         if (!ID_IS_LINKED(ob)) {
1942                                 IDP_RelinkProperty(ob->id.properties);
1943                         }
1944                 }
1945                 FOREACH_SCENE_OBJECT_END;
1946
1947                 if (scene->nodetree) {
1948                         IDP_RelinkProperty(scene->nodetree->id.properties);
1949                         for (bNode *node = scene->nodetree->nodes.first; node; node = node->next) {
1950                                 IDP_RelinkProperty(node->prop);
1951                         }
1952                 }
1953
1954                 if (scene->gpd) {
1955                         IDP_RelinkProperty(scene->gpd->id.properties);
1956                 }
1957
1958                 if (scene->world) {
1959                         IDP_RelinkProperty(scene->world->id.properties);
1960                 }
1961
1962                 if (scene->clip) {
1963                         IDP_RelinkProperty(scene->clip->id.properties);
1964                 }
1965         }
1966         BKE_main_id_clear_newpoins(bmain);
1967         DEG_relations_tag_update(bmain);
1968 }
1969
1970 /******************************* Make Local ***********************************/
1971
1972 enum {
1973         MAKE_LOCAL_SELECT_OB              = 1,
1974         MAKE_LOCAL_SELECT_OBDATA          = 2,
1975         MAKE_LOCAL_SELECT_OBDATA_MATERIAL = 3,
1976         MAKE_LOCAL_ALL                    = 4,
1977 };
1978
1979 static int tag_localizable_looper(
1980         void *UNUSED(user_data), ID *UNUSED(self_id), ID **id_pointer, const int UNUSED(cb_flag))
1981 {
1982         if (*id_pointer) {
1983                 (*id_pointer)->tag &= ~LIB_TAG_DOIT;
1984         }
1985
1986         return IDWALK_RET_NOP;
1987 }
1988
1989 static void tag_localizable_objects(bContext *C, const int mode)
1990 {
1991         Main *bmain = CTX_data_main(C);
1992
1993         BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
1994
1995         /* Set LIB_TAG_DOIT flag for all selected objects, so next we can check whether
1996          * object is gonna to become local or not.
1997          */
1998         CTX_DATA_BEGIN (C, Object *, object, selected_objects)
1999         {
2000                 object->id.tag |= LIB_TAG_DOIT;
2001
2002                 /* If data is also gonna to become local, mark data we're interested in
2003                  * as gonna-to-be-local.
2004                  */
2005                 if (mode == MAKE_LOCAL_SELECT_OBDATA && object->data) {
2006                         ID *data_id = (ID *) object->data;
2007                         data_id->tag |= LIB_TAG_DOIT;
2008                 }
2009         }
2010         CTX_DATA_END;
2011
2012         /* Also forbid making objects local if other library objects are using
2013          * them for modifiers or constraints.
2014          */
2015         for (Object *object = bmain->object.first; object; object = object->id.next) {
2016                 if ((object->id.tag & LIB_TAG_DOIT) == 0) {
2017                         BKE_library_foreach_ID_link(NULL, &object->id, tag_localizable_looper, NULL, IDWALK_READONLY);
2018                 }
2019                 if (object->data) {
2020                         ID *data_id = (ID *) object->data;
2021                         if ((data_id->tag & LIB_TAG_DOIT) == 0) {
2022                                 BKE_library_foreach_ID_link(NULL, data_id, tag_localizable_looper, NULL, IDWALK_READONLY);
2023                         }
2024                 }
2025         }
2026
2027         /* TODO(sergey): Drivers targets? */
2028 }
2029
2030 /**
2031  * Instance indirectly referenced zero user objects,
2032  * otherwise they're lost on reload, see T40595.
2033  */
2034 static bool make_local_all__instance_indirect_unused(Main *bmain, ViewLayer *view_layer, Collection *collection)
2035 {
2036         Object *ob;
2037         bool changed = false;
2038
2039         for (ob = bmain->object.first; ob; ob = ob->id.next) {
2040                 if (ID_IS_LINKED(ob) && (ob->id.us == 0)) {
2041                         Base *base;
2042
2043                         id_us_plus(&ob->id);
2044
2045                         BKE_collection_object_add(bmain, collection, ob);
2046                         base = BKE_view_layer_base_find(view_layer, ob);
2047                         base->flag |= BASE_SELECTED;
2048                         BKE_scene_object_base_flag_sync_from_base(base);
2049                         DEG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
2050
2051                         changed = true;
2052                 }
2053         }
2054
2055         return changed;
2056 }
2057
2058 static void make_local_animdata_tag_strips(ListBase *strips)
2059 {
2060         NlaStrip *strip;
2061
2062         for (strip = strips->first; strip; strip = strip->next) {
2063                 if (strip->act) {
2064                         strip->act->id.tag &= ~LIB_TAG_PRE_EXISTING;
2065                 }
2066                 if (strip->remap && strip->remap->target) {
2067                         strip->remap->target->id.tag &= ~LIB_TAG_PRE_EXISTING;
2068                 }
2069
2070                 make_local_animdata_tag_strips(&strip->strips);
2071         }
2072 }
2073
2074 /* Tag all actions used by given animdata to be made local. */
2075 static void make_local_animdata_tag(AnimData *adt)
2076 {
2077         if (adt) {
2078                 /* Actions - Active and Temp */
2079                 if (adt->action) {
2080                         adt->action->id.tag &= ~LIB_TAG_PRE_EXISTING;
2081                 }
2082                 if (adt->tmpact) {
2083                         adt->tmpact->id.tag &= ~LIB_TAG_PRE_EXISTING;
2084                 }
2085                 /* Remaps */
2086                 if (adt->remap && adt->remap->target) {
2087                         adt->remap->target->id.tag &= ~LIB_TAG_PRE_EXISTING;
2088                 }
2089
2090                 /* Drivers */
2091                 /* TODO: need to handle the ID-targets too? */
2092
2093                 /* NLA Data */
2094                 for (NlaTrack *nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) {
2095                         make_local_animdata_tag_strips(&nlt->strips);
2096                 }
2097         }
2098 }
2099
2100 static void make_local_material_tag(Material *ma)
2101 {
2102         if (ma) {
2103                 ma->id.tag &= ~LIB_TAG_PRE_EXISTING;
2104                 make_local_animdata_tag(BKE_animdata_from_id(&ma->id));
2105
2106                 /* About nodetrees: root one is made local together with material, others we keep linked for now... */
2107         }
2108 }
2109
2110 static int make_local_exec(bContext *C, wmOperator *op)
2111 {
2112         Main *bmain = CTX_data_main(C);
2113         ParticleSystem *psys;
2114         Material *ma, ***matarar;
2115         const int mode = RNA_enum_get(op->ptr, "type");
2116         int a;
2117
2118         /* Note: we (ab)use LIB_TAG_PRE_EXISTING to cherry pick which ID to make local... */
2119         if (mode == MAKE_LOCAL_ALL) {
2120                 ViewLayer *view_layer = CTX_data_view_layer(C);
2121                 Collection *collection = CTX_data_collection(C);
2122
2123                 BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
2124
2125                 /* De-select so the user can differentiate newly instanced from existing objects. */
2126                 BKE_view_layer_base_deselect_all(view_layer);
2127
2128                 if (make_local_all__instance_indirect_unused(bmain, view_layer, collection)) {
2129                         BKE_report(op->reports, RPT_INFO, "Orphan library objects added to the current scene to avoid loss");
2130                 }
2131         }
2132         else {
2133                 BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true);
2134                 tag_localizable_objects(C, mode);
2135
2136                 CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
2137                 {
2138                         if ((ob->id.tag & LIB_TAG_DOIT) == 0) {
2139                                 continue;
2140                         }
2141
2142                         ob->id.tag &= ~LIB_TAG_PRE_EXISTING;
2143                         make_local_animdata_tag(BKE_animdata_from_id(&ob->id));
2144                         for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2145                                 psys->part->id.tag &= ~LIB_TAG_PRE_EXISTING;
2146                         }
2147
2148                         if (mode == MAKE_LOCAL_SELECT_OBDATA_MATERIAL) {
2149                                 for (a = 0; a < ob->totcol; a++) {
2150                                         ma = ob->mat[a];
2151                                         if (ma) {
2152                                                 make_local_material_tag(ma);
2153                                         }
2154                                 }
2155
2156                                 matarar = (Material ***)give_matarar(ob);
2157                                 if (matarar) {
2158                                         for (a = 0; a < ob->totcol; a++) {
2159                                                 ma = (*matarar)[a];
2160                                                 if (ma) {
2161                                                         make_local_material_tag(ma);
2162                                                 }
2163                                         }
2164                                 }
2165                         }
2166
2167                         if (ELEM(mode, MAKE_LOCAL_SELECT_OBDATA, MAKE_LOCAL_SELECT_OBDATA_MATERIAL) && ob->data != NULL) {
2168                                 ID *ob_data = ob->data;
2169                                 ob_data->tag &= ~LIB_TAG_PRE_EXISTING;
2170                                 make_local_animdata_tag(BKE_animdata_from_id(ob_data));
2171                         }
2172                 }
2173                 CTX_DATA_END;
2174         }
2175
2176         BKE_library_make_local(bmain, NULL, NULL, true, false); /* NULL is all libs */
2177
2178         WM_event_add_notifier(C, NC_WINDOW, NULL);
2179         return OPERATOR_FINISHED;
2180 }
2181
2182 void OBJECT_OT_make_local(wmOperatorType *ot)
2183 {
2184         static const EnumPropertyItem type_items[] = {
2185                 {MAKE_LOCAL_SELECT_OB, "SELECT_OBJECT", 0, "Selected Objects", ""},
2186                 {MAKE_LOCAL_SELECT_OBDATA, "SELECT_OBDATA", 0, "Selected Objects and Data", ""},
2187                 {MAKE_LOCAL_SELECT_OBDATA_MATERIAL, "SELECT_OBDATA_MATERIAL", 0, "Selected Objects, Data and Materials", ""},
2188                 {MAKE_LOCAL_ALL, "ALL", 0, "All", ""},
2189                 {0, NULL, 0, NULL, NULL}
2190         };
2191
2192         /* identifiers */
2193         ot->name = "Make Local";
2194         ot->description = "Make library linked data-blocks local to this file";
2195         ot->idname = "OBJECT_OT_make_local";
2196
2197         /* api callbacks */
2198         ot->invoke = WM_menu_invoke;
2199         ot->exec = make_local_exec;
2200         ot->poll = ED_operator_objectmode;
2201
2202         /* flags */
2203         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2204
2205         /* properties */
2206         ot->prop = RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "");
2207 }
2208
2209
2210 static void make_override_static_tag_object(Object *obact, Object *ob)
2211 {
2212         if (ob == obact) {
2213                 return;
2214         }
2215
2216         if (!ID_IS_LINKED(ob)) {
2217                 return;
2218         }
2219
2220         /* Note: all this is very case-by-case bad handling, ultimately we'll want a real full 'automatic', generic
2221          * handling of all this, will probably require adding some override-aware stuff to library_query code... */
2222
2223         if (obact->type == OB_ARMATURE && ob->modifiers.first != NULL) {
2224                 for (ModifierData *md = ob->modifiers.first; md != NULL; md = md->next) {
2225                         if (md->type == eModifierType_Armature) {
2226                                 ArmatureModifierData *amd = (ArmatureModifierData *)md;
2227                                 if (amd->object == obact) {
2228                                         ob->id.tag |= LIB_TAG_DOIT;
2229                                         break;
2230                                 }
2231                         }
2232                 }
2233         }
2234         else if (ob->parent == obact) {
2235                 ob->id.tag |= LIB_TAG_DOIT;
2236         }
2237
2238         if (ob->id.tag & LIB_TAG_DOIT) {
2239                 printf("Indirectly overriding %s for %s\n", ob->id.name, obact->id.name);
2240         }
2241 }
2242
2243 /* Set the object to override. */
2244 static int make_override_static_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2245 {
2246         Scene *scene = CTX_data_scene(C);
2247         Object *obact = ED_object_active_context(C);
2248
2249         /* Sanity checks. */
2250         if (!scene || ID_IS_LINKED(scene) || !obact) {
2251                 return OPERATOR_CANCELLED;
2252         }
2253
2254         /* Get object to work on - use a menu if we need to... */
2255         if (!ID_IS_LINKED(obact) && obact->dup_group != NULL && ID_IS_LINKED(obact->dup_group)) {
2256                 /* Gives menu with list of objects in group. */
2257                 WM_enum_search_invoke(C, op, event);
2258                 return OPERATOR_CANCELLED;
2259         }
2260         else if (ID_IS_LINKED(obact)) {
2261                 uiPopupMenu *pup = UI_popup_menu_begin(C, IFACE_("OK?"), ICON_QUESTION);
2262                 uiLayout *layout = UI_popup_menu_layout(pup);
2263
2264                 /* Create operator menu item with relevant properties filled in. */
2265                 PointerRNA opptr_dummy;
2266                 uiItemFullO_ptr(layout, op->type, op->type->name, ICON_NONE, NULL,
2267                                 WM_OP_EXEC_REGION_WIN, 0, &opptr_dummy);
2268
2269                 /* Present the menu and be done... */
2270                 UI_popup_menu_end(C, pup);
2271
2272                 /* This invoke just calls another instance of this operator... */
2273                 return OPERATOR_INTERFACE;
2274         }
2275         else {
2276                 /* Error.. cannot continue. */
2277                 BKE_report(op->reports, RPT_ERROR, "Can only make static override for a referenced object or collection");
2278                 return OPERATOR_CANCELLED;
2279         }
2280
2281 }
2282
2283 static int make_override_static_exec(bContext *C, wmOperator *op)
2284 {
2285         Main *bmain = CTX_data_main(C);
2286         Object *obact = CTX_data_active_object(C);
2287
2288         bool success = false;
2289
2290         if (!ID_IS_LINKED(obact) && obact->dup_group != NULL && ID_IS_LINKED(obact->dup_group)) {
2291                 const ListBase dup_collection_objects = BKE_collection_object_cache_get(obact->dup_group);
2292                 Base *base = BLI_findlink(&dup_collection_objects, RNA_enum_get(op->ptr, "object"));
2293                 Object *obcollection = obact;
2294                 obact = base->object;
2295                 Collection *collection = obcollection->dup_group;
2296
2297                 /* First, we make a static override of the linked collection itself. */
2298                 collection->id.tag |= LIB_TAG_DOIT;
2299
2300                 /* Then, we make static override of the whole set of objects in the Collection. */
2301                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(collection, ob)
2302                 {
2303                         ob->id.tag |= LIB_TAG_DOIT;
2304                 }
2305                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
2306
2307                 /* Then, we remove (untag) bone shape objects, you shall never want to override those (hopefully)... */
2308                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(collection, ob)
2309                 {
2310                         if (ob->type == OB_ARMATURE && ob->pose != NULL) {
2311                                 for (bPoseChannel *pchan = ob->pose->chanbase.first; pchan != NULL; pchan = pchan->next) {
2312                                         if (pchan->custom != NULL) {
2313                                                 pchan->custom->id.tag &= ~ LIB_TAG_DOIT;
2314                                         }
2315                                 }
2316                         }
2317                 }
2318                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
2319
2320                 success = BKE_override_static_create_from_tag(bmain);
2321
2322                 /* Intantiate our newly overridden objects in scene, if not yet done. */
2323                 Scene *scene = CTX_data_scene(C);
2324                 ViewLayer *view_layer = CTX_data_view_layer(C);
2325                 Collection *new_collection = (Collection *)collection->id.newid;
2326                 FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(new_collection, new_ob)
2327                 {
2328                         if (new_ob != NULL && new_ob->id.override_static != NULL) {
2329                                 if ((base = BKE_view_layer_base_find(view_layer, new_ob)) == NULL) {
2330                                         BKE_collection_object_add_from(bmain, scene, obcollection, new_ob);
2331                                         DEG_id_tag_update_ex(bmain, &new_ob->id, DEG_TAG_TRANSFORM | DEG_TAG_BASE_FLAGS_UPDATE);
2332                                 }
2333                                 /* parent to 'collection' empty */
2334                                 if (new_ob->parent == NULL) {
2335                                         new_ob->parent = obcollection;
2336                                 }
2337                                 if (new_ob == (Object *)obact->id.newid) {
2338                                         BKE_view_layer_base_select(view_layer, base);
2339                                 }
2340                                 else {
2341                                         /* Disable auto-override tags for non-active objects, will help with performaces... */
2342                                         new_ob->id.override_static->flag &= ~STATICOVERRIDE_AUTO;
2343                                 }
2344                                 /* We still want to store all objects' current override status (i.e. change of parent). */
2345                                 BKE_override_static_operations_create(&new_ob->id, true);
2346                         }
2347                 }
2348                 FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
2349
2350                 /* obcollection is no more duplicollection-ing, it merely parents whole collection of overriding instantiated objects. */
2351                 obcollection->dup_group = NULL;
2352
2353                 /* Also, we'd likely want to lock by default things like transformations of implicitly overriden objects? */
2354
2355                 DEG_id_tag_update(&scene->id, 0);
2356
2357                 /* Cleanup. */
2358                 BKE_main_id_clear_newpoins(bmain);
2359                 BKE_main_id_tag_listbase(&bmain->object, LIB_TAG_DOIT, false);
2360         }
2361         /* Else, poll func ensures us that ID_IS_LINKED(obact) is true. */
2362         else if (obact->type == OB_ARMATURE) {
2363                 BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
2364
2365                 obact->id.tag |= LIB_TAG_DOIT;
2366
2367                 for (Object *ob = bmain->object.first; ob != NULL; ob = ob->id.next) {
2368                         make_override_static_tag_object(obact, ob);
2369                 }
2370
2371                 success = BKE_override_static_create_from_tag(bmain);
2372
2373                 /* Also, we'd likely want to lock by default things like transformations of implicitly overriden objects? */
2374
2375                 /* Cleanup. */
2376                 BKE_main_id_clear_newpoins(bmain);
2377                 BKE_main_id_tag_listbase(&bmain->object, LIB_TAG_DOIT, false);
2378         }
2379         /* TODO: probably more cases where we want to do automated smart things in the future! */
2380         else {
2381                 success = (BKE_override_static_create_from_id(bmain, &obact->id) != NULL);
2382         }
2383
2384         WM_event_add_notifier(C, NC_WINDOW, NULL);
2385
2386         return success ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
2387 }
2388
2389 static int make_override_static_poll(bContext *C)
2390 {
2391         Object *obact = CTX_data_active_object(C);
2392
2393         /* Object must be directly linked to be overridable. */
2394         return (ED_operator_objectmode(C) && obact != NULL &&
2395                 ((ID_IS_LINKED(obact) && obact->id.tag & LIB_TAG_EXTERN) ||
2396                  (!ID_IS_LINKED(obact) && obact->dup_group != NULL && ID_IS_LINKED(obact->dup_group))));
2397 }
2398
2399 void OBJECT_OT_make_override_static(wmOperatorType *ot)
2400 {
2401         /* identifiers */
2402         ot->name = "Make Static Override";
2403         ot->description = "Make local override of this library linked data-block";
2404         ot->idname = "OBJECT_OT_make_override_static";
2405
2406         /* api callbacks */
2407         ot->invoke = make_override_static_invoke;
2408         ot->exec = make_override_static_exec;
2409         ot->poll = make_override_static_poll;
2410
2411         /* flags */
2412         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2413
2414         /* properties */
2415         PropertyRNA *prop;
2416         prop = RNA_def_enum(ot->srna, "object", DummyRNA_DEFAULT_items, 0, "Override Object",
2417                             "Name of lib-linked/collection object to make an override from");
2418         RNA_def_enum_funcs(prop, proxy_collection_object_itemf);
2419         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
2420         ot->prop = prop;
2421 }
2422
2423 enum {
2424         MAKE_SINGLE_USER_ALL      = 1,
2425         MAKE_SINGLE_USER_SELECTED = 2,
2426 };
2427
2428 static int make_single_user_exec(bContext *C, wmOperator *op)
2429 {
2430         Main *bmain = CTX_data_main(C);
2431         Scene *scene = CTX_data_scene(C);
2432         ViewLayer *view_layer = CTX_data_view_layer(C);
2433         View3D *v3d = CTX_wm_view3d(C); /* ok if this is NULL */
2434         const int flag = (RNA_enum_get(op->ptr, "type") == MAKE_SINGLE_USER_SELECTED) ? SELECT : 0;
2435         const bool copy_collections = false;
2436         bool update_deps = false;
2437
2438         if (RNA_boolean_get(op->ptr, "object")) {
2439                 if (flag == SELECT) {
2440                         BKE_view_layer_selected_objects_tag(view_layer, OB_DONE);
2441                         single_object_users(bmain, scene, v3d, OB_DONE, copy_collections);
2442                 }
2443                 else {
2444                         single_object_users(bmain, scene, v3d, 0, copy_collections);
2445                 }
2446
2447                 /* needed since object relationships may have changed */
2448                 update_deps = true;
2449         }
2450
2451         if (RNA_boolean_get(op->ptr, "obdata")) {
2452                 single_obdata_users(bmain, scene, view_layer, flag);
2453         }
2454
2455         if (RNA_boolean_get(op->ptr, "material")) {
2456                 single_mat_users(bmain, scene, view_layer, flag);
2457         }
2458
2459         if (RNA_boolean_get(op->ptr, "animation")) {
2460                 single_object_action_users(bmain, scene, view_layer, flag);
2461         }
2462
2463         BKE_main_id_clear_newpoins(bmain);
2464
2465         WM_event_add_notifier(C, NC_WINDOW, NULL);
2466
2467         if (update_deps) {
2468                 DEG_relations_tag_update(bmain);
2469         }
2470
2471         return OPERATOR_FINISHED;
2472 }
2473
2474 void OBJECT_OT_make_single_user(wmOperatorType *ot)
2475 {
2476         static const EnumPropertyItem type_items[] = {
2477                 {MAKE_SINGLE_USER_SELECTED, "SELECTED_OBJECTS", 0, "Selected Objects", ""},
2478                 {MAKE_SINGLE_USER_ALL, "ALL", 0, "All", ""},
2479                 {0, NULL, 0, NULL, NULL}};
2480
2481         /* identifiers */
2482         ot->name = "Make Single User";
2483         ot->description = "Make linked data local to each object";
2484         ot->idname = "OBJECT_OT_make_single_user";
2485
2486         /* api callbacks */
2487         ot->invoke = WM_menu_invoke;
2488         ot->exec = make_single_user_exec;
2489         ot->poll = ED_operator_objectmode;
2490
2491         /* flags */
2492         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2493
2494         /* properties */
2495         ot->prop = RNA_def_enum(ot->srna, "type", type_items, MAKE_SINGLE_USER_SELECTED, "Type", "");
2496
2497         RNA_def_boolean(ot->srna, "object", 0, "Object", "Make single user objects");
2498         RNA_def_boolean(ot->srna, "obdata", 0, "Object Data", "Make single user object data");
2499         RNA_def_boolean(ot->srna, "material", 0, "Materials", "Make materials local to each data-block");
2500         RNA_def_boolean(ot->srna, "animation", 0, "Object Animation", "Make animation data local to each object");
2501 }
2502
2503 static int drop_named_material_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2504 {
2505         Main *bmain = CTX_data_main(C);
2506         Base *base = ED_view3d_give_base_under_cursor(C, event->mval);
2507         Material *ma;
2508         char name[MAX_ID_NAME - 2];
2509
2510         RNA_string_get(op->ptr, "name", name);
2511         ma = (Material *)BKE_libblock_find_name(bmain, ID_MA, name);
2512         if (base == NULL || ma == NULL)
2513                 return OPERATOR_CANCELLED;
2514
2515         assign_material(CTX_data_main(C), base->object, ma, 1, BKE_MAT_ASSIGN_USERPREF);
2516
2517         DEG_id_tag_update(&base->object->id, OB_RECALC_OB);
2518
2519         WM_event_add_notifier(C, NC_OBJECT | ND_OB_SHADING, base->object);
2520         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, CTX_wm_view3d(C));
2521         WM_event_add_notifier(C, NC_MATERIAL | ND_SHADING_LINKS, ma);
2522
2523         return OPERATOR_FINISHED;
2524 }
2525
2526 /* used for dropbox */
2527 /* assigns to object under cursor, only first material slot */
2528 void OBJECT_OT_drop_named_material(wmOperatorType *ot)
2529 {
2530         /* identifiers */
2531         ot->name = "Drop Named Material on Object";
2532         ot->description = "";
2533         ot->idname = "OBJECT_OT_drop_named_material";
2534
2535         /* api callbacks */
2536         ot->invoke = drop_named_material_invoke;
2537         ot->poll = ED_operator_objectmode;
2538
2539         /* flags */
2540         ot->flag = OPTYPE_UNDO | OPTYPE_INTERNAL;
2541
2542         /* properties */
2543         RNA_def_string(ot->srna, "name", "Material", MAX_ID_NAME - 2, "Name", "Material name to assign");
2544 }
2545
2546 static int object_unlink_data_exec(bContext *C, wmOperator *op)
2547 {
2548         ID *id;
2549         PropertyPointerRNA pprop;
2550
2551         UI_context_active_but_prop_get_templateID(C, &pprop.ptr, &pprop.prop);
2552
2553         if (pprop.prop == NULL) {
2554                 BKE_report(op->reports, RPT_ERROR, "Incorrect context for running object data unlink");
2555                 return OPERATOR_CANCELLED;
2556         }
2557
2558         id = pprop.ptr.id.data;
2559
2560         if (GS(id->name) == ID_OB) {
2561                 Object *ob = (Object *)id;
2562                 if (ob->data) {
2563                         ID *id_data = ob->data;
2564
2565                         if (GS(id_data->name) == ID_IM) {
2566                                 id_us_min(id_data);
2567                                 ob->data = NULL;
2568                         }
2569                         else {
2570                                 BKE_report(op->reports, RPT_ERROR, "Can't unlink this object data");
2571                                 return OPERATOR_CANCELLED;
2572                         }
2573                 }
2574         }
2575
2576         RNA_property_update(C, &pprop.ptr, pprop.prop);
2577
2578         return OPERATOR_FINISHED;
2579 }
2580
2581 /**
2582  * \note Only for empty-image objects, this operator is needed
2583  */
2584 void OBJECT_OT_unlink_data(wmOperatorType *ot)
2585 {
2586         /* identifiers */
2587         ot->name = "Unlink";
2588         ot->idname = "OBJECT_OT_unlink_data";
2589         ot->description = "";
2590
2591         /* api callbacks */
2592         ot->exec = object_unlink_data_exec;
2593
2594         /* flags */
2595         ot->flag = OPTYPE_INTERNAL;
2596 }