# Efficient Rendering for multiple light sources

I'm building a 3D rendering engine using C++ and OpenGL.

Right now, I've added support for multiple light sources in my GLSL shaders, but I've hit a bit of a bump for my rendering methods.

I'm worried about my engines performance if it has to render a lot of objects for a lot of light sources.

The straight-forward approach would be something like this:

for every object to be rendered
closestLights []

for every light in the scene
if (light closer than all lights in closestLights)
swap furthest light from closestLights with current light

renderObject(object)


However, I'm afraid the performance of this rendering-loop will degrade quickly since when either the amount of lights or the amount of objects increases, the amount of calculations will rise even quicker.

1) Is there any way to circumvent this?

2) How is this implemented in 'real' engines?

3) How can I find the closest K lightsources to an object efficiently?

I've heard about kd-trees and octrees, but I feel like building a tree everytime I render is probably worse than what I'm thinking about doing right now.

4) I could keep an octree and a kd-tree for every object (which keeps track of all other objects), which when using (smart) pointers, could be quite efficient in terms of time (but not space?).

Is this a good approach?

I know the saying 'Premature optimization is the root of all evil', but I'm pretty sure this WILL become a problem when a game/program reaches a certain complexity/size.

• What is the expensive part of a light for your shader? Do you render a lightview for each so that you can do shadow mapping? How many lights do you have in your world? – Bram Oct 19 '17 at 21:16
• I'm currently using a basic Phong shader (ambient, diffuse, specular), but might move on to something a little more complex in the future – shmoo6000 Oct 19 '17 at 21:18
• It looks like you're performing forward rendering. For scaling to larger numbers of lights, have you considered deferred rendering or forward+? – DMGregory Oct 19 '17 at 22:01
• I have not, thx for the tip, I'll be sure to check it out – shmoo6000 Oct 20 '17 at 4:02