#How should I deal with the inconsistent behavior between Unity shader and standard HLSL?

1 messages · Page 1 of 1 (latest)

bright gorge
#

Could anyone teach me why unity allows code written like this?

"allows" means texture declaration is allowed in cbuffer declaration scope without error, which should be impossible, as we expand the macro it is nonsense to have a Texture2D _MainTex (and the sampler) inside cbuffer UnityPerMaterial {...} in standard HLSL.

CBUFFER_START (UnityPerMaterial)
    TEXTURE2D (_MainTex);
    SAMPLER (sampler_MainTex);
    float4 _MainTex_ST;
CBUFFER_END
unique aurora
#

I think that the shader preprocessor does take care of that and removes the texture/sampler declaration from the cbuffer.

fervent herald
bright gorge
bright gorge
# unique aurora I *think* that the shader preprocessor does take care of that and removes the te...

Yes, and I might be asking a XY problem: if it is the unity shader preprocessor muddling behind the stage, then how the hell could I learn all those implicit behaviors? Unity never gave us a complete view of its shader compiling workflow, these knowledges are all scattered in different doc pages, I might miss a LOT of things if the other day I just give up using Unity pre-defined functions/macros and write in pure hlsl.

fervent herald
#

The answer is: don't learn from third party shaders.

#

As for why that works, for starters, you should inspect the preprocessed code to see if a texture really ends up in a cbuffer.

unique aurora
#

I did actually check, forced a texture in cbuffer declaration, and checked in the compiled code: the texture was not in the final constant buffers.

I don't know myself the deep working off the different compilation stages, but I'm pretty sure one of them is responsible to move the texture out of the cbuffer.

bright gorge
# fervent herald As for why that works, for starters, you should inspect the preprocessed code to...
-- Vertex shader for "d3d11":
Constant Buffer "$Globals" (2080 bytes) on slot 0 {
  Matrix4x4 unity_MatrixVP at 1248
  Vector4 _MainTex_ST at 2064
}
...


-- Fragment shader for "d3d11":
Set 2D Texture "_MainTex" to slot 0

Constant Buffer "$Globals" (2080 bytes) on slot 0 {
  Vector2 _GlobalMipBias at 64
  Vector4 _MainLightPosition at 80
}
Constant Buffer "UnityPerMaterial" (xx bytes) on slot 1 {
  ...
}

Thank you for your advice.
But these compiled codes only shows that Unity does have the ability to handle the texture declarations beforehead, and I learn the fact that Unity could do more sneaky things than I expect.
It does not help me to make decision about the project rules like following Unity shader conventions in which degrees.

fervent herald
#

You can look through the macros source code. It's likely that unity excludes the texture somewhere.

#

But in general, just don't put textures in a cbuffer. Nothing really requires you to do it.