4 void free_bvh_tree(struct bvhnode *tree)
6 struct bvhnode *node, *tmp;
20 int ray_triangle(cgm_ray *ray, struct triangle *tri, float tmax, struct rayhit *hit)
25 if(fabs(ndotdir = cgm_vdot(&ray->dir, &tri->norm)) <= 1e-6) {
30 cgm_vsub(&vdir, &ray->origin);
32 if((t = cgm_vdot(&ray->dir, &vdir) / ndotdir) <= 1e-6 || t > tmax) {
41 cgm_raypos(&hit->v.pos, ray, t);
42 cgm_bary(&bc, &tri->v[0].pos, &tri->v[1].pos, &tri->v[2].pos, &hit->v.pos);
44 hit->v.norm.x = tri->v[0].norm.x * bc.x + tri->v[1].norm.x * bc.y + tri->v[2].norm.x * bc.z;
45 hit->v.norm.y = tri->v[0].norm.y * bc.x + tri->v[1].norm.y * bc.y + tri->v[2].norm.y * bc.z;
46 hit->v.norm.z = tri->v[0].norm.z * bc.x + tri->v[1].norm.z * bc.y + tri->v[2].norm.z * bc.z;
48 hit->v.tex.x = tri->v[0].tex.x * bc.x + tri->v[1].tex.x * bc.y + tri->v[2].tex.x * bc.z;
49 hit->v.tex.y = tri->v[0].tex.y * bc.x + tri->v[1].tex.y * bc.y + tri->v[2].tex.y * bc.z;
54 #define SLABCHECK(dim) \
56 invdir = 1.0f / ray->dir.dim; \
57 t0 = (box->vmin.dim - ray->origin.dim) * invdir; \
58 t1 = (box->vmax.dim - ray->origin.dim) * invdir; \
64 tmin = t0 > tmin ? t0 : tmin; \
65 tmax = t1 < tmax ? t1 : tmax; \
66 if(tmax <= tmin) return 0; \
69 int ray_aabox_any(cgm_ray *ray, struct aabox *box, float tmax)
71 float invdir, t0, t1, tmp;
81 int ray_bvhnode(cgm_ray *ray, struct bvhnode *bn, float tmax, struct rayhit *hit)
86 if(!ray_aabox_any(ray, &bn->aabb, tmax)) {
91 for(i=0; i<bn->num_faces; i++) {
92 if(ray_triangle(ray, bn->faces + i, tmax, 0)) {
100 for(i=0; i<bn->num_faces; i++) {
101 if(ray_triangle(ray, bn->faces + i, tmax, hit) && hit->t < hit0.t) {