In simple case by steps:
- Set the camera at the point where the ‘shadow source’ is and aim the camera in the desired direction. Camera is an abstract concept, in 3d graphics it is matrices.
- Render the view from this camera on all objects that cast a shadow, but put in the texture is not a picture, but the distance from the source of the shadow to the point of the object.
https://github.com/Dragosha/defold-light-and-shadows/blob/main/light_and_shadows/materials/shadow/shadow.fp#L16 - Get a texture with a ‘depth map’ in the ‘shadow source’ coordinate system or shadowmap as a result.
https://github.com/Dragosha/defold-light-and-shadows/blob/main/light_and_shadows/light_and_shadows.lua#L142 - Calculate a special matrix of our camera ‘shadow source’, multiplying by which we can translate any coordinate of the world into the coordinate system of the camera ‘shadow source’.
https://github.com/Dragosha/defold-light-and-shadows/blob/main/light_and_shadows/light_and_shadows.lua#L107 - Switch to a regular camera and render the world again, but in its whole form. In the shader we pass the texture with shadowmap and a special matrix from the previous points.
- In the vertex shader we translate 3d coordinates of the vertex into 2d coordinates on the screen. And additionally we translate into 2d coordinates in the shadowmap (multiplied by the special matrix).
https://github.com/Dragosha/defold-light-and-shadows/blob/main/light_and_shadows/materials/model/model.vp#L33 - In the fragment shader we compare the depth of our fragment with the value from the shadowmap texture. And this is where the ‘magic’ happens. If the value is greater, then our fragment was far away from the ‘shadow source’ than some other fragment, i.e. it is in the shadow. Something was nearer to the light bulb and we colour this pixel with the shadow in mind. This is what we will find out in step 2. If the value is smaller, it means that our pixel does not overshadow any object and it is in the light zone.
https://github.com/Dragosha/defold-light-and-shadows/blob/main/light_and_shadows/materials/model/model.fp#L73 - Going for a beer to rethink the above.