Merge branch 'master' into blender2.8
[blender.git] / source / blender / modifiers / intern / MOD_boolean.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software  Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 by the Blender Foundation.
19  * All rights reserved.
20  *
21  * Contributor(s): Daniel Dunbar
22  *                 Ton Roosendaal,
23  *                 Ben Batt,
24  *                 Brecht Van Lommel,
25  *                 Campbell Barton
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  *
29  */
30
31 /** \file blender/modifiers/intern/MOD_boolean.c
32  *  \ingroup modifiers
33  */
34
35 // #ifdef DEBUG_TIME
36
37 #include <stdio.h>
38
39 #include "DNA_object_types.h"
40
41 #include "BLI_utildefines.h"
42 #include "BLI_math_matrix.h"
43
44 #include "BKE_cdderivedmesh.h"
45 #include "BKE_library_query.h"
46 #include "BKE_modifier.h"
47
48 #include "MOD_util.h"
49
50
51 #include "BLI_alloca.h"
52 #include "BLI_math_geom.h"
53 #include "BKE_material.h"
54 #include "BKE_global.h"  /* only to check G.debug */
55 #include "MEM_guardedalloc.h"
56
57 #include "bmesh.h"
58 #include "bmesh_tools.h"
59 #include "tools/bmesh_intersect.h"
60
61 #ifdef DEBUG_TIME
62 #  include "PIL_time.h"
63 #  include "PIL_time_utildefines.h"
64 #endif
65
66 static void initData(ModifierData *md)
67 {
68         BooleanModifierData *bmd = (BooleanModifierData *)md;
69
70         bmd->double_threshold = 1e-6f;
71 }
72
73 static void copyData(ModifierData *md, ModifierData *target)
74 {
75 #if 0
76         BooleanModifierData *bmd = (BooleanModifierData *) md;
77         BooleanModifierData *tbmd = (BooleanModifierData *) target;
78 #endif
79         modifier_copyData_generic(md, target);
80 }
81
82 static bool isDisabled(ModifierData *md, int UNUSED(useRenderParams))
83 {
84         BooleanModifierData *bmd = (BooleanModifierData *) md;
85
86         return !bmd->object;
87 }
88
89 static void foreachObjectLink(
90         ModifierData *md, Object *ob,
91         ObjectWalkFunc walk, void *userData)
92 {
93         BooleanModifierData *bmd = (BooleanModifierData *) md;
94
95         walk(userData, ob, &bmd->object, IDWALK_CB_NOP);
96 }
97
98 static void updateDepsgraph(ModifierData *md,
99                             struct Main *UNUSED(bmain),
100                             struct Scene *UNUSED(scene),
101                             Object *ob,
102                             struct DepsNodeHandle *node)
103 {
104         BooleanModifierData *bmd = (BooleanModifierData *)md;
105         if (bmd->object != NULL) {
106                 DEG_add_object_relation(node, bmd->object, DEG_OB_COMP_TRANSFORM, "Boolean Modifier");
107                 DEG_add_object_relation(node, bmd->object, DEG_OB_COMP_GEOMETRY, "Boolean Modifier");
108         }
109         /* We need own transformation as well. */
110         DEG_add_object_relation(node, ob, DEG_OB_COMP_TRANSFORM, "Boolean Modifier");
111 }
112
113 static DerivedMesh *get_quick_derivedMesh(
114         Object *ob_self,  DerivedMesh *dm_self,
115         Object *ob_other, DerivedMesh *dm_other,
116         int operation)
117 {
118         DerivedMesh *result = NULL;
119
120         if (dm_self->getNumPolys(dm_self) == 0 || dm_other->getNumPolys(dm_other) == 0) {
121                 switch (operation) {
122                         case eBooleanModifierOp_Intersect:
123                                 result = CDDM_new(0, 0, 0, 0, 0);
124                                 break;
125
126                         case eBooleanModifierOp_Union:
127                                 if (dm_self->getNumPolys(dm_self) != 0) {
128                                         result = dm_self;
129                                 }
130                                 else {
131                                         result = CDDM_copy(dm_other);
132
133                                         float imat[4][4];
134                                         float omat[4][4];
135
136                                         invert_m4_m4(imat, ob_self->obmat);
137                                         mul_m4_m4m4(omat, imat, ob_other->obmat);
138
139                                         const int mverts_len = result->getNumVerts(result);
140                                         MVert *mv = CDDM_get_verts(result);
141
142                                         for (int i = 0; i < mverts_len; i++, mv++) {
143                                                 mul_m4_v3(omat, mv->co);
144                                         }
145
146                                         result->dirty |= DM_DIRTY_NORMALS;
147                                 }
148
149                                 break;
150
151                         case eBooleanModifierOp_Difference:
152                                 result = dm_self;
153                                 break;
154                 }
155         }
156
157         return result;
158 }
159
160
161 /* has no meaning for faces, do this so we can tell which face is which */
162 #define BM_FACE_TAG BM_ELEM_DRAW
163
164 /**
165  * Compare selected/unselected.
166  */
167 static int bm_face_isect_pair(BMFace *f, void *UNUSED(user_data))
168 {
169         return BM_elem_flag_test(f, BM_FACE_TAG) ? 1 : 0;
170 }
171
172 static DerivedMesh *applyModifier(
173         ModifierData *md, const struct EvaluationContext *UNUSED(eval_ctx), Object *ob,
174         DerivedMesh *dm,
175         ModifierApplyFlag flag)
176 {
177         BooleanModifierData *bmd = (BooleanModifierData *) md;
178         DerivedMesh *dm_other;
179
180         if (!bmd->object)
181                 return dm;
182
183         dm_other = get_dm_for_modifier(bmd->object, flag);
184
185         if (dm_other) {
186                 DerivedMesh *result;
187
188                 /* when one of objects is empty (has got no faces) we could speed up
189                  * calculation a bit returning one of objects' derived meshes (or empty one)
190                  * Returning mesh is depended on modifiers operation (sergey) */
191                 result = get_quick_derivedMesh(ob, dm, bmd->object, dm_other, bmd->operation);
192
193                 if (result == NULL) {
194                         const bool is_flip = (is_negative_m4(ob->obmat) != is_negative_m4(bmd->object->obmat));
195
196                         BMesh *bm;
197                         const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_DM(dm, dm_other);
198
199 #ifdef DEBUG_TIME
200                         TIMEIT_START(boolean_bmesh);
201 #endif
202                         bm = BM_mesh_create(
203                                  &allocsize,
204                                  &((struct BMeshCreateParams){.use_toolflags = false,}));
205
206                         DM_to_bmesh_ex(dm_other, bm, true);
207
208                         if (UNLIKELY(is_flip)) {
209                                 const int cd_loop_mdisp_offset = CustomData_get_offset(&bm->ldata, CD_MDISPS);
210                                 BMIter iter;
211                                 BMFace *efa;
212                                 BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
213                                         BM_face_normal_flip_ex(bm, efa, cd_loop_mdisp_offset, true);
214                                 }
215                         }
216
217                         DM_to_bmesh_ex(dm, bm, true);
218
219                         /* main bmesh intersection setup */
220                         {
221                                 /* create tessface & intersect */
222                                 const int looptris_tot = poly_to_tri_count(bm->totface, bm->totloop);
223                                 int tottri;
224                                 BMLoop *(*looptris)[3];
225
226                                 looptris = MEM_malloc_arrayN(looptris_tot, sizeof(*looptris), __func__);
227
228                                 BM_mesh_calc_tessellation_beauty(bm, looptris, &tottri);
229
230                                 /* postpone this until after tessellating
231                                  * so we can use the original normals before the vertex are moved */
232                                 {
233                                         BMIter iter;
234                                         int i;
235                                         const int i_verts_end = dm_other->getNumVerts(dm_other);
236                                         const int i_faces_end = dm_other->getNumPolys(dm_other);
237
238                                         float imat[4][4];
239                                         float omat[4][4];
240
241                                         invert_m4_m4(imat, ob->obmat);
242                                         mul_m4_m4m4(omat, imat, bmd->object->obmat);
243
244                                         BMVert *eve;
245                                         i = 0;
246                                         BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
247                                                 mul_m4_v3(omat, eve->co);
248                                                 if (++i == i_verts_end) {
249                                                         break;
250                                                 }
251                                         }
252
253                                         /* we need face normals because of 'BM_face_split_edgenet'
254                                          * we could calculate on the fly too (before calling split). */
255                                         {
256                                                 float nmat[3][3];
257                                                 copy_m3_m4(nmat, omat);
258                                                 invert_m3(nmat);
259
260                                                 if (UNLIKELY(is_flip)) {
261                                                         negate_m3(nmat);
262                                                 }
263
264                                                 const short ob_src_totcol = bmd->object->totcol;
265                                                 short *material_remap = BLI_array_alloca(material_remap, ob_src_totcol ? ob_src_totcol : 1);
266
267                                                 BKE_material_remap_object_calc(ob, bmd->object, material_remap);
268
269                                                 BMFace *efa;
270                                                 i = 0;
271                                                 BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
272                                                         mul_transposed_m3_v3(nmat, efa->no);
273                                                         normalize_v3(efa->no);
274                                                         BM_elem_flag_enable(efa, BM_FACE_TAG);  /* temp tag to test which side split faces are from */
275
276                                                         /* remap material */
277                                                         if (LIKELY(efa->mat_nr < ob_src_totcol)) {
278                                                                 efa->mat_nr = material_remap[efa->mat_nr];
279                                                         }
280
281                                                         if (++i == i_faces_end) {
282                                                                 break;
283                                                         }
284                                                 }
285                                         }
286                                 }
287
288                                 /* not needed, but normals for 'dm' will be invalid,
289                                  * currently this is ok for 'BM_mesh_intersect' */
290                                 // BM_mesh_normals_update(bm);
291
292                                 bool use_separate = false;
293                                 bool use_dissolve = true;
294                                 bool use_island_connect = true;
295
296                                 /* change for testing */
297                                 if (G.debug & G_DEBUG) {
298                                         use_separate = (bmd->bm_flag & eBooleanModifierBMeshFlag_BMesh_Separate) != 0;
299                                         use_dissolve = (bmd->bm_flag & eBooleanModifierBMeshFlag_BMesh_NoDissolve) == 0;
300                                         use_island_connect = (bmd->bm_flag & eBooleanModifierBMeshFlag_BMesh_NoConnectRegions) == 0;
301                                 }
302
303                                 BM_mesh_intersect(
304                                         bm,
305                                         looptris, tottri,
306                                         bm_face_isect_pair, NULL,
307                                         false,
308                                         use_separate,
309                                         use_dissolve,
310                                         use_island_connect,
311                                         false,
312                                         bmd->operation,
313                                         bmd->double_threshold);
314
315                                 MEM_freeN(looptris);
316                         }
317
318                         result = CDDM_from_bmesh(bm, true);
319
320                         BM_mesh_free(bm);
321
322                         result->dirty |= DM_DIRTY_NORMALS;
323
324 #ifdef DEBUG_TIME
325                         TIMEIT_END(boolean_bmesh);
326 #endif
327
328                         return result;
329                 }
330
331                 /* if new mesh returned, return it; otherwise there was
332                  * an error, so delete the modifier object */
333                 if (result)
334                         return result;
335                 else
336                         modifier_setError(md, "Cannot execute boolean operation");
337         }
338
339         return dm;
340 }
341
342 static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(md))
343 {
344         CustomDataMask dataMask = CD_MASK_MTFACE | CD_MASK_MEDGE;
345
346         dataMask |= CD_MASK_MDEFORMVERT;
347         
348         return dataMask;
349 }
350
351 ModifierTypeInfo modifierType_Boolean = {
352         /* name */              "Boolean",
353         /* structName */        "BooleanModifierData",
354         /* structSize */        sizeof(BooleanModifierData),
355         /* type */              eModifierTypeType_Nonconstructive,
356         /* flags */             eModifierTypeFlag_AcceptsMesh |
357                                 eModifierTypeFlag_UsesPointCache,
358
359         /* copyData */          copyData,
360         /* deformVerts */       NULL,
361         /* deformMatrices */    NULL,
362         /* deformVertsEM */     NULL,
363         /* deformMatricesEM */  NULL,
364         /* applyModifier */     applyModifier,
365         /* applyModifierEM */   NULL,
366         /* initData */          initData,
367         /* requiredDataMask */  requiredDataMask,
368         /* freeData */          NULL,
369         /* isDisabled */        isDisabled,
370         /* updateDepsgraph */   updateDepsgraph,
371         /* dependsOnTime */     NULL,
372         /* dependsOnNormals */  NULL,
373         /* foreachObjectLink */ foreachObjectLink,
374         /* foreachIDLink */     NULL,
375         /* foreachTexLink */    NULL,
376 };