diff --git a/shaders/Makefile b/shaders/Makefile index 3f33ddd..9720ca0 100644 --- a/shaders/Makefile +++ b/shaders/Makefile @@ -1,7 +1,7 @@ all: clean voxel.spv compaction.spv gi.spv radix_sort.spv radix_reduce.spv clean: - rm -f *.spv + rm -f out/*.spv %.spv: %.slang - slangc $< -O3 -fvk-use-entrypoint-name -target spirv -o $@ + slangc $< -O3 -g0 -fp-mode fast -fvk-use-scalar-layout -emit-spirv-directly -fvk-use-entrypoint-name -target spirv -o out/$@ diff --git a/shaders/compaction.spv b/shaders/compaction.spv deleted file mode 100644 index b4fd7ee..0000000 Binary files a/shaders/compaction.spv and /dev/null differ diff --git a/shaders/fixed_structure_table.slang b/shaders/fixed_structure_table.slang new file mode 100644 index 0000000..660cdb9 --- /dev/null +++ b/shaders/fixed_structure_table.slang @@ -0,0 +1,129 @@ +module fixed_structure_table; + +import voxel_cache; +import voxel_tracing; + +/// Parameters for the fixed structure table +public struct FixedStructureTable +{ + RWStructuredBuffer structure_table_pointer; + RWStructuredBuffer> structure_table_request_buffer; +} + +public struct FixedStructureTableChunksCursor +{ + int32_t3 current_voxel; + float3 t_off; + float3 t; + + Ray r; +} + +/// Uses a fixed structure table as a dense array of chunks +public struct FixedStructureTableChunks : IStructure +{ + typedef FixedStructureTableChunksCursor Cursor; + + public FixedStructureTable structure_table; + public uint32_t3 extent; + + public FixedStructureTableChunksCursor begin(Ray worldRay, Span s) + { + FixedStructureTableChunksCursor cursor; + + // Intersect with bounds + var inter = box_intersect(worldRay.origin, worldRay.direction, float3(0.), float3(this.extent.x, this.extent.y, this.extent.z)); + + // No hit if out of box + if (inter.y <= inter.x || inter.y <= 0.) + { + // Take position way off so it exits on firt next call + cursor.current_voxel = int32_t3(-1); + cursor.t_off = float3(0.); + return cursor; + } + inter.x = max(0., inter.x); + + // Now march inside chunk bounds + let start_position = inter.x * worldRay.direction + worldRay.origin; + + // FVT clamp to block + cursor.current_voxel = clamp( + int32_t3(floor(start_position)), + int32_t3(0), + int32_t3(this.extent.x - 1, this.extent.y - 1, this.extent.z - 1)); + cursor.t_off = abs(worldRay.invDirection); + + // Take t of next boundary + cursor.t = select( + worldRay.direction > 0., + cursor.current_voxel + int32_t3(1) - start_position, + start_position - cursor.current_voxel) * + cursor.t_off; + + // Add camera offset + cursor.t += inter.x; + cursor.r = worldRay; + return cursor; + } + + public bool next(inout Cursor c, out Cell cell) + { + while (all(c.current_voxel >= 0) && all(c.current_voxel < int32_t3(this.extent.x, this.extent.y, this.extent.z))) + { + // Current hit + let off = c.t - c.t_off; + let t_adv = max(max(off.x, max(off.y, off.z)), 0.); + let chunk_index = c.current_voxel.x + c.current_voxel.z * this.extent.x + c.current_voxel.y * this.extent.x * this.extent.z; + let position = c.r.origin + c.r.direction * t_adv; + + var hit = false; + if (this.structure_table.structure_table_pointer[chunk_index].subdivided_valid()) + { + cell.cache_pointer = this.structure_table.structure_table_pointer[chunk_index].pointer(); + cell.local_ray.origin = position - float3(c.current_voxel); + cell.local_ray.direction = c.r.direction; + cell.local_ray.invDirection = c.r.invDirection; + cell.t = t_adv; + hit = true; + } + else if (this.structure_table.structure_table_pointer[chunk_index].subdivided()) + { + this.structure_table.structure_table_request_buffer[chunk_index].add(1); + hit = false; + } + + // Advance + let min_mask = min_mask(c.t); + c.t += select(min_mask, c.t_off, float3(0.)); + c.current_voxel += select(min_mask, int32_t3(sign(c.r.direction)), int32_t3(0)); + + if (hit) + { + return true; + } + } + + return false; + } +} + +bool3 min_mask(float3 val) +{ + let min_val = min(val.x, min(val.y, val.z)); + return val == min_val; +} + +float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max) +{ + let min_ts = (box_min - origin) / ray_direction; + let max_ts = (box_max - origin) / ray_direction; + + let far_ts = max(min_ts, max_ts); + let near_ts = min(min_ts, max_ts); + + let far_t = min(far_ts.x, min(far_ts.y, far_ts.z)); + let near_t = max(near_ts.x, max(near_ts.y, near_ts.z)); + return float2(near_t, far_t); +} + diff --git a/shaders/gi.slang b/shaders/gi.slang index ac09ee6..efc6493 100644 --- a/shaders/gi.slang +++ b/shaders/gi.slang @@ -1,5 +1,3 @@ -import ray_cast; - struct PushConstants { float4x4 view_proj; @@ -13,103 +11,23 @@ struct PushConstants uint32_t chunk_alt; } -public struct VertexOutput -{ - public float4 position : SV_Position; - - [vk::location(0)] - public float3 world_position; - - [vk::location(1)] - public nointerpolation uint32_t structure_id; - - [vk::location(2)] - public float3 cam_position; - - [vk::location(3)] - public float3 chunk_position; -} - [[vk::push_constant]] uniform PushConstants constants; -struct ByteColor -{ - uint32_t byte_color; - - property uint32_t byte_r - { - get { - return byte_color & 0xFF; - } - } - - property uint32_t byte_g - { - get { - return (byte_color >> 8) & 0xFF; - } - } - - property uint32_t byte_b - { - get { - return (byte_color >> 16) & 0xFF; - } - } - - property uint32_t byte_a - { - get { - return byte_color >> 24; - } - } - - property float4 float_color - { - get { - return float4( - float(byte_r) / 255., - float(byte_g) / 255., - float(byte_b) / 255., - float(byte_a) / 255.); - } - } -} - [[vk::binding(0, 0)]] -RWStructuredBuffer structure_pool; +RWStructuredBuffer structure_pool; [[vk::binding(1, 0)]] RWStructuredBuffer attributes_pool[2]; [[vk::binding(2, 0)]] -RWStructuredBuffer request_buffer; +RWStructuredBuffer request_buffer; [[vk::binding(3, 0)]] RWStructuredBuffer usage_buffer; [[vk::binding(0, 1)]] -RWStructuredBuffer structure_table_pointer; +RWStructuredBuffer structure_table_pointer; [[vk::binding(1, 1)]] RWStructuredBuffer> structure_table_request_buffer; -ByteColor fetch_color(uint32_t index, uint32_t child_index) -{ - return ByteColor(attributes_pool[0][index * 64 + child_index]); -} - -float3 fetch_normal(uint32_t index, uint32_t child_index) -{ - let a = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3]); - let b = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]); - let c = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]); - return float3(a, b, c); -} - -bool3 min_mask(float3 val) -{ - let min_val = min(val.x, min(val.y, val.z)); - return val == min_val; -} - [[vk::binding(0, 2)]] [[format("rgba32f")]] WTexture2D target_texture; @@ -155,110 +73,5 @@ void gi(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_Gr let albedo = gbuffer_albedo.Load(location.xy); target_texture.Store(location.xy, albedo); return; - - let illumination = dot(float3(0., 1., 0.), normal.xyz); - - let view_dir = pos.xyz - constants.cam_pos; - // let ray_dir = normalize(reflect(view_dir, normal.xyz)); - let ray_dir = sampleHemisphere(normal.xyz, constants.frame_timestamp, 6767 + (location.x * 67) + (location.y * 91)); - if (any(isinf(ray_dir)) || any(isnan(ray_dir))) - { - target_texture.Store(location.xy, albedo); - return; - } - - let stack_index = local_location.x + local_location.y * 16; - - var voxel_cache : VoxelCache; - voxel_cache.structure_pool = structure_pool; - voxel_cache.attributes_pool = attributes_pool; - voxel_cache.request_buffer = request_buffer; - voxel_cache.usage_buffer = usage_buffer; - voxel_cache.structure_table_pointer = structure_table_pointer; - voxel_cache.structure_table_request_buffer = structure_table_request_buffer; - - var ray_cast_context : RayCastContext; - ray_cast_context.ray_direction = ray_dir; - ray_cast_context.ray_origin = pos.xyz + normal.xyz * 0.1; - ray_cast_context.bounds = uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_width); - ray_cast_context.frame_timestamp = constants.frame_timestamp; - ray_cast_context.cache_report = true; - - let hit = ray_cast(voxel_cache, ray_cast_context, stack_index); - - if (hit.hit) - { - // Gather - let smpl_albedo = fetch_color(hit.node_index, hit.child_index).float_color; - target_texture.Store(location.xy, albedo * smpl_albedo); - } - else - { - target_texture.Store(location.xy, float4(float3(illumination), 1.)); - } -} - -float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max) -{ - let min_ts = (box_min - origin) / ray_direction; - let max_ts = (box_max - origin) / ray_direction; - - let far_ts = max(min_ts, max_ts); - let near_ts = min(min_ts, max_ts); - - let far_t = min(far_ts.x, min(far_ts.y, far_ts.z)); - let near_t = max(near_ts.x, max(near_ts.y, near_ts.z)); - return float2(near_t, far_t); -} - -// Returns a cosine-weighted random direction in the hemisphere -// oriented around `normal`. -// -// `frame` should change every frame/sample sequence. -// `seed` can be a per-pixel or per-path identifier. -float3 sampleHemisphere(float3 normal, uint frame, uint seed) -{ - // Hash to get two uniform random numbers in [0, 1). - uint state = seed ^ (frame * 0x9E3779B9u); - - state ^= state >> 16; - state *= 0x7FEB352Du; - state ^= state >> 15; - state *= 0x846CA68Bu; - state ^= state >> 16; - - float u1 = float(state) * (1.0 / 4294967296.0); - - state ^= state >> 16; - state *= 0x7FEB352Du; - state ^= state >> 15; - state *= 0x846CA68Bu; - state ^= state >> 16; - - float u2 = float(state) * (1.0 / 4294967296.0); - - // Cosine-weighted hemisphere sampling. - float r = sqrt(u1); - float phi = 2.0 * 3.14159 * u2; - - float x = r * cos(phi); - float y = r * sin(phi); - float z = sqrt(max(0.0, 1.0 - u1)); - - // Build an orthonormal basis around the normal. - float3 tangent; - - if (abs(normal.z) < 0.999) - tangent = normalize(cross(float3(0.0, 0.0, 1.0), normal)); - else - tangent = normalize(cross(float3(0.0, 1.0, 0.0), normal)); - - float3 bitangent = cross(normal, tangent); - - // Transform from local hemisphere space to world space. - return normalize( - tangent * x + - bitangent * y + - normal * z); } diff --git a/shaders/lod_policies.slang b/shaders/lod_policies.slang new file mode 100644 index 0000000..0b17a45 --- /dev/null +++ b/shaders/lod_policies.slang @@ -0,0 +1,45 @@ +module lod_policies; +import voxel_tracing; + +public struct PixelFootprintLod : ILodPolicy +{ + // Angular size of one pixel in radians (small-angle approximation). + // For a pinhole camera: 2 * tan(fovY * 0.5) / imageHeightInPixels. + public float pixelAngle; + + // How many pixels a node may cover before we refuse to stop. + // 1.0 = stop once a node is <= 1 pixel wide. + // < 1.0 = more detail (sharper, slower), > 1.0 = coarser (faster, blurrier). + public float pixelThreshold; + + // Cone radius at t = 0. Zero for a pinhole camera; non-zero for + // secondary rays that inherit a footprint from a previous bounce. + public float coneRadius0; + + // Footprint (world-space width of one pixel) at ray distance t. + public float footprint(float t) + { + return coneRadius0 + t * pixelAngle; + } + + public bool shouldStop(float t, float nodeSize) + { + // Node edge length not larger than the allowed pixel coverage -> stop. + return nodeSize <= footprint(t) * pixelThreshold; + } + + // Convenience constructor from camera parameters. + public static PixelFootprintLod create( + float fovYRadians, + float imageHeightPixels, + float pixelThreshold = 1.0, + float coneRadius0 = 0.0) + { + PixelFootprintLod p; + p.pixelAngle = 2.0 * tan(0.5 * fovYRadians) / imageHeightPixels; + p.pixelThreshold = pixelThreshold; + p.coneRadius0 = coneRadius0; + return p; + } +} + diff --git a/shaders/out/compaction.spv b/shaders/out/compaction.spv new file mode 100644 index 0000000..1e30405 Binary files /dev/null and b/shaders/out/compaction.spv differ diff --git a/shaders/gi.spv b/shaders/out/gi.spv similarity index 73% rename from shaders/gi.spv rename to shaders/out/gi.spv index aa8c41e..c015590 100644 Binary files a/shaders/gi.spv and b/shaders/out/gi.spv differ diff --git a/shaders/radix_reduce.spv b/shaders/out/radix_reduce.spv similarity index 55% rename from shaders/radix_reduce.spv rename to shaders/out/radix_reduce.spv index 85fc112..346f607 100644 Binary files a/shaders/radix_reduce.spv and b/shaders/out/radix_reduce.spv differ diff --git a/shaders/out/radix_sort.spv b/shaders/out/radix_sort.spv new file mode 100644 index 0000000..6f8e7b4 Binary files /dev/null and b/shaders/out/radix_sort.spv differ diff --git a/shaders/out/voxel.spv b/shaders/out/voxel.spv new file mode 100644 index 0000000..a0ee316 Binary files /dev/null and b/shaders/out/voxel.spv differ diff --git a/shaders/radix_sort.spv b/shaders/radix_sort.spv deleted file mode 100644 index 72cf267..0000000 Binary files a/shaders/radix_sort.spv and /dev/null differ diff --git a/shaders/ray_cast.slang b/shaders/ray_cast.slang deleted file mode 100644 index f15268d..0000000 --- a/shaders/ray_cast.slang +++ /dev/null @@ -1,390 +0,0 @@ -module ray_cast; - -struct ByteColor -{ - uint32_t byte_color; - - property uint32_t byte_r - { - get { - return byte_color & 0xFF; - } - } - - property uint32_t byte_g - { - get { - return (byte_color >> 8) & 0xFF; - } - } - - property uint32_t byte_b - { - get { - return (byte_color >> 16) & 0xFF; - } - } - - property uint32_t byte_a - { - get { - return byte_color >> 24; - } - } - - property float4 float_color - { - get { - return float4( - float(byte_r) / 255., - float(byte_g) / 255., - float(byte_b) / 255., - float(byte_a) / 255.); - } - } -} - -public struct StructurePointer -{ - uint32_t value; - - bool subdivided() - { - return (this.value & 0x80000000) != 0; - } - - bool pointer_valid() - { - return (this.value & 0x40000000) != 0; - } - - bool subdivided_valid() - { - return (this.value & 0xC0000000) == 0xC0000000; - } - - uint32_t pointer() - { - return this.value & 0x3FFFFFFF; - } -} - -public struct StructurePoolElement -{ - public uint32_t occupancy_low; - public uint32_t occupancy_high; - public StructurePointer pointers[64]; -} - -public struct RequestBufferElement -{ - public Atomic requests[64]; -} - -public struct VoxelCache -{ - public RWStructuredBuffer structure_pool; - public RWStructuredBuffer attributes_pool[2]; - public RWStructuredBuffer request_buffer; - public RWStructuredBuffer usage_buffer; - - public RWStructuredBuffer structure_table_pointer; - public RWStructuredBuffer> structure_table_request_buffer; -} - -ByteColor fetch_color(VoxelCache cache, uint32_t index, uint32_t child_index) -{ - return ByteColor(cache.attributes_pool[0][index * 64 + child_index]); -} - -uint32_t3 get_children_pos(float3 position, uint32_t scale_exp) -{ - return (asuint(position) >> scale_exp) & 3; -} - -uint32_t get_children_index(float3 position, uint32_t scale_exp) -{ - // Get mantissa bits for this scale exp an retain bits for the specific children - uint32_t3 cell_position = (asuint(position) >> scale_exp) & 3; - return cell_position.x + cell_position.y * 4 + cell_position.z * 4 * 4; -} - -uint64_t get_child_mask(uint32_t low, uint32_t high) -{ - return ((uint64_t)high << 32) | (uint64_t)low; -} - -float3 floor_scale(float3 position, uint32_t scale_exp) -{ - uint32_t mask = ~0u << scale_exp; - return asfloat(asuint(position) & mask); -} - -public struct HitInformation -{ - public bool hit; - public float3 hit_pos; - public uint32_t node_index; - public uint32_t child_index; - public float4 color; -} - -groupshared uint32_t stack[256 * 5]; - -HitInformation chunk_ray_march( - VoxelCache cache, - float3 real_ray_direction, - float3 ray_origin, - uint32_t root_id, - float dist_offset, - uint32_t stack_index, - uint32_t frame_timestamp, - bool report, ) -{ - // Cone tracing info - float fov_deg = 100. / 1920.; - float fov_rad = (float.getPi() * fov_deg) / 180.; - float cone_factor = tan(fov_rad / 2.) * 2; // Horizontal size of pixel - - let st_pointer = cache.structure_table_pointer[root_id]; - - if (!st_pointer.subdivided()) - { - var hit : HitInformation; - hit.hit = false; - return hit; - } - - if (!st_pointer.pointer_valid()) - { - // Record request - if (report) - { - cache.structure_table_request_buffer[root_id].add(1); - } - var hit : HitInformation; - hit.hit = false; - return hit; - } - // _hit.color = float4(0., 1., 0., 1.); - // return _hit; - - // Ray mirroring - ray_origin += float3(1.); - ray_origin = clamp(ray_origin, float(1.), asfloat(0x3fffffff)); - ray_origin = select(real_ray_direction > 0., asfloat(asuint(ray_origin) ^ 0x007fffff), ray_origin); - uint32_t child_mirror = 0; - if (real_ray_direction.x > 0.) - { - child_mirror |= 3; - } - if (real_ray_direction.y > 0.) - { - child_mirror |= 3 << 2; - } - if (real_ray_direction.z > 0.) - { - child_mirror |= 3 << 4; - } - let ray_direction = -abs(real_ray_direction); - - float3 pos = ray_origin; - uint32_t scale_exp = 23 - 2; - uint32_t current_node_index = cache.structure_table_pointer[root_id].pointer(); - if (report) - { - cache.usage_buffer[current_node_index] = frame_timestamp; - } - stack[stack_index * 5 + 10 - scale_exp / 2] = current_node_index; - - [loop] - for (uint32_t iter = 0; iter < 500; iter++) - { - uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror; - StructurePointer current_node = cache.structure_pool[current_node_index].pointers[child_index]; - - // Scale computations - let cone_size = (length(ray_origin - pos) + dist_offset) * cone_factor; - let exponent = - select( - cone_size == 0., - 0, - 23 - (127 - (asuint(cone_size) >> 23))); - - while ( - current_node.subdivided_valid() && - scale_exp - 2 > exponent) - { - scale_exp -= 2; - current_node_index = current_node.pointer(); - stack[stack_index * 5 + 10 - scale_exp / 2] = current_node_index; - child_index = get_children_index(pos, scale_exp) ^ child_mirror; - current_node = cache.structure_pool[current_node_index].pointers[child_index]; - // Write usage - if (report) - { - cache.usage_buffer[current_node_index] = frame_timestamp; - } - } - - // Request subdiv - if (report && current_node.subdivided() && !current_node.pointer_valid()) - { - cache.request_buffer[current_node_index].requests[child_index].add(1); - } - - uint64_t occupancy = get_child_mask(cache.structure_pool[current_node_index].occupancy_low, cache.structure_pool[current_node_index].occupancy_high); - let occupied = ((occupancy >> child_index) & 1) != 0; - if (fetch_color(cache, current_node_index, child_index).byte_a != 0) - { - var hit : HitInformation; - hit.hit = true; - hit.node_index = current_node_index; - hit.child_index = child_index; - hit.hit_pos = - select( - real_ray_direction > 0., - asfloat(asuint(pos) ^ 0x007fffff), - pos) - - float3(1.); - return hit; - } - - uint32_t adv_scale_exp = scale_exp; - if (((occupancy >> (child_index & 0b101010)) & 0x00330033) == 0) - { - adv_scale_exp++; - } - - // Perform dda - // Compute correct exponent, and shift it into the exponent part of floatt - let child_pos : float3 = floor_scale(pos, adv_scale_exp); - // Intersection t - let inter_ts : float3 = (child_pos - ray_origin) / ray_direction; - float inter_t = min(inter_ts.x, min(inter_ts.y, inter_ts.z)); - // return float4(inter_t); - - // Perform dda step - // let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1); - let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1); - pos = min(ray_origin + ray_direction * inter_t, asfloat(neighbor_max)); - - // Find most common ancestor - uint32_t3 diffs = asuint(child_pos) ^ asuint(pos); - uint32_t diff = (diffs.x | diffs.y | diffs.z); - - int32_t common_depth = (1 + (22 - firstbithigh(diff)) / 2) * 2; - if (common_depth <= 0) - { - break; - } - - scale_exp = 23 - common_depth; - current_node_index = stack[stack_index * 5 + 10 - scale_exp / 2]; - } - - var hit : HitInformation; - hit.hit = false; - return hit; -} - -public struct RayCastContext -{ - public float3 ray_direction; - public float3 ray_origin; - public uint32_t3 bounds; - public uint32_t frame_timestamp; - public bool cache_report; -} - -public HitInformation ray_cast( - VoxelCache cache, - RayCastContext context, - uint32_t thread_id) -{ - let stack_index = thread_id; - - // Intersect with bounds - var inter = box_intersect(context.ray_origin, context.ray_direction, float3(0.), float3(context.bounds.x, context.bounds.y, context.bounds.z)); - - // No hit if out of box - if (inter.y <= inter.x || inter.y <= 0.) - { - var hit : HitInformation; - hit.hit = false; - return hit; - } - inter.x = max(0., inter.x); - - // Now march inside chunk bounds - let start_position = inter.x * context.ray_direction + context.ray_origin; - // FVT - int32_t3 current_voxel = clamp( - int32_t3(floor(start_position)), - int32_t3(0), - int32_t3(context.bounds.x - 1, context.bounds.y - 1, context.bounds.z - 1)); - // int32_t3 offset = int32_t3(sign(ray_direction)); - // float3 delta = abs(1. / ray_direction); - float3 t = select( - context.ray_direction > 0., - current_voxel + int32_t3(1) - start_position, - start_position - current_voxel) / - abs(context.ray_direction); - t += inter.x; - - [loop] - while (true) - { - if (any(current_voxel < 0) || any(current_voxel >= int32_t3(context.bounds.x, context.bounds.y, context.bounds.z))) - { - var hit : HitInformation; - hit.hit = false; - return hit; - } - { - let off = t - abs(1. / context.ray_direction); - let t_adv = max(max(off.x, max(off.y, off.z)), 0.); - // let chunk_index = current_voxel.y + current_voxel.z * context.bounds.y + current_voxel.x * context.bounds.y * context.bounds.z; - let chunk_index = current_voxel.x + current_voxel.z * context.bounds.x + current_voxel.y * context.bounds.x * context.bounds.z; - let position = context.ray_origin + context.ray_direction * t_adv; - var hit = chunk_ray_march( - cache, - context.ray_direction, - position - float3(current_voxel), - chunk_index, - max(t_adv, 0.01), - stack_index, - context.frame_timestamp, - context.cache_report); - if (hit.hit) - { - hit.hit_pos += float3(current_voxel); - return hit; - } - } - - let min_mask = min_mask(t); - t += select(min_mask, abs(1. / context.ray_direction), float3(0.)); - current_voxel += select(min_mask, int32_t3(sign(context.ray_direction)), int32_t3(0)); - } -} - -bool3 min_mask(float3 val) -{ - let min_val = min(val.x, min(val.y, val.z)); - return val == min_val; -} - -float2 box_intersect(float3 origin, float3 ray_direction, float3 box_min, float3 box_max) -{ - let min_ts = (box_min - origin) / ray_direction; - let max_ts = (box_max - origin) / ray_direction; - - let far_ts = max(min_ts, max_ts); - let near_ts = min(min_ts, max_ts); - - let far_t = min(far_ts.x, min(far_ts.y, far_ts.z)); - let near_t = max(near_ts.x, max(near_ts.y, near_ts.z)); - return float2(near_t, far_t); -} - diff --git a/shaders/voxel.slang b/shaders/voxel.slang index 6d07188..017a160 100644 --- a/shaders/voxel.slang +++ b/shaders/voxel.slang @@ -1,4 +1,8 @@ -import ray_cast; +// import ray_cast; +import voxel_cache; +import fixed_structure_table; +import voxel_tracing; +import lod_policies; struct PushConstants { @@ -33,74 +37,43 @@ public struct VertexOutput [[vk::push_constant]] uniform PushConstants constants; -struct ByteColor +ParameterBlock> cache_parameters; +ParameterBlock table_parameters; + +public struct ColorHit : IVoxelHit { - uint32_t byte_color; + public __init() {}; - property uint32_t byte_r + public bool shouldHit(VoxelCacheParameters cache, uint32_t node_index, uint32_t child_index) { - get { - return byte_color & 0xFF; - } - } - - property uint32_t byte_g - { - get { - return (byte_color >> 8) & 0xFF; - } - } - - property uint32_t byte_b - { - get { - return (byte_color >> 16) & 0xFF; - } - } - - property uint32_t byte_a - { - get { - return byte_color >> 24; - } - } - - property float4 float_color - { - get { - return float4( - float(byte_r) / 255., - float(byte_g) / 255., - float(byte_b) / 255., - float(byte_a) / 255.); - } + return ByteColor(cache.attributes_pool[0][node_index * 64 + child_index]).byte_a != 0; } } -[[vk::binding(0, 0)]] -RWStructuredBuffer structure_pool; -[[vk::binding(1, 0)]] -RWStructuredBuffer attributes_pool[2]; -[[vk::binding(2, 0)]] -RWStructuredBuffer request_buffer; -[[vk::binding(3, 0)]] -RWStructuredBuffer usage_buffer; - -[[vk::binding(0, 1)]] -RWStructuredBuffer structure_table_pointer; -[[vk::binding(1, 1)]] -RWStructuredBuffer> structure_table_request_buffer; +// [[vk::binding(0, 0)]] +// RWStructuredBuffer structure_pool; +// [[vk::binding(1, 0)]] +// RWStructuredBuffer request_buffer; +// [[vk::binding(2, 0)]] +// RWStructuredBuffer usage_buffer; +// [[vk::binding(3, 0)]] +// RWStructuredBuffer attributes_pool[2]; +// +// [[vk::binding(0, 1)]] +// RWStructuredBuffer structure_table_pointer; +// [[vk::binding(1, 1)]] +// RWStructuredBuffer> structure_table_request_buffer; ByteColor fetch_color(uint32_t index, uint32_t child_index) { - return ByteColor(attributes_pool[0][index * 64 + child_index]); + return ByteColor(cache_parameters.attributes_pool[0][index * 64 + child_index]); } float3 fetch_normal(uint32_t index, uint32_t child_index) { - let a = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3]); - let b = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]); - let c = asfloat(attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]); + let a = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3]); + let b = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]); + let c = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]); return float3(a, b, c); } @@ -141,6 +114,8 @@ void gi_march(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: } } +groupshared VoxelTraceStack stacks[256]; + [shader("compute")] [numthreads(16, 16, 1)] void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID) @@ -152,33 +127,46 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_ let stack_index = local_location.x + local_location.y * 16; - var voxel_cache : VoxelCache; - voxel_cache.structure_pool = structure_pool; - voxel_cache.attributes_pool = attributes_pool; - voxel_cache.request_buffer = request_buffer; - voxel_cache.usage_buffer = usage_buffer; - voxel_cache.structure_table_pointer = structure_table_pointer; - voxel_cache.structure_table_request_buffer = structure_table_request_buffer; + VoxelCacheTracer<2, ColorHit<2>> cache_tracer; + cache_tracer.parameters = cache_parameters; + cache_tracer.report_usage = true; + cache_tracer.report_requests = true; + cache_tracer.frame_timestamp = constants.frame_timestamp; + cache_tracer.voxel_hit = ColorHit<2>(); + + FixedStructureTableChunks table_tracer; + table_tracer.structure_table = table_parameters; + table_tracer.extent = uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_width); let ray_direction = get_ray_direction(location.xy); - var ray_cast_context : RayCastContext; - ray_cast_context.ray_direction = ray_direction; - ray_cast_context.ray_origin = constants.cam_pos; - ray_cast_context.bounds = uint32_t3(constants.chunk_width, constants.chunk_alt, constants.chunk_width); - ray_cast_context.frame_timestamp = constants.frame_timestamp; - ray_cast_context.cache_report = true; + Ray r; + r.origin = constants.cam_pos; + r.direction = ray_direction; + r.invDirection = 1.f / ray_direction; - let hit = ray_cast(voxel_cache, ray_cast_context, stack_index); + PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 200.f); - if (hit.hit) + Tracer>, PixelFootprintLod> tracer; + tracer.structure = table_tracer; + tracer.cache = cache_tracer; + tracer.lod = lod; + + Hit h; + Span s; + bool hit = tracer.trace(stacks[stack_index], h, r, s); + + FixedStructureTableChunks.Cursor cursor = table_tracer.begin(r, s); + Cell cell; + + if (hit) { // Gather - let hit_pos = hit.hit_pos; + let hit_pos = h.hit_location; - let hit_normal = fetch_normal(hit.node_index, hit.child_index); + let hit_normal = fetch_normal(h.node_index, h.child_index); var hit_albedo = float4(0.); - hit_albedo = fetch_color(hit.node_index, hit.child_index).float_color; + hit_albedo = fetch_color(h.node_index, h.child_index).float_color; // let hit_albedo = hit.color; gbuffer_position.Store(location.xy, float4(hit_pos, 1.)); diff --git a/shaders/voxel.spv b/shaders/voxel.spv deleted file mode 100644 index bb83279..0000000 Binary files a/shaders/voxel.spv and /dev/null differ diff --git a/shaders/voxel_cache.slang b/shaders/voxel_cache.slang new file mode 100644 index 0000000..b75562e --- /dev/null +++ b/shaders/voxel_cache.slang @@ -0,0 +1,264 @@ +import voxel_tracing; + +public struct ByteColor +{ + public uint32_t byte_color; + + public property uint32_t byte_r + { + get { + return byte_color & 0xFF; + } + } + + public property uint32_t byte_g + { + get { + return (byte_color >> 8) & 0xFF; + } + } + + public property uint32_t byte_b + { + get { + return (byte_color >> 16) & 0xFF; + } + } + + public property uint32_t byte_a + { + get { + return byte_color >> 24; + } + } + + public property float4 float_color + { + get { + return float4( + float(byte_r) / 255., + float(byte_g) / 255., + float(byte_b) / 255., + float(byte_a) / 255.); + } + } +} + +public struct StructurePointer +{ + uint32_t value; + + public bool subdivided() + { + return (this.value & 0x80000000) != 0; + } + + public bool pointer_valid() + { + return (this.value & 0x40000000) != 0; + } + + public bool subdivided_valid() + { + return (this.value & 0xC0000000) == 0xC0000000; + } + + public uint32_t pointer() + { + return this.value & 0x3FFFFFFF; + } +} + +public struct StructureElement +{ + public uint32_t occupancy_low; + public uint32_t occupancy_high; + public StructurePointer pointers[64]; +} + +public struct RequestBufferElement +{ + public Atomic requests[64]; +} + +/// Everything needed to trace within a voxelCache, to be used with a parameter block +public struct VoxelCacheParameters +{ + public RWStructuredBuffer structure_pool; + public RWStructuredBuffer request_buffer; + public RWStructuredBuffer usage_buffer; + public RWStructuredBuffer attributes_pool[N]; +} + +public struct VoxelTraceStack +{ + public uint32_t stack[5]; +} + +uint32_t3 get_children_pos(float3 position, uint32_t scale_exp) +{ + return (asuint(position) >> scale_exp) & 3; +} + +uint32_t get_children_index(float3 position, uint32_t scale_exp) +{ + // Get mantissa bits for this scale exp an retain bits for the specific children + uint32_t3 cell_position = (asuint(position) >> scale_exp) & 3; + return cell_position.x + cell_position.y * 4 + cell_position.z * 4 * 4; +} + +uint64_t get_child_mask(uint32_t low, uint32_t high) +{ + return ((uint64_t)high << 32) | (uint64_t)low; +} + +float3 floor_scale(float3 position, uint32_t scale_exp) +{ + uint32_t mask = ~0u << scale_exp; + return asfloat(asuint(position) & mask); +} + +float node_size(uint32_t scale_exp) +{ + let mantissa_mask = ~(~0u << 23); + return ((1 << scale_exp) & mantissa_mask | (127 << 23)) - 1.f; +} + +ByteColor fetch_color(VoxelCacheParameters p, uint32_t index, uint32_t child_index) +{ + return ByteColor(p.attributes_pool[0][index * 64 + child_index]); +} + +public interface IVoxelHit +{ + public bool shouldHit(VoxelCacheParameters parameters, uint32_t node_index, uint32_t child_index); +} + +public struct VoxelCacheTracer> : IVoxelCache +{ + typedef VoxelTraceStack GroupSharedData; + + public bool report_usage; + public bool report_requests; + public uint32_t frame_timestamp; + public H voxel_hit; + public VoxelCacheParameters parameters; + + public bool trace(uint32_t root, inout VoxelTraceStack stack, Ray r, L lod, float offset_t, out Hit v) + { + // Ray mirroring + r.origin += float3(1.); + r.origin = clamp(r.origin, float(1.), asfloat(0x3fffffff)); + r.origin = select(r.direction > 0., asfloat(asuint(r.origin) ^ 0x007fffff), r.origin); + uint32_t child_mirror = 0; + if (r.direction.x > 0.) + { + child_mirror |= 3; + } + if (r.direction.y > 0.) + { + child_mirror |= 3 << 2; + } + if (r.direction.z > 0.) + { + child_mirror |= 3 << 4; + } + + let ray_direction = -abs(r.direction); + + float t = 0.; + float3 pos = r.origin; + uint32_t scale_exp = 23 - 2; + uint32_t current_node_index = root; + if (this.report_usage) + { + this.parameters.usage_buffer[current_node_index] = this.frame_timestamp; + } + stack.stack[10 - scale_exp / 2] = current_node_index; + + [loop] + for (uint32_t iter = 0; iter < 500; iter++) + { + uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror; + StructurePointer current_node = this.parameters.structure_pool[current_node_index].pointers[child_index]; + + while (current_node.subdivided_valid() && !lod.shouldStop(offset_t + t, node_size(scale_exp))) + { + scale_exp -= 2; + current_node_index = current_node.pointer(); + stack.stack[10 - scale_exp / 2] = current_node_index; + child_index = get_children_index(pos, scale_exp) ^ child_mirror; + current_node = this.parameters.structure_pool[current_node_index].pointers[child_index]; + // Write usage + if (this.report_usage) + { + this.parameters.usage_buffer[current_node_index] = frame_timestamp; + } + } + + // Request subdiv + if (this.report_requests && !lod.shouldStop(t + offset_t, scale_exp) && current_node.subdivided() && !current_node.pointer_valid()) + { + this.parameters.request_buffer[current_node_index].requests[child_index].add(1); + } + + uint64_t occupancy = get_child_mask( + this.parameters.structure_pool[current_node_index].occupancy_low, + this.parameters.structure_pool[current_node_index].occupancy_high); + + let occupied = ((occupancy >> child_index) & 1) != 0; + // if (fetch_color(this.parameters, current_node_index, child_index).byte_a != 0) + // if (fetch_color(cache, current_node_index, child_index).byte_a != 0) + if (occupied && voxel_hit.shouldHit(this.parameters, current_node_index, child_index)) + { + v.hit = true; + v.node_index = current_node_index; + v.child_index = child_index; + v.hit_location = + select( + r.direction > 0., + asfloat(asuint(pos) ^ 0x007fffff), + pos) - + float3(1.); + return true; + } + + uint32_t adv_scale_exp = scale_exp; + if (((occupancy >> (child_index & 0b101010)) & 0x00330033) == 0) + { + adv_scale_exp++; + } + + // Perform dda + // Compute correct exponent, and shift it into the exponent part of floatt + let child_pos : float3 = floor_scale(pos, adv_scale_exp); + // Intersection t + let inter_ts : float3 = (child_pos - r.origin) / ray_direction; + float inter_t = min(inter_ts.x, min(inter_ts.y, inter_ts.z)); + t = inter_t; + // return float4(inter_t); + + // Perform dda step + // let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1); + let neighbor_max = asint(child_pos) + select(inter_t == inter_ts, -1, (1 << adv_scale_exp) - 1); + pos = min(r.origin + ray_direction * inter_t, asfloat(neighbor_max)); + + // Find most common ancestor + uint32_t3 diffs = asuint(child_pos) ^ asuint(pos); + uint32_t diff = (diffs.x | diffs.y | diffs.z); + + int32_t common_depth = (1 + (22 - firstbithigh(diff)) / 2) * 2; + if (common_depth <= 0) + { + break; + } + + scale_exp = 23 - common_depth; + current_node_index = stack.stack[10 - scale_exp / 2]; + } + + v.hit = false; + return false; + } +} + diff --git a/shaders/voxel_tracing.slang b/shaders/voxel_tracing.slang index 1619385..d65dcbb 100644 --- a/shaders/voxel_tracing.slang +++ b/shaders/voxel_tracing.slang @@ -1,54 +1,93 @@ -struct Ray +module voxel_tracing; + +public struct Ray { - float3 origin; - float3 direction; - float3 invDirection; + public float3 origin; + public float3 direction; + public float3 invDirection; } -struct Span +public struct Span { - float t0; - float t1; + public float t0; + public float t1; } -struct Cell +public struct Cell { /// Entry pointer into the cache - uint32_t cache_pointer; // entry into the cache + public uint32_t cache_pointer; // entry into the cache /// Ray to be traced inside the cache - Ray local_ray; + public Ray local_ray; + + /// How much distance from the camera + public float t; } -interface IStructure +public interface IStructure { /// A cursor structure to keep ray state - associatedtype Cursor; + public associatedtype Cursor; /// Begins tracing a certain ray, with a span - Cursor begin(Ray worldRay, Span s); + public Cursor begin(Ray worldRay, Span s); /// Returns whether it hits, updating the state, and returning a cell structure if hit. - bool next(inout Cursor c, out Cell cell); // next populated cell along the ray + public bool next(inout Cursor c, out Cell cell); // next populated cell along the ray } -interface ILodPolicy +public interface ILodPolicy { /// cone / pixel-footprint termination - bool shouldStop(float t, float nodeSize); + public bool shouldStop(float t, float nodeSize); } -interface IVoxelCache +public struct Hit { - associatedtype Voxel; - bool trace(uint32_t root, Ray r, L lod, out float t, out Voxel v); + public bool hit; + + // Cache location + public uint32_t node_index; + public uint32_t child_index; + public float3 hit_location; } -struct Tracer +public interface IVoxelCache { - S structure; - C cache; + // The voxel cache tracer needs to store a small stack. + // Keeping it in registers is wastefull thus using groupshared memory is the best option + associatedtype GroupSharedData; + public bool trace(uint32_t root, inout GroupSharedData data, Ray r, L lod, float offset_t, out Hit v); +} - Hit trace(Ray r, Span s) { /* loop: next cell -> cache.trace -> early out */ } +public struct Tracer +{ + + public S structure; + public C cache; + public L lod; + + public bool trace(inout C.GroupSharedData gsData, out Hit h, Ray r, Span s) + { + /* loop: next cell -> cache.trace -> early out */ + S.Cursor cursor = this.structure.begin(r, s); + Cell cell; + + h.hit = false; + h.hit_location = float3(0.f); + h.child_index = 0; + h.node_index = 0; + + while (this.structure.next(cursor, cell)) + { + if (cache.trace(cell.cache_pointer, gsData, cell.local_ray, lod, cell.t, h)) + { + return true; + } + } + + return false; + } } diff --git a/src/gpu/buffer_compactor.rs b/src/gpu/buffer_compactor.rs index ff915d3..9f3ac6b 100644 --- a/src/gpu/buffer_compactor.rs +++ b/src/gpu/buffer_compactor.rs @@ -136,7 +136,7 @@ impl NonZeroBufferCompactor wgpu::ShaderModuleDescriptor { label: Some("compaction_shader_layout"), source: wgpu::ShaderSource::SpirV(wgpu::__macro_helpers::Cow::Borrowed( - wgpu::include_spirv_source!("../../shaders/compaction.spv"), + wgpu::include_spirv_source!("../../shaders/out/compaction.spv"), )), }, wgpu::ShaderRuntimeChecks { diff --git a/src/gpu/radix_sort.rs b/src/gpu/radix_sort.rs index a0eee4d..2ea149f 100644 --- a/src/gpu/radix_sort.rs +++ b/src/gpu/radix_sort.rs @@ -225,7 +225,7 @@ impl RadixSorter }); let radix_sort_shader_module = - device.create_shader_module(include_spirv!("../../shaders/radix_sort.spv")); + device.create_shader_module(include_spirv!("../../shaders/out/radix_sort.spv")); let compilation_options = wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, diff --git a/src/main.rs b/src/main.rs index f804d01..fabbf57 100644 --- a/src/main.rs +++ b/src/main.rs @@ -360,7 +360,7 @@ impl State init: voxel_cache::CacheAttributeInit::External, }); - let voxel_cache = VoxelCache::<4>::new(&device, 50_000, &layout); + let voxel_cache = VoxelCache::<4>::new(&device, 150_000, &layout); let request_buffer = CacheRequestBuffer::new(&device, 1024); let insertion_data = CacheInsertionData::new(&device, 1024, &layout); @@ -467,7 +467,7 @@ impl State wgpu::ShaderModuleDescriptorPassthrough { label: wgpu::__macro_helpers::Some("../shaders/voxel.spv"), spirv: Some(std::borrow::Cow::Borrowed(wgpu::include_spirv_source!( - "../shaders/voxel.spv" + "../shaders/out/voxel.spv" ))), entry_points: std::borrow::Cow::Borrowed(&[ wgpu::PassthroughShaderEntryPoint { @@ -490,7 +490,7 @@ impl State wgpu::ShaderModuleDescriptorPassthrough { label: wgpu::__macro_helpers::Some("../shaders/gi.spv"), spirv: Some(std::borrow::Cow::Borrowed(wgpu::include_spirv_source!( - "../shaders/gi.spv" + "../shaders/out/gi.spv" ))), entry_points: std::borrow::Cow::Borrowed(&[ wgpu::PassthroughShaderEntryPoint { diff --git a/src/voxel_cache.rs b/src/voxel_cache.rs index 8589e00..5f2cd46 100644 --- a/src/voxel_cache.rs +++ b/src/voxel_cache.rs @@ -315,23 +315,9 @@ where }, count: None, }, - // Attributes - wgpu::BindGroupLayoutEntry { - binding: 1, - visibility: wgpu::ShaderStages::COMPUTE, - ty: wgpu::BindingType::Buffer { - ty: wgpu::BufferBindingType::Storage { read_only: false }, - has_dynamic_offset: false, - min_binding_size: None, - }, - count: Some( - NonZero::new(attribute_count as u32) - .expect("Null amount of cache attributes."), - ), - }, // Request pages wgpu::BindGroupLayoutEntry { - binding: 2, + binding: 1, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: false }, @@ -342,7 +328,7 @@ where }, // Usage pages wgpu::BindGroupLayoutEntry { - binding: 3, + binding: 2, visibility: wgpu::ShaderStages::COMPUTE, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only: false }, @@ -351,6 +337,20 @@ where }, count: None, }, + // Attributes + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only: false }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: Some( + NonZero::new(attribute_count as u32) + .expect("Null amount of cache attributes."), + ), + }, ], }); @@ -369,16 +369,16 @@ where }, wgpu::BindGroupEntry { binding: 1, - resource: wgpu::BindingResource::BufferArray(&attributes_bindings), - }, - wgpu::BindGroupEntry { - binding: 2, resource: request_handler.request_pages_buffer().as_entire_binding(), }, wgpu::BindGroupEntry { - binding: 3, + binding: 2, resource: evictor.timestamp_pages_buffer().as_entire_binding(), }, + wgpu::BindGroupEntry { + binding: 3, + resource: wgpu::BindingResource::BufferArray(&attributes_bindings), + }, ], });