WGPU API

This document describes the wgpu API. It is basically a Pythonic version of the WebGPU API. It exposes an API for performing operations, such as rendering and computation, on a Graphics Processing Unit.

Warning

The WebGPU API is still being developed and occasionally there are backwards incompatible changes. Since we mostly follow the WebGPU API, there may be backwards incompatible changes to wgpu-py too. This will be so until the WebGPU API settles as a standard.

How to read this API

The classes in this API all have a name staring with “GPU”, this helps discern them from flags and enums. These classes are never instantiated directly; new objects are returned by certain methods.

Most methods in this API have no positional arguments; each argument must be referenced by name. Some argument values must be a dict, these can be thought of as “nested” arguments.

Many arguments (and dict fields) must be a flags or enums. Flags are integer bitmasks that can be orred together. Enum values are strings in this API.

Some arguments have a default value. Most do not.

Selecting the backend

Before you can use this API, you have to select a backend. Eventually there may be multiple backends, but at the moment there is only one backend, which is based on the Rust libary wgpu-native. You select the backend by importing it:

import wgpu.backends.rs

The wgpu-py package comes with the wgpu-native library. If you want to use your own version of that library instead, set the WGPU_LIB_PATH environment variable.

Differences from WebGPU

This API is derived from the WebGPU spec, but differs in a few ways. For example, methods that in WebGPU accept a descriptor/struct/dict, here accept the fields in that struct as keyword arguments.

wgpu.base.apidiff Differences of base API:
  • Adds GPUAdapter.properties() - useful for desktop
  • Adds GPUBuffer.map_read() - Alternative to mapping API
  • Adds GPUBuffer.map_write() - Alternative to mapping API
  • Adds GPUBuffer.size() - Too useful to not-have
  • Adds GPUBuffer.usage() - Too useful to not-have
  • Adds GPUCanvasContext.present() - Present method is exposed
  • Adds GPUDevice.adapter() - Too useful to not-have
  • Adds GPUDevice.create_buffer_with_data() - replaces WebGPU’s mapping API
  • Adds GPUQueue.read_buffer() - replaces WebGPU’s mapping API
  • Adds GPUQueue.read_texture() - For symmetry, and to help work around the bytes_per_row constraint
  • Adds GPUTexture.dimension() - Too useful to not-have
  • Adds GPUTexture.format() - Too useful to not-have
  • Adds GPUTexture.mip_level_count() - Too useful to not-have
  • Adds GPUTexture.sample_count() - Too useful to not-have
  • Adds GPUTexture.size() - Too useful to not-have
  • Adds GPUTexture.usage() - Too useful to not-have
  • Adds GPUTextureView.size() - Too useful to not-have
  • Adds GPUTextureView.texture() - Too useful to not-have
  • Changes GPU.request_adapter() - arguments include a canvas object
  • Changes GPU.request_adapter_async() - arguments include a canvas object
  • Hides GPUBuffer.get_mapped_range()
  • Hides GPUBuffer.map_async()
  • Hides GPUBuffer.unmap()
  • Hides GPUComputePassEncoder.begin_pipeline_statistics_query()
  • Hides GPUComputePassEncoder.end_pipeline_statistics_query()
  • Hides GPUDevice.import_external_texture() - Specific to browsers.
  • Hides GPUDevice.pop_error_scope()
  • Hides GPUDevice.push_error_scope()
  • Hides GPUQueue.copy_external_image_to_texture() - Specific to browsers.
  • Hides GPURenderPassEncoder.begin_pipeline_statistics_query()
  • Hides GPURenderPassEncoder.end_pipeline_statistics_query()

Each backend may also implement minor differences (usually additions) from the base API. For the rs backend check print(wgpu.backends.rs.apidiff.__doc__).

Adapter

To start using the GPU for computations or rendering, a device object is required. One first requests an adapter, which represens a GPU implementation on the current system. The device can then be requested from the adapter.

WGPU supports a variety of wgpu-backends. By default one is selected automatically. This can be overridden by setting the WGPU_BACKEND_TYPE environment variable to “Vulkan”, “Metal”, “D3D12”, “D3D11”, or “OpenGL”.

class wgpu.GPU

Class that represents the root namespace of the API.

wgpu.request_adapter(**parameters)

Get a GPUAdapter, the object that represents an abstract wgpu implementation, from which one can request a GPUDevice.

Parameters:
  • canvas (WgpuCanvasInterface) – The canvas that the adapter should be able to render to (to create a swap chain for, to be precise). Can be None if you’re not rendering to screen (or if you’re confident that the returned adapter will work just fine).
  • powerPreference (PowerPreference) – “high-performance” or “low-power”
wgpu.request_adapter_async(**parameters)

Async version of request_adapter().

class wgpu.GPUAdapter

An adapter represents both an instance of a hardware accelerator (e.g. GPU or CPU) and an implementation of WGPU on top of that accelerator. If an adapter becomes unavailable, it becomes invalid. Once invalid, it never becomes valid again.

features

A tuple of supported feature names.

is_fallback_adapter

Whether this adapter runs on software (rather than dedicated hardware).

limits

A dict with the adapter limits.

name

A human-readable name identifying the adapter.

properties

A dict with the adapter properties (info on device, backend, etc.)

request_device(**parameters)

Request a GPUDevice from the adapter.

Parameters:
  • label (str) – A human readable label. Optional.
  • required_features (list of str) – the features (extensions) that you need. Default [].
  • required_limits (dict) – the various limits that you need. Default {}.
request_device_async(**parameters)

Async version of request_device().

Device

The device is the central object; most other GPU objects are created from it. It is recommended to request a device object once, or perhaps twice. But not for every operation (e.g. in unit tests). Also see wgpu.utils.get_default_device().

class wgpu.GPUObjectBase

The base class for all GPU objects (the device and all objects belonging to a device).

label

A human-readable name identifying the GPU object.

class wgpu.GPUDevice

Subclass of GPUObjectBase

A device is the logical instantiation of an adapter, through which internal objects are created. It can be shared across threads. A device is the exclusive owner of all internal objects created from it: when the device is lost, all objects created from it become invalid.

Create a device using GPUAdapter.request_device() or GPUAdapter.request_device_async().

adapter

The adapter object corresponding to this device.

create_bind_group(**parameters)

Create a GPUBindGroup object, which can be used in pass.set_bind_group() to attach a group of resources.

Parameters:
  • label (str) – A human readable label. Optional.
  • layout (GPUBindGroupLayout) – The layout (abstract representation) for this bind group.
  • entries (list of dict) – A list of dicts, see below.

Example entry dicts:

# For a sampler
{
    "binding" : 0,  # slot
    "resource": a_sampler,
}
# For a texture view
{
    "binding" : 0,  # slot
    "resource": a_texture_view,
}
# For a buffer
{
    "binding" : 0,  # slot
    "resource": {
        "buffer": a_buffer,
        "offset": 0,
        "size": 812,
    }
}
create_bind_group_layout(**parameters)

Create a GPUBindGroupLayout object. One or more such objects are passed to create_pipeline_layout() to specify the (abstract) pipeline layout for resources. See the docs on bind groups for details.

Parameters:
  • label (str) – A human readable label. Optional.
  • entries (list of dict) – A list of layout entry dicts.

Example entry dict:

# Buffer
{
    "binding": 0,
    "visibility": wgpu.ShaderStage.COMPUTE,
    "buffer": {
        "type": wgpu.BufferBindingType.storage_buffer,
        "has_dynamic_offset": False,  # optional
        "min_binding_size": 0  # optional
    }
},
# Sampler
{
    "binding": 1,
    "visibility": wgpu.ShaderStage.COMPUTE,
    "sampler": {
        "type": wgpu.SamplerBindingType.filtering,
    }
},
# Sampled texture
{
    "binding": 2,
    "visibility": wgpu.ShaderStage.FRAGMENT,
    "texture": {
        "sample_type": wgpu.TextureSampleType.float,  # optional
        "view_dimension": wgpu.TextureViewDimension.d2,  # optional
        "multisampled": False,  # optional
    }
},
# Storage texture
{
    "binding": 3,
    "visibility": wgpu.ShaderStage.FRAGMENT,
    "storage_texture": {
        "access": wgpu.StorageTextureAccess.read_only,
        "format": wgpu.TextureFormat.r32float,
        "view_dimension": wgpu.TextureViewDimension.d2,
    }
},

About has_dynamic_offset: For uniform-buffer, storage-buffer, and readonly-storage-buffer bindings, it indicates whether the binding has a dynamic offset. One offset must be passed to set_bind_group for each dynamic binding in increasing order of binding number.

create_buffer(**parameters)

Create a GPUBuffer object.

Parameters:
  • label (str) – A human readable label. Optional.
  • size (int) – The size of the buffer in bytes.
  • usage (BufferUsageFlags) – The ways in which this buffer will be used.
  • mapped_at_creation (bool) – Must be False, use create_buffer_with_data() instead.
create_buffer_with_data(**parameters)

Create a GPUBuffer object initialized with the given data.

Parameters:
  • label (str) – A human readable label. Optional.
  • data – Any object supporting the Python buffer protocol (this includes bytes, bytearray, ctypes arrays, numpy arrays, etc.).
  • usage (BufferUsageFlags) – The ways in which this buffer will be used.

Also see GPUQueue.write_buffer() and GPUQueue.read_buffer().

create_command_encoder(**parameters)

Create a GPUCommandEncoder object. A command encoder is used to record commands, which can then be submitted at once to the GPU.

Parameters:
  • label (str) – A human readable label. Optional.
  • measure_execution_time (bool) – Whether to measure the execution time. Default False.
create_compute_pipeline(**parameters)

Create a GPUComputePipeline object.

Parameters:
  • label (str) – A human readable label. Optional.
  • layout (GPUPipelineLayout) – object created with create_pipeline_layout().
  • compute (dict) – E.g. {"module": shader_module, entry_point="main"}.
create_compute_pipeline_async(**parameters)

Async version of create_compute_pipeline().

create_pipeline_layout(**parameters)

Create a GPUPipelineLayout object, which can be used in create_render_pipeline() or create_compute_pipeline().

Parameters:
  • label (str) – A human readable label. Optional.
  • bind_group_layouts (list) – A list of GPUBindGroupLayout objects.
create_query_set(**parameters)

Create a GPUQuerySet object.

create_render_bundle_encoder(**parameters)

Create a GPURenderBundle object.

TODO: not yet available in wgpu-native

create_render_pipeline(**parameters)

Create a GPURenderPipeline object.

Parameters:
  • label (str) – A human readable label. Optional.
  • layout (GPUPipelineLayout) – A layout created with create_pipeline_layout().
  • vertex (VertexState) – Describes the vertex shader entry point of the pipeline and its input buffer layouts.
  • primitive (PrimitiveState) – Describes the the primitive-related properties of the pipeline. If strip_index_format is present (which means the primitive topology is a strip), and the drawCall is indexed, the vertex index list is split into sub-lists using the maximum value of this index format as a separator. Example: a list with values [1, 2, 65535, 4, 5, 6] of type “uint16” will be split in sub-lists [1, 2] and [4, 5, 6].
  • depth_stencil (DepthStencilState) – Describes the optional depth-stencil properties, including the testing, operations, and bias. Optional.
  • multisample (MultisampleState) – Describes the multi-sampling properties of the pipeline.
  • fragment (FragmentState) – Describes the fragment shader entry point of the pipeline and its output colors. If it’s None, the No Color Output mode is enabled: the pipeline does not produce any color attachment outputs. It still performs rasterization and produces depth values based on the vertex position output. The depth testing and stencil operations can still be used.

In the example dicts below, the values that are marked as optional, the shown value is the default.

Example vertex (VertexState) dict:

{
    "module": shader_module,
    "entry_point": "main",
    "buffers": [
        {
            "array_stride": 8,
            "step_mode": wgpu.VertexStepMode.vertex,  # optional
            "attributes": [
                {
                    "format": wgpu.VertexFormat.float2,
                    "offset": 0,
                    "shader_location": 0,
                },
                ...
            ],
        },
        ...
    ]
}

Example primitive (GPUPrimitiveState) dict:

{
    "topology": wgpu.PrimitiveTopology.triangle_list,
    "strip_index_format": wgpu.IndexFormat.uint32,  # see note
    "front_face": wgpu.FrontFace.ccw,  # optional
    "cull_mode": wgpu.CullMode.none,  # optional
}

Example depth_stencil (GPUDepthStencilState) dict:

{
    "format": wgpu.TextureFormat.depth24plus_stencil8,
    "depth_write_enabled": False,  # optional
    "depth_compare": wgpu.CompareFunction.always,  # optional
    "stencil_front": {  # optional
        "compare": wgpu.CompareFunction.equal,
        "fail_op": wgpu.StencilOperation.keep,
        "depth_fail_op": wgpu.StencilOperation.keep,
        "pass_op": wgpu.StencilOperation.keep,
    },
    "stencil_back": {  # optional
        "compare": wgpu.CompareFunction.equal,
        "fail_op": wgpu.StencilOperation.keep,
        "depth_fail_op": wgpu.StencilOperation.keep,
        "pass_op": wgpu.StencilOperation.keep,
    },
    "stencil_read_mask": 0xFFFFFFFF,  # optional
    "stencil_write_mask": 0xFFFFFFFF,  # optional
    "depth_bias": 0,  # optional
    "depth_bias_slope_scale": 0.0,  # optional
    "depth_bias_clamp": 0.0,  # optional
}

Example multisample (MultisampleState) dict:

{
    "count": 1,  # optional
    "mask": 0xFFFFFFFF,  # optional
    "alpha_to_coverage_enabled": False  # optional
}

Example fragment (FragmentState) dict. The blend parameter can be None to disable blending (not all texture formats support blending).

{
    "module": shader_module,
    "entry_point": "main",
    "targets": [
        {
            "format": wgpu.TextureFormat.bgra8unorm_srgb,
            "blend": {
                "color": (
                    wgpu.BlendFactor.One,
                    wgpu.BlendFactor.zero,
                    gpu.BlendOperation.add,
                ),
                "alpha": (
                    wgpu.BlendFactor.One,
                    wgpu.BlendFactor.zero,
                    wgpu.BlendOperation.add,
                ),
            }
            "write_mask": wgpu.ColorWrite.ALL  # optional
        },
        ...
    ]
}
create_render_pipeline_async(**parameters)

Async version of create_render_pipeline().

create_sampler(**parameters)

Create a GPUSampler object. Samplers specify how a texture is sampled.

Parameters:
  • label (str) – A human readable label. Optional.
  • address_mode_u (AddressMode) – What happens when sampling beyond the x edge. Default “clamp-to-edge”.
  • address_mode_v (AddressMode) – What happens when sampling beyond the y edge. Default “clamp-to-edge”.
  • address_mode_w (AddressMode) – What happens when sampling beyond the z edge. Default “clamp-to-edge”.
  • mag_filter (FilterMode) – Interpolation when zoomed in. Default ‘nearest’.
  • min_filter (FilterMode) – Interpolation when zoomed out. Default ‘nearest’.
  • mipmap_filter – (FilterMode): Interpolation between mip levels. Default ‘nearest’.
  • lod_min_clamp (float) – The minimum level of detail. Default 0.
  • lod_max_clamp (float) – The maxium level of detail. Default 32.
  • compare (CompareFunction) – The sample compare operation for depth textures. Only specify this for depth textures. Default None.
  • max_anisotropy (int) – The maximum anisotropy value clamp used by the sample, betweet 1 and 16, default 1.
create_shader_module(**parameters)

Create a GPUShaderModule object from shader source.

Parameters:
  • label (str) – A human readable label. Optional.
  • code (str | bytes) – The shader code, as WGSL text or binary SpirV (or an object implementing to_spirv() or to_bytes()).
create_texture(**parameters)

Create a GPUTexture object.

Parameters:
  • label (str) – A human readable label. Optional.
  • size (tuple or dict) – The texture size as a 3-tuple or a dict (width, height, depth_or_array_layers).
  • mip_level_count (int) – The number of mip leveles. Default 1.
  • sample_count (int) – The number of samples. Default 1.
  • dimension (TextureDimension) – The dimensionality of the texture. Default 2d.
  • format (TextureFormat) – What channels it stores and how.
  • usage (TextureUsageFlags) – The ways in which the texture will be used.

See https://gpuweb.github.io/gpuweb/#texture-format-caps for a list of available texture formats. Note that less formats are available for storage usage.

destroy()

Destroy this device.

features

A tuple of strings representing the features (i.e. extensions) with which this device was created.

limits

A dict exposing the limits with which this device was created.

lost

Provides information about why the device is lost.

onuncapturederror

Method called when an error is capured?

queue

The default GPUQueue for this device.

Buffers and textures

Buffers and textures are used to provide your shaders with data.

class wgpu.GPUBuffer

Subclass of GPUObjectBase

A GPUBuffer represents a block of memory that can be used in GPU operations. Data is stored in linear layout, meaning that each byte of the allocation can be addressed by its offset from the start of the buffer, subject to alignment restrictions depending on the operation.

Create a buffer using GPUDevice.create_buffer(), GPUDevice.create_buffer_mapped() or GPUDevice.create_buffer_mapped_async().

One can sync data in a buffer by mapping it (or by creating a mapped buffer) and then setting/getting the values in the mapped memoryview. Alternatively, one can tell the GPU (via the command encoder) to copy data between buffers and textures.

destroy()

An application that no longer requires a buffer can choose to destroy it. Note that this is automatically called when the Python object is cleaned up by the garbadge collector.

map_read()

Map the buffer and read the data from it, then unmap. Return a memoryview object. Requires the buffer usage to include MAP_READ.

See queue.read_buffer() for a simpler alternative.

map_write(data)

Map the buffer and write the data to it, then unmap. Return a memoryview object. Requires the buffer usage to include MAP_WRITE.

See queue.write_buffer() for a simpler alternative.

size

The length of the GPUBuffer allocation in bytes.

usage

The allowed usages (int bitmap) for this GPUBuffer, specifying e.g. whether the buffer may be used as a vertex buffer, uniform buffer, target or source for copying data, etc.

class wgpu.GPUTexture

Subclass of GPUObjectBase

A texture represents a 1D, 2D or 3D color image object. It also can have mipmaps (different levels of varying detail), and arrays. The texture represents the “raw” data. A GPUTextureView is used to define how the texture data should be interpreted.

Create a texture using GPUDevice.create_texture().

create_view(**parameters)

Create a GPUTextureView object.

If no aguments are given, a default view is given, with the same format and dimension as the texture.

Parameters:
  • label (str) – A human readable label. Optional.
  • format (TextureFormat) – What channels it stores and how.
  • dimension (TextureViewDimension) – The dimensionality of the texture view.
  • aspect (TextureAspect) – Whether this view is used for depth, stencil, or all. Default all.
  • base_mip_level (int) – The starting mip level. Default 0.
  • mip_level_count (int) – The number of mip levels. Default None.
  • base_array_layer (int) – The starting array layer. Default 0.
  • array_layer_count (int) – The number of array layers. Default None.
destroy()

An application that no longer requires a texture can choose to destroy it. Note that this is automatically called when the Python object is cleaned up by the garbadge collector.

dimension

The dimension of the texture.

format

The format of the texture.

mip_level_count

The total number of the mipmap levels of the texture.

sample_count

The number of samples in each texel of the texture.

size

The size of the texture in mipmap level 0, as a 3-tuple of ints.

usage

The allowed usages for this texture.

class wgpu.GPUTextureView

Subclass of GPUObjectBase

A texture view represents a way to represent a GPUTexture.

Create a texture view using GPUTexture.create_view().

size

The texture size (as a 3-tuple).

texture

The texture object to which this is a view.

class wgpu.GPUSampler

Subclass of GPUObjectBase

A sampler specifies how a texture (view) must be sampled by the shader, in terms of subsampling, sampling between mip levels, and sampling out of the image boundaries.

Create a sampler using GPUDevice.create_sampler().

Bind groups

Shaders need access to resources like buffers, texture views, and samplers. The access to these resources occurs via so called bindings. There are integer slots, which you specify both via the API and in the shader, to bind the resources to the shader.

Bindings are organized into bind groups, which are essentially a list of bindings. E.g. in Python shaders the slot of each resource is specified as a two-tuple (e.g. (1, 3)) specifying the bind group and binding slot respectively.

Further, in wgpu you need to specify a binding layout, providing meta-information about the binding (type, texture dimension etc.).

One uses device.create_bind_group() to create a group of bindings using the actual buffers/textures/samplers.

One uses device.create_bind_group_layout() to specify more information about these bindings, and device.create_pipeline_layout() to pack one or more bind group layouts together, into a complete layout description for a pipeline.

class wgpu.GPUBindGroupLayout

Subclass of GPUObjectBase

A bind group layout defines the interface between a set of resources bound in a GPUBindGroup and their accessibility in shader stages.

Create a bind group layout using GPUDevice.create_bind_group_layout().

class wgpu.GPUBindGroup

Subclass of GPUObjectBase

A bind group represents a group of bindings, the shader slot, and a resource (sampler, texture-view, buffer).

Create a bind group using GPUDevice.create_bind_group().

class wgpu.GPUPipelineLayout

Subclass of GPUObjectBase

A pipeline layout describes the layout of a pipeline, as a list of GPUBindGroupLayout objects.

Create a pipeline layout using GPUDevice.create_pipeline_layout().

Shaders and pipelines

The wgpu API knows three kinds of shaders: compute, vertex and fragment. Pipelines define how the shader is run, and with what resources.

class wgpu.GPUShaderModule

Subclass of GPUObjectBase

A shader module represents a programmable shader.

Create a shader module using GPUDevice.create_shader_module().

compilation_info()

Get shader compilation info. Always returns empty string at the moment.

compilation_info_async()

Async version of compilation_info()

class wgpu.GPUPipelineBase

A mixin class for render and compute pipelines.

get_bind_group_layout(index)

Get the bind group layout at the given index.

class wgpu.GPUComputePipeline

Subclass of GPUPipelineBase

A compute pipeline represents a single pipeline for computations (no rendering).

Create a compute pipeline using GPUDevice.create_compute_pipeline().

class wgpu.GPURenderPipeline

Subclass of GPUPipelineBase

A render pipeline represents a single pipeline to draw something using a vertex and a fragment shader. The render target can come from a window on the screen or from an in-memory texture (off-screen rendering).

Create a render pipeline using GPUDevice.create_render_pipeline().

Command buffers and encoders

class wgpu.GPUCommandBuffer

Subclass of GPUObjectBase

A command buffer stores a series of commands, generated by a GPUCommandEncoder, to be submitted to a GPUQueue.

Create a command buffer using GPUCommandEncoder.finish().

execution_time

Returns a future that, if measureExecutionTime is true, resolves after the command buffer executes.

class wgpu.GPUCommandEncoder

Subclass of GPUObjectBase

A command encoder is used to record a series of commands. When done, call finish() to obtain a GPUCommandBuffer object.

Create a command encoder using GPUDevice.create_command_encoder().

begin_compute_pass(**parameters)

Record the beginning of a compute pass. Returns a GPUComputePassEncoder object.

Parameters:label (str) – A human readable label. Optional.
begin_render_pass(**parameters)

Record the beginning of a render pass. Returns a GPURenderPassEncoder object.

Parameters:
  • label (str) – A human readable label. Optional.
  • color_attachments (list of dict) – List of color attachment dicts. See below.
  • depth_stencil_attachment (dict) – A depth stencil attachment dict. See below. Default None.
  • occlusion_query_set – Default None. TODO NOT IMPLEMENTED in wgpu-native.

Example color attachment:

{
    "view": texture_view,
    "resolve_target": None,  # optional
    "load_value": (0, 0, 0, 0),  # LoadOp.load or a color
    "store_op": wgpu.StoreOp.store,  # optional
}

Example depth stencil attachment:

{
    "view": texture_view,
    "depth_load_value": 0.0,
    "depth_store_op": wgpu.StoreOp.store,
    "stencil_load_value": wgpu.LoadOp.load,
    "stencil_store_op": wgpu.StoreOp.store,
}
copy_buffer_to_buffer(source, source_offset, destination, destination_offset, size)

Copy the contents of a buffer to another buffer.

Parameters:
  • source (GPUBuffer) – The source buffer.
  • source_offset (int) – The byte offset (a multiple of 4).
  • destination (GPUBuffer) – The target buffer.
  • destination_offset (int) – The byte offset in the destination buffer (a multiple of 4).
  • size (int) – The number of bytes to copy (a multiple of 4).
copy_buffer_to_texture(source, destination, copy_size)

Copy the contents of a buffer to a texture (view).

Parameters:
  • source (GPUBuffer) – A dict with fields: buffer, offset, bytes_per_row, rows_per_image.
  • destination (GPUTexture) – A dict with fields: texture, mip_level, origin.
  • copy_size (int) – The number of bytes to copy.

Note that the bytes_per_row must be a multiple of 256.

copy_texture_to_buffer(source, destination, copy_size)

Copy the contents of a texture (view) to a buffer.

Parameters:
  • source (GPUTexture) – A dict with fields: texture, mip_level, origin.
  • destination (GPUBuffer) – A dict with fields: buffer, offset, bytes_per_row, rows_per_image.
  • copy_size (int) – The number of bytes to copy.

Note that the bytes_per_row must be a multiple of 256.

copy_texture_to_texture(source, destination, copy_size)

Copy the contents of a texture (view) to another texture (view).

Parameters:
  • source (GPUTexture) – A dict with fields: texture, mip_level, origin.
  • destination (GPUTexture) – A dict with fields: texture, mip_level, origin.
  • copy_size (int) – The number of bytes to copy.
finish(**parameters)

Finish recording. Returns a GPUCommandBuffer to submit to a GPUQueue.

Parameters:label (str) – A human readable label. Optional.
insert_debug_marker(marker_label)

Insert a debug label in stack.

pop_debug_group()

Pop a label from the debug group stack.

push_debug_group(group_label)

Push a label on the debug group stack. (todo: docs)

resolve_query_set(query_set, first_query, query_count, destination, destination_offset)

TODO

write_timestamp(query_set, query_index)

TODO

class wgpu.GPUProgrammablePassEncoder

Base class for the different pass encoder classes.

insert_debug_marker(marker_label)

Insert the given message into the debug message queue.

pop_debug_group()

Pop the active debug group.

push_debug_group(group_label)

Push a named debug group into the command stream.

set_bind_group(index, bind_group, dynamic_offsets_data, dynamic_offsets_data_start, dynamic_offsets_data_length)

Associate the given bind group (i.e. group or resources) with the given slot/index.

Parameters:
  • index (int) – The slot to bind at.
  • bind_group (GPUBindGroup) – The bind group to bind.
  • dynamic_offsets_data (list of int) – A list of offsets (one for each bind group).
  • dynamic_offsets_data_start (int) – Not used.
  • dynamic_offsets_data_length (int) – Not used.
class wgpu.GPUComputePassEncoder

Subclass of GPUProgrammablePassEncoder

A compute-pass encoder records commands related to a compute pass.

Create a compute pass encoder using GPUCommandEncoder.begin_compute_pass().

dispatch(x, y=1, z=1)

Run the compute shader.

Parameters:
  • x (int) – The number of cycles in index x.
  • y (int) – The number of cycles in index y. Default 1.
  • z (int) – The number of cycles in index z. Default 1.
dispatch_indirect(indirect_buffer, indirect_offset)

Like dispatch(), but the function arguments are in a buffer.

Parameters:
  • indirect_buffer (GPUBuffer) – The buffer that contains the arguments.
  • indirect_offset (int) – The byte offset at which the arguments are.
end_pass()

Record the end of the compute pass.

set_pipeline(pipeline)

Set the pipeline for this compute pass.

Parameters:pipeline (GPUComputePipeline) – The pipeline to use.
write_timestamp(query_set, query_index)

TODO

class wgpu.GPURenderEncoderBase

Base class for different render-pass encoder classes.

draw(vertex_count, instance_count=1, first_vertex=0, first_instance=0)

Run the render pipeline without an index buffer.

Parameters:
  • vertex_count (int) – The number of vertices to draw.
  • instance_count (int) – The number of instances to draw. Default 1.
  • first_vertex (int) – The vertex offset. Default 0.
  • first_instance (int) – The instance offset. Default 0.
draw_indexed(index_count, instance_count=1, first_index=0, base_vertex=0, first_instance=0)

Run the render pipeline using an index buffer.

Parameters:
  • index_count (int) – The number of indices to draw.
  • instance_count (int) – The number of instances to draw. Default 1.
  • first_index (int) – The index offset. Default 0.
  • base_vertex (int) – A number added to each index in the index buffer. Default 0.
  • first_instance (int) – The instance offset. Default 0.
draw_indexed_indirect(indirect_buffer, indirect_offset)

Like draw_indexed(), but the function arguments are in a buffer.

Parameters:
  • indirect_buffer (GPUBuffer) – The buffer that contains the arguments.
  • indirect_offset (int) – The byte offset at which the arguments are.
draw_indirect(indirect_buffer, indirect_offset)

Like draw(), but the function arguments are in a buffer.

Parameters:
  • indirect_buffer (GPUBuffer) – The buffer that contains the arguments.
  • indirect_offset (int) – The byte offset at which the arguments are.
set_index_buffer(buffer, index_format, offset=0, size=None)

Set the index buffer for this render pass.

Parameters:
  • buffer (GPUBuffer) – The buffer that contains the indices.
  • index_format (GPUIndexFormat) – The format of the index data contained in buffer. If strip_index_format is given in the call to create_render_pipeline(), it must match.
  • offset (int) – The byte offset in the buffer. Default 0.
  • size (int) – The number of bytes to use. If zero, the remaining size (after offset) of the buffer is used. Default 0.
set_pipeline(pipeline)

Set the pipeline for this render pass.

Parameters:pipeline (GPURenderPipeline) – The pipeline to use.
set_vertex_buffer(slot, buffer, offset=0, size=None)

Associate a vertex buffer with a bind slot.

Parameters:
  • slot (int) – The binding slot for the vertex buffer.
  • buffer (GPUBuffer) – The buffer that contains the vertex data.
  • offset (int) – The byte offset in the buffer. Default 0.
  • size (int) – The number of bytes to use. If zero, the remaining size (after offset) of the buffer is used. Default 0.
class wgpu.GPURenderPassEncoder

Subclass of GPUProgrammablePassEncoder

A render-pass encoder records commands related to a render pass.

Create a render pass encoder using GPUCommandEncoder.begin_render_pass().

begin_occlusion_query(query_index)

TODO

end_occlusion_query()

TODO

end_pass()

Record the end of the render pass.

execute_bundles(bundles)

TODO: not yet available in wgpu-native

set_blend_constant(color)

Set the blend color for the render pass.

Parameters:color (tuple or dict) – A color with fields (r, g, b, a).
set_scissor_rect(x, y, width, height)

Set the scissor rectangle for this render pass. The scene is rendered as usual, but is only applied to this sub-rectangle.

Parameters:
  • x (int) – Horizontal coordinate.
  • y (int) – Vertical coordinate.
  • width (int) – Horizontal size.
  • height (int) – Vertical size.
set_stencil_reference(reference)

Set the reference stencil value for this render pass.

Parameters:reference (int) – The reference value.
set_viewport(x, y, width, height, min_depth, max_depth)

Set the viewport for this render pass. The whole scene is rendered to this sub-rectangle.

Parameters:
  • x (int) – Horizontal coordinate.
  • y (int) – Vertical coordinate.
  • width (int) – Horizontal size.
  • height (int) – Vertical size.
  • min_depth (int) – Clipping in depth.
  • max_depth (int) – Clipping in depth.
write_timestamp(query_set, query_index)

TODO

class wgpu.GPURenderBundle

Subclass of GPUObjectBase

TODO: not yet available in wgpu-native

class wgpu.GPURenderBundleEncoder

Subclass of GPUProgrammablePassEncoder

TODO: not yet available in wgpu-native

finish(**parameters)

Finish recording and return a GPURenderBundle.

Parameters:label (str) – A human readable label. Optional.

Other

class wgpu.GPUCanvasContext

A context object associated with a canvas, to present what has been drawn.

canvas

The associated canvas object.

configure(**parameters)

Configures the presentation context for the associated canvas. Destroys any textures produced with a previous configuration.

Parameters:
  • device (WgpuDevice) – The GPU device object.
  • format (TextureFormat) – The texture format, e.g. “bgra8unorm-srgb”. Default uses the preferred_format.
  • usage (TextureUsage) – Default TextureUsage.OUTPUT_ATTACHMENT.
  • color_space (PredefinedColorSpace) – Default “srgb”.
  • compositing_alpha_mode (CanvasCompositingAlphaMode) – Default opaque.
  • size – The 3D size of the texture to draw to. Default use canvas’ physical size.
get_current_texture()

Get the GPUTexture that will be composited to the canvas by the context next.

NOTE: for the time being, this could return a GPUTextureView instead.

get_preferred_format(adapter)

Get the preferred swap chain format.

present()

Present what has been drawn to the current texture, by compositing it to the canvas. Note that a canvas based on WgpuCanvasBase will call this method automatically at the end of each draw event.

unconfigure()

Removes the presentation context configuration. Destroys any textures produced while configured.

class wgpu.GPUQueue

Subclass of GPUObjectBase

A queue can be used to submit command buffers to.

You can obtain a queue object via the GPUDevice.default_queue property.

on_submitted_work_done()

TODO

read_buffer(buffer, buffer_offset=0, size=None)

Takes the data contents of the buffer and return them as a memoryview.

Parameters:
  • buffer – The GPUBuffer object to read from.
  • buffer_offset (int) – The offset in the buffer to start reading from.
  • size – The number of bytes to read. Default all minus offset.

This copies the data in the given buffer to a temporary buffer and then maps that buffer to read the data. The given buffer’s usage must include COPY_SRC.

Also see GPUBuffer.map_read().

read_texture(source, data_layout, size)

Reads the contents of the texture and return them as a memoryview.

Parameters:
  • source – A dict with fields: “texture” (a texture object), “origin” (a 3-tuple), “mip_level” (an int, default 0).
  • data_layout – A dict with fields: “offset” (an int, default 0), “bytes_per_row” (an int), “rows_per_image” (an int, default 0).
  • size – A 3-tuple of ints specifying the size to write.

Unlike GPUCommandEncoder.copyBufferToTexture(), there is no alignment requirement on bytes_per_row, although in the current implementation there will be a performance penalty if bytes_per_row is not a multiple of 256 (because we’ll be copying data row-by-row in Python).

submit(command_buffers)

Submit a GPUCommandBuffer to the queue.

Parameters:command_buffers (list) – The GPUCommandBuffer objects to add.
write_buffer(buffer, buffer_offset, data, data_offset=0, size=None)

Takes the data contents and schedules a write operation of these contents to the buffer. A snapshot of the data is taken; any changes to the data after this function is called do not affect the buffer contents.

Parameters:
  • buffer – The GPUBuffer object to write to.
  • buffer_offset (int) – The offset in the buffer to start writing at.
  • data – The data to write. Must be contiguous.
  • data_offset – The byte offset in the data. Default 0.
  • size – The number of bytes to write. Default all minus offset.

This maps the data to a temporary buffer and then copies that buffer to the given buffer. The given buffer’s usage must include COPY_DST.

Also see GPUDevice.create_buffer_with_data() and GPUBuffer.map_write().

write_texture(destination, data, data_layout, size)

Takes the data contents and schedules a write operation of these contents to the destination texture in the queue. A snapshot of the data is taken; any changes to the data after this function is called do not affect the texture contents.

Parameters:
  • destination – A dict with fields: “texture” (a texture object), “origin” (a 3-tuple), “mip_level” (an int, default 0).
  • data – The data to write.
  • data_layout – A dict with fields: “offset” (an int, default 0), “bytes_per_row” (an int), “rows_per_image” (an int, default 0).
  • size – A 3-tuple of ints specifying the size to write.

Unlike GPUCommandEncoder.copyBufferToTexture(), there is no alignment requirement on bytes_per_row.

class wgpu.GPUQuerySet

Subclass of GPUObjectBase

TODO

destroy()

Destroy the queryset.

class wgpu.GPUDeviceLostInfo

An object that contains information about the device being lost.

message

The error message specifying the reason for the device being lost.

reason

The reason (enums.GPUDeviceLostReason) for the device getting lost. Can be None.

class wgpu.GPUOutOfMemoryError

Subclass of Exception

An error raised when the GPU is out of memory.

class wgpu.GPUValidationError

Subclass of Exception

An error raised when the pipeline could not be validated.

message

The error message specifying the reason for invalidation.

class wgpu.GPUCompilationInfo

TODO

messages

A list of GPUCompilationMessage objects.

class wgpu.GPUCompilationMessage

An object that contains information about a problem with shader compilation.

length

The length of the line?

line_num

The corresponding line number in the shader source.

line_pos

The position on the line in the shader source.

message

The warning/error message.

offset

Offset of …

type

The type of warning/problem.

class wgpu.GPUUncapturedErrorEvent

TODO

error

The error object.

class wgpu.GPUExternalTexture

Subclass of GPUObjectBase

Ignore this - specific to browsers.