www.xbdev.net
xbdev - software development
Sunday April 20, 2025
Home | Contact | Support | WebGPU Graphics and Compute ...
     
 

WebGPU/WGSL Tutorials and Articles

Graphics and Compute ...

 


Userscripts are a little secret that lets you run scripts on specific web pages to do your bidding and make your life easier - ...
Userscripts are a little secret that lets you run scripts on specific web pages to do your bidding and make your life easier - fun images are from from 'Rick and Morty' - Userscripts turn you into a Rick (a super genius).


Upgrading Old WebGPU and WGSL Scripts (Syntax Fixes)



WebGPU is new (very new) and as you'd would expect it has gone through a few updates to the language since it was released to the public - nothing major - just some tweaks and refinements to the syntax (both the API and the WGSL shaders).

As I've written hundreds of scripts - I wanted a quick way to upgrade any outdated versions - without having to manually go through them and fix the lines. The fixes aren't major - but it's time consuming if you've got lots and lots of scripts.

So this article gives a userscript with a bit of regular expression search/replace - to fix any WebGPU scripts on a page that are located in a textarea block.

The script isn't perfect - but it works with most of my examples - and you can easily take it further if you want. I didn't want to write a full language tokenizer/parser - just look for common language changes (e.g.
[[blocks]]
is no longer used). Search for these old styles and upgrade them.


Key points:
• Userscript uses the TamperMonkey browser extension
• Hardcoded regular expressions
• Timeout startup (waits 2 seconds before launching on new pages)
• Adds fixed button to the page (top left)
• Only replace scripts in 'textarea' (does not give any warnings or options)


Complete Code


// ==UserScript==
// @name         WebGPU and WGSL Upgrader Fixer Userscript
// @namespace    http://tampermonkey.net/
// @version      2024-06-24
// @description  WebGPU and WGSL Syntax and Function Upgrade Fixer Early Releases
// @author       You
// @match        https://*/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=xbdev.net
// @grant        none
// ==/UserScript==

function updatewebgpuscript(txt)
{
    
let newpresformat2 = `
//const presentationFormat = context.getPreferredFormat(adapter); - no longer supported
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
`;

    
let newpresformat = `navigator.gpu.getPreferredCanvasFormat(); // context.getPreferredFormat(adapter); - no longer supported`;

    
txt txt.replaceAll(/context.getPreferredFormat\(adapter\);/gnewpresformat);

    
txt txt.replaceAll(/window.devicePixelRatio/g'1'); // window.devicePixelRatio => 1

    
txt txt.replaceAll(/stencilLoadValue/g'// stencilLoadValue');
    
txt txt.replaceAll(/stencilStoreOp/g,   '// stencilStoreOp');

    
// loadValue -> clearValue
    
txt txt.replaceAll(/loadValue/g'loadOp:"clear", clearValue');
    
// endPass() -> end()
    
txt txt.replaceAll(/endPass\(\)/g'end()');
    
// stage
    
txt txt.replaceAll(/\[\[stage\(vertex\)\]\]/g'@stage(vertex)');
    
txt txt.replaceAll(/\[\[stage\(fragment\)\]\]/g'@stage(fragment)');
    
txt txt.replaceAll(/\[\[stage\(compute\)\]\]/g'@stage(compute)');
    
// builtin - [[builtin(position)]] changed to @builtin(position)
    
txt txt.replaceAll(/\[\[builtin\(([a-zA-Z_]*)\)\]\]/g'@builtin($1)');
    
// [[group(0), binding(0)]] var mySampler: sampler; -> @group(0) @binding(0) var mySampler: sampler;
    
txt txt.replaceAll(/\[\[group\((\w)\), binding\((\w)\)\]\]/g'@group($1) @binding($2)');
    
txt txt.replaceAll(/\[\[binding\((\w)\), group\((\w)\)\]\]/g'@binding($1) @group($2)');
    
// [[location(0)]] -> @location(0)
    
txt txt.replaceAll(/\[\[location\((\w)\)\]\]/g'@location($1)');
    
// smoothstep
    
txt txt.replaceAll(/fn smoothstep/g'fn mysmoothstep');
    
// depthLoadValue -> depthLoadOp and depthClearValue
    
txt txt.replaceAll(/depthLoadValue/g'depthLoadOp:"clear", depthClearValue');
    
//
    
txt txt.replaceAll(/(context.configure\(\{ device device,)/g'$1 compositingAlphaMode: "opaque",');
    
//
    // [[stage(compute), workgroup_size(8, 8)]]
    
txt txt.replaceAll(/\[\[stage\(([a-zA-Z_]*)\), workgroup_size\(([a-zA-Z_0-9, ]*)\)\]\]/g'@stage($1) @workgroup_size($2)');
    
// [[stride(16)]] -> ''
    
txt txt.replaceAll(/\[\[stride\([0-9]*\)\]\]/g'');
    
// @location(1) iIdx: u32 -> @location(1) @interpolate(flat) iIdx: u32
    
txt txt.replaceAll(/(@location\([0-9]*\)[ ]*?)([a-zA-Z_0-9]*[ ]*?:[ ]*?u32)/g'$1 @interpolate(flat) $2');


    
// remove [[block]]
    
txt txt.replaceAll(/\[\[block\]\]/g'');


    
// remove struct block listing (save them for later)
    // semicolons -> commas
    
const regexp = /struct [a-zA-Z0-9_]* \{((.|[\r\n])*?)\}/g;
    const array  = [...
txt.matchAll(regexp)];
    
txt txt.replace(/struct [a-zA-Z0-9_]* \{((.|[\r\n])*?)\}/g'{STRUCT}' );

    
// Restore struct blocks with added wrapping
    
for (let i=0i<array.lengthi++)
    {   
let arr = array[i][0].replaceAll(';'',');
        
txt txt.replace(/(\{STRUCT\})/, arr );
    }
// end for i



    
txt txt.replaceAll(/@stage\(vertex\)/g,   '@vertex');
    
txt txt.replaceAll(/@stage\(fragment\)/g'@fragment');
    
txt txt.replaceAll(/@stage\(compute\)/g,  '@compute');

    
txt txt.replaceAll(/\.dispatch\(/g,  '.dispatchWorkgroups(');

    return 
txt;
}

function 
setupWebGPUFix()
{
//(function() {
    
'use strict';

    
console.log('hell0');
    
// Function to replace text in all textareas
    
function replaceText() {
        
console.log('replaceText called');
        
// Find all textarea elements
        
const textareas document.querySelectorAll('textarea');
        if (
textareas.length 0) {
            
textareas.forEach(textarea => {
                
console.log('text area...');
                
// Replace occurrences of 'catslikemilk' with 'nomilk'
                //textarea.value = textarea.value.replace(/catslikemilk/g, 'nomilk');

                
textarea.value updatewebgpuscripttextarea.value );

                var 
event2 = new Event('input', { bubblestrue });
                
textarea.dispatchEvent(event2);
                
textarea.parentNode.dispatchEvent(event2);

            });
        } else {
            
console.log('No textareas found');
        }
    }

    
// Create a button
    
const button document.createElement('button');
    
button.textContent 'Fix & Replace WebGPU WGSL Text';
    
button.style.position 'fixed';
    
button.style.top '10px';
    
button.style.left '10px';
    
button.style.zIndex 10000;

    
// Add click event to button
    
button.addEventListener('click'replaceText);

    
// Append button to body
    
document.body.appendChild(button);
//})();
}

setTimeout(setupWebGPUFix2000);


Things to Try


The example shows a quick and dirty prototype to make my life easier - and can be used on examples you stumble across on the web if you want to do a quick update. Few ideas if you want to develop the prototype further:

• Extract the script and put into a popup dialog - highlight the lines that are going to be changed
• Include an 'option' dialog to select which language features to upgrade
• Extract the script, upgrade it, and put it into a new textarea (does not replace the original version)
• Split the text into API (JS) and the WGSL components - run the JS through Lint checker, and the WGSL through the WebGPU API compiler




Resources and Links


• Regular Expressions [LINK]
• WebGPU Lab [LINK]
• Usersripts Tutorial/Example [LINK]












101 WebGPU Programming Projects. WebGPU Development Pixels - coding fragment shaders from post processing to ray tracing! WebGPU by Example: Fractals, Image Effects, Ray-Tracing, Procedural Geometry, 2D/3D, Particles, Simulations WebGPU Games WGSL 2d 3d interactive web-based fun learning WebGPU Compute WebGPU API - Owners WebGPU Development Cookbook - coding recipes for all your webgpu needs! WebGPU & WGSL Essentials: A Hands-On Approach to Interactive Graphics, Games, 2D Interfaces, 3D Meshes, Animation, Security and Production Kenwright graphics and animations using the webgpu api 12 week course kenwright learn webgpu api kenwright programming compute and graphics applications with html5 and webgpu api kenwright real-time 3d graphics with webgpu kenwright webgpu for dummies kenwright webgpu wgsl compute graphics all in one kenwright webgpu api develompent a quick start guide kenwright webgpu by example 2022 kenwright webgpu gems kenwright webgpu interactive compute and graphics visualization cookbook kenwright wgsl webgpu shading language cookbook kenwright WebGPU Shader Language Development: Vertex, Fragment, Compute Shaders for Programmers Kenwright WGSL Fundamentals book kenwright WebGPU Data Visualization Cookbook kenwright Special Effects Programming with WebGPU kenwright WebGPU Programming Guide: Interactive Graphics and Compute Programming with WebGPU & WGSL kenwright Ray-Tracing with WebGPU kenwright



 
Advert (Support Website)

 
 Visitor:
Copyright (c) 2002-2025 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.