bkaradzic / bgfx

Cross-platform, graphics API agnostic, "Bring Your Own Engine/Framework" style rendering library.
https://bkaradzic.github.io/bgfx/overview.html
BSD 2-Clause "Simplified" License
15.15k stars 1.95k forks source link

bgfx::createUniform behaviour when 2 different shader programs use the same uniform name #1905

Open UnTraDe opened 5 years ago

UnTraDe commented 5 years ago

How doesbgfx::createUniform handles a case where I have 2 separate shader programs (not different stages!) where I define SAMPLER2DARRAY(s_texSampler, 0); in one of them and SAMPLER2D(s_texSampler, 0); in the other? (in the case they also have different types)

Coming from OpenGL background glGetUniformLocation accepts both the uniform name AND the target shader. bgfx::createUniform accepts only the uniform name.

Also, the documentation state:

Uniform names are unique. It's valid to call bgfx::createUniform multiple times with the same uniform name. The library will always return the same handle, but the handle reference count will be incremented.

Can the same handle represent different uniforms in completely different shaders?

Am I missing something obvious?

goodartistscopy commented 5 years ago

In your case Sampler2D and Sampler2DArray are actually the same (opaque) type, so there should be no issue; they're both declared as UniformType:Enum::Sampler.

You might have 2 different shaders, but each one is used in separate draw calls. So the value of the uniform at the time of the submit() call is the one used.

You cannot call createUniform() with the same name and different types (bgfx will throw a runtime error - see bgfx_p.h#4512 [1]). Because bgfx has a limited set of supported types for uniforms anyway (samplers, mat3/4 and vec4, and arrays of the last three), this is probably not a problem most of the time.

[1] btw @bkaradzic, am I missing something with the following line a couple of lines later:

uniform.m_type = oldsize < newsize ? _type : uniform.m_type;

Don't we have _type == uniform.m_type at this point, by the previous BX_CHECK ?

UnTraDe commented 5 years ago

@goodartistscopy So the same bgfx::UniformHandle is "translated" into something different depends on the program used for bgfx::submit?

goodartistscopy commented 5 years ago

Translated is not the right word, more like reused. You create the uniform once so its type is fixed for all programs where it's used (cannot be a sampler in one and vec4 in another). But again no "translation" is necessary for Sampler2D and Sample2DArray, they're both just Samplers.