update thread setup with a good cap
[physics.git] / src / main.cpp
index d34f420..1309824 100644 (file)
@@ -59,10 +59,15 @@ bool is_Running;
  * last_Second := stores the time of the last second, used for ups and fps
  */
 int target_UPS = 100;
+float update_Wait = 0;
 
 int ups, fps;
 int update_Count, draw_Count;
-long int last_Second;
+MICRO last_Second;
+
+const int min_wait_milli = 20;
+const int min_wait_micro = min_wait_milli * 1000;
+const float game_step    = 10;
 
 int startUpdateThread(void*);
 int startDrawThread(void*);
@@ -118,6 +123,7 @@ void run()
 
     SDL_Thread* updates = SDL_CreateThread(startUpdateThread, NULL);
 
+    // for some reason this needs to be on the main thread ...?
     startDrawThread(NULL);
 
     SDL_WaitThread(updates, NULL);
@@ -173,14 +179,25 @@ void draw()
 
 int startUpdateThread(void*)
 {
+    last_Second = tickCountMicro();
+
     while(is_Running)
     {
-        handleInput();
-        update(10);
+        MICRO time = tickCountMicro();
+            handleInput();
+            update(game_step);
+
+            updateFPSCounters();
+        time = tickCountMicro() - time;
 
-        updateFPSCounters();
+        float wait = (1000000.0 / target_UPS - time);
+        update_Wait += 0 < wait ? wait : 0;
 
-        SDL_Delay(10);
+        while(min_wait_micro < update_Wait)
+        {
+            update_Wait -= min_wait_micro;
+            SDL_Delay(min_wait_milli);
+        }
     }
 
     return 0;