A simple, template literals-based preprocessor for WGSL shaders
npm install wgsl-preprocessor#if
#elif
#else
#endif
npm install wgsl-preprocessor
js
import { wgsl } from './node-modules/wgsl-preprocessor/wgsl-preprocessor.js';
`
Or use without an install step by loading it from a CDN like jsdelivr:
`js
import { wgsl } from 'https://cdn.jsdelivr.net/npm/wgsl-preprocessor@1.0/wgsl-preprocessor.js';
`
Or, you know, just copy and paste the contents of wgsl-preprocessor.js where ever is convenient for you. It's less
than a 100 lines of code, we really don't need to overthink it!
Usage
Import the wgsl symbol from wherever you've installed wgsl-preprocessor.js and use it as a tag for a template
literal string:
`js
import { wgsl } from 'https://cdn.jsdelivr.net/npm/wgsl-preprocessor@1.0/wgsl-preprocessor.js';
function getDebugShader(sRGB = false) {
return wgsl
;
}
When using #if or #elif the preprocessor symbol _must_ be followed by a substitution expression that will be
evaluated as a boolean.
`js
wgsl
;
`
If the result of the expression is truthy then the string
contents between the opening and closing tags will be returned as part of the string, otherwise it will be omitted.
`js
const x = 1;
const source = wgsl
;
// source will be:
// let a = 1
//
//
// let c = 0;
//
// let d = 1;
`
#if/#elif statements may be nested any number of levels deep:
`js
wgsl
;
`
And any number of #elifs may be chained:
`js
wgsl
;
`
Why no
#define?
If you need something to approximate a #define statement from other preprocessors, simply use JavaScript's built-in substitution expressions! You don't even need the wgsl tag!
`js
const ambientFactor = 1.0;
const sampleCount = 2;
const source =
;
`
But of course, they play nicely with the wgsl tag too:
`js
const useApproximateSRGB = true;
const approxGamma = 2.2;
export const colorConversions = wgsl
;
``