I’m new to GLSL and am trying to implement my own basic set of shaders, starting with Lambert shading. I’ve looked at a bunch of examples but am stuck.
My shader draws a shadow on a sphere based on a single light source. My problem is that the shadow doesn’t update as I move the OrbitControls camera around.
The problem is that you have to transform the position of the sun light into view space (and not world space). For this, you have to update the respective uniform per animation step (assuming the light position is going to change). I’ve refactored the code a bit to make this clear.
BTW: Camera.matrixWorldInverse is nothing else than the view matrix. Multiplying a vector in world space with this matrix transforms it into the (local) coordinate system of the camera.
Thank you! I understand the difference between view space and world space better now.
Per your suggestion, I wound up doing the correction in the shader by creating vViewLightPos = (viewMatrix * vec4(lightPos, 1.0)).xyz; and using that in place of lightPos.
The problem with this approach is that your are performing the same computation for all fragments which is actually not necessary. You should do it once per frame in JavaScript and then just reuse the uniform.