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