diff --git a/404.html b/404.html index d4f1447f..f5863d34 100644 --- a/404.html +++ b/404.html @@ -1,4 +1,4 @@ -404: This page could not be found

404

This page could not be found.

\ No newline at end of file + }

404

This page could not be found.

\ No newline at end of file diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/A-buffer.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/A-buffer.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/A-buffer.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/A-buffer.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/animometer.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/animometer.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/animometer.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/animometer.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/bitonicSort.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/bitonicSort.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/bitonicSort.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/bitonicSort.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/cameras.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/cameras.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/cameras.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/cameras.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/computeBoids.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/computeBoids.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/computeBoids.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/computeBoids.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/cornell.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/cornell.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/cornell.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/cornell.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/cubemap.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/cubemap.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/cubemap.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/cubemap.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/deferredRendering.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/deferredRendering.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/deferredRendering.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/deferredRendering.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/fractalCube.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/fractalCube.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/fractalCube.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/fractalCube.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/gameOfLife.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/gameOfLife.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/gameOfLife.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/gameOfLife.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/helloTriangle.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/helloTriangle.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/helloTriangle.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/helloTriangle.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/helloTriangleMSAA.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/helloTriangleMSAA.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/helloTriangleMSAA.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/helloTriangleMSAA.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/imageBlur.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/imageBlur.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/imageBlur.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/imageBlur.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/instancedCube.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/instancedCube.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/instancedCube.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/instancedCube.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/normalMap.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/normalMap.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/normalMap.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/normalMap.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/particles.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/particles.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/particles.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/particles.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/renderBundles.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/renderBundles.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/renderBundles.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/renderBundles.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/resizeCanvas.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/resizeCanvas.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/resizeCanvas.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/resizeCanvas.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/reversedZ.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/reversedZ.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/reversedZ.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/reversedZ.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/rotatingCube.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/rotatingCube.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/rotatingCube.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/rotatingCube.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/samplerParameters.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/samplerParameters.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/samplerParameters.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/samplerParameters.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/shadowMapping.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/shadowMapping.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/shadowMapping.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/shadowMapping.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/texturedCube.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/texturedCube.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/texturedCube.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/texturedCube.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/twoCubes.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/twoCubes.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/twoCubes.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/twoCubes.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/videoUploading.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/videoUploading.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/videoUploading.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/videoUploading.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/videoUploadingWebCodecs.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/videoUploadingWebCodecs.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/videoUploadingWebCodecs.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/videoUploadingWebCodecs.json diff --git a/_next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/worker.json b/_next/data/em7S8GbBqqJHvN6FB6pa3/samples/worker.json similarity index 100% rename from _next/data/7tQ8oBVY1ynV2T9P3Rkzz/samples/worker.json rename to _next/data/em7S8GbBqqJHvN6FB6pa3/samples/worker.json diff --git a/_next/static/chunks/880.1f119f655da3bf3a.js b/_next/static/chunks/880.1f119f655da3bf3a.js deleted file mode 100644 index 3f416972..00000000 --- a/_next/static/chunks/880.1f119f655da3bf3a.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[880],{5671:function(e,n,t){"use strict";t.d(n,{Tl:function(){return d},hu:function(){return p}});var o=t(5893),r=t(9008),i=t.n(r),a=t(1163),s=t(7294),l=t(9147),u=t.n(l);t(7319);let c=e=>{let n=(0,s.useRef)(null),r=(0,s.useRef)(null),l=(0,s.useMemo)(()=>e.sources.map(e=>{let{name:n,contents:r}=e;return{name:n,...function(e){let n;let r=null;{r=document.createElement("div");let i=t(4631);n=i(r,{lineNumbers:!0,lineWrapping:!0,theme:"monokai",readOnly:!0})}return{Container:function(t){return(0,o.jsx)("div",{...t,children:(0,o.jsx)("div",{ref(t){r&&t&&(t.appendChild(r),n.setOption("value",e))}})})}}}(r)}}),e.sources),c=(0,s.useRef)(null),d=(0,s.useMemo)(()=>{if(e.gui){let n=t(4376),o=new n.GUI({autoPlace:!1});return o.domElement.style.position="relative",o.domElement.style.zIndex="1000",o}},[]),p=(0,s.useRef)(null),m=(0,s.useMemo)(()=>{if(e.stats){let n=t(2792);return new n}},[]),f=(0,a.useRouter)(),g=f.asPath.match(/#([a-zA-Z0-9\.\/]+)/),[h,S]=(0,s.useState)(null),[_,E]=(0,s.useState)(null);return(0,s.useEffect)(()=>{if(g?E(g[1]):E(l[0].name),d&&c.current)for(c.current.appendChild(d.domElement);d.__controllers.length>0;)d.__controllers[0].remove();m&&p.current&&(m.dom.style.position="absolute",m.showPanel(1),p.current.appendChild(m.dom));let t={active:!0},o=()=>{t.active=!1};try{let r=n.current;if(!r)throw Error("The canvas is not available");let i=e.init({canvas:r,pageState:t,gui:d,stats:m});i instanceof Promise&&i.catch(e=>{console.error(e),S(e)})}catch(a){console.error(a),S(a)}return o},[]),(0,o.jsxs)("main",{children:[(0,o.jsxs)(i(),{children:[(0,o.jsx)("style",{dangerouslySetInnerHTML:{__html:"\n .CodeMirror {\n height: auto !important;\n margin: 1em 0;\n }\n\n .CodeMirror-scroll {\n height: auto !important;\n overflow: visible !important;\n }\n "}}),(0,o.jsx)("title",{children:"".concat(e.name," - WebGPU Samples")}),(0,o.jsx)("meta",{name:"description",content:e.description}),(0,o.jsx)("meta",{httpEquiv:"origin-trial",content:e.originTrial})]}),(0,o.jsxs)("div",{children:[(0,o.jsx)("h1",{children:e.name}),(0,o.jsx)("a",{target:"_blank",rel:"noreferrer",href:"https://github.com/".concat("webgpu/webgpu-samples","/tree/main/").concat(e.filename),children:"See it on Github!"}),(0,o.jsx)("p",{children:e.description}),h?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("p",{children:"Something went wrong. Do your browser and device support WebGPU?"}),(0,o.jsx)("p",{children:"".concat(h)})]}):null]}),(0,o.jsxs)("div",{className:u().canvasContainer,children:[(0,o.jsx)("div",{style:{position:"absolute",left:10},ref:p}),(0,o.jsx)("div",{style:{position:"absolute",right:10},ref:c}),(0,o.jsx)("canvas",{ref:n})]}),(0,o.jsxs)("div",{children:[(0,o.jsx)("nav",{className:u().sourceFileNav,ref:r,children:(0,o.jsx)("div",{className:u().sourceFileScrollContainer,onScroll(e){let n=e.currentTarget,t=n.scrollWidth-n.clientWidth-n.scrollLeft;n.scrollLeft>25?r.current.setAttribute("data-left","true"):r.current.setAttribute("data-left","false"),t>25?r.current.setAttribute("data-right","true"):r.current.setAttribute("data-right","false")},children:(0,o.jsx)("ul",{children:l.map((e,n)=>(0,o.jsx)("li",{children:(0,o.jsx)("a",{href:"#".concat(e.name),"data-active":_==e.name,onClick(){E(e.name)},children:e.name})},n))})})}),l.map((e,n)=>(0,o.jsx)(e.Container,{className:u().sourceFileContainer,"data-active":_==e.name},n))]})]})},d=e=>(0,o.jsx)(c,{...e});function p(e,n){if(!e)throw Error(n)}},9880:function(e,n,t){"use strict";let o;t.r(n),t.d(n,{default:function(){return _}});var r,i,a=t(5671),s=t(134);let l=(e,n,t,o,r,i,a)=>{let s=[];for(let l=0;l{let n=async n=>{let{canvas:t,pageState:o,gui:r,stats:i}=n,a=await navigator.gpu.requestAdapter(),s=await a.requestDevice();if(!o.active)return;let l=t.getContext("webgpu"),u=window.devicePixelRatio;t.width=t.clientWidth*u,t.height=t.clientHeight*u;let c=navigator.gpu.getPreferredCanvasFormat();l.configure({device:s,format:c,alphaMode:"premultiplied"}),e({canvas:t,pageState:o,gui:r,device:s,context:l,presentationFormat:c,stats:i})};return n};class c{executeRun(e,n,t,o){let r=e.beginRenderPass(n);r.setPipeline(t);for(let i=0;i{e.queue.writeBuffer(i,0,new Uint32Array([n.highlight]))}}}p.sourceInfo={name:"src/sample/bitonicSort/bitonicDisplay.ts".substring(23),contents:"import {\n BindGroupCluster,\n Base2DRendererClass,\n createBindGroupCluster,\n} from './utils';\n\nimport bitonicDisplay from './bitonicDisplay.frag.wgsl';\n\ninterface BitonicDisplayRenderArgs {\n highlight: number;\n}\n\nexport default class BitonicDisplayRenderer extends Base2DRendererClass {\n static sourceInfo = {\n name: __filename.substring(__dirname.length + 1),\n contents: __SOURCE__,\n };\n\n switchBindGroup: (name: string) => void;\n setArguments: (args: BitonicDisplayRenderArgs) => void;\n computeBGDescript: BindGroupCluster;\n\n constructor(\n device: GPUDevice,\n presentationFormat: GPUTextureFormat,\n renderPassDescriptor: GPURenderPassDescriptor,\n computeBGDescript: BindGroupCluster,\n label: string\n ) {\n super();\n this.renderPassDescriptor = renderPassDescriptor;\n this.computeBGDescript = computeBGDescript;\n\n const uniformBuffer = device.createBuffer({\n size: Uint32Array.BYTES_PER_ELEMENT,\n usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,\n });\n\n const bgCluster = createBindGroupCluster(\n [0],\n [GPUShaderStage.FRAGMENT],\n ['buffer'],\n [{ type: 'uniform' }],\n [[{ buffer: uniformBuffer }]],\n label,\n device\n );\n\n this.currentBindGroup = bgCluster.bindGroups[0];\n\n this.pipeline = super.create2DRenderPipeline(\n device,\n label,\n [this.computeBGDescript.bindGroupLayout, bgCluster.bindGroupLayout],\n bitonicDisplay,\n presentationFormat\n );\n\n this.setArguments = (args: BitonicDisplayRenderArgs) => {\n device.queue.writeBuffer(\n uniformBuffer,\n 0,\n new Uint32Array([args.highlight])\n );\n };\n }\n\n startRun(commandEncoder: GPUCommandEncoder, args: BitonicDisplayRenderArgs) {\n this.setArguments(args);\n super.executeRun(commandEncoder, this.renderPassDescriptor, this.pipeline, [\n this.computeBGDescript.bindGroups[0],\n this.currentBindGroup,\n ]);\n }\n}\n"};let m=e=>((e%2!=0||e>256)&&(e=256),"\n\nstruct Uniforms {\n width: f32,\n height: f32,\n algo: u32,\n blockHeight: u32,\n}\n\n// Create local workgroup data that can contain all elements\nvar local_data: array;\n\n// Define groups (functions refer to this data)\n@group(0) @binding(0) var input_data: array;\n@group(0) @binding(1) var output_data: array;\n@group(0) @binding(2) var uniforms: Uniforms;\n@group(0) @binding(3) var counter: atomic;\n\n// Compare and swap values in local_data\nfn local_compare_and_swap(idx_before: u32, idx_after: u32) {\n //idx_before should always be < idx_after\n if (local_data[idx_after] < local_data[idx_before]) {\n atomicAdd(&counter, 1);\n var temp: u32 = local_data[idx_before];\n local_data[idx_before] = local_data[idx_after];\n local_data[idx_after] = temp;\n }\n return;\n}\n\n// invoke_id goes from 0 to workgroupSize\nfn get_flip_indices(invoke_id: u32, block_height: u32) -> vec2 {\n // Caculate index offset (i.e move indices into correct block)\n let block_offset: u32 = ((2 * invoke_id) / block_height) * block_height;\n let half_height = block_height / 2;\n // Calculate index spacing\n var idx: vec2 = vec2(\n invoke_id % half_height, block_height - (invoke_id % half_height) - 1,\n );\n idx.x += block_offset;\n idx.y += block_offset;\n return idx;\n}\n\nfn get_disperse_indices(invoke_id: u32, block_height: u32) -> vec2 {\n var block_offset: u32 = ((2 * invoke_id) / block_height) * block_height;\n let half_height = block_height / 2;\n var idx: vec2 = vec2(\n invoke_id % half_height, (invoke_id % half_height) + half_height\n );\n idx.x += block_offset;\n idx.y += block_offset;\n return idx;\n}\n\nfn global_compare_and_swap(idx_before: u32, idx_after: u32) {\n if (input_data[idx_after] < input_data[idx_before]) {\n output_data[idx_before] = input_data[idx_after];\n output_data[idx_after] = input_data[idx_before];\n } \n}\n\n// Constants/enum\nconst ALGO_NONE = 0;\nconst ALGO_LOCAL_FLIP = 1;\nconst ALGO_LOCAL_DISPERSE = 2;\nconst ALGO_GLOBAL_FLIP = 3;\n\n// Our compute shader will execute specified # of invocations or elements / 2 invocations\n@compute @workgroup_size(").concat(e,", 1, 1)\nfn computeMain(\n @builtin(global_invocation_id) global_id: vec3,\n @builtin(local_invocation_id) local_id: vec3,\n @builtin(workgroup_id) workgroup_id: vec3,\n) {\n\n let offset = ").concat(e," * 2 * workgroup_id.x;\n // If we will perform a local swap, then populate the local data\n if (uniforms.algo <= 2) {\n // Assign range of input_data to local_data.\n // Range cannot exceed maxWorkgroupsX * 2\n // Each invocation will populate the workgroup data... (1 invocation for every 2 elements)\n local_data[local_id.x * 2] = input_data[offset + local_id.x * 2];\n local_data[local_id.x * 2 + 1] = input_data[offset + local_id.x * 2 + 1];\n }\n\n //...and wait for each other to finish their own bit of data population.\n workgroupBarrier();\n\n switch uniforms.algo {\n case 1: { // Local Flip\n let idx = get_flip_indices(local_id.x, uniforms.blockHeight);\n local_compare_and_swap(idx.x, idx.y);\n } \n case 2: { // Local Disperse\n let idx = get_disperse_indices(local_id.x, uniforms.blockHeight);\n local_compare_and_swap(idx.x, idx.y);\n } \n case 3: { // Global Flip\n let idx = get_flip_indices(global_id.x, uniforms.blockHeight);\n global_compare_and_swap(idx.x, idx.y);\n }\n case 4: { \n let idx = get_disperse_indices(global_id.x, uniforms.blockHeight);\n global_compare_and_swap(idx.x, idx.y);\n }\n default: { \n \n }\n }\n\n // Ensure that all invocations have swapped their own regions of data\n workgroupBarrier();\n\n if (uniforms.algo <= ALGO_LOCAL_DISPERSE) {\n //Repopulate global data with local data\n output_data[offset + local_id.x * 2] = local_data[local_id.x * 2];\n output_data[offset + local_id.x * 2 + 1] = local_data[local_id.x * 2 + 1];\n }\n\n}"));var f="@group(0) @binding(3) var counter: atomic;\n\n@compute @workgroup_size(1, 1, 1)\nfn atomicToZero() {\n let counterValue = atomicLoad(&counter);\n atomicSub(&counter, counterValue);\n}",g="src/sample/bitonicSort/main.ts";(r=i||(i={}))[r.NONE=0]="NONE",r[r.FLIP_LOCAL=1]="FLIP_LOCAL",r[r.DISPERSE_LOCAL=2]="DISPERSE_LOCAL",r[r.FLIP_GLOBAL=3]="FLIP_GLOBAL",r[r.DISPERSE_GLOBAL=4]="DISPERSE_GLOBAL";let h=e=>{let n=Math.log2(e);return n*(n+1)/2};u(async e=>{let{pageState:n,device:t,gui:o,presentationFormat:r,context:a,canvas:s}=e,u=t.limits.maxComputeWorkgroupSizeX,c=[],d=32*u;for(let g=d;g>=4;g/=2)c.push(g);let S=[];for(let _=u;_>=2;_/=2)S.push(_);let E=Math.sqrt(d)%2==0?Math.floor(Math.sqrt(d)):Math.floor(Math.sqrt(d/2)),v=d/E,x={"Total Elements":d,"Grid Width":E,"Grid Height":v,"Grid Dimensions":"".concat(E,"x").concat(v),"Workgroup Size":u,"Size Limit":u,"Workgroups Per Step":d/(2*u),"Hovered Cell":0,"Swapped Cell":1,"Step Index":0,"Total Steps":h(d),"Current Step":"0 of 91","Prev Step":"NONE","Next Step":"FLIP_LOCAL","Prev Swap Span":0,"Next Swap Span":2,executeStep:!1,"Randomize Values"(){},"Execute Sort Step"(){},"Log Elements"(){},"Complete Sort"(){},"Sort Speed":50,"Display Mode":"Elements","Total Swaps":0},b=new Uint32Array(Array.from({length:x["Total Elements"]},(e,n)=>n)),w=Float32Array.BYTES_PER_ELEMENT*c[0],y=t.createBuffer({size:w,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),C=t.createBuffer({size:w,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),P=t.createBuffer({size:w,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),L=t.createBuffer({size:Uint32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),G=t.createBuffer({size:Uint32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),B=t.createBuffer({size:4*Float32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),T=l([0,1,2,3],[GPUShaderStage.COMPUTE|GPUShaderStage.FRAGMENT,GPUShaderStage.COMPUTE,GPUShaderStage.COMPUTE|GPUShaderStage.FRAGMENT,GPUShaderStage.COMPUTE],["buffer","buffer","buffer","buffer"],[{type:"read-only-storage"},{type:"storage"},{type:"uniform"},{type:"storage"}],[[{buffer:y},{buffer:C},{buffer:B},{buffer:L}]],"BitonicSort",t),I=t.createComputePipeline({layout:t.createPipelineLayout({bindGroupLayouts:[T.bindGroupLayout]}),compute:{module:t.createShaderModule({code:m(x["Workgroup Size"])}),entryPoint:"computeMain"}}),k=t.createComputePipeline({layout:t.createPipelineLayout({bindGroupLayouts:[T.bindGroupLayout]}),compute:{module:t.createShaderModule({code:f}),entryPoint:"atomicToZero"}}),A={colorAttachments:[{view:void 0,clearValue:{r:.1,g:.4,b:.5,a:1},loadOp:"clear",storeOp:"store"}]},U=new p(t,r,A,T,"BitonicDisplay"),O=()=>{W.setValue(Math.min(x["Total Elements"]/2,x["Size Limit"]));let e=(x["Total Elements"]-1)/(2*x["Size Limit"]);q.setValue(Math.ceil(e)),x["Step Index"]=0,x["Total Steps"]=h(x["Total Elements"]),K.setValue("".concat(x["Step Index"]," of ").concat(x["Total Steps"]));let n=Math.sqrt(x["Total Elements"])%2==0?Math.floor(Math.sqrt(x["Total Elements"])):Math.floor(Math.sqrt(x["Total Elements"]/2)),o=x["Total Elements"]/n;x["Grid Width"]=n,x["Grid Height"]=o,Z.setValue("".concat(n,"x").concat(o)),J.setValue("NONE"),ee.setValue("FLIP_LOCAL"),et.setValue(0),eo.setValue(2);let r=t.createCommandEncoder(),i=r.beginComputePass();i.setPipeline(k),i.setBindGroup(0,T.bindGroups[0]),i.dispatchWorkgroups(1),i.end(),t.queue.submit([r.finish()]),en.setValue(0),ea=2},N=()=>{let e=b.length;for(;0!==e;){let n=Math.floor(Math.random()*e);e-=1,[b[e],b[n]]=[b[n],b[e]]}},R=()=>{b=new Uint32Array(Array.from({length:x["Total Elements"]},(e,n)=>n)),O(),I=t.createComputePipeline({layout:t.createPipelineLayout({bindGroupLayouts:[T.bindGroupLayout]}),compute:{module:t.createShaderModule({code:m(Math.min(x["Total Elements"]/2,x["Size Limit"]))}),entryPoint:"computeMain"}}),N(),ea=2};N();let M=()=>{let e;switch(x["Next Step"]){case"FLIP_LOCAL":case"FLIP_GLOBAL":{let n=x["Next Swap Span"],t=Math.floor(x["Hovered Cell"]/n)+1,o=x["Hovered Cell"]%n;e=n*t-o-1,$.setValue(e)}break;case"DISPERSE_LOCAL":{let r=x["Next Swap Span"],i=r/2;e=x["Hovered Cell"]%r{null!==D&&(clearInterval(D),D=null)},F=()=>{let e=x["Sort Speed"];D=setInterval(()=>{"NONE"===x["Next Step"]&&(clearInterval(D),D=null,V.domElement.style.pointerEvents="auto"),x["Sort Speed"]!==e&&(clearInterval(D),D=null,F()),x.executeStep=!0,M()},x["Sort Speed"])},H=o.addFolder("Compute Resources");H.add(x,"Total Elements",c).onChange(()=>{z(),R(),V.domElement.style.pointerEvents="auto"});let V=H.add(x,"Size Limit",S).onChange(()=>{let e=Math.min(x["Total Elements"]/2,x["Size Limit"]),n=(x["Total Elements"]-1)/(2*x["Size Limit"]);W.setValue(e),q.setValue(Math.ceil(n)),I=I=t.createComputePipeline({layout:t.createPipelineLayout({bindGroupLayouts:[T.bindGroupLayout]}),compute:{module:t.createShaderModule({code:m(Math.min(x["Total Elements"]/2,x["Size Limit"]))}),entryPoint:"computeMain"}})}),W=H.add(x,"Workgroup Size"),q=H.add(x,"Workgroups Per Step");H.open();let Y=o.addFolder("Sort Controls");Y.add(x,"Sort Speed",50,1e3).step(50),Y.add(x,"Execute Sort Step").onChange(()=>{V.domElement.style.pointerEvents="none",z(),x.executeStep=!0}),Y.add(x,"Randomize Values").onChange(()=>{z(),N(),O(),V.domElement.style.pointerEvents="auto"}),Y.add(x,"Log Elements").onChange(()=>console.log(b)),Y.add(x,"Complete Sort").onChange(()=>{V.domElement.style.pointerEvents="none",F()}),Y.open();let j=o.addFolder("Grid Information");j.add(x,"Display Mode",["Elements","Swap Highlight"]);let Z=j.add(x,"Grid Dimensions"),X=j.add(x,"Hovered Cell").onChange(M),$=j.add(x,"Swapped Cell"),Q=o.addFolder("Execution Information"),K=Q.add(x,"Current Step"),J=Q.add(x,"Prev Step"),ee=Q.add(x,"Next Step"),en=Q.add(x,"Total Swaps"),et=Q.add(x,"Prev Swap Span"),eo=Q.add(x,"Next Swap Span"),er=document.getElementsByClassName("cr function");for(let ei=0;ei{let n=s.getBoundingClientRect().width,t=s.getBoundingClientRect().height,o=[n/x["Grid Width"],t/x["Grid Height"]],r=Math.floor(e.offsetX/o[0]),i=x["Grid Height"]-1-Math.floor(e.offsetY/o[1]);X.setValue(i*x["Grid Width"]+r),x["Hovered Cell"]=i*x["Grid Width"]+r}),V.domElement.style.pointerEvents="none",q.domElement.style.pointerEvents="none",X.domElement.style.pointerEvents="none",$.domElement.style.pointerEvents="none",K.domElement.style.pointerEvents="none",J.domElement.style.pointerEvents="none",et.domElement.style.pointerEvents="none",ee.domElement.style.pointerEvents="none",eo.domElement.style.pointerEvents="none",W.domElement.style.pointerEvents="none",Z.domElement.style.pointerEvents="none",en.domElement.style.pointerEvents="none",o.width=325;let ea=2;async function es(){if(!n.active)return;t.queue.writeBuffer(y,0,b.buffer,b.byteOffset,b.byteLength);let e=new Float32Array([x["Grid Width"],x["Grid Height"]]),o=new Uint32Array([i[x["Next Step"]],x["Next Swap Span"]]);t.queue.writeBuffer(B,0,e.buffer,e.byteOffset,e.byteLength),t.queue.writeBuffer(B,8,o),A.colorAttachments[0].view=a.getCurrentTexture().createView();let r=t.createCommandEncoder();if(U.startRun(r,{highlight:"Elements"===x["Display Mode"]?0:1}),x.executeStep&&ea!==2*x["Total Elements"]){let s=r.beginComputePass();s.setPipeline(I),s.setBindGroup(0,T.bindGroups[0]),s.dispatchWorkgroups(x["Workgroups Per Step"]),s.end(),x["Step Index"]=x["Step Index"]+1,K.setValue("".concat(x["Step Index"]," of ").concat(x["Total Steps"])),J.setValue(x["Next Step"]),et.setValue(x["Next Swap Span"]),eo.setValue(x["Next Swap Span"]/2),1===x["Next Swap Span"]?(ea*=2)==2*x["Total Elements"]?(ee.setValue("NONE"),eo.setValue(0)):ea>2*x["Workgroup Size"]?(ee.setValue("FLIP_GLOBAL"),eo.setValue(ea)):(ee.setValue("FLIP_LOCAL"),eo.setValue(ea)):x["Next Swap Span"]>2*x["Workgroup Size"]?ee.setValue("DISPERSE_GLOBAL"):ee.setValue("DISPERSE_LOCAL"),r.copyBufferToBuffer(C,0,P,0,w),r.copyBufferToBuffer(L,0,G,0,Uint32Array.BYTES_PER_ELEMENT)}if(t.queue.submit([r.finish()]),x.executeStep){await P.mapAsync(GPUMapMode.READ,0,w);let l=P.getMappedRange(0,w);await G.mapAsync(GPUMapMode.READ,0,Uint32Array.BYTES_PER_ELEMENT);let u=G.getMappedRange(0,Uint32Array.BYTES_PER_ELEMENT),c=l.slice(0,Uint32Array.BYTES_PER_ELEMENT*x["Total Elements"]),d=u.slice(0,Uint32Array.BYTES_PER_ELEMENT),p=new Uint32Array(c);en.setValue(new Uint32Array(d)[0]),P.unmap(),G.unmap(),b=p,M()}x.executeStep=!1,requestAnimationFrame(es)}F(),requestAnimationFrame(es)}).then(e=>o=e);let S=()=>(0,a.Tl)({name:"Bitonic Sort",description:"A naive bitonic sort algorithm executed on the GPU, based on tgfrerer's implementation at poniesandlight.co.uk/reflect/bitonic_merge_sort/. Each dispatch of the bitonic sort shader dispatches a workgroup containing elements/2 invocations. The GUI's Execution Information folder contains information about the sort's current state. The visualizer displays the sort's results as colored cells sorted from brightest to darkest.",init:o,gui:!0,sources:[{name:g.substring(23),contents:"import { makeSample, SampleInit } from '../../components/SampleLayout';\nimport { createBindGroupCluster, SampleInitFactoryWebGPU } from './utils';\nimport BitonicDisplayRenderer from './bitonicDisplay';\nimport bitonicDisplay from './bitonicDisplay.frag.wgsl';\nimport { NaiveBitonicCompute } from './bitonicCompute';\nimport fullscreenTexturedQuad from '../../shaders/fullscreenTexturedQuad.wgsl';\nimport atomicToZero from './atomicToZero.wgsl';\n\n// Type of step that will be executed in our shader\nenum StepEnum {\n NONE,\n FLIP_LOCAL,\n DISPERSE_LOCAL,\n FLIP_GLOBAL,\n DISPERSE_GLOBAL,\n}\n\ntype StepType =\n // NONE: No sort step has or will occur\n | 'NONE'\n // FLIP_LOCAL: A sort step that performs a flip operation over indices in a workgroup's locally addressable area\n // (i.e invocations * workgroup_index -> invocations * (workgroup_index + 1) - 1.\n | 'FLIP_LOCAL'\n // DISPERSE_LOCAL A sort step that performs a flip operation over indices in a workgroup's locally addressable area.\n | 'DISPERSE_LOCAL'\n // FLIP_GLOBAL A sort step that performs a flip step across a range of indices outside a workgroup's locally addressable area.\n | 'FLIP_GLOBAL'\n // DISPERSE_GLOBAL A sort step that performs a disperse operation across a range of indices outside a workgroup's locally addressable area.\n | 'DISPERSE_GLOBAL';\n\ntype DisplayType = 'Elements' | 'Swap Highlight';\n\n// Gui settings object\ninterface SettingsInterface {\n 'Total Elements': number;\n 'Grid Width': number;\n 'Grid Height': number;\n 'Grid Dimensions': string;\n 'Workgroup Size': number;\n 'Size Limit': number;\n 'Workgroups Per Step': number;\n 'Hovered Cell': number;\n 'Swapped Cell': number;\n 'Current Step': string;\n 'Step Index': number;\n 'Total Steps': number;\n 'Prev Step': StepType;\n 'Next Step': StepType;\n 'Prev Swap Span': number;\n 'Next Swap Span': number;\n executeStep: boolean;\n 'Randomize Values': () => void;\n 'Execute Sort Step': () => void;\n 'Log Elements': () => void;\n 'Complete Sort': () => void;\n 'Sort Speed': number;\n 'Display Mode': DisplayType;\n 'Total Swaps': number;\n}\n\nconst getNumSteps = (numElements: number) => {\n const n = Math.log2(numElements);\n return (n * (n + 1)) / 2;\n};\n\nlet init: SampleInit;\nSampleInitFactoryWebGPU(\n async ({ pageState, device, gui, presentationFormat, context, canvas }) => {\n const maxInvocationsX = device.limits.maxComputeWorkgroupSizeX;\n\n const totalElementOptions = [];\n const maxElements = maxInvocationsX * 32;\n for (let i = maxElements; i >= 4; i /= 2) {\n totalElementOptions.push(i);\n }\n\n const sizeLimitOptions: number[] = [];\n for (let i = maxInvocationsX; i >= 2; i /= 2) {\n sizeLimitOptions.push(i);\n }\n\n const defaultGridWidth =\n Math.sqrt(maxElements) % 2 === 0\n ? Math.floor(Math.sqrt(maxElements))\n : Math.floor(Math.sqrt(maxElements / 2));\n\n const defaultGridHeight = maxElements / defaultGridWidth;\n\n const settings: SettingsInterface = {\n // TOTAL ELEMENT AND GRID SETTINGS\n // The number of elements to be sorted. Must equal gridWidth * gridHeight || Workgroup Size * Workgroups * 2\n // When changed, all relevant values within the settings object are reset to their defaults at the beginning of a sort with n elements.\n 'Total Elements': maxElements,\n // width of screen in cells\n 'Grid Width': defaultGridWidth,\n // height of screen in cells\n 'Grid Height': defaultGridHeight,\n // Grid Dimensions as string\n 'Grid Dimensions': `${defaultGridWidth}x${defaultGridHeight}`,\n\n // INVOCATION, WORKGROUP SIZE, AND WORKGROUP DISPATCH SETTINGS\n // The size of a workgroup, or the number of invocations executed within each workgroup\n // Determined algorithmically based on 'Size Limit', maxInvocationsX, and the current number of elements to sort\n 'Workgroup Size': maxInvocationsX,\n // An artifical constraint on the maximum workgroup size/maximumn invocations per workgroup as specified by device.limits.maxComputeWorkgroupSizeX\n 'Size Limit': maxInvocationsX,\n // Total workgroups that are dispatched during each step of the bitonic sort\n 'Workgroups Per Step': maxElements / (maxInvocationsX * 2),\n\n // HOVER SETTINGS\n // The element/cell in the element visualizer directly beneath the mouse cursor\n 'Hovered Cell': 0,\n // The element/cell in the element visualizer that the hovered cell will swap with in the next execution step of the bitonic sort.\n 'Swapped Cell': 1,\n\n // STEP INDEX, STEP TYPE, AND STEP SWAP SPAN SETTINGS\n // The index of the current step in the bitonic sort.\n 'Step Index': 0,\n // The total number of steps required to sort the displayed elements.\n 'Total Steps': getNumSteps(maxElements),\n // A string that condenses 'Step Index' and 'Total Steps' into a single GUI Controller display element.\n 'Current Step': `0 of 91`,\n // The category of the previously executed step. Always begins the bitonic sort with a value of 'NONE' and ends with a value of 'DISPERSE_LOCAL'\n 'Prev Step': 'NONE',\n // The category of the next step that will be executed. Always begins the bitonic sort with a value of 'FLIP_LOCAL' and ends with a value of 'NONE'\n 'Next Step': 'FLIP_LOCAL',\n // The maximum span of a swap operation in the sort's previous step.\n 'Prev Swap Span': 0,\n // The maximum span of a swap operation in the sort's upcoming step.\n 'Next Swap Span': 2,\n\n // ANIMATION LOOP AND FUNCTION SETTINGS\n // A flag that designates whether we will dispatch a workload this frame.\n executeStep: false,\n // A function that randomizes the values of each element.\n // When called, all relevant values within the settings object are reset to their defaults at the beginning of a sort with n elements.\n 'Randomize Values': () => {\n return;\n },\n // A function that manually executes a single step of the bitonic sort.\n 'Execute Sort Step': () => {\n return;\n },\n // A function that logs the values of each element as an array to the browser's console.\n 'Log Elements': () => {\n return;\n },\n // A function that automatically executes each step of the bitonic sort at an interval determined by 'Sort Speed'\n 'Complete Sort': () => {\n return;\n },\n // The speed at which each step of the bitonic sort will be executed after 'Complete Sort' has been called.\n 'Sort Speed': 50,\n\n // MISCELLANEOUS SETTINGS\n 'Display Mode': 'Elements',\n // An atomic value representing the total number of swap operations executed over the course of the bitonic sort.\n 'Total Swaps': 0,\n };\n\n // Initialize initial elements array\n let elements = new Uint32Array(\n Array.from({ length: settings['Total Elements'] }, (_, i) => i)\n );\n\n // Initialize elementsBuffer and elementsStagingBuffer\n const elementsBufferSize =\n Float32Array.BYTES_PER_ELEMENT * totalElementOptions[0];\n // Initialize input, output, staging buffers\n const elementsInputBuffer = device.createBuffer({\n size: elementsBufferSize,\n usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,\n });\n const elementsOutputBuffer = device.createBuffer({\n size: elementsBufferSize,\n usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,\n });\n const elementsStagingBuffer = device.createBuffer({\n size: elementsBufferSize,\n usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,\n });\n\n // Initialize atomic swap buffer on GPU and CPU. Counts number of swaps actually performed by\n // compute shader (when value at index x is greater than value at index y)\n const atomicSwapsOutputBuffer = device.createBuffer({\n size: Uint32Array.BYTES_PER_ELEMENT,\n usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,\n });\n const atomicSwapsStagingBuffer = device.createBuffer({\n size: Uint32Array.BYTES_PER_ELEMENT,\n usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,\n });\n\n // Create uniform buffer for compute shader\n const computeUniformsBuffer = device.createBuffer({\n // width, height, blockHeight, algo\n size: Float32Array.BYTES_PER_ELEMENT * 4,\n usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,\n });\n\n const computeBGCluster = createBindGroupCluster(\n [0, 1, 2, 3],\n [\n GPUShaderStage.COMPUTE | GPUShaderStage.FRAGMENT,\n GPUShaderStage.COMPUTE,\n GPUShaderStage.COMPUTE | GPUShaderStage.FRAGMENT,\n GPUShaderStage.COMPUTE,\n ],\n ['buffer', 'buffer', 'buffer', 'buffer'],\n [\n { type: 'read-only-storage' },\n { type: 'storage' },\n { type: 'uniform' },\n { type: 'storage' },\n ],\n [\n [\n { buffer: elementsInputBuffer },\n { buffer: elementsOutputBuffer },\n { buffer: computeUniformsBuffer },\n { buffer: atomicSwapsOutputBuffer },\n ],\n ],\n 'BitonicSort',\n device\n );\n\n let computePipeline = device.createComputePipeline({\n layout: device.createPipelineLayout({\n bindGroupLayouts: [computeBGCluster.bindGroupLayout],\n }),\n compute: {\n module: device.createShaderModule({\n code: NaiveBitonicCompute(settings['Workgroup Size']),\n }),\n entryPoint: 'computeMain',\n },\n });\n\n // Simple pipeline that zeros out an atomic value at group 0 binding 3\n const atomicToZeroComputePipeline = device.createComputePipeline({\n layout: device.createPipelineLayout({\n bindGroupLayouts: [computeBGCluster.bindGroupLayout],\n }),\n compute: {\n module: device.createShaderModule({\n code: atomicToZero,\n }),\n entryPoint: 'atomicToZero',\n },\n });\n\n // Create bitonic debug renderer\n const renderPassDescriptor: GPURenderPassDescriptor = {\n colorAttachments: [\n {\n view: undefined, // Assigned later\n\n clearValue: { r: 0.1, g: 0.4, b: 0.5, a: 1.0 },\n loadOp: 'clear',\n storeOp: 'store',\n },\n ],\n };\n\n const bitonicDisplayRenderer = new BitonicDisplayRenderer(\n device,\n presentationFormat,\n renderPassDescriptor,\n computeBGCluster,\n 'BitonicDisplay'\n );\n\n const resetExecutionInformation = () => {\n // The workgroup size is either elements / 2 or Size Limit\n workgroupSizeController.setValue(\n Math.min(settings['Total Elements'] / 2, settings['Size Limit'])\n );\n\n // Dispatch a workgroup for every (Size Limit * 2) elements\n const workgroupsPerStep =\n (settings['Total Elements'] - 1) / (settings['Size Limit'] * 2);\n\n workgroupsPerStepController.setValue(Math.ceil(workgroupsPerStep));\n\n // Reset step Index and number of steps based on elements size\n settings['Step Index'] = 0;\n settings['Total Steps'] = getNumSteps(settings['Total Elements']);\n currentStepController.setValue(\n `${settings['Step Index']} of ${settings['Total Steps']}`\n );\n\n // Get new width and height of screen display in cells\n const newCellWidth =\n Math.sqrt(settings['Total Elements']) % 2 === 0\n ? Math.floor(Math.sqrt(settings['Total Elements']))\n : Math.floor(Math.sqrt(settings['Total Elements'] / 2));\n const newCellHeight = settings['Total Elements'] / newCellWidth;\n settings['Grid Width'] = newCellWidth;\n settings['Grid Height'] = newCellHeight;\n gridDimensionsController.setValue(`${newCellWidth}x${newCellHeight}`);\n\n // Set prevStep to None (restart) and next step to FLIP\n prevStepController.setValue('NONE');\n nextStepController.setValue('FLIP_LOCAL');\n\n // Reset block heights\n prevBlockHeightController.setValue(0);\n nextBlockHeightController.setValue(2);\n\n // Reset Total Swaps by setting atomic value to 0\n const commandEncoder = device.createCommandEncoder();\n const computePassEncoder = commandEncoder.beginComputePass();\n computePassEncoder.setPipeline(atomicToZeroComputePipeline);\n computePassEncoder.setBindGroup(0, computeBGCluster.bindGroups[0]);\n computePassEncoder.dispatchWorkgroups(1);\n computePassEncoder.end();\n device.queue.submit([commandEncoder.finish()]);\n totalSwapsController.setValue(0);\n\n highestBlockHeight = 2;\n };\n\n const randomizeElementArray = () => {\n let currentIndex = elements.length;\n // While there are elements to shuffle\n while (currentIndex !== 0) {\n // Pick a remaining element\n const randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex -= 1;\n [elements[currentIndex], elements[randomIndex]] = [\n elements[randomIndex],\n elements[currentIndex],\n ];\n }\n };\n\n const resizeElementArray = () => {\n // Recreate elements array with new length\n elements = new Uint32Array(\n Array.from({ length: settings['Total Elements'] }, (_, i) => i)\n );\n\n resetExecutionInformation();\n\n // Create new shader invocation with workgroupSize that reflects number of invocations\n computePipeline = device.createComputePipeline({\n layout: device.createPipelineLayout({\n bindGroupLayouts: [computeBGCluster.bindGroupLayout],\n }),\n compute: {\n module: device.createShaderModule({\n code: NaiveBitonicCompute(\n Math.min(settings['Total Elements'] / 2, settings['Size Limit'])\n ),\n }),\n entryPoint: 'computeMain',\n },\n });\n // Randomize array elements\n randomizeElementArray();\n highestBlockHeight = 2;\n };\n\n randomizeElementArray();\n\n const setSwappedCell = () => {\n let swappedIndex: number;\n switch (settings['Next Step']) {\n case 'FLIP_LOCAL':\n case 'FLIP_GLOBAL':\n {\n const blockHeight = settings['Next Swap Span'];\n const p2 = Math.floor(settings['Hovered Cell'] / blockHeight) + 1;\n const p3 = settings['Hovered Cell'] % blockHeight;\n swappedIndex = blockHeight * p2 - p3 - 1;\n swappedCellController.setValue(swappedIndex);\n }\n break;\n case 'DISPERSE_LOCAL':\n {\n const blockHeight = settings['Next Swap Span'];\n const halfHeight = blockHeight / 2;\n swappedIndex =\n settings['Hovered Cell'] % blockHeight < halfHeight\n ? settings['Hovered Cell'] + halfHeight\n : settings['Hovered Cell'] - halfHeight;\n swappedCellController.setValue(swappedIndex);\n }\n break;\n case 'NONE': {\n swappedIndex = settings['Hovered Cell'];\n swappedCellController.setValue(swappedIndex);\n }\n default:\n {\n swappedIndex = settings['Hovered Cell'];\n swappedCellController.setValue(swappedIndex);\n }\n break;\n }\n };\n\n let completeSortIntervalID: ReturnType | null = null;\n const endSortInterval = () => {\n if (completeSortIntervalID !== null) {\n clearInterval(completeSortIntervalID);\n completeSortIntervalID = null;\n }\n };\n const startSortInterval = () => {\n const currentIntervalSpeed = settings['Sort Speed'];\n completeSortIntervalID = setInterval(() => {\n if (settings['Next Step'] === 'NONE') {\n clearInterval(completeSortIntervalID);\n completeSortIntervalID = null;\n sizeLimitController.domElement.style.pointerEvents = 'auto';\n }\n if (settings['Sort Speed'] !== currentIntervalSpeed) {\n clearInterval(completeSortIntervalID);\n completeSortIntervalID = null;\n startSortInterval();\n }\n settings.executeStep = true;\n setSwappedCell();\n }, settings['Sort Speed']);\n };\n\n // At top level, information about resources used to execute the compute shader\n // i.e elements sorted, invocations per workgroup, and workgroups dispatched\n const computeResourcesFolder = gui.addFolder('Compute Resources');\n computeResourcesFolder\n .add(settings, 'Total Elements', totalElementOptions)\n .onChange(() => {\n endSortInterval();\n resizeElementArray();\n sizeLimitController.domElement.style.pointerEvents = 'auto';\n });\n const sizeLimitController = computeResourcesFolder\n .add(settings, 'Size Limit', sizeLimitOptions)\n .onChange(() => {\n const constraint = Math.min(\n settings['Total Elements'] / 2,\n settings['Size Limit']\n );\n const workgroupsPerStep =\n (settings['Total Elements'] - 1) / (settings['Size Limit'] * 2);\n workgroupSizeController.setValue(constraint);\n workgroupsPerStepController.setValue(Math.ceil(workgroupsPerStep));\n computePipeline = computePipeline = device.createComputePipeline({\n layout: device.createPipelineLayout({\n bindGroupLayouts: [computeBGCluster.bindGroupLayout],\n }),\n compute: {\n module: device.createShaderModule({\n code: NaiveBitonicCompute(\n Math.min(settings['Total Elements'] / 2, settings['Size Limit'])\n ),\n }),\n entryPoint: 'computeMain',\n },\n });\n });\n const workgroupSizeController = computeResourcesFolder.add(\n settings,\n 'Workgroup Size'\n );\n const workgroupsPerStepController = computeResourcesFolder.add(\n settings,\n 'Workgroups Per Step'\n );\n computeResourcesFolder.open();\n\n // Folder with functions that control the execution of the sort\n const controlFolder = gui.addFolder('Sort Controls');\n controlFolder.add(settings, 'Sort Speed', 50, 1000).step(50);\n controlFolder.add(settings, 'Execute Sort Step').onChange(() => {\n // Size Limit locked upon sort\n sizeLimitController.domElement.style.pointerEvents = 'none';\n endSortInterval();\n settings.executeStep = true;\n });\n controlFolder.add(settings, 'Randomize Values').onChange(() => {\n endSortInterval();\n randomizeElementArray();\n resetExecutionInformation();\n // Unlock workgroup size limit controller since sort has stopped\n sizeLimitController.domElement.style.pointerEvents = 'auto';\n });\n controlFolder\n .add(settings, 'Log Elements')\n .onChange(() => console.log(elements));\n controlFolder.add(settings, 'Complete Sort').onChange(() => {\n // Invocation Limit locked upon sort\n sizeLimitController.domElement.style.pointerEvents = 'none';\n startSortInterval();\n });\n controlFolder.open();\n\n // Information about grid display\n const gridFolder = gui.addFolder('Grid Information');\n gridFolder.add(settings, 'Display Mode', ['Elements', 'Swap Highlight']);\n const gridDimensionsController = gridFolder.add(\n settings,\n 'Grid Dimensions'\n );\n const hoveredCellController = gridFolder\n .add(settings, 'Hovered Cell')\n .onChange(setSwappedCell);\n const swappedCellController = gridFolder.add(settings, 'Swapped Cell');\n\n // Additional Information about the execution state of the sort\n const executionInformationFolder = gui.addFolder('Execution Information');\n const currentStepController = executionInformationFolder.add(\n settings,\n 'Current Step'\n );\n const prevStepController = executionInformationFolder.add(\n settings,\n 'Prev Step'\n );\n const nextStepController = executionInformationFolder.add(\n settings,\n 'Next Step'\n );\n const totalSwapsController = executionInformationFolder.add(\n settings,\n 'Total Swaps'\n );\n const prevBlockHeightController = executionInformationFolder.add(\n settings,\n 'Prev Swap Span'\n );\n const nextBlockHeightController = executionInformationFolder.add(\n settings,\n 'Next Swap Span'\n );\n\n // Adjust styles of Function List Elements within GUI\n const liFunctionElements = document.getElementsByClassName('cr function');\n for (let i = 0; i < liFunctionElements.length; i++) {\n (liFunctionElements[i].children[0] as HTMLElement).style.display = 'flex';\n (liFunctionElements[i].children[0] as HTMLElement).style.justifyContent =\n 'center';\n (\n liFunctionElements[i].children[0].children[1] as HTMLElement\n ).style.position = 'absolute';\n }\n\n // Mouse listener that determines values of hoveredCell and swappedCell\n canvas.addEventListener('mousemove', (event) => {\n const currWidth = canvas.getBoundingClientRect().width;\n const currHeight = canvas.getBoundingClientRect().height;\n const cellSize: [number, number] = [\n currWidth / settings['Grid Width'],\n currHeight / settings['Grid Height'],\n ];\n const xIndex = Math.floor(event.offsetX / cellSize[0]);\n const yIndex =\n settings['Grid Height'] - 1 - Math.floor(event.offsetY / cellSize[1]);\n hoveredCellController.setValue(yIndex * settings['Grid Width'] + xIndex);\n settings['Hovered Cell'] = yIndex * settings['Grid Width'] + xIndex;\n });\n\n // Deactivate interaction with select GUI elements\n sizeLimitController.domElement.style.pointerEvents = 'none';\n workgroupsPerStepController.domElement.style.pointerEvents = 'none';\n hoveredCellController.domElement.style.pointerEvents = 'none';\n swappedCellController.domElement.style.pointerEvents = 'none';\n currentStepController.domElement.style.pointerEvents = 'none';\n prevStepController.domElement.style.pointerEvents = 'none';\n prevBlockHeightController.domElement.style.pointerEvents = 'none';\n nextStepController.domElement.style.pointerEvents = 'none';\n nextBlockHeightController.domElement.style.pointerEvents = 'none';\n workgroupSizeController.domElement.style.pointerEvents = 'none';\n gridDimensionsController.domElement.style.pointerEvents = 'none';\n totalSwapsController.domElement.style.pointerEvents = 'none';\n gui.width = 325;\n\n let highestBlockHeight = 2;\n\n startSortInterval();\n\n async function frame() {\n if (!pageState.active) return;\n\n // Write elements buffer\n device.queue.writeBuffer(\n elementsInputBuffer,\n 0,\n elements.buffer,\n elements.byteOffset,\n elements.byteLength\n );\n\n const dims = new Float32Array([\n settings['Grid Width'],\n settings['Grid Height'],\n ]);\n const stepDetails = new Uint32Array([\n StepEnum[settings['Next Step']],\n settings['Next Swap Span'],\n ]);\n device.queue.writeBuffer(\n computeUniformsBuffer,\n 0,\n dims.buffer,\n dims.byteOffset,\n dims.byteLength\n );\n\n device.queue.writeBuffer(computeUniformsBuffer, 8, stepDetails);\n\n renderPassDescriptor.colorAttachments[0].view = context\n .getCurrentTexture()\n .createView();\n\n const commandEncoder = device.createCommandEncoder();\n bitonicDisplayRenderer.startRun(commandEncoder, {\n highlight: settings['Display Mode'] === 'Elements' ? 0 : 1,\n });\n if (\n settings.executeStep &&\n highestBlockHeight !== settings['Total Elements'] * 2\n ) {\n const computePassEncoder = commandEncoder.beginComputePass();\n computePassEncoder.setPipeline(computePipeline);\n computePassEncoder.setBindGroup(0, computeBGCluster.bindGroups[0]);\n computePassEncoder.dispatchWorkgroups(settings['Workgroups Per Step']);\n computePassEncoder.end();\n settings['Step Index'] = settings['Step Index'] + 1;\n currentStepController.setValue(\n `${settings['Step Index']} of ${settings['Total Steps']}`\n );\n prevStepController.setValue(settings['Next Step']);\n prevBlockHeightController.setValue(settings['Next Swap Span']);\n nextBlockHeightController.setValue(settings['Next Swap Span'] / 2);\n // Each cycle of a bitonic sort contains a flip operation followed by multiple disperse operations\n // Next Swap Span will equal one when the sort needs to begin a new cycle of flip and disperse operations\n if (settings['Next Swap Span'] === 1) {\n // The next cycle's flip operation will have a maximum swap span 2 times that of the previous cycle\n highestBlockHeight *= 2;\n if (highestBlockHeight === settings['Total Elements'] * 2) {\n // The next cycle's maximum swap span exceeds the total number of elements. Thus, the sort is over.\n nextStepController.setValue('NONE');\n nextBlockHeightController.setValue(0);\n } else if (highestBlockHeight > settings['Workgroup Size'] * 2) {\n // The next cycle's maximum swap span exceeds the range of a single workgroup, so our next flip will operate on global indices.\n nextStepController.setValue('FLIP_GLOBAL');\n nextBlockHeightController.setValue(highestBlockHeight);\n } else {\n // The next cycle's maximum swap span can be executed on a range of indices local to the workgroup.\n nextStepController.setValue('FLIP_LOCAL');\n nextBlockHeightController.setValue(highestBlockHeight);\n }\n } else {\n // Otherwise, execute the next disperse operation\n settings['Next Swap Span'] > settings['Workgroup Size'] * 2\n ? nextStepController.setValue('DISPERSE_GLOBAL')\n : nextStepController.setValue('DISPERSE_LOCAL');\n }\n\n // Copy GPU accessible buffers to CPU accessible buffers\n commandEncoder.copyBufferToBuffer(\n elementsOutputBuffer,\n 0,\n elementsStagingBuffer,\n 0,\n elementsBufferSize\n );\n\n commandEncoder.copyBufferToBuffer(\n atomicSwapsOutputBuffer,\n 0,\n atomicSwapsStagingBuffer,\n 0,\n Uint32Array.BYTES_PER_ELEMENT\n );\n }\n device.queue.submit([commandEncoder.finish()]);\n\n if (settings.executeStep) {\n // Copy GPU element data to CPU\n await elementsStagingBuffer.mapAsync(\n GPUMapMode.READ,\n 0,\n elementsBufferSize\n );\n const copyElementsBuffer = elementsStagingBuffer.getMappedRange(\n 0,\n elementsBufferSize\n );\n // Copy atomic swaps data to CPU\n await atomicSwapsStagingBuffer.mapAsync(\n GPUMapMode.READ,\n 0,\n Uint32Array.BYTES_PER_ELEMENT\n );\n const copySwapsBuffer = atomicSwapsStagingBuffer.getMappedRange(\n 0,\n Uint32Array.BYTES_PER_ELEMENT\n );\n // Get correct range of data from CPU copy of GPU Data\n const elementsData = copyElementsBuffer.slice(\n 0,\n Uint32Array.BYTES_PER_ELEMENT * settings['Total Elements']\n );\n const swapsData = copySwapsBuffer.slice(\n 0,\n Uint32Array.BYTES_PER_ELEMENT\n );\n // Extract data\n const elementsOutput = new Uint32Array(elementsData);\n totalSwapsController.setValue(new Uint32Array(swapsData)[0]);\n elementsStagingBuffer.unmap();\n atomicSwapsStagingBuffer.unmap();\n // Elements output becomes elements input, swap accumulate\n elements = elementsOutput;\n setSwappedCell();\n }\n settings.executeStep = false;\n requestAnimationFrame(frame);\n }\n requestAnimationFrame(frame);\n }\n).then((resultInit) => (init = resultInit));\n\nconst bitonicSortExample: () => JSX.Element = () =>\n makeSample({\n name: 'Bitonic Sort',\n description:\n \"A naive bitonic sort algorithm executed on the GPU, based on tgfrerer's implementation at poniesandlight.co.uk/reflect/bitonic_merge_sort/. Each dispatch of the bitonic sort shader dispatches a workgroup containing elements/2 invocations. The GUI's Execution Information folder contains information about the sort's current state. The visualizer displays the sort's results as colored cells sorted from brightest to darkest.\",\n init,\n gui: true,\n sources: [\n {\n name: __filename.substring(__dirname.length + 1),\n contents: __SOURCE__,\n },\n BitonicDisplayRenderer.sourceInfo,\n {\n name: '../../../shaders/fullscreenTexturedQuad.vert.wgsl',\n contents: fullscreenTexturedQuad,\n },\n {\n name: './bitonicDisplay.frag.wgsl',\n contents: bitonicDisplay,\n },\n {\n name: './bitonicCompute.ts',\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n contents: require('!!raw-loader!./bitonicCompute.ts').default,\n },\n {\n name: './atomicToZero.wgsl',\n contents: atomicToZero,\n },\n ],\n filename: __filename,\n });\n\nexport default bitonicSortExample;\n"},p.sourceInfo,{name:"../../../shaders/fullscreenTexturedQuad.vert.wgsl",contents:s.Z},{name:"./bitonicDisplay.frag.wgsl",contents:d},{name:"./bitonicCompute.ts",contents:t(6502).Z},{name:"./atomicToZero.wgsl",contents:f}],filename:g});var _=S},9147:function(e){e.exports={canvasContainer:"SampleLayout_canvasContainer__zRR_l",sourceFileNav:"SampleLayout_sourceFileNav__ml48P",sourceFileScrollContainer:"SampleLayout_sourceFileScrollContainer__LsNEm",sourceFileContainer:"SampleLayout_sourceFileContainer__3s84x"}},6502:function(e,n){"use strict";n.Z="export const computeArgKeys = ['width', 'height', 'algo', 'blockHeight'];\n\nexport const NaiveBitonicCompute = (workgroupSize: number) => {\n if (workgroupSize % 2 !== 0 || workgroupSize > 256) {\n workgroupSize = 256;\n }\n // Ensure that workgroupSize is half the number of elements\n return `\n\nstruct Uniforms {\n width: f32,\n height: f32,\n algo: u32,\n blockHeight: u32,\n}\n\n// Create local workgroup data that can contain all elements\nvar local_data: array;\n\n// Define groups (functions refer to this data)\n@group(0) @binding(0) var input_data: array;\n@group(0) @binding(1) var output_data: array;\n@group(0) @binding(2) var uniforms: Uniforms;\n@group(0) @binding(3) var counter: atomic;\n\n// Compare and swap values in local_data\nfn local_compare_and_swap(idx_before: u32, idx_after: u32) {\n //idx_before should always be < idx_after\n if (local_data[idx_after] < local_data[idx_before]) {\n atomicAdd(&counter, 1);\n var temp: u32 = local_data[idx_before];\n local_data[idx_before] = local_data[idx_after];\n local_data[idx_after] = temp;\n }\n return;\n}\n\n// invoke_id goes from 0 to workgroupSize\nfn get_flip_indices(invoke_id: u32, block_height: u32) -> vec2 {\n // Caculate index offset (i.e move indices into correct block)\n let block_offset: u32 = ((2 * invoke_id) / block_height) * block_height;\n let half_height = block_height / 2;\n // Calculate index spacing\n var idx: vec2 = vec2(\n invoke_id % half_height, block_height - (invoke_id % half_height) - 1,\n );\n idx.x += block_offset;\n idx.y += block_offset;\n return idx;\n}\n\nfn get_disperse_indices(invoke_id: u32, block_height: u32) -> vec2 {\n var block_offset: u32 = ((2 * invoke_id) / block_height) * block_height;\n let half_height = block_height / 2;\n var idx: vec2 = vec2(\n invoke_id % half_height, (invoke_id % half_height) + half_height\n );\n idx.x += block_offset;\n idx.y += block_offset;\n return idx;\n}\n\nfn global_compare_and_swap(idx_before: u32, idx_after: u32) {\n if (input_data[idx_after] < input_data[idx_before]) {\n output_data[idx_before] = input_data[idx_after];\n output_data[idx_after] = input_data[idx_before];\n } \n}\n\n// Constants/enum\nconst ALGO_NONE = 0;\nconst ALGO_LOCAL_FLIP = 1;\nconst ALGO_LOCAL_DISPERSE = 2;\nconst ALGO_GLOBAL_FLIP = 3;\n\n// Our compute shader will execute specified # of invocations or elements / 2 invocations\n@compute @workgroup_size(${workgroupSize}, 1, 1)\nfn computeMain(\n @builtin(global_invocation_id) global_id: vec3,\n @builtin(local_invocation_id) local_id: vec3,\n @builtin(workgroup_id) workgroup_id: vec3,\n) {\n\n let offset = ${workgroupSize} * 2 * workgroup_id.x;\n // If we will perform a local swap, then populate the local data\n if (uniforms.algo <= 2) {\n // Assign range of input_data to local_data.\n // Range cannot exceed maxWorkgroupsX * 2\n // Each invocation will populate the workgroup data... (1 invocation for every 2 elements)\n local_data[local_id.x * 2] = input_data[offset + local_id.x * 2];\n local_data[local_id.x * 2 + 1] = input_data[offset + local_id.x * 2 + 1];\n }\n\n //...and wait for each other to finish their own bit of data population.\n workgroupBarrier();\n\n switch uniforms.algo {\n case 1: { // Local Flip\n let idx = get_flip_indices(local_id.x, uniforms.blockHeight);\n local_compare_and_swap(idx.x, idx.y);\n } \n case 2: { // Local Disperse\n let idx = get_disperse_indices(local_id.x, uniforms.blockHeight);\n local_compare_and_swap(idx.x, idx.y);\n } \n case 3: { // Global Flip\n let idx = get_flip_indices(global_id.x, uniforms.blockHeight);\n global_compare_and_swap(idx.x, idx.y);\n }\n case 4: { \n let idx = get_disperse_indices(global_id.x, uniforms.blockHeight);\n global_compare_and_swap(idx.x, idx.y);\n }\n default: { \n \n }\n }\n\n // Ensure that all invocations have swapped their own regions of data\n workgroupBarrier();\n\n if (uniforms.algo <= ALGO_LOCAL_DISPERSE) {\n //Repopulate global data with local data\n output_data[offset + local_id.x * 2] = local_data[local_id.x * 2];\n output_data[offset + local_id.x * 2 + 1] = local_data[local_id.x * 2 + 1];\n }\n\n}`;\n};\n"},134:function(e,n){"use strict";n.Z="@group(0) @binding(0) var mySampler : sampler;\n@group(0) @binding(1) var myTexture : texture_2d;\n\nstruct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2,\n}\n\n@vertex\nfn vert_main(@builtin(vertex_index) VertexIndex : u32) -> VertexOutput {\n const pos = array(\n vec2( 1.0, 1.0),\n vec2( 1.0, -1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2(-1.0, 1.0),\n );\n\n const uv = array(\n vec2(1.0, 0.0),\n vec2(1.0, 1.0),\n vec2(0.0, 1.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(0.0, 0.0),\n );\n\n var output : VertexOutput;\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = uv[VertexIndex];\n return output;\n}\n\n@fragment\nfn frag_main(@location(0) fragUV : vec2) -> @location(0) vec4 {\n return textureSample(myTexture, mySampler, fragUV);\n}\n"}}]); \ No newline at end of file diff --git a/_next/static/chunks/880.ee954aed19019741.js b/_next/static/chunks/880.ee954aed19019741.js new file mode 100644 index 00000000..56c10ac7 --- /dev/null +++ b/_next/static/chunks/880.ee954aed19019741.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[880],{5671:function(e,n,t){"use strict";t.d(n,{Tl:function(){return p},hu:function(){return d}});var o=t(5893),r=t(9008),i=t.n(r),a=t(1163),s=t(7294),l=t(9147),u=t.n(l);t(7319);let c=e=>{let n=(0,s.useRef)(null),r=(0,s.useRef)(null),l=(0,s.useMemo)(()=>e.sources.map(e=>{let{name:n,contents:r}=e;return{name:n,...function(e){let n;let r=null;{r=document.createElement("div");let i=t(4631);n=i(r,{lineNumbers:!0,lineWrapping:!0,theme:"monokai",readOnly:!0})}return{Container:function(t){return(0,o.jsx)("div",{...t,children:(0,o.jsx)("div",{ref(t){r&&t&&(t.appendChild(r),n.setOption("value",e))}})})}}}(r)}}),e.sources),c=(0,s.useRef)(null),p=(0,s.useMemo)(()=>{if(e.gui){let n=t(4376),o=new n.GUI({autoPlace:!1});return o.domElement.style.position="relative",o.domElement.style.zIndex="1000",o}},[]),d=(0,s.useRef)(null),m=(0,s.useMemo)(()=>{if(e.stats){let n=t(2792);return new n}},[]),f=(0,a.useRouter)(),g=f.asPath.match(/#([a-zA-Z0-9\.\/]+)/),[h,S]=(0,s.useState)(null),[E,_]=(0,s.useState)(null);return(0,s.useEffect)(()=>{if(g?_(g[1]):_(l[0].name),p&&c.current)for(c.current.appendChild(p.domElement);p.__controllers.length>0;)p.__controllers[0].remove();m&&d.current&&(m.dom.style.position="absolute",m.showPanel(1),d.current.appendChild(m.dom));let t={active:!0},o=()=>{t.active=!1};try{let r=n.current;if(!r)throw Error("The canvas is not available");let i=e.init({canvas:r,pageState:t,gui:p,stats:m});i instanceof Promise&&i.catch(e=>{console.error(e),S(e)})}catch(a){console.error(a),S(a)}return o},[]),(0,o.jsxs)("main",{children:[(0,o.jsxs)(i(),{children:[(0,o.jsx)("style",{dangerouslySetInnerHTML:{__html:"\n .CodeMirror {\n height: auto !important;\n margin: 1em 0;\n }\n\n .CodeMirror-scroll {\n height: auto !important;\n overflow: visible !important;\n }\n "}}),(0,o.jsx)("title",{children:"".concat(e.name," - WebGPU Samples")}),(0,o.jsx)("meta",{name:"description",content:e.description}),(0,o.jsx)("meta",{httpEquiv:"origin-trial",content:e.originTrial})]}),(0,o.jsxs)("div",{children:[(0,o.jsx)("h1",{children:e.name}),(0,o.jsx)("a",{target:"_blank",rel:"noreferrer",href:"https://github.com/".concat("webgpu/webgpu-samples","/tree/main/").concat(e.filename),children:"See it on Github!"}),(0,o.jsx)("p",{children:e.description}),h?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("p",{children:"Something went wrong. Do your browser and device support WebGPU?"}),(0,o.jsx)("p",{children:"".concat(h)})]}):null]}),(0,o.jsxs)("div",{className:u().canvasContainer,children:[(0,o.jsx)("div",{style:{position:"absolute",left:10},ref:d}),(0,o.jsx)("div",{style:{position:"absolute",right:10},ref:c}),(0,o.jsx)("canvas",{ref:n})]}),(0,o.jsxs)("div",{children:[(0,o.jsx)("nav",{className:u().sourceFileNav,ref:r,children:(0,o.jsx)("div",{className:u().sourceFileScrollContainer,onScroll(e){let n=e.currentTarget,t=n.scrollWidth-n.clientWidth-n.scrollLeft;n.scrollLeft>25?r.current.setAttribute("data-left","true"):r.current.setAttribute("data-left","false"),t>25?r.current.setAttribute("data-right","true"):r.current.setAttribute("data-right","false")},children:(0,o.jsx)("ul",{children:l.map((e,n)=>(0,o.jsx)("li",{children:(0,o.jsx)("a",{href:"#".concat(e.name),"data-active":E==e.name,onClick(){_(e.name)},children:e.name})},n))})})}),l.map((e,n)=>(0,o.jsx)(e.Container,{className:u().sourceFileContainer,"data-active":E==e.name},n))]})]})},p=e=>(0,o.jsx)(c,{...e});function d(e,n){if(!e)throw Error(n)}},9880:function(e,n,t){"use strict";let o;t.r(n),t.d(n,{default:function(){return E}});var r,i,a=t(5671),s=t(134);let l=(e,n,t,o,r,i,a)=>{let s=[];for(let l=0;l{let n=async n=>{let t,{canvas:o,pageState:r,gui:i,stats:a}=n,s=await navigator.gpu.requestAdapter(),l=s.features.has("timestamp-query");if(t=l?await s.requestDevice({requiredFeatures:["timestamp-query"]}):await s.requestDevice(),!r.active)return;let u=o.getContext("webgpu"),c=window.devicePixelRatio;o.width=o.clientWidth*c,o.height=o.clientHeight*c;let p=navigator.gpu.getPreferredCanvasFormat();u.configure({device:t,format:p,alphaMode:"premultiplied"}),e({canvas:o,pageState:r,gui:i,device:t,context:u,presentationFormat:p,stats:a,timestampQueryAvailable:l})};return n};class c{executeRun(e,n,t,o){let r=e.beginRenderPass(n);r.setPipeline(t);for(let i=0;i{e.queue.writeBuffer(i,0,new Uint32Array([n.highlight]))}}}d.sourceInfo={name:"src/sample/bitonicSort/bitonicDisplay.ts".substring(23),contents:"import {\n BindGroupCluster,\n Base2DRendererClass,\n createBindGroupCluster,\n} from './utils';\n\nimport bitonicDisplay from './bitonicDisplay.frag.wgsl';\n\ninterface BitonicDisplayRenderArgs {\n highlight: number;\n}\n\nexport default class BitonicDisplayRenderer extends Base2DRendererClass {\n static sourceInfo = {\n name: __filename.substring(__dirname.length + 1),\n contents: __SOURCE__,\n };\n\n switchBindGroup: (name: string) => void;\n setArguments: (args: BitonicDisplayRenderArgs) => void;\n computeBGDescript: BindGroupCluster;\n\n constructor(\n device: GPUDevice,\n presentationFormat: GPUTextureFormat,\n renderPassDescriptor: GPURenderPassDescriptor,\n computeBGDescript: BindGroupCluster,\n label: string\n ) {\n super();\n this.renderPassDescriptor = renderPassDescriptor;\n this.computeBGDescript = computeBGDescript;\n\n const uniformBuffer = device.createBuffer({\n size: Uint32Array.BYTES_PER_ELEMENT,\n usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,\n });\n\n const bgCluster = createBindGroupCluster(\n [0],\n [GPUShaderStage.FRAGMENT],\n ['buffer'],\n [{ type: 'uniform' }],\n [[{ buffer: uniformBuffer }]],\n label,\n device\n );\n\n this.currentBindGroup = bgCluster.bindGroups[0];\n\n this.pipeline = super.create2DRenderPipeline(\n device,\n label,\n [this.computeBGDescript.bindGroupLayout, bgCluster.bindGroupLayout],\n bitonicDisplay,\n presentationFormat\n );\n\n this.setArguments = (args: BitonicDisplayRenderArgs) => {\n device.queue.writeBuffer(\n uniformBuffer,\n 0,\n new Uint32Array([args.highlight])\n );\n };\n }\n\n startRun(commandEncoder: GPUCommandEncoder, args: BitonicDisplayRenderArgs) {\n this.setArguments(args);\n super.executeRun(commandEncoder, this.renderPassDescriptor, this.pipeline, [\n this.computeBGDescript.bindGroups[0],\n this.currentBindGroup,\n ]);\n }\n}\n"};let m=e=>((e%2!=0||e>256)&&(e=256),"\n\nstruct Uniforms {\n width: f32,\n height: f32,\n algo: u32,\n blockHeight: u32,\n}\n\n// Create local workgroup data that can contain all elements\nvar local_data: array;\n\n// Define groups (functions refer to this data)\n@group(0) @binding(0) var input_data: array;\n@group(0) @binding(1) var output_data: array;\n@group(0) @binding(2) var uniforms: Uniforms;\n@group(0) @binding(3) var counter: atomic;\n\n// Compare and swap values in local_data\nfn local_compare_and_swap(idx_before: u32, idx_after: u32) {\n //idx_before should always be < idx_after\n if (local_data[idx_after] < local_data[idx_before]) {\n atomicAdd(&counter, 1);\n var temp: u32 = local_data[idx_before];\n local_data[idx_before] = local_data[idx_after];\n local_data[idx_after] = temp;\n }\n return;\n}\n\n// invoke_id goes from 0 to workgroupSize\nfn get_flip_indices(invoke_id: u32, block_height: u32) -> vec2 {\n // Caculate index offset (i.e move indices into correct block)\n let block_offset: u32 = ((2 * invoke_id) / block_height) * block_height;\n let half_height = block_height / 2;\n // Calculate index spacing\n var idx: vec2 = vec2(\n invoke_id % half_height, block_height - (invoke_id % half_height) - 1,\n );\n idx.x += block_offset;\n idx.y += block_offset;\n return idx;\n}\n\nfn get_disperse_indices(invoke_id: u32, block_height: u32) -> vec2 {\n var block_offset: u32 = ((2 * invoke_id) / block_height) * block_height;\n let half_height = block_height / 2;\n var idx: vec2 = vec2(\n invoke_id % half_height, (invoke_id % half_height) + half_height\n );\n idx.x += block_offset;\n idx.y += block_offset;\n return idx;\n}\n\nfn global_compare_and_swap(idx_before: u32, idx_after: u32) {\n if (input_data[idx_after] < input_data[idx_before]) {\n output_data[idx_before] = input_data[idx_after];\n output_data[idx_after] = input_data[idx_before];\n } \n}\n\n// Constants/enum\nconst ALGO_NONE = 0;\nconst ALGO_LOCAL_FLIP = 1;\nconst ALGO_LOCAL_DISPERSE = 2;\nconst ALGO_GLOBAL_FLIP = 3;\n\n// Our compute shader will execute specified # of invocations or elements / 2 invocations\n@compute @workgroup_size(").concat(e,", 1, 1)\nfn computeMain(\n @builtin(global_invocation_id) global_id: vec3,\n @builtin(local_invocation_id) local_id: vec3,\n @builtin(workgroup_id) workgroup_id: vec3,\n) {\n\n let offset = ").concat(e," * 2 * workgroup_id.x;\n // If we will perform a local swap, then populate the local data\n if (uniforms.algo <= 2) {\n // Assign range of input_data to local_data.\n // Range cannot exceed maxWorkgroupsX * 2\n // Each invocation will populate the workgroup data... (1 invocation for every 2 elements)\n local_data[local_id.x * 2] = input_data[offset + local_id.x * 2];\n local_data[local_id.x * 2 + 1] = input_data[offset + local_id.x * 2 + 1];\n }\n\n //...and wait for each other to finish their own bit of data population.\n workgroupBarrier();\n\n switch uniforms.algo {\n case 1: { // Local Flip\n let idx = get_flip_indices(local_id.x, uniforms.blockHeight);\n local_compare_and_swap(idx.x, idx.y);\n } \n case 2: { // Local Disperse\n let idx = get_disperse_indices(local_id.x, uniforms.blockHeight);\n local_compare_and_swap(idx.x, idx.y);\n } \n case 3: { // Global Flip\n let idx = get_flip_indices(global_id.x, uniforms.blockHeight);\n global_compare_and_swap(idx.x, idx.y);\n }\n case 4: { \n let idx = get_disperse_indices(global_id.x, uniforms.blockHeight);\n global_compare_and_swap(idx.x, idx.y);\n }\n default: { \n \n }\n }\n\n // Ensure that all invocations have swapped their own regions of data\n workgroupBarrier();\n\n if (uniforms.algo <= ALGO_LOCAL_DISPERSE) {\n //Repopulate global data with local data\n output_data[offset + local_id.x * 2] = local_data[local_id.x * 2];\n output_data[offset + local_id.x * 2 + 1] = local_data[local_id.x * 2 + 1];\n }\n\n}"));var f="@group(0) @binding(3) var counter: atomic;\n\n@compute @workgroup_size(1, 1, 1)\nfn atomicToZero() {\n let counterValue = atomicLoad(&counter);\n atomicSub(&counter, counterValue);\n}",g="src/sample/bitonicSort/main.ts";(r=i||(i={}))[r.NONE=0]="NONE",r[r.FLIP_LOCAL=1]="FLIP_LOCAL",r[r.DISPERSE_LOCAL=2]="DISPERSE_LOCAL",r[r.FLIP_GLOBAL=3]="FLIP_GLOBAL",r[r.DISPERSE_GLOBAL=4]="DISPERSE_GLOBAL";let h=e=>{let n=Math.log2(e);return n*(n+1)/2};u(async e=>{let n,t,o,{pageState:r,device:a,gui:s,presentationFormat:u,context:c,canvas:p,timestampQueryAvailable:g}=e,S=a.limits.maxComputeWorkgroupSizeX;g&&(n=a.createQuerySet({type:"timestamp",count:2}),t=a.createBuffer({size:2*BigInt64Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),o=a.createBuffer({size:2*BigInt64Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}));let E=[],_=32*S;for(let v=_;v>=4;v/=2)E.push(v);let x=[];for(let y=S;y>=2;y/=2)x.push(y);let b=Math.sqrt(_)%2==0?Math.floor(Math.sqrt(_)):Math.floor(Math.sqrt(_/2)),w=_/b,C={"Total Elements":_,"Grid Width":b,"Grid Height":w,"Grid Dimensions":"".concat(b,"x").concat(w),"Workgroup Size":S,"Size Limit":S,"Workgroups Per Step":_/(2*S),"Hovered Cell":0,"Swapped Cell":1,"Step Index":0,"Total Steps":h(_),"Current Step":"0 of 91","Prev Step":"NONE","Next Step":"FLIP_LOCAL","Prev Swap Span":0,"Next Swap Span":2,executeStep:!1,"Randomize Values"(){},"Execute Sort Step"(){},"Log Elements"(){},"Auto Sort"(){},"Auto Sort Speed":50,"Display Mode":"Elements","Total Swaps":0,"Step Time":"0ms",stepTime:0,"Sort Time":"0ms",sortTime:0,"Average Sort Time":"0ms",configToCompleteSwapsMap:{"8192 256":{sorts:0,time:0}},configKey:"8192 256"},T=new Uint32Array(Array.from({length:C["Total Elements"]},(e,n)=>n)),P=Float32Array.BYTES_PER_ELEMENT*E[0],B=a.createBuffer({size:P,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST}),L=a.createBuffer({size:P,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),A=a.createBuffer({size:P,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),G=a.createBuffer({size:Uint32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC}),I=a.createBuffer({size:Uint32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),k=a.createBuffer({size:4*Float32Array.BYTES_PER_ELEMENT,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),U=l([0,1,2,3],[GPUShaderStage.COMPUTE|GPUShaderStage.FRAGMENT,GPUShaderStage.COMPUTE,GPUShaderStage.COMPUTE|GPUShaderStage.FRAGMENT,GPUShaderStage.COMPUTE],["buffer","buffer","buffer","buffer"],[{type:"read-only-storage"},{type:"storage"},{type:"uniform"},{type:"storage"}],[[{buffer:B},{buffer:L},{buffer:k},{buffer:G}]],"BitonicSort",a),M=a.createComputePipeline({layout:a.createPipelineLayout({bindGroupLayouts:[U.bindGroupLayout]}),compute:{module:a.createShaderModule({code:m(C["Workgroup Size"])}),entryPoint:"computeMain"}}),R=a.createComputePipeline({layout:a.createPipelineLayout({bindGroupLayouts:[U.bindGroupLayout]}),compute:{module:a.createShaderModule({code:f}),entryPoint:"atomicToZero"}}),O={colorAttachments:[{view:void 0,clearValue:{r:.1,g:.4,b:.5,a:1},loadOp:"clear",storeOp:"store"}]},N=new d(a,u,O,U,"BitonicDisplay"),D=()=>{C.stepTime=0,C.sortTime=0,ec.setValue("0ms"),ep.setValue("0ms");let e=C.configToCompleteSwapsMap[C.configKey].time/C.configToCompleteSwapsMap[C.configKey].sorts;ed.setValue("".concat((e||0).toFixed(5),"ms"))},z=()=>{Q.setValue(Math.min(C["Total Elements"]/2,C["Size Limit"]));let e=(C["Total Elements"]-1)/(2*C["Size Limit"]);$.setValue(Math.ceil(e)),C["Step Index"]=0,C["Total Steps"]=h(C["Total Elements"]),eo.setValue("".concat(C["Step Index"]," of ").concat(C["Total Steps"]));let n=Math.sqrt(C["Total Elements"])%2==0?Math.floor(Math.sqrt(C["Total Elements"])):Math.floor(Math.sqrt(C["Total Elements"]/2)),t=C["Total Elements"]/n;C["Grid Width"]=n,C["Grid Height"]=t,J.setValue("".concat(n,"x").concat(t)),er.setValue("NONE"),ei.setValue("FLIP_LOCAL"),es.setValue(0),el.setValue(2);let o=a.createCommandEncoder(),r=o.beginComputePass();r.setPipeline(R),r.setBindGroup(0,U.bindGroups[0]),r.dispatchWorkgroups(1),r.end(),a.queue.submit([o.finish()]),ea.setValue(0),eg=2},F=()=>{let e=T.length;for(;0!==e;){let n=Math.floor(Math.random()*e);e-=1,[T[e],T[n]]=[T[n],T[e]]}},H=()=>{T=new Uint32Array(Array.from({length:C["Total Elements"]},(e,n)=>n)),z(),M=a.createComputePipeline({layout:a.createPipelineLayout({bindGroupLayouts:[U.bindGroupLayout]}),compute:{module:a.createShaderModule({code:m(Math.min(C["Total Elements"]/2,C["Size Limit"]))}),entryPoint:"computeMain"}}),F(),eg=2};F();let V=()=>{let e;switch(C["Next Step"]){case"FLIP_LOCAL":case"FLIP_GLOBAL":{let n=C["Next Swap Span"],t=Math.floor(C["Hovered Cell"]/n)+1,o=C["Hovered Cell"]%n;e=n*t-o-1,en.setValue(e)}break;case"DISPERSE_LOCAL":{let r=C["Next Swap Span"],i=r/2;e=C["Hovered Cell"]%r{null!==W&&(clearInterval(W),W=null)},q=()=>{let e=C["Auto Sort Speed"];W=setInterval(()=>{"NONE"===C["Next Step"]&&(clearInterval(W),W=null,K.domElement.style.pointerEvents="auto"),C["Auto Sort Speed"]!==e&&(clearInterval(W),W=null,q()),C.executeStep=!0,V()},C["Auto Sort Speed"])},j=s.addFolder("Compute Resources");j.add(C,"Total Elements",E).onChange(()=>{Y(),H(),K.domElement.style.pointerEvents="auto";let e="".concat(C["Total Elements"]," ").concat(C["Size Limit"]);C.configToCompleteSwapsMap[e]||(C.configToCompleteSwapsMap[e]={sorts:0,time:0}),C.configKey=e,D()});let K=j.add(C,"Size Limit",x).onChange(()=>{let e=Math.min(C["Total Elements"]/2,C["Size Limit"]),n=(C["Total Elements"]-1)/(2*C["Size Limit"]);Q.setValue(e),$.setValue(Math.ceil(n)),M=M=a.createComputePipeline({layout:a.createPipelineLayout({bindGroupLayouts:[U.bindGroupLayout]}),compute:{module:a.createShaderModule({code:m(Math.min(C["Total Elements"]/2,C["Size Limit"]))}),entryPoint:"computeMain"}});let t="".concat(C["Total Elements"]," ").concat(C["Size Limit"]);C.configToCompleteSwapsMap[t]||(C.configToCompleteSwapsMap[t]={sorts:0,time:0}),C.configKey=t,D()}),Q=j.add(C,"Workgroup Size"),$=j.add(C,"Workgroups Per Step");j.open();let Z=s.addFolder("Sort Controls");Z.add(C,"Execute Sort Step").onChange(()=>{K.domElement.style.pointerEvents="none",Y(),C.executeStep=!0}),Z.add(C,"Randomize Values").onChange(()=>{Y(),F(),z(),D(),K.domElement.style.pointerEvents="auto"}),Z.add(C,"Log Elements").onChange(()=>console.log(T)),Z.add(C,"Auto Sort").onChange(()=>{K.domElement.style.pointerEvents="none",q()}),Z.add(C,"Auto Sort Speed",50,1e3).step(50),Z.open();let X=s.addFolder("Grid Information");X.add(C,"Display Mode",["Elements","Swap Highlight"]);let J=X.add(C,"Grid Dimensions"),ee=X.add(C,"Hovered Cell").onChange(V),en=X.add(C,"Swapped Cell"),et=s.addFolder("Execution Information"),eo=et.add(C,"Current Step"),er=et.add(C,"Prev Step"),ei=et.add(C,"Next Step"),ea=et.add(C,"Total Swaps"),es=et.add(C,"Prev Swap Span"),el=et.add(C,"Next Swap Span"),eu=s.addFolder("Timestamp Info (Chrome 121+)"),ec=eu.add(C,"Step Time"),ep=eu.add(C,"Sort Time"),ed=eu.add(C,"Average Sort Time"),em=document.getElementsByClassName("cr function");for(let ef=0;ef{let n=p.getBoundingClientRect().width,t=p.getBoundingClientRect().height,o=[n/C["Grid Width"],t/C["Grid Height"]],r=Math.floor(e.offsetX/o[0]),i=C["Grid Height"]-1-Math.floor(e.offsetY/o[1]);ee.setValue(i*C["Grid Width"]+r),C["Hovered Cell"]=i*C["Grid Width"]+r}),K.domElement.style.pointerEvents="none",$.domElement.style.pointerEvents="none",ee.domElement.style.pointerEvents="none",en.domElement.style.pointerEvents="none",eo.domElement.style.pointerEvents="none",er.domElement.style.pointerEvents="none",es.domElement.style.pointerEvents="none",ei.domElement.style.pointerEvents="none",el.domElement.style.pointerEvents="none",Q.domElement.style.pointerEvents="none",J.domElement.style.pointerEvents="none",ea.domElement.style.pointerEvents="none",ec.domElement.style.pointerEvents="none",ep.domElement.style.pointerEvents="none",ed.domElement.style.pointerEvents="none",s.width=325;let eg=2;async function eh(){if(!r.active)return;a.queue.writeBuffer(B,0,T.buffer,T.byteOffset,T.byteLength);let e=new Float32Array([C["Grid Width"],C["Grid Height"]]),s=new Uint32Array([i[C["Next Step"]],C["Next Swap Span"]]);a.queue.writeBuffer(k,0,e.buffer,e.byteOffset,e.byteLength),a.queue.writeBuffer(k,8,s),O.colorAttachments[0].view=c.getCurrentTexture().createView();let l=a.createCommandEncoder();if(N.startRun(l,{highlight:"Elements"===C["Display Mode"]?0:1}),C.executeStep&&eg<2*C["Total Elements"]){let u;(u=g?l.beginComputePass({timestampWrites:{querySet:n,beginningOfPassWriteIndex:0,endOfPassWriteIndex:1}}):l.beginComputePass()).setPipeline(M),u.setBindGroup(0,U.bindGroups[0]),u.dispatchWorkgroups(C["Workgroups Per Step"]),u.end(),g&&(l.resolveQuerySet(n,0,2,t,0),l.copyBufferToBuffer(t,0,o,0,2*BigInt64Array.BYTES_PER_ELEMENT)),C["Step Index"]=C["Step Index"]+1,eo.setValue("".concat(C["Step Index"]," of ").concat(C["Total Steps"])),er.setValue(C["Next Step"]),es.setValue(C["Next Swap Span"]),el.setValue(C["Next Swap Span"]/2),1===C["Next Swap Span"]?(eg*=2)==2*C["Total Elements"]?(ei.setValue("NONE"),el.setValue(0),C.configToCompleteSwapsMap[C.configKey].sorts+=1):eg>2*C["Workgroup Size"]?(ei.setValue("FLIP_GLOBAL"),el.setValue(eg)):(ei.setValue("FLIP_LOCAL"),el.setValue(eg)):C["Next Swap Span"]>2*C["Workgroup Size"]?ei.setValue("DISPERSE_GLOBAL"):ei.setValue("DISPERSE_LOCAL"),l.copyBufferToBuffer(L,0,A,0,P),l.copyBufferToBuffer(G,0,I,0,Uint32Array.BYTES_PER_ELEMENT)}if(a.queue.submit([l.finish()]),C.executeStep&&eg<4*C["Total Elements"]){await A.mapAsync(GPUMapMode.READ,0,P);let p=A.getMappedRange(0,P);await I.mapAsync(GPUMapMode.READ,0,Uint32Array.BYTES_PER_ELEMENT);let d=I.getMappedRange(0,Uint32Array.BYTES_PER_ELEMENT),m=p.slice(0,Uint32Array.BYTES_PER_ELEMENT*C["Total Elements"]),f=d.slice(0,Uint32Array.BYTES_PER_ELEMENT),h=new Uint32Array(m);if(ea.setValue(new Uint32Array(f)[0]),A.unmap(),I.unmap(),T=h,V(),g){await o.mapAsync(GPUMapMode.READ,0,2*BigInt64Array.BYTES_PER_ELEMENT);let S=new BigInt64Array(o.getMappedRange()),E=Number(S[1]-S[0])/1e6,_=C.sortTime+E;if(C.stepTime=E,C.sortTime=_,ec.setValue("".concat(E.toFixed(5),"ms")),ep.setValue("".concat(_.toFixed(5),"ms")),eg===2*C["Total Elements"]){eg*=2,C.configToCompleteSwapsMap[C.configKey].time+=_;let v=C.configToCompleteSwapsMap[C.configKey].time/C.configToCompleteSwapsMap[C.configKey].sorts;ed.setValue("".concat(v.toFixed(5),"ms"))}o.unmap()}}C.executeStep=!1,requestAnimationFrame(eh)}q(),requestAnimationFrame(eh)}).then(e=>o=e);let S=()=>(0,a.Tl)({name:"Bitonic Sort",description:"A naive bitonic sort algorithm executed on the GPU, based on tgfrerer's implementation at poniesandlight.co.uk/reflect/bitonic_merge_sort/. Each dispatch of the bitonic sort shader dispatches a workgroup containing elements/2 invocations. The GUI's Execution Information folder contains information about the sort's current state. The visualizer displays the sort's results as colored cells sorted from brightest to darkest.",init:o,gui:!0,sources:[{name:g.substring(23),contents:"import { makeSample, SampleInit } from '../../components/SampleLayout';\nimport { createBindGroupCluster, SampleInitFactoryWebGPU } from './utils';\nimport BitonicDisplayRenderer from './bitonicDisplay';\nimport bitonicDisplay from './bitonicDisplay.frag.wgsl';\nimport { NaiveBitonicCompute } from './bitonicCompute';\nimport fullscreenTexturedQuad from '../../shaders/fullscreenTexturedQuad.wgsl';\nimport atomicToZero from './atomicToZero.wgsl';\n\n// Type of step that will be executed in our shader\nenum StepEnum {\n NONE,\n FLIP_LOCAL,\n DISPERSE_LOCAL,\n FLIP_GLOBAL,\n DISPERSE_GLOBAL,\n}\n\ntype StepType =\n // NONE: No sort step has or will occur\n | 'NONE'\n // FLIP_LOCAL: A sort step that performs a flip operation over indices in a workgroup's locally addressable area\n // (i.e invocations * workgroup_index -> invocations * (workgroup_index + 1) - 1.\n | 'FLIP_LOCAL'\n // DISPERSE_LOCAL A sort step that performs a flip operation over indices in a workgroup's locally addressable area.\n | 'DISPERSE_LOCAL'\n // FLIP_GLOBAL A sort step that performs a flip step across a range of indices outside a workgroup's locally addressable area.\n | 'FLIP_GLOBAL'\n // DISPERSE_GLOBAL A sort step that performs a disperse operation across a range of indices outside a workgroup's locally addressable area.\n | 'DISPERSE_GLOBAL';\n\ntype DisplayType = 'Elements' | 'Swap Highlight';\n\ninterface ConfigInfo {\n // Number of sorts executed under a given elements + size limit config\n sorts: number;\n // Total collective time taken to execute each complete sort under this config\n time: number;\n}\n\ninterface StringKeyToNumber {\n [key: string]: ConfigInfo;\n}\n\n// Gui settings object\ninterface SettingsInterface {\n 'Total Elements': number;\n 'Grid Width': number;\n 'Grid Height': number;\n 'Grid Dimensions': string;\n 'Workgroup Size': number;\n 'Size Limit': number;\n 'Workgroups Per Step': number;\n 'Hovered Cell': number;\n 'Swapped Cell': number;\n 'Current Step': string;\n 'Step Index': number;\n 'Total Steps': number;\n 'Prev Step': StepType;\n 'Next Step': StepType;\n 'Prev Swap Span': number;\n 'Next Swap Span': number;\n executeStep: boolean;\n 'Randomize Values': () => void;\n 'Execute Sort Step': () => void;\n 'Log Elements': () => void;\n 'Auto Sort': () => void;\n 'Auto Sort Speed': number;\n 'Display Mode': DisplayType;\n 'Total Swaps': number;\n stepTime: number;\n 'Step Time': string;\n sortTime: number;\n 'Sort Time': string;\n 'Average Sort Time': string;\n configToCompleteSwapsMap: StringKeyToNumber;\n configKey: string;\n}\n\nconst getNumSteps = (numElements: number) => {\n const n = Math.log2(numElements);\n return (n * (n + 1)) / 2;\n};\n\nlet init: SampleInit;\nSampleInitFactoryWebGPU(\n async ({\n pageState,\n device,\n gui,\n presentationFormat,\n context,\n canvas,\n timestampQueryAvailable,\n }) => {\n const maxInvocationsX = device.limits.maxComputeWorkgroupSizeX;\n\n let querySet: GPUQuerySet;\n let timestampQueryResolveBuffer: GPUBuffer;\n let timestampQueryResultBuffer: GPUBuffer;\n if (timestampQueryAvailable) {\n querySet = device.createQuerySet({ type: 'timestamp', count: 2 });\n timestampQueryResolveBuffer = device.createBuffer({\n // 2 timestamps * BigInt size for nanoseconds\n size: 2 * BigInt64Array.BYTES_PER_ELEMENT,\n usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,\n });\n timestampQueryResultBuffer = device.createBuffer({\n // 2 timestamps * BigInt size for nanoseconds\n size: 2 * BigInt64Array.BYTES_PER_ELEMENT,\n usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,\n });\n }\n\n const totalElementOptions = [];\n const maxElements = maxInvocationsX * 32;\n for (let i = maxElements; i >= 4; i /= 2) {\n totalElementOptions.push(i);\n }\n\n const sizeLimitOptions: number[] = [];\n for (let i = maxInvocationsX; i >= 2; i /= 2) {\n sizeLimitOptions.push(i);\n }\n\n const defaultGridWidth =\n Math.sqrt(maxElements) % 2 === 0\n ? Math.floor(Math.sqrt(maxElements))\n : Math.floor(Math.sqrt(maxElements / 2));\n\n const defaultGridHeight = maxElements / defaultGridWidth;\n\n const settings: SettingsInterface = {\n // TOTAL ELEMENT AND GRID SETTINGS\n // The number of elements to be sorted. Must equal gridWidth * gridHeight || Workgroup Size * Workgroups * 2.\n // When changed, all relevant values within the settings object are reset to their defaults at the beginning of a sort with n elements.\n 'Total Elements': maxElements,\n // The width of the screen in cells.\n 'Grid Width': defaultGridWidth,\n // The height of the screen in cells.\n 'Grid Height': defaultGridHeight,\n // Grid Dimensions as string\n 'Grid Dimensions': `${defaultGridWidth}x${defaultGridHeight}`,\n\n // INVOCATION, WORKGROUP SIZE, AND WORKGROUP DISPATCH SETTINGS\n // The size of a workgroup, or the number of invocations executed within each workgroup\n // Determined algorithmically based on 'Size Limit', maxInvocationsX, and the current number of elements to sort\n 'Workgroup Size': maxInvocationsX,\n // An artifical constraint on the maximum workgroup size/maximumn invocations per workgroup as specified by device.limits.maxComputeWorkgroupSizeX\n 'Size Limit': maxInvocationsX,\n // Total workgroups that are dispatched during each step of the bitonic sort\n 'Workgroups Per Step': maxElements / (maxInvocationsX * 2),\n\n // HOVER SETTINGS\n // The element/cell in the element visualizer directly beneath the mouse cursor\n 'Hovered Cell': 0,\n // The element/cell in the element visualizer that the hovered cell will swap with in the next execution step of the bitonic sort.\n 'Swapped Cell': 1,\n\n // STEP INDEX, STEP TYPE, AND STEP SWAP SPAN SETTINGS\n // The index of the current step in the bitonic sort.\n 'Step Index': 0,\n // The total number of steps required to sort the displayed elements.\n 'Total Steps': getNumSteps(maxElements),\n // A string that condenses 'Step Index' and 'Total Steps' into a single GUI Controller display element.\n 'Current Step': `0 of 91`,\n // The category of the previously executed step. Always begins the bitonic sort with a value of 'NONE' and ends with a value of 'DISPERSE_LOCAL'\n 'Prev Step': 'NONE',\n // The category of the next step that will be executed. Always begins the bitonic sort with a value of 'FLIP_LOCAL' and ends with a value of 'NONE'\n 'Next Step': 'FLIP_LOCAL',\n // The maximum span of a swap operation in the sort's previous step.\n 'Prev Swap Span': 0,\n // The maximum span of a swap operation in the sort's upcoming step.\n 'Next Swap Span': 2,\n\n // ANIMATION LOOP AND FUNCTION SETTINGS\n // A flag that designates whether we will dispatch a workload this frame.\n executeStep: false,\n // A function that randomizes the values of each element.\n // When called, all relevant values within the settings object are reset to their defaults at the beginning of a sort with n elements.\n 'Randomize Values': () => {\n return;\n },\n // A function that manually executes a single step of the bitonic sort.\n 'Execute Sort Step': () => {\n return;\n },\n // A function that logs the values of each element as an array to the browser's console.\n 'Log Elements': () => {\n return;\n },\n // A function that automatically executes each step of the bitonic sort at an interval determined by 'Auto Sort Speed'\n 'Auto Sort': () => {\n return;\n },\n // The speed at which each step of the bitonic sort will be executed after 'Auto Sort' has been called.\n 'Auto Sort Speed': 50,\n\n // MISCELLANEOUS SETTINGS\n 'Display Mode': 'Elements',\n // An atomic value representing the total number of swap operations executed over the course of the bitonic sort.\n 'Total Swaps': 0,\n\n // TIMESTAMP SETTINGS\n // NOTE: Timestep values below all are calculated in terms of milliseconds rather than the nanoseconds a timestamp query set usually outputs.\n // Time taken to execute the previous step of the bitonic sort in milliseconds\n 'Step Time': '0ms',\n stepTime: 0,\n // Total taken to colletively execute each step of the complete bitonic sort, represented in milliseconds.\n 'Sort Time': '0ms',\n sortTime: 0,\n // Average time taken to complete a bitonic sort with the current combination of n 'Total Elements' and x 'Size Limit'\n 'Average Sort Time': '0ms',\n // A string to number map that maps a string representation of the current 'Total Elements' + 'Size Limit' configuration to a number\n // representing the total number of sorts that have been executed under that same configuration.\n configToCompleteSwapsMap: {\n '8192 256': {\n sorts: 0,\n time: 0,\n },\n },\n // Current key into configToCompleteSwapsMap\n configKey: '8192 256',\n };\n\n // Initialize initial elements array\n let elements = new Uint32Array(\n Array.from({ length: settings['Total Elements'] }, (_, i) => i)\n );\n\n // Initialize elementsBuffer and elementsStagingBuffer\n const elementsBufferSize =\n Float32Array.BYTES_PER_ELEMENT * totalElementOptions[0];\n // Initialize input, output, staging buffers\n const elementsInputBuffer = device.createBuffer({\n size: elementsBufferSize,\n usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,\n });\n const elementsOutputBuffer = device.createBuffer({\n size: elementsBufferSize,\n usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,\n });\n const elementsStagingBuffer = device.createBuffer({\n size: elementsBufferSize,\n usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,\n });\n\n // Initialize atomic swap buffer on GPU and CPU. Counts number of swaps actually performed by\n // compute shader (when value at index x is greater than value at index y)\n const atomicSwapsOutputBuffer = device.createBuffer({\n size: Uint32Array.BYTES_PER_ELEMENT,\n usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC,\n });\n const atomicSwapsStagingBuffer = device.createBuffer({\n size: Uint32Array.BYTES_PER_ELEMENT,\n usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,\n });\n\n // Create uniform buffer for compute shader\n const computeUniformsBuffer = device.createBuffer({\n // width, height, blockHeight, algo\n size: Float32Array.BYTES_PER_ELEMENT * 4,\n usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,\n });\n\n const computeBGCluster = createBindGroupCluster(\n [0, 1, 2, 3],\n [\n GPUShaderStage.COMPUTE | GPUShaderStage.FRAGMENT,\n GPUShaderStage.COMPUTE,\n GPUShaderStage.COMPUTE | GPUShaderStage.FRAGMENT,\n GPUShaderStage.COMPUTE,\n ],\n ['buffer', 'buffer', 'buffer', 'buffer'],\n [\n { type: 'read-only-storage' },\n { type: 'storage' },\n { type: 'uniform' },\n { type: 'storage' },\n ],\n [\n [\n { buffer: elementsInputBuffer },\n { buffer: elementsOutputBuffer },\n { buffer: computeUniformsBuffer },\n { buffer: atomicSwapsOutputBuffer },\n ],\n ],\n 'BitonicSort',\n device\n );\n\n let computePipeline = device.createComputePipeline({\n layout: device.createPipelineLayout({\n bindGroupLayouts: [computeBGCluster.bindGroupLayout],\n }),\n compute: {\n module: device.createShaderModule({\n code: NaiveBitonicCompute(settings['Workgroup Size']),\n }),\n entryPoint: 'computeMain',\n },\n });\n\n // Simple pipeline that zeros out an atomic value at group 0 binding 3\n const atomicToZeroComputePipeline = device.createComputePipeline({\n layout: device.createPipelineLayout({\n bindGroupLayouts: [computeBGCluster.bindGroupLayout],\n }),\n compute: {\n module: device.createShaderModule({\n code: atomicToZero,\n }),\n entryPoint: 'atomicToZero',\n },\n });\n\n // Create bitonic debug renderer\n const renderPassDescriptor: GPURenderPassDescriptor = {\n colorAttachments: [\n {\n view: undefined, // Assigned later\n\n clearValue: { r: 0.1, g: 0.4, b: 0.5, a: 1.0 },\n loadOp: 'clear',\n storeOp: 'store',\n },\n ],\n };\n\n const bitonicDisplayRenderer = new BitonicDisplayRenderer(\n device,\n presentationFormat,\n renderPassDescriptor,\n computeBGCluster,\n 'BitonicDisplay'\n );\n\n const resetTimeInfo = () => {\n settings.stepTime = 0;\n settings.sortTime = 0;\n stepTimeController.setValue('0ms');\n sortTimeController.setValue(`0ms`);\n const nanCheck =\n settings.configToCompleteSwapsMap[settings.configKey].time /\n settings.configToCompleteSwapsMap[settings.configKey].sorts;\n const ast = nanCheck ? nanCheck : 0;\n averageSortTimeController.setValue(`${ast.toFixed(5)}ms`);\n };\n\n const resetExecutionInformation = () => {\n // The workgroup size is either elements / 2 or Size Limit\n workgroupSizeController.setValue(\n Math.min(settings['Total Elements'] / 2, settings['Size Limit'])\n );\n\n // Dispatch a workgroup for every (Size Limit * 2) elements\n const workgroupsPerStep =\n (settings['Total Elements'] - 1) / (settings['Size Limit'] * 2);\n\n workgroupsPerStepController.setValue(Math.ceil(workgroupsPerStep));\n\n // Reset step Index and number of steps based on elements size\n settings['Step Index'] = 0;\n settings['Total Steps'] = getNumSteps(settings['Total Elements']);\n currentStepController.setValue(\n `${settings['Step Index']} of ${settings['Total Steps']}`\n );\n\n // Get new width and height of screen display in cells\n const newCellWidth =\n Math.sqrt(settings['Total Elements']) % 2 === 0\n ? Math.floor(Math.sqrt(settings['Total Elements']))\n : Math.floor(Math.sqrt(settings['Total Elements'] / 2));\n const newCellHeight = settings['Total Elements'] / newCellWidth;\n settings['Grid Width'] = newCellWidth;\n settings['Grid Height'] = newCellHeight;\n gridDimensionsController.setValue(`${newCellWidth}x${newCellHeight}`);\n\n // Set prevStep to None (restart) and next step to FLIP\n prevStepController.setValue('NONE');\n nextStepController.setValue('FLIP_LOCAL');\n\n // Reset block heights\n prevBlockHeightController.setValue(0);\n nextBlockHeightController.setValue(2);\n\n // Reset Total Swaps by setting atomic value to 0\n const commandEncoder = device.createCommandEncoder();\n const computePassEncoder = commandEncoder.beginComputePass();\n computePassEncoder.setPipeline(atomicToZeroComputePipeline);\n computePassEncoder.setBindGroup(0, computeBGCluster.bindGroups[0]);\n computePassEncoder.dispatchWorkgroups(1);\n computePassEncoder.end();\n device.queue.submit([commandEncoder.finish()]);\n totalSwapsController.setValue(0);\n\n highestBlockHeight = 2;\n };\n\n const randomizeElementArray = () => {\n let currentIndex = elements.length;\n // While there are elements to shuffle\n while (currentIndex !== 0) {\n // Pick a remaining element\n const randomIndex = Math.floor(Math.random() * currentIndex);\n currentIndex -= 1;\n [elements[currentIndex], elements[randomIndex]] = [\n elements[randomIndex],\n elements[currentIndex],\n ];\n }\n };\n\n const resizeElementArray = () => {\n // Recreate elements array with new length\n elements = new Uint32Array(\n Array.from({ length: settings['Total Elements'] }, (_, i) => i)\n );\n\n resetExecutionInformation();\n\n // Create new shader invocation with workgroupSize that reflects number of invocations\n computePipeline = device.createComputePipeline({\n layout: device.createPipelineLayout({\n bindGroupLayouts: [computeBGCluster.bindGroupLayout],\n }),\n compute: {\n module: device.createShaderModule({\n code: NaiveBitonicCompute(\n Math.min(settings['Total Elements'] / 2, settings['Size Limit'])\n ),\n }),\n entryPoint: 'computeMain',\n },\n });\n // Randomize array elements\n randomizeElementArray();\n highestBlockHeight = 2;\n };\n\n randomizeElementArray();\n\n const setSwappedCell = () => {\n let swappedIndex: number;\n switch (settings['Next Step']) {\n case 'FLIP_LOCAL':\n case 'FLIP_GLOBAL':\n {\n const blockHeight = settings['Next Swap Span'];\n const p2 = Math.floor(settings['Hovered Cell'] / blockHeight) + 1;\n const p3 = settings['Hovered Cell'] % blockHeight;\n swappedIndex = blockHeight * p2 - p3 - 1;\n swappedCellController.setValue(swappedIndex);\n }\n break;\n case 'DISPERSE_LOCAL':\n {\n const blockHeight = settings['Next Swap Span'];\n const halfHeight = blockHeight / 2;\n swappedIndex =\n settings['Hovered Cell'] % blockHeight < halfHeight\n ? settings['Hovered Cell'] + halfHeight\n : settings['Hovered Cell'] - halfHeight;\n swappedCellController.setValue(swappedIndex);\n }\n break;\n case 'NONE': {\n swappedIndex = settings['Hovered Cell'];\n swappedCellController.setValue(swappedIndex);\n }\n default:\n {\n swappedIndex = settings['Hovered Cell'];\n swappedCellController.setValue(swappedIndex);\n }\n break;\n }\n };\n\n let autoSortIntervalID: ReturnType | null = null;\n const endSortInterval = () => {\n if (autoSortIntervalID !== null) {\n clearInterval(autoSortIntervalID);\n autoSortIntervalID = null;\n }\n };\n const startSortInterval = () => {\n const currentIntervalSpeed = settings['Auto Sort Speed'];\n autoSortIntervalID = setInterval(() => {\n if (settings['Next Step'] === 'NONE') {\n clearInterval(autoSortIntervalID);\n autoSortIntervalID = null;\n sizeLimitController.domElement.style.pointerEvents = 'auto';\n }\n if (settings['Auto Sort Speed'] !== currentIntervalSpeed) {\n clearInterval(autoSortIntervalID);\n autoSortIntervalID = null;\n startSortInterval();\n }\n settings.executeStep = true;\n setSwappedCell();\n }, settings['Auto Sort Speed']);\n };\n\n // At top level, information about resources used to execute the compute shader\n // i.e elements sorted, invocations per workgroup, and workgroups dispatched\n const computeResourcesFolder = gui.addFolder('Compute Resources');\n computeResourcesFolder\n .add(settings, 'Total Elements', totalElementOptions)\n .onChange(() => {\n endSortInterval();\n resizeElementArray();\n sizeLimitController.domElement.style.pointerEvents = 'auto';\n // Create new config key for current element + size limit configuration\n const currConfigKey = `${settings['Total Elements']} ${settings['Size Limit']}`;\n // If configKey doesn't exist in the map, create it.\n if (!settings.configToCompleteSwapsMap[currConfigKey]) {\n settings.configToCompleteSwapsMap[currConfigKey] = {\n sorts: 0,\n time: 0,\n };\n }\n settings.configKey = currConfigKey;\n resetTimeInfo();\n });\n const sizeLimitController = computeResourcesFolder\n .add(settings, 'Size Limit', sizeLimitOptions)\n .onChange(() => {\n // Change total workgroups per step and size of a workgroup based on arbitrary constraint\n // imposed by size limit.\n const constraint = Math.min(\n settings['Total Elements'] / 2,\n settings['Size Limit']\n );\n const workgroupsPerStep =\n (settings['Total Elements'] - 1) / (settings['Size Limit'] * 2);\n workgroupSizeController.setValue(constraint);\n workgroupsPerStepController.setValue(Math.ceil(workgroupsPerStep));\n // Apply new compute resources values to the sort's compute pipeline\n computePipeline = computePipeline = device.createComputePipeline({\n layout: device.createPipelineLayout({\n bindGroupLayouts: [computeBGCluster.bindGroupLayout],\n }),\n compute: {\n module: device.createShaderModule({\n code: NaiveBitonicCompute(\n Math.min(settings['Total Elements'] / 2, settings['Size Limit'])\n ),\n }),\n entryPoint: 'computeMain',\n },\n });\n // Create new config key for current element + size limit configuration\n const currConfigKey = `${settings['Total Elements']} ${settings['Size Limit']}`;\n // If configKey doesn't exist in the map, create it.\n if (!settings.configToCompleteSwapsMap[currConfigKey]) {\n settings.configToCompleteSwapsMap[currConfigKey] = {\n sorts: 0,\n time: 0,\n };\n }\n settings.configKey = currConfigKey;\n resetTimeInfo();\n });\n const workgroupSizeController = computeResourcesFolder.add(\n settings,\n 'Workgroup Size'\n );\n const workgroupsPerStepController = computeResourcesFolder.add(\n settings,\n 'Workgroups Per Step'\n );\n\n computeResourcesFolder.open();\n\n // Folder with functions that control the execution of the sort\n const controlFolder = gui.addFolder('Sort Controls');\n controlFolder.add(settings, 'Execute Sort Step').onChange(() => {\n // Size Limit locked upon sort\n sizeLimitController.domElement.style.pointerEvents = 'none';\n endSortInterval();\n settings.executeStep = true;\n });\n controlFolder.add(settings, 'Randomize Values').onChange(() => {\n endSortInterval();\n randomizeElementArray();\n resetExecutionInformation();\n resetTimeInfo();\n // Unlock workgroup size limit controller since sort has stopped\n sizeLimitController.domElement.style.pointerEvents = 'auto';\n });\n controlFolder\n .add(settings, 'Log Elements')\n .onChange(() => console.log(elements));\n controlFolder.add(settings, 'Auto Sort').onChange(() => {\n // Invocation Limit locked upon sort\n sizeLimitController.domElement.style.pointerEvents = 'none';\n startSortInterval();\n });\n controlFolder.add(settings, 'Auto Sort Speed', 50, 1000).step(50);\n controlFolder.open();\n\n // Information about grid display\n const gridFolder = gui.addFolder('Grid Information');\n gridFolder.add(settings, 'Display Mode', ['Elements', 'Swap Highlight']);\n const gridDimensionsController = gridFolder.add(\n settings,\n 'Grid Dimensions'\n );\n const hoveredCellController = gridFolder\n .add(settings, 'Hovered Cell')\n .onChange(setSwappedCell);\n const swappedCellController = gridFolder.add(settings, 'Swapped Cell');\n\n // Additional Information about the execution state of the sort\n const executionInformationFolder = gui.addFolder('Execution Information');\n const currentStepController = executionInformationFolder.add(\n settings,\n 'Current Step'\n );\n const prevStepController = executionInformationFolder.add(\n settings,\n 'Prev Step'\n );\n const nextStepController = executionInformationFolder.add(\n settings,\n 'Next Step'\n );\n const totalSwapsController = executionInformationFolder.add(\n settings,\n 'Total Swaps'\n );\n const prevBlockHeightController = executionInformationFolder.add(\n settings,\n 'Prev Swap Span'\n );\n const nextBlockHeightController = executionInformationFolder.add(\n settings,\n 'Next Swap Span'\n );\n\n // Timestamp information for Chrome 121+ or other compatible browsers\n const timestampFolder = gui.addFolder('Timestamp Info (Chrome 121+)');\n const stepTimeController = timestampFolder.add(settings, 'Step Time');\n const sortTimeController = timestampFolder.add(settings, 'Sort Time');\n const averageSortTimeController = timestampFolder.add(\n settings,\n 'Average Sort Time'\n );\n\n // Adjust styles of Function List Elements within GUI\n const liFunctionElements = document.getElementsByClassName('cr function');\n for (let i = 0; i < liFunctionElements.length; i++) {\n (liFunctionElements[i].children[0] as HTMLElement).style.display = 'flex';\n (liFunctionElements[i].children[0] as HTMLElement).style.justifyContent =\n 'center';\n (\n liFunctionElements[i].children[0].children[1] as HTMLElement\n ).style.position = 'absolute';\n }\n\n // Mouse listener that determines values of hoveredCell and swappedCell\n canvas.addEventListener('mousemove', (event) => {\n const currWidth = canvas.getBoundingClientRect().width;\n const currHeight = canvas.getBoundingClientRect().height;\n const cellSize: [number, number] = [\n currWidth / settings['Grid Width'],\n currHeight / settings['Grid Height'],\n ];\n const xIndex = Math.floor(event.offsetX / cellSize[0]);\n const yIndex =\n settings['Grid Height'] - 1 - Math.floor(event.offsetY / cellSize[1]);\n hoveredCellController.setValue(yIndex * settings['Grid Width'] + xIndex);\n settings['Hovered Cell'] = yIndex * settings['Grid Width'] + xIndex;\n });\n\n // Deactivate interaction with select GUI elements\n sizeLimitController.domElement.style.pointerEvents = 'none';\n workgroupsPerStepController.domElement.style.pointerEvents = 'none';\n hoveredCellController.domElement.style.pointerEvents = 'none';\n swappedCellController.domElement.style.pointerEvents = 'none';\n currentStepController.domElement.style.pointerEvents = 'none';\n prevStepController.domElement.style.pointerEvents = 'none';\n prevBlockHeightController.domElement.style.pointerEvents = 'none';\n nextStepController.domElement.style.pointerEvents = 'none';\n nextBlockHeightController.domElement.style.pointerEvents = 'none';\n workgroupSizeController.domElement.style.pointerEvents = 'none';\n gridDimensionsController.domElement.style.pointerEvents = 'none';\n totalSwapsController.domElement.style.pointerEvents = 'none';\n stepTimeController.domElement.style.pointerEvents = 'none';\n sortTimeController.domElement.style.pointerEvents = 'none';\n averageSortTimeController.domElement.style.pointerEvents = 'none';\n gui.width = 325;\n\n let highestBlockHeight = 2;\n\n startSortInterval();\n\n async function frame() {\n if (!pageState.active) return;\n\n // Write elements buffer\n device.queue.writeBuffer(\n elementsInputBuffer,\n 0,\n elements.buffer,\n elements.byteOffset,\n elements.byteLength\n );\n\n const dims = new Float32Array([\n settings['Grid Width'],\n settings['Grid Height'],\n ]);\n const stepDetails = new Uint32Array([\n StepEnum[settings['Next Step']],\n settings['Next Swap Span'],\n ]);\n device.queue.writeBuffer(\n computeUniformsBuffer,\n 0,\n dims.buffer,\n dims.byteOffset,\n dims.byteLength\n );\n\n device.queue.writeBuffer(computeUniformsBuffer, 8, stepDetails);\n\n renderPassDescriptor.colorAttachments[0].view = context\n .getCurrentTexture()\n .createView();\n\n const commandEncoder = device.createCommandEncoder();\n bitonicDisplayRenderer.startRun(commandEncoder, {\n highlight: settings['Display Mode'] === 'Elements' ? 0 : 1,\n });\n if (\n settings.executeStep &&\n highestBlockHeight < settings['Total Elements'] * 2\n ) {\n let computePassEncoder: GPUComputePassEncoder;\n if (timestampQueryAvailable) {\n computePassEncoder = commandEncoder.beginComputePass({\n timestampWrites: {\n querySet,\n beginningOfPassWriteIndex: 0,\n endOfPassWriteIndex: 1,\n },\n });\n } else {\n computePassEncoder = commandEncoder.beginComputePass();\n }\n computePassEncoder.setPipeline(computePipeline);\n computePassEncoder.setBindGroup(0, computeBGCluster.bindGroups[0]);\n computePassEncoder.dispatchWorkgroups(settings['Workgroups Per Step']);\n computePassEncoder.end();\n // Resolve time passed in between beginning and end of computePass\n if (timestampQueryAvailable) {\n commandEncoder.resolveQuerySet(\n querySet,\n 0,\n 2,\n timestampQueryResolveBuffer,\n 0\n );\n commandEncoder.copyBufferToBuffer(\n timestampQueryResolveBuffer,\n 0,\n timestampQueryResultBuffer,\n 0,\n 2 * BigInt64Array.BYTES_PER_ELEMENT\n );\n }\n settings['Step Index'] = settings['Step Index'] + 1;\n currentStepController.setValue(\n `${settings['Step Index']} of ${settings['Total Steps']}`\n );\n prevStepController.setValue(settings['Next Step']);\n prevBlockHeightController.setValue(settings['Next Swap Span']);\n nextBlockHeightController.setValue(settings['Next Swap Span'] / 2);\n // Each cycle of a bitonic sort contains a flip operation followed by multiple disperse operations\n // Next Swap Span will equal one when the sort needs to begin a new cycle of flip and disperse operations\n if (settings['Next Swap Span'] === 1) {\n // The next cycle's flip operation will have a maximum swap span 2 times that of the previous cycle\n highestBlockHeight *= 2;\n if (highestBlockHeight === settings['Total Elements'] * 2) {\n // The next cycle's maximum swap span exceeds the total number of elements. Therefore, the sort is over.\n // Accordingly, there will be no next step.\n nextStepController.setValue('NONE');\n // And if there is no next step, then there are no swaps, and no block range within which two elements are swapped.\n nextBlockHeightController.setValue(0);\n // Finally, with our sort completed, we can increment the number of total completed sorts executed with n 'Total Elements'\n // and x 'Size Limit', which will allow us to calculate the average time of all sorts executed with this specific\n // configuration of compute resources\n settings.configToCompleteSwapsMap[settings.configKey].sorts += 1;\n } else if (highestBlockHeight > settings['Workgroup Size'] * 2) {\n // The next cycle's maximum swap span exceeds the range of a single workgroup, so our next flip will operate on global indices.\n nextStepController.setValue('FLIP_GLOBAL');\n nextBlockHeightController.setValue(highestBlockHeight);\n } else {\n // The next cycle's maximum swap span can be executed on a range of indices local to the workgroup.\n nextStepController.setValue('FLIP_LOCAL');\n nextBlockHeightController.setValue(highestBlockHeight);\n }\n } else {\n // Otherwise, execute the next disperse operation\n settings['Next Swap Span'] > settings['Workgroup Size'] * 2\n ? nextStepController.setValue('DISPERSE_GLOBAL')\n : nextStepController.setValue('DISPERSE_LOCAL');\n }\n\n // Copy GPU accessible buffers to CPU accessible buffers\n commandEncoder.copyBufferToBuffer(\n elementsOutputBuffer,\n 0,\n elementsStagingBuffer,\n 0,\n elementsBufferSize\n );\n\n commandEncoder.copyBufferToBuffer(\n atomicSwapsOutputBuffer,\n 0,\n atomicSwapsStagingBuffer,\n 0,\n Uint32Array.BYTES_PER_ELEMENT\n );\n }\n device.queue.submit([commandEncoder.finish()]);\n\n if (\n settings.executeStep &&\n highestBlockHeight < settings['Total Elements'] * 4\n ) {\n // Copy GPU element data to CPU\n await elementsStagingBuffer.mapAsync(\n GPUMapMode.READ,\n 0,\n elementsBufferSize\n );\n const copyElementsBuffer = elementsStagingBuffer.getMappedRange(\n 0,\n elementsBufferSize\n );\n // Copy atomic swaps data to CPU\n await atomicSwapsStagingBuffer.mapAsync(\n GPUMapMode.READ,\n 0,\n Uint32Array.BYTES_PER_ELEMENT\n );\n const copySwapsBuffer = atomicSwapsStagingBuffer.getMappedRange(\n 0,\n Uint32Array.BYTES_PER_ELEMENT\n );\n const elementsData = copyElementsBuffer.slice(\n 0,\n Uint32Array.BYTES_PER_ELEMENT * settings['Total Elements']\n );\n const swapsData = copySwapsBuffer.slice(\n 0,\n Uint32Array.BYTES_PER_ELEMENT\n );\n // Extract data\n const elementsOutput = new Uint32Array(elementsData);\n totalSwapsController.setValue(new Uint32Array(swapsData)[0]);\n elementsStagingBuffer.unmap();\n atomicSwapsStagingBuffer.unmap();\n // Elements output becomes elements input, swap accumulate\n elements = elementsOutput;\n setSwappedCell();\n\n // Handle timestamp query stuff\n if (timestampQueryAvailable) {\n // Copy timestamp query result buffer data to CPU\n await timestampQueryResultBuffer.mapAsync(\n GPUMapMode.READ,\n 0,\n 2 * BigInt64Array.BYTES_PER_ELEMENT\n );\n const copyTimestampResult = new BigInt64Array(\n timestampQueryResultBuffer.getMappedRange()\n );\n // Calculate new step, sort, and average sort times\n const newStepTime =\n Number(copyTimestampResult[1] - copyTimestampResult[0]) / 1000000;\n const newSortTime = settings.sortTime + newStepTime;\n // Apply calculated times to settings object as both number and 'ms' appended string\n settings.stepTime = newStepTime;\n settings.sortTime = newSortTime;\n stepTimeController.setValue(`${newStepTime.toFixed(5)}ms`);\n sortTimeController.setValue(`${newSortTime.toFixed(5)}ms`);\n // Calculate new average sort upon end of final execution step of a full bitonic sort.\n if (highestBlockHeight === settings['Total Elements'] * 2) {\n // Lock off access to this larger if block..not best architected solution but eh\n highestBlockHeight *= 2;\n settings.configToCompleteSwapsMap[settings.configKey].time +=\n newSortTime;\n const averageSortTime =\n settings.configToCompleteSwapsMap[settings.configKey].time /\n settings.configToCompleteSwapsMap[settings.configKey].sorts;\n averageSortTimeController.setValue(\n `${averageSortTime.toFixed(5)}ms`\n );\n }\n timestampQueryResultBuffer.unmap();\n // Get correct range of data from CPU copy of GPU Data\n }\n }\n settings.executeStep = false;\n requestAnimationFrame(frame);\n }\n requestAnimationFrame(frame);\n }\n).then((resultInit) => (init = resultInit));\n\nconst bitonicSortExample: () => JSX.Element = () =>\n makeSample({\n name: 'Bitonic Sort',\n description:\n \"A naive bitonic sort algorithm executed on the GPU, based on tgfrerer's implementation at poniesandlight.co.uk/reflect/bitonic_merge_sort/. Each dispatch of the bitonic sort shader dispatches a workgroup containing elements/2 invocations. The GUI's Execution Information folder contains information about the sort's current state. The visualizer displays the sort's results as colored cells sorted from brightest to darkest.\",\n init,\n gui: true,\n sources: [\n {\n name: __filename.substring(__dirname.length + 1),\n contents: __SOURCE__,\n },\n BitonicDisplayRenderer.sourceInfo,\n {\n name: '../../../shaders/fullscreenTexturedQuad.vert.wgsl',\n contents: fullscreenTexturedQuad,\n },\n {\n name: './bitonicDisplay.frag.wgsl',\n contents: bitonicDisplay,\n },\n {\n name: './bitonicCompute.ts',\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n contents: require('!!raw-loader!./bitonicCompute.ts').default,\n },\n {\n name: './atomicToZero.wgsl',\n contents: atomicToZero,\n },\n ],\n filename: __filename,\n });\n\nexport default bitonicSortExample;\n"},d.sourceInfo,{name:"../../../shaders/fullscreenTexturedQuad.vert.wgsl",contents:s.Z},{name:"./bitonicDisplay.frag.wgsl",contents:p},{name:"./bitonicCompute.ts",contents:t(6502).Z},{name:"./atomicToZero.wgsl",contents:f}],filename:g});var E=S},9147:function(e){e.exports={canvasContainer:"SampleLayout_canvasContainer__zRR_l",sourceFileNav:"SampleLayout_sourceFileNav__ml48P",sourceFileScrollContainer:"SampleLayout_sourceFileScrollContainer__LsNEm",sourceFileContainer:"SampleLayout_sourceFileContainer__3s84x"}},6502:function(e,n){"use strict";n.Z="export const computeArgKeys = ['width', 'height', 'algo', 'blockHeight'];\n\nexport const NaiveBitonicCompute = (workgroupSize: number) => {\n if (workgroupSize % 2 !== 0 || workgroupSize > 256) {\n workgroupSize = 256;\n }\n // Ensure that workgroupSize is half the number of elements\n return `\n\nstruct Uniforms {\n width: f32,\n height: f32,\n algo: u32,\n blockHeight: u32,\n}\n\n// Create local workgroup data that can contain all elements\nvar local_data: array;\n\n// Define groups (functions refer to this data)\n@group(0) @binding(0) var input_data: array;\n@group(0) @binding(1) var output_data: array;\n@group(0) @binding(2) var uniforms: Uniforms;\n@group(0) @binding(3) var counter: atomic;\n\n// Compare and swap values in local_data\nfn local_compare_and_swap(idx_before: u32, idx_after: u32) {\n //idx_before should always be < idx_after\n if (local_data[idx_after] < local_data[idx_before]) {\n atomicAdd(&counter, 1);\n var temp: u32 = local_data[idx_before];\n local_data[idx_before] = local_data[idx_after];\n local_data[idx_after] = temp;\n }\n return;\n}\n\n// invoke_id goes from 0 to workgroupSize\nfn get_flip_indices(invoke_id: u32, block_height: u32) -> vec2 {\n // Caculate index offset (i.e move indices into correct block)\n let block_offset: u32 = ((2 * invoke_id) / block_height) * block_height;\n let half_height = block_height / 2;\n // Calculate index spacing\n var idx: vec2 = vec2(\n invoke_id % half_height, block_height - (invoke_id % half_height) - 1,\n );\n idx.x += block_offset;\n idx.y += block_offset;\n return idx;\n}\n\nfn get_disperse_indices(invoke_id: u32, block_height: u32) -> vec2 {\n var block_offset: u32 = ((2 * invoke_id) / block_height) * block_height;\n let half_height = block_height / 2;\n var idx: vec2 = vec2(\n invoke_id % half_height, (invoke_id % half_height) + half_height\n );\n idx.x += block_offset;\n idx.y += block_offset;\n return idx;\n}\n\nfn global_compare_and_swap(idx_before: u32, idx_after: u32) {\n if (input_data[idx_after] < input_data[idx_before]) {\n output_data[idx_before] = input_data[idx_after];\n output_data[idx_after] = input_data[idx_before];\n } \n}\n\n// Constants/enum\nconst ALGO_NONE = 0;\nconst ALGO_LOCAL_FLIP = 1;\nconst ALGO_LOCAL_DISPERSE = 2;\nconst ALGO_GLOBAL_FLIP = 3;\n\n// Our compute shader will execute specified # of invocations or elements / 2 invocations\n@compute @workgroup_size(${workgroupSize}, 1, 1)\nfn computeMain(\n @builtin(global_invocation_id) global_id: vec3,\n @builtin(local_invocation_id) local_id: vec3,\n @builtin(workgroup_id) workgroup_id: vec3,\n) {\n\n let offset = ${workgroupSize} * 2 * workgroup_id.x;\n // If we will perform a local swap, then populate the local data\n if (uniforms.algo <= 2) {\n // Assign range of input_data to local_data.\n // Range cannot exceed maxWorkgroupsX * 2\n // Each invocation will populate the workgroup data... (1 invocation for every 2 elements)\n local_data[local_id.x * 2] = input_data[offset + local_id.x * 2];\n local_data[local_id.x * 2 + 1] = input_data[offset + local_id.x * 2 + 1];\n }\n\n //...and wait for each other to finish their own bit of data population.\n workgroupBarrier();\n\n switch uniforms.algo {\n case 1: { // Local Flip\n let idx = get_flip_indices(local_id.x, uniforms.blockHeight);\n local_compare_and_swap(idx.x, idx.y);\n } \n case 2: { // Local Disperse\n let idx = get_disperse_indices(local_id.x, uniforms.blockHeight);\n local_compare_and_swap(idx.x, idx.y);\n } \n case 3: { // Global Flip\n let idx = get_flip_indices(global_id.x, uniforms.blockHeight);\n global_compare_and_swap(idx.x, idx.y);\n }\n case 4: { \n let idx = get_disperse_indices(global_id.x, uniforms.blockHeight);\n global_compare_and_swap(idx.x, idx.y);\n }\n default: { \n \n }\n }\n\n // Ensure that all invocations have swapped their own regions of data\n workgroupBarrier();\n\n if (uniforms.algo <= ALGO_LOCAL_DISPERSE) {\n //Repopulate global data with local data\n output_data[offset + local_id.x * 2] = local_data[local_id.x * 2];\n output_data[offset + local_id.x * 2 + 1] = local_data[local_id.x * 2 + 1];\n }\n\n}`;\n};\n"},134:function(e,n){"use strict";n.Z="@group(0) @binding(0) var mySampler : sampler;\n@group(0) @binding(1) var myTexture : texture_2d;\n\nstruct VertexOutput {\n @builtin(position) Position : vec4,\n @location(0) fragUV : vec2,\n}\n\n@vertex\nfn vert_main(@builtin(vertex_index) VertexIndex : u32) -> VertexOutput {\n const pos = array(\n vec2( 1.0, 1.0),\n vec2( 1.0, -1.0),\n vec2(-1.0, -1.0),\n vec2( 1.0, 1.0),\n vec2(-1.0, -1.0),\n vec2(-1.0, 1.0),\n );\n\n const uv = array(\n vec2(1.0, 0.0),\n vec2(1.0, 1.0),\n vec2(0.0, 1.0),\n vec2(1.0, 0.0),\n vec2(0.0, 1.0),\n vec2(0.0, 0.0),\n );\n\n var output : VertexOutput;\n output.Position = vec4(pos[VertexIndex], 0.0, 1.0);\n output.fragUV = uv[VertexIndex];\n return output;\n}\n\n@fragment\nfn frag_main(@location(0) fragUV : vec2) -> @location(0) vec4 {\n return textureSample(myTexture, mySampler, fragUV);\n}\n"}}]); \ No newline at end of file diff --git a/_next/static/chunks/webpack-10122935cde669a5.js b/_next/static/chunks/webpack-a8f2b4711331d9bc.js similarity index 98% rename from _next/static/chunks/webpack-10122935cde669a5.js rename to _next/static/chunks/webpack-a8f2b4711331d9bc.js index be1b4b51..094ceb5f 100644 --- a/_next/static/chunks/webpack-10122935cde669a5.js +++ b/_next/static/chunks/webpack-a8f2b4711331d9bc.js @@ -1 +1 @@ -!function(){"use strict";var e,t,r,n,a,f,c,o,i,u,d={},b={};function l(e){var t=b[e];if(void 0!==t)return t.exports;var r=b[e]={exports:{}},n=!0;try{d[e].call(r.exports,r,r.exports,l),n=!1}finally{n&&delete b[e]}return r.exports}l.m=d,e=[],l.O=function(t,r,n,a){if(r){a=a||0;for(var f=e.length;f>0&&e[f-1][2]>a;f--)e[f]=e[f-1];e[f]=[r,n,a];return}for(var c=1/0,f=0;f=a&&Object.keys(l.O).every(function(e){return l.O[e](r[i])})?r.splice(i--,1):(o=!1,a0&&e[f-1][2]>a;f--)e[f]=e[f-1];e[f]=[r,n,a];return}for(var c=1/0,f=0;f=a&&Object.keys(l.O).every(function(e){return l.O[e](r[i])})?r.splice(i--,1):(o=!1,aWebGPU Samples \ No newline at end of file +WebGPU Samples \ No newline at end of file diff --git a/samples/A-buffer.html b/samples/A-buffer.html index 76f582c8..e0f60959 100644 --- a/samples/A-buffer.html +++ b/samples/A-buffer.html @@ -10,6 +10,6 @@ } A-Buffer - WebGPU Samples

A-Buffer

See it on Github!

Demonstrates order independent transparency using a per-pixel + limiting memory usage (when required)."/>

\ No newline at end of file + limiting memory usage (when required).

\ No newline at end of file diff --git a/samples/animometer.html b/samples/animometer.html index a25e68e6..0fd7a67b 100644 --- a/samples/animometer.html +++ b/samples/animometer.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Animometer - WebGPU Samples \ No newline at end of file + Animometer - WebGPU Samples \ No newline at end of file diff --git a/samples/bitonicSort.html b/samples/bitonicSort.html index 962459fa..cb19f5f6 100644 --- a/samples/bitonicSort.html +++ b/samples/bitonicSort.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Bitonic Sort - WebGPU Samples

Bitonic Sort

See it on Github!

A naive bitonic sort algorithm executed on the GPU, based on tgfrerer's implementation at poniesandlight.co.uk/reflect/bitonic_merge_sort/. Each dispatch of the bitonic sort shader dispatches a workgroup containing elements/2 invocations. The GUI's Execution Information folder contains information about the sort's current state. The visualizer displays the sort's results as colored cells sorted from brightest to darkest.

\ No newline at end of file + Bitonic Sort - WebGPU Samples

Bitonic Sort

See it on Github!

A naive bitonic sort algorithm executed on the GPU, based on tgfrerer's implementation at poniesandlight.co.uk/reflect/bitonic_merge_sort/. Each dispatch of the bitonic sort shader dispatches a workgroup containing elements/2 invocations. The GUI's Execution Information folder contains information about the sort's current state. The visualizer displays the sort's results as colored cells sorted from brightest to darkest.

\ No newline at end of file diff --git a/samples/cameras.html b/samples/cameras.html index ab1059ea..8cfe59db 100644 --- a/samples/cameras.html +++ b/samples/cameras.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Cameras - WebGPU Samples \ No newline at end of file + Cameras - WebGPU Samples \ No newline at end of file diff --git a/samples/computeBoids.html b/samples/computeBoids.html index 65157250..182e638e 100644 --- a/samples/computeBoids.html +++ b/samples/computeBoids.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Compute Boids - WebGPU Samples \ No newline at end of file + Compute Boids - WebGPU Samples \ No newline at end of file diff --git a/samples/cornell.html b/samples/cornell.html index 815977eb..bd54e1c3 100644 --- a/samples/cornell.html +++ b/samples/cornell.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Cornell box - WebGPU Samples \ No newline at end of file + Cornell box - WebGPU Samples \ No newline at end of file diff --git a/samples/cubemap.html b/samples/cubemap.html index 4f916711..3f006bb8 100644 --- a/samples/cubemap.html +++ b/samples/cubemap.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Cubemap - WebGPU Samples \ No newline at end of file + Cubemap - WebGPU Samples \ No newline at end of file diff --git a/samples/deferredRendering.html b/samples/deferredRendering.html index f080b7f0..89be8b57 100644 --- a/samples/deferredRendering.html +++ b/samples/deferredRendering.html @@ -16,7 +16,7 @@ We also update light position in a compute shader, where further operations like tile/cluster culling could happen. The debug view shows the depth buffer on the left (flipped and scaled a bit to make it more visible), the normal G buffer in the middle, and the albedo G-buffer on the right side of the screen. - "/>

Deferred Rendering

See it on Github!

This example shows how to do deferred rendering with webgpu. + "/>

Deferred Rendering

See it on Github!

This example shows how to do deferred rendering with webgpu. Render geometry info to multiple targets in the gBuffers in the first pass. In this sample we have 2 gBuffers for normals and albedo, along with a depth texture. And then do the lighting in a second pass with per fragment data read from gBuffers so it's independent of scene complexity. @@ -24,4 +24,4 @@ We also update light position in a compute shader, where further operations like tile/cluster culling could happen. The debug view shows the depth buffer on the left (flipped and scaled a bit to make it more visible), the normal G buffer in the middle, and the albedo G-buffer on the right side of the screen. -

\ No newline at end of file +

\ No newline at end of file diff --git a/samples/fractalCube.html b/samples/fractalCube.html index 974ea2d4..a4b13a7a 100644 --- a/samples/fractalCube.html +++ b/samples/fractalCube.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Fractal Cube - WebGPU Samples \ No newline at end of file + Fractal Cube - WebGPU Samples \ No newline at end of file diff --git a/samples/gameOfLife.html b/samples/gameOfLife.html index e300af6f..2c701f0a 100644 --- a/samples/gameOfLife.html +++ b/samples/gameOfLife.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Conway's Game of Life - WebGPU Samples \ No newline at end of file + Conway's Game of Life - WebGPU Samples \ No newline at end of file diff --git a/samples/helloTriangle.html b/samples/helloTriangle.html index bc5670e7..8f1b2ad0 100644 --- a/samples/helloTriangle.html +++ b/samples/helloTriangle.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Hello Triangle - WebGPU Samples \ No newline at end of file + Hello Triangle - WebGPU Samples \ No newline at end of file diff --git a/samples/helloTriangleMSAA.html b/samples/helloTriangleMSAA.html index b3e70b82..1613b9d3 100644 --- a/samples/helloTriangleMSAA.html +++ b/samples/helloTriangleMSAA.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Hello Triangle MSAA - WebGPU Samples \ No newline at end of file + Hello Triangle MSAA - WebGPU Samples \ No newline at end of file diff --git a/samples/imageBlur.html b/samples/imageBlur.html index 73e0d675..b5e76dc3 100644 --- a/samples/imageBlur.html +++ b/samples/imageBlur.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Image Blur - WebGPU Samples \ No newline at end of file + Image Blur - WebGPU Samples \ No newline at end of file diff --git a/samples/instancedCube.html b/samples/instancedCube.html index 763f96f8..2b021c0d 100644 --- a/samples/instancedCube.html +++ b/samples/instancedCube.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Instanced Cube - WebGPU Samples \ No newline at end of file + Instanced Cube - WebGPU Samples \ No newline at end of file diff --git a/samples/normalMap.html b/samples/normalMap.html index c82849a5..19df8c30 100644 --- a/samples/normalMap.html +++ b/samples/normalMap.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Normal Mapping - WebGPU Samples \ No newline at end of file + Normal Mapping - WebGPU Samples \ No newline at end of file diff --git a/samples/particles.html b/samples/particles.html index 4b347117..31310154 100644 --- a/samples/particles.html +++ b/samples/particles.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Particles - WebGPU Samples \ No newline at end of file + Particles - WebGPU Samples \ No newline at end of file diff --git a/samples/renderBundles.html b/samples/renderBundles.html index e4f936b2..134a8c0c 100644 --- a/samples/renderBundles.html +++ b/samples/renderBundles.html @@ -11,7 +11,7 @@ Render Bundles - WebGPU Samples

Render Bundles

See it on Github!

This example shows how to use render bundles. It renders a large number of + of instancing to reduce draw overhead.)"/>

Render Bundles

See it on Github!

This example shows how to use render bundles. It renders a large number of meshes individually as a proxy for a more complex scene in order to demonstrate the reduction in JavaScript time spent to issue render commands. (Typically a scene like this would make use - of instancing to reduce draw overhead.)

\ No newline at end of file + of instancing to reduce draw overhead.)

\ No newline at end of file diff --git a/samples/resizeCanvas.html b/samples/resizeCanvas.html index 966622f9..9045e2ae 100644 --- a/samples/resizeCanvas.html +++ b/samples/resizeCanvas.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Resize Canvas - WebGPU Samples \ No newline at end of file + Resize Canvas - WebGPU Samples \ No newline at end of file diff --git a/samples/reversedZ.html b/samples/reversedZ.html index b2c5a0dd..26aa15ae 100644 --- a/samples/reversedZ.html +++ b/samples/reversedZ.html @@ -17,7 +17,7 @@ Related reading: https://developer.nvidia.com/content/depth-precision-visualized https://web.archive.org/web/20220724174000/https://thxforthefish.com/posts/reverse_z/ - "/>

Reversed Z

See it on Github!

This example shows the use of reversed z technique for better utilization of depth buffer precision. + "/>

Reversed Z

See it on Github!

This example shows the use of reversed z technique for better utilization of depth buffer precision. The left column uses regular method, while the right one uses reversed z technique. Both are using depth32float as their depth buffer format. A set of red and green planes are positioned very close to each other. Higher sets are placed further from camera (and are scaled for better visual purpose). @@ -26,4 +26,4 @@ Related reading: https://developer.nvidia.com/content/depth-precision-visualized https://web.archive.org/web/20220724174000/https://thxforthefish.com/posts/reverse_z/ -

\ No newline at end of file +

\ No newline at end of file diff --git a/samples/rotatingCube.html b/samples/rotatingCube.html index 35b36334..130fe3ac 100644 --- a/samples/rotatingCube.html +++ b/samples/rotatingCube.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Rotating Cube - WebGPU Samples \ No newline at end of file + Rotating Cube - WebGPU Samples \ No newline at end of file diff --git a/samples/samplerParameters.html b/samples/samplerParameters.html index f84a093a..2810bb1d 100644 --- a/samples/samplerParameters.html +++ b/samples/samplerParameters.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Sampler Parameters - WebGPU Samples

Sampler Parameters

See it on Github!

Visualizes what all the sampler parameters do. Shows a textured plane at various scales (rotated, head-on, in perspective, and in vanishing perspective). The bottom-right view shows the raw contents of the 4 mipmap levels of the test texture (16x16, 8x8, 4x4, and 2x2).

\ No newline at end of file + Sampler Parameters - WebGPU Samples

Sampler Parameters

See it on Github!

Visualizes what all the sampler parameters do. Shows a textured plane at various scales (rotated, head-on, in perspective, and in vanishing perspective). The bottom-right view shows the raw contents of the 4 mipmap levels of the test texture (16x16, 8x8, 4x4, and 2x2).

\ No newline at end of file diff --git a/samples/shadowMapping.html b/samples/shadowMapping.html index f463a77f..345d07cb 100644 --- a/samples/shadowMapping.html +++ b/samples/shadowMapping.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Shadow Mapping - WebGPU Samples \ No newline at end of file + Shadow Mapping - WebGPU Samples \ No newline at end of file diff --git a/samples/texturedCube.html b/samples/texturedCube.html index 46a67e16..66dbbcfe 100644 --- a/samples/texturedCube.html +++ b/samples/texturedCube.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Textured Cube - WebGPU Samples \ No newline at end of file + Textured Cube - WebGPU Samples \ No newline at end of file diff --git a/samples/twoCubes.html b/samples/twoCubes.html index 8fbb624a..98caffea 100644 --- a/samples/twoCubes.html +++ b/samples/twoCubes.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Two Cubes - WebGPU Samples \ No newline at end of file + Two Cubes - WebGPU Samples \ No newline at end of file diff --git a/samples/videoUploading.html b/samples/videoUploading.html index ad428e78..5f742a0a 100644 --- a/samples/videoUploading.html +++ b/samples/videoUploading.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Video Uploading - WebGPU Samples \ No newline at end of file + Video Uploading - WebGPU Samples \ No newline at end of file diff --git a/samples/videoUploadingWebCodecs.html b/samples/videoUploadingWebCodecs.html index 667cd5ec..d1127427 100644 --- a/samples/videoUploadingWebCodecs.html +++ b/samples/videoUploadingWebCodecs.html @@ -8,4 +8,4 @@ height: auto !important; overflow: visible !important; } - Video Uploading with WebCodecs - WebGPU Samples \ No newline at end of file + Video Uploading with WebCodecs - WebGPU Samples \ No newline at end of file diff --git a/samples/worker.html b/samples/worker.html index ef84e6b8..0b892e57 100644 --- a/samples/worker.html +++ b/samples/worker.html @@ -10,6 +10,6 @@ } WebGPU in a Worker - WebGPU Samples

WebGPU in a Worker

See it on Github!

This example shows one method of using WebGPU in a web worker and presenting to + which is then transferred to the worker where all the WebGPU calls are made."/>

\ No newline at end of file + which is then transferred to the worker where all the WebGPU calls are made.

\ No newline at end of file