Artist To Programmer Continued : General Shader Questions (HLSL)

Started by
2 comments, last by matt77hias 6 years, 1 month ago

Hello. I have already posted a thread about myself and what I am trying to accomplish here.  TLDR: I am a 12 year, game industry, artist moving into graphics programming, starting with hlsl shader development. I started with a basic phong shader and received a ton of help on these forums here. Now I continue my journey and am starting a new thread with general questions. I am using several books and online resources in my process but sometimes community is a great way to learn as well. 

Here we go!

Question #1: 

I understand that there are global variables and local variables. If you want to use a declared, global. variable in a function (like a vertex shader) you need to pass it in. I usually create a struct that I want to use in the vertex shader for this reason. However, I have noticed that some variables (like, worldViewProjection : WORLDVIEWPROJECTION) can be declared and used in a function without being passed into it. Why is that? What am I missing here?

 

 

 

Advertisement

Another example of a var that doesnt need to be passed into a function is texture2d. I can just sample it in the pixel shader without having it as an input. Why is that?

Short answer: scope

For more info: see http://en.cppreference.com/w/cpp/language/scope (this is for C++, though the principle is the same for HLSL).

Everything in HLSL that is bound to some register (constant buffers, textures, etc.) is contained in the outer most scope, which means you can access these values/objects from everywhere inside your HLSL code. Note that this is just the same as for functions and their scope.

If you want to minimize the number of functions using global variables, you can just pass these global variables as function parameters (e.g. you can just pass a parameter of type Texture2D< float4 >). Note that this is not possible for the shader entry point function (though, you could redirect immediately).

Similar for static const variables. Just write


static const float g_inv_pi = 0.318309886f;

somewhere outside of a HLSL function, and you can use the variable g_inv_pi everywhere.

 

At the moment, the number of scopes is pretty basic in HLSL. The "namespace" keyword, though, is supposed to be supported someday in HLSL.

🧙

This topic is closed to new replies.

Advertisement