OpenTTD Source: src/video/dedicated_v.cpp Source File

OpenTTD Source 13.2.1

dedicated_v.cpp
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 #include "../stdafx.h"
11
12 #include "../gfx_func.h"
13 #include "../network/network.h"
14 #include "../network/network_internal.h"
15 #include "../console_func.h"
16 #include "../genworld.h"
17 #include "../fileio_type.h"
18 #include "../fios.h"
19 #include "../blitter/factory.hpp"
20 #include "../company_func.h"
21 #include "../core/random_func.hpp"
22 #include "../saveload/saveload.h"
23 #include "../thread.h"
24 #include "../window_func.h"
25 #include "dedicated_v.h"
26
27 #ifdef __OS2__
28 # include <sys/time.h> /* gettimeofday */
29 # include <sys/types.h>
30 # include <unistd.h>
31 # include <conio.h>
32
33 # define INCL_DOS
34 # include <os2.h>
35
36 # define STDIN 0 /* file descriptor for standard input */
37
42 static void OS2_SwitchToConsoleMode()
43 {
44 PPIB pib;
45 PTIB tib;
46
47 DosGetInfoBlocks(&tib, &pib);
48
49 /* Change flag from PM to VIO */
50 pib->pib_ultype = 3;
51 }
52 #endif
53
54 #if defined(UNIX)
55 # include <sys/time.h> /* gettimeofday */
56 # include <sys/types.h>
57 # include <unistd.h>
58 # include <signal.h>
59 # define STDIN 0 /* file descriptor for standard input */
60
61 /* Signal handlers */
62 static void DedicatedSignalHandler(int sig)
63 {
64 if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
65 _exit_game = true;
66 signal(sig, DedicatedSignalHandler);
67 }
68 #endif
69
70 #if defined(_WIN32)
71 # include <windows.h> /* GetTickCount */
72 # include <conio.h>
73 # include <time.h>
74 # include <tchar.h>
75 # include "../os/windows/win32.h"
76
77 static HANDLE _hInputReady, _hWaitForInputHandling;
78 static HANDLE _hThread; // Thread to close
79 static char _win_console_thread_buffer[200];
80
81 /* Windows Console thread. Just loop and signal when input has been received */
82 static void WINAPI CheckForConsoleInput()
83 {
84 SetCurrentThreadName("ottd:win-console");
85
86 DWORD nb;
87 HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
88 for (;;) {
89 ReadFile(hStdin, _win_console_thread_buffer, lengthof(_win_console_thread_buffer), &nb, nullptr);
90 if (nb >= lengthof(_win_console_thread_buffer)) nb = lengthof(_win_console_thread_buffer) - 1;
91 _win_console_thread_buffer[nb] = '\0';
92
93 /* Signal input waiting that input is read and wait for it being handled
94 * SignalObjectAndWait() should be used here, but it's unsupported in Win98< */
95 SetEvent(_hInputReady);
96 WaitForSingleObject(_hWaitForInputHandling, INFINITE);
97 }
98 }
99
100 static void CreateWindowsConsoleThread()
101 {
102 DWORD dwThreadId;
103 /* Create event to signal when console input is ready */
104 _hInputReady = CreateEvent(nullptr, false, false, nullptr);
105 _hWaitForInputHandling = CreateEvent(nullptr, false, false, nullptr);
106 if (_hInputReady == nullptr || _hWaitForInputHandling == nullptr) usererror("Cannot create console event!");
107
108 _hThread = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, nullptr, 0, &dwThreadId);
109 if (_hThread == nullptr) usererror("Cannot create console thread!");
110
111 Debug(driver, 2, "Windows console thread started");
112 }
113
114 static void CloseWindowsConsoleThread()
115 {
116 CloseHandle(_hThread);
117 CloseHandle(_hInputReady);
118 CloseHandle(_hWaitForInputHandling);
119 Debug(driver, 2, "Windows console thread shut down");
120 }
121
122 #endif
123
124 #include "../safeguards.h"
125
126
127 static void *_dedicated_video_mem;
128
129 /* Whether a fork has been done. */
130 bool _dedicated_forks;
131
132 extern bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr);
133
134 static FVideoDriver_Dedicated iFVideoDriver_Dedicated;
135
136
137 const char *VideoDriver_Dedicated::Start(const StringList &parm)
138 {
139 this->UpdateAutoResolution();
140
141 int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
142 _dedicated_video_mem = (bpp == 0) ? nullptr : MallocT<byte>(_cur_resolution.width * _cur_resolution.height * (bpp / 8));
143
144 _screen.width = _screen.pitch = _cur_resolution.width;
145 _screen.height = _cur_resolution.height;
146 _screen.dst_ptr = _dedicated_video_mem;
147 ScreenSizeChanged();
148 BlitterFactory::GetCurrentBlitter()->PostResize();
149
150 #if defined(_WIN32)
151 /* For win32 we need to allocate a console (debug mode does the same) */
152 CreateConsole();
153 CreateWindowsConsoleThread();
154 SetConsoleTitle(L"OpenTTD Dedicated Server");
155 #endif
156
157 #ifdef _MSC_VER
158 /* Disable the MSVC assertion message box. */
159 _set_error_mode(_OUT_TO_STDERR);
160 #endif
161
162 #ifdef __OS2__
163 /* For OS/2 we also need to switch to console mode instead of PM mode */
164 OS2_SwitchToConsoleMode();
165 #endif
166
167 Debug(driver, 1, "Loading dedicated server");
168 return nullptr;
169 }
170
171 void VideoDriver_Dedicated::Stop()
172 {
173 #ifdef _WIN32
174 CloseWindowsConsoleThread();
175 #endif
176 free(_dedicated_video_mem);
177 }
178
179 void VideoDriver_Dedicated::MakeDirty(int left, int top, int width, int height) {}
180 bool VideoDriver_Dedicated::ChangeResolution(int w, int h) { return false; }
181 bool VideoDriver_Dedicated::ToggleFullscreen(bool fs) { return false; }
182
183 #if defined(UNIX) || defined(__OS2__)
184 static bool InputWaiting()
185 {
186 struct timeval tv;
187 fd_set readfds;
188
189 tv.tv_sec = 0;
190 tv.tv_usec = 1;
191
192 FD_ZERO(&readfds);
193 FD_SET(STDIN, &readfds);
194
195 /* don't care about writefds and exceptfds: */
196 return select(STDIN + 1, &readfds, nullptr, nullptr, &tv) > 0;
197 }
198
199 #else
200
201 static bool InputWaiting()
202 {
203 return WaitForSingleObject(_hInputReady, 1) == WAIT_OBJECT_0;
204 }
205
206 #endif
207
208 static void DedicatedHandleKeyInput()
209 {
210 static char input_line[1024] = "";
211
212 if (!InputWaiting()) return;
213
214 if (_exit_game) return;
215
216 #if defined(UNIX) || defined(__OS2__)
217 if (fgets(input_line, lengthof(input_line), stdin) == nullptr) return;
218 #else
219 /* Handle console input, and signal console thread, it can accept input again */
220 static_assert(lengthof(_win_console_thread_buffer) <= lengthof(input_line));
221 strecpy(input_line, _win_console_thread_buffer, lastof(input_line));
222 SetEvent(_hWaitForInputHandling);
223 #endif
224
225 /* Remove trailing \r or \n */
226 for (char *c = input_line; *c != '\0'; c++) {
227 if (*c == '\n' || *c == '\r' || c == lastof(input_line)) {
228 *c = '\0';
229 break;
230 }
231 }
232 StrMakeValidInPlace(input_line, lastof(input_line));
233
234 IConsoleCmdExec(input_line); // execute command
235 }
236
237 void VideoDriver_Dedicated::MainLoop()
238 {
239 /* Signal handlers */
240 #if defined(UNIX)
241 signal(SIGTERM, DedicatedSignalHandler);
242 signal(SIGINT, DedicatedSignalHandler);
243 signal(SIGQUIT, DedicatedSignalHandler);
244 #endif
245
246 /* Load the dedicated server stuff */
247 _is_network_server = true;
248 _network_dedicated = true;
249 _current_company = _local_company = COMPANY_SPECTATOR;
250
251 /* If SwitchMode is SM_LOAD_GAME, it means that the user used the '-g' options */
252 if (_switch_mode != SM_LOAD_GAME) {
253 StartNewGameWithoutGUI(GENERATE_NEW_SEED);
254 }
255
256 this->is_game_threaded = false;
257
258 /* Done loading, start game! */
259
260 while (!_exit_game) {
261 if (!_dedicated_forks) DedicatedHandleKeyInput();
262 this->DrainCommandQueue();
263
264 ChangeGameSpeed(_ddc_fastforward);
265 this->Tick();
266 this->SleepTillNextTick();
267 }
268 }
VideoDriver::Tick
void Tick()
Give the video-driver a tick.
Definition: video_driver.cpp:101
usererror
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:105
SM_LOAD_GAME
@ SM_LOAD_GAME
Load game, Play Scenario.
Definition: openttd.h:31
DoExitSave
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition: saveload.cpp:3344
GUISettings::autosave_on_exit
bool autosave_on_exit
save an autosave when you quit the game, but do not ask "Do you really want to quit?...
Definition: settings_type.h:140
SaveLoadOperation
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:47
Blitter::GetScreenDepth
virtual uint8 GetScreenDepth()=0
Get the screen depth this blitter works for.
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:53
SetCurrentThreadName
void SetCurrentThreadName(const char *)
Name the thread this function is called on for the debugger.
Definition: os2.cpp:212
SafeLoad
bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=nullptr)
Load the specified savegame but on error do different things.
Definition: openttd.cpp:962
GENERATE_NEW_SEED
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
Definition: genworld.h:24
dedicated_v.h
StrMakeValidInPlace
void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings)
Scans the string for invalid characters and replaces then with a question mark '?' (if not ignored).
Definition: string.cpp:273
Blitter::PostResize
virtual void PostResize()
Post resize event.
Definition: base.hpp:209
FVideoDriver_Dedicated
Factory for the dedicated server video driver.
Definition: dedicated_v.h:34
BlitterFactory::GetCurrentBlitter
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:141
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
StringList
std::vector< std::string > StringList
Type for a list of strings.
Definition: string_type.h:59
VideoDriver_Dedicated::MakeDirty
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
Definition: dedicated_v.cpp:179
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:61
GameMode
GameMode
Mode which defines the state of the game.
Definition: openttd.h:17
StartNewGameWithoutGUI
void StartNewGameWithoutGUI(uint32 seed)
Start a normal game without the GUI.
Definition: genworld_gui.cpp:1099
VideoDriver_Dedicated::Start
const char * Start(const StringList &param) override
Start this driver.
Definition: dedicated_v.cpp:137
_switch_mode
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:49
_ddc_fastforward
#define _ddc_fastforward
Helper variable to make the dedicated server go fast until the (first) join.
Definition: network_internal.h:50
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
DetailedFileType
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:28
VideoDriver_Dedicated::ChangeResolution
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
Definition: dedicated_v.cpp:180
VideoDriver::UpdateAutoResolution
void UpdateAutoResolution()
Apply resolution auto-detection and clamp to sensible defaults.
Definition: video_driver.hpp:242
COMPANY_SPECTATOR
@ COMPANY_SPECTATOR
The client is spectating.
Definition: company_type.h:35
VideoDriver::DrainCommandQueue
void DrainCommandQueue()
Execute all queued commands.
Definition: video_driver.hpp:328
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:108
Debug
#define Debug(name, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
LoadFilter
Interface for filtering a savegame till it is loaded.
Definition: saveload_filter.h:14
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:386
VideoDriver::SleepTillNextTick
void SleepTillNextTick()
Sleep till the next tick is about to happen.
Definition: video_driver.cpp:170
IConsoleCmdExec
void IConsoleCmdExec(const char *cmdstr, const uint recurse_count)
Execute a given command passed to us.
Definition: console.cpp:303
VideoDriver_Dedicated::MainLoop
void MainLoop() override
Perform the actual drawing.
Definition: dedicated_v.cpp:237
VideoDriver_Dedicated::Stop
void Stop() override
Stop this driver.
Definition: dedicated_v.cpp:171
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:113
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:470
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:402
VideoDriver_Dedicated::ToggleFullscreen
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
Definition: dedicated_v.cpp:181
_cur_resolution
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:32
_is_network_server
bool _is_network_server
Does this client wants to be a network-server?
Definition: network.cpp:62
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:604