MaterialXLab API  0.0.1
APIs For MaterialXLab Libraries
Loading...
Searching...
No Matches
glsl_to_wgsl.js
Go to the documentation of this file.
1// Install dependencies first:
2// npm install @webgpu/glslang twgsl
3
4import glslangModule from "@webgpu/glslang";
5import { compile } from "twgsl";
6
7async function convertGLSLtoWGSL(glslCode, shaderStage = "vertex") {
8 // Load glslang
9 const glslang = await glslangModule();
10
11 // Map shader stage string to glslang constant
12 const stageMap = {
13 vertex: "vertex",
14 fragment: "fragment",
15 compute: "compute"
16 };
17
18 if (!stageMap[shaderStage]) {
19 throw new Error(`Invalid shader stage: ${shaderStage}`);
20 }
21
22 // Step 1: GLSL → SPIR-V
23 const spirv = glslang.compileGLSL(glslCode, stageMap[shaderStage]);
24
25 // Step 2: SPIR-V → WGSL
26 const wgsl = compile(spirv);
27
28 return wgsl;
29}
30
31// Example usage
32const vertexShaderGLSL = `#version 450
33layout(location = 0) in vec3 position;
34void main() {
35 gl_Position = vec4(position, 1.0);
36}`;
37
38const fragmentShaderGLSL = `#version 450
39layout(location = 0) out vec4 outColor;
40void main() {
41 outColor = vec4(1.0, 0.0, 0.0, 1.0); // red
42}`;
43
44(async () => {
45 const vertexWGSL = await convertGLSLtoWGSL(vertexShaderGLSL, "vertex");
46 const fragmentWGSL = await convertGLSLtoWGSL(fragmentShaderGLSL, "fragment");
47
48 console.log("=== Vertex Shader WGSL ===");
49 console.log(vertexWGSL);
50
51 console.log("\n=== Fragment Shader WGSL ===");
52 console.log(fragmentWGSL);
53})();
function async convertGLSLtoWGSL(glslCode, shaderStage="vertex")
const vertexShaderGLSL
const fragmentShaderGLSL
void main()
import glslangModule from webgpu glslang