engine icon indicating copy to clipboard operation
engine copied to clipboard

Improve async webgl2 device methods

Open AlexAPPi opened this issue 3 months ago • 1 comments

The changes in the WebGL subsystem (WebglGraphicsDevice) are related to asynchronous pixel reading from the GPU and handling synchronization for waiting on read results.

Key updates:

  • The method clientWaitAsync now accepts an additional abort signal parameter (AbortSignal), allowing cancellation of the asynchronous wait if needed.
  • An asynchronous version of readPixelsAsync is added, which uses a Pixel Buffer Object (PBO) for efficient async reading of pixels from the GPU.
  • In readPixelsAsync:
    • A temporary GPU buffer (gl.PIXEL_PACK_BUFFER) is created, and pixel data is copied into it via gl.readPixels using format and type parameters obtained from the current color buffer.
    • An asynchronous wait is performed for the operation to complete using clientWaitAsync with support for aborting.
    • Then the data is copied back from the GPU buffer into the provided pixel array.
  • Similar changes are reflected in readTextureAsync, which now supports passing an abort signal and uses the updated readPixelsAsync.
  • Resource management (creating/deleting buffers) is handled more carefully with try/finally blocks and considers operation cancellation.

Overall, these changes improve asynchronous handling and control over GPU pixel reading operations with the ability to cancel operations, enhancing responsiveness and resource management in WebGL applications.

    let readerAbortController = new AbortController();

    document.addEventListener("visibilitychange", () => {
        if (document.hidden) {
              readerAbortController.abort();
              readerAbortController = new AbortController();
        }
    });

    ...
    
    async readRenderData() {
        const pixels = new Float32Array(1024);
        const signal = readerAbortController.signal;
        await device.readPixelsAsync(0, 0, 128, 128, pixels, signal);
        ...
    }

I have read the contributing guidelines

AlexAPPi avatar Oct 11 '25 15:10 AlexAPPi

Is there any API changes, are they breaking ones? Please add every new argument and/or method to first post.

Maksims avatar Oct 11 '25 18:10 Maksims