Blender V5.3
mesh_validate.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2011-2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <algorithm>
10#include <fmt/format.h>
11
13#include "BKE_attribute_math.hh"
14#include "CLG_log.h"
15
16#include "DNA_mesh_types.h"
17#include "DNA_meshdata_types.h"
18
19#include "BLI_array_utils.hh"
21#include "BLI_listbase.hh"
22#include "BLI_ordered_edge.hh"
23
24#include "BKE_attribute.hh"
25#include "BKE_customdata.hh"
26#include "BKE_mesh.hh"
27
28#include "DEG_depsgraph.hh"
29
30namespace blender {
31
32static CLG_LogRef LOG = {"geom.mesh"};
33
34namespace bke {
35
36/* Helper class to collect error messages in parallel. */
38 Mutex mutex_;
39 bool verbose_;
40
41 public:
43
44 ErrorMessages(const bool verbose) : verbose_(verbose) {}
46 {
47 std::ranges::sort(messages);
48 for (const std::string &message : messages) {
49 CLOG_ERROR(&LOG, "%s", message.c_str());
50 }
51 }
52
53 void add(std::string message)
54 {
55 if (!verbose_) {
56 return;
57 }
58 std::lock_guard lock(mutex_);
59 this->messages.append(std::move(message));
60 }
61
62 template<typename... T> void add(fmt::format_string<T...> fmt, T &&...args)
63 {
64 if (!verbose_) {
65 return;
66 }
67 this->add(fmt::format(fmt, std::forward<T>(args)...));
68 }
69};
70
71template<typename... T>
73 fmt::format_string<T...> fmt,
74 T &&...args)
75{
76 fmt::memory_buffer buffer;
77 fmt::appender dst(buffer);
78 fmt::format_to(dst, fmt, std::forward<T>(args)...);
79 fmt::format_to(dst, " at indices: ");
80 mask.foreach_index([&](const int index, const int pos) {
81 if (pos != 0) {
82 fmt::format_to(dst, ", ");
83 }
84 fmt::format_to(dst, "{}", index);
85 });
86 CLOG_ERROR(&LOG, "%s", fmt::to_string(buffer).c_str());
87}
88
90 IndexMaskMemory &memory,
91 const bool verbose)
92{
93 const IndexRange verts_range(mesh.verts_num);
94 const Span<int2> edges = mesh.edges();
95
96 ErrorMessages errors(verbose);
97 return IndexMask::from_predicate(edges.index_range(), memory, [&](const int edge_i) {
98 const int2 edge = edges[edge_i];
99 if (edge[0] == edge[1]) {
100 errors.add("Edge {} has equal vertex indices {}", edge_i, edge[0]);
101 return true;
102 }
103 if (!verts_range.contains(edge[0]) || !verts_range.contains(edge[1])) {
104 errors.add("Edge {} has out of range vertex ({}, {})", edge_i, edge[0], edge[1]);
105 return true;
106 }
107 return false;
108 });
109}
110
112 32,
118
120 const IndexMask &mask,
121 IndexMaskMemory &memory,
122 const bool verbose,
123 EdgeMap &unique_edges)
124{
125 const Span<int2> edges = mesh.edges();
126 BitVector<> duplicate_edges(edges.size());
127 ErrorMessages errors(verbose);
128 mask.foreach_index([&](const int edge_i) {
129 const int2 edge = edges[edge_i];
130 if (!unique_edges.add(edge)) {
131 errors.add(fmt::runtime("Edge {} is a duplicate of {}"),
132 edge_i,
133 int(mask[unique_edges.index_of(edge)]));
134 duplicate_edges[edge_i].set();
135 }
136 });
137 return IndexMask::from_bits(mask, duplicate_edges, memory);
138}
139
141 IndexMaskMemory &memory,
142 const bool verbose)
143{
144 if (mesh.faces_num == 0) {
145 return {};
146 }
147 const Span<int> face_offsets = mesh.face_offsets();
148 ErrorMessages errors(verbose);
149 if (face_offsets.last() != mesh.corners_num) {
150 errors.add("Face offsets last value is {}, expected {}. Considering all faces invalid",
151 face_offsets.last(),
152 mesh.corners_num);
153 return IndexMask(mesh.faces_num);
154 }
155 if (face_offsets.first() != 0) {
156 errors.add("Faces offsets do not start at 0. Considering all faces invalid");
157 return IndexMask(mesh.faces_num);
158 }
159 std::atomic<bool> non_monotonic = false;
161 IndexRange(mesh.faces_num),
162 memory,
163 [&](const IndexMaskSegment universe_segment, IndexRangesBuilder<int16_t> &builder) {
164 for (const int16_t i : universe_segment.base_span()) {
165 const int face_i = int(universe_segment.offset() + i);
166 const int face_start = face_offsets[face_i];
167 const int face_end = face_offsets[face_i + 1];
168 if (face_end < face_start) {
169 non_monotonic.store(true, std::memory_order_relaxed);
170 continue;
171 }
172 if (face_end - face_start < 3) {
173 errors.add("Face {} has invalid size {}", face_i, face_end - face_start);
174 builder.add(i);
175 }
176 }
177 return universe_segment.offset();
178 });
179 if (non_monotonic.load(std::memory_order_relaxed)) {
180 errors.add("Face offsets must be monotonically increasing. Considering all faces invalid");
181 return IndexMask(mesh.faces_num);
182 }
183 return mask;
184}
185
187 const IndexMask &mask,
188 IndexMaskMemory &memory,
189 const bool verbose)
190{
191 const IndexRange verts_range(mesh.verts_num);
192 const OffsetIndices<int> faces(mesh.face_offsets(), offset_indices::NoSortCheck());
193 const Span<int> corner_verts = mesh.corner_verts();
194 ErrorMessages errors(verbose);
196 mask,
197 memory,
198 [&](const int face_i) {
199 const IndexRange face = faces[face_i];
200 for (const int vert : corner_verts.slice(face)) {
201 if (!verts_range.contains(vert)) {
202 errors.add("Face {} has invalid vertex {}", face_i, vert);
203 return true;
204 }
205 }
206 return false;
207 },
209}
210
212 const IndexMask &mask,
213 IndexMaskMemory &memory,
214 const bool verbose)
215{
216 const IndexRange verts_range(mesh.verts_num);
217 const OffsetIndices<int> faces(mesh.face_offsets(), offset_indices::NoSortCheck());
218 const Span<int> corner_verts = mesh.corner_verts();
219 ErrorMessages errors(verbose);
221 mask,
222 memory,
223 [&](const int face_i) {
224 Set<int, 16> set;
225 const IndexRange face = faces[face_i];
226 for (const int vert : corner_verts.slice(face)) {
227 if (!set.add(vert)) {
228 errors.add("Face {} has duplicate vertex {}", face_i, vert);
229 return true;
230 }
231 }
232 return false;
233 },
235}
236
238 const IndexMask &mask,
239 const EdgeMap &unique_edges,
240 IndexMaskMemory &memory,
241 const bool verbose)
242{
243 const IndexRange edges_range(mesh.edges_num);
244 const OffsetIndices<int> faces(mesh.face_offsets(), offset_indices::NoSortCheck());
245 const Span<int> corner_verts = mesh.corner_verts();
246
247 ErrorMessages errors(verbose);
249 mask,
250 memory,
251 [&](const int face_i) {
252 const IndexRange face = faces[face_i];
253 for (const int corner : face) {
254 const int corner_next = mesh::face_corner_next(face, corner);
255 const OrderedEdge actual_edge(corner_verts[corner], corner_verts[corner_next]);
256 if (!unique_edges.contains(actual_edge)) {
257 errors.add("Face {} has missing edge ({}, {})",
258 face_i,
259 actual_edge.v_low,
260 actual_edge.v_high);
261 return true;
262 }
263 }
264 return false;
265 },
267}
268
269static bool find_faces_bad_edges(const Mesh &mesh,
270 const IndexMask &mask,
271 IndexMaskMemory &memory,
272 const bool verbose)
273{
274 const IndexRange edges_range(mesh.edges_num);
275 const Span<int2> edges = mesh.edges();
276 const OffsetIndices<int> faces(mesh.face_offsets(), offset_indices::NoSortCheck());
277 const Span<int> corner_verts = mesh.corner_verts();
278 const Span<int> corner_edges = mesh.corner_edges();
279
280 ErrorMessages errors(verbose);
281 const IndexMask bad_faces = IndexMask::from_predicate(
282 mask,
283 memory,
284 [&](const int face_i) {
285 const IndexRange face = faces[face_i];
286 for (const int corner : face) {
287 const int edge_index = corner_edges[corner];
288 if (!edges_range.contains(edge_index)) {
289 errors.add("Corner {} has out of range edge index {}", corner, edge_index);
290 return true;
291 }
292 const int corner_next = mesh::face_corner_next(face, corner);
293 const OrderedEdge actual_edge(corner_verts[corner], corner_verts[corner_next]);
294 if (OrderedEdge(edges[edge_index]) != actual_edge) {
295 errors.add("Corner {} has incorrect edge index {}", corner, edge_index);
296 return true;
297 }
298 }
299 return false;
300 },
302 return !bad_faces.is_empty();
303}
304
306 const Span<int> corner_verts,
307 const IndexMask &mask,
308 IndexMaskMemory &memory,
309 MutableSpan<int> r_originals)
310{
311 Array<int> ordered_corner_verts(corner_verts.size());
312 mask.foreach_index(
313 [&](const int face_i) {
314 const IndexRange face = faces[face_i];
315 MutableSpan<int> ordered_face_verts = ordered_corner_verts.as_mutable_span().slice(face);
316 /* Order by the smallest index, then the smallest adjacent index this ensures:
317 * - Faces are only considered duplicates when they share vertices & edges.
318 * - Faces winding in opposite directions are considered duplicates.
319 * See: #150842. */
320 Span<int> face_verts = corner_verts.slice(face);
321 const int face_verts_num = face_verts.size();
322 int i_min = 0;
323 for (int i = 1; i < face_verts_num; i += 1) {
324 if (face_verts[i] < face_verts[i_min]) {
325 i_min = i;
326 }
327 }
328 /* Allow modulo after subtraction within the `face_verts_num` range. */
329 const int i_min_for_modulo = i_min + face_verts_num;
330 const int i_min_prev = (i_min_for_modulo - 1) % face_verts_num;
331 const int i_min_next = (i_min_for_modulo + 1) % face_verts_num;
332 const int sign = face_verts[i_min_next] < face_verts[i_min_prev] ? 1 : -1;
333 for (int i = 0; i < face_verts_num; i += 1) {
334 ordered_face_verts[i] = face_verts[(i_min_for_modulo + (i * sign)) % face_verts_num];
335 }
336 },
338
339 /* Group faces by their first vertex in the order established above. */
340 Array<int> first_verts(mask.size());
341 mask.foreach_index(
342 [&](const int face_i, const int pos) {
343 first_verts[pos] = ordered_corner_verts[faces[face_i].first()];
344 },
346 /* Compress indices of vertices to avoid empty groups for vertices not used by masked faces. */
347 Array<int> group_indices(mask.size());
348 const int groups_num = array_utils::group_ids_to_indices(
349 first_verts, first_verts.index_range(), group_indices);
350 Array<int> offset_data;
351 Array<int> index_data;
352 const OffsetIndices faces_by_first_vert =
354 group_indices, groups_num, offset_data, index_data, mask)
355 .offsets;
356
357 Array<bool> duplicate_faces(faces.size(), false);
358 threading::parallel_for(faces_by_first_vert.index_range(), 1024, [&](const IndexRange range) {
359 for (const int group_index : range) {
360 MutableSpan<int> group = index_data.as_mutable_span().slice(
361 faces_by_first_vert[group_index]);
362 if (group.size() < 2) {
363 continue;
364 }
365 /* After sorting by the ordered vertices, duplicates are contiguous and the first
366 * of each group of duplicates has the lowest index. */
367 const auto face_verts = [&](const int face_i) {
368 return ordered_corner_verts.as_span().slice(faces[face_i]);
369 };
370 std::ranges::sort(group, [&](const int a, const int b) {
371 const Span<int> verts_a = face_verts(a);
372 const Span<int> verts_b = face_verts(b);
373 if (verts_a == verts_b) {
374 return a < b;
375 }
376 return std::ranges::lexicographical_compare(verts_a, verts_b);
377 });
378 int original = group[0];
379 for (const int face_i : group.drop_front(1)) {
380 if (face_verts(face_i) != face_verts(original)) {
381 original = face_i;
382 continue;
383 }
384 if (!r_originals.is_empty()) {
385 r_originals[face_i] = original;
386 }
387 duplicate_faces[face_i] = true;
388 }
389 }
390 });
391
392 return IndexMask::from_bools(mask, duplicate_faces, memory);
393}
394
396 const IndexMask &mask,
397 IndexMaskMemory &memory,
398 const bool verbose)
399{
400 const OffsetIndices<int> faces(mesh.face_offsets(), offset_indices::NoSortCheck());
401 if (!verbose) {
402 return find_duplicate_faces(faces, mesh.corner_verts(), mask, memory);
403 }
404 Array<int> originals(faces.size());
405 const IndexMask duplicate_faces = find_duplicate_faces(
406 faces, mesh.corner_verts(), mask, memory, originals);
407 ErrorMessages errors(verbose);
408 duplicate_faces.foreach_index(
409 [&](const int face) { errors.add("Face {} is a duplicate of {}", face, originals[face]); });
410 return duplicate_faces;
411}
412
413static void remove_invalid_faces(Mesh &mesh, const IndexMask &valid_faces)
414{
415 const int valid_faces_num = valid_faces.size();
416 const OffsetIndices<int> old_faces(mesh.face_offsets(), offset_indices::NoSortCheck());
417
418 Vector<int> new_face_offsets(valid_faces_num + 1);
420 old_faces, valid_faces, new_face_offsets);
421
422 for (bke::Attribute &attr : mesh.attribute_storage.wrap()) {
423 const CPPType &type = attribute_type_to_cpp_type(attr.data_type());
424 switch (attr.domain()) {
425 case AttrDomain::Face: {
426 switch (attr.storage_type()) {
428 const auto &src_data = std::get<Attribute::ArrayData>(attr.data());
429 auto dst_data = Attribute::ArrayData::from_uninitialized(type, valid_faces_num);
430 array_utils::gather(GSpan(type, src_data.data, mesh.faces_num),
431 valid_faces,
432 GMutableSpan(type, dst_data.data, valid_faces_num));
433 attr.assign_data(std::move(dst_data));
434 break;
435 }
437 break;
438 }
439 break;
440 }
441 case AttrDomain::Corner: {
442 switch (attr.storage_type()) {
444 const auto &src_data = std::get<Attribute::ArrayData>(attr.data());
445 auto dst_data = Attribute::ArrayData::from_uninitialized(type, new_faces.total_size());
447 old_faces,
448 new_faces,
449 valid_faces,
450 GSpan(type, src_data.data, mesh.corners_num),
451 GMutableSpan(type, dst_data.data, new_faces.total_size()));
452 attr.assign_data(std::move(dst_data));
453 break;
454 }
456 break;
457 }
458 break;
459 }
460 default:
461 break;
462 }
463 }
464
465 for (CustomDataLayer &layer : MutableSpan(mesh.face_data.layers, mesh.face_data.totlayer)) {
466 if (layer.type == CD_ORIGINDEX) {
467 const Span src(static_cast<const int *>(layer.data), mesh.faces_num);
468
469 int *dst_data = MEM_new_array_uninitialized<int>(valid_faces_num, __func__);
470 MutableSpan dst(dst_data, valid_faces_num);
471
472 array_utils::gather(src, valid_faces, dst);
473
474 layer.sharing_info->remove_user_and_delete_if_last();
475 layer.data = dst_data;
476 layer.sharing_info = implicit_sharing::info_for_mem_free(dst_data);
477 }
478 }
479
480 for (CustomDataLayer &layer : MutableSpan(mesh.corner_data.layers, mesh.corner_data.totlayer)) {
481 const eCustomDataType cd_type = eCustomDataType(layer.type);
482 if (ELEM(layer.type,
483 CD_NORMAL,
485 CD_MDISPS,
488 {
489 const size_t elem_size = CustomData_sizeof(cd_type);
490 const void *src = layer.data;
491
492 void *dst = MEM_new_array_uninitialized(new_faces.total_size(), elem_size, __func__);
493
494 valid_faces.foreach_index(
495 [&](const int64_t src_i, const int64_t dst_i) {
497 POINTER_OFFSET(src, elem_size * old_faces[src_i].start()),
498 POINTER_OFFSET(dst, elem_size * new_faces[dst_i].start()),
499 new_faces[dst_i].size());
500 },
502
503 layer.sharing_info->remove_user_and_delete_if_last();
504 layer.data = dst;
506 cd_type, dst, new_faces.total_size());
507 }
508 }
509
510 mesh.faces_num = new_faces.size();
511 mesh.corners_num = new_faces.total_size();
512 mesh.face_offset_indices = new_face_offsets.release().data;
513 mesh.runtime->face_offsets_sharing_info->remove_user_and_delete_if_last();
514 mesh.runtime->face_offsets_sharing_info = implicit_sharing::info_for_mem_free(
515 mesh.face_offset_indices);
516
517 mesh.tag_topology_changed();
518}
519
520static void remove_invalid_edges(Mesh &mesh, const IndexMask &valid_edges)
521{
522 const int valid_edges_num = valid_edges.size();
523
524 for (bke::Attribute &attr : mesh.attribute_storage.wrap()) {
525 if (attr.domain() != AttrDomain::Edge) {
526 continue;
527 }
528 const CPPType &type = attribute_type_to_cpp_type(attr.data_type());
529 switch (attr.storage_type()) {
531 const auto &src_data = std::get<Attribute::ArrayData>(attr.data());
532 auto dst_data = Attribute::ArrayData::from_uninitialized(type, valid_edges_num);
533 array_utils::gather(GSpan(type, src_data.data, mesh.edges_num),
534 valid_edges,
535 GMutableSpan(type, dst_data.data, valid_edges_num));
536 attr.assign_data(std::move(dst_data));
537 break;
538 }
540 break;
541 }
542 }
543
544 for (CustomDataLayer &layer : MutableSpan(mesh.edge_data.layers, mesh.edge_data.totlayer)) {
545 if (layer.type == CD_ORIGINDEX) {
546 const Span src(static_cast<const int *>(layer.data), mesh.edges_num);
547
548 int *dst_data = MEM_new_array_uninitialized<int>(valid_edges_num, __func__);
549 MutableSpan dst(dst_data, valid_edges_num);
550
551 array_utils::gather(src, valid_edges, dst);
552
553 layer.sharing_info->remove_user_and_delete_if_last();
554 layer.data = dst_data;
555 layer.sharing_info = implicit_sharing::info_for_mem_free(dst_data);
556 }
557 }
558
559 mesh.edges_num = valid_edges.size();
560
561 mesh.tag_topology_changed();
562}
563
564static bool validate_vertex_groups(const Mesh &mesh, const bool verbose, Mesh *mesh_mut)
565{
566 const Span<MDeformVert> dverts = mesh.deform_verts();
567 if (dverts.is_empty()) {
568 return true;
569 }
570 const int vertex_groups_num = mesh.vertex_group_names.count();
571 Mutex mutex;
574 threading::parallel_for(dverts.index_range(), 2048, [&](const IndexRange range) {
575 for (const int vert : range) {
576 const MDeformVert &dvert = dverts[vert];
577
578 Vector<std::string> errors;
579 bool invalid = false;
580 Vector<MDeformWeight, 64> fixed_weights;
581 for (const MDeformWeight &dw : Span(dvert.dw, dvert.totweight)) {
582 const uint def_nr = dw.def_nr;
583 if (dw.def_nr >= vertex_groups_num) {
584 invalid = true;
585 if (verbose) {
586 std::lock_guard lock(mutex);
587 errors.append(fmt::format("Vertex {} has invalid deform group {}", vert, def_nr));
588 }
589 continue;
590 }
591 if (!std::isfinite(dw.weight)) {
592 invalid = true;
593 if (verbose) {
594 std::lock_guard lock(mutex);
595 errors.append(fmt::format(
596 "Vertex {} deform group {} has invalid weight {}", vert, def_nr, dw.weight));
597 }
598 if (mesh_mut) {
599 fixed_weights.append({def_nr, 0.0f});
600 }
601 continue;
602 }
603 if (dw.weight < 0.0f || dw.weight > 1.0f) {
604 invalid = true;
605 if (verbose) {
606 std::lock_guard lock(mutex);
607 errors.append(fmt::format(
608 "Vertex {} deform group {} has invalid weight {}", vert, def_nr, dw.weight));
609 }
610 if (mesh_mut) {
611 fixed_weights.append({def_nr, std::clamp(dw.weight, 0.0f, 1.0f)});
612 }
613 continue;
614 }
615 if (mesh_mut) {
616 fixed_weights.append(dw);
617 }
618 }
619
620 if (invalid) {
621 std::lock_guard lock(mutex);
622 all_errors.append({vert, std::move(errors)});
623 replacements.append({vert, std::move(fixed_weights)});
624 }
625 }
626 });
627 if (replacements.is_empty()) {
628 return true;
629 }
630 if (verbose) {
631 for (const auto &[vert, errors] : all_errors) {
632 for (const std::string &error : errors) {
633 CLOG_ERROR(&LOG, "%s", error.c_str());
634 }
635 }
636 }
637 if (mesh_mut) {
638 MutableSpan<MDeformVert> dverts = mesh_mut->deform_verts_for_write();
639 for (auto &[vert, weights] : replacements) {
640 MEM_delete(dverts[vert].dw);
641 dverts[vert].totweight = weights.size();
642 dverts[vert].dw = weights.release().data;
643 }
644 }
645 return false;
646}
647
649 const bool only_check_negative,
650 const bool verbose,
651 Mesh *mesh_mut)
652{
653 const IndexRange materials_range(only_check_negative ? std::numeric_limits<int>::max() :
654 std::max(int(mesh.totcol), 1));
655 const bke::AttributeAccessor attributes = mesh.attributes();
656 const VArray material_indices = *attributes.lookup<int>("material_index", bke::AttrDomain::Face);
657 if (!material_indices) {
658 return true;
659 }
660 if (const std::optional<int> index = material_indices.get_if_single()) {
661 if (!materials_range.contains(*index)) {
662 if (mesh_mut) {
663 mesh_mut->attributes_for_write().remove("material_index");
664 }
665 return false;
666 }
667 return true;
668 }
669 const VArraySpan<int> material_indices_span(material_indices);
670 IndexMaskMemory memory;
671 const IndexMask invalid_indices = IndexMask::from_predicate(
672 material_indices.index_range(), memory, [&](const int face) {
673 return !materials_range.contains(material_indices_span[face]);
674 });
675 if (invalid_indices.is_empty()) {
676 return true;
677 }
678 if (verbose) {
679 invalid_indices.foreach_index([&](const int face) {
680 CLOG_ERROR(&LOG, "Face %d has invalid material index %d", face, material_indices_span[face]);
681 });
682 }
683 if (mesh_mut) {
684 bke::MutableAttributeAccessor attributes = mesh_mut->attributes_for_write();
685 bke::SpanAttributeWriter material_indices = attributes.lookup_for_write_span<int>(
686 "material_index");
687 index_mask::masked_fill(material_indices.span, 0, invalid_indices);
688 material_indices.finish();
690 }
691 return false;
692}
693
694static bool validate_selection_history(const Mesh &mesh, const bool verbose, Mesh *mesh_mut)
695{
696 if (!mesh.mselect) {
697 return true;
698 }
699 const Span<MSelect> mselect(mesh.mselect, mesh.totselect);
700 IndexMaskMemory memory;
701 const IndexMask invalid = IndexMask::from_predicate(
702 mselect.index_range(), memory, [&](const int i) {
703 if (mselect[i].index < 0) {
704 return true;
705 }
706 const int domain_size = [&]() {
707 switch (mselect[i].type) {
708 case ME_VSEL:
709 return mesh.verts_num;
710 case ME_ESEL:
711 return mesh.edges_num;
712 case ME_FSEL:
713 return mesh.faces_num;
714 }
715 return 0;
716 }();
717 if (mselect[i].index >= domain_size) {
718 return true;
719 }
720 return false;
721 });
722 if (invalid.is_empty()) {
723 return true;
724 }
725
726 if (verbose) {
727 invalid.foreach_index([&](const int i) {
729 "Selection element (%d, %d) has invalid index, must not be negative",
730 mselect[i].type,
731 mselect[i].index);
732 });
733 }
734 if (mesh_mut) {
735 MEM_SAFE_DELETE(mesh_mut->mselect);
736 }
737
738 return false;
739}
740
742 const int floats_per_item,
743 IndexMaskMemory &memory)
744{
745 if (floats_per_item == 0) {
746 return {};
747 }
748 const int num_items = values.size() / floats_per_item;
749
750 return IndexMask::from_predicate(IndexRange(num_items), memory, [&](const int64_t index) {
751 const Span<float> item_floats = values.slice(index * floats_per_item, floats_per_item);
752 return std::any_of(item_floats.begin(), item_floats.end(), [](const float value) {
753 return !std::isfinite(value);
754 });
755 });
756}
757
759 const int floats_per_item,
760 const bool verbose,
761 bool &all_attributes_valid,
762 Mesh *mesh_mut)
763{
764 const GVArraySpan span = *iter.get();
765 const Span<float> float_span(static_cast<const float *>(span.data()),
766 span.size_in_bytes() / sizeof(float));
767 IndexMaskMemory memory;
768 const IndexMask invalid = get_invalid_float_mask(float_span, floats_per_item, memory);
769 if (invalid.is_empty()) {
770 return;
771 }
772 if (verbose) {
773 print_error_with_indices(invalid, "Attribute {} has invalid values", iter.name);
774 }
775 all_attributes_valid = false;
776 if (mesh_mut) {
777 bke::MutableAttributeAccessor attributes = mesh_mut->attributes_for_write();
779 const CPPType &type = attr.span.type();
780 type.fill_assign_indices(type.default_value(), attr.span.data(), invalid);
781 attr.finish();
782 }
783}
784
786 const bool verbose,
787 bool &all_attributes_valid,
788 Mesh *mesh_mut)
789{
790 const VArraySpan<bool> span = *iter.get<bool>();
791 const Span<int8_t> int_span = span.cast<int8_t>();
792 IndexMaskMemory memory;
793 const IndexMask invalid = IndexMask::from_predicate(
794 int_span.index_range(), memory, [&](const int i) { return !ELEM(int_span[i], 0, 1); });
795 if (invalid.is_empty()) {
796 return;
797 }
798 if (verbose) {
799 print_error_with_indices(invalid, "Attribute {} has invalid values", iter.name);
800 }
801 all_attributes_valid = false;
802 if (mesh_mut) {
803 bke::MutableAttributeAccessor attributes = mesh_mut->attributes_for_write();
804 bke::SpanAttributeWriter<bool> attr = attributes.lookup_for_write_span<bool>(iter.name);
805 index_mask::masked_fill(attr.span, true, invalid);
806 attr.finish();
807 }
808}
809
810static bool validate_generic_attributes(const Mesh &mesh, const bool verbose, Mesh *mesh_mut)
811{
812 bool all_attributes_valid = true;
813 mesh.attributes().foreach_attribute([&](const bke::AttributeIter &iter) {
814 switch (iter.data_type) {
815 case AttrType::Bool:
816 validate_bool_attribute(iter, verbose, all_attributes_valid, mesh_mut);
817 break;
818 case AttrType::Int8:
819 break;
821 break;
822 case AttrType::Int32:
823 break;
825 break;
826 case AttrType::Float:
827 validate_float_attribute(iter, 1, verbose, all_attributes_valid, mesh_mut);
828 break;
829 case AttrType::Float2:
830 validate_float_attribute(iter, 2, verbose, all_attributes_valid, mesh_mut);
831 break;
832 case AttrType::Float3:
833 validate_float_attribute(iter, 3, verbose, all_attributes_valid, mesh_mut);
834 break;
836 validate_float_attribute(iter, 4, verbose, all_attributes_valid, mesh_mut);
837 break;
839 validate_float_attribute(iter, 4, verbose, all_attributes_valid, mesh_mut);
840 break;
842 validate_float_attribute(iter, 16, verbose, all_attributes_valid, mesh_mut);
843 break;
845 break;
846 case AttrType::String:
847 break;
848 case AttrType::Float4:
849 validate_float_attribute(iter, 4, verbose, all_attributes_valid, mesh_mut);
850 break;
851 }
852 });
853 return all_attributes_valid;
854}
855
856static bool validate_mdisps(const Mesh &mesh, const bool verbose, Mesh *mesh_mut)
857{
858 const MDisps *mdisps = static_cast<const MDisps *>(
859 CustomData_get_layer(&mesh.corner_data, CD_MDISPS));
860 if (!mdisps) {
861 return true;
862 }
863
864 IndexMaskMemory memory;
865 const IndexMask invalid = IndexMask::from_predicate(
866 IndexRange(mesh.corners_num), memory, [&](const int i) {
867 const Span<float> disps = Span(reinterpret_cast<const float3 *>(mdisps[i].disps),
868 mdisps[i].totdisp)
869 .cast<float>();
870 return std::any_of(
871 disps.begin(), disps.end(), [&](const float &v) { return !std::isfinite(v); });
872 });
873
874 if (invalid.is_empty()) {
875 return true;
876 }
877
878 if (verbose) {
879 print_error_with_indices(invalid, "Multires displacement has invalid values");
880 }
881
882 if (mesh_mut) {
883 if (MDisps *mdisp_mut = static_cast<MDisps *>(
884 CustomData_get_layer_for_write(&mesh_mut->corner_data, CD_MDISPS, mesh.corners_num)))
885 {
886 invalid.foreach_index(
887 [&](const int i) {
888 MutableSpan<float> disps = MutableSpan(reinterpret_cast<float3 *>(mdisp_mut[i].disps),
889 mdisp_mut[i].totdisp)
890 .cast<float>();
891 for (float &disp_component : disps) {
892 disp_component = std::isfinite(disp_component) ? disp_component : 0.0f;
893 }
894 },
895 exec_mode::grain_size(512));
896 }
897 }
898 return false;
899}
900
901static bool mesh_validate_impl(const Mesh &mesh,
902 const bool verbose,
903 const bool allow_missing_edges,
904 Mesh *mesh_mut)
905{
906 IndexMaskMemory memory;
907
908 IndexMask valid_edges(mesh.edges_num);
909
910 const IndexMask edges_bad_verts = find_edges_bad_verts(mesh, memory, verbose);
911 valid_edges = IndexMask::from_difference(valid_edges, edges_bad_verts, memory);
912
913 EdgeMap unique_edges;
914 const IndexMask edges_duplicate = find_edges_duplicates(
915 mesh, valid_edges, memory, verbose, unique_edges);
916 valid_edges = IndexMask::from_difference(valid_edges, edges_duplicate, memory);
917
918 IndexMask valid_faces(mesh.faces_num);
919
920 const IndexMask faces_bad_offsets = find_faces_bad_offsets(mesh, memory, verbose);
921 valid_faces = IndexMask::from_difference(valid_faces, faces_bad_offsets, memory);
922
923 const IndexMask faces_bad_verts = find_faces_bad_verts(mesh, valid_faces, memory, verbose);
924 valid_faces = IndexMask::from_difference(valid_faces, faces_bad_verts, memory);
925
926 const IndexMask faces_duplicate_verts = find_faces_duplicate_verts(
927 mesh, valid_faces, memory, verbose);
928 valid_faces = IndexMask::from_difference(valid_faces, faces_duplicate_verts, memory);
929
930 const IndexMask duplicate_faces = find_duplicate_faces(mesh, valid_faces, memory, verbose);
931 valid_faces = IndexMask::from_difference(valid_faces, duplicate_faces, memory);
932
933 const IndexMask faces_missing_edges = find_faces_missing_edges(
934 mesh, valid_faces, unique_edges, memory, verbose && !allow_missing_edges);
935 const IndexMask valid_and_missing_edge_faces = valid_faces;
936 valid_faces = IndexMask::from_difference(valid_faces, faces_missing_edges, memory);
937
938 const bool any_corner_edges_bad = find_faces_bad_edges(mesh, valid_faces, memory, verbose);
939
940 const int64_t valid_faces_count = allow_missing_edges ? valid_and_missing_edge_faces.size() :
941 valid_faces.size();
942 bool valid = valid_edges.size() == mesh.edges_num && valid_faces_count == mesh.faces_num &&
943 !any_corner_edges_bad;
944
945 if (mesh_mut) {
946 Mesh &mesh = *mesh_mut;
947 if (valid_and_missing_edge_faces.size() < mesh.faces_num) {
948 remove_invalid_faces(mesh, valid_and_missing_edge_faces);
949 }
950
951 const bool any_edges_removed = valid_edges.size() < mesh.edges_num;
952 if (any_edges_removed) {
953 remove_invalid_edges(mesh, valid_edges);
954 }
955
956 /* Regenerate edges if edges are missing or corner edges are bad. */
957 if (any_corner_edges_bad || any_edges_removed || !faces_missing_edges.is_empty()) {
958 mesh_calc_edges(mesh, true, false);
959 }
960 }
961
962 valid &= validate_vertex_groups(mesh, verbose, mesh_mut);
963 valid &= validate_material_indices(mesh, true, verbose, mesh_mut);
964 valid &= validate_selection_history(mesh, verbose, mesh_mut);
965 valid &= validate_generic_attributes(mesh, verbose, mesh_mut);
966 valid &= validate_mdisps(mesh, verbose, mesh_mut);
967
968 if (valid) {
969 return true;
970 }
971
972 if (mesh_mut) {
974 }
975
976 return false;
977}
978
979bool mesh_validate(Mesh &mesh, const bool verbose, const bool allow_missing_edges)
980{
981 if (verbose) {
982 CLOG_INFO(&LOG, "Validating Mesh: %s", mesh.id.name + 2);
983 }
984 return mesh_validate_impl(mesh, verbose, allow_missing_edges, &mesh);
985}
986
987bool mesh_is_valid(const Mesh &mesh, const bool verbose)
988{
989 return mesh_validate_impl(mesh, verbose, false, nullptr);
990}
991
993{
994 return validate_material_indices(mesh, false, false, &mesh);
995}
996
998{
999 const IndexMask valid_faces(mesh.faces().size());
1000 return find_faces_duplicate_verts(mesh, valid_faces, memory, false);
1001}
1002
1003} // namespace bke
1004} // namespace blender
CustomData interface, see also DNA_customdata_types.h.
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_INFO(clg_ref,...)
Definition CLG_log.h:190
volatile int lock
#define ELEM(...)
#define POINTER_OFFSET(v, ofs)
MutableSpan< T > as_mutable_span()
Definition BLI_array.hh:259
IndexRange index_range() const
Definition BLI_array.hh:371
void fill_assign_indices(const void *value, void *dst, const IndexMask &mask) const
const void * default_value() const
const CPPType & type() const
int64_t size_in_bytes() const
const void * data() const
static IndexMask from_predicate(const IndexMask &universe, LinearAllocator<> &memory, Fn &&predicate, exec_mode::Mode mode=exec_mode::parallel)
static IndexMask from_bools(Span< bool > bools, LinearAllocator<> &memory)
static IndexMask from_difference(const IndexMask &mask_a, const IndexMask &mask_b, LinearAllocator<> &memory)
static IndexMask from_bits(BitSpan bits, LinearAllocator<> &memory)
static IndexMask from_batch_predicate(const IndexMask &universe, LinearAllocator<> &memory, FunctionRef< int64_t(const IndexMaskSegment &universe_segment, IndexRangesBuilder< int16_t > &builder)> batch_predicate, exec_mode::Mode mode=exec_mode::parallel)
constexpr IndexRange()=default
constexpr bool contains(int64_t value) const
bool add(const Key &key)
Definition BLI_set.hh:248
constexpr Span slice(int64_t start, int64_t size) const
Definition BLI_span.hh:141
constexpr const T & first() const
Definition BLI_span.hh:319
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr const T & last(const int64_t n=0) const
Definition BLI_span.hh:329
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
std::optional< T > get_if_single() const
IndexRange index_range() const
bool add(const Key &key)
int64_t index_of(const Key &key) const
bool contains(const Key &key) const
void append(const T &value)
VectorData< T, Allocator > release()
GAttributeReader lookup(const StringRef name) const
GAttributeReader get() const
void add(fmt::format_string< T... > fmt, T &&...args)
ErrorMessages(const bool verbose)
void add(std::string message)
Vector< std::string > messages
GSpanAttributeWriter lookup_for_write_span(StringRef name)
Span< NewT > constexpr cast() const
void foreach_index(Fn &&fn, Mode mode=exec_mode::serial) const
#define index(i)
#define layer
constexpr T sign(T) RET
#define LOG(level)
Definition log.h:97
ccl_device_inline float2 mask(const MaskType mask, const float2 a)
#define T
void gather(const GVArray &src, const IndexMask &indices, GMutableSpan dst, exec_mode::Mode mode=exec_mode::parallel)
int group_ids_to_indices(Span< int > ids, const IndexMask &mask, MutableSpan< int > r_group_indices, Vector< int > *r_first_indices=nullptr)
void gather_group_to_group(OffsetIndices< int > src_offsets, OffsetIndices< int > dst_offsets, const IndexMask &selection, GSpan src, GMutableSpan dst)
int face_corner_next(const IndexRange face, const int corner)
Definition BKE_mesh.hh:315
static bool validate_vertex_groups(const Mesh &mesh, const bool verbose, Mesh *mesh_mut)
bool mesh_validate_material_indices(Mesh &mesh)
IndexMask mesh_find_faces_duplicate_verts(const Mesh &mesh, IndexMaskMemory &memory)
static bool validate_selection_history(const Mesh &mesh, const bool verbose, Mesh *mesh_mut)
static bool mesh_validate_impl(const Mesh &mesh, const bool verbose, const bool allow_missing_edges, Mesh *mesh_mut)
bool mesh_is_valid(const Mesh &mesh, bool verbose=true)
static IndexMask get_invalid_float_mask(const Span< float > values, const int floats_per_item, IndexMaskMemory &memory)
static IndexMask find_faces_bad_offsets(const Mesh &mesh, IndexMaskMemory &memory, const bool verbose)
static bool validate_generic_attributes(const Mesh &mesh, const bool verbose, Mesh *mesh_mut)
static IndexMask find_faces_missing_edges(const Mesh &mesh, const IndexMask &mask, const EdgeMap &unique_edges, IndexMaskMemory &memory, const bool verbose)
IndexMask find_duplicate_faces(OffsetIndices< int > faces, Span< int > corner_verts, const IndexMask &mask, IndexMaskMemory &memory, MutableSpan< int > r_originals={})
static bool validate_mdisps(const Mesh &mesh, const bool verbose, Mesh *mesh_mut)
static IndexMask find_faces_bad_verts(const Mesh &mesh, const IndexMask &mask, IndexMaskMemory &memory, const bool verbose)
static void remove_invalid_edges(Mesh &mesh, const IndexMask &valid_edges)
void mesh_calc_edges(Mesh &mesh, bool keep_existing_edges, bool select_new_edges)
static bool find_faces_bad_edges(const Mesh &mesh, const IndexMask &mask, IndexMaskMemory &memory, const bool verbose)
bool mesh_validate(Mesh &mesh, bool verbose=false, bool allow_missing_edges=false)
static IndexMask find_edges_duplicates(const Mesh &mesh, const IndexMask &mask, IndexMaskMemory &memory, const bool verbose, EdgeMap &unique_edges)
static void remove_invalid_faces(Mesh &mesh, const IndexMask &valid_faces)
static void print_error_with_indices(const IndexMask &mask, fmt::format_string< T... > fmt, T &&...args)
static IndexMask find_edges_bad_verts(const Mesh &mesh, IndexMaskMemory &memory, const bool verbose)
static void validate_float_attribute(const bke::AttributeIter &iter, const int floats_per_item, const bool verbose, bool &all_attributes_valid, Mesh *mesh_mut)
VectorSet< OrderedEdge, 32, DefaultProbingStrategy, DefaultHash< OrderedEdge >, DefaultEquality< OrderedEdge >, SimpleVectorSetSlot< OrderedEdge, int >, GuardedAllocator > EdgeMap
static bool validate_material_indices(const Mesh &mesh, const bool only_check_negative, const bool verbose, Mesh *mesh_mut)
static IndexMask find_faces_duplicate_verts(const Mesh &mesh, const IndexMask &mask, IndexMaskMemory &memory, const bool verbose)
static void validate_bool_attribute(const bke::AttributeIter &iter, const bool verbose, bool &all_attributes_valid, Mesh *mesh_mut)
const CPPType & attribute_type_to_cpp_type(AttrType type)
constexpr ParallelGrainSize grain_size(int grain_size)
const ImplicitSharingInfo * info_for_mem_free(T *data)
void masked_fill(MutableSpan< T > data, const T &value, const IndexMask &mask)
GroupedSpan< int > build_groups_from_indices(Span< int > indices, int groups_num, Array< int > &offset_data, Array< int > &index_data)
OffsetIndices< int > gather_selected_offsets(OffsetIndices< int > src_offsets, const IndexMask &selection, int start_offset, MutableSpan< int > dst_offsets)
void parallel_for(const IndexRange range, const int64_t grain_size, const Function &function, const TaskSizeHints &size_hints=detail::TaskSizeHints_Static(1))
Definition BLI_task.hh:69
BMesh Iterators.
__int64 int64_t
Definition BKE_text.h:90
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
const ImplicitSharingInfo * CustomData_make_layer_sharing_info(eCustomDataType type, const void *data, int totelem)
int CustomData_sizeof(eCustomDataType type)
VecBase< int32_t, 2 > int2
void DEG_id_tag_update(ID *id, unsigned int flags)
const void * CustomData_get_layer(const CustomData *data, eCustomDataType type)
PythonProbingStrategy<> DefaultProbingStrategy
std::mutex Mutex
Definition BLI_mutex.hh:51
@ ID_RECALC_GEOMETRY_ALL_MODES
Definition DNA_ID.h:1183
static CLG_LogRef LOG
Definition logging.cpp:12
void * CustomData_get_layer_for_write(CustomData *data, eCustomDataType type, int totelem)
signed char int8_t
Definition BKE_text.h:76
void vert(const int vert_id, float4 &position)
static ArrayData from_uninitialized(const CPPType &type, int64_t domain_size)