Getting rid of Tex2D macros
Getting rid of Texture2D/Sample macros
In foreseeable future, some macros like all variations of CreateTexture2D
might become obsolete. In this article you'll see a simple example how can you use Texture2D and SamplerState in your shader code to avoid using CreateTexture2D
/ Tex2DS
macros.
CreateTexture2D to Texture2D, Tex2DS to Sample()
Currently, most shaders use CreateTexture2D
or CreateTexture2DWithoutSampler
macros to create a new texture variable, and then Tex2DS
to sample it inside the main pixel shader function. This is how code usually looks like:
Instead of using CreateTexture2D
, you can simply create a new Texture2D variable using native HLSL features and add the annotation like in previous example:
And then instead of sampling your new Texture2D using Tex2D
/Tex2DS
macro, simply use .Sample( SamplerState, UV )
. In this code example, we will use built-in sampler state g_sAniso
, so you won't need to create a new sampler.
In this code example, we're using g_sAniso
as a sampler. This is one of built-in samplers that are always available, in most cases that's all what you will need for your shader. If you're looking for a full list of pre-defined samplers, or more details about how sampler states work, check the documentation for Sampler States in s&box docs.
If you can't find a built-in sampler that meets your requirements, you can create your own. For example, we need a sampler with AddressU
and AddressV
set to CLAMP
, and point filtering enabled. Before the MainPs
block, declare a new ShaderState variable and set up sampler states in the annotation:
In MainPs
block, you can now sample your Texture2D object using a new sampler like this:
Other examples
If you are using Texture2D arrays, approach to replace macros with native HLSL code will be almost identical. Instead of CreateTexture2DArray
macro, declare a new object Texture2DArray name
. To sample a Texture2DArray object, do .Sample( sampler, uv.xyz )
.
If you're working with Texture2DMS, CreateTexture2DMS
macro will be just Texture2DMS<float> name
. Don't forget about including annotations to your Texture2D declarations.
But why?
Most IDEs do not understand these macros, and they can make things more confusing for beginners. These macros exist in engine's code since very early days of Source 2 and apparently were required back when it had to compile stuff for DX9, DX11 and OpenGL.
Instead of fiddling with CreateTexture2DWithoutSampler
, Tex2DS
and other macros, you can just use <object>.Sample( sampler, uv )
function for all types of Texture2Ds, and IDEs will understand it. s&box has a bunch of built-in samplers so in most cases you won't need to create a new sampler state for every shader, but even if you'll need to do this, it's very easy.