Changeset - r25011:61d28a13bb41
[Not reviewed]
master
0 14 0
Patric Stout - 3 years ago 2021-02-24 14:04:41
truebrain@openttd.org
Remove: [Video] no longer draw in a thread

Drawing in a thread is a bit odd, and often leads to surprising
issues. For example, OpenGL would only allow it if you move the
full context to the thread. Which is not always easily done on
all OSes.
In general, the advise is to handle system events and drawing
from the main thread, and do everything else in other threads.
So, let's be more like other games.

Additionally, putting the drawing routine in a thread was only
done for a few targets.

Upcoming commit will move the GameLoop in a thread, which will
work for all targets.
14 files changed with 20 insertions and 408 deletions:
0 comments (0 inline, 0 general)
src/video/allegro_v.cpp
Show inline comments
 
@@ -475,15 +475,13 @@ void VideoDriver_Allegro::InputLoop()
 

	
 
void VideoDriver_Allegro::MainLoop()
 
{
 
	for (;;) {
 
		if (_exit_game) return;
 

	
 
		if (this->Tick()) {
 
			this->Paint();
 
		}
 
		this->Tick();
 
		this->SleepTillNextTick();
 
	}
 
}
 

	
 
bool VideoDriver_Allegro::ChangeResolution(int w, int h)
 
{
src/video/cocoa/cocoa_v.mm
Show inline comments
 
@@ -440,15 +440,13 @@ void VideoDriver_Cocoa::MainLoopReal()
 
			if (_exit_game) {
 
				/* Restore saved resolution if in fullscreen mode. */
 
				if (this->IsFullscreen()) _cur_resolution = this->orig_res;
 
				break;
 
			}
 

	
 
			if (this->Tick()) {
 
				this->Paint();
 
			}
 
			this->Tick();
 
			this->SleepTillNextTick();
 
		}
 
	}
 
}
 

	
 

	
src/video/sdl2_default_v.cpp
Show inline comments
 
@@ -133,28 +133,12 @@ void VideoDriver_SDL_Default::Paint()
 
	}
 
	SDL_UpdateWindowSurfaceRects(this->sdl_window, &r, 1);
 

	
 
	this->dirty_rect = {};
 
}
 

	
 
void VideoDriver_SDL_Default::PaintThread()
 
{
 
	/* First tell the main thread we're started */
 
	std::unique_lock<std::recursive_mutex> lock(*this->draw_mutex);
 
	this->draw_signal->notify_one();
 

	
 
	/* Now wait for the first thing to draw! */
 
	this->draw_signal->wait(*this->draw_mutex);
 

	
 
	while (this->draw_continue) {
 
		/* Then just draw and wait till we stop */
 
		this->Paint();
 
		this->draw_signal->wait(lock);
 
	}
 
}
 

	
 
bool VideoDriver_SDL_Default::AllocateBackingStore(int w, int h, bool force)
 
{
 
	int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
 

	
 
	_sdl_real_surface = SDL_GetWindowSurface(this->sdl_window);
 
	if (_sdl_real_surface == nullptr) usererror("SDL2: Couldn't get window surface: %s", SDL_GetError());
src/video/sdl2_default_v.h
Show inline comments
 
@@ -18,13 +18,12 @@ public:
 
	const char *GetName() const override { return "sdl"; }
 

	
 
protected:
 
	bool AllocateBackingStore(int w, int h, bool force = false) override;
 
	void *GetVideoPointer() override;
 
	void Paint() override;
 
	void PaintThread() override;
 

	
 
	void ReleaseVideoPointer() override {}
 

	
 
private:
 
	void UpdatePalette();
 
	void MakePalette();
src/video/sdl2_opengl_v.cpp
Show inline comments
 
@@ -68,13 +68,12 @@ const char *VideoDriver_SDL_OpenGL::Star
 
	 * so all buffers are allocated correctly. */
 
	int w, h;
 
	SDL_GetWindowSize(this->sdl_window, &w, &h);
 
	this->ClientSizeChanged(w, h, true);
 

	
 
	SDL_GL_SetSwapInterval(GetDriverParamBool(param, "vsync") ? 1 : 0);
 
	this->draw_threaded = false;
 

	
 
	return nullptr;
 
}
 

	
 
void VideoDriver_SDL_OpenGL::Stop()
 
{
src/video/sdl2_opengl_v.h
Show inline comments
 
@@ -33,14 +33,12 @@ protected:
 
	bool AllocateBackingStore(int w, int h, bool force = false) override;
 
	void *GetVideoPointer() override;
 
	void ReleaseVideoPointer() override;
 
	void Paint() override;
 
	bool CreateMainWindow(uint w, uint h, uint flags) override;
 

	
 
	void PaintThread() override {}
 

	
 
private:
 
	void  *gl_context;  ///< OpenGL context.
 
	uint8 *anim_buffer; ///< Animation buffer from OpenGL back-end.
 

	
 
	const char *AllocateContext();
 
	void DestroyContext();
src/video/sdl2_v.cpp
Show inline comments
 
@@ -20,13 +20,12 @@
 
#include "../core/geometry_func.hpp"
 
#include "../fileio_func.h"
 
#include "../framerate_type.h"
 
#include "../window_func.h"
 
#include "sdl2_v.h"
 
#include <SDL.h>
 
#include <mutex>
 
#ifdef __EMSCRIPTEN__
 
#	include <emscripten.h>
 
#	include <emscripten/html5.h>
 
#endif
 

	
 
#include "../safeguards.h"
 
@@ -47,17 +46,12 @@ void VideoDriver_SDL_Base::CheckPaletteA
 
	if (_cur_palette.count_dirty == 0) return;
 

	
 
	this->local_palette = _cur_palette;
 
	this->MakeDirty(0, 0, _screen.width, _screen.height);
 
}
 

	
 
/* static */ void VideoDriver_SDL_Base::PaintThreadThunk(VideoDriver_SDL_Base *drv)
 
{
 
	drv->PaintThread();
 
}
 

	
 
static const Dimension default_resolutions[] = {
 
	{  640,  480 },
 
	{  800,  600 },
 
	{ 1024,  768 },
 
	{ 1152,  864 },
 
	{ 1280,  800 },
 
@@ -562,25 +556,12 @@ const char *VideoDriver_SDL_Base::Start(
 

	
 
	const char *dname = SDL_GetCurrentVideoDriver();
 
	DEBUG(driver, 1, "SDL2: using driver '%s'", dname);
 

	
 
	MarkWholeScreenDirty();
 

	
 
	this->draw_threaded = !GetDriverParamBool(parm, "no_threads") && !GetDriverParamBool(parm, "no_thread");
 
	/* Wayland SDL video driver uses EGL to render the game. SDL created the
 
	 * EGL context from the main-thread, and with EGL you are not allowed to
 
	 * draw in another thread than the context was created. The function of
 
	 * draw_threaded is to do exactly this: draw in another thread than the
 
	 * window was created, and as such, this fails on Wayland SDL video
 
	 * driver. So, we disable threading by default if Wayland SDL video
 
	 * driver is detected.
 
	 */
 
	if (strcmp(dname, "wayland") == 0) {
 
		this->draw_threaded = false;
 
	}
 

	
 
	SDL_StopTextInput();
 
	this->edit_box_focused = false;
 

	
 
	return nullptr;
 
}
 

	
 
@@ -628,117 +609,50 @@ void VideoDriver_SDL_Base::LoopOnce()
 
		 * the browser. So if _exit_game goes true, the main loop ends (the
 
		 * cancel call), but we still have to call the cleanup that is
 
		 * normally done at the end of the main loop for non-Emscripten.
 
		 * After that, Emscripten just halts, and the HTML shows a nice
 
		 * "bye, see you next time" message. */
 
		emscripten_cancel_main_loop();
 
		MainLoopCleanup();
 
		emscripten_exit_pointerlock();
 
		/* In effect, the game ends here. As emscripten_set_main_loop() caused
 
		 * the stack to be unwound, the code after MainLoop() in
 
		 * openttd_main() is never executed. */
 
		EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
 
		EM_ASM(if (window["openttd_exit"]) openttd_exit());
 
#endif
 
		return;
 
	}
 

	
 
	if (VideoDriver::Tick()) {
 
		if (this->draw_mutex != nullptr && !HasModalProgress()) {
 
			this->draw_signal->notify_one();
 
		} else {
 
			this->Paint();
 
		}
 
	}
 
	this->Tick();
 

	
 
/* Emscripten is running an event-based mainloop; there is already some
 
 * downtime between each iteration, so no need to sleep. */
 
#ifndef __EMSCRIPTEN__
 
	this->SleepTillNextTick();
 
#endif
 
}
 

	
 
void VideoDriver_SDL_Base::MainLoop()
 
{
 
	if (this->draw_threaded) {
 
		/* Initialise the mutex first, because that's the thing we *need*
 
		 * directly in the newly created thread. */
 
		this->draw_mutex = new std::recursive_mutex();
 
		if (this->draw_mutex == nullptr) {
 
			this->draw_threaded = false;
 
		} else {
 
			draw_lock = std::unique_lock<std::recursive_mutex>(*this->draw_mutex);
 
			this->draw_signal = new std::condition_variable_any();
 
			this->draw_continue = true;
 

	
 
			this->draw_threaded = StartNewThread(&draw_thread, "ottd:draw-sdl", &VideoDriver_SDL_Base::PaintThreadThunk, this);
 

	
 
			/* Free the mutex if we won't be able to use it. */
 
			if (!this->draw_threaded) {
 
				draw_lock.unlock();
 
				draw_lock.release();
 
				delete this->draw_mutex;
 
				delete this->draw_signal;
 
				this->draw_mutex = nullptr;
 
				this->draw_signal = nullptr;
 
			} else {
 
				/* Wait till the draw mutex has started itself. */
 
				this->draw_signal->wait(*this->draw_mutex);
 
			}
 
		}
 
	}
 

	
 
	DEBUG(driver, 1, "SDL2: using %sthreads", this->draw_threaded ? "" : "no ");
 

	
 
#ifdef __EMSCRIPTEN__
 
	/* Run the main loop event-driven, based on RequestAnimationFrame. */
 
	emscripten_set_main_loop_arg(&this->EmscriptenLoop, this, 0, 1);
 
#else
 
	while (!_exit_game) {
 
		LoopOnce();
 
	}
 

	
 
	MainLoopCleanup();
 
#endif
 
}
 

	
 
void VideoDriver_SDL_Base::MainLoopCleanup()
 
{
 
	if (this->draw_mutex != nullptr) {
 
		this->draw_continue = false;
 
		/* Sending signal if there is no thread blocked
 
		 * is very valid and results in noop */
 
		this->draw_signal->notify_one();
 
		if (draw_lock.owns_lock()) draw_lock.unlock();
 
		draw_lock.release();
 
		draw_thread.join();
 

	
 
		delete this->draw_mutex;
 
		delete this->draw_signal;
 

	
 
		this->draw_mutex = nullptr;
 
		this->draw_signal = nullptr;
 
	}
 

	
 
#ifdef __EMSCRIPTEN__
 
	emscripten_exit_pointerlock();
 
	/* In effect, the game ends here. As emscripten_set_main_loop() caused
 
	 * the stack to be unwound, the code after MainLoop() in
 
	 * openttd_main() is never executed. */
 
	EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
 
	EM_ASM(if (window["openttd_exit"]) openttd_exit());
 
#endif
 
}
 

	
 
bool VideoDriver_SDL_Base::ChangeResolution(int w, int h)
 
{
 
	std::unique_lock<std::recursive_mutex> lock;
 
	if (this->draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*this->draw_mutex);
 

	
 
	return CreateMainSurface(w, h, true);
 
}
 

	
 
bool VideoDriver_SDL_Base::ToggleFullscreen(bool fullscreen)
 
{
 
	std::unique_lock<std::recursive_mutex> lock;
 
	if (this->draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*this->draw_mutex);
 

	
 
	int w, h;
 

	
 
	/* Remember current window size */
 
	if (fullscreen) {
 
		SDL_GetWindowSize(this->sdl_window, &w, &h);
 

	
 
@@ -770,22 +684,12 @@ bool VideoDriver_SDL_Base::AfterBlitterC
 
	assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
 
	int w, h;
 
	SDL_GetWindowSize(this->sdl_window, &w, &h);
 
	return CreateMainSurface(w, h, false);
 
}
 

	
 
void VideoDriver_SDL_Base::AcquireBlitterLock()
 
{
 
	if (this->draw_mutex != nullptr) this->draw_mutex->lock();
 
}
 

	
 
void VideoDriver_SDL_Base::ReleaseBlitterLock()
 
{
 
	if (this->draw_mutex != nullptr) this->draw_mutex->unlock();
 
}
 

	
 
Dimension VideoDriver_SDL_Base::GetScreenSize() const
 
{
 
	SDL_DisplayMode mode;
 
	if (SDL_GetCurrentDisplayMode(this->startup_display, &mode) != 0) return VideoDriver::GetScreenSize();
 

	
 
	return { static_cast<uint>(mode.w), static_cast<uint>(mode.h) };
 
@@ -793,14 +697,12 @@ Dimension VideoDriver_SDL_Base::GetScree
 

	
 
bool VideoDriver_SDL_Base::LockVideoBuffer()
 
{
 
	if (this->buffer_locked) return false;
 
	this->buffer_locked = true;
 

	
 
	if (this->draw_threaded) this->draw_lock.lock();
 

	
 
	_screen.dst_ptr = this->GetVideoPointer();
 
	assert(_screen.dst_ptr != nullptr);
 

	
 
	return true;
 
}
 

	
 
@@ -809,9 +711,8 @@ void VideoDriver_SDL_Base::UnlockVideoBu
 
	if (_screen.dst_ptr != nullptr) {
 
		/* Hand video buffer back to the drawing backend. */
 
		this->ReleaseVideoPointer();
 
		_screen.dst_ptr = nullptr;
 
	}
 

	
 
	if (this->draw_threaded) this->draw_lock.unlock();
 
	this->buffer_locked = false;
 
}
src/video/sdl2_v.h
Show inline comments
 
@@ -30,31 +30,23 @@ public:
 
	bool ChangeResolution(int w, int h) override;
 

	
 
	bool ToggleFullscreen(bool fullscreen) override;
 

	
 
	bool AfterBlitterChange() override;
 

	
 
	void AcquireBlitterLock() override;
 

	
 
	void ReleaseBlitterLock() override;
 

	
 
	bool ClaimMousePointer() override;
 

	
 
	void EditBoxGainedFocus() override;
 

	
 
	void EditBoxLostFocus() override;
 

	
 
	const char *GetName() const override { return "sdl"; }
 

	
 
protected:
 
	struct SDL_Window *sdl_window; ///< Main SDL window.
 
	Palette local_palette; ///< Copy of _cur_palette.
 
	bool draw_threaded; ///< Whether the drawing is/may be done in a separate thread.
 
	std::recursive_mutex *draw_mutex = nullptr; ///< Mutex to keep the access to the shared memory controlled.
 
	std::condition_variable_any *draw_signal = nullptr; ///< Signal to draw the next frame.
 
	volatile bool draw_continue; ///< Should we keep continue drawing?
 
	bool buffer_locked; ///< Video buffer was locked by the main thread.
 
	Rect dirty_rect; ///< Rectangle encompassing the dirty area of the video buffer.
 

	
 
	Dimension GetScreenSize() const override;
 
	void InputLoop() override;
 
	bool LockVideoBuffer() override;
 
@@ -88,13 +80,9 @@ private:
 
	/**
 
	 * This is true to indicate that keyboard input is in text input mode, and SDL_TEXTINPUT events are enabled.
 
	 */
 
	bool edit_box_focused;
 

	
 
	int startup_display;
 
	std::thread draw_thread;
 
	std::unique_lock<std::recursive_mutex> draw_lock;
 

	
 
	static void PaintThreadThunk(VideoDriver_SDL_Base *drv);
 
};
 

	
 
#endif /* VIDEO_SDL_H */
src/video/sdl_v.cpp
Show inline comments
 
@@ -20,31 +20,21 @@
 
#include "../core/math_func.hpp"
 
#include "../fileio_func.h"
 
#include "../framerate_type.h"
 
#include "../window_func.h"
 
#include "sdl_v.h"
 
#include <SDL.h>
 
#include <mutex>
 
#include <condition_variable>
 

	
 
#include "../safeguards.h"
 

	
 
static FVideoDriver_SDL iFVideoDriver_SDL;
 

	
 
static SDL_Surface *_sdl_surface;
 
static SDL_Surface *_sdl_realscreen;
 
static bool _all_modes;
 

	
 
/** Whether the drawing is/may be done in a separate thread. */
 
static bool _draw_threaded;
 
/** Mutex to keep the access to the shared memory controlled. */
 
static std::recursive_mutex *_draw_mutex = nullptr;
 
/** Signal to draw the next frame. */
 
static std::condition_variable_any *_draw_signal = nullptr;
 
/** Should we keep continue drawing? */
 
static volatile bool _draw_continue;
 
static Palette _local_palette;
 

	
 
#define MAX_DIRTY_RECTS 100
 
static SDL_Rect _dirty_rects[MAX_DIRTY_RECTS];
 
static int _num_dirty_rects;
 
static int _use_hwpalette;
 
@@ -171,33 +161,12 @@ void VideoDriver_SDL::Paint()
 
		}
 

	
 
		SDL_UpdateRects(_sdl_realscreen, n, _dirty_rects);
 
	}
 
}
 

	
 
void VideoDriver_SDL::PaintThread()
 
{
 
	/* First tell the main thread we're started */
 
	std::unique_lock<std::recursive_mutex> lock(*_draw_mutex);
 
	_draw_signal->notify_one();
 

	
 
	/* Now wait for the first thing to draw! */
 
	_draw_signal->wait(*_draw_mutex);
 

	
 
	while (_draw_continue) {
 
		/* Then just draw and wait till we stop */
 
		this->Paint();
 
		_draw_signal->wait(lock);
 
	}
 
}
 

	
 
/* static */ void VideoDriver_SDL::PaintThreadThunk(VideoDriver_SDL *drv)
 
{
 
	drv->PaintThread();
 
}
 

	
 
static const Dimension _default_resolutions[] = {
 
	{ 640,  480},
 
	{ 800,  600},
 
	{1024,  768},
 
	{1152,  864},
 
	{1280,  800},
 
@@ -627,14 +596,12 @@ const char *VideoDriver_SDL::Start(const
 
	SDL_VideoDriverName(buf, sizeof buf);
 
	DEBUG(driver, 1, "SDL: using driver '%s'", buf);
 

	
 
	MarkWholeScreenDirty();
 
	SetupKeyboard();
 

	
 
	_draw_threaded = !GetDriverParamBool(parm, "no_threads") && !GetDriverParamBool(parm, "no_thread");
 

	
 
	return nullptr;
 
}
 

	
 
void VideoDriver_SDL::SetupKeyboard()
 
{
 
	SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
 
@@ -677,86 +644,27 @@ void VideoDriver_SDL::InputLoop()
 

	
 
	if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
 
}
 

	
 
void VideoDriver_SDL::MainLoop()
 
{
 
	std::thread draw_thread;
 
	if (_draw_threaded) {
 
		/* Initialise the mutex first, because that's the thing we *need*
 
		 * directly in the newly created thread. */
 
		_draw_mutex = new std::recursive_mutex();
 
		if (_draw_mutex == nullptr) {
 
			_draw_threaded = false;
 
		} else {
 
			this->draw_lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
 
			_draw_signal = new std::condition_variable_any();
 
			_draw_continue = true;
 

	
 
			_draw_threaded = StartNewThread(&draw_thread, "ottd:draw-sdl", &VideoDriver_SDL::PaintThreadThunk, this);
 

	
 
			/* Free the mutex if we won't be able to use it. */
 
			if (!_draw_threaded) {
 
				this->draw_lock.unlock();
 
				this->draw_lock.release();
 
				delete _draw_mutex;
 
				delete _draw_signal;
 
				_draw_mutex = nullptr;
 
				_draw_signal = nullptr;
 
			} else {
 
				/* Wait till the draw mutex has started itself. */
 
				_draw_signal->wait(*_draw_mutex);
 
			}
 
		}
 
	}
 

	
 
	DEBUG(driver, 1, "SDL: using %sthreads", _draw_threaded ? "" : "no ");
 

	
 
	for (;;) {
 
		if (_exit_game) break;
 

	
 
		if (this->Tick()) {
 
			if (_draw_mutex != nullptr && !HasModalProgress()) {
 
				_draw_signal->notify_one();
 
			} else {
 
				this->Paint();
 
			}
 
		}
 
		this->Tick();
 
		this->SleepTillNextTick();
 
	}
 

	
 
	if (_draw_mutex != nullptr) {
 
		_draw_continue = false;
 
		/* Sending signal if there is no thread blocked
 
		 * is very valid and results in noop */
 
		_draw_signal->notify_one();
 
		if (this->draw_lock.owns_lock()) this->draw_lock.unlock();
 
		this->draw_lock.release();
 
		draw_thread.join();
 

	
 
		delete _draw_mutex;
 
		delete _draw_signal;
 

	
 
		_draw_mutex = nullptr;
 
		_draw_signal = nullptr;
 
	}
 
}
 

	
 
bool VideoDriver_SDL::ChangeResolution(int w, int h)
 
{
 
	std::unique_lock<std::recursive_mutex> lock;
 
	if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
 

	
 
	return CreateMainSurface(w, h);
 
}
 

	
 
bool VideoDriver_SDL::ToggleFullscreen(bool fullscreen)
 
{
 
	std::unique_lock<std::recursive_mutex> lock;
 
	if (_draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*_draw_mutex);
 

	
 
	_fullscreen = fullscreen;
 
	GetVideoModes(); // get the list of available video modes
 
	bool ret = !_resolutions.empty() && CreateMainSurface(_cur_resolution.width, _cur_resolution.height);
 

	
 
	if (!ret) {
 
		/* switching resolution failed, put back full_screen to original status */
 
@@ -769,28 +677,7 @@ bool VideoDriver_SDL::ToggleFullscreen(b
 

	
 
bool VideoDriver_SDL::AfterBlitterChange()
 
{
 
	return CreateMainSurface(_screen.width, _screen.height);
 
}
 

	
 
void VideoDriver_SDL::AcquireBlitterLock()
 
{
 
	if (_draw_mutex != nullptr) _draw_mutex->lock();
 
}
 

	
 
void VideoDriver_SDL::ReleaseBlitterLock()
 
{
 
	if (_draw_mutex != nullptr) _draw_mutex->unlock();
 
}
 

	
 
bool VideoDriver_SDL::LockVideoBuffer()
 
{
 
	if (_draw_threaded) this->draw_lock.lock();
 
	return true;
 
}
 

	
 
void VideoDriver_SDL::UnlockVideoBuffer()
 
{
 
	if (_draw_threaded) this->draw_lock.unlock();
 
}
 

	
 
#endif /* WITH_SDL */
src/video/sdl_v.h
Show inline comments
 
@@ -26,36 +26,25 @@ public:
 
	bool ChangeResolution(int w, int h) override;
 

	
 
	bool ToggleFullscreen(bool fullscreen) override;
 

	
 
	bool AfterBlitterChange() override;
 

	
 
	void AcquireBlitterLock() override;
 

	
 
	void ReleaseBlitterLock() override;
 

	
 
	bool ClaimMousePointer() override;
 

	
 
	const char *GetName() const override { return "sdl"; }
 

	
 
protected:
 
	void InputLoop() override;
 
	bool LockVideoBuffer() override;
 
	void UnlockVideoBuffer() override;
 
	void Paint() override;
 
	void PaintThread() override;
 
	void CheckPaletteAnim() override;
 
	bool PollEvent() override;
 

	
 
private:
 
	std::unique_lock<std::recursive_mutex> draw_lock;
 

	
 
	bool CreateMainSurface(uint w, uint h);
 
	void SetupKeyboard();
 

	
 
	static void PaintThreadThunk(VideoDriver_SDL *drv);
 
};
 

	
 
/** Factory for the SDL video driver. */
 
class FVideoDriver_SDL : public DriverFactoryBase {
 
public:
 
	FVideoDriver_SDL() : DriverFactoryBase(Driver::DT_VIDEO, 5, "sdl", "SDL Video Driver") {}
src/video/video_driver.cpp
Show inline comments
 
@@ -16,13 +16,13 @@
 
#include "../thread.h"
 
#include "../window_func.h"
 
#include "video_driver.hpp"
 

	
 
bool _video_hw_accel; ///< Whether to consider hardware accelerated video drivers.
 

	
 
bool VideoDriver::Tick()
 
void VideoDriver::Tick()
 
{
 
	auto cur_ticks = std::chrono::steady_clock::now();
 

	
 
	if (cur_ticks >= this->next_game_tick) {
 
		this->next_game_tick += this->GetGameInterval();
 
		/* Avoid next_game_tick getting behind more and more if it cannot keep up. */
 
@@ -63,18 +63,16 @@ bool VideoDriver::Tick()
 
			ChangeGameSpeed(false);
 
			this->fast_forward_via_key = false;
 
		}
 

	
 
		::InputLoop();
 
		UpdateWindows();
 

	
 
		this->CheckPaletteAnim();
 

	
 
		return true;
 
		this->Paint();
 
	}
 

	
 
	return false;
 
}
 

	
 
void VideoDriver::SleepTillNextTick()
 
{
 
	/* See how much time there is till we have to process the next event, and try to hit that as close as possible. */
 
	auto next_tick = std::min(this->next_draw_tick, this->next_game_tick);
src/video/video_driver.hpp
Show inline comments
 
@@ -239,32 +239,28 @@ protected:
 
	/**
 
	 * Paint the window.
 
	 */
 
	virtual void Paint() {}
 

	
 
	/**
 
	 * Thread function for threaded drawing.
 
	 */
 
	virtual void PaintThread() {}
 

	
 
	/**
 
	 * Process any pending palette animation.
 
	 */
 
	virtual void CheckPaletteAnim() {}
 

	
 
	/**
 
	 * Process a single system event.
 
	 * @returns False if there are no more events to process.
 
	 */
 
	virtual bool PollEvent() { return false; };
 

	
 
	/**
 
	 * Run the game for a single tick, processing boththe game-tick and draw-tick.
 
	 * @returns True if the driver should redraw the screen.
 
	 * Give the video-driver a tick.
 
	 * It will process any potential game-tick and/or draw-tick, and/or any
 
	 * other video-driver related event.
 
	 */
 
	bool Tick();
 
	void Tick();
 

	
 
	/**
 
	 * Sleep till the next tick is about to happen.
 
	 */
 
	void SleepTillNextTick();
 

	
src/video/win32_v.cpp
Show inline comments
 
@@ -222,17 +222,12 @@ bool VideoDriver_Win32Base::MakeWindow(b
 
	BlitterFactory::GetCurrentBlitter()->PostResize();
 

	
 
	GameSizeChanged();
 
	return true;
 
}
 

	
 
/* static */ void VideoDriver_Win32Base::PaintThreadThunk(VideoDriver_Win32Base *drv)
 
{
 
	drv->PaintThread();
 
}
 

	
 
/** Forward key presses to the window system. */
 
static LRESULT HandleCharMsg(uint keycode, WChar charcode)
 
{
 
	static WChar prev_char = 0;
 

	
 
	/* Did we get a lead surrogate? If yes, store and exit. */
 
@@ -865,76 +860,18 @@ bool VideoDriver_Win32Base::PollEvent()
 

	
 
	return true;
 
}
 

	
 
void VideoDriver_Win32Base::MainLoop()
 
{
 
	std::thread draw_thread;
 

	
 
	if (this->draw_threaded) {
 
		/* Initialise the mutex first, because that's the thing we *need*
 
		 * directly in the newly created thread. */
 
		try {
 
			this->draw_signal = new std::condition_variable_any();
 
			this->draw_mutex = new std::recursive_mutex();
 
		} catch (...) {
 
			this->draw_threaded = false;
 
		}
 

	
 
		if (this->draw_threaded) {
 
			this->draw_lock = std::unique_lock<std::recursive_mutex>(*this->draw_mutex);
 

	
 
			this->draw_continue = true;
 
			this->draw_threaded = StartNewThread(&draw_thread, "ottd:draw-win32", &VideoDriver_Win32Base::PaintThreadThunk, this);
 

	
 
			/* Free the mutex if we won't be able to use it. */
 
			if (!this->draw_threaded) {
 
				this->draw_lock.unlock();
 
				this->draw_lock.release();
 
				delete this->draw_mutex;
 
				delete this->draw_signal;
 
				this->draw_mutex = nullptr;
 
				this->draw_signal = nullptr;
 
			} else {
 
				DEBUG(driver, 1, "Threaded drawing enabled");
 
				/* Wait till the draw thread has started itself. */
 
				this->draw_signal->wait(*this->draw_mutex);
 
			}
 
		}
 
	}
 

	
 
	for (;;) {
 
		if (_exit_game) break;
 

	
 
		/* Flush GDI buffer to ensure we don't conflict with the drawing thread. */
 
		GdiFlush();
 

	
 
		if (this->Tick()) {
 
			if (this->draw_mutex != nullptr && !HasModalProgress()) {
 
				this->draw_signal->notify_one();
 
			} else {
 
				this->Paint();
 
			}
 
		}
 
		this->Tick();
 
		this->SleepTillNextTick();
 
	}
 

	
 
	if (this->draw_threaded) {
 
		this->draw_continue = false;
 
		/* Sending signal if there is no thread blocked
 
		 * is very valid and results in noop */
 
		this->draw_signal->notify_all();
 
		if (this->draw_lock.owns_lock()) this->draw_lock.unlock();
 
		this->draw_lock.release();
 
		draw_thread.join();
 

	
 
		delete this->draw_mutex;
 
		delete this->draw_signal;
 

	
 
		this->draw_mutex = nullptr;
 
	}
 
}
 

	
 
void VideoDriver_Win32Base::ClientSizeChanged(int w, int h, bool force)
 
{
 
	/* Allocate backing store of the new size. */
 
	if (this->AllocateBackingStore(w, h, force)) {
 
@@ -948,49 +885,30 @@ void VideoDriver_Win32Base::ClientSizeCh
 
		GameSizeChanged();
 
	}
 
}
 

	
 
bool VideoDriver_Win32Base::ChangeResolution(int w, int h)
 
{
 
	std::unique_lock<std::recursive_mutex> lock;
 
	if (this->draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*this->draw_mutex);
 

	
 
	if (_window_maximize) ShowWindow(this->main_wnd, SW_SHOWNORMAL);
 

	
 
	this->width = this->width_org = w;
 
	this->height = this->height_org = h;
 

	
 
	return this->MakeWindow(_fullscreen); // _wnd.fullscreen screws up ingame resolution switching
 
}
 

	
 
bool VideoDriver_Win32Base::ToggleFullscreen(bool full_screen)
 
{
 
	std::unique_lock<std::recursive_mutex> lock;
 
	if (this->draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*this->draw_mutex);
 

	
 
	bool res = this->MakeWindow(full_screen);
 

	
 
	InvalidateWindowClassesData(WC_GAME_OPTIONS, 3);
 
	return res;
 
}
 

	
 
void VideoDriver_Win32Base::AcquireBlitterLock()
 
{
 
	if (this->draw_mutex != nullptr) this->draw_mutex->lock();
 
}
 

	
 
void VideoDriver_Win32Base::ReleaseBlitterLock()
 
{
 
	if (this->draw_mutex != nullptr) this->draw_mutex->unlock();
 
}
 

	
 
void VideoDriver_Win32Base::EditBoxLostFocus()
 
{
 
	std::unique_lock<std::recursive_mutex> lock;
 
	if (this->draw_mutex != nullptr) lock = std::unique_lock<std::recursive_mutex>(*this->draw_mutex);
 

	
 
	CancelIMEComposition(this->main_wnd);
 
	SetCompositionPos(this->main_wnd);
 
	SetCandidatePos(this->main_wnd);
 
}
 

	
 
Dimension VideoDriver_Win32Base::GetScreenSize() const
 
@@ -1040,14 +958,12 @@ float VideoDriver_Win32Base::GetDPIScale
 

	
 
bool VideoDriver_Win32Base::LockVideoBuffer()
 
{
 
	if (this->buffer_locked) return false;
 
	this->buffer_locked = true;
 

	
 
	if (this->draw_threaded) this->draw_lock.lock();
 

	
 
	_screen.dst_ptr = this->GetVideoPointer();
 
	assert(_screen.dst_ptr != nullptr);
 

	
 
	return true;
 
}
 

	
 
@@ -1057,13 +973,12 @@ void VideoDriver_Win32Base::UnlockVideoB
 
	if (_screen.dst_ptr != nullptr) {
 
		/* Hand video buffer back to the drawing backend. */
 
		this->ReleaseVideoPointer();
 
		_screen.dst_ptr = nullptr;
 
	}
 

	
 
	if (this->draw_threaded) this->draw_lock.unlock();
 
	this->buffer_locked = false;
 
}
 

	
 

	
 
static FVideoDriver_Win32GDI iFVideoDriver_Win32GDI;
 

	
 
@@ -1076,14 +991,12 @@ const char *VideoDriver_Win32GDI::Start(
 
	this->MakePalette();
 
	this->AllocateBackingStore(_cur_resolution.width, _cur_resolution.height);
 
	this->MakeWindow(_fullscreen);
 

	
 
	MarkWholeScreenDirty();
 

	
 
	this->draw_threaded = !GetDriverParam(param, "no_threads") && !GetDriverParam(param, "no_thread") && std::thread::hardware_concurrency() > 1;
 

	
 
	return nullptr;
 
}
 

	
 
void VideoDriver_Win32GDI::Stop()
 
{
 
	DeleteObject(this->gdi_palette);
 
@@ -1227,32 +1140,12 @@ void VideoDriver_Win32GDI::Paint()
 

	
 
	ReleaseDC(this->main_wnd, dc);
 

	
 
	this->dirty_rect = {};
 
}
 

	
 
void VideoDriver_Win32GDI::PaintThread()
 
{
 
	/* First tell the main thread we're started */
 
	std::unique_lock<std::recursive_mutex> lock(*this->draw_mutex);
 
	this->draw_signal->notify_one();
 

	
 
	/* Now wait for the first thing to draw! */
 
	this->draw_signal->wait(*this->draw_mutex);
 

	
 
	while (this->draw_continue) {
 
		this->Paint();
 

	
 
		/* Flush GDI buffer to ensure drawing here doesn't conflict with any GDI usage in the main WndProc. */
 
		GdiFlush();
 

	
 
		this->draw_signal->wait(*this->draw_mutex);
 
	}
 
}
 

	
 

	
 
#ifdef _DEBUG
 
/* Keep this function here..
 
 * It allows you to redraw the screen from within the MSVC debugger */
 
/* static */ int VideoDriver_Win32GDI::RedrawScreenDebug()
 
{
 
	static int _fooctr;
 
@@ -1392,13 +1285,12 @@ const char *VideoDriver_Win32OpenGL::Sta
 
		_cur_resolution = old_res;
 
		return err;
 
	}
 

	
 
	this->ClientSizeChanged(this->width, this->height, true);
 

	
 
	this->draw_threaded = false;
 
	MarkWholeScreenDirty();
 

	
 
	return nullptr;
 
}
 

	
 
void VideoDriver_Win32OpenGL::Stop()
src/video/win32_v.h
Show inline comments
 
@@ -14,28 +14,24 @@
 
#include <mutex>
 
#include <condition_variable>
 

	
 
/** Base class for Windows video drivers. */
 
class VideoDriver_Win32Base : public VideoDriver {
 
public:
 
	VideoDriver_Win32Base() : main_wnd(nullptr), fullscreen(false), draw_mutex(nullptr), draw_signal(nullptr) {}
 
	VideoDriver_Win32Base() : main_wnd(nullptr), fullscreen(false) {}
 

	
 
	void Stop() override;
 

	
 
	void MakeDirty(int left, int top, int width, int height) override;
 

	
 
	void MainLoop() override;
 

	
 
	bool ChangeResolution(int w, int h) override;
 

	
 
	bool ToggleFullscreen(bool fullscreen) override;
 

	
 
	void AcquireBlitterLock() override;
 

	
 
	void ReleaseBlitterLock() override;
 

	
 
	bool ClaimMousePointer() override;
 

	
 
	void EditBoxLostFocus() override;
 

	
 
protected:
 
	HWND main_wnd;          ///< Handle to system window.
 
@@ -44,18 +40,13 @@ protected:
 
	Rect dirty_rect;        ///< Region of the screen that needs redrawing.
 
	int width = 0;          ///< Width in pixels of our display surface.
 
	int height = 0;         ///< Height in pixels of our display surface.
 
	int width_org = 0;      ///< Original monitor resolution width, before we changed it.
 
	int height_org = 0;     ///< Original monitor resolution height, before we changed it.
 

	
 
	bool draw_threaded;          ///< Whether the drawing is/may be done in a separate thread.
 
	bool buffer_locked;          ///< Video buffer was locked by the main thread.
 
	volatile bool draw_continue; ///< Should we keep continue drawing?
 

	
 
	std::recursive_mutex *draw_mutex;         ///< Mutex to keep the access to the shared memory controlled.
 
	std::condition_variable_any *draw_signal; ///< Signal to draw the next frame.
 
	bool buffer_locked;     ///< Video buffer was locked by the main thread.
 

	
 
	Dimension GetScreenSize() const override;
 
	float GetDPIScale() override;
 
	void InputLoop() override;
 
	bool LockVideoBuffer() override;
 
	void UnlockVideoBuffer() override;
 
@@ -75,16 +66,12 @@ protected:
 
	/** Hand video buffer back to the painting backend. */
 
	virtual void ReleaseVideoPointer() {}
 
	/** Palette of the window has changed. */
 
	virtual void PaletteChanged(HWND hWnd) = 0;
 

	
 
private:
 
	std::unique_lock<std::recursive_mutex> draw_lock;
 

	
 
	static void PaintThreadThunk(VideoDriver_Win32Base *drv);
 

	
 
	friend LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
 
};
 
/** The GDI video driver for windows. */
 
class VideoDriver_Win32GDI : public VideoDriver_Win32Base {
 
public:
 
	VideoDriver_Win32GDI() : dib_sect(nullptr), gdi_palette(nullptr), buffer_bits(nullptr) {}
 
@@ -101,13 +88,12 @@ protected:
 
	HBITMAP  dib_sect;      ///< System bitmap object referencing our rendering buffer.
 
	HPALETTE gdi_palette;   ///< Palette object for 8bpp blitter.
 
	void     *buffer_bits;  ///< Internal rendering buffer.
 

	
 
	void Paint() override;
 
	void *GetVideoPointer() override { return this->buffer_bits; }
 
	void PaintThread() override;
 

	
 
	bool AllocateBackingStore(int w, int h, bool force = false) override;
 
	void PaletteChanged(HWND hWnd) override;
 
	void MakePalette();
 
	void UpdatePalette(HDC dc, uint start, uint count);
 

	
 
@@ -156,13 +142,12 @@ protected:
 
	bool   vsync;       ///< Enable VSync?
 
	uint8 *anim_buffer; ///< Animation buffer from OpenGL back-end.
 

	
 
	uint8 GetFullscreenBpp() override { return 32; } // OpenGL is always 32 bpp.
 

	
 
	void Paint() override;
 
	void PaintThread() override {}
 

	
 
	bool AllocateBackingStore(int w, int h, bool force = false) override;
 
	void *GetVideoPointer() override;
 
	void ReleaseVideoPointer() override;
 
	void PaletteChanged(HWND hWnd) override {}
 

	
0 comments (0 inline, 0 general)