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