Applying scene ambient color to shader material

I’m confused about applying the scene’s ambientColor to a shader material:

varying vec2 vUV;

uniform vec3 ambientColor;
uniform sampler2D sourceTexture;

void main()
    vec4 tColor = texture2D(sourceTexture, 1.0 - vUV);
    gl_FragColor = vec4(tColor.x * ambientColor.x, tColor.y * ambientColor.y, tColor.z * ambientColor.z, 1.0);


this works mostly, but when Chrome is hidden at creation of the scene ‘ambientColor’ remains 0.0 even if it is set to 1 at render time when visible (so the material remains black).

What is a better way to apply the ambientColor and keep it up to date?

Why don’t you store the ambientColor in a variable and set it from the variable instead?

because I don’t know what that would look like :wink:

You can create for example a function like this and you don’t need a variable to store the ambientColor

    private _changeSceneAmbientColor(color: BABYLON.Color3) {
        this._scene.ambientColor = color
        this._shaderMaterial.setColor3("color", color)

hm I don’t really see how that helps. If that would work, why doesn’t my code work?

Are you reusing an existing ‘color’ shader-variable? if so, I want to give the material its own color as well.

I can’t see your code thus I can’t tell you.

1 Like

You don’t need to read the color from the scene…

You can also simply in shaderMaterial.effect.onApply observable always bind it :slight_smile: there is a clever cache in Babylon which will prevent it to flow to the GPU if the value did not change


I forgot to add ambientColor to the list of uniforms. I have no idea why it worked almost all of the time, but I won’t make that mistake again :slight_smile:

edit: the following is not optimal after all.
I didn’t find your onApply suggestion (getEffect() was giving undefined), but this worked:

baseMaterial.onBindObservable.add(() => {
1 Like

actually… I went back to my original observable: onBeforeRenderObservable, because otherwise there was again a moment where the material is completely black while the rest of the scene is fading in!

1 Like

There are many ways to achieve your goal. As I said it’s impossible to tell you why do you get a black material without seeing your code. However I’m glad you managed it to work! :sunglasses: :vulcan_salute:

1 Like