425035d41cc01474641bd17143574c67f29d6a6d
[blender.git] / source / blender / editors / object / object_add.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup edobj
22  */
23
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <ctype.h>
28
29 #include "MEM_guardedalloc.h"
30
31 #include "DNA_anim_types.h"
32 #include "DNA_camera_types.h"
33 #include "DNA_collection_types.h"
34 #include "DNA_curve_types.h"
35 #include "DNA_light_types.h"
36 #include "DNA_key_types.h"
37 #include "DNA_material_types.h"
38 #include "DNA_mesh_types.h"
39 #include "DNA_meta_types.h"
40 #include "DNA_object_fluidsim_types.h"
41 #include "DNA_object_force_types.h"
42 #include "DNA_object_types.h"
43 #include "DNA_lightprobe_types.h"
44 #include "DNA_scene_types.h"
45 #include "DNA_vfont_types.h"
46 #include "DNA_gpencil_types.h"
47
48 #include "BLI_utildefines.h"
49 #include "BLI_ghash.h"
50 #include "BLI_listbase.h"
51 #include "BLI_math.h"
52 #include "BLI_string.h"
53
54 #include "BLT_translation.h"
55
56 #include "BKE_action.h"
57 #include "BKE_anim.h"
58 #include "BKE_animsys.h"
59 #include "BKE_armature.h"
60 #include "BKE_camera.h"
61 #include "BKE_collection.h"
62 #include "BKE_context.h"
63 #include "BKE_constraint.h"
64 #include "BKE_curve.h"
65 #include "BKE_displist.h"
66 #include "BKE_effect.h"
67 #include "BKE_font.h"
68 #include "BKE_gpencil.h"
69 #include "BKE_key.h"
70 #include "BKE_light.h"
71 #include "BKE_lattice.h"
72 #include "BKE_layer.h"
73 #include "BKE_library.h"
74 #include "BKE_library_query.h"
75 #include "BKE_library_remap.h"
76 #include "BKE_lightprobe.h"
77 #include "BKE_main.h"
78 #include "BKE_material.h"
79 #include "BKE_mball.h"
80 #include "BKE_mesh.h"
81 #include "BKE_mesh_runtime.h"
82 #include "BKE_nla.h"
83 #include "BKE_object.h"
84 #include "BKE_particle.h"
85 #include "BKE_report.h"
86 #include "BKE_scene.h"
87 #include "BKE_speaker.h"
88
89 #include "DEG_depsgraph.h"
90 #include "DEG_depsgraph_build.h"
91 #include "DEG_depsgraph_query.h"
92
93 #include "RNA_access.h"
94 #include "RNA_define.h"
95 #include "RNA_enum_types.h"
96
97 #include "WM_api.h"
98 #include "WM_types.h"
99
100 #include "ED_armature.h"
101 #include "ED_curve.h"
102 #include "ED_gpencil.h"
103 #include "ED_mball.h"
104 #include "ED_mesh.h"
105 #include "ED_node.h"
106 #include "ED_object.h"
107 #include "ED_physics.h"
108 #include "ED_render.h"
109 #include "ED_screen.h"
110 #include "ED_transform.h"
111 #include "ED_view3d.h"
112
113 #include "UI_resources.h"
114
115 #include "object_intern.h"
116
117 /* this is an exact copy of the define in rna_light.c
118  * kept here because of linking order.
119  * Icons are only defined here */
120 const EnumPropertyItem rna_enum_light_type_items[] = {
121         {LA_LOCAL, "POINT", ICON_LIGHT_POINT, "Point", "Omnidirectional point light source"},
122         {LA_SUN, "SUN", ICON_LIGHT_SUN, "Sun", "Constant direction parallel ray light source"},
123         {LA_SPOT, "SPOT", ICON_LIGHT_SPOT, "Spot", "Directional cone light source"},
124         {LA_AREA, "AREA", ICON_LIGHT_AREA, "Area", "Directional area light source"},
125         {0, NULL, 0, NULL, NULL},
126 };
127
128 /* copy from rna_object_force.c */
129 static const EnumPropertyItem field_type_items[] = {
130         {PFIELD_FORCE, "FORCE", ICON_FORCE_FORCE, "Force", ""},
131         {PFIELD_WIND, "WIND", ICON_FORCE_WIND, "Wind", ""},
132         {PFIELD_VORTEX, "VORTEX", ICON_FORCE_VORTEX, "Vortex", ""},
133         {PFIELD_MAGNET, "MAGNET", ICON_FORCE_MAGNETIC, "Magnetic", ""},
134         {PFIELD_HARMONIC, "HARMONIC", ICON_FORCE_HARMONIC, "Harmonic", ""},
135         {PFIELD_CHARGE, "CHARGE", ICON_FORCE_CHARGE, "Charge", ""},
136         {PFIELD_LENNARDJ, "LENNARDJ", ICON_FORCE_LENNARDJONES, "Lennard-Jones", ""},
137         {PFIELD_TEXTURE, "TEXTURE", ICON_FORCE_TEXTURE, "Texture", ""},
138         {PFIELD_GUIDE, "GUIDE", ICON_FORCE_CURVE, "Curve Guide", ""},
139         {PFIELD_BOID, "BOID", ICON_FORCE_BOID, "Boid", ""},
140         {PFIELD_TURBULENCE, "TURBULENCE", ICON_FORCE_TURBULENCE, "Turbulence", ""},
141         {PFIELD_DRAG, "DRAG", ICON_FORCE_DRAG, "Drag", ""},
142         {PFIELD_SMOKEFLOW, "SMOKE", ICON_FORCE_SMOKEFLOW, "Smoke Flow", ""},
143         {0, NULL, 0, NULL, NULL},
144 };
145
146 static EnumPropertyItem lightprobe_type_items[] = {
147         {LIGHTPROBE_TYPE_CUBE, "CUBEMAP", ICON_LIGHTPROBE_CUBEMAP, "Reflection Cubemap",
148      "Reflection probe with spherical or cubic attenuation"},
149         {LIGHTPROBE_TYPE_PLANAR, "PLANAR", ICON_LIGHTPROBE_PLANAR, "Reflection Plane",
150      "Planar reflection probe"},
151         {LIGHTPROBE_TYPE_GRID, "GRID", ICON_LIGHTPROBE_GRID, "Irradiance Volume",
152      "Irradiance probe to capture diffuse indirect lighting"},
153         {0, NULL, 0, NULL, NULL},
154 };
155
156 /************************** Exported *****************************/
157
158 void ED_object_location_from_view(bContext *C, float loc[3])
159 {
160         const Scene *scene = CTX_data_scene(C);
161         copy_v3_v3(loc, scene->cursor.location);
162 }
163
164 void ED_object_rotation_from_quat(float rot[3], const float viewquat[4], const char align_axis)
165 {
166         BLI_assert(align_axis >= 'X' && align_axis <= 'Z');
167
168         switch (align_axis) {
169                 case 'X':
170                 {
171                         /* Same as 'rv3d->viewinv[1]' */
172                         float axis_y[4] = {0.0f, 1.0f, 0.0f};
173                         float quat_y[4], quat[4];
174                         axis_angle_to_quat(quat_y, axis_y, M_PI_2);
175                         mul_qt_qtqt(quat, viewquat, quat_y);
176                         quat_to_eul(rot, quat);
177                         break;
178                 }
179                 case 'Y':
180                 {
181                         quat_to_eul(rot, viewquat);
182                         rot[0] -= (float)M_PI_2;
183                         break;
184                 }
185                 case 'Z':
186                 {
187                         quat_to_eul(rot, viewquat);
188                         break;
189                 }
190         }
191 }
192
193 void ED_object_rotation_from_view(bContext *C, float rot[3], const char align_axis)
194 {
195         RegionView3D *rv3d = CTX_wm_region_view3d(C);
196         BLI_assert(align_axis >= 'X' && align_axis <= 'Z');
197         if (rv3d) {
198                 float viewquat[4];
199                 copy_qt_qt(viewquat, rv3d->viewquat);
200                 viewquat[0] *= -1.0f;
201                 ED_object_rotation_from_quat(rot, viewquat, align_axis);
202         }
203         else {
204                 zero_v3(rot);
205         }
206 }
207
208 void ED_object_base_init_transform(bContext *C, Base *base, const float loc[3], const float rot[3])
209 {
210         Object *ob = base->object;
211         Scene *scene = CTX_data_scene(C);
212         Depsgraph *depsgraph = CTX_data_depsgraph(C);
213
214         if (!scene) return;
215
216         if (loc)
217                 copy_v3_v3(ob->loc, loc);
218
219         if (rot)
220                 copy_v3_v3(ob->rot, rot);
221
222         BKE_object_where_is_calc(depsgraph, scene, ob);
223 }
224
225 /* Uses context to figure out transform for primitive.
226  * Returns standard diameter. */
227 float ED_object_new_primitive_matrix(
228         bContext *C, Object *obedit,
229         const float loc[3], const float rot[3], float primmat[4][4])
230 {
231         Scene *scene = CTX_data_scene(C);
232         View3D *v3d = CTX_wm_view3d(C);
233         float mat[3][3], rmat[3][3], cmat[3][3], imat[3][3];
234
235         unit_m4(primmat);
236
237         eul_to_mat3(rmat, rot);
238         invert_m3(rmat);
239
240         /* inverse transform for initial rotation and object */
241         copy_m3_m4(mat, obedit->obmat);
242         mul_m3_m3m3(cmat, rmat, mat);
243         invert_m3_m3(imat, cmat);
244         copy_m4_m3(primmat, imat);
245
246         /* center */
247         copy_v3_v3(primmat[3], loc);
248         sub_v3_v3v3(primmat[3], primmat[3], obedit->obmat[3]);
249         invert_m3_m3(imat, mat);
250         mul_m3_v3(imat, primmat[3]);
251
252         {
253                 const float dia = v3d ? ED_view3d_grid_scale(scene, v3d, NULL) : ED_scene_grid_scale(scene, NULL);
254                 return dia;
255         }
256
257         // return 1.0f;
258 }
259
260 /********************* Add Object Operator ********************/
261
262 static void view_align_update(struct Main *UNUSED(main), struct Scene *UNUSED(scene), struct PointerRNA *ptr)
263 {
264         RNA_struct_idprops_unset(ptr, "rotation");
265 }
266
267 void ED_object_add_unit_props_size(wmOperatorType *ot)
268 {
269         RNA_def_float_distance(ot->srna, "size", 2.0f, 0.0, OBJECT_ADD_SIZE_MAXF, "Size", "", 0.001, 100.00);
270 }
271
272 void ED_object_add_unit_props_radius(wmOperatorType *ot)
273 {
274         RNA_def_float_distance(ot->srna, "radius", 1.0f, 0.0, OBJECT_ADD_SIZE_MAXF, "Radius", "", 0.001, 100.00);
275 }
276
277 void ED_object_add_generic_props(wmOperatorType *ot, bool do_editmode)
278 {
279         PropertyRNA *prop;
280
281         /* note: this property gets hidden for add-camera operator */
282         prop = RNA_def_boolean(ot->srna, "view_align", 0, "Align to View", "Align the new object to the view");
283         RNA_def_property_update_runtime(prop, view_align_update);
284
285         if (do_editmode) {
286                 prop = RNA_def_boolean(ot->srna, "enter_editmode", 0, "Enter Editmode",
287                                        "Enter editmode when adding this object");
288                 RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
289         }
290
291         prop = RNA_def_float_vector_xyz(ot->srna, "location", 3, NULL, -OBJECT_ADD_SIZE_MAXF, OBJECT_ADD_SIZE_MAXF,
292                                         "Location", "Location for the newly added object", -1000.0f, 1000.0f);
293         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
294         prop = RNA_def_float_rotation(ot->srna, "rotation", 3, NULL, -OBJECT_ADD_SIZE_MAXF, OBJECT_ADD_SIZE_MAXF,
295                                       "Rotation", "Rotation for the newly added object",
296                                       DEG2RADF(-360.0f), DEG2RADF(360.0f));
297         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
298 }
299
300 void ED_object_add_mesh_props(wmOperatorType *ot)
301 {
302         RNA_def_boolean(ot->srna, "calc_uvs", true, "Generate UVs", "Generate a default UV map");
303 }
304
305 bool ED_object_add_generic_get_opts(
306         bContext *C, wmOperator *op, const char view_align_axis,
307         float loc[3], float rot[3],
308         bool *enter_editmode, ushort *local_view_bits, bool *is_view_aligned)
309 {
310         PropertyRNA *prop;
311
312         /* Switch to Edit mode? optional prop */
313         if ((prop = RNA_struct_find_property(op->ptr, "enter_editmode"))) {
314                 bool _enter_editmode;
315                 if (!enter_editmode)
316                         enter_editmode = &_enter_editmode;
317
318                 if (RNA_property_is_set(op->ptr, prop) && enter_editmode)
319                         *enter_editmode = RNA_property_boolean_get(op->ptr, prop);
320                 else {
321                         *enter_editmode = (U.flag & USER_ADD_EDITMODE) != 0;
322                         RNA_property_boolean_set(op->ptr, prop, *enter_editmode);
323                 }
324         }
325
326         if (local_view_bits) {
327                 View3D *v3d = CTX_wm_view3d(C);
328                 if (v3d && v3d->localvd) {
329                         *local_view_bits = v3d->local_view_uuid;
330                 }
331         }
332
333         /* Location! */
334         {
335                 float _loc[3];
336                 if (!loc)
337                         loc = _loc;
338
339                 if (RNA_struct_property_is_set(op->ptr, "location")) {
340                         RNA_float_get_array(op->ptr, "location", loc);
341                 }
342                 else {
343                         ED_object_location_from_view(C, loc);
344                         RNA_float_set_array(op->ptr, "location", loc);
345                 }
346         }
347
348         /* Rotation! */
349         {
350                 bool _is_view_aligned;
351                 float _rot[3];
352                 if (!is_view_aligned)
353                         is_view_aligned = &_is_view_aligned;
354                 if (!rot)
355                         rot = _rot;
356
357                 if (RNA_struct_property_is_set(op->ptr, "rotation"))
358                         *is_view_aligned = false;
359                 else if (RNA_struct_property_is_set(op->ptr, "view_align"))
360                         *is_view_aligned = RNA_boolean_get(op->ptr, "view_align");
361                 else {
362                         *is_view_aligned = (U.flag & USER_ADD_VIEWALIGNED) != 0;
363                         RNA_boolean_set(op->ptr, "view_align", *is_view_aligned);
364                 }
365
366                 if (*is_view_aligned) {
367                         ED_object_rotation_from_view(C, rot, view_align_axis);
368                         RNA_float_set_array(op->ptr, "rotation", rot);
369                 }
370                 else
371                         RNA_float_get_array(op->ptr, "rotation", rot);
372         }
373
374         return true;
375 }
376
377 /* For object add primitive operators.
378  * Do not call undo push in this function (users of this function have to). */
379 Object *ED_object_add_type(
380         bContext *C,
381         int type, const char *name,
382         const float loc[3], const float rot[3],
383         bool enter_editmode, ushort local_view_bits)
384 {
385         Main *bmain = CTX_data_main(C);
386         Scene *scene = CTX_data_scene(C);
387         ViewLayer *view_layer = CTX_data_view_layer(C);
388         Object *ob;
389
390         /* for as long scene has editmode... */
391         if (CTX_data_edit_object(C)) {
392                 ED_object_editmode_exit(C, EM_FREEDATA);
393         }
394
395         /* deselects all, sets active object */
396         ob = BKE_object_add(bmain, scene, view_layer, type, name);
397         BASACT(view_layer)->local_view_bits = local_view_bits;
398         /* editor level activate, notifiers */
399         ED_object_base_activate(C, view_layer->basact);
400
401         /* more editor stuff */
402         ED_object_base_init_transform(C, view_layer->basact, loc, rot);
403
404         /* TODO(sergey): This is weird to manually tag objects for update, better to
405          * use DEG_id_tag_update here perhaps.
406          */
407         DEG_id_type_tag(bmain, ID_OB);
408         DEG_relations_tag_update(bmain);
409         if (ob->data != NULL) {
410                 DEG_id_tag_update_ex(bmain, (ID *)ob->data, ID_RECALC_EDITORS);
411         }
412
413         if (enter_editmode) {
414                 ED_object_editmode_enter_ex(bmain, scene, ob, 0);
415         }
416
417         WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, scene);
418
419         /* TODO(sergey): Use proper flag for tagging here. */
420         DEG_id_tag_update(&scene->id, 0);
421
422         return ob;
423 }
424
425 /* for object add operator */
426 static int object_add_exec(bContext *C, wmOperator *op)
427 {
428         Object *ob;
429         bool enter_editmode;
430         ushort local_view_bits;
431         float loc[3], rot[3], radius;
432
433         WM_operator_view3d_unit_defaults(C, op);
434         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &local_view_bits, NULL)) {
435                 return OPERATOR_CANCELLED;
436         }
437         radius = RNA_float_get(op->ptr, "radius");
438         ob = ED_object_add_type(C, RNA_enum_get(op->ptr, "type"), NULL, loc, rot, enter_editmode, local_view_bits);
439
440         if (ob->type == OB_LATTICE) {
441                 /* lattice is a special case!
442                  * we never want to scale the obdata since that is the rest-state */
443                 copy_v3_fl(ob->scale, radius);
444         }
445         else {
446                 BKE_object_obdata_size_init(ob, radius);
447         }
448
449         return OPERATOR_FINISHED;
450 }
451
452 void OBJECT_OT_add(wmOperatorType *ot)
453 {
454         /* identifiers */
455         ot->name = "Add Object";
456         ot->description = "Add an object to the scene";
457         ot->idname = "OBJECT_OT_add";
458
459         /* api callbacks */
460         ot->exec = object_add_exec;
461         ot->poll = ED_operator_objectmode;
462
463         /* flags */
464         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
465
466         /* properties */
467         ED_object_add_unit_props_radius(ot);
468         PropertyRNA *prop = RNA_def_enum(ot->srna, "type", rna_enum_object_type_items, 0, "Type", "");
469         RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_ID);
470
471         ED_object_add_generic_props(ot, true);
472 }
473
474 /********************** Add Probe Operator **********************/
475
476 /* for object add operator */
477 static const char *get_lightprobe_defname(int type)
478 {
479         switch (type) {
480                 case LIGHTPROBE_TYPE_GRID: return CTX_DATA_(BLT_I18NCONTEXT_ID_LIGHT, "IrradianceVolume");
481                 case LIGHTPROBE_TYPE_PLANAR: return CTX_DATA_(BLT_I18NCONTEXT_ID_LIGHT, "ReflectionPlane");
482                 case LIGHTPROBE_TYPE_CUBE: return CTX_DATA_(BLT_I18NCONTEXT_ID_LIGHT, "ReflectionCubemap");
483                 default:
484                         return CTX_DATA_(BLT_I18NCONTEXT_ID_LIGHT, "LightProbe");
485         }
486 }
487
488 static int lightprobe_add_exec(bContext *C, wmOperator *op)
489 {
490         Object *ob;
491         LightProbe *probe;
492         int type;
493         bool enter_editmode;
494         ushort local_view_bits;
495         float loc[3], rot[3];
496         float radius;
497
498         WM_operator_view3d_unit_defaults(C, op);
499         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &local_view_bits, NULL)) {
500                 return OPERATOR_CANCELLED;
501         }
502         type = RNA_enum_get(op->ptr, "type");
503         radius = RNA_float_get(op->ptr, "radius");
504
505         ob = ED_object_add_type(C, OB_LIGHTPROBE, get_lightprobe_defname(type), loc, rot, false, local_view_bits);
506         BKE_object_obdata_size_init(ob, radius);
507
508         probe = (LightProbe *)ob->data;
509         probe->type = type;
510
511         switch (type) {
512                 case LIGHTPROBE_TYPE_GRID:
513                         probe->distinf = 0.3f;
514                         probe->falloff = 1.0f;
515                         probe->clipsta = 0.01f;
516                         break;
517                 case LIGHTPROBE_TYPE_PLANAR:
518                         probe->distinf = 0.1f;
519                         probe->falloff = 0.5f;
520                         probe->clipsta = 0.001f;
521                         ob->empty_drawsize = 0.5f;
522                         break;
523                 case LIGHTPROBE_TYPE_CUBE:
524                         probe->attenuation_type = LIGHTPROBE_SHAPE_ELIPSOID;
525                         break;
526                 default:
527                         BLI_assert(!"LightProbe type not configured.");
528                         break;
529         }
530
531         DEG_relations_tag_update(CTX_data_main(C));
532
533         return OPERATOR_FINISHED;
534 }
535
536 void OBJECT_OT_lightprobe_add(wmOperatorType *ot)
537 {
538         /* identifiers */
539         ot->name = "Add Light Probe";
540         ot->description = "Add a light probe object";
541         ot->idname = "OBJECT_OT_lightprobe_add";
542
543         /* api callbacks */
544         ot->exec = lightprobe_add_exec;
545         ot->poll = ED_operator_objectmode;
546
547         /* flags */
548         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
549
550         /* properties */
551         ot->prop = RNA_def_enum(ot->srna, "type", lightprobe_type_items, 0, "Type", "");
552
553         ED_object_add_unit_props_radius(ot);
554         ED_object_add_generic_props(ot, true);
555 }
556
557 /********************* Add Effector Operator ********************/
558
559 /* for object add operator */
560 static int effector_add_exec(bContext *C, wmOperator *op)
561 {
562         Object *ob;
563         int type;
564         bool enter_editmode;
565         ushort local_view_bits;
566         float loc[3], rot[3];
567         float mat[4][4];
568         float dia;
569
570         WM_operator_view3d_unit_defaults(C, op);
571         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &local_view_bits, NULL)) {
572                 return OPERATOR_CANCELLED;
573         }
574         type = RNA_enum_get(op->ptr, "type");
575         dia = RNA_float_get(op->ptr, "radius");
576
577         if (type == PFIELD_GUIDE) {
578                 Curve *cu;
579                 const char *name = CTX_DATA_(BLT_I18NCONTEXT_ID_OBJECT, "CurveGuide");
580                 ob = ED_object_add_type(C, OB_CURVE, name, loc, rot, false, local_view_bits);
581
582                 cu = ob->data;
583                 cu->flag |= CU_PATH | CU_3D;
584                 ED_object_editmode_enter(C, 0);
585                 ED_object_new_primitive_matrix(C, ob, loc, rot, mat);
586                 BLI_addtail(&cu->editnurb->nurbs, ED_curve_add_nurbs_primitive(C, ob, mat, CU_NURBS | CU_PRIM_PATH, dia));
587                 if (!enter_editmode)
588                         ED_object_editmode_exit(C, EM_FREEDATA);
589         }
590         else {
591                 const char *name = CTX_DATA_(BLT_I18NCONTEXT_ID_OBJECT, "Field");
592                 ob = ED_object_add_type(C, OB_EMPTY, name, loc, rot, false, local_view_bits);
593                 BKE_object_obdata_size_init(ob, dia);
594                 if (ELEM(type, PFIELD_WIND, PFIELD_VORTEX))
595                         ob->empty_drawtype = OB_SINGLE_ARROW;
596         }
597
598         ob->pd = BKE_partdeflect_new(type);
599
600         DEG_relations_tag_update(CTX_data_main(C));
601
602         return OPERATOR_FINISHED;
603 }
604
605 void OBJECT_OT_effector_add(wmOperatorType *ot)
606 {
607         /* identifiers */
608         ot->name = "Add Effector";
609         ot->description = "Add an empty object with a physics effector to the scene";
610         ot->idname = "OBJECT_OT_effector_add";
611
612         /* api callbacks */
613         ot->exec = effector_add_exec;
614         ot->poll = ED_operator_objectmode;
615
616         /* flags */
617         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
618
619         /* properties */
620         ot->prop = RNA_def_enum(ot->srna, "type", field_type_items, 0, "Type", "");
621
622         ED_object_add_unit_props_radius(ot);
623         ED_object_add_generic_props(ot, true);
624 }
625
626 /********************* Add Camera Operator ********************/
627
628 static int object_camera_add_exec(bContext *C, wmOperator *op)
629 {
630         View3D *v3d = CTX_wm_view3d(C);
631         Scene *scene = CTX_data_scene(C);
632         Object *ob;
633         Camera *cam;
634         bool enter_editmode;
635         ushort local_view_bits;
636         float loc[3], rot[3];
637
638         /* force view align for cameras */
639         RNA_boolean_set(op->ptr, "view_align", true);
640
641         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &local_view_bits, NULL)) {
642                 return OPERATOR_CANCELLED;
643         }
644         ob = ED_object_add_type(C, OB_CAMERA, NULL, loc, rot, false, local_view_bits);
645
646         if (v3d) {
647                 if (v3d->camera == NULL)
648                         v3d->camera = ob;
649                 if (v3d->scenelock && scene->camera == NULL) {
650                         scene->camera = ob;
651                 }
652         }
653
654         cam = ob->data;
655         cam->drawsize = v3d ? ED_view3d_grid_scale(scene, v3d, NULL) : ED_scene_grid_scale(scene, NULL);
656
657         return OPERATOR_FINISHED;
658 }
659
660 void OBJECT_OT_camera_add(wmOperatorType *ot)
661 {
662         PropertyRNA *prop;
663
664         /* identifiers */
665         ot->name = "Add Camera";
666         ot->description = "Add a camera object to the scene";
667         ot->idname = "OBJECT_OT_camera_add";
668
669         /* api callbacks */
670         ot->exec = object_camera_add_exec;
671         ot->poll = ED_operator_objectmode;
672
673         /* flags */
674         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
675
676         ED_object_add_generic_props(ot, true);
677
678         /* hide this for cameras, default */
679         prop = RNA_struct_type_find_property(ot->srna, "view_align");
680         RNA_def_property_flag(prop, PROP_HIDDEN);
681 }
682
683
684 /********************* Add Metaball Operator ********************/
685
686 static int object_metaball_add_exec(bContext *C, wmOperator *op)
687 {
688         Object *obedit = CTX_data_edit_object(C);
689         bool newob = false;
690         bool enter_editmode;
691         ushort local_view_bits;
692         float loc[3], rot[3];
693         float mat[4][4];
694         float dia;
695
696         WM_operator_view3d_unit_defaults(C, op);
697         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &local_view_bits, NULL)) {
698                 return OPERATOR_CANCELLED;
699         }
700         if (obedit == NULL || obedit->type != OB_MBALL) {
701                 obedit = ED_object_add_type(C, OB_MBALL, NULL, loc, rot, true, local_view_bits);
702                 newob = true;
703         }
704         else {
705                 DEG_id_tag_update(&obedit->id, ID_RECALC_GEOMETRY);
706         }
707
708         ED_object_new_primitive_matrix(C, obedit, loc, rot, mat);
709         dia = RNA_float_get(op->ptr, "radius");
710
711         ED_mball_add_primitive(C, obedit, mat, dia, RNA_enum_get(op->ptr, "type"));
712
713         /* userdef */
714         if (newob && !enter_editmode) {
715                 ED_object_editmode_exit(C, EM_FREEDATA);
716         }
717
718         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obedit);
719
720         return OPERATOR_FINISHED;
721 }
722
723 void OBJECT_OT_metaball_add(wmOperatorType *ot)
724 {
725         /* identifiers */
726         ot->name = "Add Metaball";
727         ot->description = "Add an metaball object to the scene";
728         ot->idname = "OBJECT_OT_metaball_add";
729
730         /* api callbacks */
731         ot->invoke = WM_menu_invoke;
732         ot->exec = object_metaball_add_exec;
733         ot->poll = ED_operator_scene_editable;
734
735         /* flags */
736         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
737
738         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_metaelem_type_items, 0, "Primitive", "");
739
740         ED_object_add_unit_props_radius(ot);
741         ED_object_add_generic_props(ot, true);
742 }
743
744 /********************* Add Text Operator ********************/
745
746 static int object_add_text_exec(bContext *C, wmOperator *op)
747 {
748         Object *obedit = CTX_data_edit_object(C);
749         bool enter_editmode;
750         ushort local_view_bits;
751         float loc[3], rot[3];
752
753         WM_operator_view3d_unit_defaults(C, op);
754         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &local_view_bits, NULL)) {
755                 return OPERATOR_CANCELLED;
756         }
757         if (obedit && obedit->type == OB_FONT)
758                 return OPERATOR_CANCELLED;
759
760         obedit = ED_object_add_type(C, OB_FONT, NULL, loc, rot, enter_editmode, local_view_bits);
761         BKE_object_obdata_size_init(obedit, RNA_float_get(op->ptr, "radius"));
762
763         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obedit);
764
765         return OPERATOR_FINISHED;
766 }
767
768 void OBJECT_OT_text_add(wmOperatorType *ot)
769 {
770         /* identifiers */
771         ot->name = "Add Text";
772         ot->description = "Add a text object to the scene";
773         ot->idname = "OBJECT_OT_text_add";
774
775         /* api callbacks */
776         ot->exec = object_add_text_exec;
777         ot->poll = ED_operator_objectmode;
778
779         /* flags */
780         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
781
782         /* properties */
783         ED_object_add_unit_props_radius(ot);
784         ED_object_add_generic_props(ot, true);
785 }
786
787 /********************* Add Armature Operator ********************/
788
789 static int object_armature_add_exec(bContext *C, wmOperator *op)
790 {
791         Object *obedit = CTX_data_edit_object(C);
792         RegionView3D *rv3d = CTX_wm_region_view3d(C);
793         bool newob = false;
794         bool enter_editmode;
795         ushort local_view_bits;
796         float loc[3], rot[3], dia;
797         bool view_aligned = rv3d && (U.flag & USER_ADD_VIEWALIGNED);
798
799         WM_operator_view3d_unit_defaults(C, op);
800         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, &enter_editmode, &local_view_bits, NULL)) {
801                 return OPERATOR_CANCELLED;
802         }
803         if ((obedit == NULL) || (obedit->type != OB_ARMATURE)) {
804                 obedit = ED_object_add_type(C, OB_ARMATURE, NULL, loc, rot, true, local_view_bits);
805                 ED_object_editmode_enter(C, 0);
806                 newob = true;
807         }
808         else {
809                 DEG_id_tag_update(&obedit->id, ID_RECALC_GEOMETRY);
810         }
811
812         if (obedit == NULL) {
813                 BKE_report(op->reports, RPT_ERROR, "Cannot create editmode armature");
814                 return OPERATOR_CANCELLED;
815         }
816
817         dia = RNA_float_get(op->ptr, "radius");
818         ED_armature_ebone_add_primitive(obedit, dia, view_aligned);
819
820         /* userdef */
821         if (newob && !enter_editmode)
822                 ED_object_editmode_exit(C, EM_FREEDATA);
823
824         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obedit);
825
826         return OPERATOR_FINISHED;
827 }
828
829 void OBJECT_OT_armature_add(wmOperatorType *ot)
830 {
831         /* identifiers */
832         ot->name = "Add Armature";
833         ot->description = "Add an armature object to the scene";
834         ot->idname = "OBJECT_OT_armature_add";
835
836         /* api callbacks */
837         ot->exec = object_armature_add_exec;
838         ot->poll = ED_operator_objectmode;
839
840         /* flags */
841         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
842
843         /* properties */
844         ED_object_add_unit_props_radius(ot);
845         ED_object_add_generic_props(ot, true);
846 }
847
848 /********************* Add Empty Operator ********************/
849
850 static int object_empty_add_exec(bContext *C, wmOperator *op)
851 {
852         Object *ob;
853         int type = RNA_enum_get(op->ptr, "type");
854         ushort local_view_bits;
855         float loc[3], rot[3];
856
857         WM_operator_view3d_unit_defaults(C, op);
858         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, NULL, &local_view_bits, NULL)) {
859                 return OPERATOR_CANCELLED;
860         }
861         ob = ED_object_add_type(C, OB_EMPTY, NULL, loc, rot, false, local_view_bits);
862
863         BKE_object_empty_draw_type_set(ob, type);
864         BKE_object_obdata_size_init(ob, RNA_float_get(op->ptr, "radius"));
865
866         return OPERATOR_FINISHED;
867 }
868
869 void OBJECT_OT_empty_add(wmOperatorType *ot)
870 {
871         /* identifiers */
872         ot->name = "Add Empty";
873         ot->description = "Add an empty object to the scene";
874         ot->idname = "OBJECT_OT_empty_add";
875
876         /* api callbacks */
877         ot->invoke = WM_menu_invoke;
878         ot->exec = object_empty_add_exec;
879         ot->poll = ED_operator_objectmode;
880
881         /* flags */
882         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
883
884         /* properties */
885         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_object_empty_drawtype_items, 0, "Type", "");
886
887         ED_object_add_unit_props_radius(ot);
888         ED_object_add_generic_props(ot, false);
889 }
890
891 static int empty_drop_named_image_invoke(bContext *C, wmOperator *op, const wmEvent *event)
892 {
893         Scene *scene = CTX_data_scene(C);
894
895         Image *ima = NULL;
896
897         ima = (Image *)WM_operator_drop_load_path(C, op, ID_IM);
898         if (!ima) {
899                 return OPERATOR_CANCELLED;
900         }
901         /* handled below */
902         id_us_min((ID *)ima);
903
904         Object *ob = NULL;
905         Object *ob_cursor = ED_view3d_give_object_under_cursor(C, event->mval);
906
907         /* either change empty under cursor or create a new empty */
908         if (ob_cursor && ob_cursor->type == OB_EMPTY) {
909                 WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
910                 DEG_id_tag_update((ID *)ob_cursor, ID_RECALC_TRANSFORM);
911                 ob = ob_cursor;
912         }
913         else {
914                 /* add new empty */
915                 ushort local_view_bits;
916                 float rot[3];
917
918                 if (!ED_object_add_generic_get_opts(C, op, 'Z', NULL, rot, NULL, &local_view_bits, NULL)) {
919                         return OPERATOR_CANCELLED;
920                 }
921                 ob = ED_object_add_type(C, OB_EMPTY, NULL, NULL, rot, false, local_view_bits);
922
923                 ED_object_location_from_view(C, ob->loc);
924                 ED_view3d_cursor3d_position(C, event->mval, false, ob->loc);
925                 ED_object_rotation_from_view(C, ob->rot, 'Z');
926                 ob->empty_drawsize = 5.0f;
927         }
928
929         BKE_object_empty_draw_type_set(ob, OB_EMPTY_IMAGE);
930
931         id_us_min(ob->data);
932         ob->data = ima;
933         id_us_plus(ob->data);
934
935         return OPERATOR_FINISHED;
936 }
937
938 void OBJECT_OT_drop_named_image(wmOperatorType *ot)
939 {
940         PropertyRNA *prop;
941
942         /* identifiers */
943         ot->name = "Add Empty Image/Drop Image To Empty";
944         ot->description = "Add an empty image type to scene with data";
945         ot->idname = "OBJECT_OT_drop_named_image";
946
947         /* api callbacks */
948         ot->invoke = empty_drop_named_image_invoke;
949         ot->poll = ED_operator_objectmode;
950
951         /* flags */
952         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
953
954         /* properties */
955         prop = RNA_def_string(ot->srna, "filepath", NULL, FILE_MAX, "Filepath", "Path to image file");
956         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
957         RNA_def_boolean(ot->srna, "relative_path", true, "Relative Path", "Select the file relative to the blend file");
958         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
959         prop = RNA_def_string(ot->srna, "name", NULL, MAX_ID_NAME - 2, "Name", "Image name to assign");
960         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
961         ED_object_add_generic_props(ot, false);
962 }
963
964 /********************* Add Gpencil Operator ********************/
965 static bool object_gpencil_add_poll(bContext *C)
966 {
967         Scene *scene = CTX_data_scene(C);
968         Object *obact = CTX_data_active_object(C);
969
970         if ((scene == NULL) || (ID_IS_LINKED(scene))) {
971                 return false;
972         }
973
974         if (obact && obact->type == OB_GPENCIL) {
975                 if (obact->mode != OB_MODE_OBJECT) {
976                         return false;
977                 }
978         }
979
980         return true;
981 }
982
983 static int object_gpencil_add_exec(bContext *C, wmOperator *op)
984 {
985         Object *ob = CTX_data_active_object(C);
986         bGPdata *gpd = (ob && (ob->type == OB_GPENCIL)) ? ob->data : NULL;
987
988         const int type = RNA_enum_get(op->ptr, "type");
989
990         ushort local_view_bits;
991         float loc[3], rot[3];
992         bool newob = false;
993
994         /* Note: We use 'Y' here (not 'Z'), as */
995         WM_operator_view3d_unit_defaults(C, op);
996         if (!ED_object_add_generic_get_opts(C, op, 'Y', loc, rot, NULL, &local_view_bits, NULL)) {
997                 return OPERATOR_CANCELLED;
998         }
999         /* add new object if not currently editing a GP object,
1000          * or if "empty" was chosen (i.e. user wants a blank GP canvas)
1001          */
1002         if ((gpd == NULL) || (GPENCIL_ANY_MODE(gpd) == false) || (type == GP_EMPTY)) {
1003                 const char *ob_name = NULL;
1004                 switch (type) {
1005                         case GP_MONKEY:
1006                         {
1007                                 ob_name = "Suzanne";
1008                                 break;
1009                         }
1010                         case GP_STROKE:
1011                         {
1012                                 ob_name = "Stroke";
1013                                 break;
1014                         }
1015                         default:
1016                         {
1017                                 break;
1018                         }
1019                 }
1020
1021                 ob = ED_object_add_type(C, OB_GPENCIL, ob_name, loc, rot, true, local_view_bits);
1022                 gpd = ob->data;
1023                 newob = true;
1024         }
1025         else {
1026                 DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
1027                 WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_ADDED, NULL);
1028         }
1029
1030         /* create relevant geometry */
1031         switch (type) {
1032                 case GP_STROKE:
1033                 {
1034                         float radius = RNA_float_get(op->ptr, "radius");
1035                         float mat[4][4];
1036
1037                         ED_object_new_primitive_matrix(C, ob, loc, rot, mat);
1038                         mul_v3_fl(mat[0], radius);
1039                         mul_v3_fl(mat[1], radius);
1040                         mul_v3_fl(mat[2], radius);
1041
1042                         ED_gpencil_create_stroke(C, ob, mat);
1043                         break;
1044                 }
1045                 case GP_MONKEY:
1046                 {
1047                         float radius = RNA_float_get(op->ptr, "radius");
1048                         float mat[4][4];
1049
1050                         ED_object_new_primitive_matrix(C, ob, loc, rot, mat);
1051                         mul_v3_fl(mat[0], radius);
1052                         mul_v3_fl(mat[1], radius);
1053                         mul_v3_fl(mat[2], radius);
1054
1055                         ED_gpencil_create_monkey(C, ob, mat);
1056                         break;
1057                 }
1058                 case GP_EMPTY:
1059                         /* do nothing */
1060                         break;
1061
1062                 default:
1063                         BKE_report(op->reports, RPT_WARNING, "Not implemented");
1064                         break;
1065         }
1066
1067         /* if this is a new object, initialise default stuff (colors, etc.) */
1068         if (newob) {
1069                 ED_gpencil_add_defaults(C, ob);
1070         }
1071
1072         return OPERATOR_FINISHED;
1073 }
1074
1075 void OBJECT_OT_gpencil_add(wmOperatorType *ot)
1076 {
1077         /* identifiers */
1078         ot->name = "Add Grease Pencil";
1079         ot->description = "Add a Grease Pencil object to the scene";
1080         ot->idname = "OBJECT_OT_gpencil_add";
1081
1082         /* api callbacks */
1083         ot->invoke = WM_menu_invoke;
1084         ot->exec = object_gpencil_add_exec;
1085         ot->poll = object_gpencil_add_poll;
1086
1087         /* flags */
1088         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1089
1090         /* properties */
1091         ED_object_add_unit_props_radius(ot);
1092         ED_object_add_generic_props(ot, false);
1093
1094         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_object_gpencil_type_items, 0, "Type", "");
1095 }
1096
1097 /********************* Add Light Operator ********************/
1098
1099 static const char *get_light_defname(int type)
1100 {
1101         switch (type) {
1102                 case LA_LOCAL: return CTX_DATA_(BLT_I18NCONTEXT_ID_LIGHT, "Point");
1103                 case LA_SUN: return CTX_DATA_(BLT_I18NCONTEXT_ID_LIGHT, "Sun");
1104                 case LA_SPOT: return CTX_DATA_(BLT_I18NCONTEXT_ID_LIGHT, "Spot");
1105                 case LA_AREA: return CTX_DATA_(BLT_I18NCONTEXT_ID_LIGHT, "Area");
1106                 default:
1107                         return CTX_DATA_(BLT_I18NCONTEXT_ID_LIGHT, "Light");
1108         }
1109 }
1110
1111 static int object_light_add_exec(bContext *C, wmOperator *op)
1112 {
1113         Scene *scene = CTX_data_scene(C);
1114         Object *ob;
1115         Light *la;
1116         int type = RNA_enum_get(op->ptr, "type");
1117         ushort local_view_bits;
1118         float loc[3], rot[3];
1119
1120         WM_operator_view3d_unit_defaults(C, op);
1121         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, NULL, &local_view_bits, NULL)) {
1122                 return OPERATOR_CANCELLED;
1123         }
1124         ob = ED_object_add_type(C, OB_LAMP, get_light_defname(type), loc, rot, false, local_view_bits);
1125
1126         float size = RNA_float_get(op->ptr, "radius");
1127         /* Better defaults for light size. */
1128         switch (type) {
1129                 case LA_LOCAL:
1130                 case LA_SPOT:
1131                         break;
1132                 case LA_AREA:
1133                         size *= 4.0f;
1134                         break;
1135                 default:
1136                         size *= 0.5f;
1137                         break;
1138         }
1139         BKE_object_obdata_size_init(ob, size);
1140
1141         la = (Light *)ob->data;
1142         la->type = type;
1143
1144         if (BKE_scene_uses_cycles(scene)) {
1145                 ED_node_shader_default(C, &la->id);
1146                 la->use_nodes = true;
1147         }
1148
1149         return OPERATOR_FINISHED;
1150 }
1151
1152 void OBJECT_OT_light_add(wmOperatorType *ot)
1153 {
1154         /* identifiers */
1155         ot->name = "Add Light";
1156         ot->description = "Add a light object to the scene";
1157         ot->idname = "OBJECT_OT_light_add";
1158
1159         /* api callbacks */
1160         ot->invoke = WM_menu_invoke;
1161         ot->exec = object_light_add_exec;
1162         ot->poll = ED_operator_objectmode;
1163
1164         /* flags */
1165         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1166
1167         /* properties */
1168         ot->prop = RNA_def_enum(ot->srna, "type", rna_enum_light_type_items, 0, "Type", "");
1169         RNA_def_property_translation_context(ot->prop, BLT_I18NCONTEXT_ID_LIGHT);
1170
1171         ED_object_add_unit_props_radius(ot);
1172         ED_object_add_generic_props(ot, false);
1173 }
1174
1175 /********************* Add Collection Instance Operator ********************/
1176
1177 static int collection_instance_add_exec(bContext *C, wmOperator *op)
1178 {
1179         Main *bmain = CTX_data_main(C);
1180         Collection *collection;
1181         ushort local_view_bits;
1182         float loc[3], rot[3];
1183
1184         if (RNA_struct_property_is_set(op->ptr, "name")) {
1185                 char name[MAX_ID_NAME - 2];
1186
1187                 RNA_string_get(op->ptr, "name", name);
1188                 collection = (Collection *)BKE_libblock_find_name(bmain, ID_GR, name);
1189
1190                 if (0 == RNA_struct_property_is_set(op->ptr, "location")) {
1191                         const wmEvent *event = CTX_wm_window(C)->eventstate;
1192                         ARegion *ar = CTX_wm_region(C);
1193                         const int mval[2] = {event->x - ar->winrct.xmin,
1194                                              event->y - ar->winrct.ymin};
1195                         ED_object_location_from_view(C, loc);
1196                         ED_view3d_cursor3d_position(C, mval, false, loc);
1197                         RNA_float_set_array(op->ptr, "location", loc);
1198                 }
1199         }
1200         else
1201                 collection = BLI_findlink(&CTX_data_main(C)->collection, RNA_enum_get(op->ptr, "collection"));
1202
1203         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, NULL, &local_view_bits, NULL)) {
1204                 return OPERATOR_CANCELLED;
1205         }
1206         if (collection) {
1207                 Scene *scene = CTX_data_scene(C);
1208                 ViewLayer *view_layer = CTX_data_view_layer(C);
1209
1210                 /* Avoid dependency cycles. */
1211                 LayerCollection *active_lc = BKE_layer_collection_get_active(view_layer);
1212                 while (BKE_collection_find_cycle(active_lc->collection, collection)) {
1213                         active_lc = BKE_layer_collection_activate_parent(view_layer, active_lc);
1214                 }
1215
1216                 Object *ob = ED_object_add_type(C, OB_EMPTY, collection->id.name + 2, loc, rot, false, local_view_bits);
1217                 ob->instance_collection = collection;
1218                 ob->transflag |= OB_DUPLICOLLECTION;
1219                 id_us_plus(&collection->id);
1220
1221                 /* works without this except if you try render right after, see: 22027 */
1222                 DEG_relations_tag_update(bmain);
1223                 DEG_id_tag_update(&scene->id, ID_RECALC_SELECT);
1224                 WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
1225
1226                 return OPERATOR_FINISHED;
1227         }
1228
1229         return OPERATOR_CANCELLED;
1230 }
1231
1232 /* only used as menu */
1233 void OBJECT_OT_collection_instance_add(wmOperatorType *ot)
1234 {
1235         PropertyRNA *prop;
1236
1237         /* identifiers */
1238         ot->name = "Add Collection Instance";
1239         ot->description = "Add a collection instance";
1240         ot->idname = "OBJECT_OT_collection_instance_add";
1241
1242         /* api callbacks */
1243         ot->invoke = WM_enum_search_invoke;
1244         ot->exec = collection_instance_add_exec;
1245         ot->poll = ED_operator_objectmode;
1246
1247         /* flags */
1248         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1249
1250         /* properties */
1251         RNA_def_string(ot->srna, "name", "Collection", MAX_ID_NAME - 2, "Name", "Collection name to add");
1252         prop = RNA_def_enum(ot->srna, "collection", DummyRNA_NULL_items, 0, "Collection", "");
1253         RNA_def_enum_funcs(prop, RNA_collection_itemf);
1254         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
1255         ot->prop = prop;
1256         ED_object_add_generic_props(ot, false);
1257 }
1258
1259 /********************* Add Speaker Operator ********************/
1260
1261 static int object_speaker_add_exec(bContext *C, wmOperator *op)
1262 {
1263         Object *ob;
1264         ushort local_view_bits;
1265         float loc[3], rot[3];
1266         Scene *scene = CTX_data_scene(C);
1267
1268         if (!ED_object_add_generic_get_opts(C, op, 'Z', loc, rot, NULL, &local_view_bits, NULL)) {
1269                 return OPERATOR_CANCELLED;
1270         }
1271         ob = ED_object_add_type(C, OB_SPEAKER, NULL, loc, rot, false, local_view_bits);
1272
1273         /* to make it easier to start using this immediately in NLA, a default sound clip is created
1274          * ready to be moved around to retime the sound and/or make new sound clips
1275          */
1276         {
1277                 /* create new data for NLA hierarchy */
1278                 AnimData *adt = BKE_animdata_add_id(&ob->id);
1279                 NlaTrack *nlt = BKE_nlatrack_add(adt, NULL);
1280                 NlaStrip *strip = BKE_nla_add_soundstrip(scene, ob->data);
1281                 strip->start = CFRA;
1282                 strip->end += strip->start;
1283
1284                 /* hook them up */
1285                 BKE_nlatrack_add_strip(nlt, strip);
1286
1287                 /* auto-name the strip, and give the track an interesting name  */
1288                 BLI_strncpy(nlt->name, DATA_("SoundTrack"), sizeof(nlt->name));
1289                 BKE_nlastrip_validate_name(adt, strip);
1290
1291                 WM_event_add_notifier(C, NC_ANIMATION | ND_NLA | NA_EDITED, NULL);
1292         }
1293
1294         return OPERATOR_FINISHED;
1295 }
1296
1297 void OBJECT_OT_speaker_add(wmOperatorType *ot)
1298 {
1299         /* identifiers */
1300         ot->name = "Add Speaker";
1301         ot->description = "Add a speaker object to the scene";
1302         ot->idname = "OBJECT_OT_speaker_add";
1303
1304         /* api callbacks */
1305         ot->exec = object_speaker_add_exec;
1306         ot->poll = ED_operator_objectmode;
1307
1308         /* flags */
1309         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1310
1311         ED_object_add_generic_props(ot, true);
1312 }
1313
1314 /**************************** Delete Object *************************/
1315
1316 /* remove base from a specific scene */
1317 /* note: now unlinks constraints as well */
1318 void ED_object_base_free_and_unlink(Main *bmain, Scene *scene, Object *ob)
1319 {
1320         if (BKE_library_ID_is_indirectly_used(bmain, ob) &&
1321             ID_REAL_USERS(ob) <= 1 && ID_EXTRA_USERS(ob) == 0)
1322         {
1323                 /* We cannot delete indirectly used object... */
1324                 printf("WARNING, undeletable object '%s', should have been catched before reaching this function!",
1325                        ob->id.name + 2);
1326                 return;
1327         }
1328
1329         DEG_id_tag_update_ex(bmain, &ob->id, ID_RECALC_BASE_FLAGS);
1330
1331         BKE_scene_collections_object_remove(bmain, scene, ob, true);
1332 }
1333
1334 static int object_delete_exec(bContext *C, wmOperator *op)
1335 {
1336         Main *bmain = CTX_data_main(C);
1337         Scene *scene = CTX_data_scene(C);
1338         wmWindowManager *wm = CTX_wm_manager(C);
1339         wmWindow *win;
1340         const bool use_global = RNA_boolean_get(op->ptr, "use_global");
1341         uint changed_count = 0;
1342
1343         if (CTX_data_edit_object(C))
1344                 return OPERATOR_CANCELLED;
1345
1346         CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
1347         {
1348                 const bool is_indirectly_used = BKE_library_ID_is_indirectly_used(bmain, ob);
1349                 if (ob->id.tag & LIB_TAG_INDIRECT) {
1350                         /* Can this case ever happen? */
1351                         BKE_reportf(op->reports, RPT_WARNING, "Cannot delete indirectly linked object '%s'", ob->id.name + 2);
1352                         continue;
1353                 }
1354                 else if (is_indirectly_used && ID_REAL_USERS(ob) <= 1 && ID_EXTRA_USERS(ob) == 0) {
1355                         BKE_reportf(op->reports, RPT_WARNING,
1356                                 "Cannot delete object '%s' from scene '%s', indirectly used objects need at least one user",
1357                                 ob->id.name + 2, scene->id.name + 2);
1358                         continue;
1359                 }
1360
1361                 /* if grease pencil object, set cache as dirty */
1362                 if (ob->type == OB_GPENCIL) {
1363                         bGPdata *gpd = (bGPdata *)ob->data;
1364                         DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
1365                 }
1366
1367                 /* This is sort of a quick hack to address T51243 - Proper thing to do here would be to nuke most of all this
1368                  * custom scene/object/base handling, and use generic lib remap/query for that.
1369                  * But this is for later (aka 2.8, once layers & co are settled and working).
1370                  */
1371                 if (use_global && ob->id.lib == NULL) {
1372                         /* We want to nuke the object, let's nuke it the easy way (not for linked data though)... */
1373                         BKE_id_delete(bmain, &ob->id);
1374                         changed_count += 1;
1375                         continue;
1376                 }
1377
1378                 /* remove from Grease Pencil parent */
1379                 /* XXX This is likely not correct? Will also remove parent from grease pencil from other scenes,
1380                  *     even when use_global is false... */
1381                 for (bGPdata *gpd = bmain->gpencil.first; gpd; gpd = gpd->id.next) {
1382                         for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
1383                                 if (gpl->parent != NULL) {
1384                                         if (gpl->parent == ob) {
1385                                                 gpl->parent = NULL;
1386                                         }
1387                                 }
1388                         }
1389                 }
1390
1391                 /* remove from current scene only */
1392                 ED_object_base_free_and_unlink(bmain, scene, ob);
1393                 changed_count += 1;
1394
1395                 if (use_global) {
1396                         Scene *scene_iter;
1397                         for (scene_iter = bmain->scene.first; scene_iter; scene_iter = scene_iter->id.next) {
1398                                 if (scene_iter != scene && !ID_IS_LINKED(scene_iter)) {
1399                                         if (is_indirectly_used && ID_REAL_USERS(ob) <= 1 && ID_EXTRA_USERS(ob) == 0) {
1400                                                 BKE_reportf(op->reports, RPT_WARNING,
1401                                                             "Cannot delete object '%s' from scene '%s', indirectly used objects need at least one user",
1402                                                             ob->id.name + 2, scene_iter->id.name + 2);
1403                                                 break;
1404                                         }
1405                                         ED_object_base_free_and_unlink(bmain, scene_iter, ob);
1406                                 }
1407                         }
1408                 }
1409                 /* end global */
1410         }
1411         CTX_DATA_END;
1412
1413         BKE_reportf(op->reports, RPT_INFO, "Deleted %u object(s)", changed_count);
1414
1415         if (changed_count == 0) {
1416                 return OPERATOR_CANCELLED;
1417         }
1418
1419         /* delete has to handle all open scenes */
1420         BKE_main_id_tag_listbase(&bmain->scene, LIB_TAG_DOIT, true);
1421         for (win = wm->windows.first; win; win = win->next) {
1422                 scene = WM_window_get_active_scene(win);
1423
1424                 if (scene->id.tag & LIB_TAG_DOIT) {
1425                         scene->id.tag &= ~LIB_TAG_DOIT;
1426
1427                         DEG_relations_tag_update(bmain);
1428
1429                         DEG_id_tag_update(&scene->id, ID_RECALC_SELECT);
1430                         WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
1431                         WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, scene);
1432                 }
1433         }
1434
1435         return OPERATOR_FINISHED;
1436 }
1437
1438 void OBJECT_OT_delete(wmOperatorType *ot)
1439 {
1440         /* identifiers */
1441         ot->name = "Delete";
1442         ot->description = "Delete selected objects";
1443         ot->idname = "OBJECT_OT_delete";
1444
1445         /* api callbacks */
1446         ot->invoke = WM_operator_confirm_or_exec;
1447         ot->exec = object_delete_exec;
1448         ot->poll = ED_operator_objectmode;
1449
1450         /* flags */
1451         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1452
1453         PropertyRNA *prop;
1454         prop = RNA_def_boolean(ot->srna, "use_global", 0, "Delete Globally", "Remove object from all scenes");
1455         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1456         WM_operator_properties_confirm_or_exec(ot);
1457 }
1458
1459 /**************************** Copy Utilities ******************************/
1460
1461 /* after copying objects, copied data should get new pointers */
1462 static void copy_object_set_idnew(bContext *C)
1463 {
1464         Main *bmain = CTX_data_main(C);
1465
1466         CTX_DATA_BEGIN (C, Object *, ob, selected_editable_objects)
1467         {
1468                 BKE_libblock_relink_to_newid(&ob->id);
1469         }
1470         CTX_DATA_END;
1471
1472         BKE_main_id_clear_newpoins(bmain);
1473 }
1474
1475 /********************* Make Duplicates Real ************************/
1476
1477 /**
1478  * \note regarding hashing dupli-objects when using OB_DUPLICOLLECTION, skip the first member of #DupliObject.persistent_id
1479  * since its a unique index and we only want to know if the group objects are from the same dupli-group instance.
1480  */
1481 static unsigned int dupliobject_group_hash(const void *ptr)
1482 {
1483         const DupliObject *dob = ptr;
1484         unsigned int hash = BLI_ghashutil_ptrhash(dob->ob);
1485         unsigned int i;
1486         for (i = 1; (i < MAX_DUPLI_RECUR) && dob->persistent_id[i] != INT_MAX; i++) {
1487                 hash ^= (dob->persistent_id[i] ^ i);
1488         }
1489         return hash;
1490 }
1491
1492 /**
1493  * \note regarding hashing dupli-objects when NOT using OB_DUPLICOLLECTION, include the first member of #DupliObject.persistent_id
1494  * since its the index of the vertex/face the object is instantiated on and we want to identify objects on the same vertex/face.
1495  */
1496 static unsigned int dupliobject_hash(const void *ptr)
1497 {
1498         const DupliObject *dob = ptr;
1499         unsigned int hash = BLI_ghashutil_ptrhash(dob->ob);
1500         hash ^= (dob->persistent_id[0] ^ 0);
1501         return hash;
1502 }
1503
1504 /* Compare function that matches dupliobject_group_hash */
1505 static bool dupliobject_group_cmp(const void *a_, const void *b_)
1506 {
1507         const DupliObject *a = a_;
1508         const DupliObject *b = b_;
1509         unsigned int i;
1510
1511         if (a->ob != b->ob) {
1512                 return true;
1513         }
1514
1515         for (i = 1; (i < MAX_DUPLI_RECUR); i++) {
1516                 if (a->persistent_id[i] != b->persistent_id[i]) {
1517                         return true;
1518                 }
1519                 else if (a->persistent_id[i] == INT_MAX) {
1520                         break;
1521                 }
1522         }
1523
1524         /* matching */
1525         return false;
1526 }
1527
1528 /* Compare function that matches dupliobject_hash */
1529 static bool dupliobject_cmp(const void *a_, const void *b_)
1530 {
1531         const DupliObject *a = a_;
1532         const DupliObject *b = b_;
1533
1534         if (a->ob != b->ob) {
1535                 return true;
1536         }
1537
1538         if (a->persistent_id[0] != b->persistent_id[0]) {
1539                 return true;
1540         }
1541
1542         /* matching */
1543         return false;
1544 }
1545
1546 static void make_object_duplilist_real(bContext *C, Scene *scene, Base *base,
1547                                        const bool use_base_parent,
1548                                        const bool use_hierarchy)
1549 {
1550         Main *bmain = CTX_data_main(C);
1551         ViewLayer *view_layer = CTX_data_view_layer(C);
1552         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1553         ListBase *lb_duplis;
1554         DupliObject *dob;
1555         GHash *dupli_gh, *parent_gh = NULL;
1556
1557         if (!(base->object->transflag & OB_DUPLI)) {
1558                 return;
1559         }
1560
1561         Object *object_eval = DEG_get_evaluated_object(depsgraph, base->object);
1562         lb_duplis = object_duplilist(depsgraph, scene, object_eval);
1563
1564         dupli_gh = BLI_ghash_ptr_new(__func__);
1565         if (use_hierarchy) {
1566                 if (base->object->transflag & OB_DUPLICOLLECTION) {
1567                         parent_gh = BLI_ghash_new(dupliobject_group_hash, dupliobject_group_cmp, __func__);
1568                 }
1569                 else {
1570                         parent_gh = BLI_ghash_new(dupliobject_hash, dupliobject_cmp, __func__);
1571                 }
1572         }
1573
1574         for (dob = lb_duplis->first; dob; dob = dob->next) {
1575                 Object *ob_src = DEG_get_original_object(dob->ob);
1576                 Object *ob_dst = ID_NEW_SET(dob->ob, BKE_object_copy(bmain, ob_src));
1577                 Base *base_dst;
1578
1579                 /* font duplis can have a totcol without material, we get them from parent
1580                  * should be implemented better...
1581                  */
1582                 if (ob_dst->mat == NULL) {
1583                         ob_dst->totcol = 0;
1584                 }
1585
1586                 BKE_collection_object_add_from(bmain, scene, base->object, ob_dst);
1587                 base_dst = BKE_view_layer_base_find(view_layer, ob_dst);
1588                 BLI_assert(base_dst != NULL);
1589
1590                 BKE_scene_object_base_flag_sync_from_base(base_dst);
1591
1592                 /* make sure apply works */
1593                 BKE_animdata_free(&ob_dst->id, true);
1594                 ob_dst->adt = NULL;
1595
1596                 /* Proxies are not to be copied. */
1597                 ob_dst->proxy_from = NULL;
1598                 ob_dst->proxy_group = NULL;
1599                 ob_dst->proxy = NULL;
1600
1601                 ob_dst->parent = NULL;
1602                 BKE_constraints_free(&ob_dst->constraints);
1603                 ob_dst->runtime.curve_cache = NULL;
1604                 ob_dst->transflag &= ~OB_DUPLI;
1605
1606                 copy_m4_m4(ob_dst->obmat, dob->mat);
1607                 BKE_object_apply_mat4(ob_dst, ob_dst->obmat, false, false);
1608
1609                 BLI_ghash_insert(dupli_gh, dob, ob_dst);
1610                 if (parent_gh) {
1611                         void **val;
1612                         /* Due to nature of hash/comparison of this ghash, a lot of duplis may be considered as
1613                          * 'the same', this avoids trying to insert same key several time and
1614                          * raise asserts in debug builds... */
1615                         if (!BLI_ghash_ensure_p(parent_gh, dob, &val)) {
1616                                 *val = ob_dst;
1617                         }
1618                 }
1619         }
1620
1621         for (dob = lb_duplis->first; dob; dob = dob->next) {
1622                 Object *ob_src = dob->ob;
1623                 Object *ob_dst = BLI_ghash_lookup(dupli_gh, dob);
1624
1625                 /* Remap new object to itself, and clear again newid pointer of orig object. */
1626                 BKE_libblock_relink_to_newid(&ob_dst->id);
1627
1628                 DEG_id_tag_update(&ob_dst->id, ID_RECALC_GEOMETRY);
1629
1630                 if (use_hierarchy) {
1631                         /* original parents */
1632                         Object *ob_src_par = ob_src->parent;
1633                         Object *ob_dst_par = NULL;
1634
1635                         /* find parent that was also made real */
1636                         if (ob_src_par) {
1637                                 /* OK to keep most of the members uninitialized,
1638                                  * they won't be read, this is simply for a hash lookup. */
1639                                 DupliObject dob_key;
1640                                 dob_key.ob = ob_src_par;
1641                                 if (base->object->transflag & OB_DUPLICOLLECTION) {
1642                                         memcpy(&dob_key.persistent_id[1],
1643                                                &dob->persistent_id[1],
1644                                                sizeof(dob->persistent_id[1]) * (MAX_DUPLI_RECUR - 1));
1645                                 }
1646                                 else {
1647                                         dob_key.persistent_id[0] = dob->persistent_id[0];
1648                                 }
1649                                 ob_dst_par = BLI_ghash_lookup(parent_gh, &dob_key);
1650                         }
1651
1652                         if (ob_dst_par) {
1653                                 /* allow for all possible parent types */
1654                                 ob_dst->partype = ob_src->partype;
1655                                 BLI_strncpy(ob_dst->parsubstr, ob_src->parsubstr, sizeof(ob_dst->parsubstr));
1656                                 ob_dst->par1 = ob_src->par1;
1657                                 ob_dst->par2 = ob_src->par2;
1658                                 ob_dst->par3 = ob_src->par3;
1659
1660                                 copy_m4_m4(ob_dst->parentinv, ob_src->parentinv);
1661
1662                                 ob_dst->parent = ob_dst_par;
1663                         }
1664                         else if (use_base_parent) {
1665                                 ob_dst->parent = base->object;
1666                                 ob_dst->partype = PAROBJECT;
1667                         }
1668                 }
1669                 else if (use_base_parent) {
1670                         /* since we are ignoring the internal hierarchy - parent all to the
1671                          * base object */
1672                         ob_dst->parent = base->object;
1673                         ob_dst->partype = PAROBJECT;
1674                 }
1675
1676                 if (ob_dst->parent) {
1677                         /* note, this may be the parent of other objects, but it should
1678                          * still work out ok */
1679                         BKE_object_apply_mat4(ob_dst, dob->mat, false, true);
1680
1681                         /* to set ob_dst->orig and in case there's any other discrepancies */
1682                         DEG_id_tag_update(&ob_dst->id, ID_RECALC_TRANSFORM);
1683                 }
1684         }
1685
1686         if (base->object->transflag & OB_DUPLICOLLECTION && base->object->instance_collection) {
1687                 for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
1688                         if (ob->proxy_group == base->object) {
1689                                 ob->proxy = NULL;
1690                                 ob->proxy_from = NULL;
1691                                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM);
1692                         }
1693                 }
1694         }
1695
1696         BLI_ghash_free(dupli_gh, NULL, NULL);
1697         if (parent_gh) {
1698                 BLI_ghash_free(parent_gh, NULL, NULL);
1699         }
1700
1701         free_object_duplilist(lb_duplis);
1702
1703         BKE_main_id_clear_newpoins(bmain);
1704
1705         base->object->transflag &= ~OB_DUPLI;
1706         DEG_id_tag_update(&base->object->id, ID_RECALC_COPY_ON_WRITE);
1707 }
1708
1709 static int object_duplicates_make_real_exec(bContext *C, wmOperator *op)
1710 {
1711         Main *bmain = CTX_data_main(C);
1712         Scene *scene = CTX_data_scene(C);
1713
1714         const bool use_base_parent = RNA_boolean_get(op->ptr, "use_base_parent");
1715         const bool use_hierarchy = RNA_boolean_get(op->ptr, "use_hierarchy");
1716
1717         BKE_main_id_clear_newpoins(bmain);
1718
1719         CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
1720         {
1721                 make_object_duplilist_real(C, scene, base, use_base_parent, use_hierarchy);
1722
1723                 /* dependencies were changed */
1724                 WM_event_add_notifier(C, NC_OBJECT | ND_PARENT, base->object);
1725         }
1726         CTX_DATA_END;
1727
1728         DEG_relations_tag_update(bmain);
1729         WM_event_add_notifier(C, NC_SCENE, scene);
1730         WM_main_add_notifier(NC_OBJECT | ND_DRAW, NULL);
1731
1732         return OPERATOR_FINISHED;
1733 }
1734
1735 void OBJECT_OT_duplicates_make_real(wmOperatorType *ot)
1736 {
1737         /* identifiers */
1738         ot->name = "Make Duplicates Real";
1739         ot->description = "Make dupli objects attached to this object real";
1740         ot->idname = "OBJECT_OT_duplicates_make_real";
1741
1742         /* api callbacks */
1743         ot->exec = object_duplicates_make_real_exec;
1744
1745         ot->poll = ED_operator_objectmode;
1746
1747         /* flags */
1748         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_USE_EVAL_DATA;
1749
1750         RNA_def_boolean(ot->srna, "use_base_parent", 0, "Parent", "Parent newly created objects to the original duplicator");
1751         RNA_def_boolean(ot->srna, "use_hierarchy", 0, "Keep Hierarchy", "Maintain parent child relationships");
1752 }
1753
1754 /**************************** Convert **************************/
1755
1756 static const EnumPropertyItem convert_target_items[] = {
1757         {OB_CURVE, "CURVE", ICON_OUTLINER_OB_CURVE, "Curve from Mesh/Text", ""},
1758         {OB_MESH, "MESH", ICON_OUTLINER_OB_MESH, "Mesh from Curve/Meta/Surf/Text", ""},
1759         {0, NULL, 0, NULL, NULL},
1760 };
1761
1762 static void convert_ensure_curve_cache(Depsgraph *depsgraph, Scene *scene, Object *ob)
1763 {
1764         if (ob->runtime.curve_cache == NULL) {
1765                 /* Force creation. This is normally not needed but on operator
1766                  * redo we might end up with an object which isn't evaluated yet.
1767                  * Also happens in case we are working on a copy of the object (all its caches have been nuked then).
1768                  */
1769                 if (ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) {
1770                         /* We need 'for render' ON here, to enable computing bevel dipslist if needed.
1771                          * Also makes sense anyway, we would not want e.g. to loose hidden parts etc. */
1772                         BKE_displist_make_curveTypes(depsgraph, scene, ob, true, false, NULL);
1773                 }
1774                 else if (ob->type == OB_MBALL) {
1775                         BKE_displist_make_mball(depsgraph, scene, ob);
1776                 }
1777         }
1778 }
1779
1780 static void curvetomesh(Main *bmain, Depsgraph *depsgraph, Scene *scene, Object *ob)
1781 {
1782         convert_ensure_curve_cache(depsgraph, scene, ob);
1783         BKE_mesh_from_nurbs(bmain, ob); /* also does users */
1784
1785         if (ob->type == OB_MESH) {
1786                 BKE_object_free_modifiers(ob, 0);
1787         }
1788 }
1789
1790 static bool convert_poll(bContext *C)
1791 {
1792         Scene *scene = CTX_data_scene(C);
1793         Base *base_act = CTX_data_active_base(C);
1794         Object *obact = base_act ? base_act->object : NULL;
1795
1796         return (!ID_IS_LINKED(scene) && obact && (BKE_object_is_in_editmode(obact) == false) &&
1797                 (base_act->flag & BASE_SELECTED) && !ID_IS_LINKED(obact));
1798 }
1799
1800 /* Helper for convert_exec */
1801 static Base *duplibase_for_convert(Main *bmain, Scene *scene, ViewLayer *view_layer, Base *base, Object *ob)
1802 {
1803         Object *obn;
1804         Base *basen;
1805
1806         if (ob == NULL) {
1807                 ob = base->object;
1808         }
1809
1810         obn = BKE_object_copy(bmain, ob);
1811         DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1812         BKE_collection_object_add_from(bmain, scene, ob, obn);
1813
1814         basen = BKE_view_layer_base_find(view_layer, obn);
1815         ED_object_base_select(basen, BA_SELECT);
1816         ED_object_base_select(basen, BA_DESELECT);
1817         return basen;
1818 }
1819
1820 static int convert_exec(bContext *C, wmOperator *op)
1821 {
1822         Main *bmain = CTX_data_main(C);
1823         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1824         Scene *scene = CTX_data_scene(C);
1825         ViewLayer *view_layer = CTX_data_view_layer(C);
1826         Base *basen = NULL, *basact = NULL;
1827         Object *ob1, *obact = CTX_data_active_object(C);
1828         Curve *cu;
1829         Nurb *nu;
1830         MetaBall *mb;
1831         Mesh *me;
1832         const short target = RNA_enum_get(op->ptr, "target");
1833         bool keep_original = RNA_boolean_get(op->ptr, "keep_original");
1834         int a, mballConverted = 0;
1835
1836         /* don't forget multiple users! */
1837
1838         {
1839                 FOREACH_SCENE_OBJECT_BEGIN(scene, ob)
1840                 {
1841                         ob->flag &= ~OB_DONE;
1842
1843                         /* flag data that's not been edited (only needed for !keep_original) */
1844                         if (ob->data) {
1845                                 ((ID *)ob->data)->tag |= LIB_TAG_DOIT;
1846                         }
1847
1848                         /* possible metaball basis is not in this scene */
1849                         if (ob->type == OB_MBALL && target == OB_MESH) {
1850                                 if (BKE_mball_is_basis(ob) == false) {
1851                                         Object *ob_basis;
1852                                         ob_basis = BKE_mball_basis_find(scene, ob);
1853                                         if (ob_basis) {
1854                                                 ob_basis->flag &= ~OB_DONE;
1855                                         }
1856                                 }
1857                         }
1858                 }
1859                 FOREACH_SCENE_OBJECT_END;
1860         }
1861
1862         ListBase selected_editable_bases = CTX_data_collection_get(C, "selected_editable_bases");
1863
1864         /* Ensure we get all meshes calculated with a sufficient data-mask,
1865          * needed since re-evaluating single modifiers causes bugs if they depend
1866          * on other objects data masks too, see: T50950. */
1867         {
1868                 for (CollectionPointerLink *link = selected_editable_bases.first; link; link = link->next) {
1869                         Base *base = link->ptr.data;
1870                         Object *ob = base->object;
1871
1872                         /* The way object type conversion works currently (enforcing conversion of *all* objects using converted
1873                          * object-data, even some un-selected/hidden/another scene ones, sounds totally bad to me.
1874                          * However, changing this is more design than bug-fix, not to mention convoluted code below,
1875                          * so that will be for later.
1876                          * But at the very least, do not do that with linked IDs! */
1877                         if ((ID_IS_LINKED(ob) || (ob->data && ID_IS_LINKED(ob->data))) && !keep_original) {
1878                                 keep_original = true;
1879                                 BKE_reportf(op->reports, RPT_INFO,
1880                                             "Converting some linked object/object data, enforcing 'Keep Original' option to True");
1881                         }
1882
1883                         DEG_id_tag_update(&base->object->id, ID_RECALC_GEOMETRY);
1884                 }
1885
1886                 uint64_t customdata_mask_prev = scene->customdata_mask;
1887                 scene->customdata_mask |= CD_MASK_MESH;
1888                 BKE_scene_graph_update_tagged(depsgraph, bmain);
1889                 scene->customdata_mask = customdata_mask_prev;
1890         }
1891
1892         for (CollectionPointerLink *link = selected_editable_bases.first; link; link = link->next) {
1893                 Object *newob = NULL;
1894                 Base *base = link->ptr.data;
1895                 Object *ob = base->object;
1896
1897                 if (ob->flag & OB_DONE || !IS_TAGGED(ob->data)) {
1898                         if (ob->type != target) {
1899                                 base->flag &= ~SELECT;
1900                                 ob->flag &= ~SELECT;
1901                         }
1902
1903                         /* obdata already modified */
1904                         if (!IS_TAGGED(ob->data)) {
1905                                 /* When 2 objects with linked data are selected, converting both
1906                                  * would keep modifiers on all but the converted object [#26003] */
1907                                 if (ob->type == OB_MESH) {
1908                                         BKE_object_free_modifiers(ob, 0);  /* after derivedmesh calls! */
1909                                 }
1910                                 if (ob->type == OB_GPENCIL) {
1911                                         BKE_object_free_modifiers(ob, 0);  /* after derivedmesh calls! */
1912                                         BKE_object_free_shaderfx(ob, 0);
1913                                 }
1914                         }
1915                 }
1916                 else if (ob->type == OB_MESH && target == OB_CURVE) {
1917                         ob->flag |= OB_DONE;
1918
1919                         if (keep_original) {
1920                                 basen = duplibase_for_convert(bmain, scene, view_layer, base, NULL);
1921                                 newob = basen->object;
1922
1923                                 /* decrement original mesh's usage count  */
1924                                 me = newob->data;
1925                                 id_us_min(&me->id);
1926
1927                                 /* make a new copy of the mesh */
1928                                 newob->data = BKE_mesh_copy(bmain, me);
1929                         }
1930                         else {
1931                                 newob = ob;
1932                         }
1933
1934                         BKE_mesh_to_curve(bmain, depsgraph, scene, newob);
1935
1936                         if (newob->type == OB_CURVE) {
1937                                 BKE_object_free_modifiers(newob, 0);   /* after derivedmesh calls! */
1938                                 ED_rigidbody_object_remove(bmain, scene, newob);
1939                         }
1940                 }
1941                 else if (ob->type == OB_MESH) {
1942                         ob->flag |= OB_DONE;
1943
1944                         if (keep_original) {
1945                                 basen = duplibase_for_convert(bmain, scene, view_layer, base, NULL);
1946                                 newob = basen->object;
1947
1948                                 /* decrement original mesh's usage count  */
1949                                 me = newob->data;
1950                                 id_us_min(&me->id);
1951
1952                                 /* make a new copy of the mesh */
1953                                 newob->data = BKE_mesh_copy(bmain, me);
1954                         }
1955                         else {
1956                                 newob = ob;
1957                                 DEG_id_tag_update(&ob->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
1958                         }
1959
1960                         /* make new mesh data from the original copy */
1961                         /* note: get the mesh from the original, not from the copy in some
1962                          * cases this doesn't give correct results (when MDEF is used for eg)
1963                          */
1964                         Scene *scene_eval = (Scene *)DEG_get_evaluated_id(depsgraph, &scene->id);
1965                         Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob);
1966                         Mesh *me_eval = mesh_get_eval_final(depsgraph, scene_eval, ob_eval, CD_MASK_MESH);
1967                         me_eval = BKE_mesh_copy_for_eval(me_eval, false);
1968                         BKE_mesh_nomain_to_mesh(me_eval, newob->data, newob, CD_MASK_MESH, true);
1969                         BKE_object_free_modifiers(newob, 0);   /* after derivedmesh calls! */
1970                 }
1971                 else if (ob->type == OB_FONT) {
1972                         ob->flag |= OB_DONE;
1973
1974                         if (keep_original) {
1975                                 basen = duplibase_for_convert(bmain, scene, view_layer, base, NULL);
1976                                 newob = basen->object;
1977
1978                                 /* decrement original curve's usage count  */
1979                                 id_us_min(&((Curve *)newob->data)->id);
1980
1981                                 /* make a new copy of the curve */
1982                                 newob->data = BKE_curve_copy(bmain, ob->data);
1983                         }
1984                         else {
1985                                 newob = ob;
1986                         }
1987
1988                         cu = newob->data;
1989
1990                         /* TODO(sergey): Ideally DAG will create nurbs list for a curve data
1991                          *               datablock, but for until we've got granular update
1992                          *               lets take care by selves.
1993                          */
1994                         /* XXX This may fail/crash, since BKE_vfont_to_curve()
1995                          * accesses evaluated data in some cases (bastien). */
1996                         BKE_vfont_to_curve(newob, FO_EDIT);
1997
1998                         newob->type = OB_CURVE;
1999                         cu->type = OB_CURVE;
2000
2001                         if (cu->vfont) {
2002                                 id_us_min(&cu->vfont->id);
2003                                 cu->vfont = NULL;
2004                         }
2005                         if (cu->vfontb) {
2006                                 id_us_min(&cu->vfontb->id);
2007                                 cu->vfontb = NULL;
2008                         }
2009                         if (cu->vfonti) {
2010                                 id_us_min(&cu->vfonti->id);
2011                                 cu->vfonti = NULL;
2012                         }
2013                         if (cu->vfontbi) {
2014                                 id_us_min(&cu->vfontbi->id);
2015                                 cu->vfontbi = NULL;
2016                         }
2017
2018                         if (!keep_original) {
2019                                 /* other users */
2020                                 if (cu->id.us > 1) {
2021                                         for (ob1 = bmain->object.first; ob1; ob1 = ob1->id.next) {
2022                                                 if (ob1->data == ob->data) {
2023                                                         ob1->type = OB_CURVE;
2024                                                         DEG_id_tag_update(&ob1->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_ANIMATION);
2025                                                 }
2026                                         }
2027                                 }
2028                         }
2029
2030                         for (nu = cu->nurb.first; nu; nu = nu->next)
2031                                 nu->charidx = 0;
2032
2033                         cu->flag &= ~CU_3D;
2034                         BKE_curve_curve_dimension_update(cu);
2035
2036                         if (target == OB_MESH) {
2037                                 curvetomesh(bmain, depsgraph, scene, newob);
2038
2039                                 /* meshes doesn't use displist */
2040                                 BKE_object_free_curve_cache(newob);
2041                         }
2042                 }
2043                 else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
2044                         ob->flag |= OB_DONE;
2045
2046                         if (target == OB_MESH) {
2047                                 if (keep_original) {
2048                                         basen = duplibase_for_convert(bmain, scene, view_layer, base, NULL);
2049                                         newob = basen->object;
2050
2051                                         /* decrement original curve's usage count  */
2052                                         id_us_min(&((Curve *)newob->data)->id);
2053
2054                                         /* make a new copy of the curve */
2055                                         newob->data = BKE_curve_copy(bmain, ob->data);
2056                                 }
2057                                 else {
2058                                         newob = ob;
2059                                 }
2060
2061                                 curvetomesh(bmain, depsgraph, scene, newob);
2062
2063                                 /* meshes doesn't use displist */
2064                                 BKE_object_free_curve_cache(newob);
2065                         }
2066                 }
2067                 else if (ob->type == OB_MBALL && target == OB_MESH) {
2068                         Object *baseob;
2069
2070                         base->flag &= ~BASE_SELECTED;
2071                         ob->base_flag &= ~BASE_SELECTED;
2072
2073                         baseob = BKE_mball_basis_find(scene, ob);
2074
2075                         if (ob != baseob) {
2076                                 /* if motherball is converting it would be marked as done later */
2077                                 ob->flag |= OB_DONE;
2078                         }
2079
2080                         if (!(baseob->flag & OB_DONE)) {
2081                                 baseob->flag |= OB_DONE;
2082
2083                                 basen = duplibase_for_convert(bmain, scene, view_layer, base, baseob);
2084                                 newob = basen->object;
2085
2086                                 mb = newob->data;
2087                                 id_us_min(&mb->id);
2088
2089                                 newob->data = BKE_mesh_add(bmain, "Mesh");
2090                                 newob->type = OB_MESH;
2091
2092                                 me = newob->data;
2093                                 me->totcol = mb->totcol;
2094                                 if (newob->totcol) {
2095                                         me->mat = MEM_dupallocN(mb->mat);
2096                                         for (a = 0; a < newob->totcol; a++) id_us_plus((ID *)me->mat[a]);
2097                                 }
2098
2099                                 convert_ensure_curve_cache(depsgraph, scene, baseob);
2100                                 BKE_mesh_from_metaball(&baseob->runtime.curve_cache->disp, newob->data);
2101
2102                                 if (obact->type == OB_MBALL) {
2103                                         basact = basen;
2104                                 }
2105
2106                                 mballConverted = 1;
2107                         }
2108                 }
2109                 else {
2110                         continue;
2111                 }
2112
2113                 /* Ensure new object has consistent material data with its new obdata. */
2114                 if (newob) {
2115                         test_object_materials(bmain, newob, newob->data);
2116                 }
2117
2118                 /* tag obdata if it was been changed */
2119
2120                 /* If the original object is active then make this object active */
2121                 if (basen) {
2122                         if (ob == obact) {
2123                                 /* store new active base to update BASACT */
2124                                 basact = basen;
2125                         }
2126
2127                         basen = NULL;
2128                 }
2129
2130                 if (!keep_original && (ob->flag & OB_DONE)) {
2131                         DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY);
2132                         ((ID *)ob->data)->tag &= ~LIB_TAG_DOIT; /* flag not to convert this datablock again */
2133                 }
2134         }
2135         BLI_freelistN(&selected_editable_bases);
2136
2137         if (!keep_original) {
2138                 if (mballConverted) {
2139                         FOREACH_SCENE_OBJECT_BEGIN(scene, ob_mball)
2140                         {
2141                                 if (ob_mball->type == OB_MBALL) {
2142                                         if (ob_mball->flag & OB_DONE) {
2143                                                 Object *ob_basis = NULL;
2144                                                 if (BKE_mball_is_basis(ob_mball) ||
2145                                                     ((ob_basis = BKE_mball_basis_find(scene, ob_mball)) && (ob_basis->flag & OB_DONE)))
2146                                                 {
2147                                                         ED_object_base_free_and_unlink(bmain, scene, ob_mball);
2148                                                 }
2149                                         }
2150                                 }
2151                         }
2152                         FOREACH_SCENE_OBJECT_END;
2153                 }
2154         }
2155
2156 // XXX  ED_object_editmode_enter(C, 0);
2157 // XXX  exit_editmode(C, EM_FREEDATA|); /* freedata, but no undo */
2158
2159         if (basact) {
2160                 /* active base was changed */
2161                 ED_object_base_activate(C, basact);
2162                 BASACT(view_layer) = basact;
2163         }
2164         else if (BASACT(view_layer)->object->flag & OB_DONE) {
2165                 WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, BASACT(view_layer)->object);
2166                 WM_event_add_notifier(C, NC_OBJECT | ND_DATA, BASACT(view_layer)->object);
2167         }
2168
2169         DEG_relations_tag_update(bmain);
2170         DEG_id_tag_update(&scene->id, ID_RECALC_SELECT);
2171         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, scene);
2172         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
2173
2174         return OPERATOR_FINISHED;
2175 }
2176
2177
2178 void OBJECT_OT_convert(wmOperatorType *ot)
2179 {
2180         /* identifiers */
2181         ot->name = "Convert to";
2182         ot->description = "Convert selected objects to another type";
2183         ot->idname = "OBJECT_OT_convert";
2184
2185         /* api callbacks */
2186         ot->invoke = WM_menu_invoke;
2187         ot->exec = convert_exec;
2188         ot->poll = convert_poll;
2189
2190         /* flags */
2191         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2192
2193         /* properties */
2194         ot->prop = RNA_def_enum(ot->srna, "target", convert_target_items, OB_MESH, "Target", "Type of object to convert to");
2195         RNA_def_boolean(ot->srna, "keep_original", 0, "Keep Original", "Keep original objects instead of replacing them");
2196 }
2197
2198 /**************************** Duplicate ************************/
2199
2200 /*
2201  * dupflag: a flag made from constants declared in DNA_userdef_types.h
2202  * The flag tells adduplicate() whether to copy data linked to the object, or to reference the existing data.
2203  * U.dupflag for default operations or you can construct a flag as python does
2204  * if the dupflag is 0 then no data will be copied (linked duplicate) */
2205
2206 /* used below, assumes id.new is correct */
2207 /* leaves selection of base/object unaltered */
2208 /* Does set ID->newid pointers. */
2209 static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, ViewLayer *view_layer, Object *ob, int dupflag)
2210 {
2211 #define ID_NEW_REMAP_US(a)      if (      (a)->id.newid) { (a) = (void *)(a)->id.newid;       (a)->id.us++; }
2212 #define ID_NEW_REMAP_US2(a)     if (((ID *)a)->newid)    { (a) = ((ID  *)a)->newid;     ((ID *)a)->us++;    }
2213
2214         Base *base, *basen = NULL;
2215         Material ***matarar;
2216         Object *obn;
2217         ID *id;
2218         int a, didit;
2219
2220         if (ob->mode & OB_MODE_POSE) {
2221                 ; /* nothing? */
2222         }
2223         else {
2224                 obn = ID_NEW_SET(ob, BKE_object_copy(bmain, ob));
2225                 DEG_id_tag_update(&obn->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
2226
2227                 base = BKE_view_layer_base_find(view_layer, ob);
2228                 if ((base != NULL) && (base->flag & BASE_VISIBLE)) {
2229                         BKE_collection_object_add_from(bmain, scene, ob, obn);
2230                 }
2231                 else {
2232                         LayerCollection *layer_collection = BKE_layer_collection_get_active(view_layer);
2233                         BKE_collection_object_add(bmain, layer_collection->collection, obn);
2234                 }
2235
2236                 basen = BKE_view_layer_base_find(view_layer, obn);
2237                 if (base != NULL) {
2238                         basen->local_view_bits = base->local_view_bits;
2239                 }
2240
2241                 /* 1) duplis should end up in same collection as the original
2242                  * 2) Rigid Body sim participants MUST always be part of a collection...
2243                  */
2244                 // XXX: is 2) really a good measure here?
2245                 if (ob->rigidbody_object || ob->rigidbody_constraint) {
2246                         Collection *collection;
2247                         for (collection = bmain->collection.first; collection; collection = collection->id.next) {
2248                                 if (BKE_collection_has_object(collection, ob))
2249                                         BKE_collection_object_add(bmain, collection, obn);
2250                         }
2251                 }
2252
2253                 /* duplicates using userflags */
2254                 if (dupflag & USER_DUP_ACT) {
2255                         BKE_animdata_copy_id_action(bmain, &obn->id, true);
2256                 }
2257
2258                 if (dupflag & USER_DUP_MAT) {
2259                         for (a = 0; a < obn->totcol; a++) {
2260                                 id = (ID *)obn->mat[a];
2261                                 if (id) {
2262                                         ID_NEW_REMAP_US(obn->mat[a])
2263                                         else {
2264                                                 obn->mat[a] = ID_NEW_SET(obn->mat[a], BKE_material_copy(bmain, obn->mat[a]));
2265                                         }
2266                                         id_us_min(id);
2267
2268                                         if (dupflag & USER_DUP_ACT) {
2269                                                 BKE_animdata_copy_id_action(bmain, &obn->mat[a]->id, true);
2270                                         }
2271                                 }
2272                         }
2273                 }
2274                 if (dupflag & USER_DUP_PSYS) {
2275                         ParticleSystem *psys;
2276                         for (psys = obn->particlesystem.first; psys; psys = psys->next) {
2277                                 id = (ID *) psys->part;
2278                                 if (id) {
2279                                         ID_NEW_REMAP_US(psys->part)
2280                                         else {
2281                                                 psys->part = ID_NEW_SET(psys->part, BKE_particlesettings_copy(bmain, psys->part));
2282                                         }
2283
2284                                         if (dupflag & USER_DUP_ACT) {
2285                                                 BKE_animdata_copy_id_action(bmain, &psys->part->id, true);
2286                                         }
2287
2288                                         id_us_min(id);
2289                                 }
2290                         }
2291                 }
2292
2293                 id = obn->data;
2294                 didit = 0;
2295
2296                 switch (obn->type) {
2297                         case OB_MESH:
2298                                 if (dupflag & USER_DUP_MESH) {
2299                                         ID_NEW_REMAP_US2(obn->data)
2300                                         else {
2301                                                 obn->data = ID_NEW_SET(obn->data, BKE_mesh_copy(bmain, obn->data));
2302                                                 didit = 1;
2303                                         }
2304                                         id_us_min(id);
2305                                 }
2306                                 break;
2307                         case OB_CURVE:
2308                                 if (dupflag & USER_DUP_CURVE) {
2309                                         ID_NEW_REMAP_US2(obn->data)
2310                                         else {
2311                                                 obn->data = ID_NEW_SET(obn->data, BKE_curve_copy(bmain, obn->data));
2312                                                 didit = 1;
2313                                         }
2314                                         id_us_min(id);
2315                                 }
2316                                 break;
2317                         case OB_SURF:
2318                                 if (dupflag & USER_DUP_SURF) {
2319                                         ID_NEW_REMAP_US2(obn->data)
2320                                         else {
2321                                                 obn->data = ID_NEW_SET(obn->data, BKE_curve_copy(bmain, obn->data));
2322                                                 didit = 1;
2323                                         }
2324                                         id_us_min(id);
2325                                 }
2326                                 break;
2327                         case OB_FONT:
2328                                 if (dupflag & USER_DUP_FONT) {
2329                                         ID_NEW_REMAP_US2(obn->data)
2330                                         else {
2331                                                 obn->data = ID_NEW_SET(obn->data, BKE_curve_copy(bmain, obn->data));
2332                                                 didit = 1;
2333                                         }
2334                                         id_us_min(id);
2335                                 }
2336                                 break;
2337                         case OB_MBALL:
2338                                 if (dupflag & USER_DUP_MBALL) {
2339                                         ID_NEW_REMAP_US2(obn->data)
2340                                         else {
2341                                                 obn->data = ID_NEW_SET(obn->data, BKE_mball_copy(bmain, obn->data));
2342                                                 didit = 1;
2343                                         }
2344                                         id_us_min(id);
2345                                 }
2346                                 break;
2347                         case OB_LAMP:
2348                                 if (dupflag & USER_DUP_LAMP) {
2349                                         ID_NEW_REMAP_US2(obn->data)
2350                                         else {
2351                                                 obn->data = ID_NEW_SET(obn->data, BKE_light_copy(bmain, obn->data));
2352                                                 didit = 1;
2353                                         }
2354                                         id_us_min(id);
2355                                 }
2356                                 break;
2357                         case OB_ARMATURE:
2358                                 DEG_id_tag_update(&obn->id, ID_RECALC_GEOMETRY);
2359                                 if (obn->pose)
2360                                         BKE_pose_tag_recalc(bmain, obn->pose);
2361                                 if (dupflag & USER_DUP_ARM) {
2362                                         ID_NEW_REMAP_US2(obn->data)
2363                                         else {
2364                                                 obn->data = ID_NEW_SET(obn->data, BKE_armature_copy(bmain, obn->data));
2365                                                 BKE_pose_rebuild(bmain, obn, obn->data, true);
2366                                                 didit = 1;
2367                                         }
2368                                         id_us_min(id);
2369                                 }
2370                                 break;
2371                         case OB_LATTICE:
2372                                 if (dupflag != 0) {
2373                                         ID_NEW_REMAP_US2(obn->data)
2374                                         else {
2375                                                 obn->data = ID_NEW_SET(obn->data, BKE_lattice_copy(bmain, obn->data));
2376                                                 didit = 1;
2377                                         }
2378                                         id_us_min(id);
2379                                 }
2380                                 break;
2381                         case OB_CAMERA:
2382                                 if (dupflag != 0) {
2383                                         ID_NEW_REMAP_US2(obn->data)
2384                                         else {
2385                                                 obn->data = ID_NEW_SET(obn->data, BKE_camera_copy(bmain, obn->data));
2386                                                 didit = 1;
2387                                         }
2388                                         id_us_min(id);
2389                                 }
2390                                 break;
2391                         case OB_LIGHTPROBE:
2392                                 if (dupflag != 0) {
2393                                         ID_NEW_REMAP_US2(obn->data)
2394                                         else {
2395                                                 obn->data = ID_NEW_SET(obn->data, BKE_lightprobe_copy(bmain, obn->data));
2396                                                 didit = 1;
2397                                         }
2398                                         id_us_min(id);
2399                                 }
2400                                 break;
2401                         case OB_SPEAKER:
2402                                 if (dupflag != 0) {
2403                                         ID_NEW_REMAP_US2(obn->data)
2404                                         else {
2405                                                 obn->data = ID_NEW_SET(obn->data, BKE_speaker_copy(bmain, obn->data));
2406                                                 didit = 1;
2407                                         }
2408                                         id_us_min(id);
2409                                 }
2410                                 break;
2411                         case OB_GPENCIL:
2412                                 if (dupflag != 0) {
2413                                         ID_NEW_REMAP_US2(obn->data)
2414                                         else {
2415                                                 obn->data = ID_NEW_SET(obn->data, BKE_gpencil_copy(bmain, obn->data));
2416                                                 didit = 1;
2417                                         }
2418                                         id_us_min(id);
2419                                 }
2420                                 break;
2421                 }
2422
2423                 /* check if obdata is copied */
2424                 if (didit) {
2425                         Key *key = BKE_key_from_object(obn);
2426
2427                         Key *oldkey = BKE_key_from_object(ob);
2428                         if (oldkey != NULL) {
2429                                 ID_NEW_SET(oldkey, key);
2430                         }
2431
2432                         if (dupflag & USER_DUP_ACT) {
2433                                 BKE_animdata_copy_id_action(bmain, (ID *)obn->data, true);
2434                                 if (key) {
2435                                         BKE_animdata_copy_id_action(bmain, (ID *)key, true);
2436                                 }
2437                         }
2438
2439                         if (dupflag & USER_DUP_MAT) {
2440                                 matarar = give_matarar(obn);
2441                                 if (matarar) {
2442                                         for (a = 0; a < obn->totcol; a++) {
2443                                                 id = (ID *)(*matarar)[a];
2444                                                 if (id) {
2445                                                         ID_NEW_REMAP_US((*matarar)[a])
2446                                                         else {
2447                                                                 (*matarar)[a] = ID_NEW_SET((*matarar)[a], BKE_material_copy(bmain, (*matarar)[a]));
2448                                                         }
2449                                                         id_us_min(id);
2450                                                 }
2451                                         }
2452                                 }
2453                         }
2454                 }
2455         }
2456         return basen;
2457
2458 #undef ID_NEW_REMAP_US
2459 #undef ID_NEW_REMAP_US2
2460 }
2461
2462 /* single object duplicate, if dupflag==0, fully linked, else it uses the flags given */
2463 /* leaves selection of base/object unaltered.
2464  * note: don't call this within a loop since clear_* funcs loop over the entire database.
2465  * note: caller must do DAG_relations_tag_update(bmain);
2466  *       this is not done automatic since we may duplicate many objects in a batch */
2467 Base *ED_object_add_duplicate(Main *bmain, Scene *scene, ViewLayer *view_layer, Base *base, int dupflag)
2468 {
2469         Base *basen;
2470         Object *ob;
2471
2472         basen = object_add_duplicate_internal(bmain, scene, view_layer, base->object, dupflag);
2473         if (basen == NULL) {
2474                 return NULL;
2475         }
2476
2477         ob = basen->object;
2478
2479         /* link own references to the newly duplicated data [#26816] */
2480         BKE_libblock_relink_to_newid(&ob->id);
2481
2482         /* DAG_relations_tag_update(bmain); */ /* caller must do */
2483
2484         if (ob->data != NULL) {
2485                 DEG_id_tag_update_ex(bmain, (ID *)ob->data, ID_RECALC_EDITORS);
2486         }
2487
2488         BKE_main_id_clear_newpoins(bmain);
2489
2490         return basen;
2491 }
2492
2493 /* contextual operator dupli */
2494 static int duplicate_exec(bContext *C, wmOperator *op)
2495 {
2496         Main *bmain = CTX_data_main(C);
2497         Scene *scene = CTX_data_scene(C);
2498         ViewLayer *view_layer = CTX_data_view_layer(C);
2499         const bool linked = RNA_boolean_get(op->ptr, "linked");
2500         int dupflag = (linked) ? 0 : U.dupflag;
2501
2502         CTX_DATA_BEGIN (C, Base *, base, selected_bases)
2503         {
2504                 Base *basen = object_add_duplicate_internal(bmain, scene, view_layer, base->object, dupflag);
2505
2506                 /* note that this is safe to do with this context iterator,
2507                  * the list is made in advance */
2508                 ED_object_base_select(base, BA_DESELECT);
2509                 ED_object_base_select(basen, BA_SELECT);
2510
2511                 if (basen == NULL) {
2512                         continue;
2513                 }
2514
2515                 /* new object becomes active */
2516                 if (BASACT(view_layer) == base)
2517                         ED_object_base_activate(C, basen);
2518
2519                 if (basen->object->data) {
2520                         DEG_id_tag_update(basen->object->data, 0);
2521                 }
2522         }
2523         CTX_DATA_END;
2524
2525         copy_object_set_idnew(C);
2526
2527         DEG_relations_tag_update(bmain);
2528         DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE | ID_RECALC_SELECT);
2529
2530         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
2531
2532         return OPERATOR_FINISHED;
2533 }
2534
2535 void OBJECT_OT_duplicate(wmOperatorType *ot)
2536 {
2537         PropertyRNA *prop;
2538
2539         /* identifiers */
2540         ot->name = "Duplicate Objects";
2541         ot->description = "Duplicate selected objects";
2542         ot->idname = "OBJECT_OT_duplicate";
2543
2544         /* api callbacks */
2545         ot->exec = duplicate_exec;
2546         ot->poll = ED_operator_objectmode;
2547
2548         /* flags */
2549         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2550
2551         /* to give to transform */
2552         RNA_def_boolean(ot->srna, "linked", 0, "Linked", "Duplicate object but not object data, linking to the original data");
2553         prop = RNA_def_enum(ot->srna, "mode", rna_enum_transform_mode_types, TFM_TRANSLATION, "Mode", "");
2554         RNA_def_property_flag(prop, PROP_HIDDEN);
2555 }
2556
2557 /* **************** add named object, for dragdrop ************* */
2558
2559 static int add_named_exec(bContext *C, wmOperator *op)
2560 {
2561         wmWindow *win = CTX_wm_window(C);
2562         const wmEvent *event = win ? win->eventstate : NULL;
2563         Main *bmain = CTX_data_main(C);
2564         Scene *scene = CTX_data_scene(C);
2565         ViewLayer *view_layer = CTX_data_view_layer(C);
2566         Base *basen;
2567         Object *ob;
2568         const bool linked = RNA_boolean_get(op->ptr, "linked");
2569         int dupflag = (linked) ? 0 : U.dupflag;
2570         char name[MAX_ID_NAME - 2];
2571
2572         /* find object, create fake base */
2573         RNA_string_get(op->ptr, "name", name);
2574         ob = (Object *)BKE_libblock_find_name(bmain, ID_OB, name);
2575
2576         if (ob == NULL) {
2577                 BKE_report(op->reports, RPT_ERROR, "Object not found");
2578                 return OPERATOR_CANCELLED;
2579         }
2580
2581         /* prepare dupli */
2582         basen = object_add_duplicate_internal(bmain, scene, view_layer, ob, dupflag);
2583
2584         if (basen == NULL) {
2585                 BKE_report(op->reports, RPT_ERROR, "Object could not be duplicated");
2586                 return OPERATOR_CANCELLED;
2587         }
2588
2589         BKE_scene_object_base_flag_sync_from_object(basen);
2590         basen->object->restrictflag &= ~OB_RESTRICT_VIEW;
2591
2592         if (event) {
2593                 ARegion *ar = CTX_wm_region(C);
2594                 const int mval[2] = {event->x - ar->winrct.xmin,
2595                                      event->y - ar->winrct.ymin};
2596                 ED_object_location_from_view(C, basen->object->loc);
2597                 ED_view3d_cursor3d_position(C, mval, false, basen->object->loc);
2598         }
2599
2600         ED_object_base_select(basen, BA_SELECT);
2601         ED_object_base_activate(C, basen);
2602
2603         copy_object_set_idnew(C);
2604
2605         /* TODO(sergey): Only update relations for the current scene. */
2606         DEG_relations_tag_update(bmain);
2607
2608         DEG_id_tag_update(&scene->id, ID_RECALC_SELECT);
2609         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
2610         WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
2611
2612         return OPERATOR_FINISHED;
2613 }
2614
2615 void OBJECT_OT_add_named(wmOperatorType *ot)
2616 {
2617         /* identifiers */
2618         ot->name = "Add Named Object";
2619         ot->description = "Add named object";
2620         ot->idname = "OBJECT_OT_add_named";
2621
2622         /* api callbacks */
2623         ot->exec = add_named_exec;
2624         ot->poll = ED_operator_objectmode;
2625
2626         /* flags */
2627         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2628
2629         RNA_def_boolean(ot->srna, "linked", 0, "Linked", "Duplicate object but not object data, linking to the original data");
2630         RNA_def_string(ot->srna, "name", NULL, MAX_ID_NAME - 2, "Name", "Object name to add");
2631 }
2632
2633 /**************************** Join *************************/
2634
2635 static bool join_poll(bContext *C)
2636 {
2637         Object *ob = CTX_data_active_object(C);
2638
2639         if (!ob || ID_IS_LINKED(ob)) return 0;
2640
2641         if (ELEM(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_ARMATURE, OB_GPENCIL))
2642                 return ED_operator_screenactive(C);
2643         else
2644                 return 0;
2645 }
2646
2647 static int join_exec(bContext *C, wmOperator *op)
2648 {
2649         Object *ob = CTX_data_active_object(C);
2650
2651         if (ob->mode & OB_MODE_EDIT) {
2652                 BKE_report(op->reports, RPT_ERROR, "This data does not support joining in edit mode");
2653                 return OPERATOR_CANCELLED;
2654         }
2655         else if (BKE_object_obdata_is_libdata(ob)) {
2656                 BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
2657                 return OPERATOR_CANCELLED;
2658         }
2659         else if (ob->type == OB_GPENCIL) {
2660                 bGPdata *gpd = (bGPdata *)ob->data;
2661                 if ((!gpd) || GPENCIL_ANY_MODE(gpd)) {
2662                         BKE_report(op->reports, RPT_ERROR, "This data does not support joining in this mode");
2663                         return OPERATOR_CANCELLED;
2664                 }
2665         }
2666
2667         if (ob->type == OB_MESH)
2668                 return join_mesh_exec(C, op);
2669         else if (ELEM(ob->type, OB_CURVE, OB_SURF))
2670                 return join_curve_exec(C, op);
2671         else if (ob->type == OB_ARMATURE)
2672                 return join_armature_exec(C, op);
2673         else if (ob->type == OB_GPENCIL)
2674                 return ED_gpencil_join_objects_exec(C, op);
2675
2676         return OPERATOR_CANCELLED;
2677 }
2678
2679 void OBJECT_OT_join(wmOperatorType *ot)
2680 {
2681         /* identifiers */
2682         ot->name = "Join";
2683         ot->description = "Join selected objects into active object";
2684         ot->idname = "OBJECT_OT_join";
2685
2686         /* api callbacks */
2687         ot->exec = join_exec;
2688         ot->poll = join_poll;
2689
2690         /* flags */
2691         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2692 }
2693
2694 /**************************** Join as Shape Key*************************/
2695
2696 static bool join_shapes_poll(bContext *C)
2697 {
2698         Object *ob = CTX_data_active_object(C);
2699
2700         if (!ob || ID_IS_LINKED(ob)) return 0;
2701
2702         /* only meshes supported at the moment */
2703         if (ob->type == OB_MESH)
2704                 return ED_operator_screenactive(C);
2705         else
2706                 return 0;
2707 }
2708
2709 static int join_shapes_exec(bContext *C, wmOperator *op)
2710 {
2711         Object *ob = CTX_data_active_object(C);
2712
2713         if (ob->mode & OB_MODE_EDIT) {
2714                 BKE_report(op->reports, RPT_ERROR, "This data does not support joining in edit mode");
2715                 return OPERATOR_CANCELLED;
2716         }
2717         else if (BKE_object_obdata_is_libdata(ob)) {
2718                 BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
2719                 return OPERATOR_CANCELLED;
2720         }
2721
2722         if (ob->type == OB_MESH)
2723                 return join_mesh_shapes_exec(C, op);
2724
2725         return OPERATOR_CANCELLED;
2726 }
2727
2728 void OBJECT_OT_join_shapes(wmOperatorType *ot)
2729 {
2730         /* identifiers */
2731         ot->name = "Join as Shapes";
2732         ot->description = "Merge selected objects to shapes of active object";
2733         ot->idname = "OBJECT_OT_join_shapes";
2734
2735         /* api callbacks */
2736         ot->exec = join_shapes_exec;
2737         ot->poll = join_shapes_poll;
2738
2739         /* flags */
2740         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2741 }