PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Rendering and physics thread repartition

Hi all,

(I did a very canonical Win32/GDI sample to demonstrate this issue. It can be downloaded above)

erratum : the sample is bogus. I will post it again later.

I am trying to run my game rendering and physics in separate threads.
Rendering is done in the main thread while physics are processed in "child" thread.

This pseudo-code may explain better what I am doing

-> The first piece is in the main message loop (main thread)
Code:

while(1)
{
// checking for possible window message to process
if (::PeekMessage( &l;_oMessage, 0, 0, 0, PM_REMOVE ))
// Do message processing stuffs...
else
// If there was no message to process, render a single frame
l_oTheGameCore.DoRendering();
}


-> The second piece is in the "physics thread" (child thread)

Code:
DWORD WINAPI PhysicsThread(LPVOID p_pGameCore) {
GameCore *l_pGameCore = (GameCore*)p_pGameCore;
while (g_bDoPhysics)
l_pGameCore->DoPhysics();
return 0;
}


The trouble I am running in is that the system seems not to give the same CPU time to the two threads. This makes the rendering to hang (which make the displayed objects to "lag").

I am sure I am not explaining well the problem so below are some details :)

Consider a square that traverses a horizontal line on the screen at a speed of 100pixel/second.
The physics routine processes the real time position (based on system
ticks) for our square. When threaded as explained, this routine is called about 2millions times in a second(on my PC). So the square logical position is not supposed to move by more than 1 pixel at a time.
The rendering routine simply displays our square at its position. This routine is called about a thousand times in a second. So, as for physics, the square should occupy each single pixel on its trajectory.

It seems reality doesn't meet the theory because the given square moves smoothly during some pixels and then lag and "jump" 10 further pixels.

I tried synchronizing data access for the two threads (even if physics only writes and rendering only reads). Nothing changed.
I tried changing thread/process priorities. Same behaviour.
I tried on Windows CE (PPC2002 and WM5) and it's the same behaviour. The only thing that seemed to make it better is to delay the physics with a call to Sleep.

Any idea? :P

PS: The GDI sample provided only demonstrates the problem. The real program uses PocketFrog but I though it was more appropriate to post this here. So this sample does not use PF/PHAL.
It is a really bad idea to run rendering and simulation (physics) in a separate thread when you only have one processor running both... It is better to do everything in the same loop.

Multithreading in this case isn't going to make the game any faster (it will probably slow it down). Multithreading is also difficult. Why bother?
For some (relatively esoteric) handheld systems (notably the GP2X) it is worth partitioning the game code into two because they do have multiple CPUs. It's also worth considering if you're targeting the game at current/future PCs.

However, I agree with kzinti and would target a single-cored machine with a traditional single-threaded one. There's no point messing about with the extra thread synchronisation overhead if you're not gaining anything anyway.
Kzinti wrote:It is a really bad idea to run rendering and simulation (physics) in a separate thread when you only have one processor running both... It is better to do everything in the same loop.

Multithreading in this case isn't going to make the game any faster (it will probably slow it down). Multithreading is also difficult. Why bother?


Thanks for your answers Kzinti and Refractor.

I am already aware of many multithreading issues. And I now that context switching is costly. However, my main concern is not to make the game run faster as it has already been optimized. On most devices, it runs at more than 70 fps so I can accept a (small) loss in the frame rate.
The problem comes with devices such as the Acer n300. The simplest sample (a swap loop) cannot run at more than ~20fps because of its amazingly slow display.
In this case, physics are called once every 50ms (in the single-threaded mode). As my physics algorithms rely on real-time positions (based on system ticks) without interpolation, an object could have crossed an area without giving me the chance to detect a collision.

This is the reason for which I want the physics to run in a separate thread. This would allow physics to run frequently enough to be accurate.

Of course, I can also change all my physics algorithms to do interpolation but I would prefer that the multithreading solution works (as it is already implemented).

I also though of updating the screen progressively (by small pieces) while intercalating physics calls, But this leads mainly to 2 problems:
- I have no control on the screen update as the swap is in PHAL.
- It makes the solution even more complicated than adding interpolation :wink: .
Using mutltithreading won't make the screen any faster. You say you are using PocketHAL and only get 20 fps? MMmmm... Perhaps I need to tweak something for that device...

Acer n300... Is that a Pocket PC? Any chance you can post the OEM string?
Obviously it won’t make the screen faster. I think I overestimated my english :roll:, but if you give me an other chance to explain the issue; here is the “technical approach”

Consider a running man. I’ll call him Arnoldz :D.

    Arnoldz runs on a horizontal line at a given speed: V (pixel per millisecond)

    Its last known position by the physics engine is: LastX (pixel).

    The time between the last call and the next call to the physics engine is noted DeltaTick (in milliseconds - this is roughly the time spent to render a frame)


When the physics engine is called to process the new Arnoldz position NewX, he uses this formula:

    NewX = LastX + V * DeltaTick


After processing the new position, the physics does some collision detections (is Arnoldz on a bomb, a bonus or something he should react to?)

The thing is that if DeltaTick is a large number (like for the Acer n310), the difference between NewX and LastX can be too important. Important enough to “miss” a collision with an object that was between NewX and LastX.

By multithreading, I am trying to make the physics routines called often enough to keep them accurate.

I hope I managed to be understandable :wink: . I added a small PHAL sample if you want to have a look at it.

For the Acer here is a review. I will try to get you the OEM string tomorrow if you are still interested.

I know it’s a crap device, but I think that slow Pocket PC owners should also be able to play :)
Attachments:
PHAL thread sample.zip (52 KB)
Kzinti wrote:
Acer n300... Is that a Pocket PC? Any chance you can post the OEM string?


Here it is : "Acer n300 Handheld"

Hum... Can I ask you what is this used for? 8O
Marcus":1gagdpll]

Actually, there's no such device as n300, as it's a series, containing two models - n311 and n310.
It is about the cheapest VGA device on a market, and it's really slow.
"The thing is that if DeltaTick is a large number (like for the Acer n310), the difference between NewX and LastX can be too important. Important enough to “miss” a collision with an object that was between NewX and LastX."

Well, yeah so you are having typical problems with Euler integration.

http://www.devmaster.net/wiki/Integrati ... variations
in a single loop, you can just render once and run the physics thread as many times as you need, depending on the time spent so far.

I suppose somebody'd have said it in those long messages though ;)
What Kak said... You don't want to run your physics with a variable timestep. Just run the physics at the rate you need (say 30/sec) with a fixed time step.
I know that most people are not interested in the multithreading part of this post, but if you are reading this, you might be (technically) curious… So here is the solution :D

The original need: make the physics run as often as you want, regardless of what happens in your game loop.
Problem: Simply moving physics in a separate thread makes the game - terribly - lagging.

This is a very simplified view of what we want in perfect world:

Green: running render code.
Blue: running physics code.
Image

Of course, this would happen if both threads were running simultaneously but as many know, threads do NOT run simultaneously on a single CPU. The CPU simply switch “very quickly” between codes of running threads to give an illusion of simultaneity. Therefore, the following is a more realistic view of what is supposed to happen.

Image

Note: Usually physics routines are much faster than rendering ones, so the blue bars should be in fact much “thinner”. Hence, they don’t really slow rendering.

So what’s wrong? We have to take a closer look at the “very quickly”…

A piece of Windows code known as the Scheduler is responsible for deciding when to switch between threads (and which thread to grant CPU to). In order to do that, the scheduler knows how much time each thread can run before assigning the CPU to one other thread. This time-slice is called the thread quantum. And the thread quantum is by default a quite large value on Windows CE (as on XP): about 80ms.

So we end up with a more accurate view of what happens really:
Image

Now, we can easily figure out the reason for the game to “lag”. As we can see on the above figure, if the thread quantum is 80ms, the rendering thread will run about 6 times in a second ( = 1000 / (80*2)). During the time it runs, it will display the same frame regardless to the number of game loops performed! Obviously, physics can’t run during the rendering thread quantum, so no position, no object state can be updated during that time.

The thread for physics runs also about 6 times in a second. During that time, logical data are updated but not rendered.

So even with the simplest sample (as the one provided above), you get only 6 different frames displayed per second.

(note that in this post, I intentionally omitted other processes threads: in most cases they are negligible).

Ok, what’s the solution?

1) Not to use multithreading, just change the algorithms as many said here and on several other forums :roll:
2) Make the scheduler do things the way you want :twisted:

As I already spend a lot of time to debug this thing and to write this "article", so I will simply point the basics of the solution.

Windows CE being a real-time operating system (since 3.0), it allows you to control the thread quantum you want for your threads. This is the API function to call:

Code:
BOOL CeSetThreadQuantum(
HANDLE hThread,
DWORD dwTime );


For the sample provided, setting our threads quantum to 1ms is a straight forward solution to avoid the lagging problem and to guarantee high frequency calls to physics routine.

However, we are still using half of the CPU for physics which result in a significant fps loss. To avoid that, the physics routine needs to relinquish its thread quantum when it finishes its work.

A thread does that by calling the well-known API function Sleep :!:

Calling this function with duration of 0ms tells the scheduler that, the remaining time of the caller thread quantum can be granted to another thread.

Case closed :wink:
in this approach you'd need some semaphores so that the render thread and the physics thread doesn't disturb themselves.

personally I'll stick with the KISS rule ;)