UNPKG

@giraphics/grpkggfx

Version:
86 lines (85 loc) 3.21 kB
export class Renderer { constructor(canvas, binding, primitive) { this.render = (scene, camera) => { // Acquire next image from context this.colorTexture = this.context.getCurrentTexture(); this.colorTextureView = this.colorTexture.createView(); let colorAttachment = { view: this.colorTextureView, loadValue: { r: 0.2, g: 0.2, b: 0.2, a: 1.0 }, storeOp: 'store' }; const depthAttachment = { view: this.depthTextureView, depthLoadValue: 1, depthStoreOp: 'store', stencilLoadValue: 'load', stencilStoreOp: 'store' }; const renderPassDesc = { colorAttachments: [colorAttachment], depthStencilAttachment: depthAttachment }; this.commandEncoder = this.device.createCommandEncoder(); // Encode drawing commands this.passEncoder = this.commandEncoder.beginRenderPass(renderPassDesc); this.passEncoder.setViewport(0, 0, this.canvas.width, this.canvas.height, 0, 1); this.passEncoder.setScissorRect(0, 0, this.canvas.width, this.canvas.height); // Write and submit commands to queue this.renderScene(scene, camera); this.passEncoder.endPass(); this.queue.submit([this.commandEncoder.finish()]); }; this.canvas = canvas; this.binding = binding; this.primitive = primitive; } // Initialize async initializeAPI() { try { // Entry to GPU const entry = navigator.gpu; if (!entry) { return false; } // Physical Device Adapter this.adapter = await entry.requestAdapter(); // Logical Device this.device = await this.adapter.requestDevice(); // Queue this.queue = this.device.queue; this.resizeBackings(); } catch (e) { console.error(e); return false; } return true; } // Resize swapchain, frame buffer attachments resizeBackings() { // Swapchain if (!this.context) { this.context = this.canvas.getContext('webgpu'); const canvasConfig = { device: this.device, format: 'bgra8unorm', usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC }; this.context.configure(canvasConfig); } const depthTextureDesc = { size: [this.canvas.width, this.canvas.height, 1], dimension: '2d', format: 'depth24plus-stencil8', usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC }; this.depthTexture = this.device.createTexture(depthTextureDesc); this.depthTextureView = this.depthTexture.createView(); } renderScene(scene, camera) { for (let object of scene.getObjects()) { object.draw(this.passEncoder, camera); } } }