Skip to content

WebGL and WebGPU backends should not panic if canvas context is unavailable #3017

Closed
@kpreid

Description

@kpreid

The WebGL and WebGPU backends have code which expect()s success in obtaining a canvas:

let context: wasm_bindgen::JsValue = match canvas.get_context("webgpu") {
Ok(Some(ctx)) => ctx.into(),
_ => panic!("expected to get context from canvas"),
};

let webgl2_context = canvas
.get_context_with_context_options("webgl2", &Self::create_context_options())
.expect("Cannot create WebGL2 context")
.and_then(|context| context.dyn_into::<web_sys::WebGl2RenderingContext>().ok())
.expect("Cannot convert into WebGL2 context");

These will panic if the browser declines to provide a context, which may happen for reasons outside of the application programmer's control (browser does not support WebGPU or WebGL2, insufficient GPU memory, browser glitches) as well as ones which are (such as trying to use the same canvas for "2d" drawing). Therefore, the application may have reason to handle the error (if nothing else, to give the user an error message visible on the web page), which is best done by returning an Err rather than panicking — especially as Rust on wasm32 does not support unwinding, so every panic is fatal to the Rust module and can at best be handled from JavaScript.

This is not a solely theoretical scenario — I noticed the problem due to some Bevy Jam #2 games failing to start.

Platform
web, wgpu 0.13

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions