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