UNPKG

@giraphics/grpkggfx

Version:
81 lines (80 loc) 2.77 kB
export var device; export class WebGpuRenderer { constructor() { this.swapChainFormat = 'bgra8unorm'; this.initSuccess = false; } async init(canvas) { if (!canvas) { console.log('missing canvas!'); return false; } const adapter = await navigator.gpu.requestAdapter(); device = await adapter.requestDevice(); if (!device) { console.log('found no gpu device!'); return false; } this.context = canvas.getContext('webgpu'); //this.presentationFormat = this.context.getPreferredFormat(adapter); this.presentationFormat = this.swapChainFormat; //Parminder this.presentationSize = [canvas.clientWidth * devicePixelRatio, canvas.clientHeight * devicePixelRatio]; this.context.configure({ device, format: this.presentationFormat, size: this.presentationSize, }); const depthTextureView = this.depthTextureView(canvas); this.renderPassDescriptor = { colorAttachments: [ { // attachment is acquired and set in render loop. view: undefined, loadValue: { r: 0.75, g: 0.5, b: 0.5, a: 1.0 }, }, ], depthStencilAttachment: { view: depthTextureView, depthLoadValue: 1.0, depthStoreOp: 'store', stencilLoadValue: 0, stencilStoreOp: 'store', }, }; return (this.initSuccess = true); } update(canvas) { if (!this.initSuccess) { return; } this.updateRenderPassDescriptor(canvas); } frame(camera, scene) { if (!this.initSuccess) { return; } this.renderPassDescriptor.colorAttachments[0].view = this.context .getCurrentTexture() .createView(); const commandEncoder = device.createCommandEncoder(); const passEncoder = commandEncoder.beginRenderPass(this.renderPassDescriptor); for (let object of scene.getObjects()) { object.draw(passEncoder, device, camera); } passEncoder.endPass(); device.queue.submit([commandEncoder.finish()]); } depthTextureView(canvas) { return device .createTexture({ size: this.presentationSize, format: 'depth24plus-stencil8', usage: GPUTextureUsage.RENDER_ATTACHMENT, }) .createView(); } updateRenderPassDescriptor(canvas) { this.renderPassDescriptor.depthStencilAttachment.view = this.depthTextureView(canvas); } }