Cleanup: strip trailing space in bmesh module
[blender.git] / source / blender / bmesh / operators / bmo_hull.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  * Contributor(s): Nicholas Bishop
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/bmesh/operators/bmo_hull.c
24  *  \ingroup bmesh
25  *
26  * Create a convex hull using bullet physics library.
27  */
28
29 #ifdef WITH_BULLET
30
31 #include "MEM_guardedalloc.h"
32
33 #include "BLI_array.h"
34 #include "BLI_listbase.h"
35 #include "BLI_math.h"
36
37 #include "Bullet-C-Api.h"
38
39 /* XXX: using 128 for totelem and pchunk of mempool, no idea what good
40  * values would be though */
41
42 #include "bmesh.h"
43
44 #include "intern/bmesh_operators_private.h"  /* own include */
45
46 /* Internal operator flags */
47 typedef enum {
48         HULL_FLAG_INPUT =           (1 << 0),
49
50         HULL_FLAG_INTERIOR_ELE =    (1 << 1),
51         HULL_FLAG_OUTPUT_GEOM =     (1 << 2),
52
53         HULL_FLAG_DEL =             (1 << 3),
54         HULL_FLAG_HOLE =            (1 << 4)
55 } HullFlags;
56
57 /* Store hull triangles separate from BMesh faces until the end; this
58  * way we don't have to worry about cleaning up extraneous edges or
59  * incorrectly deleting existing geometry. */
60 typedef struct HullTriangle {
61         BMVert *v[3];
62         float no[3];
63         int skip;
64 } HullTriangle;
65
66
67
68 /*************************** Hull Triangles ***************************/
69
70 static void hull_add_triangle(
71         BMesh *bm, GSet *hull_triangles, BLI_mempool *pool,
72         BMVert *v1, BMVert *v2, BMVert *v3)
73 {
74         HullTriangle *t;
75         int i;
76
77         t = BLI_mempool_calloc(pool);
78         t->v[0] = v1;
79         t->v[1] = v2;
80         t->v[2] = v3;
81
82         /* Mark triangles vertices as not interior */
83         for (i = 0; i < 3; i++)
84                 BMO_vert_flag_disable(bm, t->v[i], HULL_FLAG_INTERIOR_ELE);
85
86         BLI_gset_insert(hull_triangles, t);
87         normal_tri_v3(t->no, v1->co, v2->co, v3->co);
88 }
89
90 static BMFace *hull_find_example_face(BMesh *bm, BMEdge *e)
91 {
92         BMIter iter;
93         BMFace *f;
94
95         BM_ITER_ELEM (f, &iter, e, BM_FACES_OF_EDGE) {
96                 if (BMO_face_flag_test(bm, f, HULL_FLAG_INPUT) ||
97                     BMO_face_flag_test(bm, f, HULL_FLAG_OUTPUT_GEOM) == false)
98                 {
99                         return f;
100                 }
101         }
102
103         return NULL;
104 }
105
106 static void hull_output_triangles(BMesh *bm, GSet *hull_triangles)
107 {
108         GSetIterator iter;
109
110         GSET_ITER (iter, hull_triangles) {
111                 HullTriangle *t = BLI_gsetIterator_getKey(&iter);
112                 int i;
113
114                 if (!t->skip) {
115                         BMEdge *edges[3] = {
116                                 BM_edge_create(bm, t->v[0], t->v[1], NULL, BM_CREATE_NO_DOUBLE),
117                                 BM_edge_create(bm, t->v[1], t->v[2], NULL, BM_CREATE_NO_DOUBLE),
118                                 BM_edge_create(bm, t->v[2], t->v[0], NULL, BM_CREATE_NO_DOUBLE)
119                         };
120                         BMFace *f, *example = NULL;
121
122                         f = BM_face_exists(t->v, 3);
123                         if (f != NULL) {
124                                 /* If the operator is run with "use_existing_faces"
125                                  * disabled, but an output face in the hull is the
126                                  * same as a face in the existing mesh, it should not
127                                  * be marked as unused or interior. */
128                                 BMO_face_flag_enable(bm, f, HULL_FLAG_OUTPUT_GEOM);
129                                 BMO_face_flag_disable(bm, f, HULL_FLAG_HOLE);
130                                 BMO_face_flag_disable(bm, f, HULL_FLAG_INTERIOR_ELE);
131                         }
132                         else {
133                                 /* Look for an adjacent face that existed before the hull */
134                                 for (i = 0; i < 3; i++) {
135                                         if (!example)
136                                                 example = hull_find_example_face(bm, edges[i]);
137                                 }
138
139                                 /* Create new hull face */
140                                 f = BM_face_create_verts(bm, t->v, 3, example, BM_CREATE_NO_DOUBLE, true);
141                                 BM_face_copy_shared(bm, f, NULL, NULL);
142                         }
143                         /* Mark face for 'geom.out' slot and select */
144                         BMO_face_flag_enable(bm, f, HULL_FLAG_OUTPUT_GEOM);
145                         BM_face_select_set(bm, f, true);
146
147                         /* Mark edges for 'geom.out' slot */
148                         for (i = 0; i < 3; i++) {
149                                 BMO_edge_flag_enable(bm, edges[i], HULL_FLAG_OUTPUT_GEOM);
150                         }
151                 }
152                 else {
153                         /* Mark input edges for 'geom.out' slot */
154                         for (i = 0; i < 3; i++) {
155                                 const int next = (i == 2 ? 0 : i + 1);
156                                 BMEdge *e = BM_edge_exists(t->v[i], t->v[next]);
157                                 if (e &&
158                                     BMO_edge_flag_test(bm, e, HULL_FLAG_INPUT) &&
159                                     !BMO_edge_flag_test(bm, e, HULL_FLAG_HOLE))
160                                 {
161                                         BMO_edge_flag_enable(bm, e, HULL_FLAG_OUTPUT_GEOM);
162                                 }
163                         }
164                 }
165
166                 /* Mark verts for 'geom.out' slot */
167                 for (i = 0; i < 3; i++) {
168                         BMO_vert_flag_enable(bm, t->v[i], HULL_FLAG_OUTPUT_GEOM);
169                 }
170         }
171 }
172
173
174
175 /***************************** Final Edges ****************************/
176
177 typedef struct {
178         GHash *edges;
179         BLI_mempool *base_pool, *link_pool;
180 } HullFinalEdges;
181
182 static LinkData *final_edges_find_link(ListBase *adj, BMVert *v)
183 {
184         LinkData *link;
185
186         for (link = adj->first; link; link = link->next) {
187                 if (link->data == v)
188                         return link;
189         }
190
191         return NULL;
192 }
193
194 static int hull_final_edges_lookup(
195         HullFinalEdges *final_edges,
196         BMVert *v1, BMVert *v2)
197 {
198         ListBase *adj;
199
200         /* Use lower vertex pointer for hash key */
201         if (v1 > v2)
202                 SWAP(BMVert *, v1, v2);
203
204         adj = BLI_ghash_lookup(final_edges->edges, v1);
205         if (!adj)
206                 return false;
207
208         return !!final_edges_find_link(adj, v2);
209 }
210
211 /* Used for checking whether a pre-existing edge lies on the hull */
212 static HullFinalEdges *hull_final_edges(GSet *hull_triangles)
213 {
214         HullFinalEdges *final_edges;
215         GSetIterator iter;
216
217         final_edges = MEM_callocN(sizeof(HullFinalEdges), "HullFinalEdges");
218         final_edges->edges = BLI_ghash_ptr_new("final edges ghash");
219         final_edges->base_pool = BLI_mempool_create(sizeof(ListBase), 0, 128, BLI_MEMPOOL_NOP);
220         final_edges->link_pool = BLI_mempool_create(sizeof(LinkData), 0, 128, BLI_MEMPOOL_NOP);
221
222         GSET_ITER (iter, hull_triangles) {
223                 HullTriangle *t = BLI_gsetIterator_getKey(&iter);
224                 LinkData *link;
225                 int i;
226
227                 for (i = 0; i < 3; i++) {
228                         BMVert *v1 = t->v[i];
229                         BMVert *v2 = t->v[(i + 1) % 3];
230                         ListBase *adj;
231
232                         /* Use lower vertex pointer for hash key */
233                         if (v1 > v2)
234                                 SWAP(BMVert *, v1, v2);
235
236                         adj = BLI_ghash_lookup(final_edges->edges, v1);
237                         if (!adj) {
238                                 adj = BLI_mempool_calloc(final_edges->base_pool);
239                                 BLI_ghash_insert(final_edges->edges, v1, adj);
240                         }
241
242                         if (!final_edges_find_link(adj, v2)) {
243                                 link = BLI_mempool_calloc(final_edges->link_pool);
244                                 link->data = v2;
245                                 BLI_addtail(adj, link);
246                         }
247                 }
248         }
249
250         return final_edges;
251 }
252
253 static void hull_final_edges_free(HullFinalEdges *final_edges)
254 {
255         BLI_ghash_free(final_edges->edges, NULL, NULL);
256         BLI_mempool_destroy(final_edges->base_pool);
257         BLI_mempool_destroy(final_edges->link_pool);
258         MEM_freeN(final_edges);
259 }
260
261
262
263 /**************************** Final Output ****************************/
264
265 static void hull_remove_overlapping(
266         BMesh *bm, GSet *hull_triangles,
267         HullFinalEdges *final_edges)
268 {
269         GSetIterator hull_iter;
270
271         GSET_ITER (hull_iter, hull_triangles) {
272                 HullTriangle *t = BLI_gsetIterator_getKey(&hull_iter);
273                 BMIter bm_iter1, bm_iter2;
274                 BMFace *f;
275                 bool f_on_hull;
276
277                 BM_ITER_ELEM (f, &bm_iter1, t->v[0], BM_FACES_OF_VERT) {
278                         BMEdge *e;
279
280                         /* Check that all the face's edges are on the hull,
281                          * otherwise can't reuse it */
282                         f_on_hull = true;
283                         BM_ITER_ELEM (e, &bm_iter2, f, BM_EDGES_OF_FACE) {
284                                 if (!hull_final_edges_lookup(final_edges, e->v1, e->v2)) {
285                                         f_on_hull = false;
286                                         break;
287                                 }
288                         }
289
290                         /* Note: can't change ghash while iterating, so mark
291                          * with 'skip' flag rather than deleting triangles */
292                         if (BM_vert_in_face(t->v[1], f) &&
293                             BM_vert_in_face(t->v[2], f) && f_on_hull)
294                         {
295                                 t->skip = true;
296                                 BMO_face_flag_disable(bm, f, HULL_FLAG_INTERIOR_ELE);
297                                 BMO_face_flag_enable(bm, f, HULL_FLAG_HOLE);
298                         }
299                 }
300         }
301 }
302
303 static void hull_mark_interior_elements(
304         BMesh *bm, BMOperator *op,
305         HullFinalEdges *final_edges)
306 {
307         BMEdge *e;
308         BMFace *f;
309         BMOIter oiter;
310
311         /* Check for interior edges too */
312         BMO_ITER (e, &oiter, op->slots_in, "input", BM_EDGE) {
313                 if (!hull_final_edges_lookup(final_edges, e->v1, e->v2))
314                         BMO_edge_flag_enable(bm, e, HULL_FLAG_INTERIOR_ELE);
315         }
316
317         /* Mark all input faces as interior, some may be unmarked in
318          * hull_remove_overlapping() */
319         BMO_ITER (f, &oiter, op->slots_in, "input", BM_FACE) {
320                 BMO_face_flag_enable(bm, f, HULL_FLAG_INTERIOR_ELE);
321         }
322 }
323
324 static void hull_tag_unused(BMesh *bm, BMOperator *op)
325 {
326         BMIter iter;
327         BMOIter oiter;
328         BMVert *v;
329         BMEdge *e;
330         BMFace *f;
331
332         /* Mark vertices, edges, and faces that are already marked
333          * interior (i.e. were already part of the input, but not part of
334          * the hull), but that aren't also used by elements outside the
335          * input set */
336         BMO_ITER (v, &oiter, op->slots_in, "input", BM_VERT) {
337                 if (BMO_vert_flag_test(bm, v, HULL_FLAG_INTERIOR_ELE)) {
338                         bool del = true;
339
340                         BM_ITER_ELEM (e, &iter, v, BM_EDGES_OF_VERT) {
341                                 if (!BMO_edge_flag_test(bm, e, HULL_FLAG_INPUT)) {
342                                         del = false;
343                                         break;
344                                 }
345                         }
346
347                         BM_ITER_ELEM (f, &iter, v, BM_FACES_OF_VERT) {
348                                 if (!BMO_face_flag_test(bm, f, HULL_FLAG_INPUT)) {
349                                         del = false;
350                                         break;
351                                 }
352                         }
353
354                         if (del) {
355                                 BMO_vert_flag_enable(bm, v, HULL_FLAG_DEL);
356                         }
357                 }
358         }
359
360         BMO_ITER (e, &oiter, op->slots_in, "input", BM_EDGE) {
361                 if (BMO_edge_flag_test(bm, e, HULL_FLAG_INTERIOR_ELE)) {
362                         bool del = true;
363
364                         BM_ITER_ELEM (f, &iter, e, BM_FACES_OF_EDGE) {
365                                 if (!BMO_face_flag_test(bm, f, HULL_FLAG_INPUT)) {
366                                         del = false;
367                                         break;
368                                 }
369                         }
370
371                         if (del) {
372                                 BMO_edge_flag_enable(bm, e, HULL_FLAG_DEL);
373                         }
374                 }
375         }
376
377         BMO_ITER (f, &oiter, op->slots_in, "input", BM_FACE) {
378                 if (BMO_face_flag_test(bm, f, HULL_FLAG_INTERIOR_ELE)) {
379                         BMO_face_flag_enable(bm, f, HULL_FLAG_DEL);
380                 }
381         }
382 }
383
384 static void hull_tag_holes(BMesh *bm, BMOperator *op)
385 {
386         BMIter iter;
387         BMOIter oiter;
388         BMFace *f;
389         BMEdge *e;
390
391         /* Unmark any hole faces if they are isolated or part of a
392          * border */
393         BMO_ITER (f, &oiter, op->slots_in, "input", BM_FACE) {
394                 if (BMO_face_flag_test(bm, f, HULL_FLAG_HOLE)) {
395                         BM_ITER_ELEM (e, &iter, f, BM_EDGES_OF_FACE) {
396                                 if (BM_edge_is_boundary(e)) {
397                                         BMO_face_flag_disable(bm, f, HULL_FLAG_HOLE);
398                                         break;
399                                 }
400                         }
401                 }
402         }
403
404         /* Mark edges too if all adjacent faces are holes and the edge is
405          * not already isolated */
406         BMO_ITER (e, &oiter, op->slots_in, "input", BM_EDGE) {
407                 bool hole = true;
408                 bool any_faces = false;
409
410                 BM_ITER_ELEM (f, &iter, e, BM_FACES_OF_EDGE) {
411                         any_faces = true;
412                         if (!BMO_face_flag_test(bm, f, HULL_FLAG_HOLE)) {
413                                 hole = false;
414                                 break;
415                         }
416                 }
417
418                 if (hole && any_faces)
419                         BMO_edge_flag_enable(bm, e, HULL_FLAG_HOLE);
420         }
421 }
422
423 static int hull_input_vert_count(BMOperator *op)
424 {
425         BMOIter oiter;
426         BMVert *v;
427         int count = 0;
428
429         BMO_ITER (v, &oiter, op->slots_in, "input", BM_VERT) {
430                 count++;
431         }
432
433         return count;
434 }
435
436 static BMVert **hull_input_verts_copy(
437         BMOperator *op,
438         const int num_input_verts)
439 {
440         BMOIter oiter;
441         BMVert *v;
442         BMVert **input_verts = MEM_callocN(sizeof(*input_verts) *
443                                            num_input_verts, AT);
444         int i = 0;
445
446         BMO_ITER (v, &oiter, op->slots_in, "input", BM_VERT) {
447                 input_verts[i++] = v;
448         }
449
450         return input_verts;
451 }
452
453 static float (*hull_verts_for_bullet(
454         BMVert **input_verts,
455         const int num_input_verts))[3]
456 {
457         float (*coords)[3] = MEM_callocN(sizeof(*coords) * num_input_verts, __func__);
458         int i;
459
460         for (i = 0; i < num_input_verts; i++) {
461                 copy_v3_v3(coords[i], input_verts[i]->co);
462         }
463
464         return coords;
465 }
466
467 static BMVert **hull_verts_from_bullet(
468         plConvexHull hull,
469         BMVert **input_verts,
470         const int num_input_verts)
471 {
472         const int num_verts = plConvexHullNumVertices(hull);
473         BMVert **hull_verts = MEM_mallocN(sizeof(*hull_verts) *
474                                           num_verts, AT);
475         int i;
476
477         for (i = 0; i < num_verts; i++) {
478                 float co[3];
479                 int original_index;
480                 plConvexHullGetVertex(hull, i, co, &original_index);
481
482                 if (original_index >= 0 && original_index < num_input_verts) {
483                         hull_verts[i] = input_verts[original_index];
484                 }
485                 else
486                         BLI_assert(!"Unexpected new vertex in hull output");
487         }
488
489         return hull_verts;
490 }
491
492 static void hull_from_bullet(
493         BMesh *bm, BMOperator *op,
494         GSet *hull_triangles,
495         BLI_mempool *pool)
496 {
497         int *fvi = NULL;
498         BLI_array_declare(fvi);
499
500         BMVert **input_verts;
501         float (*coords)[3];
502         BMVert **hull_verts;
503
504         plConvexHull hull;
505         int i, count = 0;
506
507         const int num_input_verts = hull_input_vert_count(op);
508
509         input_verts = hull_input_verts_copy(op, num_input_verts);
510         coords = hull_verts_for_bullet(input_verts, num_input_verts);
511
512         hull = plConvexHullCompute(coords, num_input_verts);
513         hull_verts = hull_verts_from_bullet(hull, input_verts, num_input_verts);
514
515         count = plConvexHullNumFaces(hull);
516         for (i = 0; i < count; i++) {
517                 const int len = plConvexHullGetFaceSize(hull, i);
518
519                 if (len > 2) {
520                         BMVert *fv[3];
521                         int j;
522
523                         /* Get face vertex indices */
524                         BLI_array_clear(fvi);
525                         BLI_array_grow_items(fvi, len);
526                         plConvexHullGetFaceVertices(hull, i, fvi);
527
528                         /* Note: here we throw away any NGons from Bullet and turn
529                          * them into triangle fans. Would be nice to use these
530                          * directly, but will have to wait until HullTriangle goes
531                          * away (TODO) */
532                         fv[0] = hull_verts[fvi[0]];
533                         for (j = 2; j < len; j++) {
534                                 fv[1] = hull_verts[fvi[j - 1]];
535                                 fv[2] = hull_verts[fvi[j]];
536
537                                 hull_add_triangle(bm, hull_triangles, pool,
538                                                   fv[0], fv[1], fv[2]);
539                         }
540                 }
541         }
542
543         BLI_array_free(fvi);
544
545         plConvexHullDelete(hull);
546
547         MEM_freeN(hull_verts);
548         MEM_freeN(coords);
549         MEM_freeN(input_verts);
550 }
551
552 /* Check that there are at least three vertices in the input */
553 static bool hull_num_input_verts_is_ok(BMOperator *op)
554 {
555         BMOIter oiter;
556         BMVert *v;
557         int partial_num_verts = 0;
558
559         BMO_ITER (v, &oiter, op->slots_in, "input", BM_VERT) {
560                 partial_num_verts++;
561                 if (partial_num_verts >= 3)
562                         break;
563         }
564
565         return (partial_num_verts >= 3);
566 }
567
568 void bmo_convex_hull_exec(BMesh *bm, BMOperator *op)
569 {
570         HullFinalEdges *final_edges;
571         BLI_mempool *hull_pool;
572         BMElemF *ele;
573         BMOIter oiter;
574         GSet *hull_triangles;
575
576         /* Verify that at least three verts in the input */
577         if (!hull_num_input_verts_is_ok(op)) {
578                 BMO_error_raise(bm, op, BMERR_CONVEX_HULL_FAILED,
579                                 "Requires at least three vertices");
580                 return;
581         }
582
583         /* Tag input elements */
584         BMO_ITER (ele, &oiter, op->slots_in, "input", BM_ALL) {
585
586                 /* Mark all vertices as interior to begin with */
587                 if (ele->head.htype == BM_VERT) {
588                         BMO_vert_flag_enable(bm, (BMVert *)ele, HULL_FLAG_INPUT | HULL_FLAG_INTERIOR_ELE);
589                 }
590                 else if (ele->head.htype == BM_EDGE) {
591                         BMO_edge_flag_enable(bm, (BMEdge *)ele, HULL_FLAG_INPUT);
592                 }
593                 else {
594                         BMO_face_flag_enable(bm, (BMFace *)ele, HULL_FLAG_INPUT);
595                 }
596         }
597
598         hull_pool = BLI_mempool_create(sizeof(HullTriangle), 0, 128, BLI_MEMPOOL_NOP);
599         hull_triangles = BLI_gset_ptr_new("hull_triangles");
600
601         hull_from_bullet(bm, op, hull_triangles, hull_pool);
602
603         final_edges = hull_final_edges(hull_triangles);
604
605         hull_mark_interior_elements(bm, op, final_edges);
606
607         /* Remove hull triangles covered by an existing face */
608         if (BMO_slot_bool_get(op->slots_in, "use_existing_faces")) {
609                 hull_remove_overlapping(bm, hull_triangles, final_edges);
610
611                 hull_tag_holes(bm, op);
612         }
613
614         /* Done with edges */
615         hull_final_edges_free(final_edges);
616
617         /* Convert hull triangles to BMesh faces */
618         hull_output_triangles(bm, hull_triangles);
619         BLI_mempool_destroy(hull_pool);
620
621         BLI_gset_free(hull_triangles, NULL);
622
623         hull_tag_unused(bm, op);
624
625         /* Output slot of input elements that ended up inside the hull
626          * rather than part of it */
627         BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "geom_interior.out",
628                                           BM_ALL_NOLOOP, HULL_FLAG_INTERIOR_ELE);
629
630         /* Output slot of input elements that ended up inside the hull and
631          * are are unused by other geometry. */
632         BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "geom_unused.out",
633                                           BM_ALL_NOLOOP, HULL_FLAG_DEL);
634
635         /* Output slot of faces and edges that were in the input and on
636          * the hull (useful for cases like bridging where you want to
637          * delete some input geometry) */
638         BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "geom_holes.out",
639                                           BM_ALL_NOLOOP, HULL_FLAG_HOLE);
640
641         /* Output slot of all hull vertices, faces, and edges */
642         BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "geom.out",
643                                           BM_ALL_NOLOOP, HULL_FLAG_OUTPUT_GEOM);
644 }
645
646 #endif  /* WITH_BULLET */