SWY1985 / CivOne

An open source implementation of Sid Meier's Civilization.
http://www.civone.org/
Creative Commons Zero v1.0 Universal
244 stars 49 forks source link

Prevent game freezes by moving actions in background threads #350

Closed SWY1985 closed 7 years ago

SWY1985 commented 7 years ago

Sometimes the game hangs because it is busy, and the screen (including the mouse cursor) hangs. This could be solved my moving slow tasks to a background thread.

AlexFolland commented 7 years ago

Might it be useful to call System.Threading.Thread.Sleep(1) in the main loop, to prevent busy-waiting? Are there slow tasks to do while idle, or is it doing them extremely quickly, but many times unnecessarily?

SWY1985 commented 7 years ago

The main loop is handled by OpenTK, with update events being called every 1/60th of a second. The problem is that there's certain moments that these updates take too long to fit in 1/60th of a second. Added Sleep(1) won't fix the problem, as the game is actually busy. Putting heavy tasks into seperate background threads might be a good solution. Another solution could be handling heavy tasks over multiple update moments.

AlexFolland commented 7 years ago

I don't understand what it could be busy with while idly waiting for user input. Civilization takes almost no CPU while idle. There should be no heavy tasks, except once in a while, between turns or movements. I will have to take a good look at it myself some time.

SWY1985 commented 7 years ago

I have just moved the mouse position update code to the Render event. It appears to make the cursor lag less. Can you try it?

Edit: The only thing CivOne is doing while waiting is constantly redrawing the canvas, which isn't a really expensive action. You're right, it should be smoooooth.

AlexFolland commented 7 years ago

Sure! I'll do so when I next update, after this game. I have been avoiding updating during games since they lose all progress currently.

SWY1985 commented 7 years ago

I'm hopefully able to fix load/save games this weekend...