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