- /* if il is 0, this is a leaf */
- u32 il, count;
- union{ u32 ir, start; };
-};
-
-static void bvh_update_bounds( scene *s, u32 inode )
-{
- bvh_node *node = &s->bvh.nodes[ inode ];
-
- box_init_inf( node->bbx );
- for( u32 i=0; i<node->count; i++ )
- {
- u32 idx = node->start+i;
- model_vert *pa = &s->verts[ s->indices[idx*3+0] ],
- *pb = &s->verts[ s->indices[idx*3+1] ],
- *pc = &s->verts[ s->indices[idx*3+2] ];
-
- box_addpt( node->bbx, pa->co );
- box_addpt( node->bbx, pb->co );
- box_addpt( node->bbx, pc->co );
- }
-}
-
-static void bvh_subdiv( scene *s, u32 inode )
-{
- bvh_node *node = &s->bvh.nodes[ inode ];
-
- v3f extent;
- v3_sub( node->bbx[1], node->bbx[0], extent );
-
- int axis = 0;
- if( extent[1] > extent[0] ) axis = 1;
- if( extent[2] > extent[axis] ) axis = 2;
-
- float split = node->bbx[0][axis] + extent[axis]*0.5f;
-
- /* To beat: 121,687 / 136,579
- * 136,375
- */
-
- float avg = 0.0;
- for( u32 t=0; t<node->count; t++ )
- {
- u32 *ti = &s->indices[(node->start+t)*3];
- float a = s->verts[ti[0]].co[axis],
- b = s->verts[ti[1]].co[axis],
- c = s->verts[ti[2]].co[axis];
- avg += (a+b+c)/3.0;
- }
- avg /= (float)node->count;
-
- split = avg;
-
- i32 i = node->start,
- j = i + node->count-1;
-
- while( i <= j )
- {
- u32 *ti = &s->indices[i*3];
-
- float a = s->verts[ti[0]].co[axis],
- b = s->verts[ti[1]].co[axis],
- c = s->verts[ti[2]].co[axis];
-
- if( ((a+b+c) / 3.0f) < split )
- i ++;
- else
- {
- /* Swap triangle indices */
- u32 *tj = &s->indices[j*3];
- u32 temp[3];
- temp[0] = ti[0];
- temp[1] = ti[1];
- temp[2] = ti[2];
-
- ti[0] = tj[0];
- ti[1] = tj[1];
- ti[2] = tj[2];
-
- tj[0] = temp[0];
- tj[1] = temp[1];
- tj[2] = temp[2];
-
- j --;
- }
- }
-
- u32 left_count = i - node->start;
- if( left_count == 0 || left_count == node->count ) return;
-
- u32 il = s->bvh.node_count ++,
- ir = s->bvh.node_count ++;
-
- struct bvh_node *lnode = &s->bvh.nodes[il],
- *rnode = &s->bvh.nodes[ir];
-
- lnode->start = node->start;
- lnode->count = left_count;
- rnode->start = i;
- rnode->count = node->count - left_count;
-
- node->il = il;
- node->ir = ir;
- node->count = 0;
-
- bvh_update_bounds( s, il );
- bvh_update_bounds( s, ir );
- bvh_subdiv( s, il );
- bvh_subdiv( s, ir );