- Online Community Forums » Programming Questions » Lighting using too much cpu

This thread is locked; no one can reply to it. rss feed Print
Lighting using too much cpu
Space cpp
Member #16,322
May 2016

Hello, I just made a small program to learn how to do a lighting system. The logic works well, but the cpu usage seems to be too high for a simple program.

Here's the drawing routine:

1void draw() 2{ 3 4 if (darkness_level > 0) 5 { 6 7 al_set_target_bitmap(darkness_bitmap); 8 al_clear_to_color( al_map_rgba_f(0,0,0,darkness_level) ); 9 al_set_blender(ALLEGRO_DEST_MINUS_SRC, ALLEGRO_ONE, ALLEGRO_ONE); 10 11 if (lights_on) 12 { 13 14 al_draw_bitmap(light_circle, mouse_x - 50, mouse_y - 50, 0); 15 16 if (background_lights) 17 { 18 19 for (int y = 0; y < 8; y++) 20 for (int x = 0; x < 10; x++) 21 al_draw_bitmap(light_circle, x * 100, y * 100, 0); 22 23 } 24 25 } 26 27 al_set_target_backbuffer(display); 28 29 } 30 31 al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA); 32 al_draw_bitmap(background, 0, 0, 0); 33 34 if (darkness_level > 0) 35 al_draw_bitmap(darkness_bitmap, 0, 0, 0); 36 37}

When the lights are turned off, the cpu usage is very low, bellow 10%; When I turn lights on it goes around 25%; If I move the mouse (which controls the coordinates of the first light) it goes around 50%. Plus, it doesn't matter if the 80 background lights are on or not, the cpu usage doesn't appear to change at all.

What I can do?

Member #11,410
October 2009

1) It's probably the cpu that's sitting there waiting for the gpu, not the cpu actually working hard.

It seems to me that you are busting your graphics card's fill rate (try at 640x480, see if performance increases)

It looks like background is sizeof(screen) which means you are sort of doing triple buffering. This allows for neat effects, but graphics cards really do not like rendering big textures like that.

Instead, since you are just blending the same content repeatedly, have your 'background' be sizeof(light_circle), draw at 0,0 then draw 'background' where you need it to the back buffer, and draw empty rectangles with color (0,0,0,darkness) to fill the gaps.

Actually I don't think you need to clear and redraw the 'background' target every time, nothing is changing on it from frame to frame. Only need to redraw it when darkness changes.

That might not work, I'm still not 100% sure the effect you're going for. Ty also to see if shaders could help. But the main thing is you need to avoid rendering a bitmap sizeof(screen) that's very expensive; especially where non power of 2 textures are not well supported.

Space cpp
Member #16,322
May 2016

Just found the problem: it was the darkness_bitmap lacking the ALLEGRO_NO_PRESERVE_TEXTURE flag, exactly like in this topic

By the way, the background bitmap was just for testing purposes, I am going to implement this system in the actual game now.

Thanks for the attention.

Go to: