Utils

The wgpu library provides a few utilities. Note that most functions below need to be explicitly imported.

Logger

Errors, warnings, and info messages (including messages generated by wgpu-native) are logged using Python’s default logging mechanics. The wgpu logger instance is in wgpu.logger, but can also be obtained via:

import logging
logger = logging.getLogger("wgpu")

Diagnostics

To print a full diagnostic report:

wgpu.diagnostics.print_report()

To inspect (for example) the total buffer usage:

>>> counts = wgpu.diagnostics.object_counts.get_dict()
>>> print(counts["Buffer"])
{'count': 3, 'resource_mem': 784}
class wgpu._diagnostics.DiagnosticsRoot

Root object to access wgpu diagnostics (i.e. wgpu.diagnostics).

Per-topic diagnostics can be accessed as attributes on this object. These include system, wgpu_native_info, versions, object_counts, wgpu_native_counts.

get_dict()

Get a dict that represents the full diagnostics info.

The keys are the diagnostic topics, and the values are dicts of dicts. See e.g. wgpu.diagnostics.counts.get_dict() for a topic-specific dict.

get_report()

Get the full textual diagnostic report (as a str).

print_report()

Convenience method to print the full diagnostics report.

class wgpu.DiagnosticsBase(name)

Object that represents diagnostics on a specific topic.

This is a base class that must be subclassed to provide diagnostics on a certain topic. Typically only get_dict() needs to be implemented. Instantiating the class registers it with the root diagnostics object.

get_dict()

Get the diagnostics for this topic, in the form of a Python dict.

Subclasses must implement this method. The dict can be a simple map of keys to values (str, int, float):

foo: 1
bar: 2

If the values are dicts, the data has a table-like layout, with the keys representing the table header:

          count  mem

Adapter:      1  264
 Buffer:      4  704

Subdicts are also supported, which results in multi-row entries. In the report, the keys of the subdicts have colons behind them:

          count  mem  backend  o  v  e  el_size

Adapter:      1  264  vulkan:  1  0  0      264
                       d3d12:  1  0  0      220
 Buffer:      4  704  vulkan:  4  0  0      176
                       d3d12:  0  0  0      154
get_report()

Get the textual diagnostics report for this topic.

get_subscript()

Get informative text that helps interpret the report.

Subclasses can implement this method. The text will show below the table in the report.

print_report()

Print the diagnostics report for this topic.

Base class for flags and enums

class wgpu.utils.BaseEnum

Base class for flags and enums.

Looks like Python’s builtin Enum class, but is simpler; fields are simply ints or strings.

Get default device

wgpu.utils.preconfigure_default_device(caller_info: str, *, feature_level: Literal['core', 'compatibility', None] = None, power_preference: Literal['low-power', 'high-performance'] | str | None = None, force_fallback_adapter: bool | None = None, canvas: object | None = None, adapter: GPUAdapter | None = None, label: str | None = None, required_features: set[Literal['core-features-and-limits', 'depth-clip-control', 'depth32float-stencil8', 'texture-compression-bc', 'texture-compression-bc-sliced-3d', 'texture-compression-etc2', 'texture-compression-astc', 'texture-compression-astc-sliced-3d', 'timestamp-query', 'indirect-first-instance', 'shader-f16', 'rg11b10ufloat-renderable', 'bgra8unorm-storage', 'float32-filterable', 'float32-blendable', 'clip-distances', 'dual-source-blending', 'subgroups', 'texture-formats-tier1', 'texture-formats-tier2', 'primitive-index'] | str] | None = None, required_limits: dict[str, int | None] | None = None) None

Configure the default GPUDevice before it is created.

This function can only be called at import-time or at the top of your script. It is an error to call this once the default device has been created.

This function can be called multiple times, e.g. different libraries that use wgpu can each require the features they need. For required features the union of set features is used. For required limits the minimum of each set limit is used. For the other arguments, the last set value is used, and a warning is logged when a value is overriden.

Parameters:
  • caller_info (str) – A very brief description of the code that calls this, or the reason for calling it, e.g. a library name. For debugging only.

  • feature_level (str) – The feature level “core” (default) or “compatibility”. This provides a way to opt into additional validation restrictions.

  • power_preference (PowerPreference) – “high-performance” or “low-power”.

  • force_fallback_adapter (bool) – whether to use a (probably CPU-based) fallback adapter.

  • canvas – The canvas or context that the adapter should be able to render to. This can typically be left to None. If given, it should be a GPUCanvasContext or RenderCanvas.

  • adapter (GPUAdapter) – the adapter object to use to create the default device. This can be useful to target a specific GPU in a multi-GPU setting. Setting the adapter overrules all other adapter settings (feature_level, power_preference, force_fallback_adapter, canvas).

  • label (str) – A human-readable label for the device.

  • required_features (list of str) – the features (extensions) that you need. Features can also be discarded by prefixing them with ‘!’. This is not recommended unless for testing and very specific use-cases.

  • required_limits (dict) – the various limits that you want to apply. Limits can also be discarded by setting their value to None.

wgpu.utils.get_default_device() GPUDevice

Get the default GPUDevice instance.

The default device is a global/shared device. It is generally recommended to use this device; different parts of a running program can only share objects like textures and buffers when they use the same device.

The default device can be configured at import-time using preconfigure_default_device().

Compute with buffers

from wgpu.utils.compute import compute_with_buffers
wgpu.utils.compute.compute_with_buffers(input_arrays, output_arrays, shader, constants=None, n=None)

Apply the given compute shader to the given input_arrays and return output arrays. Both input and output arrays are represented on the GPU using storage buffer objects.

Parameters:
  • input_arrays (dict) – A dict mapping int bindings to arrays. The array can be anything that supports the buffer protocol, including bytes, memoryviews, ctypes arrays and numpy arrays. The type and shape of the array does not need to match the type with which the shader will interpret the buffer data (though it probably makes your code easier to follow).

  • output_arrays (dict) – A dict mapping int bindings to output shapes. If the value is int, it represents the size (in bytes) of the buffer. If the value is a tuple, its last element specifies the format (see below), and the preceding elements specify the shape. These are used to cast() the memoryview object before it is returned. If the value is a ctypes array type, the result will be cast to that instead of a memoryview. Note that any buffer that is NOT in the output arrays dict will be considered readonly in the shader.

  • shader (str or bytes) – The shader as a string of WGSL code or SpirV bytes.

  • constants (dict, optional) – provide override constants

  • n (int, tuple, optional) – The dispatch counts. Can be an int or a 3-tuple of ints to specify (x, y, z). If not given or None, the length of the first output array type is used.

Returns:

A dict mapping int bindings to memoryviews.

Return type:

output (dict)

The format characters to cast a memoryview are hard to remember, so here’s a refresher:

  • “b” and “B” are signed and unsigned 8-bit ints.

  • “h” and “H” are signed and unsigned 16-bit ints.

  • “i” and “I” are signed and unsigned 32-bit ints.

  • “e” and “f” are 16-bit and 32-bit floats.

Helper for using glfw directly (not via rendercanvas)

from wgpu.utils.glfw_present_info import get_glfw_present_info
wgpu.utils.glfw_present_info.get_glfw_present_info(window, vsync=True) dict

Get the present_info dict required to instantiate a GPUCanvasContext.

Given a glfw window handle, return a dict that can be passed to wgpu.gpu.get_canvas_context() to create a GPUCanvasContext.