---
title: "HLSL InterlockedAdd on RWTexture2D without vk::image_format"
url: https://recursiveai.org/oneshader/cookbook/hlsl-rwtexture2d-uint-atomics-without-image-format/
description: "Compile HLSL InterlockedAdd on RWTexture2D<uint> without vk::image_format. See OneShader infer R32ui and emit a SPIR-V texel atomic for Vulkan."
version: "1.7.3"
---

# HLSL InterlockedAdd on RWTexture2D without vk::image_format

**OneShader** is a free, open-source HLSL compiler library for .NET from Recursive AI. MIT or Apache-2.0.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneShader) · [GitHub](https://github.com/recursive-ai-oss/oneshader-csharp) · [Docs](https://recursiveai.org/oneshader/docs/) · [Download example (.zip)](https://recursiveai.org/oneshader/cookbook/hlsl-rwtexture2d-uint-atomics-without-image-format/hlsl-rwtexture2d-uint-atomics-without-image-format.zip)

OneShader infers `r32ui` for an atomic add to an `RWTexture2D<uint>` texel in Vulkan.
This example needs OneShader 1.7.3 or later.

```shell
dotnet add package RecursiveAI.OneShader
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```hlsl
RWTexture2D<uint> Counts : register(u0);
[shader("compute")] [numthreads(4, 1, 1)]
void CSMain() {
    InterlockedAdd(Counts[uint2(0, 0)], 1u);
}
```

Save this as `Counter.hlsl`, or use the copy in the zip. The program writes `counter.spv` and prints the inferred format without dispatching the shader.

[The example](https://recursiveai.org/oneshader/cookbook/hlsl-rwtexture2d-uint-atomics-without-image-format/hlsl-rwtexture2d-uint-atomics-without-image-format.zip) is the full program below: unzip it and `dotnet run`.

## The full program

The program compiles the shader and writes `counter.spv` first.
The optional verification reads the format from `OpTypeImage`
and looks for `OpImageTexelPointer` and `OpAtomicIAdd`.
Those instructions get a pointer to the texel and perform the atomic add.

```csharp
using System.Buffers.Binary;
using OneShader;

var result = ShaderCompiler.CompileFile("Counter.hlsl",
    new CompileOptions { Targets = [CompileTarget.SpirV] });
if (!result.Success)
    throw new Exception(string.Join("\n", result.Diagnostics));
byte[] shader = result.Find("CSMain", CompileTarget.SpirV)!
    .ToArray();
File.WriteAllBytes("counter.spv", shader);
Console.WriteLine("Wrote counter.spv");

// Optional verification: inspect the compiled SPIR-V.
// Instructions start after the five-word header.
bool texelPointer = false, atomicAdd = false;
string? imageFormat = null;
for (int offset = 20; offset < shader.Length;)
{
    uint instruction = Word(offset);
    uint opcode = instruction & 0xffff;
    if (opcode == 25) // OpTypeImage; Image Format is operand 8.
        imageFormat = Word(offset + 32) switch
        {
            33 => "R32ui",
            24 => "R32i",
            _ => null
        };
    texelPointer |= opcode == 60; // OpImageTexelPointer
    atomicAdd |= opcode == 234;   // OpAtomicIAdd
    offset += (int)(instruction >> 16) * 4;
}
if (imageFormat is null || !texelPointer || !atomicAdd)
    throw new InvalidOperationException("Expected a typed image atomic add.");

Console.WriteLine($"OpTypeImage format: {imageFormat}");
Console.WriteLine("Found OpImageTexelPointer and OpAtomicIAdd");

uint Word(int offset) =>
    BinaryPrimitives.ReadUInt32LittleEndian(shader.AsSpan(offset));
```

```text
Wrote counter.spv
OpTypeImage format: R32ui
Found OpImageTexelPointer and OpAtomicIAdd
```

If you specify an incompatible image format explicitly, OneShader rejects the atomic with `OSH0314`; it does not silently replace your format.

## Variations

For a signed counter, replace the texture declaration and use an `int` increment inside `CSMain`:

```hlsl
// Global declaration:
RWTexture2D<int> Counts : register(u0);

// Inside CSMain:
InterlockedAdd(Counts[uint2(0, 0)], 1);
```

```text
Wrote counter.spv
OpTypeImage format: R32i
Found OpImageTexelPointer and OpAtomicIAdd
```

## Related recipes

- [HLSL InterlockedAdd on buffers](https://recursiveai.org/oneshader/cookbook/hlsl-interlockedadd/)
- [Compile HLSL to SPIR-V](https://recursiveai.org/oneshader/cookbook/hlsl-to-spirv/)

## The short answer

Declare `RWTexture2D<uint>` and pass the indexed texel directly to `InterlockedAdd`, as in `InterlockedAdd(Counts[uint2(0, 0)], 1u)`. OneShader infers `r32ui` for that unsigned atomic destination and emits `R32ui` in SPIR-V. Use `RWTexture2D<int>` for `r32i` (`R32i` in SPIR-V). The format is inferred in the shader; your Vulkan host still needs to bind an image view with a matching format.

## How do you use InterlockedAdd on an RWTexture2D in HLSL?

The first argument must be the writable texel, not a local variable that holds a copy of it. The second argument is the increment. Each invocation in the example adds `1u` to coordinate `(0, 0)`. An ordinary load, add and store could lose an increment if two invocations read the same old value. [`InterlockedAdd`](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/interlockedadd) performs the update atomically, and its optional third argument receives the value before that invocation’s update. The intrinsic itself does not act as a memory barrier. If a later pass consumes the updated image, it still needs synchronization with the dispatch that wrote it.

## Why does InterlockedAdd fail to compile for Vulkan?

Leave the attribute off to infer the format, or specify a matching format.
A four-channel format doesn’t work here: each texel holds one 32-bit unsigned integer.

For the unsigned example, bind a storage image view with `VK_FORMAT_R32_UINT`. For the signed variation use `VK_FORMAT_R32_SINT`. Check that the format and tiling you intend to use support `VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT` and create the image with `VK_IMAGE_USAGE_STORAGE_BIT`. See the Vulkan references for [format feature flags](https://docs.vulkan.org/refpages/latest/refpages/source/VkFormatFeatureFlagBits.html) and [storage image descriptors](https://docs.vulkan.org/refpages/latest/refpages/source/VkDescriptorType.html).

Bind the view to set 0, binding 0 for this shader and initialize the texel before using it as a counter. An inferred shader format doesn’t allocate, clear, or bind the image. The C# download inspects the compiler output only; it doesn’t test image format support on your device or read back a counter value.
