World coordinate in fragment shader

Hello everyone!

I wonder is there a simple way to get a world coordinate into a fragment shader? Well, I think I could get the entity’s world transform matrix and pass it into the shader as uniform value. But is there anything simpler?

I am able to get a local pixel coordinate via attribute vec3 aPosition;, so maybe you have something built-in for world (global) position, that takes into account model’s world transform (position, rotation, scale) and could output pixel’s world coordinate (so cube center on the picture below is [0, 1.25, 0] instead of [0, 0, 0] that I am getting from aPosition)?


P.S. I am completely new to GLSL and shaders :slight_smile:

Hi @Igor,

If you are working with shader chunks what you are looking for is dPositionW.

1 Like

Thank you for the answer @Leonidas!

Another noob question: how to access dPositionW from my custom frag (or vert) shader? I see it’s returned in getWorldPosition(), but trying to call it I get an error:


So I don’t think you need to do anything at all, just use the dPositionW variable wherever is required.

Example diffuse color that changes based on the pixel distance from world ZERO:

    float distance = distance(vPositionW, vec3(0.0));
    dAlbedo *= 1.0 - clamp(distance/ 10.0, 0.0, 1.0);

Edit: sorry I’ve just seen you use a custom shader, in that case that would be different, you need to calculate that value yourself in the vertex shader and pass it as varying to the pixel shader.

Here is a stackoverflow on how to do that in GLSL: