WebGPU Demo Ray Tracer var script document createElement script script type text javascript script async false script src https cdnjs cloudflare com ajax libs gl matrix 2 6 0 gl matrix min js document head appendChild script const canvas document createElement canvas document body appendChild canvas canvas width canvas height 512 console log canvas width canvas height const context canvas getContext webgpu const gpu navigator gpu console log gpu gpu const adapter await gpu requestAdapter const device await adapter requestDevice const devicePixelRatio 1 1 const presentationSize canvas clientWidth devicePixelRatio canvas clientHeight devicePixelRatio const presentationFormat navigator gpu getPreferredCanvasFormat context getPreferredFormat adapter no longer supported console log presentationFormat context configure device device format presentationFormat size presentationSize var vertWGSL struct VSOut builtin position Position vec4 f32 location 0 uvs vec2 f32 vertex fn main builtin vertex_index VertexIndex u32 VSOut var s 0 9 var pos array vec2 f32 4 vec2 f32 s s vec2 f32 s s vec2 f32 s s vec2 f32 s s s 1 0 var uvs array vec2 f32 4 vec2 f32 s s vec2 f32 s s vec2 f32 s s vec2 f32 s s var vsOut VSOut vsOut Position vec4 f32 pos VertexIndex 0 0 1 0 vsOut uvs uvs VertexIndex 0 5 0 5 0 1 return vsOut var fragWGSL struct Uniforms mytimer f32 group 0 binding 0 var mySampler sampler group 0 binding 1 var myTexture texture_2d f32 group 0 binding 2 var uniform uniforms Uniforms Helper structures struct Ray origin vec3 f32 direction vec3 f32 struct Material color vec3 f32 diffuse f32 specular f32 struct Light color vec3 f32 direction vec3 f32 struct Intersect valid f32 len f32 normal vec3 f32 material Material struct Sphere radius f32 position vec3 f32 material Material struct Plane normal vec3 f32 point vec3 f32 material Material fn createLight c vec3 f32 d vec3 f32 Light var light Light light color c light direction d return light fn createMaterial c vec3 f32 d f32 s f32 Material var material Material material color c material diffuse d material specular s return material fn createSphere c vec3 f32 r f32 m Material Sphere var sphere Sphere sphere position c sphere radius r sphere material m return sphere fn planeIntersect ray Ray plane Plane Intersect var miss Intersect miss valid 0 0 miss len 0 0 miss normal vec3 f32 0 0 plane equation p p0 n 0 ray equation p l0 l t solve for parameter t t p0 l0 n l n var n plane normal var p0 plane point var l0 ray origin var l ray direction var denom dot n l if abs denom 0 01 return miss var t dot p0 l0 n denom var hitpoint l0 l t if length hitpoint plane point 6 0 return miss if t 0 0 return miss var d 0 0 dot plane normal plane point var len dot ray origin plane normal dot ray direction plane normal d if len 0 0 return miss var hit Intersect hit valid 1 0 hit len t hit normal plane normal hit material plane material return hit fn sphereIntersect ray Ray sphere Sphere Intersect var miss Intersect miss valid 0 0 miss len 0 0 miss normal vec3 f32 0 0 Check for a Negative Square Root var oc sphere position ray origin var l dot ray direction oc var det pow l 2 0 dot oc oc pow sphere radius 2 0 if det 0 0 return miss Find the Closer of Two Solutions var len l sqrt det if len 0 0 len l sqrt det if len 0 0 return miss var hit Intersect hit valid 1 0 hit len len hit normal ray origin len ray direction sphere position sphere radius hit material sphere material return hit Trace a single ray Takes a ray and returns color fn trace ray Ray Intersect var planeo Plane planeo normal vec3 f32 0 0 1 0 0 0 planeo point vec3 f32 0 0 1 0 0 2 planeo material createMaterial vec3 f32 0 0 1 0 1 0 0 4 0 2 var hit2 Intersect hit2 valid 0 0 hit2 len 0 0 hit2 normal vec3 f32 0 0 var plane planeIntersect ray planeo if plane valid 1 0 hit2 plane var sphere0 createSphere vec3 f32 3 0 2 0 10 0 2 0 createMaterial vec3 f32 0 0 1 0 0 0 0 5 0 06 var sphere1 createSphere vec3 f32 0 5 2 0 9 0 1 0 createMaterial vec3 f32 1 0 0 0 1 0 0 6 0 5 var sphere2 createSphere vec3 f32 1 0 1 0 7 0 1 0 createMaterial vec3 f32 0 0 0 0 1 0 0 5 0 95 var spheres array Sphere 3 sphere0 sphere1 sphere2 for var i 0 i 3 i i 1 var sphere sphereIntersect ray spheres i if sphere valid 1 0 hit2 sphere return hit2 fn radiance rayin Ray vec3 f32 var ray rayin var exposure 0 001 var gamma 2 2 var intensity 2 0 var ambient vec3 f32 0 6 0 8 1 0 intensity gamma var epsilon 0 0001 Static Light var light createLight vec3 f32 1 0 1 0 1 0 intensity normalize vec3 f32 0 2 0 75 1 0 var color vec3 f32 0 0 0 0 0 0 var fresnel vec3 f32 0 0 var mask vec3 f32 1 0 1 0 1 0 for var i 0 0 i 16 0 i i 1 0 var hit trace ray var hit Intersect miss len 0 0 miss normal vec3 f32 0 0 0 0 0 0 if hit valid 1 0 var r0 hit material color rgb hit material specular var hv clamp dot hit normal ray direction 0 0 1 0 fresnel r0 1 0 r0 pow 1 0 hv 5 0 mask mask fresnel fresnel fresnel 0 8 var scale 1 0 fresnel 1 0 var br Ray br origin ray origin hit len ray direction epsilon light direction br direction light direction var bounce trace br if bounce valid 0 0 miss color color clamp dot hit normal light direction 0 0 1 0 light color hit material color rgb hit material diffuse scale 1 0 fresnel mask fresnel color color clamp dot hit normal light direction 0 0 1 0 light color hit material color rgb hit material diffuse scale 1 0 fresnel mask fresnel var reflection reflect ray direction hit normal ray origin ray origin hit len ray direction epsilon reflection ray direction reflection else var spotlight vec3 f32 0 001 pow abs dot ray direction light direction 250 0 color color mask ambient spotlight break return vec3 f32 color ref https www shadertoy com view 4ljGRd Entry point for the ray tracer fragment shader Each fragment pixel has its own ray from a desired origin directed at the coordinates of each fragment fragment fn main location 0 uvs vec2 f32 location 0 vec4 f32 let uv 1 0 2 0 uvs xy let vEye vec3 f32 0 0 0 0 2 0 var r Ray r origin vEye r direction normalize vec3 f32 uv 0 0 vEye let c radiance r return vec4 f32 c 1 0 let textureSampler device createSampler minFilter linear magFilter linear const img document createElement img img src https notebook xbdev net var images test512 png await img decode const basicTexture device createTexture size img width img height 1 format presentationFormat bgra8unorm rgba8unorm usage 0x2 0x4 GPUTextureUsage COPY_DST GPUTextureUsage TEXTURE_BINDING const imageCanvas document createElement canvas imageCanvas width img width imageCanvas height img height const imageCanvasContext imageCanvas getContext 2d imageCanvasContext drawImage img 0 0 imageCanvas width imageCanvas height const imageData imageCanvasContext getImageData 0 0 imageCanvas width imageCanvas height let textureData new Uint8Array img width img height 4 for let x 0 x img width img height 4 x textureData x imageData data x device queue writeTexture texture basicTexture textureData offset 0 bytesPerRow img width 4 rowsPerImage img height img width img height 1 const timerUniformBuffer device createBuffer size 4 usage GPUBufferUsage UNIFORM GPUBufferUsage COPY_DST const timestep new Float32Array 3 14 device queue writeBuffer timerUniformBuffer 0 timestep const sceneUniformBindGroupLayout device createBindGroupLayout entries binding 0 visibility GPUShaderStage FRAGMENT sampler type filtering binding 1 visibility GPUShaderStage FRAGMENT texture sampleType float viewDimension 2d binding 2 visibility GPUShaderStage FRAGMENT buffer type uniform const uniformBindGroup device createBindGroup layout sceneUniformBindGroupLayout entries binding 0 resource textureSampler binding 1 resource basicTexture createView binding 2 resource buffer timerUniformBuffer const pipeline device createRenderPipeline layout device createPipelineLayout bindGroupLayouts sceneUniformBindGroupLayout vertex module device createShaderModule code vertWGSL entryPoint main fragment module device createShaderModule code fragWGSL entryPoint main targets format presentationFormat primitive topology triangle strip frontFace ccw cullMode back stripIndexFormat uint32 GPURenderPassDescriptor const renderPassDescriptor colorAttachments view undefined asign later in frame loadOp clear clearValue r 0 0 g 0 5 b 0 5 a 1 0 storeOp store function frame timestep 0 0 01 device queue writeBuffer timerUniformBuffer 0 timestep renderPassDescriptor colorAttachments 0 view context getCurrentTexture createView const commandEncoder device createCommandEncoder const renderPass commandEncoder beginRenderPass renderPassDescriptor renderPass setPipeline pipeline renderPass setBindGroup 0 uniformBindGroup renderPass draw 4 1 0 0 renderPass end device queue submit commandEncoder finish if you want constant updates animated keep refreshing requestAnimationFrame frame frame console log ready
eateLight vec3 f32 1 0 1 0 1 0 intensity normalize vec3 f32 0 2 0 75 1 0 var color vec3 f32 0 0 0 0 0 0 var fresnel vec3 f32 0 0 var mask vec3 f32 1 0 1 0 1 0 for var i 0 0 i 16 0 i i 1 0 var hit trace ray var hit Intersect miss len 0 0 miss normal vec3 f32 0 0 0 0 0 0 if hit valid 1 0 var r0 hit material color rgb hit material specular var hv clamp dot hit normal ray direction 0 0 1 0 fresnel r0 1 0 r0 pow 1 0 hv 5 0 mask mask fresnel fresnel fresnel 0 8 var scale 1 0 fresnel 1 0 var br Ray br origin ray origin hit len ray direction epsilon light direction br direction light direction var bounce trace br if bounce valid 0 0 miss color color clamp dot hit normal light direction 0 0 1 0 light color hit material color rgb hit material diffuse scale 1 0 fresnel mask fresnel color color clamp dot hit normal light direction 0 0 1 0 light color hit material color rgb hit material diffuse scale 1 0 fresnel mask fresnel var reflection reflect ray direction hit normal ray origin ray origin hit len ray direction epsilon reflection ray direction reflection else var spotlight vec3 f32 0 001 pow abs dot ray direction light direction 250 0 color color mask ambient spotlight break return vec3 f32 color ref https www shadertoy com view 4ljGRd Entry point for the ray tracer fragment shader Each fragment pixel has its own ray from a desired origin directed at the coordinates of each fragment fragment fn main location 0 uvs vec2 f32 location 0 vec4 f32 let uv 1 0 2 0 uvs xy let vEye vec3 f32 0 0 0 0 2 0 var r Ray r origin vEye r direction normalize vec3 f32 uv 0 0 vEye let c radiance r return vec4 f32 c 1 0 let textureSampler device createSampler minFilter linear magFilter linear const img document createElement img img src https notebook xbdev net var images test512 png await img decode const basicTexture device createTexture size img width img height 1 format presentationFormat bgra8unorm rgba8unorm usage 0x2 0x4 GPUTextureUsage COPY_DST GPUTextureUsage TEXTURE_BINDING const imageCanvas document createElement canvas imageCanvas width img width imageCanvas height img height const imageCanvasContext imageCanvas getContext 2d imageCanvasContext drawImage img 0 0 imageCanvas width imageCanvas height const imageData imageCanvasContext getImageData 0 0 imageCanvas width imageCanvas height let textureData new Uint8Array img width img height 4 for let x 0 x img width img height 4 x textureData x imageData data x device queue writeTexture texture basicTexture textureData offset 0 bytesPerRow img width 4 rowsPerImage img height img width img height 1 const timerUniformBuffer device createBuffer size 4 usage GPUBufferUsage UNIFORM GPUBufferUsage COPY_DST const timestep new Float32Array 3 14 device queue writeBuffer timerUniformBuffer 0 timestep const sceneUniformBindGroupLayout device createBindGroupLayout entries binding 0 visibility GPUShaderStage FRAGMENT sampler type filtering binding 1 visibility GPUShaderStage FRAGMENT texture sampleType float viewDimension 2d binding 2 visibility GPUShaderStage FRAGMENT buffer type uniform const uniformBindGroup device createBindGroup layout sceneUniformBindGroupLayout entries binding 0 resource textureSampler binding 1 resource basicTexture createView binding 2 resource buffer timerUniformBuffer const pipeline device createRenderPipeline layout device createPipelineLayout bindGroupLayouts sceneUniformBindGroupLayout vertex module device createShaderModule code vertWGSL entryPoint main fragment module device createShaderModule code fragWGSL entryPoint main targets format presentationFormat primitive topology triangle strip frontFace ccw cullMode back stripIndexFormat uint32 GPURenderPassDescriptor const renderPassDescriptor colorAttachments view undefined asign later in frame loadOp clear clearValue r 0 0 g 0 5 b 0 5 a 1 0 storeOp store function frame timestep 0 0 01 device queue writeBuffer timerUniformBuffer 0 timestep renderPassDescriptor colorAttachments 0 view context getCurrentTexture createView const commandEncoder device createCommandEncoder const renderPass commandEncoder beginRenderPass renderPassDescriptor renderPass setPipeline pipeline renderPass setBindGroup 0 uniformBindGroup renderPass draw 4 1 0 0 renderPass end device queue submit commandEncoder finish if you want constant updates animated keep refreshing requestAnimationFrame frame frame console log ready