Blender V5.3
mesh_join.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2025 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <algorithm>
10
11#include "MEM_guardedalloc.h"
12
13#include "BLI_listbase.hh"
14#include "BLI_math_matrix.hh"
15#include "BLI_math_matrix_c.hh"
16#include "BLI_vector.hh"
17#include "BLI_virtual_array.hh"
18
19#include "DNA_key_types.h"
20#include "DNA_material_types.h"
21#include "DNA_mesh_types.h"
22#include "DNA_meshdata_types.h"
23#include "DNA_modifier_types.h"
24#include "DNA_object_types.h"
25#include "DNA_scene_types.h"
26
27#include "BKE_attribute.h"
28#include "BKE_attribute.hh"
29#include "BKE_context.hh"
30#include "BKE_customdata.hh"
31#include "BKE_deform.hh"
32#include "BKE_key.hh"
33#include "BKE_lib_id.hh"
34#include "BKE_material.hh"
35#include "BKE_mesh.hh"
36#include "BKE_mesh_runtime.hh"
37#include "BKE_multires.hh"
38#include "BKE_object.hh"
39#include "BKE_object_deform.h"
40#include "BKE_report.hh"
41
42#include "DEG_depsgraph.hh"
45
46#include "ED_geometry.hh"
47#include "ED_mesh.hh"
48#include "ED_object.hh"
49#include "ED_view3d.hh"
50
51#include "WM_api.hh"
52#include "WM_types.hh"
53
54#include "mesh_intern.hh"
55
56namespace blender::ed::mesh {
57
59 const OffsetIndices<int> vert_ranges,
60 Mesh &dst_mesh)
61{
62 VectorSet<std::string> vertex_group_names;
63 for (const int i : objects_to_join.index_range()) {
64 const Mesh &mesh = *id_cast<const Mesh *>(objects_to_join[i]->data);
65 for (const bDeformGroup &dg : mesh.vertex_group_names) {
66 if (vertex_group_names.add_as(dg.name)) {
68 }
69 }
70 }
71
72 if (vertex_group_names.is_empty()) {
73 return vertex_group_names;
74 }
75
76 MDeformVert *dvert = static_cast<MDeformVert *>(
78
79 for (const int i : objects_to_join.index_range()) {
80 const Mesh &src_mesh = *id_cast<const Mesh *>(objects_to_join[i]->data);
81 const Span<MDeformVert> src_dverts = src_mesh.deform_verts();
82 if (src_dverts.is_empty()) {
83 continue;
84 }
85 Vector<int, 32> index_map;
86 for (const bDeformGroup &dg : src_mesh.vertex_group_names) {
87 index_map.append(vertex_group_names.index_of_as(dg.name));
88 }
89 for (const int vert : src_dverts.index_range()) {
90 const MDeformVert &src = src_dverts[vert];
91 MDeformVert &dst = dvert[vert_ranges[i][vert]];
92 dst = src;
94 for (const int weight : IndexRange(src.totweight)) {
95 dst.dw[weight].def_nr = index_map[src.dw[weight].def_nr];
96 dst.dw[weight].weight = src.dw[weight].weight;
97 }
98 }
99 }
100
101 return vertex_group_names;
102}
103
104static void join_positions(const Span<const Object *> objects_to_join,
105 const OffsetIndices<int> vert_ranges,
106 const float4x4 &world_to_dst_mesh,
107 Mesh &dst_mesh)
108{
109 MutableSpan<float3> dst_positions = dst_mesh.vert_positions_for_write();
110 for (const int i : objects_to_join.index_range()) {
111 const Object &src_object = *objects_to_join[i];
112 const IndexRange dst_range = vert_ranges[i];
113 const Mesh &src_mesh = *id_cast<const Mesh *>(src_object.data);
114 const Span<float3> src_positions = src_mesh.vert_positions();
115 const float4x4 transform = world_to_dst_mesh * src_object.object_to_world();
116 math::transform_points(src_positions, transform, dst_positions.slice(dst_range));
117 }
118}
119
120static void join_normals(const Span<const Object *> objects_to_join,
121 const OffsetIndices<int> vert_ranges,
122 const OffsetIndices<int> face_ranges,
123 const OffsetIndices<int> corner_ranges,
124 const float4x4 &world_to_dst_mesh,
125 Mesh &dst_mesh)
126{
127 bke::mesh::NormalJoinInfo normal_info;
128 for (const Object *object : objects_to_join) {
129 const Mesh &mesh = *id_cast<const Mesh *>(object->data);
130 normal_info.add_mesh(mesh);
131 }
132
133 bke::MutableAttributeAccessor dst_attributes = dst_mesh.attributes_for_write();
134 switch (normal_info.result_type) {
136 break;
137 }
140 "custom_normal", bke::AttrDomain::Corner);
141 for (const int i : objects_to_join.index_range()) {
142 const Object &src_object = *objects_to_join[i];
143 const Mesh &src_mesh = *id_cast<const Mesh *>(src_object.data);
144 const bke::AttributeAccessor attributes = src_mesh.attributes();
145 const bke::GAttributeReader src = attributes.lookup("custom_normal");
146 if (!src) {
147 dst_attr.span.slice(corner_ranges[i]).fill(short2(0));
148 continue;
149 }
151 if (!bke::mesh::is_corner_fan_normals({src.domain, data_type})) {
152 dst_attr.span.slice(corner_ranges[i]).fill(short2(0));
153 continue;
154 }
155 src.typed<short2>().varray.materialize(dst_attr.span.slice(corner_ranges[i]));
156 }
157 dst_attr.finish();
158 break;
159 }
162 "custom_normal", *normal_info.result_domain);
163 for (const int i : objects_to_join.index_range()) {
164 const Object &src_object = *objects_to_join[i];
165 const Mesh &src_mesh = *id_cast<const Mesh *>(src_object.data);
166 switch (*normal_info.result_domain) {
168 math::transform_normals(src_mesh.vert_normals(),
169 float3x3(world_to_dst_mesh),
170 dst_attr.span.slice(vert_ranges[i]));
171 break;
173 math::transform_normals(src_mesh.face_normals(),
174 float3x3(world_to_dst_mesh),
175 dst_attr.span.slice(face_ranges[i]));
176 break;
178 math::transform_normals(src_mesh.corner_normals(),
179 float3x3(world_to_dst_mesh),
180 dst_attr.span.slice(corner_ranges[i]));
181 break;
182 default:
184 }
185 }
186 dst_attr.finish();
187 break;
188 }
189 }
190}
191
192static void join_shape_keys(Main *bmain,
193 const Span<const Object *> objects_to_join,
194 const OffsetIndices<int> vert_ranges,
195 const float4x4 &world_to_active_mesh,
196 Mesh &active_mesh)
197{
198 const int dst_verts_num = vert_ranges.total_size();
199 Vector<KeyBlock *> key_blocks;
200 VectorSet<std::string> key_names;
201 if (Key *key = active_mesh.key) {
202 for (KeyBlock &kb : key->block) {
203 kb.data = MEM_realloc_uninitialized(kb.data, sizeof(float3) * dst_verts_num);
204 kb.totelem = dst_verts_num;
205 key_names.add_new(kb.name);
206 key_blocks.append(&kb);
207 }
208 }
209
210 const auto ensure_dst_key = [&]() {
211 if (!active_mesh.key) {
212 active_mesh.key = BKE_key_add(bmain, &active_mesh.id);
213 active_mesh.key->type = KEY_RELATIVE;
214 }
215 };
216
217 const Span<float3> active_mesh_positions = active_mesh.vert_positions();
218
219 for (const int i : objects_to_join.index_range().drop_front(1)) {
220 const Key *src_key = id_cast<const Mesh *>(objects_to_join[i]->data)->key;
221 if (!src_key) {
222 continue;
223 }
224 ensure_dst_key();
225 for (const KeyBlock &src_kb : src_key->block) {
226 if (key_names.add_as(src_kb.name)) {
227 KeyBlock *dst_kb = BKE_keyblock_add(active_mesh.key, src_kb.name);
228 BKE_keyblock_copy_settings(dst_kb, &src_kb);
229 dst_kb->data = MEM_new_array_uninitialized<float3>(dst_verts_num, __func__);
230 dst_kb->totelem = dst_verts_num;
231
232 /* Initialize the new shape key data with the base positions for the active object. */
233 MutableSpan<float3> key_data(static_cast<float3 *>(dst_kb->data), dst_kb->totelem);
234 key_data.take_front(vert_ranges[0].size()).copy_from(active_mesh_positions);
235
236 /* Remap `KeyBlock::relative`. */
237 if (const KeyBlock *src_kb_relative = static_cast<KeyBlock *>(
238 BLI_findlink(&src_key->block, src_kb.relative)))
239 {
240 dst_kb->relative = key_names.index_of_as(src_kb_relative->name);
241 }
242 }
243 }
244 }
245
246 Key *dst_key = active_mesh.key;
247 if (!dst_key) {
248 return;
249 }
250
251 for (const int i : objects_to_join.index_range().drop_front(1)) {
252 const Object &src_object = *objects_to_join[i];
253 const IndexRange dst_range = vert_ranges[i];
254 const Mesh &src_mesh = *id_cast<const Mesh *>(src_object.data);
255 const Span<float3> src_positions = src_mesh.vert_positions();
256 const float4x4 transform = world_to_active_mesh * src_object.object_to_world();
257
258 for (KeyBlock &kb : dst_key->block) {
259 MutableSpan<float3> key_data(static_cast<float3 *>(kb.data), kb.totelem);
260 if (const KeyBlock *src_kb = src_mesh.key ? BKE_keyblock_find_name(src_mesh.key, kb.name) :
261 nullptr)
262 {
263 const Span<float3> src_kb_data(static_cast<float3 *>(src_kb->data), dst_range.size());
264 math::transform_points(src_kb_data, transform, key_data.slice(dst_range));
265 }
266 else {
267 math::transform_points(src_positions, transform, key_data.slice(dst_range));
268 }
269 }
270 }
271}
272
274 const StringRef name,
275 const bke::AttrDomain domain,
276 const bke::AttrType data_type,
277 bke::MutableAttributeAccessor dst_attributes)
278{
279 if (data_type == bke::AttrType::String) {
280 return false;
281 }
282 const auto get_single_value = [&](const Object &object) {
283 const Mesh &src_mesh = *id_cast<const Mesh *>(object.data);
284 const bke::AttributeAccessor attributes = src_mesh.attributes();
285 const GVArray src = *attributes.lookup_or_default(name, domain, data_type);
286 const CommonVArrayInfo info = src.common_info();
288 return GPointer();
289 }
290 return GPointer(src.type(), info.data);
291 };
292 const GPointer first_value = get_single_value(*objects_to_join.first());
293 if (!first_value) {
294 return false;
295 }
296 const bool all_equal = threading::parallel_reduce(
297 objects_to_join.index_range().drop_front(1),
298 8,
299 true,
300 [&](const IndexRange range, bool value) {
301 if (!value) {
302 return false;
303 }
304 for (const int i : range) {
305 const GPointer value = get_single_value(*objects_to_join[i]);
306 if (!value) {
307 return false;
308 }
309 if (!value.type()->is_equal(value.get(), first_value.get())) {
310 return false;
311 }
312 }
313 return true;
314 },
315 std::logical_and<bool>());
316 if (!all_equal) {
317 return false;
318 }
319 return dst_attributes.add(name, domain, data_type, bke::AttributeInitValue(first_value));
320}
321
322static void join_generic_attributes(const Span<const Object *> objects_to_join,
323 const VectorSet<std::string> &all_vertex_group_names,
324 const OffsetIndices<int> vert_ranges,
325 const OffsetIndices<int> edge_ranges,
326 const OffsetIndices<int> face_ranges,
327 const OffsetIndices<int> corner_ranges,
328 Mesh &dst_mesh)
329{
330 Set<StringRef> skip_names{"position",
331 ".edge_verts",
332 ".corner_vert",
333 ".corner_edge",
334 "material_index",
335 "custom_normal",
336 ".sculpt_face_set"};
337
338 Array<std::string> names;
340 {
342 for (const int i : objects_to_join.index_range()) {
343 const Mesh &mesh = *id_cast<const Mesh *>(objects_to_join[i]->data);
344 mesh.attributes().foreach_attribute([&](const bke::AttributeIter &attr) {
345 if (skip_names.contains(attr.name) || all_vertex_group_names.contains(attr.name)) {
346 return;
347 }
348 attr_info.add(attr.name, {attr.domain, attr.data_type});
349 });
350 }
351 names.reinitialize(attr_info.names.size());
352 kinds.reinitialize(attr_info.names.size());
353 for (const int i : attr_info.names.index_range()) {
354 names[i] = attr_info.names[i];
355 kinds[i] = attr_info.kinds[i];
356 }
357 }
358
359 bke::MutableAttributeAccessor dst_attributes = dst_mesh.attributes_for_write();
360
361 for (const int attr_i : names.index_range()) {
362 const StringRef name = names[attr_i];
363 const bke::AttrDomain domain = kinds[attr_i].domain;
364 const bke::AttrType data_type = kinds[attr_i].data_type;
365
366 if (try_join_single_value_attribute(objects_to_join, name, domain, data_type, dst_attributes))
367 {
368 continue;
369 }
370
372 name, domain, data_type);
373 for (const int i : objects_to_join.index_range()) {
374 const Mesh &src_mesh = *id_cast<const Mesh *>(objects_to_join[i]->data);
375 const bke::AttributeAccessor src_attributes = src_mesh.attributes();
376 const GVArray src = *src_attributes.lookup_or_default(name, domain, data_type);
377
378 const IndexRange dst_range = [&]() {
379 switch (domain) {
381 return vert_ranges[i];
383 return edge_ranges[i];
385 return face_ranges[i];
387 return corner_ranges[i];
388 default:
390 return IndexRange();
391 }
392 }();
393
394 src.materialize(dst.span.slice(dst_range).data());
395 }
396 dst.finish();
397 }
398}
399
401 const OffsetIndices<int> face_ranges,
402 Mesh &dst_mesh)
403{
404 VectorSet<Material *> materials;
405 for (const int i : objects_to_join.index_range()) {
406 const Object &src_object = *objects_to_join[i];
407 const Mesh &src_mesh = *id_cast<const Mesh *>(src_object.data);
408 if (src_mesh.totcol == 0) {
409 materials.add(nullptr);
410 continue;
411 }
412 for (const int material_index : IndexRange(src_mesh.totcol)) {
413 Material *material = BKE_object_material_get(&const_cast<Object &>(src_object),
414 material_index + 1);
415 if (materials.size() < MAXMAT) {
416 materials.add(material);
417 }
418 }
419 }
420
421 bke::MutableAttributeAccessor dst_attributes = dst_mesh.attributes_for_write();
422 if (materials.size() <= 1) {
423 BLI_assert(!dst_attributes.contains("material_index"));
424 return materials;
425 }
426
427 bke::SpanAttributeWriter dst_attr = dst_attributes.lookup_or_add_for_write_only_span<int>(
428 "material_index", bke::AttrDomain::Face);
429 if (!dst_attr) {
430 return {};
431 }
432
433 for (const int i : objects_to_join.index_range()) {
434 const Object &src_object = *objects_to_join[i];
435 const IndexRange dst_range = face_ranges[i];
436 const Mesh &src_mesh = *id_cast<const Mesh *>(src_object.data);
437 const bke::AttributeAccessor src_attributes = src_mesh.attributes();
438
439 const VArray<int> material_indices = *src_attributes.lookup<int>("material_index",
441 if (material_indices.is_empty()) {
442 Material *first_material = src_mesh.totcol == 0 ?
443 nullptr :
444 BKE_object_material_get(&const_cast<Object &>(src_object), 1);
445 dst_attr.span.slice(dst_range).fill(materials.index_of(first_material));
446 continue;
447 }
448
449 if (src_mesh.totcol == 0) {
450 /* These material indices are invalid, but copy them anyway to avoid destroying user data. */
451 material_indices.materialize(dst_range.index_range(), dst_attr.span.slice(dst_range));
452 continue;
453 }
454
455 Array<int, 32> index_map(src_mesh.totcol);
456 for (const int material_index : IndexRange(src_mesh.totcol)) {
457 Material *material = BKE_object_material_get(&const_cast<Object &>(src_object),
458 material_index + 1);
459 const int dst_index = materials.index_of_try(material);
460 index_map[material_index] = dst_index == -1 ? 0 : dst_index;
461 }
462
463 const int max = src_mesh.totcol - 1;
464 for (const int face : dst_range.index_range()) {
465 const int src = std::clamp(material_indices[face], 0, max);
466 dst_attr.span[dst_range[face]] = index_map[src];
467 }
468 }
469
470 dst_attr.finish();
471
472 return materials;
473}
474
475/* Face set IDs are a sparse sequence, so this function offsets all the IDs by face_set_offset and
476 * updates face_set_offset with the maximum ID value. This way, when used in multiple meshes, all
477 * of them will have different IDs for their face sets. */
478static void join_face_sets(const Span<const Object *> objects_to_join,
479 const OffsetIndices<int> face_ranges,
480 Mesh &dst_mesh)
481{
482 if (std::none_of(objects_to_join.begin(),
483 objects_to_join.end(),
484 [](const Object *object) {
485 const Mesh &mesh = *id_cast<const Mesh *>(object->data);
486 return mesh.attributes().contains(".sculpt_face_set");
487 }))
488 {
489 return;
490 }
491
492 bke::MutableAttributeAccessor dst_attributes = dst_mesh.attributes_for_write();
493 bke::SpanAttributeWriter dst_face_sets = dst_attributes.lookup_or_add_for_write_span<int>(
494 ".sculpt_face_set", bke::AttrDomain::Face);
495 if (!dst_face_sets) {
496 return;
497 }
498
499 int max_face_set = 0;
500 for (const int i : objects_to_join.index_range()) {
501 const Object &src_object = *objects_to_join[i];
502 const IndexRange dst_range = face_ranges[i];
503 const Mesh &src_mesh = *id_cast<const Mesh *>(src_object.data);
504 const bke::AttributeAccessor src_attributes = src_mesh.attributes();
505 const VArraySpan src_face_sets = *src_attributes.lookup<int>(".sculpt_face_set",
507 if (src_face_sets.is_empty()) {
508 dst_face_sets.span.slice(dst_range).fill(max_face_set);
509 }
510 else {
511 for (const int face : dst_range.index_range()) {
512 dst_face_sets.span[dst_range[face]] = src_face_sets[face] + max_face_set;
513 }
514 max_face_set = std::max(
515 max_face_set,
516 *std::max_element(src_face_sets.begin(), src_face_sets.begin() + dst_range.size()));
517 }
518 max_face_set++;
519 }
520 dst_face_sets.finish();
521}
522
524{
525 Main *bmain = CTX_data_main(C);
526 Scene *scene = CTX_data_scene(C);
527 Object *const active_object = CTX_data_active_object(C);
528
529 if (active_object->mode & OB_MODE_EDIT) {
530 BKE_report(op->reports, RPT_WARNING, "Cannot join while in edit mode");
531 return OPERATOR_CANCELLED;
532 }
533
534 /* active_object is the object we are adding geometry to */
535 if (!active_object || active_object->type != OB_MESH) {
536 BKE_report(op->reports, RPT_WARNING, "Active object is not a mesh");
537 return OPERATOR_CANCELLED;
538 }
539
540 Depsgraph *depsgraph = CTX_data_ensure_evaluated_depsgraph(C);
541
542 Vector<Object *> objects_to_join;
543 CTX_DATA_BEGIN (C, Object *, ob_iter, selected_editable_objects) {
544 if (ob_iter->type == OB_MESH) {
545 objects_to_join.append(ob_iter);
546 }
547 }
549
550 {
551 /* Make sure the active object is first, that way its data will be first in the new mesh. */
552 const int active_index = objects_to_join.as_span().first_index_try(active_object);
553 if (active_index == -1) {
554 BKE_report(op->reports, RPT_WARNING, "Active object is not a selected mesh");
555 return OPERATOR_CANCELLED;
556 }
557 objects_to_join.remove(active_index);
558 objects_to_join.prepend(active_object);
559 }
560
561 Array<int> vert_offset_data(objects_to_join.size() + 1);
562 Array<int> edge_offset_data(objects_to_join.size() + 1);
563 Array<int> face_offset_data(objects_to_join.size() + 1);
564 Array<int> corner_offset_data(objects_to_join.size() + 1);
565 for (const int i : objects_to_join.index_range()) {
566 const Mesh &mesh = *id_cast<const Mesh *>(objects_to_join[i]->data);
567 vert_offset_data[i] = mesh.verts_num;
568 edge_offset_data[i] = mesh.edges_num;
569 face_offset_data[i] = mesh.faces_num;
570 corner_offset_data[i] = mesh.corners_num;
571 }
572
574 vert_offset_data);
576 edge_offset_data);
578 face_offset_data);
580 corner_offset_data);
581
582 /* Apply parent transform if the active object's parent was joined to it.
583 * NOTE: This doesn't apply recursive parenting. */
584 if (objects_to_join.contains(active_object->parent)) {
585 active_object->parent = nullptr;
586 BKE_object_apply_mat4_ex(active_object,
587 active_object->object_to_world().ptr(),
588 active_object->parent,
589 active_object->parentinv,
590 false);
591 }
592
593 /* Only join meshes if there are verts to join,
594 * there aren't too many, and we only had one mesh selected. */
595 Mesh *active_mesh = id_cast<Mesh *>(active_object->data);
596
597 if (ELEM(vert_ranges.total_size(), 0, active_mesh->verts_num)) {
598 BKE_report(op->reports, RPT_WARNING, "No mesh data to join");
599 return OPERATOR_CANCELLED;
600 }
601
602 if (vert_ranges.total_size() > MESH_MAX_VERTS) {
605 "Joining results in %d vertices, limit is %ld",
606 vert_ranges.total_size(),
608 return OPERATOR_CANCELLED;
609 }
610
611 Mesh *dst_mesh = BKE_mesh_new_nomain(vert_ranges.total_size(),
612 edge_ranges.total_size(),
613 face_ranges.total_size(),
614 corner_ranges.total_size());
615 BKE_mesh_copy_parameters_for_eval(dst_mesh, active_mesh);
616 dst_mesh->vertex_group_names.free_no_destruct();
617 MEM_SAFE_DELETE(dst_mesh->mat);
618 dst_mesh->totcol = 0;
619
620 /* Inverse transform for all selected meshes in this object,
621 * See #object_join_exec for detailed comment on why the safe version is used. */
622 float4x4 world_to_active_object;
623 invert_m4_m4_safe_ortho(world_to_active_object.ptr(), active_object->object_to_world().ptr());
624
625 join_shape_keys(bmain, objects_to_join, vert_ranges, world_to_active_object, *active_mesh);
626 join_positions(objects_to_join, vert_ranges, world_to_active_object, *dst_mesh);
628 objects_to_join, vert_ranges, face_ranges, corner_ranges, world_to_active_object, *dst_mesh);
629
630 MutableSpan<int2> dst_edges = dst_mesh->edges_for_write();
631 for (const int i : objects_to_join.index_range()) {
632 const Object &src_object = *objects_to_join[i];
633 const IndexRange dst_range = edge_ranges[i];
634 const Mesh &src_mesh = *id_cast<const Mesh *>(src_object.data);
635 const Span<int2> src_edges = src_mesh.edges();
636 for (const int edge : dst_range.index_range()) {
637 dst_edges[dst_range[edge]] = src_edges[edge] + int(vert_ranges[i].start());
638 }
639 }
640
641 MutableSpan<int> dst_corner_verts = dst_mesh->corner_verts_for_write();
642 for (const int i : objects_to_join.index_range()) {
643 const Object &src_object = *objects_to_join[i];
644 const IndexRange dst_range = corner_ranges[i];
645 const Mesh &src_mesh = *id_cast<const Mesh *>(src_object.data);
646 const Span<int> src_corner_verts = src_mesh.corner_verts();
647 for (const int corner : dst_range.index_range()) {
648 dst_corner_verts[dst_range[corner]] = src_corner_verts[corner] + int(vert_ranges[i].start());
649 }
650 }
651
652 MutableSpan<int> dst_corner_edges = dst_mesh->corner_edges_for_write();
653 for (const int i : objects_to_join.index_range()) {
654 const Object &src_object = *objects_to_join[i];
655 const IndexRange dst_range = corner_ranges[i];
656 const Mesh &src_mesh = *id_cast<const Mesh *>(src_object.data);
657 const Span<int> src_corner_edges = src_mesh.corner_edges();
658 for (const int corner : dst_range.index_range()) {
659 dst_corner_edges[dst_range[corner]] = src_corner_edges[corner] + int(edge_ranges[i].start());
660 }
661 }
662
663 if (dst_mesh->faces_num > 0) {
664 MutableSpan<int> dst_face_offsets = dst_mesh->face_offsets_for_write();
665 for (const int i : objects_to_join.index_range()) {
666 const Object &src_object = *objects_to_join[i];
667 const IndexRange dst_range = face_ranges[i];
668 const Mesh &src_mesh = *id_cast<const Mesh *>(src_object.data);
669 const Span<int> src_face_offsets = src_mesh.face_offsets();
670 for (const int face : dst_range.index_range()) {
671 dst_face_offsets[dst_range[face]] = src_face_offsets[face] + corner_ranges[i].start();
672 }
673 }
674 dst_face_offsets.last() = dst_mesh->corners_num;
675 }
676
677 join_face_sets(objects_to_join, face_ranges, *dst_mesh);
678
679 VectorSet<Material *> materials = join_materials(objects_to_join, face_ranges, *dst_mesh);
680
681 VectorSet<std::string> vertex_group_names = join_vertex_groups(
682 objects_to_join, vert_ranges, *dst_mesh);
683
684 join_generic_attributes(objects_to_join,
685 vertex_group_names,
686 vert_ranges,
687 edge_ranges,
688 face_ranges,
689 corner_ranges,
690 *dst_mesh);
691
692 /* Copy multires data to the out-of-main mesh. */
693 if (get_multires_modifier(scene, active_object, true)) {
694 for (const int i : objects_to_join.index_range().drop_front(1)) {
695 Object &src_object = *objects_to_join[i];
696 multiresModifier_prepare_join(depsgraph, scene, &src_object, active_object);
697 if (MultiresModifierData *mmd = get_multires_modifier(scene, &src_object, true)) {
699 bmain, &src_object, true, object::multires_update_totlevels, &mmd->totlvl);
700 }
701 }
702 if (std::any_of(objects_to_join.begin(),
703 objects_to_join.end(),
704 [](const Object *object) {
705 const Mesh &src_mesh = *id_cast<const Mesh *>(object->data);
706 return CustomData_has_layer(&src_mesh.corner_data, CD_MDISPS);
707 }))
708 {
709 MDisps *dst = static_cast<MDisps *>(CustomData_add_layer(
710 &dst_mesh->corner_data, CD_MDISPS, CD_CONSTRUCT, dst_mesh->corners_num));
711 for (const int i : objects_to_join.index_range()) {
712 const Mesh &src_mesh = *id_cast<const Mesh *>(objects_to_join[i]->data);
713 if (const void *src = CustomData_get_layer(&src_mesh.corner_data, CD_MDISPS)) {
715 CD_MDISPS, src, &dst[corner_ranges[i].first()], src_mesh.corners_num);
716 }
717 }
718 }
719 if (std::any_of(objects_to_join.begin(),
720 objects_to_join.end(),
721 [](const Object *object) {
722 const Mesh &src_mesh = *id_cast<const Mesh *>(object->data);
723 return CustomData_has_layer(&src_mesh.corner_data, CD_GRID_PAINT_MASK);
724 }))
725 {
727 &dst_mesh->corner_data, CD_GRID_PAINT_MASK, CD_CONSTRUCT, dst_mesh->corners_num));
728 for (const int i : objects_to_join.index_range()) {
729 const Mesh &src_mesh = *id_cast<const Mesh *>(objects_to_join[i]->data);
730 if (const void *src = CustomData_get_layer(&src_mesh.corner_data, CD_GRID_PAINT_MASK)) {
732 CD_GRID_PAINT_MASK, src, &dst[corner_ranges[i].first()], src_mesh.corners_num);
733 }
734 }
735 }
736 }
737
738 BKE_mesh_nomain_to_mesh(dst_mesh, active_mesh, active_object, false);
739
740 for (Object *object : objects_to_join.as_span().drop_front(1)) {
741 object::base_free_and_unlink(bmain, scene, object);
742 }
743
744 /* old material array */
745 for (const int a : IndexRange(active_object->totcol)) {
746 if (Material *ma = active_object->mat[a]) {
747 id_us_min(&ma->id);
748 }
749 }
750 for (const int a : IndexRange(active_object->totcol)) {
751 if (Material *ma = active_mesh->mat[a]) {
752 id_us_min(&ma->id);
753 }
754 }
755 MEM_SAFE_DELETE(active_object->mat);
756 MEM_SAFE_DELETE(active_object->matbits);
757 MEM_SAFE_DELETE(active_mesh->mat);
758
759 /* If the object had no slots, don't add an empty one. */
760 if (active_object->totcol == 0 && materials.size() == 1 && materials[0] == nullptr) {
761 materials.clear();
762 }
763
764 const int totcol = materials.size();
765 if (totcol) {
766 VectorData data = materials.extract_vector().release();
767 active_mesh->mat = data.data;
768 for (const int i : IndexRange(totcol)) {
769 if (Material *ma = active_mesh->mat[i]) {
770 id_us_plus(id_cast<ID *>(ma));
771 }
772 }
773 active_object->mat = MEM_new_array_zeroed<Material *>(totcol, __func__);
774 active_object->matbits = MEM_new_array_zeroed<char>(totcol, __func__);
775 }
776
777 active_object->totcol = active_mesh->totcol = totcol;
778
779 /* other mesh users */
780 BKE_objects_materials_sync_length_all(bmain, &active_mesh->id);
781
782 /* ensure newly inserted keys are time sorted */
783 if (Key *key = active_mesh->key) {
784 if (key->type != KEY_RELATIVE) {
785 BKE_key_sort(key);
786 }
787 }
788
789 /* Due to dependency cycle some other object might access old derived data. */
790 BKE_object_free_derived_caches(active_object);
791
792 DEG_relations_tag_update(bmain); /* removed objects, need to rebuild dag */
793
795
799
800 return OPERATOR_FINISHED;
801}
802
803} // namespace blender::ed::mesh
Generic geometry attributes built on CustomData.
#define CTX_DATA_BEGIN(C, Type, instance, member)
#define CTX_DATA_END
CustomData interface, see also DNA_customdata_types.h.
support for deformation groups and hooks.
General operations, lookup, etc. for materials.
General operations, lookup, etc. for blender objects.
Functions for dealing with objects and deform verts, used by painting and tools.
#define MAXMAT
#define MESH_MAX_VERTS
Object is a sort of wrapper for general info.
Read Blender memory allocation and freeing.
#define C
Definition RandGen.cpp:29
#define ND_OB_ACTIVE
Definition WM_types.hh:459
#define NC_SCENE
Definition WM_types.hh:391
#define ND_LAYER_CONTENT
Definition WM_types.hh:472
#define BLI_assert_unreachable()
#define ELEM(...)
#define MEM_realloc_uninitialized(vmemh, len)
btScalar max
IndexRange index_range() const
Definition BLI_array.hh:371
void reinitialize(const int64_t new_size)
Definition BLI_array.hh:430
bool is_equal(const void *a, const void *b) const
GMutableSpan slice(const int64_t start, int64_t size) const
const CPPType * type() const
GPointer()=default
const void * get() const
CommonVArrayInfo common_info() const
void materialize(void *dst) const
constexpr int64_t size() const
constexpr IndexRange()=default
constexpr IndexRange index_range() const
constexpr IndexRange drop_front(int64_t n) const
constexpr MutableSpan slice(const int64_t start, const int64_t size) const
Definition BLI_span.hh:579
constexpr void copy_from(Span< T > values) const
Definition BLI_span.hh:745
constexpr MutableSpan take_front(const int64_t n) const
Definition BLI_span.hh:635
constexpr T & last(const int64_t n=0) const
Definition BLI_span.hh:695
bool contains(const Key &key) const
Definition BLI_set.hh:310
constexpr const T & first() const
Definition BLI_span.hh:319
constexpr const T * end() const
Definition BLI_span.hh:228
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
constexpr const T * begin() const
Definition BLI_span.hh:224
constexpr bool is_empty() const
Definition BLI_span.hh:264
void materialize(MutableSpan< T > r_span) const
int64_t index_of_try(const Key &key) const
bool add(const Key &key)
int64_t index_of_as(const ForwardKey &key) const
bool add_as(ForwardKey &&key)
int64_t size() const
int64_t index_of(const Key &key) const
bool contains(const Key &key) const
void add_new(const Key &key)
int64_t size() const
void prepend(const T &value)
bool contains(const T &value) const
void append(const T &value)
void remove(const int64_t index)
IndexRange index_range() const
Span< T > as_span() const
VectorData< T, Allocator > release()
GAttributeReader lookup_or_default(StringRef name, AttrDomain domain, AttrType data_type, const void *default_value=nullptr) const
bool contains(StringRef name) const
GAttributeReader lookup(const StringRef name) const
GSpanAttributeWriter lookup_or_add_for_write_span(StringRef name, AttrDomain domain, AttrType data_type, const AttributeInit &initializer=AttributeInitDefaultValue())
GSpanAttributeWriter lookup_or_add_for_write_only_span(StringRef name, AttrDomain domain, AttrType data_type)
std::optional< bke::AttrDomain > result_domain
Definition BKE_mesh.hh:263
constexpr bool is_empty() const
constexpr const T * begin() const
bool is_corner_fan_normals(const AttributeMetaData &meta_data)
AttrType cpp_type_to_attribute_type(const CPPType &type)
static void join_generic_attributes(const Span< const Object * > objects_to_join, const VectorSet< std::string > &all_vertex_group_names, const OffsetIndices< int > vert_ranges, const OffsetIndices< int > edge_ranges, const OffsetIndices< int > face_ranges, const OffsetIndices< int > corner_ranges, Mesh &dst_mesh)
Definition mesh_join.cc:322
wmOperatorStatus join_objects_exec(bContext *C, wmOperator *op)
Definition mesh_join.cc:523
static void join_positions(const Span< const Object * > objects_to_join, const OffsetIndices< int > vert_ranges, const float4x4 &world_to_dst_mesh, Mesh &dst_mesh)
Definition mesh_join.cc:104
static void join_face_sets(const Span< const Object * > objects_to_join, const OffsetIndices< int > face_ranges, Mesh &dst_mesh)
Definition mesh_join.cc:478
static VectorSet< Material * > join_materials(const Span< const Object * > objects_to_join, const OffsetIndices< int > face_ranges, Mesh &dst_mesh)
Definition mesh_join.cc:400
static void join_shape_keys(Main *bmain, const Span< const Object * > objects_to_join, const OffsetIndices< int > vert_ranges, const float4x4 &world_to_active_mesh, Mesh &active_mesh)
Definition mesh_join.cc:192
static VectorSet< std::string > join_vertex_groups(const Span< const Object * > objects_to_join, const OffsetIndices< int > vert_ranges, Mesh &dst_mesh)
Definition mesh_join.cc:58
static void join_normals(const Span< const Object * > objects_to_join, const OffsetIndices< int > vert_ranges, const OffsetIndices< int > face_ranges, const OffsetIndices< int > corner_ranges, const float4x4 &world_to_dst_mesh, Mesh &dst_mesh)
Definition mesh_join.cc:120
static bool try_join_single_value_attribute(const Span< const Object * > objects_to_join, const StringRef name, const bke::AttrDomain domain, const bke::AttrType data_type, bke::MutableAttributeAccessor dst_attributes)
Definition mesh_join.cc:273
bool iter_other(Main *bmain, Object *orig_ob, bool include_orig, bool(*callback)(Object *ob, void *callback_data), void *callback_data)
bool multires_update_totlevels(Object *ob, void *totlevel_v)
void base_free_and_unlink(Main *bmain, Scene *scene, Object *ob)
void transform_normals(const float3x3 &transform, MutableSpan< float3 > normals)
void transform_points(const float4x4 &transform, MutableSpan< float3 > points, bool use_threading=true)
OffsetIndices< int > accumulate_counts_to_offsets(MutableSpan< int > counts_to_offsets, int start_offset=0)
Value parallel_reduce(IndexRange range, int64_t grain_size, const Value &identity, const Function &function, const Reduction &reduction)
Definition BLI_task.hh:127
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
@ RPT_WARNING
Definition BKE_report.hh:40
void CustomData_copy_elements(eCustomDataType type, const void *src_data, void *dst_data, int count)
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
void id_us_plus(ID *id)
Definition lib_id.cc:433
Material * BKE_object_material_get(Object *ob, short act)
void BKE_key_sort(Key *key)
Definition key.cc:279
void BKE_mesh_nomain_to_mesh(Mesh *mesh_src, Mesh *mesh_dst, Object *ob, bool process_shape_keys=true)
KeyBlock * BKE_keyblock_find_name(Key *key, const char name[])
Definition key.cc:1434
MatBase< float, 4, 4 > float4x4
void * BLI_findlink(const ListBase *listbase, int number) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:541
void BKE_mesh_copy_parameters_for_eval(Mesh *me_dst, const Mesh *me_src)
void BKE_object_free_derived_caches(Object *ob)
Definition object.cc:1810
Key * BKE_key_add(Main *bmain, ID *id)
Definition key.cc:228
void DEG_id_tag_update(ID *id, unsigned int flags)
MultiresModifierData * get_multires_modifier(Scene *scene, Object *ob, bool use_first)
Definition multires.cc:185
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
BMesh const char void * data
Depsgraph * CTX_data_ensure_evaluated_depsgraph(const bContext *C, bool rna_write_check=false)
bDeformGroup * BKE_defgroup_duplicate(const bDeformGroup *ingroup)
Definition deform.cc:85
Mesh * BKE_mesh_new_nomain(int verts_num, int edges_num, int faces_num, int corners_num)
const void * CustomData_get_layer(const CustomData *data, eCustomDataType type)
void BKE_objects_materials_sync_length_all(Main *bmain, ID *id)
MatBase< float, 3, 3 > float3x3
void WM_event_add_notifier(const bContext *C, uint type, void *reference)
void BKE_reportf(ReportList *reports, eReportType type, const char *format,...) ATTR_PRINTF_FORMAT(3
Definition report.cc:191
void BLI_addtail(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:118
Main * CTX_data_main(const bContext *C)
VecBase< int16_t, 2 > short2
KeyBlock * BKE_keyblock_add(Key *key, const char *name)
Definition key.cc:1322
@ ID_RECALC_SELECT
Definition DNA_ID.h:1101
@ ID_RECALC_TRANSFORM
Definition DNA_ID.h:1054
@ ID_RECALC_GEOMETRY
Definition DNA_ID.h:1074
void BKE_keyblock_copy_settings(KeyBlock *kb_dst, const KeyBlock *kb_src)
copy shape-key attributes, but not key data or name/UID.
Definition key.cc:1449
void DEG_relations_tag_update(Main *bmain)
Scene * CTX_data_scene(const bContext *C)
VecBase< float, 3 > float3
Object * CTX_data_active_object(const bContext *C)
void id_us_min(ID *id)
Definition lib_id.cc:441
void multiresModifier_prepare_join(Depsgraph *depsgraph, Scene *scene, Object *ob, Object *to_ob)
Definition multires.cc:719
void invert_m4_m4_safe_ortho(float inverse[4][4], const float mat[4][4])
void BKE_object_apply_mat4_ex(Object *ob, const float mat[4][4], Object *parent, const float parentinv[4][4], bool use_compat)
Definition object.cc:3620
void * MEM_new_array_zeroed(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
void * CustomData_add_layer(CustomData *data, eCustomDataType type, eCDAllocType alloctype, int totelem)
ListBaseT< KeyBlock > block
ShapekeyContainerType type
struct MDeformWeight * dw
const c_style_mat & ptr() const
struct Material ** mat
ListBaseT< bDeformGroup > vertex_group_names
struct Key * key
CustomData corner_data
CustomData vert_data
struct Object * parent
float parentinv[4][4]
struct Material ** mat
AttributeReader< T > typed() const
void add(const StringRef name, const AttributeDomainAndType &kind)
Vector< AttributeDomainAndType, 16 > kinds
struct ReportList * reports