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