From 3376c8a22e45b15ae59b7efd95e45df5eaf1fc83 Mon Sep 17 00:00:00 2001
From: Noelle Calliope <1581674+mekanoe@users.noreply.github.com>
Date: Sun, 8 Oct 2023 00:19:24 -0400
Subject: [PATCH] add #pragma branching
---
html/002-webgpu-instead/main.js | 2 +-
src/002-webgpu-instead/main.ts | 3 ++-
src/renderer/shader.ts | 33 ++++++++++++++++++++++++++-------
3 files changed, 29 insertions(+), 9 deletions(-)
diff --git a/html/002-webgpu-instead/main.js b/html/002-webgpu-instead/main.js
index 064463d..4c1e958 100644
--- a/html/002-webgpu-instead/main.js
+++ b/html/002-webgpu-instead/main.js
@@ -1 +1 @@
-import{a as o,b as k} from"../chunk-c8239659df5e5cce.js";class C{v;canvas;_adapter;_device;_context;telemetry;registry={onBeforeUpdate:[],onAfterUpdate:[],onUpdate:[],onStart:[]};constructor(v={}){this.config=v;this.config={fov:45,...v},this.canvas=document.querySelector("canvas"),this.canvas.width=window.innerWidth,this.canvas.height=window.innerHeight,this.telemetry=new k(this),this.init().catch((S)=>{const x=document.querySelector("main");if(x)x.innerHTML="
your browser didn't let me set up webgpu. firefox nightly or enable dom.webgpu.enable
.
";throw new Error("Unable to initialize WebGPU. Your browser or machine may not support it.",S)})}async init(){if(!navigator.gpu)throw new Error("WebGPU not supported");if(this._adapter=await navigator.gpu.requestAdapter(),!this._adapter)throw new Error("No GPU adapter found");if(this._device=await this.adapter.requestDevice(),!this._device)throw new Error("No GPU device found");this._context=this.canvas.getContext("webgpu"),this.context.configure({device:this.device,format:"bgra8unorm",alphaMode:"premultiplied",...this.config.context})}get context(){if(!this._context)throw new Error("WebGPU context not initialized");return this._context}get adapter(){if(!this._adapter)throw new Error("WebGPU adapter not initialized");return this._adapter}get device(){if(!this._device)throw new Error("WebGPU device not initialized");return this._device}onBeforeUpdate(v){this.registry.onBeforeUpdate.push(v)}onAfterUpdate(v){this.registry.onAfterUpdate.push(v)}onUpdate(v){this.registry.onUpdate.push(v)}onStart(v){this.registry.onStart.push(v)}doUpdate(v){this.registry.onBeforeUpdate.forEach((S)=>S(v,this)),this.registry.onUpdate.forEach((S)=>S(v,this)),this.registry.onAfterUpdate.forEach((S)=>S(v,this))}doStart(v=0){this.registry.onStart.forEach((S)=>S(this,v))}async oneShot(v=0){this.doStart(v),this.doUpdate(v)}start(){this.doStart();const v=(S)=>{this.doUpdate(S),requestAnimationFrame(v)};requestAnimationFrame(v)}}class _ extends o{v;S;depthTexture;uniformBuffer;texture;sampler;uniformBindGroup;renderPassDescriptor;constructor(v,S){super(v);this.app=v;this.mesh=S}onStart(){console.log("hello from meshrenderer!"),console.log(`i've got a ${this.mesh.constructor.name}`)}onUpdate(v){}}class c{v;constructor(v){this.config=v}buffer(v){const S=v.device.createBuffer({size:this.config.mesh.byteLength,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});return new Float32Array(S.getMappedRange()).set(this.config.mesh),S.unmap(),S}pipeline(v,S,x){const j=S.module(v);return v.device.createRenderPipeline({layout:"auto",vertex:{module:j,entryPoint:"main",buffers:[{arrayStride:4,attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:2,offset:this.config.positionSize,format:"float32x4"},{shaderLocation:1,offset:this.config.positionSize+this.config.colorSize,format:"float32x4"}]}]},fragment:{module:j,entryPoint:"main",targets:[{format:"rgba8unorm"}]},primitive:{topology:"triangle-list",cullMode:x.cullMode??"back"},depthStencil:x.stencil&&{depthWriteEnabled:!0,depthCompare:"less",format:"depth24plus"}})}}var E=new Float32Array([-1,-1,0,1,1,1,1,1,0,0,1,-1,0,1,1,1,1,1,1,0,-1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1]),q=new c({mesh:E,positionSize:16,colorSize:16,uvSize:8});var z="fn rgb2hsv(vec3f c)->vec3f{vec4f K=vec4f(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4f p=mix(vec4f(c.bg,K.wz),vec4f(c.gb,K.xy),step(c.b,c.g));vec4f q=mix(vec4f(p.xyw,c.r),vec4f(c.r,p.yzx),step(p.x,c.r));f32 d=q.x-min(q.w,q.y);f32 e=1.0e-10;return vec3f(abs(q.z+(q.w-q.y)/(6.0*d+e)),d/(q.x+e),q.x);}fn hsv2rgb(vec3f c)->vec3f{vec4f K=vec4f(1.0,2.0/3.0,1.0/3.0,3.0);vec3f p=abs(fract(c.xxx+K.xyz)*6.0-K.www);return c.z*mix(K.xxx,clamp(p-K.xxx,0.0,1.0),c.y);}struct Uniforms{modelViewProjectionMatrix:mat4x4,time:f32,}@group(0)@binding(0)var uniforms:Uniforms;struct v2f{@builtin(position)position:vec4f,@location(0)color:vec4f,@location(1)uv:vec2f,}@vertex fn main(@builtin(position)position:vec4f,@location(0)color:vec4f,@location(1)uv:vec2f,)->v2f{return v2f(uniforms.modelViewProjectionMatrix*position,color,uv);}@fragment fn main(@location(0)uv:vec2f,)->@location(0)vec4f{f32 z=sin(uniforms.time)*0.001*0.5+0.5;vec3f hsv=vec3f(uv.x,uv.y,z);hsv.x+=uniforms.time*0.0001;hsv.y=1.0;hsv.z=1.0;vec3f rgb=hsv2rgb(hsv);return saturate(vec4f(rgb,1.0));}";var D=new C({fov:20}),$=new _(D,q);console.log({rainbowPlane:z});D.start();
+import{a as D,b as z} from"../chunk-c8239659df5e5cce.js";class _{v;canvas;_adapter;_device;_context;telemetry;registry={onBeforeUpdate:[],onAfterUpdate:[],onUpdate:[],onStart:[]};constructor(v={}){this.config=v;this.config={fov:45,...v},this.canvas=document.querySelector("canvas"),this.canvas.width=window.innerWidth,this.canvas.height=window.innerHeight,this.telemetry=new z(this),this.init().catch((x)=>{const C=document.querySelector("main");if(C)C.innerHTML="your browser didn't let me set up webgpu. firefox nightly or enable dom.webgpu.enable
.
";throw new Error("Unable to initialize WebGPU. Your browser or machine may not support it.",x)})}async init(){if(!navigator.gpu)throw new Error("WebGPU not supported");if(this._adapter=await navigator.gpu.requestAdapter(),!this._adapter)throw new Error("No GPU adapter found");if(this._device=await this.adapter.requestDevice(),!this._device)throw new Error("No GPU device found");this._context=this.canvas.getContext("webgpu"),this.context.configure({device:this.device,format:"bgra8unorm",alphaMode:"premultiplied",...this.config.context})}get context(){if(!this._context)throw new Error("WebGPU context not initialized");return this._context}get adapter(){if(!this._adapter)throw new Error("WebGPU adapter not initialized");return this._adapter}get device(){if(!this._device)throw new Error("WebGPU device not initialized");return this._device}onBeforeUpdate(v){this.registry.onBeforeUpdate.push(v)}onAfterUpdate(v){this.registry.onAfterUpdate.push(v)}onUpdate(v){this.registry.onUpdate.push(v)}onStart(v){this.registry.onStart.push(v)}doUpdate(v){this.registry.onBeforeUpdate.forEach((x)=>x(v,this)),this.registry.onUpdate.forEach((x)=>x(v,this)),this.registry.onAfterUpdate.forEach((x)=>x(v,this))}doStart(v=0){this.registry.onStart.forEach((x)=>x(this,v))}async oneShot(v=0){this.doStart(v),this.doUpdate(v)}start(){this.doStart();const v=(x)=>{this.doUpdate(x),requestAnimationFrame(v)};requestAnimationFrame(v)}}class j extends D{v;x;depthTexture;uniformBuffer;texture;sampler;uniformBindGroup;renderPassDescriptor;constructor(v,x){super(v);this.app=v;this.mesh=x}onStart(){console.log("hello from meshrenderer!"),console.log(`i've got a ${this.mesh.constructor.name}`)}onUpdate(v){}}class k{v;constructor(v){this.config=v}buffer(v){const x=v.device.createBuffer({size:this.config.mesh.byteLength,usage:GPUBufferUsage.VERTEX,mappedAtCreation:!0});return new Float32Array(x.getMappedRange()).set(this.config.mesh),x.unmap(),x}pipeline(v,x,C){const q=x.module(v);return v.device.createRenderPipeline({layout:"auto",vertex:{module:q,entryPoint:"main",buffers:[{arrayStride:4,attributes:[{shaderLocation:0,offset:0,format:"float32x4"},{shaderLocation:2,offset:this.config.positionSize,format:"float32x4"},{shaderLocation:1,offset:this.config.positionSize+this.config.colorSize,format:"float32x4"}]}]},fragment:{module:q,entryPoint:"main",targets:[{format:"rgba8unorm"}]},primitive:{topology:"triangle-list",cullMode:C.cullMode??"back"},depthStencil:C.stencil&&{depthWriteEnabled:!0,depthCompare:"less",format:"depth24plus"}})}}var J=new Float32Array([-1,-1,0,1,1,1,1,1,0,0,1,-1,0,1,1,1,1,1,1,0,-1,1,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1]),E=new k({mesh:J,positionSize:16,colorSize:16,uvSize:8});var F="fn rgb2hsv(vec3f c)->vec3f{vec4f K=vec4f(0.0,-1.0/3.0,2.0/3.0,-1.0);vec4f p=mix(vec4f(c.bg,K.wz),vec4f(c.gb,K.xy),step(c.b,c.g));vec4f q=mix(vec4f(p.xyw,c.r),vec4f(c.r,p.yzx),step(p.x,c.r));f32 d=q.x-min(q.w,q.y);f32 e=1.0e-10;return vec3f(abs(q.z+(q.w-q.y)/(6.0*d+e)),d/(q.x+e),q.x);}fn hsv2rgb(vec3f c)->vec3f{vec4f K=vec4f(1.0,2.0/3.0,1.0/3.0,3.0);vec3f p=abs(fract(c.xxx+K.xyz)*6.0-K.www);return c.z*mix(K.xxx,clamp(p-K.xxx,0.0,1.0),c.y);}struct Uniforms{modelViewProjectionMatrix:mat4x4,time:f32,}@group(0)@binding(0)var uniforms:Uniforms;struct v2f{@builtin(position)position:vec4f,@location(0)color:vec4f,@location(1)uv:vec2f,}@vertex fn main(@builtin(position)position:vec4f,@location(0)color:vec4f,@location(1)uv:vec2f,)->v2f{return v2f(uniforms.modelViewProjectionMatrix*position,color,uv);}@fragment fn main(@location(0)uv:vec2f,)->@location(0)vec4f{f32 z=sin(uniforms.time)*0.001*0.5+0.5;vec3f hsv=vec3f(uv.x,uv.y,z);hsv.x+=uniforms.time*0.0001;hsv.y=1.0;hsv.z=1.0;vec3f rgb=hsv2rgb(hsv);return saturate(vec4f(rgb,1.0));}";var H="struct Uniforms{modelViewProjectionMatrix:mat4x4,time:f32,}@group(0)@binding(0)var uniforms:Uniforms;struct v2f{@builtin(position)position:vec4f,@location(0)uv:vec2f,}@vertex fn vertex_main(@builtin(position)position:vec4f,@location(0)uv:vec2f,)->v2f{return v2f(uniforms.modelViewProjectionMatrix*position,uv);}@fragment fn fragment_main(@location(0)uv:vec2f,)->vec4f{return vec4f(1.0,0.0,1.0,1.0);}";var N=new RegExp("#pragma ([a-z]+) ([a-zA-Z_0-9]+)","g");class P{_module=null;vertexMain="main";fragmentMain="main";code;constructor(...v){this.code=v.join("\n");const x=this.code.matchAll(N);for(let C of x||[])switch(C[1]){case"fragment":this.fragmentMain=C[2];break;case"vertex":this.vertexMain=C[2];break}}module(v){return this._module=this._module||(this._module=v.device.createShaderModule({code:this.code}))}}var S=new P(H);var I=new _({fov:20}),s=new j(I,E),u=new P(F);I.start();
diff --git a/src/002-webgpu-instead/main.ts b/src/002-webgpu-instead/main.ts
index 02e34f4..cd0e8d0 100644
--- a/src/002-webgpu-instead/main.ts
+++ b/src/002-webgpu-instead/main.ts
@@ -2,9 +2,10 @@ import { WebGPUApp } from "../renderer/webgpu";
import { MeshRenderer } from "../renderer/mesh-renderer";
import plane from "../meshes/plane";
import rainbowPlane from "./rainbow-plane.wgsl";
+import { Shader } from "../renderer/shader";
const app = new WebGPUApp({ fov: 20 });
const renderer = new MeshRenderer(app, plane);
-console.log({ rainbowPlane });
+const shader = new Shader(rainbowPlane);
app.start();
diff --git a/src/renderer/shader.ts b/src/renderer/shader.ts
index 1dc425d..7c0e458 100644
--- a/src/renderer/shader.ts
+++ b/src/renderer/shader.ts
@@ -1,19 +1,38 @@
import { WebGPUApp } from "./webgpu";
import oopsWsgl from "./oops.wgsl";
+const pragmaRegexp = new RegExp("#pragma ([a-z]+) ([a-zA-Z_0-9]+)", "g");
+
export class Shader {
private _module: GPUShaderModule | null = null;
- constructor(private code: string[]) {}
+ public vertexMain: string = "main";
+ public fragmentMain: string = "main";
+ public code: string;
+
+ constructor(...code: string[]) {
+ this.code = code.join("\n");
+
+ // pragma preprocessing
+ const matches = this.code.matchAll(pragmaRegexp);
+ for (const match of matches || []) {
+ switch (match[1]) {
+ case "fragment":
+ this.fragmentMain = match[2];
+ break;
+ case "vertex":
+ this.vertexMain = match[2];
+ break;
+ }
+ }
+ }
module(app: WebGPUApp) {
- this._module =
+ return (this._module =
this._module ||
(this._module = app.device.createShaderModule({
- code: this.code.join("\n"),
- }));
-
- return this._module;
+ code: this.code,
+ })));
}
}
-export const Oops = new Shader([oopsWsgl]);
+export const Oops = new Shader(oopsWsgl);