84 lines
1.6 KiB
JavaScript
84 lines
1.6 KiB
JavaScript
|
|
export class RenderSystem {
|
||
|
|
|
||
|
|
constructor( device, canvas ) {
|
||
|
|
|
||
|
|
this.device = device;
|
||
|
|
this.canvas = canvas;
|
||
|
|
|
||
|
|
// simple per-system depth texture; recreated on resize by user as needed
|
||
|
|
this.depthTexture = null;
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
_beginFrame( clearColor = { r: 0.3, g: 0.3, b: 0.3, a: 1 } ) {
|
||
|
|
|
||
|
|
const canvas = this.canvas;
|
||
|
|
|
||
|
|
const context = canvas.getContext( "webgpu" );
|
||
|
|
|
||
|
|
const format = navigator.gpu.getPreferredCanvasFormat();
|
||
|
|
|
||
|
|
if ( !this.depthTexture ||
|
||
|
|
this.depthTexture.width !== canvas.width ||
|
||
|
|
this.depthTexture.height !== canvas.height ) {
|
||
|
|
|
||
|
|
this.depthTexture = this.device.createTexture( {
|
||
|
|
size: [ canvas.width, canvas.height, 1 ],
|
||
|
|
sampleCount: 1,
|
||
|
|
format: "depth24plus",
|
||
|
|
usage: GPUTextureUsage.RENDER_ATTACHMENT
|
||
|
|
} );
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
const encoder = this.device.createCommandEncoder();
|
||
|
|
|
||
|
|
const view = context.getCurrentTexture().createView();
|
||
|
|
|
||
|
|
const depthView = this.depthTexture.createView();
|
||
|
|
|
||
|
|
const renderPassDescriptor = {
|
||
|
|
colorAttachments: [ {
|
||
|
|
view: view,
|
||
|
|
loadOp: "clear",
|
||
|
|
storeOp: "store",
|
||
|
|
clearValue: clearColor
|
||
|
|
} ],
|
||
|
|
depthStencilAttachment: {
|
||
|
|
view: depthView,
|
||
|
|
depthLoadOp: "clear",
|
||
|
|
depthStoreOp: "store",
|
||
|
|
depthClearValue: 1.0
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
const passEncoder = encoder.beginRenderPass( renderPassDescriptor );
|
||
|
|
|
||
|
|
return { encoder, passEncoder };
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
_endFrame( frame ) {
|
||
|
|
|
||
|
|
frame.passEncoder.end();
|
||
|
|
|
||
|
|
this.device.queue.submit( [ frame.encoder.finish() ] );
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
render( scene, clearColor ) {
|
||
|
|
|
||
|
|
const frame = this._beginFrame( clearColor );
|
||
|
|
|
||
|
|
scene.draw( frame.passEncoder );
|
||
|
|
|
||
|
|
this._endFrame( frame );
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
}
|
||
|
|
|