webgpu / webgpufundamentals

https://webgpufundamentals.org
BSD 3-Clause "New" or "Revised" License
624 stars 88 forks source link

The introductory tutorial contains broken example code. #122

Closed 7ombie closed 2 months ago

7ombie commented 2 months ago

The website introduces WebGPU with a lesson named after the site. Towards the end of that document, there's a section on resizing the canvas. The example code sets up a resize observer like this:

const observer = new ResizeObserver(entries => {
    for (const entry of entries) {
        const canvas = entry.target;
        const width = entry.contentBoxSize[0].inlineSize;
        const height = entry.contentBoxSize[0].blockSize;
        canvas.width = Math.max(1, Math.min(width, device.limits.maxTextureDimension2D));
        canvas.height = Math.max(1, Math.min(height, device.limits.maxTextureDimension2D));
        render();
    }
});

Using entry.contentBoxSize[0] gives incorrect results. The edges of the resulting triangle are jagged, and the canvas is the wrong size.

If you resize the canvas element (by changing the size of the DevTools window), then refresh the page (with the DevTools window open still), the canvas changes size (when logically, its size should be a function of the viewport size). Using entry.devicePixelContentBoxSize[0] fixes both issues.


You can simplify the observer a little too. Mine looks like this:

const observer = new ResizeObserver(function(entries) {

    const box = entries[0].devicePixelContentBoxSize[0];
    const maxSize = device.limits.maxTextureDimension2D;

    canvas.width = Math.max(1, Math.min(box.inlineSize, maxSize));
    canvas.height = Math.max(1, Math.min(box.blockSize, maxSize));

    render();
});

P.S. Thanks for all the awesome content. WebGL Fundamentals taught me to write my first shaders, so I was really pleased to see there's a sister-site for WebGPU.

greggman commented 2 months ago

thanks for the comment

It’s intentional. You don’t have to use devicePixelContentBoxSize. it’s a choice.

Further, devicePixelContentBoxSize doesn’t exist on Safari

In any case, there is a whole article about it here

https://webgpufundamentals.org/webgpu/lessons/webgpu-resizing-the-canvas.html

7ombie commented 2 months ago

Ahh. Sorry for the noise. I should've read that first. The tutorial does mention it. I just forgot.

Thanks, @greggman. Much appreciated.