Binding Null resources

I encountered an error today about “Variable not found” in kernel validation. It turns out I was binding a null buffer and texture because a certain rendering feature was turned off. These resources were never actually accessed by the kernel program because it was guarded by an if statement that branches based on whether the feature was on or off.

Direct3D lets you bind null textures/buffers to input slots. Is there a way in optix? The workaround I did was just create a dummy buffer with one element and a 1x1 texture to use when the feature is off.

The reason I don’t always create these resources is because the data might never be there. It is based on a scene configuration.

rtBuffer and rtTextureSampler variables in device code must always be initialized or validation fails.

Buffers can be initialized with a buffer object of null size (if it is not an OpenGL interop buffer, that doesn’t allow null size buffers) and the size (in elements) can be checked with the size() function in device code.

TextureSamplers in device code must always be initialized. But you don’t need them anymore, see below.

Now, what you’re asking for is possible with bindless buffers and bindless textures.

Both are simple integer IDs in device code and there is an RT_BUFFER_ID_NULL and an RT_TEXTURE_ID_NULL which can be used to check at runtime if a bindless buffer ID or a bindless texture ID is actually present.
Find the enums in the optix_declarations.h header.
There are also bindless callable programs IDs which have RT_PROGRAM_ID_NULL.

It’s not recommended to use TextureSamplers in device code directly anymore, because not all of the texture targets and lookup functions offered by CUDA are exposed in OptiX directly. But that is possible with bindless textures and the rtTex*(id, …) intrinsics.

More explanations here:
https://devtalk.nvidia.com/default/topic/1020023/tex2dgrad-exception-when-translating-ptx-to-llvm/
https://devtalk.nvidia.com/default/topic/1038035/?comment=5273755

Example code using bindless buffers, bindless textures, and bindless callable programs dynamically in my OptiX Introduction example 07 which adds textures:
https://devtalk.nvidia.com/default/topic/998546/optix/optix-advanced-samples-on-github/
Watch the presentation and work through the examples source code. A diff between two contiguous projects shows all changes per added features.