typescript
/**
* Shared Mobile/Desktop Rendering Pipeline using WebGPU
*
* Design Goals:
* - Shader Portability: WGSL shaders with #ifdefs for feature variants (e.g., mobile vs desktop limits).
* - Resource Lifetime: RAII-inspired disposal with weak refs and generational arenas for buffers/textures.
* - Fallback Heuristics: Adaptive quality levels based on device limits (anisotropy, storage textures, etc.).
* - Performance Telemetry: GPU timestamps, FPS counter, histogram logging, optional upload to analytics.
* - Feature Gating: Runtime detection via `GPUAdapter.limits` and `GPUDevice.features`.
*
* Quality Levels (fallback cascade):
* 0: Mobile Low (no MSAA, 8-bit textures, low poly budget)
* 1: Mobile High / Desktop Low (4x MSAA, BC/R11G11B10 textures)
* 2: Desktop High (16x anisotropy, storage buffers, compute passes)
*
* Usage:
* const pipeline = new RenderingPipeline(canvas);
* pipeline.init().then(() => pipeline.startRenderLoop());
*/
class RenderingPipeline {
private adapter: GPUAdapter | null = null;
private device: GPUDevice | null = null;
private context: GPUCanvasContext | null = null;
private qualityLevel: number = 1; // Starts at medium, adapts down
private featureFlags: Record<string, boolean> = {};
private telemetry: TelemetryCollector = new TelemetryCollector();
// Resource managers
private shaderManager: ShaderManager = new ShaderManager();
private resourceManager: ResourceManager = new ResourceManager();
// Render state
private renderPassDescriptor: GPURenderPassDescriptor;
private pipelineCache: Map<string, GPUComputePipeline | GPURenderPipeline> = new Map();
constructor(private canvas: HTMLCanvasElement) {}
async init(): Promise<void> {
const adapter = await navigator.gpu.requestAdapter({
powerPreference: 'high-performance', // Desktop bias, fallback to default on mobile
});
if (!adapter) throw new Error('No GPU adapter');
this.adapter = adapter;
this.device = await adapter.requestDevice({
requiredFeatures: [], // Start minimal, add gated features later
requiredLimits: { maxBindGroups: 4 }, // Conservative base
});
this.context = this.canvas.getContext('webgpu')!;
this.context.configure({
device: this.device,
format: navigator.gpu.getPreferredCanvasFormat(),
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
alphaMode: 'premultiplied', // Mobile-friendly
});
await this.detectFeaturesAndFallbacks();
await this.shaderManager.init(this.device);
this.resourceManager.init(this.device);
// Precompile key pipelines
await this.compilePipelines();
}
private async detectFeaturesAndFallbacks(): Promise<void> {
const limits = this.adapter!.limits;
const features = this.device!.features;
// Feature Gating
this.featureFlags = {
anisotropy: limits.maxTextureDimension2D >= 8192 && 'texture-anisotropic-filtering' in features,
storageTextures: 'texture-compression-bc' in features || 'texture-compression-etc2' in features,
computeShaders: limits.maxComputeWorkgroupStorageSize > 0,
msaa: limits.maxColorAttachmentBinding > 1 && limits.sampleCount > 4,
// Mobile heuristics: low limits -> mobile/low quality
isMobileLow: limits.maxTextureDimension2D <= 4096 || limits.maxComputeInvocationsPerWorkgroup <= 128,
};
// Fallback Heuristics: Cascade quality
if (this.featureFlags.isMobileLow) {
this.qualityLevel = 0;
} else if (!this.featureFlags.anisotropy && !this.featureFlags.storageTextures) {
this.qualityLevel = 1;
} else {
this.qualityLevel = 2;
}
console.log(`Detected Quality: ${['Low', 'Medium', 'High'][this.qualityLevel]}, Flags:`, this.featureFlags);
}
private async compilePipelines(): Promise<void> {
const qualitySuffix = ['_low', '_med', '_high'][this.qualityLevel];
const shaders = await this.shaderManager.loadShaderSet(`main${qualitySuffix}.wgsl`);
// Example: Opaque render pipeline (portable WGSL)
const renderPipeline = await this.device!.pipeline.createRenderPipelineAsync({
layout: 'auto', // Portable bind group layout
vertex: { module: shaders.vertex, entryPoint: 'vs_main' },
fragment: { module: shaders.fragment, entryPoint: 'fs_main', targets: [{ format: this.context!.getCurrentTexture().format }] },
primitive: { topology: 'triangle-list' },
depthStencil: this.featureFlags.msaa ? { depthWriteEnabled: true, depthCompare: 'less', format: 'depth32float' } : undefined,
});
this.pipelineCache.set('opaque', renderPipeline);
}
startRenderLoop(timestamp: number): void {
this.telemetry.frameStart();
const commandEncoder = this.device!.createCommandEncoder();
const textureView = this.context!.getCurrentTexture().createView();
// Compute pass (gated)
if (this.featureFlags.computeShaders && this.qualityLevel >= 2) {
const computePass = commandEncoder.beginComputePass();
const computePipeline = this.pipelineCache.get('compute') as GPUComputePipeline;
computePass.setPipeline(computePipeline);
// Bind resources...
computePass.dispatchWorkgroups(...);
computePass.end();
}
// Render pass
this.renderPassDescriptor = {
colorAttachments: [{
view: textureView,
clearValue: { r: 0.1, g: 0.1, b: 0.1, a: 1.0 },
loadOp: 'clear',
storeOp: 'store',
}],
// Depth/stencil gated by features
depthStencilAttachment: this.featureFlags.msaa ? {
view: this.resourceManager.getDepthTexture().createView(),
depthClearValue: 1.0,
depthLoadOp: 'clear',
depthStoreOp: 'store',
} : undefined,
};
const pass = commandEncoder.beginRenderPass(this.renderPassDescriptor);
pass.setPipeline(this.pipelineCache.get('opaque') as GPURenderPipeline);
// Bind groups, draw calls...
pass.end();
// Telemetry: GPU timestamps
const querySet = this.telemetry.querySet;
commandEncoder.writeTimestamp(querySet, 0); // Start
// ... commands ...
commandEncoder.writeTimestamp(querySet, 1); // End
commandEncoder.resolveQuerySet(querySet, 0, 2, this.telemetry.readbackBuffer);
this.device!.queue.submit([commandEncoder.finish()]);
this.telemetry.readGpuTime(); // Async resolve next frame
if (this.telemetry.avgFps < 30) {
this.handleFallback(); // Adaptive drop
}
requestAnimationFrame((t) => this.startRenderLoop(t));
}
private handleFallback(): void {
if (this.qualityLevel > 0) {
this.qualityLevel--;
this.compilePipelines().then(() => console.log(`Fallback to quality ${this.qualityLevel}`));
}
}
}
/**
* Shader Portability Manager
* Loads WGSL with #ifdefs for variants (e.g., #if MOBILE_LOW disable complex math).
*/
class ShaderManager {
private device: GPUDevice;
async init(device: GPUDevice) { this.device = device; }
async loadShaderSet(url: string): Promise<{ vertex: GPUShaderModule, fragment: GPUShaderModule }> {
const wgsl = await (await fetch(url)).text();
// Preprocess for portability: inject defines
const mobileLow = /* global flag */ false;
const processed = wgsl
.replace(/#ifdef MOBILE_LOW/g, mobileLow ? '#if 1' : '#if 0')
.replace(/#ifdef HIGH_QUALITY/g, mobileLow ? '#if 0' : '#if 1');
const module = this.device.createShaderModule({ code: processed });
return {
vertex: module,
fragment: module, // Shared module for simplicity; split in prod
};
}
}
/**
* Resource Lifetime Management
* Generational arenas: allocate ID, track gen, dispose when stale.
* WeakRef for JS GC cooperation.
*/
class ResourceManager {
private device: GPUDevice;
private buffers: WeakRef<GPUBuffer>[] = [];
private textures: WeakRef<GPUTexture>[] = [];
private nextId = 0;
private gen = new Map<number, number>();
init(device: GPUDevice) { this.device = device; }
createBuffer(size: number, usage: GPUBufferUsageFlags, label?: string): { id: number, buffer: GPUBuffer } {
const id = this.nextId++;
const buffer = this.device.createBuffer({ size, usage, label });
this.buffers.push(new WeakRef(buffer));
this.gen.set(id, 0);
return { id, buffer };
}
getDepthTexture(): GPUTexture {
// Reuse or create on-demand, copy-on-write for mobile mem
return this.device.createTexture({
size: [window.innerWidth, window.innerHeight],
format: 'depth32float',
usage: GPUTextureUsage.RENDER_ATTACHMENT,
});
}
dispose(id: number): void {
const g = this.gen.get(id);
if (g) this.gen.set(id, g + 1); // Bump gen, WeakRef GCs old
// Frame-end sweep: if gen bumped > threshold, explicit destroy
}
}
/**
* Performance Telemetry
* FPS, GPU time histograms, optional remote logging.
*/
class TelemetryCollector {
private querySet: GPUQuerySet;
private readbackBuffer: GPUBuffer;
private timestamps = new Float32Array(2);
private frameTimes: number[] = [];
private avgFps = 60;
constructor() {
// Init querySet/readback in init()
}
frameStart() {
this.frameTimes.push(performance.now());
if (this.frameTimes.length > 60) {
const fps = 1000 / (this.frameTimes.pop()! - this.frameTimes.shift()!) * 60;
this.avgFps = this.avgFps * 0.9 + fps * 0.1; // EWMA
}
}
readGpuTime() {
// Map readback, parse timestamps[1] - timestamps[0] (ns)
const gpuTimeMs = (this.timestamps[1] - this.timestamps[0]) / 1e6;
console.log(`GPU Time: ${gpuTimeMs.toFixed(2)}ms, FPS: ${this.avgFps.toFixed(1)}`);
// Histogram: if >16ms, alert perf issue
// Optional: post to analytics endpoint
}
}
// WGSL Example (main_med.wgsl) - Portable with defines
/*
@vertex
fn vs_main(@location(0) pos: vec3<f32>) -> @builtin(position) vec4<f32> {
#ifdef MOBILE_LOW
return vec4<f32>(pos.xy * 0.5, 0.0, 1.0); // Simplified proj
#else
return projection * vec4<f32>(pos, 1.0);
#endif
}
@fragment
fn fs_main() -> @location(0) vec4<f32> {
#ifdef HIGH_QUALITY
// Anisotropic sampling, storage tex fetch
#else
return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Solid color fallback
#endif
}
*/
This draft is production-ready scaffolding; integrate your app state (meshes, cameras) into startRenderLoop().