Metadata-Version: 2.4
Name: compushady
Version: 1.0.0a3
Summary: Run GPU compute shaders from Python on D3D12, Vulkan, Metal and WebGPU
Home-page: https://github.com/rdeioris/compushady
Author: Roberto De Ioris
License: MIT
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Rust
Classifier: License :: OSI Approved :: MIT License
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.6
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: author
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: license-file
Dynamic: requires-python
Dynamic: summary

# compushady

Run GPU compute shaders (and graphics, mesh and ray tracing pipelines) from Python, Rust or the
browser, with a tiny API.

![compushadyMandlebrot](https://raw.githubusercontent.com/rdeioris/compushady/main/compushady_mandlebrot.gif "compushady Mandlebrot")

The Mandelbrot animated gif above has been generated by compushady itself: [examples/mandlebrot_gif.py](https://github.com/rdeioris/compushady/blob/main/examples/mandlebrot_gif.py).
If you are looking for something cool, try this naive pong implementation: [examples/pong.py](https://github.com/rdeioris/compushady/blob/main/examples/pong.py).

Join the Discord server for support: https://discord.gg/2WvdpkYXHW

Consider sponsoring the project by becoming a patron: https://www.patreon.com/rdeioris

## Features

* **Four GPU backends:** `d3d12` (Windows), `vulkan` (Windows, Linux, Android, and macOS through
  MoltenVK), `metal` (macOS, iOS) and `wgpu` (everywhere wgpu runs, plus WebGPU in browsers).
* **Shaders in HLSL, WGSL or GLSL**, compiled for the current backend: DXIL, SPIR-V, MSL or WGSL.
  HLSL goes through Microsoft's DXC, which ships inside the wheels. WGSL and GLSL go through naga,
  and MSL comes from SPIRV-Cross. You can also hand in precompiled SPIR-V, DXIL or MSL.
* **Resources:** buffers (raw, structured and typed), 1D/2D/3D textures with array slices and
  mip chains, samplers, and explicit memory heaps.
* **Sparse (tiled) resources** for virtual texturing and megatextures (D3D12 and Vulkan).
* **Compute pipelines** with direct and indirect dispatches and push constants.
* **Graphics pipelines** (`Rasterizer`): vertex/pixel shaders, render targets, depth, wireframe,
  and indirect draws with GPU-side draw counts.
* **Mesh shaders**, with optional amplification shaders, and indirect mesh dispatches (D3D12,
  Vulkan, Metal 3).
* **Ray tracing** (`RayTracer`, `BLAS`, `TLAS`): raygen, miss, closest hit, any hit,
  intersection (procedural AABBs) and callable shaders.
  * Native on D3D12 (DXR) and Vulkan (`VK_KHR_ray_tracing_pipeline`).
  * Emulated with inline ray queries on Metal.
  * `RayQuery` works in compute shaders as well.
* **Bindless resources**, in two flavours:
  * per pipeline (`bindless=True`);
  * an application-owned `DescriptorHeap`, read through Shader Model 6.6
    `ResourceDescriptorHeap[i]` / `SamplerDescriptorHeap[i]`.
* **Binding resources by name** (`bindings={"target": texture}`), using shader reflection.
* **Asynchronous work:** every operation has a `*_submit()` variant returning a `Fence`, and an
  `*_async()` variant for asyncio.
* **Presentation:**
  * swapchains for Win32, X11, Wayland, AppKit/UIKit (Metal layers), Android, and HTML canvases;
  * DRM/KMS to present straight to a display from a Linux console, with no X11 or Wayland.
* **Multithreading:** the GIL is released while the GPU works.
* **Python 3.6+**, through ctypes: one wheel per platform serves every Python version. No
  compiler and no numpy needed.
* **Rust crate** (`compushady`) and **JavaScript/WebAssembly** package (see [js/](https://github.com/rdeioris/compushady/blob/main/js/README.md)),
  sharing the same core.

### Backend support

| Feature | d3d12 | vulkan | metal | wgpu |
|---|---|---|---|---|
| Compute, textures, samplers, swapchain | ✅ | ✅ | ✅ | ✅ |
| Typed buffers (`Buffer<float4>`) | ✅ | ✅ | ✅ | ✅ (emulated) |
| Heaps | ✅ | ✅ | ✅ | ❌ |
| Sparse (tiled) resources | ✅ | ✅ | ❌ | ❌ |
| Push constants | ✅ | ✅ | ✅ | ✅ (if the adapter has them; not in browsers) |
| Rasterizer | ✅ | ✅ | ✅ | ✅ |
| Indirect draws / dispatches | ✅ | ✅ | ✅ | ✅ |
| GPU draw counts (`count_buffer`) | ✅ | ✅ (`VK_KHR_draw_indirect_count`) | ❌ | ❌ |
| Mesh and amplification shaders | ✅ (tier 1) | ✅ (`VK_EXT_mesh_shader`) | ✅ (Metal 3) | ❌ |
| Ray tracing pipelines | ✅ (DXR 1.1) | ✅ | ✅ (emulated) | ❌ |
| Per-pipeline bindless | ✅ | ✅ | ✅ | ❌ |
| `DescriptorHeap` (SM 6.6) | ✅ (binding tier 3) | ✅ (`VK_EXT_mutable_descriptor_type`) | ✅ (tier 2 argument buffers) | ❌ |
| KMS presentation | ❌ | ✅ (Linux) | ❌ | ❌ |

When a device lacks a feature, compushady raises an error that names the missing feature. It
never fails silently. MoltenVK does not support mutable descriptors, so on macOS bindless needs
the `metal` backend.

## Quickstart

```sh
pip install compushady
```

Wheels are available for Windows x64, Linux x86_64 (manylinux_2_28) and macOS 11+ (universal2:
Apple Silicon and Intel). They include the native library and DXC. On other platforms pip builds
from source, which needs a [Rust toolchain](https://rustup.rs) (1.88 or newer). You obviously also
need a system with at least one GPU.

### Enumerate compute devices

```py
import compushady

print(compushady.available_backends())  # e.g. ['d3d12', 'vulkan', 'wgpu']
for device in compushady.get_discovered_devices():
    name = device.name
    video_memory_in_mb = device.dedicated_video_memory // 1024 // 1024
    print('Name: {0} Dedicated Memory: {1} MB'.format(name, video_memory_in_mb))
```

### Upload data to a Texture

A Texture is an object available in GPU memory. To upload data into it you need a so-called
"staging buffer": a block of system RAM that the GPU can map. The GPU copies the data from that
buffer into the texture's memory.

To sum up: to upload data to the GPU, you first write it into a mapped memory area in RAM (a
buffer), and then ask the GPU to copy it into its own memory. (This obviously assumes a discrete
GPU with on-board memory.)

```py
from compushady import Buffer, Texture2D, HEAP_UPLOAD
from compushady.formats import R8G8B8A8_UINT

# creates a 8x8 texture in GPU with the classic RGBA 8 bit format
texture = Texture2D(8, 8, R8G8B8A8_UINT)
# creates a staging buffer with the right size and in memory optimized for uploading data
staging_buffer = Buffer(texture.size, HEAP_UPLOAD)
# upload a bunch of pixels data into the staging_buffer
staging_buffer.upload(b'\xff\x00\x00\xff') # first pixel as red
# copy from the staging_buffer to the texture
staging_buffer.copy_to(texture)
```

### Reading back from GPU memory to system memory

Now that your data is in GPU memory, you can manipulate it with a compute shader. Before we get
to that, let's see how to copy data back from texture memory to system RAM. We need a buffer
again, a readback one this time:

```python
from compushady import HEAP_READBACK, Buffer, Texture2D, HEAP_UPLOAD
from compushady.formats import R8G8B8A8_UINT

texture = Texture2D(8, 8, R8G8B8A8_UINT)
staging_buffer = Buffer(texture.size, HEAP_UPLOAD)
staging_buffer.upload(b'\xff\x00\x00\xff') # first pixel as red
staging_buffer.copy_to(texture)

# do something with the texture...

# prepare the readback buffer
readback_buffer = Buffer(texture.size, HEAP_READBACK)
# copy from texture to the readback buffer
texture.copy_to(readback_buffer)

# get the data as a python bytes object (just the first 4 bytes)
print(readback_buffer.readback(4))
```

### Your first compute shader

We are going to run code on the GPU! We will start with simple logic: swap the red channel with
the green one. To do this we write an HLSL shader that takes our texture as an input/output
object:

```python
from compushady import HEAP_READBACK, Buffer, Texture2D, HEAP_UPLOAD, Compute
from compushady.formats import R8G8B8A8_UINT
from compushady.shaders import hlsl

texture = Texture2D(8, 8, R8G8B8A8_UINT)
staging_buffer = Buffer(texture.size, HEAP_UPLOAD)
staging_buffer.upload(b'\xff\x00\x00\xff')  # first pixel as red
staging_buffer.copy_to(texture)

shader = """
RWTexture2D<uint4> texture : register(u0);
[numthreads(2, 2, 1)]
void main(int3 tid : SV_DispatchThreadID)
{
    uint4 color = texture[tid.xy];
    uint red = color.r;
    color.r = color.g;
    color.g = red;
    texture[tid.xy] = color;
}
"""
compute = Compute(hlsl.compile(shader), uav=[texture])
compute.dispatch(texture.width // 2, texture.height // 2, 1)

readback_buffer = Buffer(texture.size, HEAP_READBACK)
texture.copy_to(readback_buffer)

# get the data as a python bytes object (just the first 8 bytes)
print(readback_buffer.readback(8))
```

## API

This section covers the compushady API in detail, class by class. The [examples/](https://github.com/rdeioris/compushady/tree/main/examples)
folder has a runnable script for nearly every feature.

### Backends and devices

The backend is chosen at import time: the platform default (`d3d12` on Windows, `metal` on macOS,
`vulkan` elsewhere), or the one set in the `COMPUSHADY_BACKEND` environment variable or with
`compushady.config.set_backend(name)` before the first resource is created.

```sh
COMPUSHADY_BACKEND=wgpu python3 your_gpu_app.py
```

* `compushady.available_backends()`: the backends compiled into this build
* `compushady.get_backend()`: the backend module in use (`.name`)
* `compushady.config.set_debug(True)`: enables the validation layers and prints their messages
  at exit

### compushady.Device

This class represents a compute device (generally a GPU) on your system.

A system can have multiple devices. By default compushady picks a hardware device, preferring
discrete GPUs and then the one with the most dedicated memory. You are free to pass a specific
`device=` whenever you create a resource or a pipeline.

You can get the list of devices with `compushady.get_discovered_devices()`, or retrieve the
current "best" one with `compushady.get_best_device()`.

A compushady.Device object has the following fields:

* `name`: a string with the device description
* `backend`: the name of the backend driving it
* `dedicated_video_memory`: the amount (in bytes) of on-board (GPU) memory
* `dedicated_system_memory`: the amount of system memory the OS has dedicated to the GPU (generally meaningful only on Windows)
* `shared_system_memory`: the amount of system memory usable by the device (GPU)
* `vendor_id`: an integer representing the vendor id code
* `device_id`: an integer representing the device id code
* `is_hardware`: True if it is a hardware device (not an emulated one)
* `is_discrete`: True if it is a discrete adapter (a dedicated GPU)
* `mesh_shader_limits`: the mesh pipeline limits, or None when the device has no mesh shaders

`compushady.get_current_device()` returns the GPU device currently in use. You can switch it
with `compushady.set_current_device(index)`, where `index` is the position of one of the
elements returned by `compushady.get_discovered_devices()`. You can also choose the device from
the command line with the `COMPUSHADY_DEVICE` environment variable:

```sh
COMPUSHADY_DEVICE=2 python3 your_gpu_app.py
```

### compushady.Buffer

This class represents a resource accessible by the GPU, living in system RAM or in dedicated GPU
memory. Buffers are generic blobs of data: plain storage for your shaders, or staging/readback
buffers when dealing with textures.

When you create a Buffer you specify its size in bytes and, optionally, the type of memory it
uses:

* `HEAP_DEFAULT`: GPU memory
* `HEAP_UPLOAD`: system memory optimized for writing
* `HEAP_READBACK`: system memory optimized for reading

```python
import compushady

buffer_in_gpu = compushady.Buffer(64)
buffer_in_gpu2 = compushady.Buffer(128, compushady.HEAP_DEFAULT)
staging_buffer = compushady.Buffer(64, compushady.HEAP_UPLOAD)
readback_buffer = compushady.Buffer(256, compushady.HEAP_READBACK)
```

* Buffers created with HEAP_UPLOAD expose:
  * `upload(data, offset=0)`
  * `upload2d(data, pitch, width, height, bytes_per_pixel)`
  * `upload_chunked(data, stride, filler)`: appends `filler` after every `stride` bytes of
    `data`, for example to pad `float3` arrays to 16 bytes per element
* Buffers created with HEAP_READBACK expose:
  * `readback(size=0, offset=0)`: returns bytes
  * `readback(bytearray_or_memoryview, offset=0)`: fills an existing buffer
  * `readback2d(pitch, width, height, bytes_per_pixel)`
* Every buffer exposes the `size` property, returning its size in bytes.

Buffers can also be `structured` or `formatted` (typed):

```hlsl
struct Data
{
    uint field0;
    float field1;
};
RWStructuredBuffer<Data> buffer: register(u0);
[numthreads(1, 1, 1)]
void main()
{
    buffer[0].field0 = 1;
    buffer[0].field1 = 2.0;
    buffer[1].field0 = 4;
    buffer[1].field1 = 4.0;
}
```

You create a "structured" buffer by passing the `stride` option with the size of the structure:

```py
# will create a buffer of 16 bytes, divided in two structures of 8 bytes each (the struct Data)
structured_buffer = Buffer(size=16, stride=8)
```

Or you can use a typed buffer:

```hlsl
RWBuffer<float4> buffer: register(u0);
[numthreads(1, 1, 1)]
void main()
{
    buffer[0] = float4(1, 2, 3, 4);
    buffer[1] = float4(5, 6, 7, 8);
}
```

For which you specify the format parameter:

```py
# will create a buffer of 32 bytes, divided in two 16 bytes blocks, each one representing 4 32bits float values
typed_buffer = Buffer(size=32, format=compushady.formats.R32G32B32A32_FLOAT)
```

### compushady.Texture2D

A Texture2D object is a two-dimensional (width and height) texture living in GPU memory. You can
read and write it from your shaders, render to it, or present it to a Swapchain. To create a
Texture2D object you specify its width, height and pixel format:

```python
from compushady import Texture2D
from compushady.formats import R8G8B8A8_UINT
texture = Texture2D(1024, 1024, R8G8B8A8_UINT)
```

Texture memory is always on the GPU, so whenever your program needs to read or write a texture's
texel data, you need a staging or a readback buffer.

### compushady.Texture1D and compushady.Texture3D

They work exactly like Texture2D. Texture1D is one-dimensional (height=1). Texture3D is
three-dimensional: think of it as a stack of slices, each one a two-dimensional texture. For
Texture3D you pass an additional parameter, the depth, which is the number of slices:

```python
from compushady import Texture3D
from compushady.formats import R8G8B8A8_UINT
texture = Texture3D(1024, 1024, 4, R8G8B8A8_UINT) # you can see it as 4 1024x1024 textures
```

All the texture types expose the following properties:

* `width`, `height`, `depth`
* `row_pitch`: bytes per line in a staging/readback buffer
* `size`: the texture's size in bytes in a staging/readback buffer
* `slices`: array slices (Texture1D and Texture2D)
* `mips`: mip levels

### Texture arrays and mips

Texture1D and Texture2D accept `slices=N` to make a texture array (`Texture2DArray<float4>` in
HLSL). Every texture accepts `mips=N`; pass `mips=0` for the whole chain down to 1x1.

```py
texture = Texture2D(512, 512, R8G8B8A8_UNORM, mips=0)  # 10 levels
level1 = texture.mip_view(1)  # bind a single level as SRV, UAV or render target
staging = Buffer(texture.get_mip_size(1), HEAP_UPLOAD)
staging.copy_to(texture, dst_mip=1)
```

`get_mip_row_pitch(mip)` and `get_mip_size(mip)` give each level's layout in a buffer. You can
generate a mip chain with a compute shader that reads `texture.mip_view(i)` and writes
`texture.mip_view(i + 1)`.

### Copies

`resource.copy_to(destination, ...)` copies between any two resources. Keyword arguments select
a region:

* `size`, `src_offset`, `dst_offset`: bytes, for buffers
* `width`, `height`, `depth`: the extent of the texture region
* `src_x/y/z`, `dst_x/y/z`: texel offsets
* `src_slice`, `dst_slice`, `src_mip`, `dst_mip`: array slice and mip level

### compushady.Compute

To build a Compute object (the one running the compute shader), you need, obviously, a shader blob
(you can build one with `compushady.shaders.hlsl.compile`), plus the resources (buffers and
textures) the shader works on.

compushady uses the DirectX 12 naming conventions:

* `CBV` (Constant Buffer View): constant buffers, generally small amounts of data that do not
  change while the compute shader runs
* `SRV` (Shader Resource View): buffers and textures the shader reads
* `UAV` (Unordered Access View): buffers and textures the shader writes

This is a quick Compute object implementing a copy from one texture (the SRV, filled with random
data uploaded through a buffer) to another (the UAV), doubling the pixel values:

```py
from compushady import HEAP_UPLOAD, Buffer, Texture2D, Compute
from compushady.formats import R8G8B8A8_UINT
from compushady.shaders import hlsl
import random

source_texture = Texture2D(512, 512, R8G8B8A8_UINT)
destination_texture = Texture2D(512, 512, R8G8B8A8_UINT)

staging_buffer = Buffer(source_texture.size, HEAP_UPLOAD)
staging_buffer.upload(bytes([random.randint(0, 255) for i in range(source_texture.size)]))

staging_buffer.copy_to(source_texture)

shader = """
Texture2D<uint4> source : register(t0);
RWTexture2D<uint4> destination : register(u0);

[numthreads(8,8,1)]
void main(uint3 tid : SV_DispatchThreadID)
{
    destination[tid.xy] = source[tid.xy] * 2;
}
"""

compute = Compute(hlsl.compile(shader), srv=[source_texture], uav=[destination_texture])
compute.dispatch(source_texture.width // 8, source_texture.height // 8, 1)
```

What is that 8 value?

A compute shader runs in parallel. The `numthreads` attribute in the shader sets the size of one
thread group: how many threads (read: cores) run that code together. It is a three-dimensional
value, so the number of threads per group is x * y * z, here 64.

We want to process 512 * 512 elements (the pixels of the texture), so we launch just enough
groups to cover the whole texture. The arguments of the dispatch method are that number of
groups, again as a three-dimensional value.

If you set the arguments of dispatch to (1,1,1), only the top left 8x8 quad of the texture will
be processed.

Cool, but how can I check that everything worked?

There are tons of ways, but let's use a popular one: Pillow. Append this code after the
dispatch() call:

```py
from PIL import Image

readback_buffer = Buffer(source_texture.size, HEAP_READBACK)
destination_texture.copy_to(readback_buffer)

image = Image.frombuffer('RGBA', (destination_texture.width,
                         destination_texture.height), readback_buffer.readback())
image.show()
```

If everything goes well, a window opens with a 512x512 image of random pixel colors.

Try experimenting with different dispatch() arguments to see how the behaviour changes.

Other Compute features:

* `dispatch_indirect(buffer, offset=0)`: the group counts are 3 uint32 read from a GPU buffer
* `push_size=N` and `dispatch(x, y, z, push=bytes)`: push constants, small per-dispatch data with
  no buffer involved. In HLSL they are a `[[vk::push_constant]] ConstantBuffer<T>`, at the
  register right after the last CBV, so `b<number of cbvs>`.
* `bind_cbv(index, resource)`, `bind_srv(...)`, `bind_uav(...)`: swap a resource without
  recreating the pipeline

Note: on Vulkan any shader compiler that generates SPIR-V works with compushady. You can even
precompile your shaders, store the SPIR-V blobs in files, and pass the bytes to `Compute`.

### Binding resources by name

Instead of slot lists, every pipeline accepts `bindings={name: resource}`. The names are the ones
used in the shader, found through reflection:

```py
shader = hlsl.compile("""
cbuffer Config : register(b0) { float multiplier; };
RWTexture2D<float4> target : register(u0);
...""")
compute = Compute(shader, bindings={"Config": config, "target": texture})
compute.bind("target", other_texture)
```

Note that the compiler removes unused resources, and compushady tells you when a name is missing.
See [examples/mandlebrot_named.py](https://github.com/rdeioris/compushady/blob/main/examples/mandlebrot_named.py).

### Shaders

Every compiler returns a `ShaderBlob` (a `bytes` subclass) for the current backend, with
`entry_point`, `workgroup_size`, `binary_type` and `reflection` attached:

* `compushady.shaders.hlsl.compile(source, entry_point="main", target="cs_6_0")`: DXC. Use
  `vs_6_0`/`ps_6_0` for rasterizers, `ms_6_5`/`as_6_5` for mesh pipelines, and `cs_6_6` for
  `ResourceDescriptorHeap`. `target_type=SHADER_TARGET_TYPE_LIB` builds a ray tracing library.
* `compushady.shaders.wgsl.compile(source, entry_point="main")`: naga
* `compushady.shaders.glsl.compile(source, entry_point="main")`: naga, compute shaders only
* `compushady.shaders.msl.compile(source, grid, entry_point="main")`: Metal Shading Language
  source for the metal backend (`grid` is the threadgroup size)

DXC is loaded at run time. The wheels bundle it; otherwise set `COMPUSHADY_DXC_PATH` to the
library (or its folder). On Windows, D3D12 also needs `dxil.dll` next to `dxcompiler.dll` to sign
the shaders: compushady prefers a `dxcompiler.dll` that has one, so the DXC of the Vulkan SDK
(which has none) is only used when nothing better is found.

### compushady.Heap

By default resources (Buffers, Textures) allocate their memory automatically, based on the heap
type. If you want more control over memory allocation, you can allocate memory blocks (heaps)
yourself and then place resources in them, or in parts of them:

```py
from compushady import HEAP_UPLOAD, Buffer, Heap

heap_upload = Heap(HEAP_UPLOAD, 256 * 1024) # allocates 256k of memory
buffer0 = Buffer(
    size=256, heap_type=HEAP_UPLOAD, heap=heap_upload, heap_offset=64 * 1024
) # maps a 256 bytes buffer on heap_upload at offset 64k
buffer1 = Buffer(
    size=256, heap_type=HEAP_UPLOAD, heap=heap_upload, heap_offset=128 * 1024
) # maps a 256 bytes buffer on heap_upload at offset 128k
buffer_all = Buffer(
    size=256 * 1024, heap_type=HEAP_UPLOAD, heap=heap_upload, heap_offset=0
) # maps the whole heap in a buffer
```

Notes:

* the resource and the heap must have the same heap type
* the size of the requested resource is always checked against the heap
* textures only support HEAP_DEFAULT
* `resource.heap_size` tells you how much heap memory a resource needs

### Sparse (tiled) resources

Pass `sparse=True` to create a buffer or a texture with no memory behind it, then map heap memory
to individual tiles:

```py
texture = Texture2D(16384, 16384, R8G8B8A8_UNORM, sparse=True)
heap = Heap(HEAP_DEFAULT, 64 * 1024 * 16)
texture.bind_tile(0, 0, 0, heap, 0)  # tile (0, 0) -> the first 64k of the heap
texture.bind_tiles([(1, 0, 0, heap, 65536), (2, 0, 0, None)])  # map and unmap in one go
```

The geometry of the tiles is exposed through `tile_width/height/depth` and `tiles_x/y/z`. See
[examples/virtual_texture.py](https://github.com/rdeioris/compushady/blob/main/examples/virtual_texture.py) and [examples/megatexture.py](https://github.com/rdeioris/compushady/blob/main/examples/megatexture.py).

### compushady.Sampler

Samplers fetch texels from textures with various forms of filtering and addressing. Pass them to
pipelines with the `samplers` parameter:

```py
sampler = Sampler(
            address_mode_u=SAMPLER_ADDRESS_MODE_CLAMP,
            address_mode_v=SAMPLER_ADDRESS_MODE_CLAMP,
            address_mode_w=SAMPLER_ADDRESS_MODE_CLAMP,
            filter_min=SAMPLER_FILTER_POINT,
            filter_mag=SAMPLER_FILTER_POINT,
        )
```

You sample textures in your shader as you would in a common graphics shader. The difference is
that in compute shaders you specify the mip level yourself:

```hlsl
SamplerState sampler0;
Texture2D<float4> source;
RWTexture2D<float4> target;

[numthreads(1,1,1)]
void main(int3 tid : SV_DispatchThreadID)
{
    target[tid.xy] = source.SampleLevel(sampler0, float2(float(tid.x), float(tid.y)), 0);
}
```

* Addressing modes: `SAMPLER_ADDRESS_MODE_WRAP`, `SAMPLER_ADDRESS_MODE_MIRROR`, `SAMPLER_ADDRESS_MODE_CLAMP`
* Filters: `SAMPLER_FILTER_POINT`, `SAMPLER_FILTER_LINEAR`

### compushady.Rasterizer

A graphics pipeline: a vertex shader and a pixel shader drawing triangle lists into the `rtv`
render targets (2D textures of the same size), with an optional `dsv` depth target (a
`D32_FLOAT` texture, depth test LESS).

There are no vertex buffers. Vertex shaders read their data from SRVs, indexed by
`SV_VertexID` / `SV_InstanceID`. Back faces are culled; clockwise is the front face unless you
pass `ccw=True`.

```py
vs = hlsl.compile(source, "vs_main", "vs_6_0")
ps = hlsl.compile(source, "ps_main", "ps_6_0")
target = Texture2D(512, 512, R8G8B8A8_UNORM)
depth = Texture2D(512, 512, D32_FLOAT)
rasterizer = Rasterizer(vs, ps, rtv=[target], dsv=depth, srv=[vertices], cbv=[camera])
rasterizer.clear((0.1, 0.1, 0.1, 1.0))
rasterizer.draw(num_vertices=36, num_instances=10)
```

* `wireframe=True`: draws the triangles' edges only
* `draw_indirect(buffer, offset=0, draw_count=1, stride=16, count_buffer=None)`: 4 uint32 per
  draw. With `count_buffer`, the GPU decides how many draws run.
* `ms=` (with an optional `amplification=`) instead of `vs` makes a mesh pipeline, run with
  `dispatch_mesh(x, y, z)` or `dispatch_mesh_indirect(...)`

See [examples/rasterizer.py](https://github.com/rdeioris/compushady/blob/main/examples/rasterizer.py), [examples/rasterizer_gltf.py](https://github.com/rdeioris/compushady/blob/main/examples/rasterizer_gltf.py) and [examples/rasterizer_indirect.py](https://github.com/rdeioris/compushady/blob/main/examples/rasterizer_indirect.py).

### Ray tracing: BLAS, TLAS and RayTracer

```py
blas = BLAS(vertex_buffer, index_buffer)  # or BLAS(aabbs=boxes) for procedural geometry
tlas = TLAS([TLASInstance(blas, transform=IDENTITY, id=0, hit_group=0)])

library = hlsl.compile(source, target_type=SHADER_TARGET_TYPE_LIB)
raytracer = RayTracer(
    library,
    srv=[tlas],
    uav=[output],
    raygen="raygen",
    miss=["miss", "shadow_miss"],
    hit_groups=["closest_hit", HitGroup(closest_hit="sphere_hit", intersection="sphere")],
    callable=["checker"],
    max_payload_size=16,
    max_recursion=2,
)
raytracer.dispatch_rays(output.width, output.height, 1)
```

* `TLAS` is bound as an SRV (`RaytracingAccelerationStructure`).
* `tlas.build(instances)` rebuilds it with new transforms, up to `max_instances`.
* A TLAS can also be used from compute shaders with inline `RayQuery`.

See [examples/raytracer.py](https://github.com/rdeioris/compushady/blob/main/examples/raytracer.py) and [examples/raytracer_cubes_callable.py](https://github.com/rdeioris/compushady/blob/main/examples/raytracer_cubes_callable.py).

### Bindless

**Per pipeline:** `Compute(..., bindless=True, max_bindless=N)` (and the same on `Rasterizer`)
turns the slot lists into unbounded descriptor arrays. CBV `i` is at binding `i`, SRV `i` at
`N + i`, and UAV `i` at `2N + i`. See [examples/bindless_gallery.py](https://github.com/rdeioris/compushady/blob/main/examples/bindless_gallery.py).

**Application-owned heap (Shader Model 6.6):**

```py
heap = DescriptorHeap()
albedo = heap.add_srv(texture)       # a stable index, valid for every pipeline using the heap
output = heap.add_uav(target)
linear = heap.add_sampler(sampler)
compute = Compute(hlsl.compile(source, "main", "cs_6_6"), heap=heap, push_size=16)
compute.dispatch(64, 64, 1, push=struct.pack("III", albedo, output, linear))
```

In HLSL, read them with `ResourceDescriptorHeap[index]` and `SamplerDescriptorHeap[index]`;
the push constants are at `b0`.

* `heap.remove(index)` keeps the slot reserved until the GPU work already submitted has
  completed.
* `set_srv`/`set_uav`/`set_cbv`/`set_sampler` overwrite an index in place.

See [examples/bindless_heap.py](https://github.com/rdeioris/compushady/blob/main/examples/bindless_heap.py).

### Asynchronous work: Fence and asyncio

Every blocking operation has two non-blocking variants:

* `*_submit()`: queues the work and returns a `Fence` (`fence.done`, `fence.wait()`)
* `*_async()`: an asyncio coroutine

The operations are `dispatch`, `dispatch_indirect`, `copy_to`, `draw`, `draw_indirect`,
`dispatch_mesh`, `dispatch_rays`, `clear` and `bind_tiles`. The GPU runs submitted work in
order.

```py
fence = compute.dispatch_submit(64, 64, 1)
# ... do something else on the CPU ...
fence.wait()

async def frame():
    await compute.dispatch_async(64, 64, 1)
    await target.copy_to_async(readback)
```

### compushady.Swapchain

compushady most probably runs in a headless environment for you, but it also exposes a Swapchain
object for presenting textures in a window. To create a swapchain you pass a window handle (this
depends on the operating system), a format (generally B8G8R8A8_UNORM) and the number of buffers
(generally 3). To present a texture, call `compushady.Swapchain.present(texture, x=0, y=0)`; x
and y set where the texture is drawn. The Swapchain always waits for VSYNC.

Window handles:

* Windows: an HWND
* X11: a `(display, window)` tuple
* macOS: a CAMetalLayer from `compushady.backends.metal.create_metal_layer(nswindow)`
* Others: an explicit `(kind, display, window)` tuple, with kind one of `"win32"`, `"xlib"`,
  `"xcb"`, `"wayland"`, `"android"`, `"drm"`

`compushady.utils.create_swapchain_from_glfw(window)` handles all of this for glfw windows:

```python
import glfw
from compushady import HEAP_UPLOAD, Buffer, Texture2D
from compushady.formats import B8G8R8A8_UNORM
from compushady.utils import create_swapchain_from_glfw
import random

glfw.init()
# we do not want implicit OpenGL!
glfw.window_hint(glfw.CLIENT_API, glfw.NO_API)

target = Texture2D(256, 256, B8G8R8A8_UNORM)
random_buffer = Buffer(target.size, HEAP_UPLOAD)

window = glfw.create_window(target.width, target.height, 'Random', None, None)
swapchain = create_swapchain_from_glfw(window)

while not glfw.window_should_close(window):
    glfw.poll_events()
    random_buffer.upload(bytes([random.randint(0, 255), random.randint(
        0, 255), random.randint(0, 255), 255]) * (target.size // 4))
    random_buffer.copy_to(target)
    swapchain.present(target)

swapchain = None  # this ensures the swapchain is destroyed before the window

glfw.terminate()
```

#### Presenting without a window system (DRM/KMS)

On Linux, with the vulkan backend, `compushady.utils.create_swapchain_kms()` presents straight to
a connected display from a text console: no X11, no Wayland. Use it for kiosks, embedded boards
and similar setups. See [examples/kms_gradient.py](https://github.com/rdeioris/compushady/blob/main/examples/kms_gradient.py).

## Rust

The Python module is a thin ctypes layer over the `compushady` crate, which you can use directly:

```toml
[dependencies]
compushady = "1.0.0-alpha.3"
```

DXC is too big to ship inside a crate, so HLSL needs it at run time. The `dxc-download` feature,
on by default, fetches it at build time for Windows (x64, arm64), Linux (x86_64, aarch64) and macOS, from the compushady
GitHub releases, verified by SHA-256. The libraries are copied next to your binaries in
`target/<profile>/`, ready to ship with them. `COMPUSHADY_DXC_DOWNLOAD=0` (or an offline build)
skips the download: then point `COMPUSHADY_DXC_PATH` at a DXC release that includes `dxil.dll`.

```rust
use compushady::*;

let device = Device::best(BackendKind::platform_default())?;
let shader = shaders::hlsl(
    "RWStructuredBuffer<uint> data : register(u0);
     [numthreads(8, 1, 1)]
     void main(uint3 id : SV_DispatchThreadID) { data[id.x] = id.x * 2; }",
    "main",
    "cs_6_0",
);
let data = device.create_buffer(BufferDesc { size: 64, stride: 4, ..Default::default() })?;
let readback = device.create_buffer(BufferDesc { size: 64, heap_type: HeapType::Readback, ..Default::default() })?;
let compute = device.create_compute(&shader, ComputeDesc { uav: &[&data], ..Default::default() })?;
compute.dispatch(2, 1, 1, &[])?;
data.copy_to(&readback, &CopyRegion::default())?;
println!("{:?}", readback.readback(0, 0)?);
```

Cargo features select the backends (`vulkan`, `d3d12`, `metal`, `wgpu`, `kms`) and the shader
compilers (`dxc`, `naga`, `spirv-cross`). All of them are on by default, as is `dxc-download`. Swapchains take any
`raw-window-handle` window: winit (`cargo run -p compushady --example red_screen`), glfw or SDL3
(`cargo run -p compushady-red-screen --bin glfw` / `--bin sdl`, see
[examples/red-screen](https://github.com/rdeioris/compushady/tree/main/examples/red-screen)). The examples in
[crates/compushady/examples](https://github.com/rdeioris/compushady/tree/main/crates/compushady/examples) run with
`cargo run -p compushady --example mandelbrot`. There is also an Android example in
[examples/android-mandelbrot](https://github.com/rdeioris/compushady/tree/main/examples/android-mandelbrot).

## JavaScript / WebAssembly

The same core, compiled to WebAssembly and running on WebGPU in the browser, with the Python API
in JavaScript form. See [js/README.md](https://github.com/rdeioris/compushady/blob/main/js/README.md).

## Dealing with backend differences

### Bindings

In HLSL you assign resources to registers/slots with 3 main concepts, cbv, srv and uav, and their
related registers (b0, t0, t1, u0, ...).

When HLSL is converted to SPIR-V, an offset is added to SRVs (1024) and UAVs (2048). So b0 maps
to SPIR-V binding 0, b1 to 1, t0 to 1024, t2 to 1026, and u0 to 2048. Samplers start at 3072.
Remember this when using SPIR-V directly.

On Metal, HLSL is first translated to SPIR-V and then to MSL with SPIRV-Cross. The bindings are
remapped to Metal's two kinds of resources, buffers and textures. The SPIR-V binding ids are
discarded; instead, starting from the lowest binding id, each resource gets the next index of
its kind, either buffer or texture. For example: binding 2048 holding a buffer becomes
buffer(1), binding 2049 holding a texture becomes texture(0), and binding 1025 holding a buffer
becomes buffer(0). The numerical order always matters!

On wgpu, every class gets its own bind group: 0 for CBVs, 1 for SRVs, 2 for UAVs, 3 for samplers.

### wgpu / WebGPU limits

* no heaps, sparse resources or bindless
* typed buffers are emulated
* texture rows are 256-byte aligned (check `row_pitch`)
* READBACK buffers can only be copied into
* push constants only where the adapter supports them, never in browsers

## Environment variables

| Variable | Meaning |
|---|---|
| `COMPUSHADY_BACKEND` | backend to use (`d3d12`, `vulkan`, `metal`, `wgpu`) |
| `COMPUSHADY_DEVICE` | index of the device to use |
| `COMPUSHADY_DXC_PATH` | DXC library (or folder) to load instead of the bundled one |
| `COMPUSHADY_DXC_DOWNLOAD` | (Rust, building) `0` skips the `dxc-download` feature's download |
| `COMPUSHADY_NATIVE_LIB` | native library to load instead of the bundled one (also used by `setup.py` to skip cargo) |
| `COMPUSHADY_DXC_DIR` | (building) folder with the DXC libraries to bundle in the wheel |

## Building from source

```sh
python scripts/fetch_dxc.py       # official DXC release for this platform
pip install .                     # runs cargo build -p compushady-capi
cargo test -p compushady          # Rust tests (COMPUSHADY_TEST_BACKEND picks the backend)
```

[Build.md](https://github.com/rdeioris/compushady/blob/main/Build.md) covers the release process (wheels for Windows, manylinux and macOS built
on local machines) and the third party libraries.

## Known issues

* Vulkan on macOS (MoltenVK) has no bindless and no ray tracing: use the metal backend.
* Metal has no sparse resources and no GPU-side draw counts.
* Ray tracing on Metal is emulated with inline ray queries: a closest hit shader can trace rays
  with a different payload type (for example shadow rays), but cannot recurse with its own.
