Vertex/Weight Paint: Use PBVH for painting
[blender.git] / source / blender / blenkernel / intern / pbvh.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  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/blenkernel/intern/pbvh.c
22  *  \ingroup bli
23  */
24
25 #include "DNA_meshdata_types.h"
26
27 #include "MEM_guardedalloc.h"
28
29 #include "BLI_bitmap.h"
30 #include "BLI_math.h"
31 #include "BLI_utildefines.h"
32 #include "BLI_ghash.h"
33 #include "BLI_task.h"
34
35 #include "BKE_pbvh.h"
36 #include "BKE_ccg.h"
37 #include "BKE_subsurf.h"
38 #include "BKE_DerivedMesh.h"
39 #include "BKE_global.h"
40 #include "BKE_mesh.h" /* for BKE_mesh_calc_normals */
41 #include "BKE_paint.h"
42
43 #include "GPU_buffers.h"
44
45 #include "bmesh.h"
46
47 #include "atomic_ops.h"
48
49 #include "pbvh_intern.h"
50
51 #include <limits.h>
52
53 #define LEAF_LIMIT 10000
54
55 //#define PERFCNTRS
56
57 #define STACK_FIXED_DEPTH   100
58
59 #define PBVH_THREADED_LIMIT 4
60
61 typedef struct PBVHStack {
62         PBVHNode *node;
63         bool revisiting;
64 } PBVHStack;
65
66 typedef struct PBVHIter {
67         PBVH *bvh;
68         BKE_pbvh_SearchCallback scb;
69         void *search_data;
70
71         PBVHStack *stack;
72         int stacksize;
73
74         PBVHStack stackfixed[STACK_FIXED_DEPTH];
75         int stackspace;
76 } PBVHIter;
77
78 void BB_reset(BB *bb)
79 {
80         bb->bmin[0] = bb->bmin[1] = bb->bmin[2] = FLT_MAX;
81         bb->bmax[0] = bb->bmax[1] = bb->bmax[2] = -FLT_MAX;
82 }
83
84 /* Expand the bounding box to include a new coordinate */
85 void BB_expand(BB *bb, const float co[3])
86 {
87         for (int i = 0; i < 3; ++i) {
88                 bb->bmin[i] = min_ff(bb->bmin[i], co[i]);
89                 bb->bmax[i] = max_ff(bb->bmax[i], co[i]);
90         }
91 }
92
93 /* Expand the bounding box to include another bounding box */
94 void BB_expand_with_bb(BB *bb, BB *bb2)
95 {
96         for (int i = 0; i < 3; ++i) {
97                 bb->bmin[i] = min_ff(bb->bmin[i], bb2->bmin[i]);
98                 bb->bmax[i] = max_ff(bb->bmax[i], bb2->bmax[i]);
99         }
100 }
101
102 /* Return 0, 1, or 2 to indicate the widest axis of the bounding box */
103 int BB_widest_axis(const BB *bb)
104 {
105         float dim[3];
106
107         for (int i = 0; i < 3; ++i)
108                 dim[i] = bb->bmax[i] - bb->bmin[i];
109
110         if (dim[0] > dim[1]) {
111                 if (dim[0] > dim[2])
112                         return 0;
113                 else
114                         return 2;
115         }
116         else {
117                 if (dim[1] > dim[2])
118                         return 1;
119                 else
120                         return 2;
121         }
122 }
123
124 void BBC_update_centroid(BBC *bbc)
125 {
126         for (int i = 0; i < 3; ++i)
127                 bbc->bcentroid[i] = (bbc->bmin[i] + bbc->bmax[i]) * 0.5f;
128 }
129
130 /* Not recursive */
131 static void update_node_vb(PBVH *bvh, PBVHNode *node)
132 {
133         BB vb;
134
135         BB_reset(&vb);
136         
137         if (node->flag & PBVH_Leaf) {
138                 PBVHVertexIter vd;
139
140                 BKE_pbvh_vertex_iter_begin(bvh, node, vd, PBVH_ITER_ALL)
141                 {
142                         BB_expand(&vb, vd.co);
143                 }
144                 BKE_pbvh_vertex_iter_end;
145         }
146         else {
147                 BB_expand_with_bb(&vb,
148                                   &bvh->nodes[node->children_offset].vb);
149                 BB_expand_with_bb(&vb,
150                                   &bvh->nodes[node->children_offset + 1].vb);
151         }
152
153         node->vb = vb;
154 }
155
156 //void BKE_pbvh_node_BB_reset(PBVHNode *node)
157 //{
158 //      BB_reset(&node->vb);
159 //}
160 //
161 //void BKE_pbvh_node_BB_expand(PBVHNode *node, float co[3])
162 //{
163 //      BB_expand(&node->vb, co);
164 //}
165
166 static bool face_materials_match(const MPoly *f1, const MPoly *f2)
167 {
168         return ((f1->flag & ME_SMOOTH) == (f2->flag & ME_SMOOTH) &&
169                 (f1->mat_nr == f2->mat_nr));
170 }
171
172 static bool grid_materials_match(const DMFlagMat *f1, const DMFlagMat *f2)
173 {
174         return ((f1->flag & ME_SMOOTH) == (f2->flag & ME_SMOOTH) &&
175                 (f1->mat_nr == f2->mat_nr));
176 }
177
178 /* Adapted from BLI_kdopbvh.c */
179 /* Returns the index of the first element on the right of the partition */
180 static int partition_indices(int *prim_indices, int lo, int hi, int axis,
181                              float mid, BBC *prim_bbc)
182 {
183         int i = lo, j = hi;
184         for (;; ) {
185                 for (; prim_bbc[prim_indices[i]].bcentroid[axis] < mid; i++) ;
186                 for (; mid < prim_bbc[prim_indices[j]].bcentroid[axis]; j--) ;
187                 
188                 if (!(i < j))
189                         return i;
190                 
191                 SWAP(int, prim_indices[i], prim_indices[j]);
192                 i++;
193         }
194 }
195
196 /* Returns the index of the first element on the right of the partition */
197 static int partition_indices_material(PBVH *bvh, int lo, int hi)
198 {
199         const MPoly *mpoly = bvh->mpoly;
200         const MLoopTri *looptri = bvh->looptri;
201         const DMFlagMat *flagmats = bvh->grid_flag_mats;
202         const int *indices = bvh->prim_indices;
203         const void *first;
204         int i = lo, j = hi;
205
206         if (bvh->looptri)
207                 first = &mpoly[looptri[bvh->prim_indices[lo]].poly];
208         else
209                 first = &flagmats[bvh->prim_indices[lo]];
210
211         for (;; ) {
212                 if (bvh->looptri) {
213                         for (; face_materials_match(first, &mpoly[looptri[indices[i]].poly]); i++) ;
214                         for (; !face_materials_match(first, &mpoly[looptri[indices[j]].poly]); j--) ;
215                 }
216                 else {
217                         for (; grid_materials_match(first, &flagmats[indices[i]]); i++) ;
218                         for (; !grid_materials_match(first, &flagmats[indices[j]]); j--) ;
219                 }
220                 
221                 if (!(i < j))
222                         return i;
223
224                 SWAP(int, bvh->prim_indices[i], bvh->prim_indices[j]);
225                 i++;
226         }
227 }
228
229 void pbvh_grow_nodes(PBVH *bvh, int totnode)
230 {
231         if (UNLIKELY(totnode > bvh->node_mem_count)) {
232                 bvh->node_mem_count = bvh->node_mem_count + (bvh->node_mem_count / 3);
233                 if (bvh->node_mem_count < totnode)
234                         bvh->node_mem_count = totnode;
235                 bvh->nodes = MEM_recallocN(bvh->nodes, sizeof(PBVHNode) * bvh->node_mem_count);
236         }
237
238         bvh->totnode = totnode;
239 }
240
241 /* Add a vertex to the map, with a positive value for unique vertices and
242  * a negative value for additional vertices */
243 static int map_insert_vert(PBVH *bvh, GHash *map,
244                            unsigned int *face_verts,
245                            unsigned int *uniq_verts, int vertex)
246 {
247         void *key, **value_p;
248
249         key = SET_INT_IN_POINTER(vertex);
250         if (!BLI_ghash_ensure_p(map, key, &value_p)) {
251                 int value_i;
252                 if (BLI_BITMAP_TEST(bvh->vert_bitmap, vertex) == 0) {
253                         BLI_BITMAP_ENABLE(bvh->vert_bitmap, vertex);
254                         value_i = *uniq_verts;
255                         (*uniq_verts)++;
256                 }
257                 else {
258                         value_i = ~(*face_verts);
259                         (*face_verts)++;
260                 }
261                 *value_p = SET_INT_IN_POINTER(value_i);
262                 return value_i;
263         }
264         else {
265                 return GET_INT_FROM_POINTER(*value_p);
266         }
267 }
268
269 /* Find vertices used by the faces in this node and update the draw buffers */
270 static void build_mesh_leaf_node(PBVH *bvh, PBVHNode *node)
271 {
272         bool has_visible = false;
273
274         node->uniq_verts = node->face_verts = 0;
275         const int totface = node->totprim;
276
277         /* reserve size is rough guess */
278         GHash *map = BLI_ghash_int_new_ex("build_mesh_leaf_node gh", 2 * totface);
279
280         int (*face_vert_indices)[3] = MEM_mallocN(sizeof(int[3]) * totface,
281                                                   "bvh node face vert indices");
282
283         node->face_vert_indices = (const int (*)[3])face_vert_indices;
284
285         for (int i = 0; i < totface; ++i) {
286                 const MLoopTri *lt = &bvh->looptri[node->prim_indices[i]];
287                 for (int j = 0; j < 3; ++j) {
288                         face_vert_indices[i][j] =
289                                 map_insert_vert(bvh, map, &node->face_verts,
290                                                 &node->uniq_verts, bvh->mloop[lt->tri[j]].v);
291                 }
292
293                 if (!paint_is_face_hidden(lt, bvh->verts, bvh->mloop)) {
294                         has_visible = true;
295                 }
296         }
297
298         int *vert_indices = MEM_callocN(sizeof(int) * (node->uniq_verts + node->face_verts),
299                                         "bvh node vert indices");
300         node->vert_indices = vert_indices;
301
302         /* Build the vertex list, unique verts first */
303         GHashIterator gh_iter;
304         GHASH_ITER (gh_iter, map) {
305                 void *value = BLI_ghashIterator_getValue(&gh_iter);
306                 int ndx = GET_INT_FROM_POINTER(value);
307
308                 if (ndx < 0)
309                         ndx = -ndx + node->uniq_verts - 1;
310
311                 vert_indices[ndx] =
312                         GET_INT_FROM_POINTER(BLI_ghashIterator_getKey(&gh_iter));
313         }
314
315         for (int i = 0; i < totface; ++i) {
316                 const int sides = 3;
317
318                 for (int j = 0; j < sides; ++j) {
319                         if (face_vert_indices[i][j] < 0)
320                                 face_vert_indices[i][j] =
321                                         -face_vert_indices[i][j] +
322                                         node->uniq_verts - 1;
323                 }
324         }
325
326         BKE_pbvh_node_mark_rebuild_draw(node);
327
328         BKE_pbvh_node_fully_hidden_set(node, !has_visible);
329
330         BLI_ghash_free(map, NULL, NULL);
331 }
332
333 static void update_vb(PBVH *bvh, PBVHNode *node, BBC *prim_bbc,
334                       int offset, int count)
335 {
336         BB_reset(&node->vb);
337         for (int i = offset + count - 1; i >= offset; --i) {
338                 BB_expand_with_bb(&node->vb, (BB *)(&prim_bbc[bvh->prim_indices[i]]));
339         }
340         node->orig_vb = node->vb;
341 }
342
343 /* Returns the number of visible quads in the nodes' grids. */
344 int BKE_pbvh_count_grid_quads(BLI_bitmap **grid_hidden,
345                               int *grid_indices, int totgrid,
346                               int gridsize)
347 {
348         const int gridarea = (gridsize - 1) * (gridsize - 1);
349         int totquad = 0;
350
351         /* grid hidden layer is present, so have to check each grid for
352          * visibility */
353
354         for (int i = 0; i < totgrid; i++) {
355                 const BLI_bitmap *gh = grid_hidden[grid_indices[i]];
356
357                 if (gh) {
358                         /* grid hidden are present, have to check each element */
359                         for (int y = 0; y < gridsize - 1; y++) {
360                                 for (int x = 0; x < gridsize - 1; x++) {
361                                         if (!paint_is_grid_face_hidden(gh, gridsize, x, y))
362                                                 totquad++;
363                                 }
364                         }
365                 }
366                 else
367                         totquad += gridarea;
368         }
369
370         return totquad;
371 }
372
373 static void build_grid_leaf_node(PBVH *bvh, PBVHNode *node)
374 {
375         int totquads = BKE_pbvh_count_grid_quads(bvh->grid_hidden, node->prim_indices,
376                                                  node->totprim, bvh->gridkey.grid_size);
377         BKE_pbvh_node_fully_hidden_set(node, (totquads == 0));
378         BKE_pbvh_node_mark_rebuild_draw(node);
379 }
380
381
382 static void build_leaf(PBVH *bvh, int node_index, BBC *prim_bbc,
383                        int offset, int count)
384 {
385         bvh->nodes[node_index].flag |= PBVH_Leaf;
386
387         bvh->nodes[node_index].prim_indices = bvh->prim_indices + offset;
388         bvh->nodes[node_index].totprim = count;
389
390         /* Still need vb for searches */
391         update_vb(bvh, &bvh->nodes[node_index], prim_bbc, offset, count);
392                 
393         if (bvh->looptri)
394                 build_mesh_leaf_node(bvh, bvh->nodes + node_index);
395         else {
396                 build_grid_leaf_node(bvh, bvh->nodes + node_index);
397         }
398 }
399
400 /* Return zero if all primitives in the node can be drawn with the
401  * same material (including flat/smooth shading), non-zero otherwise */
402 static bool leaf_needs_material_split(PBVH *bvh, int offset, int count)
403 {
404         if (count <= 1)
405                 return false;
406
407         if (bvh->looptri) {
408                 const MLoopTri *first = &bvh->looptri[bvh->prim_indices[offset]];
409                 const MPoly *mp = &bvh->mpoly[first->poly];
410
411                 for (int i = offset + count - 1; i > offset; --i) {
412                         int prim = bvh->prim_indices[i];
413                         const MPoly *mp_other = &bvh->mpoly[bvh->looptri[prim].poly];
414                         if (!face_materials_match(mp, mp_other)) {
415                                 return true;
416                         }
417                 }
418         }
419         else {
420                 const DMFlagMat *first = &bvh->grid_flag_mats[bvh->prim_indices[offset]];
421
422                 for (int i = offset + count - 1; i > offset; --i) {
423                         int prim = bvh->prim_indices[i];
424                         if (!grid_materials_match(first, &bvh->grid_flag_mats[prim]))
425                                 return true;
426                 }
427         }
428
429         return false;
430 }
431
432
433 /* Recursively build a node in the tree
434  *
435  * vb is the voxel box around all of the primitives contained in
436  * this node.
437  *
438  * cb is the bounding box around all the centroids of the primitives
439  * contained in this node
440  *
441  * offset and start indicate a range in the array of primitive indices
442  */
443
444 static void build_sub(PBVH *bvh, int node_index, BB *cb, BBC *prim_bbc,
445                       int offset, int count)
446 {
447         int end;
448         BB cb_backing;
449
450         /* Decide whether this is a leaf or not */
451         const bool below_leaf_limit = count <= bvh->leaf_limit;
452         if (below_leaf_limit) {
453                 if (!leaf_needs_material_split(bvh, offset, count)) {
454                         build_leaf(bvh, node_index, prim_bbc, offset, count);
455                         return;
456                 }
457         }
458
459         /* Add two child nodes */
460         bvh->nodes[node_index].children_offset = bvh->totnode;
461         pbvh_grow_nodes(bvh, bvh->totnode + 2);
462
463         /* Update parent node bounding box */
464         update_vb(bvh, &bvh->nodes[node_index], prim_bbc, offset, count);
465
466         if (!below_leaf_limit) {
467                 /* Find axis with widest range of primitive centroids */
468                 if (!cb) {
469                         cb = &cb_backing;
470                         BB_reset(cb);
471                         for (int i = offset + count - 1; i >= offset; --i)
472                                 BB_expand(cb, prim_bbc[bvh->prim_indices[i]].bcentroid);
473                 }
474                 const int axis = BB_widest_axis(cb);
475
476                 /* Partition primitives along that axis */
477                 end = partition_indices(bvh->prim_indices,
478                                         offset, offset + count - 1,
479                                         axis,
480                                         (cb->bmax[axis] + cb->bmin[axis]) * 0.5f,
481                                         prim_bbc);
482         }
483         else {
484                 /* Partition primitives by material */
485                 end = partition_indices_material(bvh, offset, offset + count - 1);
486         }
487
488         /* Build children */
489         build_sub(bvh, bvh->nodes[node_index].children_offset, NULL,
490                   prim_bbc, offset, end - offset);
491         build_sub(bvh, bvh->nodes[node_index].children_offset + 1, NULL,
492                   prim_bbc, end, offset + count - end);
493 }
494
495 static void pbvh_build(PBVH *bvh, BB *cb, BBC *prim_bbc, int totprim)
496 {
497         if (totprim != bvh->totprim) {
498                 bvh->totprim = totprim;
499                 if (bvh->nodes) MEM_freeN(bvh->nodes);
500                 if (bvh->prim_indices) MEM_freeN(bvh->prim_indices);
501                 bvh->prim_indices = MEM_mallocN(sizeof(int) * totprim,
502                                                 "bvh prim indices");
503                 for (int i = 0; i < totprim; ++i)
504                         bvh->prim_indices[i] = i;
505                 bvh->totnode = 0;
506                 if (bvh->node_mem_count < 100) {
507                         bvh->node_mem_count = 100;
508                         bvh->nodes = MEM_callocN(sizeof(PBVHNode) *
509                                                  bvh->node_mem_count,
510                                                  "bvh initial nodes");
511                 }
512         }
513
514         bvh->totnode = 1;
515         build_sub(bvh, 0, cb, prim_bbc, 0, totprim);
516 }
517
518 /**
519  * Do a full rebuild with on Mesh data structure.
520  *
521  * \note Unlike mpoly/mloop/verts, looptri is **totally owned** by PBVH (which means it may rewrite it if needed,
522  *       see BKE_pbvh_apply_vertCos().
523  */
524 void BKE_pbvh_build_mesh(
525         PBVH *bvh, const MPoly *mpoly, const MLoop *mloop, MVert *verts,
526         int totvert, struct CustomData *vdata,
527         const MLoopTri *looptri, int looptri_num)
528 {
529         BBC *prim_bbc = NULL;
530         BB cb;
531
532         bvh->type = PBVH_FACES;
533         bvh->mpoly = mpoly;
534         bvh->mloop = mloop;
535         bvh->looptri = looptri;
536         bvh->verts = verts;
537         bvh->vert_bitmap = BLI_BITMAP_NEW(totvert, "bvh->vert_bitmap");
538         bvh->totvert = totvert;
539         bvh->leaf_limit = LEAF_LIMIT;
540         bvh->vdata = vdata;
541
542         BB_reset(&cb);
543
544         /* For each face, store the AABB and the AABB centroid */
545         prim_bbc = MEM_mallocN(sizeof(BBC) * looptri_num, "prim_bbc");
546
547         for (int i = 0; i < looptri_num; ++i) {
548                 const MLoopTri *lt = &looptri[i];
549                 const int sides = 3;
550                 BBC *bbc = prim_bbc + i;
551
552                 BB_reset((BB *)bbc);
553
554                 for (int j = 0; j < sides; ++j)
555                         BB_expand((BB *)bbc, verts[bvh->mloop[lt->tri[j]].v].co);
556
557                 BBC_update_centroid(bbc);
558
559                 BB_expand(&cb, bbc->bcentroid);
560         }
561
562         if (looptri_num)
563                 pbvh_build(bvh, &cb, prim_bbc, looptri_num);
564
565         MEM_freeN(prim_bbc);
566         MEM_freeN(bvh->vert_bitmap);
567 }
568
569 /* Do a full rebuild with on Grids data structure */
570 void BKE_pbvh_build_grids(PBVH *bvh, CCGElem **grids,
571                           int totgrid, CCGKey *key, void **gridfaces, DMFlagMat *flagmats, BLI_bitmap **grid_hidden)
572 {
573         const int gridsize = key->grid_size;
574
575         bvh->type = PBVH_GRIDS;
576         bvh->grids = grids;
577         bvh->gridfaces = gridfaces;
578         bvh->grid_flag_mats = flagmats;
579         bvh->totgrid = totgrid;
580         bvh->gridkey = *key;
581         bvh->grid_hidden = grid_hidden;
582         bvh->leaf_limit = max_ii(LEAF_LIMIT / ((gridsize - 1) * (gridsize - 1)), 1);
583
584         BB cb;
585         BB_reset(&cb);
586
587         /* For each grid, store the AABB and the AABB centroid */
588         BBC *prim_bbc = MEM_mallocN(sizeof(BBC) * totgrid, "prim_bbc");
589
590         for (int i = 0; i < totgrid; ++i) {
591                 CCGElem *grid = grids[i];
592                 BBC *bbc = prim_bbc + i;
593
594                 BB_reset((BB *)bbc);
595
596                 for (int j = 0; j < gridsize * gridsize; ++j)
597                         BB_expand((BB *)bbc, CCG_elem_offset_co(key, grid, j));
598
599                 BBC_update_centroid(bbc);
600
601                 BB_expand(&cb, bbc->bcentroid);
602         }
603
604         if (totgrid)
605                 pbvh_build(bvh, &cb, prim_bbc, totgrid);
606
607         MEM_freeN(prim_bbc);
608 }
609
610 void BKE_pbvh_set_ccgdm(PBVH *bvh, CCGDerivedMesh *ccgdm) {
611         bvh->ccgdm = ccgdm;
612 }
613
614 PBVH *BKE_pbvh_new(void)
615 {
616         PBVH *bvh = MEM_callocN(sizeof(PBVH), "pbvh");
617
618         return bvh;
619 }
620
621 void BKE_pbvh_free(PBVH *bvh)
622 {
623         for (int i = 0; i < bvh->totnode; ++i) {
624                 PBVHNode *node = &bvh->nodes[i];
625
626                 if (node->flag & PBVH_Leaf) {
627                         if (node->draw_buffers)
628                                 GPU_pbvh_buffers_free(node->draw_buffers);
629                         if (node->vert_indices)
630                                 MEM_freeN((void *)node->vert_indices);
631                         if (node->face_vert_indices)
632                                 MEM_freeN((void *)node->face_vert_indices);
633                         BKE_pbvh_node_layer_disp_free(node);
634
635                         if (node->bm_faces)
636                                 BLI_gset_free(node->bm_faces, NULL);
637                         if (node->bm_unique_verts)
638                                 BLI_gset_free(node->bm_unique_verts, NULL);
639                         if (node->bm_other_verts)
640                                 BLI_gset_free(node->bm_other_verts, NULL);
641                 }
642         }
643         GPU_pbvh_multires_buffers_free(&bvh->grid_common_gpu_buffer);
644
645         if (bvh->deformed) {
646                 if (bvh->verts) {
647                         /* if pbvh was deformed, new memory was allocated for verts/faces -- free it */
648
649                         MEM_freeN((void *)bvh->verts);
650                 }
651         }
652
653         if (bvh->looptri) {
654                 MEM_freeN((void *)bvh->looptri);
655         }
656
657         if (bvh->nodes)
658                 MEM_freeN(bvh->nodes);
659
660         if (bvh->prim_indices)
661                 MEM_freeN(bvh->prim_indices);
662
663         MEM_freeN(bvh);
664 }
665
666 void BKE_pbvh_free_layer_disp(PBVH *bvh)
667 {
668         for (int i = 0; i < bvh->totnode; ++i)
669                 BKE_pbvh_node_layer_disp_free(&bvh->nodes[i]);
670 }
671
672 static void pbvh_iter_begin(PBVHIter *iter, PBVH *bvh, BKE_pbvh_SearchCallback scb, void *search_data)
673 {
674         iter->bvh = bvh;
675         iter->scb = scb;
676         iter->search_data = search_data;
677
678         iter->stack = iter->stackfixed;
679         iter->stackspace = STACK_FIXED_DEPTH;
680
681         iter->stack[0].node = bvh->nodes;
682         iter->stack[0].revisiting = false;
683         iter->stacksize = 1;
684 }
685
686 static void pbvh_iter_end(PBVHIter *iter)
687 {
688         if (iter->stackspace > STACK_FIXED_DEPTH)
689                 MEM_freeN(iter->stack);
690 }
691
692 static void pbvh_stack_push(PBVHIter *iter, PBVHNode *node, bool revisiting)
693 {
694         if (UNLIKELY(iter->stacksize == iter->stackspace)) {
695                 iter->stackspace *= 2;
696                 if (iter->stackspace != (STACK_FIXED_DEPTH * 2)) {
697                         iter->stack = MEM_reallocN(iter->stack, sizeof(PBVHStack) * iter->stackspace);
698                 }
699                 else {
700                         iter->stack = MEM_mallocN(sizeof(PBVHStack) * iter->stackspace, "PBVHStack");
701                         memcpy(iter->stack, iter->stackfixed, sizeof(PBVHStack) * iter->stacksize);
702                 }
703         }
704
705         iter->stack[iter->stacksize].node = node;
706         iter->stack[iter->stacksize].revisiting = revisiting;
707         iter->stacksize++;
708 }
709
710 static PBVHNode *pbvh_iter_next(PBVHIter *iter)
711 {
712         /* purpose here is to traverse tree, visiting child nodes before their
713          * parents, this order is necessary for e.g. computing bounding boxes */
714
715         while (iter->stacksize) {
716                 /* pop node */
717                 iter->stacksize--;
718                 PBVHNode *node = iter->stack[iter->stacksize].node;
719
720                 /* on a mesh with no faces this can happen
721                  * can remove this check if we know meshes have at least 1 face */
722                 if (node == NULL)
723                         return NULL;
724
725                 bool revisiting = iter->stack[iter->stacksize].revisiting;
726
727                 /* revisiting node already checked */
728                 if (revisiting)
729                         return node;
730
731                 if (iter->scb && !iter->scb(node, iter->search_data))
732                         continue;  /* don't traverse, outside of search zone */
733
734                 if (node->flag & PBVH_Leaf) {
735                         /* immediately hit leaf node */
736                         return node;
737                 }
738                 else {
739                         /* come back later when children are done */
740                         pbvh_stack_push(iter, node, true);
741
742                         /* push two child nodes on the stack */
743                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset + 1, false);
744                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset, false);
745                 }
746         }
747
748         return NULL;
749 }
750
751 static PBVHNode *pbvh_iter_next_occluded(PBVHIter *iter)
752 {
753         while (iter->stacksize) {
754                 /* pop node */
755                 iter->stacksize--;
756                 PBVHNode *node = iter->stack[iter->stacksize].node;
757
758                 /* on a mesh with no faces this can happen
759                  * can remove this check if we know meshes have at least 1 face */
760                 if (node == NULL) return NULL;
761
762                 if (iter->scb && !iter->scb(node, iter->search_data)) continue;  /* don't traverse, outside of search zone */
763
764                 if (node->flag & PBVH_Leaf) {
765                         /* immediately hit leaf node */
766                         return node;
767                 }
768                 else {
769                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset + 1, false);
770                         pbvh_stack_push(iter, iter->bvh->nodes + node->children_offset, false);
771                 }
772         }
773
774         return NULL;
775 }
776
777 void BKE_pbvh_search_gather(PBVH *bvh,
778                             BKE_pbvh_SearchCallback scb, void *search_data,
779                             PBVHNode ***r_array, int *r_tot)
780 {
781         PBVHIter iter;
782         PBVHNode **array = NULL, *node;
783         int tot = 0, space = 0;
784
785         pbvh_iter_begin(&iter, bvh, scb, search_data);
786
787         while ((node = pbvh_iter_next(&iter))) {
788                 if (node->flag & PBVH_Leaf) {
789                         if (UNLIKELY(tot == space)) {
790                                 /* resize array if needed */
791                                 space = (tot == 0) ? 32 : space * 2;
792                                 array = MEM_recallocN_id(array, sizeof(PBVHNode *) * space, __func__);
793                         }
794
795                         array[tot] = node;
796                         tot++;
797                 }
798         }
799
800         pbvh_iter_end(&iter);
801
802         if (tot == 0 && array) {
803                 MEM_freeN(array);
804                 array = NULL;
805         }
806
807         *r_array = array;
808         *r_tot = tot;
809 }
810
811 void BKE_pbvh_search_callback(PBVH *bvh,
812                               BKE_pbvh_SearchCallback scb, void *search_data,
813                               BKE_pbvh_HitCallback hcb, void *hit_data)
814 {
815         PBVHIter iter;
816         PBVHNode *node;
817
818         pbvh_iter_begin(&iter, bvh, scb, search_data);
819
820         while ((node = pbvh_iter_next(&iter)))
821                 if (node->flag & PBVH_Leaf)
822                         hcb(node, hit_data);
823
824         pbvh_iter_end(&iter);
825 }
826
827 typedef struct node_tree {
828         PBVHNode *data;
829
830         struct node_tree *left;
831         struct node_tree *right;
832 } node_tree;
833
834 static void node_tree_insert(node_tree *tree, node_tree *new_node)
835 {
836         if (new_node->data->tmin < tree->data->tmin) {
837                 if (tree->left) {
838                         node_tree_insert(tree->left, new_node);
839                 }
840                 else {
841                         tree->left = new_node;
842                 }
843         }
844         else {
845                 if (tree->right) {
846                         node_tree_insert(tree->right, new_node);
847                 }
848                 else {
849                         tree->right = new_node;
850                 }
851         }
852 }
853
854 static void traverse_tree(node_tree *tree, BKE_pbvh_HitOccludedCallback hcb, void *hit_data, float *tmin)
855 {
856         if (tree->left) traverse_tree(tree->left, hcb, hit_data, tmin);
857
858         hcb(tree->data, hit_data, tmin);
859
860         if (tree->right) traverse_tree(tree->right, hcb, hit_data, tmin);
861 }
862
863 static void free_tree(node_tree *tree)
864 {
865         if (tree->left) {
866                 free_tree(tree->left);
867                 tree->left = NULL;
868         }
869
870         if (tree->right) {
871                 free_tree(tree->right);
872                 tree->right = NULL;
873         }
874
875         free(tree);
876 }
877
878 float BKE_pbvh_node_get_tmin(PBVHNode *node)
879 {
880         return node->tmin;
881 }
882
883 static void BKE_pbvh_search_callback_occluded(PBVH *bvh,
884                                               BKE_pbvh_SearchCallback scb, void *search_data,
885                                               BKE_pbvh_HitOccludedCallback hcb, void *hit_data)
886 {
887         PBVHIter iter;
888         PBVHNode *node;
889         node_tree *tree = NULL;
890
891         pbvh_iter_begin(&iter, bvh, scb, search_data);
892
893         while ((node = pbvh_iter_next_occluded(&iter))) {
894                 if (node->flag & PBVH_Leaf) {
895                         node_tree *new_node = malloc(sizeof(node_tree));
896
897                         new_node->data = node;
898
899                         new_node->left  = NULL;
900                         new_node->right = NULL;
901
902                         if (tree) {
903                                 node_tree_insert(tree, new_node);
904                         }
905                         else {
906                                 tree = new_node;
907                         }
908                 }
909         }
910
911         pbvh_iter_end(&iter);
912
913         if (tree) {
914                 float tmin = FLT_MAX;
915                 traverse_tree(tree, hcb, hit_data, &tmin);
916                 free_tree(tree);
917         }
918 }
919
920 static bool update_search_cb(PBVHNode *node, void *data_v)
921 {
922         int flag = GET_INT_FROM_POINTER(data_v);
923
924         if (node->flag & PBVH_Leaf)
925                 return (node->flag & flag) != 0;
926
927         return true;
928 }
929
930 typedef struct PBVHUpdateData {
931         PBVH *bvh;
932         PBVHNode **nodes;
933         int totnode;
934
935         float (*fnors)[3];
936         float (*vnors)[3];
937         int flag;
938 } PBVHUpdateData;
939
940 static void pbvh_update_normals_accum_task_cb(void *userdata, const int n)
941 {
942         PBVHUpdateData *data = userdata;
943
944         PBVH *bvh = data->bvh;
945         PBVHNode *node = data->nodes[n];
946         float (*fnors)[3] = data->fnors;
947         float (*vnors)[3] = data->vnors;
948
949         if ((node->flag & PBVH_UpdateNormals)) {
950                 unsigned int mpoly_prev = UINT_MAX;
951                 float fn[3];
952
953                 const int *faces = node->prim_indices;
954                 const int totface = node->totprim;
955
956                 for (int i = 0; i < totface; ++i) {
957                         const MLoopTri *lt = &bvh->looptri[faces[i]];
958                         const unsigned int vtri[3] = {
959                                 bvh->mloop[lt->tri[0]].v,
960                                 bvh->mloop[lt->tri[1]].v,
961                                 bvh->mloop[lt->tri[2]].v,
962                         };
963                         const int sides = 3;
964
965                         /* Face normal and mask */
966                         if (lt->poly != mpoly_prev) {
967                                 const MPoly *mp = &bvh->mpoly[lt->poly];
968                                 BKE_mesh_calc_poly_normal(mp, &bvh->mloop[mp->loopstart], bvh->verts, fn);
969                                 mpoly_prev = lt->poly;
970
971                                 if (fnors) {
972                                         /* We can assume a face is only present in one node ever. */
973                                         copy_v3_v3(fnors[lt->poly], fn);
974                                 }
975                         }
976
977                         for (int j = sides; j--; ) {
978                                 const int v = vtri[j];
979
980                                 if (bvh->verts[v].flag & ME_VERT_PBVH_UPDATE) {
981                                         /* Note: This avoids `lock, add_v3_v3, unlock` and is five to ten times quicker than a spinlock.
982                                          *       Not exact equivalent though, since atomicity is only ensured for one component
983                                          *       of the vector at a time, but here it shall not make any sensible difference. */
984                                         for (int k = 3; k--; ) {
985                                                 atomic_add_and_fetch_fl(&vnors[v][k], fn[k]);
986                                         }
987                                 }
988                         }
989                 }
990         }
991 }
992
993 static void pbvh_update_normals_store_task_cb(void *userdata, const int n)
994 {
995         PBVHUpdateData *data = userdata;
996         PBVH *bvh = data->bvh;
997         PBVHNode *node = data->nodes[n];
998         float (*vnors)[3] = data->vnors;
999
1000         if (node->flag & PBVH_UpdateNormals) {
1001                 const int *verts = node->vert_indices;
1002                 const int totvert = node->uniq_verts;
1003
1004                 for (int i = 0; i < totvert; ++i) {
1005                         const int v = verts[i];
1006                         MVert *mvert = &bvh->verts[v];
1007
1008                         /* mvert is shared between nodes, hence between threads. */
1009                         if (atomic_fetch_and_and_uint8(
1010                                 (uint8_t *)&mvert->flag, (uint8_t)~ME_VERT_PBVH_UPDATE) & ME_VERT_PBVH_UPDATE)
1011                         {
1012                                 normalize_v3(vnors[v]);
1013                                 normal_float_to_short_v3(mvert->no, vnors[v]);
1014                         }
1015                 }
1016
1017                 node->flag &= ~PBVH_UpdateNormals;
1018         }
1019 }
1020
1021 static void pbvh_update_normals(PBVH *bvh, PBVHNode **nodes,
1022                                 int totnode, float (*fnors)[3])
1023 {
1024         float (*vnors)[3];
1025
1026         if (bvh->type == PBVH_BMESH) {
1027                 BLI_assert(fnors == NULL);
1028                 pbvh_bmesh_normals_update(nodes, totnode);
1029                 return;
1030         }
1031
1032         if (bvh->type != PBVH_FACES)
1033                 return;
1034
1035         /* could be per node to save some memory, but also means
1036          * we have to store for each vertex which node it is in */
1037         vnors = MEM_callocN(sizeof(*vnors) * bvh->totvert, __func__);
1038
1039         /* subtle assumptions:
1040          * - We know that for all edited vertices, the nodes with faces
1041          *   adjacent to these vertices have been marked with PBVH_UpdateNormals.
1042          *   This is true because if the vertex is inside the brush radius, the
1043          *   bounding box of it's adjacent faces will be as well.
1044          * - However this is only true for the vertices that have actually been
1045          *   edited, not for all vertices in the nodes marked for update, so we
1046          *   can only update vertices marked with ME_VERT_PBVH_UPDATE.
1047          */
1048
1049         PBVHUpdateData data = {
1050             .bvh = bvh, .nodes = nodes,
1051             .fnors = fnors, .vnors = vnors,
1052         };
1053
1054         BLI_task_parallel_range(0, totnode, &data, pbvh_update_normals_accum_task_cb, totnode > PBVH_THREADED_LIMIT);
1055
1056         BLI_task_parallel_range(0, totnode, &data, pbvh_update_normals_store_task_cb, totnode > PBVH_THREADED_LIMIT);
1057
1058         MEM_freeN(vnors);
1059 }
1060
1061 static void pbvh_update_BB_redraw_task_cb(void *userdata, const int n)
1062 {
1063         PBVHUpdateData *data = userdata;
1064         PBVH *bvh = data->bvh;
1065         PBVHNode *node = data->nodes[n];
1066         const int flag = data->flag;
1067
1068         if ((flag & PBVH_UpdateBB) && (node->flag & PBVH_UpdateBB))
1069                 /* don't clear flag yet, leave it for flushing later */
1070                 /* Note that bvh usage is read-only here, so no need to thread-protect it. */
1071                 update_node_vb(bvh, node);
1072
1073         if ((flag & PBVH_UpdateOriginalBB) && (node->flag & PBVH_UpdateOriginalBB))
1074                 node->orig_vb = node->vb;
1075
1076         if ((flag & PBVH_UpdateRedraw) && (node->flag & PBVH_UpdateRedraw))
1077                 node->flag &= ~PBVH_UpdateRedraw;
1078 }
1079
1080 void pbvh_update_BB_redraw(PBVH *bvh, PBVHNode **nodes, int totnode, int flag)
1081 {
1082         /* update BB, redraw flag */
1083         PBVHUpdateData data = {
1084             .bvh = bvh, .nodes = nodes,
1085             .flag = flag,
1086         };
1087
1088         BLI_task_parallel_range(0, totnode, &data, pbvh_update_BB_redraw_task_cb, totnode > PBVH_THREADED_LIMIT);
1089 }
1090
1091 static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode)
1092 {
1093         /* can't be done in parallel with OpenGL */
1094         for (int n = 0; n < totnode; n++) {
1095                 PBVHNode *node = nodes[n];
1096
1097                 if (node->flag & PBVH_RebuildDrawBuffers) {
1098                         GPU_pbvh_buffers_free(node->draw_buffers);
1099                         switch (bvh->type) {
1100                                 case PBVH_GRIDS:
1101                                         node->draw_buffers =
1102                                                 GPU_pbvh_grid_buffers_build(node->prim_indices,
1103                                                                    node->totprim,
1104                                                                    bvh->grid_hidden,
1105                                                                    bvh->gridkey.grid_size,
1106                                                                    &bvh->gridkey, &bvh->grid_common_gpu_buffer);
1107                                         break;
1108                                 case PBVH_FACES:
1109                                         node->draw_buffers =
1110                                                 GPU_pbvh_mesh_buffers_build(node->face_vert_indices,
1111                                                                    bvh->mpoly, bvh->mloop, bvh->looptri,
1112                                                                    bvh->verts,
1113                                                                    node->prim_indices,
1114                                                                    node->totprim);
1115                                         break;
1116                                 case PBVH_BMESH:
1117                                         node->draw_buffers =
1118                                                 GPU_pbvh_bmesh_buffers_build(bvh->flags & PBVH_DYNTOPO_SMOOTH_SHADING);
1119                                         break;
1120                         }
1121
1122                         node->flag &= ~PBVH_RebuildDrawBuffers;
1123                 }
1124
1125                 if (node->flag & PBVH_UpdateDrawBuffers) {
1126                         switch (bvh->type) {
1127                                 case PBVH_GRIDS:
1128                                         GPU_pbvh_grid_buffers_update(
1129                                                 node->draw_buffers,
1130                                                 bvh->grids,
1131                                                 bvh->grid_flag_mats,
1132                                                 node->prim_indices,
1133                                                 node->totprim,
1134                                                 &bvh->gridkey,
1135                                                 bvh->show_diffuse_color);
1136                                         break;
1137                                 case PBVH_FACES:
1138                                         GPU_pbvh_mesh_buffers_update(
1139                                                 node->draw_buffers,
1140                                                 bvh->verts,
1141                                                 node->vert_indices,
1142                                                 node->uniq_verts +
1143                                                 node->face_verts,
1144                                                 CustomData_get_layer(bvh->vdata, CD_PAINT_MASK),
1145                                                 node->face_vert_indices,
1146                                                 bvh->show_diffuse_color);
1147                                         break;
1148                                 case PBVH_BMESH:
1149                                         GPU_pbvh_bmesh_buffers_update(
1150                                                 node->draw_buffers,
1151                                                 bvh->bm,
1152                                                 node->bm_faces,
1153                                                 node->bm_unique_verts,
1154                                                 node->bm_other_verts,
1155                                                 bvh->show_diffuse_color);
1156                                         break;
1157                         }
1158
1159                         node->flag &= ~PBVH_UpdateDrawBuffers;
1160                 }
1161         }
1162 }
1163
1164 void BKE_pbvh_draw_BB(PBVH *bvh)
1165 {
1166         GPU_pbvh_BB_draw_init();
1167
1168         for (int a = 0; a < bvh->totnode; a++) {
1169                 PBVHNode *node = &bvh->nodes[a];
1170
1171                 GPU_pbvh_BB_draw(node->vb.bmin, node->vb.bmax, ((node->flag & PBVH_Leaf) != 0));
1172         }
1173
1174         GPU_pbvh_BB_draw_end();
1175 }
1176
1177 static int pbvh_flush_bb(PBVH *bvh, PBVHNode *node, int flag)
1178 {
1179         int update = 0;
1180
1181         /* difficult to multithread well, we just do single threaded recursive */
1182         if (node->flag & PBVH_Leaf) {
1183                 if (flag & PBVH_UpdateBB) {
1184                         update |= (node->flag & PBVH_UpdateBB);
1185                         node->flag &= ~PBVH_UpdateBB;
1186                 }
1187
1188                 if (flag & PBVH_UpdateOriginalBB) {
1189                         update |= (node->flag & PBVH_UpdateOriginalBB);
1190                         node->flag &= ~PBVH_UpdateOriginalBB;
1191                 }
1192
1193                 return update;
1194         }
1195         else {
1196                 update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset, flag);
1197                 update |= pbvh_flush_bb(bvh, bvh->nodes + node->children_offset + 1, flag);
1198
1199                 if (update & PBVH_UpdateBB)
1200                         update_node_vb(bvh, node);
1201                 if (update & PBVH_UpdateOriginalBB)
1202                         node->orig_vb = node->vb;
1203         }
1204
1205         return update;
1206 }
1207
1208 void BKE_pbvh_update(PBVH *bvh, int flag, float (*fnors)[3])
1209 {
1210         if (!bvh->nodes)
1211                 return;
1212
1213         PBVHNode **nodes;
1214         int totnode;
1215
1216         BKE_pbvh_search_gather(bvh, update_search_cb, SET_INT_IN_POINTER(flag),
1217                                &nodes, &totnode);
1218
1219         if (flag & PBVH_UpdateNormals)
1220                 pbvh_update_normals(bvh, nodes, totnode, fnors);
1221
1222         if (flag & (PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateRedraw))
1223                 pbvh_update_BB_redraw(bvh, nodes, totnode, flag);
1224
1225         if (flag & (PBVH_UpdateBB | PBVH_UpdateOriginalBB))
1226                 pbvh_flush_bb(bvh, bvh->nodes, flag);
1227
1228         if (nodes) MEM_freeN(nodes);
1229 }
1230
1231 void BKE_pbvh_redraw_BB(PBVH *bvh, float bb_min[3], float bb_max[3])
1232 {
1233         PBVHIter iter;
1234         PBVHNode *node;
1235         BB bb;
1236
1237         BB_reset(&bb);
1238
1239         pbvh_iter_begin(&iter, bvh, NULL, NULL);
1240
1241         while ((node = pbvh_iter_next(&iter)))
1242                 if (node->flag & PBVH_UpdateRedraw)
1243                         BB_expand_with_bb(&bb, &node->vb);
1244
1245         pbvh_iter_end(&iter);
1246
1247         copy_v3_v3(bb_min, bb.bmin);
1248         copy_v3_v3(bb_max, bb.bmax);
1249 }
1250
1251 void BKE_pbvh_get_grid_updates(PBVH *bvh, bool clear, void ***r_gridfaces, int *r_totface)
1252 {
1253         GSet *face_set = BLI_gset_ptr_new(__func__);
1254         PBVHNode *node;
1255         PBVHIter iter;
1256
1257         pbvh_iter_begin(&iter, bvh, NULL, NULL);
1258
1259         while ((node = pbvh_iter_next(&iter))) {
1260                 if (node->flag & PBVH_UpdateNormals) {
1261                         for (unsigned i = 0; i < node->totprim; ++i) {
1262                                 void *face = bvh->gridfaces[node->prim_indices[i]];
1263                                 BLI_gset_add(face_set, face);
1264                         }
1265
1266                         if (clear)
1267                                 node->flag &= ~PBVH_UpdateNormals;
1268                 }
1269         }
1270
1271         pbvh_iter_end(&iter);
1272         
1273         const int tot = BLI_gset_size(face_set);
1274         if (tot == 0) {
1275                 *r_totface = 0;
1276                 *r_gridfaces = NULL;
1277                 BLI_gset_free(face_set, NULL);
1278                 return;
1279         }
1280
1281         void **faces = MEM_mallocN(sizeof(*faces) * tot, "PBVH Grid Faces");
1282
1283         GSetIterator gs_iter;
1284         int i;
1285         GSET_ITER_INDEX (gs_iter, face_set, i) {
1286                 faces[i] = BLI_gsetIterator_getKey(&gs_iter);
1287         }
1288
1289         BLI_gset_free(face_set, NULL);
1290
1291         *r_totface = tot;
1292         *r_gridfaces = faces;
1293 }
1294
1295 /***************************** PBVH Access ***********************************/
1296
1297 PBVHType BKE_pbvh_type(const PBVH *bvh)
1298 {
1299         return bvh->type;
1300 }
1301
1302 bool BKE_pbvh_has_faces(const PBVH *bvh)
1303 {
1304         if (bvh->type == PBVH_BMESH) {
1305                 return (bvh->bm->totface != 0);
1306         }
1307         else {
1308                 return (bvh->totprim != 0);
1309         }
1310 }
1311
1312 void BKE_pbvh_bounding_box(const PBVH *bvh, float min[3], float max[3])
1313 {
1314         if (bvh->totnode) {
1315                 const BB *bb = &bvh->nodes[0].vb;
1316                 copy_v3_v3(min, bb->bmin);
1317                 copy_v3_v3(max, bb->bmax);
1318         }
1319         else {
1320                 zero_v3(min);
1321                 zero_v3(max);
1322         }
1323 }
1324
1325 BLI_bitmap **BKE_pbvh_grid_hidden(const PBVH *bvh)
1326 {
1327         BLI_assert(bvh->type == PBVH_GRIDS);
1328         return bvh->grid_hidden;
1329 }
1330
1331 void BKE_pbvh_get_grid_key(const PBVH *bvh, CCGKey *key)
1332 {
1333         BLI_assert(bvh->type == PBVH_GRIDS);
1334         *key = bvh->gridkey;
1335 }
1336
1337 CCGDerivedMesh *BKE_pbvh_get_ccgdm(const PBVH *bvh) {
1338         return bvh->ccgdm;
1339 }
1340
1341
1342 BMesh *BKE_pbvh_get_bmesh(PBVH *bvh)
1343 {
1344         BLI_assert(bvh->type == PBVH_BMESH);
1345         return bvh->bm;
1346 }
1347
1348 /***************************** Node Access ***********************************/
1349
1350 void BKE_pbvh_node_mark_update(PBVHNode *node)
1351 {
1352         node->flag |= PBVH_UpdateNormals | PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateDrawBuffers | PBVH_UpdateRedraw;
1353 }
1354
1355 void BKE_pbvh_node_mark_rebuild_draw(PBVHNode *node)
1356 {
1357         node->flag |= PBVH_RebuildDrawBuffers | PBVH_UpdateDrawBuffers | PBVH_UpdateRedraw;
1358 }
1359
1360 void BKE_pbvh_node_mark_redraw(PBVHNode *node)
1361 {
1362         node->flag |= PBVH_UpdateDrawBuffers | PBVH_UpdateRedraw;
1363 }
1364
1365 void BKE_pbvh_node_mark_normals_update(PBVHNode *node)
1366 {
1367         node->flag |= PBVH_UpdateNormals;
1368 }
1369
1370
1371 void BKE_pbvh_node_fully_hidden_set(PBVHNode *node, int fully_hidden)
1372 {
1373         BLI_assert(node->flag & PBVH_Leaf);
1374         
1375         if (fully_hidden)
1376                 node->flag |= PBVH_FullyHidden;
1377         else
1378                 node->flag &= ~PBVH_FullyHidden;
1379 }
1380
1381 void BKE_pbvh_node_get_verts(
1382         PBVH *bvh, PBVHNode *node,
1383         const int **r_vert_indices, MVert **r_verts)
1384 {
1385         if (r_vert_indices) {
1386                 *r_vert_indices = node->vert_indices;
1387         }
1388
1389         if (r_verts) {
1390                 *r_verts = bvh->verts;
1391         }
1392 }
1393
1394 void BKE_pbvh_node_num_verts(
1395         PBVH *bvh, PBVHNode *node,
1396         int *r_uniquevert, int *r_totvert)
1397 {
1398         int tot;
1399         
1400         switch (bvh->type) {
1401                 case PBVH_GRIDS:
1402                         tot = node->totprim * bvh->gridkey.grid_area;
1403                         if (r_totvert) *r_totvert = tot;
1404                         if (r_uniquevert) *r_uniquevert = tot;
1405                         break;
1406                 case PBVH_FACES:
1407                         if (r_totvert) *r_totvert = node->uniq_verts + node->face_verts;
1408                         if (r_uniquevert) *r_uniquevert = node->uniq_verts;
1409                         break;
1410                 case PBVH_BMESH:
1411                         tot = BLI_gset_size(node->bm_unique_verts);
1412                         if (r_totvert) *r_totvert = tot + BLI_gset_size(node->bm_other_verts);
1413                         if (r_uniquevert) *r_uniquevert = tot;
1414                         break;
1415         }
1416 }
1417
1418 void BKE_pbvh_node_get_grids(
1419         PBVH *bvh, PBVHNode *node,
1420         int **r_grid_indices, int *r_totgrid, int *r_maxgrid, int *r_gridsize, CCGElem ***r_griddata)
1421 {
1422         switch (bvh->type) {
1423                 case PBVH_GRIDS:
1424                         if (r_grid_indices) *r_grid_indices = node->prim_indices;
1425                         if (r_totgrid) *r_totgrid = node->totprim;
1426                         if (r_maxgrid) *r_maxgrid = bvh->totgrid;
1427                         if (r_gridsize) *r_gridsize = bvh->gridkey.grid_size;
1428                         if (r_griddata) *r_griddata = bvh->grids;
1429                         break;
1430                 case PBVH_FACES:
1431                 case PBVH_BMESH:
1432                         if (r_grid_indices) *r_grid_indices = NULL;
1433                         if (r_totgrid) *r_totgrid = 0;
1434                         if (r_maxgrid) *r_maxgrid = 0;
1435                         if (r_gridsize) *r_gridsize = 0;
1436                         if (r_griddata) *r_griddata = NULL;
1437                         break;
1438         }
1439 }
1440
1441 void BKE_pbvh_node_get_BB(PBVHNode *node, float bb_min[3], float bb_max[3])
1442 {
1443         copy_v3_v3(bb_min, node->vb.bmin);
1444         copy_v3_v3(bb_max, node->vb.bmax);
1445 }
1446
1447 void BKE_pbvh_node_get_original_BB(PBVHNode *node, float bb_min[3], float bb_max[3])
1448 {
1449         copy_v3_v3(bb_min, node->orig_vb.bmin);
1450         copy_v3_v3(bb_max, node->orig_vb.bmax);
1451 }
1452
1453 void BKE_pbvh_node_get_proxies(PBVHNode *node, PBVHProxyNode **proxies, int *proxy_count)
1454 {
1455         if (node->proxy_count > 0) {
1456                 if (proxies) *proxies = node->proxies;
1457                 if (proxy_count) *proxy_count = node->proxy_count;
1458         }
1459         else {
1460                 if (proxies) *proxies = NULL;
1461                 if (proxy_count) *proxy_count = 0;
1462         }
1463 }
1464
1465 void BKE_pbvh_node_get_bm_orco_data(
1466         PBVHNode *node,
1467         int (**r_orco_tris)[3], int *r_orco_tris_num, float (**r_orco_coords)[3])
1468 {
1469         *r_orco_tris = node->bm_ortri;
1470         *r_orco_tris_num = node->bm_tot_ortri;
1471         *r_orco_coords = node->bm_orco;
1472 }
1473
1474 /**
1475  * \note doing a full search on all vertices here seems expensive,
1476  * however this is important to avoid having to recalculate boundbox & sync the buffers to the GPU
1477  * (which is far more expensive!) See: T47232.
1478  */
1479 bool BKE_pbvh_node_vert_update_check_any(PBVH *bvh, PBVHNode *node)
1480 {
1481         BLI_assert(bvh->type == PBVH_FACES);
1482         const int *verts = node->vert_indices;
1483         const int totvert = node->uniq_verts + node->face_verts;
1484
1485         for (int i = 0; i < totvert; ++i) {
1486                 const int v = verts[i];
1487                 const MVert *mvert = &bvh->verts[v];
1488
1489                 if (mvert->flag & ME_VERT_PBVH_UPDATE) {
1490                         return true;
1491                 }
1492         }
1493
1494         return false;
1495 }
1496
1497
1498 /********************************* Raycast ***********************************/
1499
1500 typedef struct {
1501         struct IsectRayAABB_Precalc ray;
1502         bool original;
1503 } RaycastData;
1504
1505 static bool ray_aabb_intersect(PBVHNode *node, void *data_v)
1506 {
1507         RaycastData *rcd = data_v;
1508         const float *bb_min, *bb_max;
1509
1510         if (rcd->original) {
1511                 /* BKE_pbvh_node_get_original_BB */
1512                 bb_min = node->orig_vb.bmin;
1513                 bb_max = node->orig_vb.bmax;
1514         }
1515         else {
1516                 /* BKE_pbvh_node_get_BB */
1517                 bb_min = node->vb.bmin;
1518                 bb_max = node->vb.bmax;
1519         }
1520
1521         return isect_ray_aabb_v3(&rcd->ray, bb_min, bb_max, &node->tmin);
1522 }
1523
1524 void BKE_pbvh_raycast(
1525         PBVH *bvh, BKE_pbvh_HitOccludedCallback cb, void *data,
1526         const float ray_start[3], const float ray_normal[3],
1527         bool original)
1528 {
1529         RaycastData rcd;
1530
1531         isect_ray_aabb_v3_precalc(&rcd.ray, ray_start, ray_normal);
1532         rcd.original = original;
1533
1534         BKE_pbvh_search_callback_occluded(bvh, ray_aabb_intersect, &rcd, cb, data);
1535 }
1536
1537 bool ray_face_intersection_quad(
1538         const float ray_start[3], const float ray_normal[3],
1539         const float t0[3], const float t1[3], const float t2[3], const float t3[3],
1540         float *dist)
1541 {
1542         float dist_test;
1543
1544         if ((isect_ray_tri_epsilon_v3(ray_start, ray_normal, t0, t1, t2, &dist_test, NULL, 0.1f) && (dist_test < *dist)) ||
1545             (isect_ray_tri_epsilon_v3(ray_start, ray_normal, t0, t2, t3, &dist_test, NULL, 0.1f) && (dist_test < *dist)))
1546         {
1547                 *dist = dist_test;
1548                 return true;
1549         }
1550         else {
1551                 return false;
1552         }
1553 }
1554
1555 bool ray_face_intersection_tri(
1556         const float ray_start[3], const float ray_normal[3],
1557         const float t0[3], const float t1[3], const float t2[3],
1558         float *dist)
1559 {
1560         float dist_test;
1561
1562         if ((isect_ray_tri_epsilon_v3(ray_start, ray_normal, t0, t1, t2, &dist_test, NULL, 0.1f) && (dist_test < *dist))) {
1563                 *dist = dist_test;
1564                 return true;
1565         }
1566         else {
1567                 return false;
1568         }
1569 }
1570
1571 static bool pbvh_faces_node_raycast(
1572         PBVH *bvh, const PBVHNode *node,
1573         float (*origco)[3],
1574         const float ray_start[3], const float ray_normal[3],
1575         float *dist)
1576 {
1577         const MVert *vert = bvh->verts;
1578         const MLoop *mloop = bvh->mloop;
1579         const int *faces = node->prim_indices;
1580         int i, totface = node->totprim;
1581         bool hit = false;
1582
1583         for (i = 0; i < totface; ++i) {
1584                 const MLoopTri *lt = &bvh->looptri[faces[i]];
1585                 const int *face_verts = node->face_vert_indices[i];
1586
1587                 if (paint_is_face_hidden(lt, vert, mloop))
1588                         continue;
1589
1590                 if (origco) {
1591                         /* intersect with backuped original coordinates */
1592                         hit |= ray_face_intersection_tri(
1593                                 ray_start, ray_normal,
1594                                 origco[face_verts[0]],
1595                                 origco[face_verts[1]],
1596                                 origco[face_verts[2]],
1597                                 dist);
1598                 }
1599                 else {
1600                         /* intersect with current coordinates */
1601                         hit |= ray_face_intersection_tri(
1602                                 ray_start, ray_normal,
1603                                 vert[mloop[lt->tri[0]].v].co,
1604                                 vert[mloop[lt->tri[1]].v].co,
1605                                 vert[mloop[lt->tri[2]].v].co,
1606                                 dist);
1607                 }
1608         }
1609
1610         return hit;
1611 }
1612
1613 static bool pbvh_grids_node_raycast(
1614         PBVH *bvh, PBVHNode *node,
1615         float (*origco)[3],
1616         const float ray_start[3], const float ray_normal[3],
1617         float *dist)
1618 {
1619         const int totgrid = node->totprim;
1620         const int gridsize = bvh->gridkey.grid_size;
1621         bool hit = false;
1622
1623         for (int i = 0; i < totgrid; ++i) {
1624                 CCGElem *grid = bvh->grids[node->prim_indices[i]];
1625                 BLI_bitmap *gh;
1626
1627                 if (!grid)
1628                         continue;
1629
1630                 gh = bvh->grid_hidden[node->prim_indices[i]];
1631
1632                 for (int y = 0; y < gridsize - 1; ++y) {
1633                         for (int x = 0; x < gridsize - 1; ++x) {
1634                                 /* check if grid face is hidden */
1635                                 if (gh) {
1636                                         if (paint_is_grid_face_hidden(gh, gridsize, x, y))
1637                                                 continue;
1638                                 }
1639
1640                                 if (origco) {
1641                                         hit |= ray_face_intersection_quad(
1642                                                 ray_start, ray_normal,
1643                                                 origco[y * gridsize + x],
1644                                                 origco[y * gridsize + x + 1],
1645                                                 origco[(y + 1) * gridsize + x + 1],
1646                                                 origco[(y + 1) * gridsize + x],
1647                                                 dist);
1648                                 }
1649                                 else {
1650                                         hit |= ray_face_intersection_quad(
1651                                                 ray_start, ray_normal,
1652                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x, y),
1653                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y),
1654                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y + 1),
1655                                                 CCG_grid_elem_co(&bvh->gridkey, grid, x, y + 1),
1656                                                 dist);
1657                                 }
1658                         }
1659                 }
1660
1661                 if (origco)
1662                         origco += gridsize * gridsize;
1663         }
1664
1665         return hit;
1666 }
1667
1668 bool BKE_pbvh_node_raycast(
1669         PBVH *bvh, PBVHNode *node, float (*origco)[3], bool use_origco,
1670         const float ray_start[3], const float ray_normal[3],
1671         float *dist)
1672 {
1673         bool hit = false;
1674
1675         if (node->flag & PBVH_FullyHidden)
1676                 return false;
1677
1678         switch (bvh->type) {
1679                 case PBVH_FACES:
1680                         hit |= pbvh_faces_node_raycast(
1681                                 bvh, node, origco,
1682                                 ray_start, ray_normal, dist);
1683                         break;
1684                 case PBVH_GRIDS:
1685                         hit |= pbvh_grids_node_raycast(
1686                                 bvh, node, origco,
1687                                 ray_start, ray_normal, dist);
1688                         break;
1689                 case PBVH_BMESH:
1690                         hit = pbvh_bmesh_node_raycast(
1691                                 node, ray_start, ray_normal, dist, use_origco);
1692                         break;
1693         }
1694
1695         return hit;
1696 }
1697
1698 void BKE_pbvh_raycast_project_ray_root(
1699         PBVH *bvh, bool original,
1700         float ray_start[3], float ray_end[3], float ray_normal[3])
1701 {
1702         if (bvh->nodes) {
1703                 float rootmin_start, rootmin_end;
1704                 float bb_min_root[3], bb_max_root[3], bb_center[3], bb_diff[3];
1705                 struct IsectRayAABB_Precalc ray;
1706                 float ray_normal_inv[3];
1707                 float offset = 1.0f + 1e-3f;
1708                 float offset_vec[3] = {1e-3f, 1e-3f, 1e-3f};
1709
1710                 if (original)
1711                         BKE_pbvh_node_get_original_BB(bvh->nodes, bb_min_root, bb_max_root);
1712                 else
1713                         BKE_pbvh_node_get_BB(bvh->nodes, bb_min_root, bb_max_root);
1714
1715                 /* slightly offset min and max in case we have a zero width node (due to a plane mesh for instance),
1716                  * or faces very close to the bounding box boundary. */
1717                 mid_v3_v3v3(bb_center, bb_max_root, bb_min_root);
1718                 /* diff should be same for both min/max since it's calculated from center */
1719                 sub_v3_v3v3(bb_diff, bb_max_root, bb_center);
1720                 /* handles case of zero width bb */
1721                 add_v3_v3(bb_diff, offset_vec);
1722                 madd_v3_v3v3fl(bb_max_root, bb_center, bb_diff, offset);
1723                 madd_v3_v3v3fl(bb_min_root, bb_center, bb_diff, -offset);
1724
1725                 /* first project start ray */
1726                 isect_ray_aabb_v3_precalc(&ray, ray_start, ray_normal);
1727                 if (!isect_ray_aabb_v3(&ray, bb_min_root, bb_max_root, &rootmin_start))
1728                         return;
1729
1730                 /* then the end ray */
1731                 mul_v3_v3fl(ray_normal_inv, ray_normal, -1.0);
1732                 isect_ray_aabb_v3_precalc(&ray, ray_end, ray_normal_inv);
1733                 /* unlikely to fail exiting if entering succeeded, still keep this here */
1734                 if (!isect_ray_aabb_v3(&ray, bb_min_root, bb_max_root, &rootmin_end))
1735                         return;
1736
1737                 madd_v3_v3v3fl(ray_start, ray_start, ray_normal, rootmin_start);
1738                 madd_v3_v3v3fl(ray_end, ray_end, ray_normal_inv, rootmin_end);
1739         }
1740 }
1741
1742 typedef struct {
1743         DMSetMaterial setMaterial;
1744         bool wireframe;
1745         bool fast;
1746 } PBVHNodeDrawData;
1747
1748 void BKE_pbvh_node_draw(PBVHNode *node, void *data_v)
1749 {
1750         PBVHNodeDrawData *data = data_v;
1751
1752 #if 0
1753         /* XXX: Just some quick code to show leaf nodes in different colors */
1754         float col[3];
1755         float spec[3] = {0.0f, 0.0f, 0.0f};
1756
1757         if (0) { //is_partial) {
1758                 col[0] = (rand() / (float)RAND_MAX); col[1] = col[2] = 0.6;
1759         }
1760         else {
1761                 srand((long long)node);
1762                 for (int i = 0; i < 3; ++i)
1763                         col[i] = (rand() / (float)RAND_MAX) * 0.3 + 0.7;
1764         }
1765
1766         GPU_basic_shader_colors(col, spec, 0, 1.0f);
1767         glColor3f(1, 0, 0);
1768 #endif
1769
1770         if (!(node->flag & PBVH_FullyHidden)) {
1771                 GPU_pbvh_buffers_draw(node->draw_buffers,
1772                                  data->setMaterial,
1773                                  data->wireframe,
1774                                  data->fast);
1775         }
1776 }
1777
1778 typedef enum {
1779         ISECT_INSIDE,
1780         ISECT_OUTSIDE,
1781         ISECT_INTERSECT
1782 } PlaneAABBIsect;
1783
1784 /* Adapted from:
1785  * http://www.gamedev.net/community/forums/topic.asp?topic_id=512123
1786  * Returns true if the AABB is at least partially within the frustum
1787  * (ok, not a real frustum), false otherwise.
1788  */
1789 static PlaneAABBIsect test_planes_aabb(const float bb_min[3],
1790                                        const float bb_max[3],
1791                                        const float (*planes)[4])
1792 {
1793         float vmin[3], vmax[3];
1794         PlaneAABBIsect ret = ISECT_INSIDE;
1795         
1796         for (int i = 0; i < 4; ++i) {
1797                 for (int axis = 0; axis < 3; ++axis) {
1798                         if (planes[i][axis] > 0) {
1799                                 vmin[axis] = bb_min[axis];
1800                                 vmax[axis] = bb_max[axis];
1801                         }
1802                         else {
1803                                 vmin[axis] = bb_max[axis];
1804                                 vmax[axis] = bb_min[axis];
1805                         }
1806                 }
1807                 
1808                 if (dot_v3v3(planes[i], vmin) + planes[i][3] > 0)
1809                         return ISECT_OUTSIDE;
1810                 else if (dot_v3v3(planes[i], vmax) + planes[i][3] >= 0)
1811                         ret = ISECT_INTERSECT;
1812         }
1813
1814         return ret;
1815 }
1816
1817 bool BKE_pbvh_node_planes_contain_AABB(PBVHNode *node, void *data)
1818 {
1819         const float *bb_min, *bb_max;
1820         /* BKE_pbvh_node_get_BB */
1821         bb_min = node->vb.bmin;
1822         bb_max = node->vb.bmax;
1823         
1824         return test_planes_aabb(bb_min, bb_max, data) != ISECT_OUTSIDE;
1825 }
1826
1827 bool BKE_pbvh_node_planes_exclude_AABB(PBVHNode *node, void *data)
1828 {
1829         const float *bb_min, *bb_max;
1830         /* BKE_pbvh_node_get_BB */
1831         bb_min = node->vb.bmin;
1832         bb_max = node->vb.bmax;
1833         
1834         return test_planes_aabb(bb_min, bb_max, data) != ISECT_INSIDE;
1835 }
1836
1837 static void pbvh_node_check_diffuse_changed(PBVH *bvh, PBVHNode *node)
1838 {
1839         if (!node->draw_buffers)
1840                 return;
1841
1842         if (GPU_pbvh_buffers_diffuse_changed(node->draw_buffers, node->bm_faces, bvh->show_diffuse_color))
1843                 node->flag |= PBVH_UpdateDrawBuffers;
1844 }
1845
1846 void BKE_pbvh_draw(PBVH *bvh, float (*planes)[4], float (*fnors)[3],
1847                    DMSetMaterial setMaterial, bool wireframe, bool fast)
1848 {
1849         PBVHNodeDrawData draw_data = {setMaterial, wireframe, fast};
1850         PBVHNode **nodes;
1851         int totnode;
1852
1853         for (int a = 0; a < bvh->totnode; a++)
1854                 pbvh_node_check_diffuse_changed(bvh, &bvh->nodes[a]);
1855
1856         BKE_pbvh_search_gather(bvh, update_search_cb, SET_INT_IN_POINTER(PBVH_UpdateNormals | PBVH_UpdateDrawBuffers),
1857                                &nodes, &totnode);
1858
1859         pbvh_update_normals(bvh, nodes, totnode, fnors);
1860         pbvh_update_draw_buffers(bvh, nodes, totnode);
1861
1862         if (nodes) MEM_freeN(nodes);
1863
1864         if (planes) {
1865                 BKE_pbvh_search_callback(bvh, BKE_pbvh_node_planes_contain_AABB,
1866                                          planes, BKE_pbvh_node_draw, &draw_data);
1867         }
1868         else {
1869                 BKE_pbvh_search_callback(bvh, NULL, NULL, BKE_pbvh_node_draw, &draw_data);
1870         }
1871
1872         if (G.debug_value == 14)
1873                 BKE_pbvh_draw_BB(bvh);
1874 }
1875
1876 void BKE_pbvh_grids_update(PBVH *bvh, CCGElem **grids, void **gridfaces,
1877                            DMFlagMat *flagmats, BLI_bitmap **grid_hidden)
1878 {
1879         bvh->grids = grids;
1880         bvh->gridfaces = gridfaces;
1881
1882         if (flagmats != bvh->grid_flag_mats || bvh->grid_hidden != grid_hidden) {
1883                 bvh->grid_flag_mats = flagmats;
1884                 bvh->grid_hidden = grid_hidden;
1885
1886                 for (int a = 0; a < bvh->totnode; ++a)
1887                         BKE_pbvh_node_mark_rebuild_draw(&bvh->nodes[a]);
1888         }
1889 }
1890
1891 /* Get the node's displacement layer, creating it if necessary */
1892 float *BKE_pbvh_node_layer_disp_get(PBVH *bvh, PBVHNode *node)
1893 {
1894         if (!node->layer_disp) {
1895                 int totvert = 0;
1896                 BKE_pbvh_node_num_verts(bvh, node, &totvert, NULL);
1897                 node->layer_disp = MEM_callocN(sizeof(float) * totvert, "layer disp");
1898         }
1899         return node->layer_disp;
1900 }
1901
1902 /* If the node has a displacement layer, free it and set to null */
1903 void BKE_pbvh_node_layer_disp_free(PBVHNode *node)
1904 {
1905         if (node->layer_disp) {
1906                 MEM_freeN(node->layer_disp);
1907                 node->layer_disp = NULL;
1908         }
1909 }
1910
1911 float (*BKE_pbvh_get_vertCos(PBVH *pbvh))[3]
1912 {
1913         float (*vertCos)[3] = NULL;
1914
1915         if (pbvh->verts) {
1916                 MVert *mvert = pbvh->verts;
1917
1918                 vertCos = MEM_callocN(3 * pbvh->totvert * sizeof(float), "BKE_pbvh_get_vertCoords");
1919                 float *co = (float *)vertCos;
1920
1921                 for (int a = 0; a < pbvh->totvert; a++, mvert++, co += 3) {
1922                         copy_v3_v3(co, mvert->co);
1923                 }
1924         }
1925
1926         return vertCos;
1927 }
1928
1929 void BKE_pbvh_apply_vertCos(PBVH *pbvh, float (*vertCos)[3])
1930 {
1931         if (!pbvh->deformed) {
1932                 if (pbvh->verts) {
1933                         /* if pbvh is not already deformed, verts/faces points to the */
1934                         /* original data and applying new coords to this arrays would lead to */
1935                         /* unneeded deformation -- duplicate verts/faces to avoid this */
1936
1937                         pbvh->verts   = MEM_dupallocN(pbvh->verts);
1938                         /* No need to dupalloc pbvh->looptri, this one is 'totally owned' by pbvh, it's never some mesh data. */
1939
1940                         pbvh->deformed = true;
1941                 }
1942         }
1943
1944         if (pbvh->verts) {
1945                 MVert *mvert = pbvh->verts;
1946                 /* copy new verts coords */
1947                 for (int a = 0; a < pbvh->totvert; ++a, ++mvert) {
1948                         /* no need for float comparison here (memory is exactly equal or not) */
1949                         if (memcmp(mvert->co, vertCos[a], sizeof(float[3])) != 0) {
1950                                 copy_v3_v3(mvert->co, vertCos[a]);
1951                                 mvert->flag |= ME_VERT_PBVH_UPDATE;
1952                         }
1953                 }
1954
1955                 /* coordinates are new -- normals should also be updated */
1956                 BKE_mesh_calc_normals_looptri(
1957                         pbvh->verts, pbvh->totvert,
1958                         pbvh->mloop,
1959                         pbvh->looptri, pbvh->totprim,
1960                         NULL);
1961
1962                 for (int a = 0; a < pbvh->totnode; ++a)
1963                         BKE_pbvh_node_mark_update(&pbvh->nodes[a]);
1964
1965                 BKE_pbvh_update(pbvh, PBVH_UpdateBB, NULL);
1966                 BKE_pbvh_update(pbvh, PBVH_UpdateOriginalBB, NULL);
1967
1968         }
1969 }
1970
1971 bool BKE_pbvh_isDeformed(PBVH *pbvh)
1972 {
1973         return pbvh->deformed;
1974 }
1975 /* Proxies */
1976
1977 PBVHProxyNode *BKE_pbvh_node_add_proxy(PBVH *bvh, PBVHNode *node)
1978 {
1979         int index, totverts;
1980
1981         index = node->proxy_count;
1982
1983         node->proxy_count++;
1984
1985         if (node->proxies)
1986                 node->proxies = MEM_reallocN(node->proxies, node->proxy_count * sizeof(PBVHProxyNode));
1987         else
1988                 node->proxies = MEM_mallocN(sizeof(PBVHProxyNode), "PBVHNodeProxy");
1989
1990         BKE_pbvh_node_num_verts(bvh, node, &totverts, NULL);
1991         node->proxies[index].co = MEM_callocN(sizeof(float[3]) * totverts, "PBVHNodeProxy.co");
1992
1993         return node->proxies + index;
1994 }
1995
1996 void BKE_pbvh_node_free_proxies(PBVHNode *node)
1997 {
1998         for (int p = 0; p < node->proxy_count; p++) {
1999                 MEM_freeN(node->proxies[p].co);
2000                 node->proxies[p].co = NULL;
2001         }
2002
2003         MEM_freeN(node->proxies);
2004         node->proxies = NULL;
2005
2006         node->proxy_count = 0;
2007 }
2008
2009 void BKE_pbvh_gather_proxies(PBVH *pbvh, PBVHNode ***r_array,  int *r_tot)
2010 {
2011         PBVHNode **array = NULL;
2012         int tot = 0, space = 0;
2013
2014         for (int n = 0; n < pbvh->totnode; n++) {
2015                 PBVHNode *node = pbvh->nodes + n;
2016
2017                 if (node->proxy_count > 0) {
2018                         if (tot == space) {
2019                                 /* resize array if needed */
2020                                 space = (tot == 0) ? 32 : space * 2;
2021                                 array = MEM_recallocN_id(array, sizeof(PBVHNode *) * space, __func__);
2022                         }
2023
2024                         array[tot] = node;
2025                         tot++;
2026                 }
2027         }
2028
2029         if (tot == 0 && array) {
2030                 MEM_freeN(array);
2031                 array = NULL;
2032         }
2033
2034         *r_array = array;
2035         *r_tot = tot;
2036 }
2037
2038 void pbvh_vertex_iter_init(PBVH *bvh, PBVHNode *node,
2039                            PBVHVertexIter *vi, int mode)
2040 {
2041         struct CCGElem **grids;
2042         struct MVert *verts;
2043         const int *vert_indices;
2044         int *grid_indices;
2045         int totgrid, gridsize, uniq_verts, totvert;
2046         
2047         vi->grid = NULL;
2048         vi->no = NULL;
2049         vi->fno = NULL;
2050         vi->mvert = NULL;
2051         
2052         BKE_pbvh_node_get_grids(bvh, node, &grid_indices, &totgrid, NULL, &gridsize, &grids);
2053         BKE_pbvh_node_num_verts(bvh, node, &uniq_verts, &totvert);
2054         BKE_pbvh_node_get_verts(bvh, node, &vert_indices, &verts);
2055         vi->key = &bvh->gridkey;
2056         
2057         vi->grids = grids;
2058         vi->grid_indices = grid_indices;
2059         vi->totgrid = (grids) ? totgrid : 1;
2060         vi->gridsize = gridsize;
2061         
2062         if (mode == PBVH_ITER_ALL)
2063                 vi->totvert = totvert;
2064         else
2065                 vi->totvert = uniq_verts;
2066         vi->vert_indices = vert_indices;
2067         vi->mverts = verts;
2068
2069         if (bvh->type == PBVH_BMESH) {
2070                 BLI_gsetIterator_init(&vi->bm_unique_verts, node->bm_unique_verts);
2071                 BLI_gsetIterator_init(&vi->bm_other_verts, node->bm_other_verts);
2072                 vi->bm_vdata = &bvh->bm->vdata;
2073                 vi->cd_vert_mask_offset = CustomData_get_offset(vi->bm_vdata, CD_PAINT_MASK);
2074         }
2075
2076         vi->gh = NULL;
2077         if (vi->grids && mode == PBVH_ITER_UNIQUE)
2078                 vi->grid_hidden = bvh->grid_hidden;
2079
2080         vi->mask = NULL;
2081         if (bvh->type == PBVH_FACES)
2082                 vi->vmask = CustomData_get_layer(bvh->vdata, CD_PAINT_MASK);
2083 }
2084
2085 void pbvh_show_diffuse_color_set(PBVH *bvh, bool show_diffuse_color)
2086 {
2087         bool has_mask = false;
2088
2089         switch (bvh->type) {
2090                 case PBVH_GRIDS:
2091                         has_mask = (bvh->gridkey.has_mask != 0);
2092                         break;
2093                 case PBVH_FACES:
2094                         has_mask = (bvh->vdata && CustomData_get_layer(bvh->vdata,
2095                                                         CD_PAINT_MASK));
2096                         break;
2097                 case PBVH_BMESH:
2098                         has_mask = (bvh->bm && (CustomData_get_offset(&bvh->bm->vdata, CD_PAINT_MASK) != -1));
2099                         break;
2100         }
2101
2102         bvh->show_diffuse_color = !has_mask || show_diffuse_color;
2103 }