SFML community forums
Help => General => Topic started by: Mills on January 19, 2020, 02:05:09 pm
-
Hi.
I'm using CSFML, and I created a c code in the main thread, which draws a sprite to a window and uses sfRenderWindow_setFramerateLimit(60).
The sprite x and y positions are taken from two global variables (SPR_X and SPR_Y).
Don't ask why I'm doing the following :P... but I created a thread which only modifies the sprite position by changing SPR_X and SPR_Y variables. The problem is, how do I sync the thread to the vsync of the main one, so that the sprite moves at 60 fps?
I used usleep(1000000/60) and it works, but you surely know what happens next... Sometimes the positions are changed in the middle of a frame, and you can see screen tearing.
Then I tried using sfRenderWindow_display() again inside the thread function. But that resulted in a black screen. So I think I must use a custom sfRenderWindow_display():
void custom_windowdisplay()
{
// Display the backbuffer on screen
//if (setActive()) m_context->display(); don't do this again!!
// Limit the framerate if needed
if (m_frameTimeLimit != Time::Zero)
{
sleep(m_frameTimeLimit - m_clock.getElapsedTime());
//m_clock.restart(); //don't restart the clock again!!
}
}
I can convert that to CSFML, But I need to get the same clock used internally for the original sfRenderWindow_display(), and also get the m_frameTimeLimit value.
How do I get the clock and the m_frameTimeLimit?.
Is there any other way to do it? I read about "mutex", but that was way complex for me to understand, and I did not make it work.
Thanks.
-
Don't ask why I'm doing the following
That would help a lot. Have you ever heard of the XY problem? ;)
If you really want to sync your update thread and your drawing thread, you could for example send a signal right after window.display() returns (in the drawing thread) to wake up the render thread. But since that involves synchronization primitives a little bit more complicated than mutexes, and that you can't make mutexes work... either spend more time learning multi-threading, or don't use threads at all.
-
Thanks Laurent.
I first tried to use the mutex functions from c, and I had some trouble with them. Now I used sfMutex functions and everything seems to work ok.
The render thread is run in the main function:
void Render(){
sfMutex_lock(GlobalMutex);
sfRenderWindow_clear(render_window, sfColor_fromRGB(0,0,0));
sfSprite_setPosition(sprite,(sfVector2f){SPR_X,SPR_Y});
sfRenderWindow_drawSprite(render_window, sprite, NULL);
sfRenderWindow_display(render_window);
sfMutex_unlock(GlobalMutex);
}
If I understand everything OK, the update thread won't be able to modify anything being read by the Render() function in the main thread, including the SPR_X and SPR_Y I defined for sprites.