@@ -120,6 +120,29 @@ export async function detectGPUDevice(): Promise<GPUDeviceDetectOutput | undefin
120120 }
121121}
122122
123+ /**
124+ * Create GPU buffer with `createBuffer()` but with error catching; destroy if error caught.
125+ * @param device The GPUDevice used to create a buffer.
126+ * @param descriptor The GPUBufferDescriptor passed to `createBuffer()`.
127+ * @returns The buffer created by `createBuffer()`.
128+ *
129+ * @note We treat any error occurred at `createBuffer()` fatal and expect the user to handle
130+ * `device.destroy()` with `device.lost.then()`.
131+ */
132+ function tryCreateBuffer ( device : GPUDevice , descriptor : GPUBufferDescriptor ) {
133+ device . pushErrorScope ( "out-of-memory" ) ;
134+ device . pushErrorScope ( "validation" ) ;
135+ device . pushErrorScope ( "internal" ) ;
136+
137+ const buffer = device . createBuffer ( descriptor ) ;
138+
139+ device . popErrorScope ( ) . then ( ( error ) => { if ( error ) { device . destroy ( ) ; console . error ( error ) ; } } ) ;
140+ device . popErrorScope ( ) . then ( ( error ) => { if ( error ) { device . destroy ( ) ; console . error ( error ) ; } } ) ;
141+ device . popErrorScope ( ) . then ( ( error ) => { if ( error ) { device . destroy ( ) ; console . error ( error ) ; } } ) ;
142+
143+ return buffer ;
144+ }
145+
123146const canvasRenderWGSL = `
124147@group(0) @binding(0) var my_sampler : sampler;
125148@group(0) @binding(1) var my_texture : texture_2d<f32>;
@@ -504,7 +527,7 @@ export class WebGPUContext {
504527
505528 if ( buffer == undefined ) {
506529 // create uniform buffer
507- buffer = this . device . createBuffer ( {
530+ buffer = tryCreateBuffer ( this . device , {
508531 size : allocSize ,
509532 usage : GPUBufferUsage . UNIFORM | GPUBufferUsage . COPY_DST ,
510533 } ) ;
@@ -779,7 +802,7 @@ export class WebGPUContext {
779802 if ( nbytes == 0 ) {
780803 nbytes = 1 ;
781804 }
782- const buffer = this . device . createBuffer ( {
805+ const buffer = tryCreateBuffer ( this . device , {
783806 size : nbytes ,
784807 usage : GPUBufferUsage . STORAGE | GPUBufferUsage . COPY_SRC | GPUBufferUsage . COPY_DST ,
785808 } ) ;
@@ -833,7 +856,7 @@ export class WebGPUContext {
833856 nbytes : number
834857 ) : void {
835858 // Perhaps it would be more useful to resuse a staging buffer?
836- const gpuTemp = this . device . createBuffer ( {
859+ const gpuTemp = tryCreateBuffer ( this . device , {
837860 size : nbytes ,
838861 usage : GPUBufferUsage . MAP_READ | GPUBufferUsage . COPY_DST ,
839862 } ) ;
0 commit comments