Files
test2/source/blender/modifiers/intern/MOD_boolean.cc

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

706 lines
22 KiB
C++
Raw Normal View History

/* SPDX-FileCopyrightText: 2005 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup modifiers
*/
#include <cstdio>
#include "BLI_utildefines.h"
#include "BLI_array.hh"
#include "BLI_math_geom.h"
#include "BLI_math_matrix.h"
#include "BLI_math_matrix_types.hh"
#include "BLI_vector.hh"
#include "BLI_vector_set.hh"
#include "BLT_translation.h"
#include "DNA_collection_types.h"
#include "DNA_defaults.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "DNA_screen_types.h"
#include "BKE_collection.h"
#include "BKE_context.h"
#include "BKE_global.h" /* only to check G.debug */
#include "BKE_lib_id.h"
#include "BKE_lib_query.h"
#include "BKE_material.h"
#include "BKE_mesh.hh"
#include "BKE_mesh_boolean_convert.hh"
#include "BKE_mesh_wrapper.hh"
#include "BKE_modifier.h"
#include "UI_interface.hh"
#include "UI_resources.hh"
#include "RNA_access.hh"
#include "RNA_prototypes.h"
#include "MOD_ui_common.hh"
#include "MOD_util.hh"
#include "DEG_depsgraph_query.hh"
2018-05-24 15:26:02 +02:00
#include "MEM_guardedalloc.h"
Geometry: add utility to check for bad geometry element index dependence Sometimes .blend files have compatibility issues between Blender versions, because .blend files depended on the specific order of geometry elements generated by some nodes/modifiers (#112746, #113018). While we make guarantees about the order in some places, that is relatively rare, because it makes future improvements much harder. The functionality in this patch makes it easier for users to notice when they depend on things that are not expected to be stable between Blender builds. This is achieved by adding a new global flag which indicates whether some algorithms should randomize their output. The functionality can be toggled on or off by searching for `Set Geometry Randomization`. If there are no differences (or acceptable minor ones) when the flag is on or off, one can be reasonably sure that one does not on unspecified behavior (can't be 100% sure though, because randomization might be missing in some places). If there are big differences, one should consider fixing the file before it comes to an actual breakage in the next Blender version. Currently, the setting is only available when `Developer Extras` is turned on, because the setting is in no menu. With this patch, if we get bug reports with compatibility issues caused by depending on indices, one of the following three cases should always apply: * We actually accidentally broke something, which requires a fix commit. * Turning on geometry randomization shows that the .blend file depends on things it shouldn't depend on. In this case the user has to fix the file. * We are missing geometry randomization somewhere, which requires a fix commit. Pull Request: https://projects.blender.org/blender/blender/pulls/113030
2023-09-29 21:44:36 +02:00
#include "GEO_randomize.hh"
#include "bmesh.h"
#include "bmesh_tools.h"
#include "tools/bmesh_boolean.h"
#include "tools/bmesh_intersect.h"
// #define DEBUG_TIME
2015-12-12 01:30:03 +11:00
#ifdef DEBUG_TIME
# include "BLI_timeit.hh"
2015-12-12 01:30:03 +11:00
#endif
using blender::Array;
Mesh: Move positions to a generic attribute **Changes** As described in T93602, this patch removes all use of the `MVert` struct, replacing it with a generic named attribute with the name `"position"`, consistent with other geometry types. Variable names have been changed from `verts` to `positions`, to align with the attribute name and the more generic design (positions are not vertices, they are just an attribute stored on the point domain). This change is made possible by previous commits that moved all other data out of `MVert` to runtime data or other generic attributes. What remains is mostly a simple type change. Though, the type still shows up 859 times, so the patch is quite large. One compromise is that now `CD_MASK_BAREMESH` now contains `CD_PROP_FLOAT3`. With the general move towards generic attributes over custom data types, we are removing use of these type masks anyway. **Benefits** The most obvious benefit is reduced memory usage and the benefits that brings in memory-bound situations. `float3` is only 3 bytes, in comparison to `MVert` which was 4. When there are millions of vertices this starts to matter more. The other benefits come from using a more generic type. Instead of writing algorithms specifically for `MVert`, code can just use arrays of vectors. This will allow eliminating many temporary arrays or wrappers used to extract positions. Many possible improvements aren't implemented in this patch, though I did switch simplify or remove the process of creating temporary position arrays in a few places. The design clarity that "positions are just another attribute" brings allows removing explicit copying of vertices in some procedural operations-- they are just processed like most other attributes. **Performance** This touches so many areas that it's hard to benchmark exhaustively, but I observed some areas as examples. * The mesh line node with 4 million count was 1.5x (8ms to 12ms) faster. * The Spring splash screen went from ~4.3 to ~4.5 fps. * The subdivision surface modifier/node was slightly faster RNA access through Python may be slightly slower, since now we need a name lookup instead of just a custom data type lookup for each index. **Future Improvements** * Remove uses of "vert_coords" functions: * `BKE_mesh_vert_coords_alloc` * `BKE_mesh_vert_coords_get` * `BKE_mesh_vert_coords_apply{_with_mat4}` * Remove more hidden copying of positions * General simplification now possible in many areas * Convert more code to C++ to use `float3` instead of `float[3]` * Currently `reinterpret_cast` is used for those C-API functions Differential Revision: https://developer.blender.org/D15982
2023-01-10 00:10:43 -05:00
using blender::float3;
using blender::float4x4;
using blender::IndexRange;
using blender::MutableSpan;
using blender::Span;
using blender::Vector;
using blender::VectorSet;
static void init_data(ModifierData *md)
{
BooleanModifierData *bmd = (BooleanModifierData *)md;
BLI_assert(MEMCMP_STRUCT_AFTER_IS_ZERO(bmd, modifier));
MEMCPY_STRUCT_AFTER(bmd, DNA_struct_default_get(BooleanModifierData), modifier);
}
static bool is_disabled(const Scene * /*scene*/, ModifierData *md, bool /*use_render_params*/)
{
2012-05-06 13:38:33 +00:00
BooleanModifierData *bmd = (BooleanModifierData *)md;
Collection *col = bmd->collection;
if (bmd->flag & eBooleanModifierFlag_Object) {
return !bmd->object || bmd->object->type != OB_MESH;
}
if (bmd->flag & eBooleanModifierFlag_Collection) {
/* The Exact solver tolerates an empty collection. */
return !col && bmd->solver != eBooleanModifierSolver_Exact;
}
return false;
}
static void foreach_ID_link(ModifierData *md, Object *ob, IDWalkFunc walk, void *user_data)
{
BooleanModifierData *bmd = (BooleanModifierData *)md;
walk(user_data, ob, (ID **)&bmd->collection, IDWALK_CB_USER);
walk(user_data, ob, (ID **)&bmd->object, IDWALK_CB_NOP);
}
static void update_depsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
Depsgraph: New dependency graph integration commit This commit integrates the work done so far on the new dependency graph system, where goal was to replace legacy depsgraph with the new one, supporting loads of neat features like: - More granular dependency relation nature, which solves issues with fake cycles in the dependencies. - Move towards all-animatable, by better integration of drivers into the system. - Lay down some basis for upcoming copy-on-write, overrides and so on. The new system is living side-by-side with the previous one and disabled by default, so nothing will become suddenly broken. The way to enable new depsgraph is to pass `--new-depsgraph` command line argument. It's a bit early to consider the system production-ready, there are some TODOs and issues were discovered during the merge period, they'll be addressed ASAP. But it's important to merge, because it's the only way to attract artists to really start testing this system. There are number of assorted documents related on the design of the new system: * http://wiki.blender.org/index.php/User:Aligorith/GSoC2013_Depsgraph#Design_Documents * http://wiki.blender.org/index.php/User:Nazg-gul/DependencyGraph There are also some user-related information online: * http://code.blender.org/2015/02/blender-dependency-graph-branch-for-users/ * http://code.blender.org/2015/03/more-dependency-graph-tricks/ Kudos to everyone who was involved into the project: - Joshua "Aligorith" Leung -- design specification, initial code - Lukas "lukas_t" Toenne -- integrating code into blender, with further fixes - Sergey "Sergey" "Sharybin" -- some mocking around, trying to wrap up the project and so - Bassam "slikdigit" Kurdali -- stressing the new system, reporting all the issues and recording/writing documentation. - Everyone else who i forgot to mention here :)
2015-05-12 15:05:57 +05:00
{
BooleanModifierData *bmd = (BooleanModifierData *)md;
if ((bmd->flag & eBooleanModifierFlag_Object) && bmd->object != nullptr) {
DEG_add_object_relation(ctx->node, bmd->object, DEG_OB_COMP_TRANSFORM, "Boolean Modifier");
DEG_add_object_relation(ctx->node, bmd->object, DEG_OB_COMP_GEOMETRY, "Boolean Modifier");
Depsgraph: New dependency graph integration commit This commit integrates the work done so far on the new dependency graph system, where goal was to replace legacy depsgraph with the new one, supporting loads of neat features like: - More granular dependency relation nature, which solves issues with fake cycles in the dependencies. - Move towards all-animatable, by better integration of drivers into the system. - Lay down some basis for upcoming copy-on-write, overrides and so on. The new system is living side-by-side with the previous one and disabled by default, so nothing will become suddenly broken. The way to enable new depsgraph is to pass `--new-depsgraph` command line argument. It's a bit early to consider the system production-ready, there are some TODOs and issues were discovered during the merge period, they'll be addressed ASAP. But it's important to merge, because it's the only way to attract artists to really start testing this system. There are number of assorted documents related on the design of the new system: * http://wiki.blender.org/index.php/User:Aligorith/GSoC2013_Depsgraph#Design_Documents * http://wiki.blender.org/index.php/User:Nazg-gul/DependencyGraph There are also some user-related information online: * http://code.blender.org/2015/02/blender-dependency-graph-branch-for-users/ * http://code.blender.org/2015/03/more-dependency-graph-tricks/ Kudos to everyone who was involved into the project: - Joshua "Aligorith" Leung -- design specification, initial code - Lukas "lukas_t" Toenne -- integrating code into blender, with further fixes - Sergey "Sergey" "Sharybin" -- some mocking around, trying to wrap up the project and so - Bassam "slikdigit" Kurdali -- stressing the new system, reporting all the issues and recording/writing documentation. - Everyone else who i forgot to mention here :)
2015-05-12 15:05:57 +05:00
}
Collection *col = bmd->collection;
if ((bmd->flag & eBooleanModifierFlag_Collection) && col != nullptr) {
DEG_add_collection_geometry_relation(ctx->node, col, "Boolean Modifier");
}
Depsgraph: New dependency graph integration commit This commit integrates the work done so far on the new dependency graph system, where goal was to replace legacy depsgraph with the new one, supporting loads of neat features like: - More granular dependency relation nature, which solves issues with fake cycles in the dependencies. - Move towards all-animatable, by better integration of drivers into the system. - Lay down some basis for upcoming copy-on-write, overrides and so on. The new system is living side-by-side with the previous one and disabled by default, so nothing will become suddenly broken. The way to enable new depsgraph is to pass `--new-depsgraph` command line argument. It's a bit early to consider the system production-ready, there are some TODOs and issues were discovered during the merge period, they'll be addressed ASAP. But it's important to merge, because it's the only way to attract artists to really start testing this system. There are number of assorted documents related on the design of the new system: * http://wiki.blender.org/index.php/User:Aligorith/GSoC2013_Depsgraph#Design_Documents * http://wiki.blender.org/index.php/User:Nazg-gul/DependencyGraph There are also some user-related information online: * http://code.blender.org/2015/02/blender-dependency-graph-branch-for-users/ * http://code.blender.org/2015/03/more-dependency-graph-tricks/ Kudos to everyone who was involved into the project: - Joshua "Aligorith" Leung -- design specification, initial code - Lukas "lukas_t" Toenne -- integrating code into blender, with further fixes - Sergey "Sergey" "Sharybin" -- some mocking around, trying to wrap up the project and so - Bassam "slikdigit" Kurdali -- stressing the new system, reporting all the issues and recording/writing documentation. - Everyone else who i forgot to mention here :)
2015-05-12 15:05:57 +05:00
/* We need own transformation as well. */
DEG_add_depends_on_transform_relation(ctx->node, "Boolean Modifier");
Depsgraph: New dependency graph integration commit This commit integrates the work done so far on the new dependency graph system, where goal was to replace legacy depsgraph with the new one, supporting loads of neat features like: - More granular dependency relation nature, which solves issues with fake cycles in the dependencies. - Move towards all-animatable, by better integration of drivers into the system. - Lay down some basis for upcoming copy-on-write, overrides and so on. The new system is living side-by-side with the previous one and disabled by default, so nothing will become suddenly broken. The way to enable new depsgraph is to pass `--new-depsgraph` command line argument. It's a bit early to consider the system production-ready, there are some TODOs and issues were discovered during the merge period, they'll be addressed ASAP. But it's important to merge, because it's the only way to attract artists to really start testing this system. There are number of assorted documents related on the design of the new system: * http://wiki.blender.org/index.php/User:Aligorith/GSoC2013_Depsgraph#Design_Documents * http://wiki.blender.org/index.php/User:Nazg-gul/DependencyGraph There are also some user-related information online: * http://code.blender.org/2015/02/blender-dependency-graph-branch-for-users/ * http://code.blender.org/2015/03/more-dependency-graph-tricks/ Kudos to everyone who was involved into the project: - Joshua "Aligorith" Leung -- design specification, initial code - Lukas "lukas_t" Toenne -- integrating code into blender, with further fixes - Sergey "Sergey" "Sharybin" -- some mocking around, trying to wrap up the project and so - Bassam "slikdigit" Kurdali -- stressing the new system, reporting all the issues and recording/writing documentation. - Everyone else who i forgot to mention here :)
2015-05-12 15:05:57 +05:00
}
static Mesh *get_quick_mesh(
Object *ob_self, Mesh *mesh_self, Object *ob_operand_ob, Mesh *mesh_operand_ob, int operation)
{
Mesh *result = nullptr;
if (mesh_self->faces_num == 0 || mesh_operand_ob->faces_num == 0) {
switch (operation) {
case eBooleanModifierOp_Intersect:
result = BKE_mesh_new_nomain(0, 0, 0, 0);
break;
case eBooleanModifierOp_Union:
if (mesh_self->faces_num != 0) {
result = mesh_self;
}
else {
result = (Mesh *)BKE_id_copy_ex(
nullptr, &mesh_operand_ob->id, nullptr, LIB_ID_COPY_LOCALIZE);
float imat[4][4];
float omat[4][4];
invert_m4_m4(imat, ob_self->object_to_world);
mul_m4_m4m4(omat, imat, ob_operand_ob->object_to_world);
Mesh: Move positions to a generic attribute **Changes** As described in T93602, this patch removes all use of the `MVert` struct, replacing it with a generic named attribute with the name `"position"`, consistent with other geometry types. Variable names have been changed from `verts` to `positions`, to align with the attribute name and the more generic design (positions are not vertices, they are just an attribute stored on the point domain). This change is made possible by previous commits that moved all other data out of `MVert` to runtime data or other generic attributes. What remains is mostly a simple type change. Though, the type still shows up 859 times, so the patch is quite large. One compromise is that now `CD_MASK_BAREMESH` now contains `CD_PROP_FLOAT3`. With the general move towards generic attributes over custom data types, we are removing use of these type masks anyway. **Benefits** The most obvious benefit is reduced memory usage and the benefits that brings in memory-bound situations. `float3` is only 3 bytes, in comparison to `MVert` which was 4. When there are millions of vertices this starts to matter more. The other benefits come from using a more generic type. Instead of writing algorithms specifically for `MVert`, code can just use arrays of vectors. This will allow eliminating many temporary arrays or wrappers used to extract positions. Many possible improvements aren't implemented in this patch, though I did switch simplify or remove the process of creating temporary position arrays in a few places. The design clarity that "positions are just another attribute" brings allows removing explicit copying of vertices in some procedural operations-- they are just processed like most other attributes. **Performance** This touches so many areas that it's hard to benchmark exhaustively, but I observed some areas as examples. * The mesh line node with 4 million count was 1.5x (8ms to 12ms) faster. * The Spring splash screen went from ~4.3 to ~4.5 fps. * The subdivision surface modifier/node was slightly faster RNA access through Python may be slightly slower, since now we need a name lookup instead of just a custom data type lookup for each index. **Future Improvements** * Remove uses of "vert_coords" functions: * `BKE_mesh_vert_coords_alloc` * `BKE_mesh_vert_coords_get` * `BKE_mesh_vert_coords_apply{_with_mat4}` * Remove more hidden copying of positions * General simplification now possible in many areas * Convert more code to C++ to use `float3` instead of `float[3]` * Currently `reinterpret_cast` is used for those C-API functions Differential Revision: https://developer.blender.org/D15982
2023-01-10 00:10:43 -05:00
MutableSpan<float3> positions = result->vert_positions_for_write();
for (const int i : positions.index_range()) {
mul_m4_v3(omat, positions[i]);
}
BKE_mesh_tag_positions_changed(result);
}
break;
case eBooleanModifierOp_Difference:
result = mesh_self;
break;
}
}
return result;
}
/* has no meaning for faces, do this so we can tell which face is which */
#define BM_FACE_TAG BM_ELEM_DRAW
/**
* Compare selected/unselected.
*/
static int bm_face_isect_pair(BMFace *f, void * /*user_data*/)
{
return BM_elem_flag_test(f, BM_FACE_TAG) ? 1 : 0;
}
static bool BMD_error_messages(const Object *ob, ModifierData *md)
{
BooleanModifierData *bmd = (BooleanModifierData *)md;
Collection *col = bmd->collection;
bool error_returns_result = false;
const bool operand_collection = (bmd->flag & eBooleanModifierFlag_Collection) != 0;
const bool use_exact = bmd->solver == eBooleanModifierSolver_Exact;
const bool operation_intersect = bmd->operation == eBooleanModifierOp_Intersect;
#ifndef WITH_GMP
/* If compiled without GMP, return a error. */
if (use_exact) {
BKE_modifier_set_error(ob, md, "Compiled without GMP, using fast solver");
error_returns_result = false;
}
#endif
/* If intersect is selected using fast solver, return a error. */
if (operand_collection && operation_intersect && !use_exact) {
BKE_modifier_set_error(ob, md, "Cannot execute, intersect only available using exact solver");
error_returns_result = true;
}
/* If the selected collection is empty and using fast solver, return a error. */
if (operand_collection) {
if (!use_exact && BKE_collection_is_empty(col)) {
BKE_modifier_set_error(ob, md, "Cannot execute, fast solver and empty collection");
error_returns_result = true;
}
/* If the selected collection contain non mesh objects, return a error. */
if (col) {
FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (col, operand_ob) {
if (operand_ob->type != OB_MESH) {
BKE_modifier_set_error(
ob, md, "Cannot execute, the selected collection contains non mesh objects");
error_returns_result = true;
}
}
FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
}
}
return error_returns_result;
}
static BMesh *BMD_mesh_bm_create(
Mesh *mesh, Object *object, Mesh *mesh_operand_ob, Object *operand_ob, bool *r_is_flip)
{
#ifdef DEBUG_TIME
SCOPED_TIMER(__func__);
#endif
*r_is_flip = (is_negative_m4(object->object_to_world) !=
is_negative_m4(operand_ob->object_to_world));
const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_ME(mesh, mesh_operand_ob);
BMeshCreateParams bmesh_create_params{};
BMesh *bm = BM_mesh_create(&allocsize, &bmesh_create_params);
/* Keep `mesh` first, needed so active layers are set based on `mesh` not `mesh_operand_ob`,
* otherwise the wrong active render layer is used, see #92384.
*
* NOTE: while initializing customer data layers the is not essential,
* it avoids the overhead of having to re-allocate #BMHeader.data when the 2nd mesh is added
* (if it contains additional custom-data layers). */
const Mesh *mesh_array[2] = {mesh, mesh_operand_ob};
BM_mesh_copy_init_customdata_from_mesh_array(bm, mesh_array, ARRAY_SIZE(mesh_array), &allocsize);
BMeshFromMeshParams bmesh_from_mesh_params{};
bmesh_from_mesh_params.calc_face_normal = true;
bmesh_from_mesh_params.calc_vert_normal = true;
BM_mesh_bm_from_me(bm, mesh_operand_ob, &bmesh_from_mesh_params);
if (UNLIKELY(*r_is_flip)) {
const int cd_loop_mdisp_offset = CustomData_get_offset(&bm->ldata, CD_MDISPS);
BMIter iter;
BMFace *efa;
BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
BM_face_normal_flip_ex(bm, efa, cd_loop_mdisp_offset, true);
}
}
BM_mesh_bm_from_me(bm, mesh, &bmesh_from_mesh_params);
return bm;
}
static void BMD_mesh_intersection(BMesh *bm,
ModifierData *md,
const ModifierEvalContext *ctx,
Mesh *mesh_operand_ob,
Object *object,
Object *operand_ob,
bool is_flip)
{
#ifdef DEBUG_TIME
SCOPED_TIMER(__func__);
#endif
BooleanModifierData *bmd = (BooleanModifierData *)md;
2023-07-09 21:22:31 +10:00
/* Main BMesh intersection setup. */
/* Create tessellation & intersect. */
const int looptris_tot = poly_to_tri_count(bm->totface, bm->totloop);
BMLoop *(*looptris)[3] = (BMLoop * (*)[3])
MEM_malloc_arrayN(looptris_tot, sizeof(*looptris), __func__);
BM_mesh_calc_tessellation_beauty(bm, looptris);
/* postpone this until after tessellating
* so we can use the original normals before the vertex are moved */
{
BMIter iter;
int i;
const int i_verts_end = mesh_operand_ob->totvert;
const int i_faces_end = mesh_operand_ob->faces_num;
float imat[4][4];
float omat[4][4];
invert_m4_m4(imat, object->object_to_world);
mul_m4_m4m4(omat, imat, operand_ob->object_to_world);
BMVert *eve;
i = 0;
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
mul_m4_v3(omat, eve->co);
if (++i == i_verts_end) {
break;
}
}
/* we need face normals because of 'BM_face_split_edgenet'
* we could calculate on the fly too (before calling split). */
float nmat[3][3];
copy_m3_m4(nmat, omat);
invert_m3(nmat);
if (UNLIKELY(is_flip)) {
negate_m3(nmat);
}
Array<short> material_remap(operand_ob->totcol ? operand_ob->totcol : 1);
/* Using original (not evaluated) object here since we are writing to it. */
/* XXX Pretty sure comment above is fully wrong now with CoW & co ? */
BKE_object_material_remap_calc(ctx->object, operand_ob, material_remap.data());
BMFace *efa;
i = 0;
BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
mul_transposed_m3_v3(nmat, efa->no);
normalize_v3(efa->no);
/* Temp tag to test which side split faces are from. */
BM_elem_flag_enable(efa, BM_FACE_TAG);
/* remap material */
if (LIKELY(efa->mat_nr < operand_ob->totcol)) {
efa->mat_nr = material_remap[efa->mat_nr];
}
if (++i == i_faces_end) {
break;
}
}
}
/* not needed, but normals for 'dm' will be invalid,
* currently this is ok for 'BM_mesh_intersect' */
// BM_mesh_normals_update(bm);
bool use_separate = false;
bool use_dissolve = true;
bool use_island_connect = true;
/* change for testing */
if (G.debug & G_DEBUG) {
use_separate = (bmd->bm_flag & eBooleanModifierBMeshFlag_BMesh_Separate) != 0;
use_dissolve = (bmd->bm_flag & eBooleanModifierBMeshFlag_BMesh_NoDissolve) == 0;
use_island_connect = (bmd->bm_flag & eBooleanModifierBMeshFlag_BMesh_NoConnectRegions) == 0;
}
BM_mesh_intersect(bm,
looptris,
looptris_tot,
bm_face_isect_pair,
nullptr,
false,
use_separate,
use_dissolve,
use_island_connect,
false,
false,
bmd->operation,
bmd->double_threshold);
MEM_freeN(looptris);
}
#ifdef WITH_GMP
Fix T99592: Exact Boolean: Skip empty materials, add index-based option **Empty Slot Fix** Currently the boolean modifier transfers the default material from meshes with no materials and empty material slots to the faces on the base mesh. I added this in a2d59b2dac9e for the sake of consistency, but the behavior is actually not useful at all. The default empty material isn't chosen by users, it just signifies "nothing," so when it replaces a material chosen by users, it feels like a bug. This commit corrects that behavior by only transferring materials from non-empty material slots. The implementation is now consistent between exact mode of the boolean modifier and the geometry node. **Index-Based Option** "Index-based" is the new default material method for the boolean modifier, to access the old behavior from before the breaking commit. a2d59b2dac9e actually broke some Boolean workflows fundamentally, since it was important to set up matching slot indices on each operand. That isn't the cleanest workflow, and it breaks when materials change procedurally, but historically that hasn't been a problem. The "transfer" behavior transfers all materials except for empty slots, but the fundamental problem is that there isn't a good way to specify the result materials besides using the slot indices. Even then, the transfer option is a bit more intuitive and useful for some simpler situations, and it allows accessing the behavior that has been in 3.2 and 3.3 for a long time, so it's also left in as an option. The geometry node doesn't get this new option, in the hope that we'll find a better solution in the future. Differential Revision: https://developer.blender.org/D16187
2022-11-28 12:42:08 -06:00
/* Get a mapping from material slot numbers in the src_ob to slot numbers in the dst_ob.
* If a material doesn't exist in the dst_ob, the mapping just goes to the same slot
* or to zero if there aren't enough slots in the destination. */
static Array<short> get_material_remap_index_based(Object *dest_ob, Object *src_ob)
{
int n = src_ob->totcol;
if (n <= 0) {
n = 1;
}
Array<short> remap(n);
BKE_object_material_remap_calc(dest_ob, src_ob, remap.data());
return remap;
}
/* Get a mapping from material slot numbers in the source geometry to slot numbers in the result
* geometry. The material is added to the result geometry if it doesn't already use it. */
Fix T99592: Exact Boolean: Skip empty materials, add index-based option **Empty Slot Fix** Currently the boolean modifier transfers the default material from meshes with no materials and empty material slots to the faces on the base mesh. I added this in a2d59b2dac9e for the sake of consistency, but the behavior is actually not useful at all. The default empty material isn't chosen by users, it just signifies "nothing," so when it replaces a material chosen by users, it feels like a bug. This commit corrects that behavior by only transferring materials from non-empty material slots. The implementation is now consistent between exact mode of the boolean modifier and the geometry node. **Index-Based Option** "Index-based" is the new default material method for the boolean modifier, to access the old behavior from before the breaking commit. a2d59b2dac9e actually broke some Boolean workflows fundamentally, since it was important to set up matching slot indices on each operand. That isn't the cleanest workflow, and it breaks when materials change procedurally, but historically that hasn't been a problem. The "transfer" behavior transfers all materials except for empty slots, but the fundamental problem is that there isn't a good way to specify the result materials besides using the slot indices. Even then, the transfer option is a bit more intuitive and useful for some simpler situations, and it allows accessing the behavior that has been in 3.2 and 3.3 for a long time, so it's also left in as an option. The geometry node doesn't get this new option, in the hope that we'll find a better solution in the future. Differential Revision: https://developer.blender.org/D16187
2022-11-28 12:42:08 -06:00
static Array<short> get_material_remap_transfer(Object &object,
const Mesh &mesh,
VectorSet<Material *> &materials)
{
const int material_num = mesh.totcol;
Array<short> map(material_num);
for (const int i : IndexRange(material_num)) {
Material *material = BKE_object_material_get_eval(&object, i + 1);
Fix T99592: Exact Boolean: Skip empty materials, add index-based option **Empty Slot Fix** Currently the boolean modifier transfers the default material from meshes with no materials and empty material slots to the faces on the base mesh. I added this in a2d59b2dac9e for the sake of consistency, but the behavior is actually not useful at all. The default empty material isn't chosen by users, it just signifies "nothing," so when it replaces a material chosen by users, it feels like a bug. This commit corrects that behavior by only transferring materials from non-empty material slots. The implementation is now consistent between exact mode of the boolean modifier and the geometry node. **Index-Based Option** "Index-based" is the new default material method for the boolean modifier, to access the old behavior from before the breaking commit. a2d59b2dac9e actually broke some Boolean workflows fundamentally, since it was important to set up matching slot indices on each operand. That isn't the cleanest workflow, and it breaks when materials change procedurally, but historically that hasn't been a problem. The "transfer" behavior transfers all materials except for empty slots, but the fundamental problem is that there isn't a good way to specify the result materials besides using the slot indices. Even then, the transfer option is a bit more intuitive and useful for some simpler situations, and it allows accessing the behavior that has been in 3.2 and 3.3 for a long time, so it's also left in as an option. The geometry node doesn't get this new option, in the hope that we'll find a better solution in the future. Differential Revision: https://developer.blender.org/D16187
2022-11-28 12:42:08 -06:00
map[i] = material ? materials.index_of_or_add(material) : -1;
}
return map;
}
static Mesh *exact_boolean_mesh(BooleanModifierData *bmd,
const ModifierEvalContext *ctx,
Mesh *mesh)
{
Vector<const Mesh *> meshes;
Vector<float4x4 *> obmats;
Vector<Array<short>> material_remaps;
# ifdef DEBUG_TIME
SCOPED_TIMER(__func__);
# endif
if ((bmd->flag & eBooleanModifierFlag_Object) && bmd->object == nullptr) {
return mesh;
}
meshes.append(mesh);
obmats.append((float4x4 *)&ctx->object->object_to_world);
material_remaps.append({});
Fix T99592: Exact Boolean: Skip empty materials, add index-based option **Empty Slot Fix** Currently the boolean modifier transfers the default material from meshes with no materials and empty material slots to the faces on the base mesh. I added this in a2d59b2dac9e for the sake of consistency, but the behavior is actually not useful at all. The default empty material isn't chosen by users, it just signifies "nothing," so when it replaces a material chosen by users, it feels like a bug. This commit corrects that behavior by only transferring materials from non-empty material slots. The implementation is now consistent between exact mode of the boolean modifier and the geometry node. **Index-Based Option** "Index-based" is the new default material method for the boolean modifier, to access the old behavior from before the breaking commit. a2d59b2dac9e actually broke some Boolean workflows fundamentally, since it was important to set up matching slot indices on each operand. That isn't the cleanest workflow, and it breaks when materials change procedurally, but historically that hasn't been a problem. The "transfer" behavior transfers all materials except for empty slots, but the fundamental problem is that there isn't a good way to specify the result materials besides using the slot indices. Even then, the transfer option is a bit more intuitive and useful for some simpler situations, and it allows accessing the behavior that has been in 3.2 and 3.3 for a long time, so it's also left in as an option. The geometry node doesn't get this new option, in the hope that we'll find a better solution in the future. Differential Revision: https://developer.blender.org/D16187
2022-11-28 12:42:08 -06:00
const BooleanModifierMaterialMode material_mode = BooleanModifierMaterialMode(
bmd->material_mode);
VectorSet<Material *> materials;
if (material_mode == eBooleanModifierMaterialMode_Transfer) {
if (mesh->totcol == 0) {
/* Necessary for faces using the default material when there are no material slots. */
materials.add(nullptr);
}
else {
materials.add_multiple({mesh->mat, mesh->totcol});
}
}
if (bmd->flag & eBooleanModifierFlag_Object) {
Mesh *mesh_operand = BKE_modifier_get_evaluated_mesh_from_evaluated_object(bmd->object);
if (!mesh_operand) {
return mesh;
}
BKE_mesh_wrapper_ensure_mdata(mesh_operand);
meshes.append(mesh_operand);
obmats.append((float4x4 *)&bmd->object->object_to_world);
Fix T99592: Exact Boolean: Skip empty materials, add index-based option **Empty Slot Fix** Currently the boolean modifier transfers the default material from meshes with no materials and empty material slots to the faces on the base mesh. I added this in a2d59b2dac9e for the sake of consistency, but the behavior is actually not useful at all. The default empty material isn't chosen by users, it just signifies "nothing," so when it replaces a material chosen by users, it feels like a bug. This commit corrects that behavior by only transferring materials from non-empty material slots. The implementation is now consistent between exact mode of the boolean modifier and the geometry node. **Index-Based Option** "Index-based" is the new default material method for the boolean modifier, to access the old behavior from before the breaking commit. a2d59b2dac9e actually broke some Boolean workflows fundamentally, since it was important to set up matching slot indices on each operand. That isn't the cleanest workflow, and it breaks when materials change procedurally, but historically that hasn't been a problem. The "transfer" behavior transfers all materials except for empty slots, but the fundamental problem is that there isn't a good way to specify the result materials besides using the slot indices. Even then, the transfer option is a bit more intuitive and useful for some simpler situations, and it allows accessing the behavior that has been in 3.2 and 3.3 for a long time, so it's also left in as an option. The geometry node doesn't get this new option, in the hope that we'll find a better solution in the future. Differential Revision: https://developer.blender.org/D16187
2022-11-28 12:42:08 -06:00
if (material_mode == eBooleanModifierMaterialMode_Index) {
material_remaps.append(get_material_remap_index_based(ctx->object, bmd->object));
}
else {
material_remaps.append(get_material_remap_transfer(*bmd->object, *mesh_operand, materials));
}
}
else if (bmd->flag & eBooleanModifierFlag_Collection) {
Collection *collection = bmd->collection;
/* Allow collection to be empty; then target mesh will just removed self-intersections. */
if (collection) {
FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (collection, ob) {
if (ob->type == OB_MESH && ob != ctx->object) {
Mesh *collection_mesh = BKE_modifier_get_evaluated_mesh_from_evaluated_object(ob);
if (!collection_mesh) {
continue;
}
BKE_mesh_wrapper_ensure_mdata(collection_mesh);
meshes.append(collection_mesh);
obmats.append((float4x4 *)&ob->object_to_world);
Fix T99592: Exact Boolean: Skip empty materials, add index-based option **Empty Slot Fix** Currently the boolean modifier transfers the default material from meshes with no materials and empty material slots to the faces on the base mesh. I added this in a2d59b2dac9e for the sake of consistency, but the behavior is actually not useful at all. The default empty material isn't chosen by users, it just signifies "nothing," so when it replaces a material chosen by users, it feels like a bug. This commit corrects that behavior by only transferring materials from non-empty material slots. The implementation is now consistent between exact mode of the boolean modifier and the geometry node. **Index-Based Option** "Index-based" is the new default material method for the boolean modifier, to access the old behavior from before the breaking commit. a2d59b2dac9e actually broke some Boolean workflows fundamentally, since it was important to set up matching slot indices on each operand. That isn't the cleanest workflow, and it breaks when materials change procedurally, but historically that hasn't been a problem. The "transfer" behavior transfers all materials except for empty slots, but the fundamental problem is that there isn't a good way to specify the result materials besides using the slot indices. Even then, the transfer option is a bit more intuitive and useful for some simpler situations, and it allows accessing the behavior that has been in 3.2 and 3.3 for a long time, so it's also left in as an option. The geometry node doesn't get this new option, in the hope that we'll find a better solution in the future. Differential Revision: https://developer.blender.org/D16187
2022-11-28 12:42:08 -06:00
if (material_mode == eBooleanModifierMaterialMode_Index) {
material_remaps.append(get_material_remap_index_based(ctx->object, ob));
}
else {
material_remaps.append(get_material_remap_transfer(*ob, *collection_mesh, materials));
}
}
}
FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
}
}
const bool use_self = (bmd->flag & eBooleanModifierFlag_Self) != 0;
const bool hole_tolerant = (bmd->flag & eBooleanModifierFlag_HoleTolerant) != 0;
Mesh *result = blender::meshintersect::direct_mesh_boolean(
meshes,
obmats,
*(float4x4 *)&ctx->object->object_to_world,
material_remaps,
use_self,
hole_tolerant,
bmd->operation,
nullptr);
Fix T99592: Exact Boolean: Skip empty materials, add index-based option **Empty Slot Fix** Currently the boolean modifier transfers the default material from meshes with no materials and empty material slots to the faces on the base mesh. I added this in a2d59b2dac9e for the sake of consistency, but the behavior is actually not useful at all. The default empty material isn't chosen by users, it just signifies "nothing," so when it replaces a material chosen by users, it feels like a bug. This commit corrects that behavior by only transferring materials from non-empty material slots. The implementation is now consistent between exact mode of the boolean modifier and the geometry node. **Index-Based Option** "Index-based" is the new default material method for the boolean modifier, to access the old behavior from before the breaking commit. a2d59b2dac9e actually broke some Boolean workflows fundamentally, since it was important to set up matching slot indices on each operand. That isn't the cleanest workflow, and it breaks when materials change procedurally, but historically that hasn't been a problem. The "transfer" behavior transfers all materials except for empty slots, but the fundamental problem is that there isn't a good way to specify the result materials besides using the slot indices. Even then, the transfer option is a bit more intuitive and useful for some simpler situations, and it allows accessing the behavior that has been in 3.2 and 3.3 for a long time, so it's also left in as an option. The geometry node doesn't get this new option, in the hope that we'll find a better solution in the future. Differential Revision: https://developer.blender.org/D16187
2022-11-28 12:42:08 -06:00
if (material_mode == eBooleanModifierMaterialMode_Transfer) {
MEM_SAFE_FREE(result->mat);
result->mat = (Material **)MEM_malloc_arrayN(materials.size(), sizeof(Material *), __func__);
result->totcol = materials.size();
MutableSpan(result->mat, result->totcol).copy_from(materials);
}
Geometry: add utility to check for bad geometry element index dependence Sometimes .blend files have compatibility issues between Blender versions, because .blend files depended on the specific order of geometry elements generated by some nodes/modifiers (#112746, #113018). While we make guarantees about the order in some places, that is relatively rare, because it makes future improvements much harder. The functionality in this patch makes it easier for users to notice when they depend on things that are not expected to be stable between Blender builds. This is achieved by adding a new global flag which indicates whether some algorithms should randomize their output. The functionality can be toggled on or off by searching for `Set Geometry Randomization`. If there are no differences (or acceptable minor ones) when the flag is on or off, one can be reasonably sure that one does not on unspecified behavior (can't be 100% sure though, because randomization might be missing in some places). If there are big differences, one should consider fixing the file before it comes to an actual breakage in the next Blender version. Currently, the setting is only available when `Developer Extras` is turned on, because the setting is in no menu. With this patch, if we get bug reports with compatibility issues caused by depending on indices, one of the following three cases should always apply: * We actually accidentally broke something, which requires a fix commit. * Turning on geometry randomization shows that the .blend file depends on things it shouldn't depend on. In this case the user has to fix the file. * We are missing geometry randomization somewhere, which requires a fix commit. Pull Request: https://projects.blender.org/blender/blender/pulls/113030
2023-09-29 21:44:36 +02:00
blender::geometry::debug_randomize_mesh_order(result);
return result;
}
#endif
static Mesh *modify_mesh(ModifierData *md, const ModifierEvalContext *ctx, Mesh *mesh)
{
BooleanModifierData *bmd = (BooleanModifierData *)md;
Object *object = ctx->object;
Mesh *result = mesh;
Collection *collection = bmd->collection;
/* Return result for certain errors. */
if (BMD_error_messages(ctx->object, md)) {
return result;
}
#ifdef WITH_GMP
if (bmd->solver == eBooleanModifierSolver_Exact) {
return exact_boolean_mesh(bmd, ctx, mesh);
}
#endif
2015-12-12 01:30:03 +11:00
#ifdef DEBUG_TIME
SCOPED_TIMER(__func__);
2015-12-12 01:30:03 +11:00
#endif
if (bmd->flag & eBooleanModifierFlag_Object) {
if (bmd->object == nullptr) {
return result;
}
Object *operand_ob = bmd->object;
Mesh *mesh_operand_ob = BKE_modifier_get_evaluated_mesh_from_evaluated_object(operand_ob);
if (mesh_operand_ob) {
/* XXX This is utterly non-optimal, we may go from a bmesh to a mesh back to a bmesh!
* But for 2.90 better not try to be smart here. */
BKE_mesh_wrapper_ensure_mdata(mesh_operand_ob);
/* when one of objects is empty (has got no faces) we could speed up
* calculation a bit returning one of objects' derived meshes (or empty one)
* Returning mesh is depended on modifiers operation (sergey) */
result = get_quick_mesh(object, mesh, operand_ob, mesh_operand_ob, bmd->operation);
if (result == nullptr) {
bool is_flip;
BMesh *bm = BMD_mesh_bm_create(mesh, object, mesh_operand_ob, operand_ob, &is_flip);
BMD_mesh_intersection(bm, md, ctx, mesh_operand_ob, object, operand_ob, is_flip);
result = BKE_mesh_from_bmesh_for_eval_nomain(bm, nullptr, mesh);
BM_mesh_free(bm);
}
if (result == nullptr) {
BKE_modifier_set_error(object, md, "Cannot execute boolean operation");
}
}
}
else {
if (collection == nullptr) {
return result;
}
FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN (collection, operand_ob) {
if (operand_ob->type == OB_MESH && operand_ob != ctx->object) {
Mesh *mesh_operand_ob = BKE_modifier_get_evaluated_mesh_from_evaluated_object(operand_ob);
if (mesh_operand_ob == nullptr) {
continue;
}
/* XXX This is utterly non-optimal, we may go from a bmesh to a mesh back to a bmesh!
* But for 2.90 better not try to be smart here. */
BKE_mesh_wrapper_ensure_mdata(mesh_operand_ob);
bool is_flip;
BMesh *bm = BMD_mesh_bm_create(result, object, mesh_operand_ob, operand_ob, &is_flip);
BMD_mesh_intersection(bm, md, ctx, mesh_operand_ob, object, operand_ob, is_flip);
/* Needed for multiple objects to work. */
if (result == mesh) {
result = BKE_mesh_from_bmesh_for_eval_nomain(bm, nullptr, mesh);
}
else {
BMeshToMeshParams bmesh_to_mesh_params{};
bmesh_to_mesh_params.calc_object_remap = false;
BM_mesh_bm_to_me(nullptr, bm, result, &bmesh_to_mesh_params);
}
BM_mesh_free(bm);
}
}
FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
}
Geometry: add utility to check for bad geometry element index dependence Sometimes .blend files have compatibility issues between Blender versions, because .blend files depended on the specific order of geometry elements generated by some nodes/modifiers (#112746, #113018). While we make guarantees about the order in some places, that is relatively rare, because it makes future improvements much harder. The functionality in this patch makes it easier for users to notice when they depend on things that are not expected to be stable between Blender builds. This is achieved by adding a new global flag which indicates whether some algorithms should randomize their output. The functionality can be toggled on or off by searching for `Set Geometry Randomization`. If there are no differences (or acceptable minor ones) when the flag is on or off, one can be reasonably sure that one does not on unspecified behavior (can't be 100% sure though, because randomization might be missing in some places). If there are big differences, one should consider fixing the file before it comes to an actual breakage in the next Blender version. Currently, the setting is only available when `Developer Extras` is turned on, because the setting is in no menu. With this patch, if we get bug reports with compatibility issues caused by depending on indices, one of the following three cases should always apply: * We actually accidentally broke something, which requires a fix commit. * Turning on geometry randomization shows that the .blend file depends on things it shouldn't depend on. In this case the user has to fix the file. * We are missing geometry randomization somewhere, which requires a fix commit. Pull Request: https://projects.blender.org/blender/blender/pulls/113030
2023-09-29 21:44:36 +02:00
blender::geometry::debug_randomize_mesh_order(result);
return result;
}
static void required_data_mask(ModifierData * /*md*/, CustomData_MeshMasks *r_cddata_masks)
{
r_cddata_masks->vmask |= CD_MASK_MDEFORMVERT;
r_cddata_masks->fmask |= CD_MASK_MTFACE;
}
static void panel_draw(const bContext * /*C*/, Panel *panel)
{
uiLayout *layout = panel->layout;
PointerRNA *ptr = modifier_panel_get_property_pointers(panel, nullptr);
uiItemR(layout, ptr, "operation", UI_ITEM_R_EXPAND, nullptr, ICON_NONE);
uiLayoutSetPropSep(layout, true);
uiItemR(layout, ptr, "operand_type", UI_ITEM_NONE, nullptr, ICON_NONE);
if (RNA_enum_get(ptr, "operand_type") == eBooleanModifierFlag_Object) {
uiItemR(layout, ptr, "object", UI_ITEM_NONE, nullptr, ICON_NONE);
}
else {
uiItemR(layout, ptr, "collection", UI_ITEM_NONE, nullptr, ICON_NONE);
}
uiItemR(layout, ptr, "solver", UI_ITEM_R_EXPAND, nullptr, ICON_NONE);
modifier_panel_end(layout, ptr);
}
static void solver_options_panel_draw(const bContext * /*C*/, Panel *panel)
{
uiLayout *layout = panel->layout;
PointerRNA *ptr = modifier_panel_get_property_pointers(panel, nullptr);
const bool use_exact = RNA_enum_get(ptr, "solver") == eBooleanModifierSolver_Exact;
uiLayoutSetPropSep(layout, true);
uiLayout *col = uiLayoutColumn(layout, true);
if (use_exact) {
uiItemR(col, ptr, "material_mode", UI_ITEM_NONE, IFACE_("Materials"), ICON_NONE);
/* When operand is collection, we always use_self. */
if (RNA_enum_get(ptr, "operand_type") == eBooleanModifierFlag_Object) {
uiItemR(col, ptr, "use_self", UI_ITEM_NONE, nullptr, ICON_NONE);
}
uiItemR(col, ptr, "use_hole_tolerant", UI_ITEM_NONE, nullptr, ICON_NONE);
}
else {
uiItemR(col, ptr, "double_threshold", UI_ITEM_NONE, nullptr, ICON_NONE);
}
if (G.debug) {
uiItemR(col, ptr, "debug_options", UI_ITEM_NONE, nullptr, ICON_NONE);
}
}
static void panel_register(ARegionType *region_type)
{
PanelType *panel = modifier_panel_register(region_type, eModifierType_Boolean, panel_draw);
modifier_subpanel_register(
region_type, "solver_options", "Solver Options", nullptr, solver_options_panel_draw, panel);
}
ModifierTypeInfo modifierType_Boolean = {
/*idname*/ "Boolean",
/*name*/ N_("Boolean"),
/*struct_name*/ "BooleanModifierData",
/*struct_size*/ sizeof(BooleanModifierData),
/*srna*/ &RNA_BooleanModifier,
/*type*/ eModifierTypeType_Nonconstructive,
/*flags*/
(ModifierTypeFlag)(eModifierTypeFlag_AcceptsMesh | eModifierTypeFlag_SupportsEditmode),
/*icon*/ ICON_MOD_BOOLEAN,
/*copy_data*/ BKE_modifier_copydata_generic,
/*deform_verts*/ nullptr,
/*deform_matrices*/ nullptr,
/*deform_verts_EM*/ nullptr,
/*deform_matrices_EM*/ nullptr,
/*modify_mesh*/ modify_mesh,
/*modify_geometry_set*/ nullptr,
/*init_data*/ init_data,
/*required_data_mask*/ required_data_mask,
/*free_data*/ nullptr,
/*is_disabled*/ is_disabled,
/*update_depsgraph*/ update_depsgraph,
/*depends_on_time*/ nullptr,
/*depends_on_normals*/ nullptr,
/*foreach_ID_link*/ foreach_ID_link,
/*foreach_tex_link*/ nullptr,
/*free_runtime_data*/ nullptr,
/*panel_register*/ panel_register,
/*blend_write*/ nullptr,
/*blend_read*/ nullptr,
};