OpenTTD Source: src/video/video_driver.hpp Source File

OpenTTD Source 14.0-beta3

video_driver.hpp
Go to the documentation of this file.
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10 #ifndef VIDEO_VIDEO_DRIVER_HPP
11 #define VIDEO_VIDEO_DRIVER_HPP
12
13 #include "../driver.h"
14 #include "../core/geometry_type.hpp"
15 #include "../core/math_func.hpp"
16 #include "../gfx_func.h"
17 #include "../settings_type.h"
18 #include "../zoom_type.h"
19 #include <atomic>
20 #include <chrono>
21 #include <condition_variable>
22 #include <mutex>
23 #include <thread>
24
25 extern std::string _ini_videodriver;
26 extern std::vector<Dimension> _resolutions;
27 extern Dimension _cur_resolution;
28 extern bool _rightclick_emulate;
29 extern bool _video_hw_accel;
30 extern bool _video_vsync;
31
33 class VideoDriver : public Driver {
34 const uint DEFAULT_WINDOW_WIDTH = 640u;
35 const uint DEFAULT_WINDOW_HEIGHT = 480u;
36
37 public:
38 VideoDriver() : fast_forward_key_pressed(false), fast_forward_via_key(false), is_game_threaded(true) {}
39
47 virtual void MakeDirty(int left, int top, int width, int height) = 0;
48
52 virtual void MainLoop() = 0;
53
60 virtual bool ChangeResolution(int w, int h) = 0;
61
67 virtual bool ToggleFullscreen(bool fullscreen) = 0;
68
73 virtual void ToggleVsync([[maybe_unused]] bool vsync) {}
74
79 virtual bool AfterBlitterChange()
80 {
81 return true;
82 }
83
84 virtual bool ClaimMousePointer()
85 {
86 return true;
87 }
88
93 virtual bool UseSystemCursor()
94 {
95 return false;
96 }
97
101 virtual void PopulateSystemSprites() {}
102
106 virtual void ClearSystemSprites() {}
107
116 virtual bool HasGUI() const
117 {
118 return true;
119 }
120
125 virtual bool HasEfficient8Bpp() const
126 {
127 return false;
128 }
129
134 virtual bool HasAnimBuffer()
135 {
136 return false;
137 }
138
143 virtual uint8_t *GetAnimBuffer()
144 {
145 return nullptr;
146 }
147
151 virtual void EditBoxLostFocus() {}
152
156 virtual void EditBoxGainedFocus() {}
157
162 virtual std::vector<int> GetListOfMonitorRefreshRates()
163 {
164 return {};
165 }
166
170 virtual int GetSuggestedUIScale()
171 {
172 float dpi_scale = this->GetDPIScale();
173
174 return Clamp(dpi_scale * 100, MIN_INTERFACE_SCALE, MAX_INTERFACE_SCALE);
175 }
176
177 virtual const char *GetInfoString() const
178 {
179 return this->GetName();
180 }
181
188 void QueueOnMainThread(std::function<void()> &&func)
189 {
190 std::lock_guard<std::mutex> lock(this->cmd_queue_mutex);
191
192 this->cmd_queue.emplace_back(std::forward<std::function<void()>>(func));
193 }
194
195 void GameLoopPause();
196
200 static VideoDriver *GetInstance()
201 {
202 return static_cast<VideoDriver*>(*DriverFactoryBase::GetActiveDriver(Driver::DT_VIDEO));
203 }
204
205 static std::string GetCaption();
206
211 struct VideoBufferLocker {
212 VideoBufferLocker()
213 {
214 this->unlock = VideoDriver::GetInstance()->LockVideoBuffer();
215 }
216
217 ~VideoBufferLocker()
218 {
219 if (this->unlock) VideoDriver::GetInstance()->UnlockVideoBuffer();
220 }
221
222 private:
223 bool unlock;
224 };
225
226 protected:
227 const uint ALLOWED_DRIFT = 5;
228
232 virtual Dimension GetScreenSize() const { return { DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT }; }
233
238 virtual float GetDPIScale() { return 1.0f; }
239
243 void UpdateAutoResolution()
244 {
245 if (_cur_resolution.width == 0 || _cur_resolution.height == 0) {
246 /* Auto-detect a good resolution. We aim for 75% of the screen size.
247 * Limit width times height times bytes per pixel to fit a 32 bit
248 * integer, This way all internal drawing routines work correctly. */
249 Dimension res = this->GetScreenSize();
250 _cur_resolution.width = ClampU(res.width * 3 / 4, DEFAULT_WINDOW_WIDTH, UINT16_MAX / 2);
251 _cur_resolution.height = ClampU(res.height * 3 / 4, DEFAULT_WINDOW_HEIGHT, UINT16_MAX / 2);
252 }
253 }
254
258 virtual void InputLoop() {}
259
264 virtual bool LockVideoBuffer()
265 {
266 return false;
267 }
268
272 virtual void UnlockVideoBuffer() {}
273
277 virtual void Paint() {}
278
282 virtual void CheckPaletteAnim() {}
283
288 virtual bool PollEvent() { return false; };
289
293 void StartGameThread();
294
298 void StopGameThread();
299
305 void Tick();
306
310 void SleepTillNextTick();
311
312 std::chrono::steady_clock::duration GetGameInterval()
313 {
314 /* If we are paused, run on normal speed. */
315 if (_pause_mode) return std::chrono::milliseconds(MILLISECONDS_PER_TICK);
316 /* Infinite speed, as quickly as you can. */
317 if (_game_speed == 0) return std::chrono::microseconds(0);
318
319 return std::chrono::microseconds(MILLISECONDS_PER_TICK * 1000 * 100 / _game_speed);
320 }
321
322 std::chrono::steady_clock::duration GetDrawInterval()
323 {
324 /* If vsync, draw interval is decided by the display driver */
325 if (_video_vsync && _video_hw_accel) return std::chrono::microseconds(0);
326 return std::chrono::microseconds(1000000 / _settings_client.gui.refresh_rate);
327 }
328
330 void DrainCommandQueue()
331 {
332 std::vector<std::function<void()>> cmds{};
333
334 {
335 /* Exchange queue with an empty one to limit the time we
336 * hold the mutex. This also ensures that queued functions can
337 * add new functions to the queue without everything blocking. */
338 std::lock_guard<std::mutex> lock(this->cmd_queue_mutex);
339 cmds.swap(this->cmd_queue);
340 }
341
342 for (auto &f : cmds) {
343 f();
344 }
345 }
346
347 std::chrono::steady_clock::time_point next_game_tick;
348 std::chrono::steady_clock::time_point next_draw_tick;
349
350 bool fast_forward_key_pressed;
351 bool fast_forward_via_key;
352
353 bool is_game_threaded;
354 std::thread game_thread;
355 std::mutex game_state_mutex;
356 std::mutex game_thread_wait_mutex;
357
358 static void GameThreadThunk(VideoDriver *drv);
359
360 private:
361 std::mutex cmd_queue_mutex;
362 std::vector<std::function<void()>> cmd_queue;
363
364 void GameLoop();
365 void GameThread();
366 };
367
368 #endif /* VIDEO_VIDEO_DRIVER_HPP */
VideoDriver::Tick
void Tick()
Give the video-driver a tick.
Definition: video_driver.cpp:102
VideoDriver::HasAnimBuffer
virtual bool HasAnimBuffer()
Does this video driver support a separate animation buffer in addition to the colour buffer?
Definition: video_driver.hpp:134
DriverFactoryBase::GetActiveDriver
static Driver ** GetActiveDriver(Driver::Type type)
Get the active driver for the given type.
Definition: driver.h:84
Driver::GetName
virtual const char * GetName() const =0
Get the name of this driver.
VideoDriver
The base of all video drivers.
Definition: video_driver.hpp:33
Dimension
Dimensions (a width and height) of a rectangle in 2D.
Definition: geometry_type.hpp:30
lock
std::mutex lock
synchronization for playback status fields
Definition: win32_m.cpp:35
VideoDriver::CheckPaletteAnim
virtual void CheckPaletteAnim()
Process any pending palette animation.
Definition: video_driver.hpp:282
VideoDriver::ToggleVsync
virtual void ToggleVsync([[maybe_unused]] bool vsync)
Change the vsync setting.
Definition: video_driver.hpp:73
VideoDriver::MakeDirty
virtual void MakeDirty(int left, int top, int width, int height)=0
Mark a particular area dirty.
VideoDriver::ToggleFullscreen
virtual bool ToggleFullscreen(bool fullscreen)=0
Change the full screen setting.
_cur_resolution
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:32
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:54
ClampU
constexpr uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between an interval.
Definition: math_func.hpp:150
VideoDriver::HasGUI
virtual bool HasGUI() const
Whether the driver has a graphical user interface with the end user.
Definition: video_driver.hpp:116
VideoDriver::StartGameThread
void StartGameThread()
Start the loop for game-tick.
Definition: video_driver.cpp:86
VideoDriver::ClearSystemSprites
virtual void ClearSystemSprites()
Clear all cached sprites.
Definition: video_driver.hpp:106
_video_vsync
bool _video_vsync
Whether we should use vsync (only if _video_hw_accel is enabled).
Definition: video_driver.cpp:26
VideoDriver::GetDPIScale
virtual float GetDPIScale()
Get DPI scaling factor of the screen OTTD is displayed on.
Definition: video_driver.hpp:238
GUISettings::refresh_rate
uint16_t refresh_rate
How often we refresh the screen (time between draw-ticks).
Definition: settings_type.h:201
VideoDriver::DEFAULT_WINDOW_HEIGHT
const uint DEFAULT_WINDOW_HEIGHT
Default window height.
Definition: video_driver.hpp:35
VideoDriver::InputLoop
virtual void InputLoop()
Handle input logic, is CTRL pressed, should we fast-forward, etc.
Definition: video_driver.hpp:258
VideoDriver::GetListOfMonitorRefreshRates
virtual std::vector< int > GetListOfMonitorRefreshRates()
Get a list of refresh rates of each available monitor.
Definition: video_driver.hpp:162
VideoDriver::Paint
virtual void Paint()
Paint the window.
Definition: video_driver.hpp:277
_rightclick_emulate
bool _rightclick_emulate
Whether right clicking is emulated.
Definition: driver.cpp:33
VideoDriver::ALLOWED_DRIFT
const uint ALLOWED_DRIFT
How many times videodriver can miss deadlines without it being overly compensated.
Definition: video_driver.hpp:227
_pause_mode
PauseMode _pause_mode
The current pause mode.
Definition: gfx.cpp:50
VideoDriver::GetAnimBuffer
virtual uint8_t * GetAnimBuffer()
Get a pointer to the animation buffer of the video back-end.
Definition: video_driver.hpp:143
VideoDriver::ChangeResolution
virtual bool ChangeResolution(int w, int h)=0
Change the resolution of the window.
VideoDriver::QueueOnMainThread
void QueueOnMainThread(std::function< void()> &&func)
Queue a function to be called on the main thread with game state lock held and video buffer locked.
Definition: video_driver.hpp:188
_game_speed
uint16_t _game_speed
Current game-speed; 100 is 1x, 0 is infinite.
Definition: gfx.cpp:39
VideoDriver::GetInstance
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Definition: video_driver.hpp:200
VideoDriver::UnlockVideoBuffer
virtual void UnlockVideoBuffer()
Unlock a previously locked video buffer.
Definition: video_driver.hpp:272
VideoDriver::UseSystemCursor
virtual bool UseSystemCursor()
Get whether the mouse cursor is drawn by the video driver.
Definition: video_driver.hpp:93
VideoDriver::GameLoopPause
void GameLoopPause()
Pause the game-loop for a bit, releasing the game-state lock.
Definition: video_driver.cpp:66
VideoDriver::StopGameThread
void StopGameThread()
Stop the loop for the game-tick.
Definition: video_driver.cpp:95
VideoDriver::PopulateSystemSprites
virtual void PopulateSystemSprites()
Populate all sprites in cache.
Definition: video_driver.hpp:101
VideoDriver::GetCaption
static std::string GetCaption()
Get the caption to use for the game's title bar.
Definition: video_driver.cpp:189
VideoDriver::UpdateAutoResolution
void UpdateAutoResolution()
Apply resolution auto-detection and clamp to sensible defaults.
Definition: video_driver.hpp:243
Driver::DT_VIDEO
@ DT_VIDEO
A video driver.
Definition: driver.h:42
VideoDriver::VideoBufferLocker::unlock
bool unlock
Stores if the lock did anything that has to be undone.
Definition: video_driver.hpp:223
VideoDriver::DrainCommandQueue
void DrainCommandQueue()
Execute all queued commands.
Definition: video_driver.hpp:330
_ini_videodriver
std::string _ini_videodriver
The video driver a stored in the configuration file.
Definition: driver.cpp:30
VideoDriver::fast_forward_via_key
bool fast_forward_via_key
The fast-forward was enabled by key press.
Definition: video_driver.hpp:351
VideoDriver::GetSuggestedUIScale
virtual int GetSuggestedUIScale()
Get a suggested default GUI scale taking screen DPI into account.
Definition: video_driver.hpp:170
_video_hw_accel
bool _video_hw_accel
Whether to consider hardware accelerated video drivers.
Definition: video_driver.cpp:25
MILLISECONDS_PER_TICK
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition: gfx_type.h:320
VideoDriver::SleepTillNextTick
void SleepTillNextTick()
Sleep till the next tick is about to happen.
Definition: video_driver.cpp:171
VideoDriver::MainLoop
virtual void MainLoop()=0
Perform the actual drawing.
VideoDriver::fast_forward_key_pressed
bool fast_forward_key_pressed
The fast-forward key is being pressed.
Definition: video_driver.hpp:350
VideoDriver::HasEfficient8Bpp
virtual bool HasEfficient8Bpp() const
Has this video driver an efficient code path for palette animated 8-bpp sprites?
Definition: video_driver.hpp:125
VideoDriver::LockVideoBuffer
virtual bool LockVideoBuffer()
Make sure the video buffer is ready for drawing.
Definition: video_driver.hpp:264
VideoDriver::EditBoxLostFocus
virtual void EditBoxLostFocus()
An edit box lost the input focus.
Definition: video_driver.hpp:151
VideoDriver::DEFAULT_WINDOW_WIDTH
const uint DEFAULT_WINDOW_WIDTH
Default window width.
Definition: video_driver.hpp:34
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:79
Driver
A driver for communicating with the user.
Definition: driver.h:21
_resolutions
std::vector< Dimension > _resolutions
List of resolutions.
Definition: driver.cpp:31
VideoDriver::PollEvent
virtual bool PollEvent()
Process a single system event.
Definition: video_driver.hpp:288
VideoDriver::VideoBufferLocker
Helper struct to ensure the video buffer is locked and ready for drawing.
Definition: video_driver.hpp:211
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:636
VideoDriver::GetScreenSize
virtual Dimension GetScreenSize() const
Get the resolution of the main screen.
Definition: video_driver.hpp:232
VideoDriver::EditBoxGainedFocus
virtual void EditBoxGainedFocus()
An edit box gained the input focus.
Definition: video_driver.hpp:156
VideoDriver::AfterBlitterChange
virtual bool AfterBlitterChange()
Callback invoked after the blitter was changed.
Definition: video_driver.hpp:79