OpenTTD
dedicated_v.cpp
Go to the documentation of this file.
1 /* $Id$ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * 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.
6  * 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.
7  * 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/>.
8  */
9 
12 #include "../stdafx.h"
13 
14 #ifdef ENABLE_NETWORK
15 
16 #include "../gfx_func.h"
17 #include "../network/network.h"
18 #include "../network/network_internal.h"
19 #include "../console_func.h"
20 #include "../genworld.h"
21 #include "../fileio_type.h"
22 #include "../fios.h"
23 #include "../blitter/factory.hpp"
24 #include "../company_func.h"
25 #include "../core/random_func.hpp"
26 #include "../saveload/saveload.h"
27 #include "dedicated_v.h"
28 
29 #ifdef BEOS_NET_SERVER
30 #include <net/socket.h>
31 #endif
32 
33 #ifdef __OS2__
34 # include <sys/time.h> /* gettimeofday */
35 # include <sys/types.h>
36 # include <unistd.h>
37 # include <conio.h>
38 
39 # define INCL_DOS
40 # include <os2.h>
41 
42 # define STDIN 0 /* file descriptor for standard input */
43 
48 static void OS2_SwitchToConsoleMode()
49 {
50  PPIB pib;
51  PTIB tib;
52 
53  DosGetInfoBlocks(&tib, &pib);
54 
55  /* Change flag from PM to VIO */
56  pib->pib_ultype = 3;
57 }
58 #endif
59 
60 #if defined(UNIX)
61 # include <sys/time.h> /* gettimeofday */
62 # include <sys/types.h>
63 # include <unistd.h>
64 # include <signal.h>
65 # define STDIN 0 /* file descriptor for standard input */
66 
67 /* Signal handlers */
68 static void DedicatedSignalHandler(int sig)
69 {
70  if (_game_mode == GM_NORMAL && _settings_client.gui.autosave_on_exit) DoExitSave();
71  _exit_game = true;
72  signal(sig, DedicatedSignalHandler);
73 }
74 #endif
75 
76 #if defined(_WIN32)
77 # include <windows.h> /* GetTickCount */
78 # include <conio.h>
79 # include <time.h>
80 # include <tchar.h>
81 # include "../os/windows/win32.h"
82 static HANDLE _hInputReady, _hWaitForInputHandling;
83 static HANDLE _hThread; // Thread to close
84 static char _win_console_thread_buffer[200];
85 
86 /* Windows Console thread. Just loop and signal when input has been received */
87 static void WINAPI CheckForConsoleInput()
88 {
89  SetWin32ThreadName(-1, "ottd:win-console");
90 
91  DWORD nb;
92  HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
93  for (;;) {
94  ReadFile(hStdin, _win_console_thread_buffer, lengthof(_win_console_thread_buffer), &nb, NULL);
95  if (nb >= lengthof(_win_console_thread_buffer)) nb = lengthof(_win_console_thread_buffer) - 1;
96  _win_console_thread_buffer[nb] = '\0';
97 
98  /* Signal input waiting that input is read and wait for it being handled
99  * SignalObjectAndWait() should be used here, but it's unsupported in Win98< */
100  SetEvent(_hInputReady);
101  WaitForSingleObject(_hWaitForInputHandling, INFINITE);
102  }
103 }
104 
105 static void CreateWindowsConsoleThread()
106 {
107  DWORD dwThreadId;
108  /* Create event to signal when console input is ready */
109  _hInputReady = CreateEvent(NULL, false, false, NULL);
110  _hWaitForInputHandling = CreateEvent(NULL, false, false, NULL);
111  if (_hInputReady == NULL || _hWaitForInputHandling == NULL) usererror("Cannot create console event!");
112 
113  _hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CheckForConsoleInput, NULL, 0, &dwThreadId);
114  if (_hThread == NULL) usererror("Cannot create console thread!");
115 
116  DEBUG(driver, 2, "Windows console thread started");
117 }
118 
119 static void CloseWindowsConsoleThread()
120 {
121  CloseHandle(_hThread);
122  CloseHandle(_hInputReady);
123  CloseHandle(_hWaitForInputHandling);
124  DEBUG(driver, 2, "Windows console thread shut down");
125 }
126 
127 #endif
128 
129 #include "../safeguards.h"
130 
131 
132 static void *_dedicated_video_mem;
133 
134 /* Whether a fork has been done. */
135 bool _dedicated_forks;
136 
137 extern bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = NULL);
138 
139 static FVideoDriver_Dedicated iFVideoDriver_Dedicated;
140 
141 
142 const char *VideoDriver_Dedicated::Start(const char * const *parm)
143 {
145  _dedicated_video_mem = (bpp == 0) ? NULL : MallocT<byte>(_cur_resolution.width * _cur_resolution.height * (bpp / 8));
146 
147  _screen.width = _screen.pitch = _cur_resolution.width;
148  _screen.height = _cur_resolution.height;
149  _screen.dst_ptr = _dedicated_video_mem;
150  ScreenSizeChanged();
152 
153 #if defined(_WIN32)
154  /* For win32 we need to allocate a console (debug mode does the same) */
155  CreateConsole();
156  CreateWindowsConsoleThread();
157  SetConsoleTitle(_T("OpenTTD Dedicated Server"));
158 #endif
159 
160 #ifdef _MSC_VER
161  /* Disable the MSVC assertion message box. */
162  _set_error_mode(_OUT_TO_STDERR);
163 #endif
164 
165 #ifdef __OS2__
166  /* For OS/2 we also need to switch to console mode instead of PM mode */
167  OS2_SwitchToConsoleMode();
168 #endif
169 
170  DEBUG(driver, 1, "Loading dedicated server");
171  return NULL;
172 }
173 
175 {
176 #ifdef _WIN32
177  CloseWindowsConsoleThread();
178 #endif
179  free(_dedicated_video_mem);
180 }
181 
182 void VideoDriver_Dedicated::MakeDirty(int left, int top, int width, int height) {}
183 bool VideoDriver_Dedicated::ChangeResolution(int w, int h) { return false; }
184 bool VideoDriver_Dedicated::ToggleFullscreen(bool fs) { return false; }
185 
186 #if defined(UNIX) || defined(__OS2__)
187 static bool InputWaiting()
188 {
189  struct timeval tv;
190  fd_set readfds;
191 
192  tv.tv_sec = 0;
193  tv.tv_usec = 1;
194 
195  FD_ZERO(&readfds);
196  FD_SET(STDIN, &readfds);
197 
198  /* don't care about writefds and exceptfds: */
199  return select(STDIN + 1, &readfds, NULL, NULL, &tv) > 0;
200 }
201 
202 static uint32 GetTime()
203 {
204  struct timeval tim;
205 
206  gettimeofday(&tim, NULL);
207  return tim.tv_usec / 1000 + tim.tv_sec * 1000;
208 }
209 
210 #else
211 
212 static bool InputWaiting()
213 {
214  return WaitForSingleObject(_hInputReady, 1) == WAIT_OBJECT_0;
215 }
216 
217 static uint32 GetTime()
218 {
219  return GetTickCount();
220 }
221 
222 #endif
223 
224 static void DedicatedHandleKeyInput()
225 {
226  static char input_line[1024] = "";
227 
228  if (!InputWaiting()) return;
229 
230  if (_exit_game) return;
231 
232 #if defined(UNIX) || defined(__OS2__)
233  if (fgets(input_line, lengthof(input_line), stdin) == NULL) return;
234 #else
235  /* Handle console input, and signal console thread, it can accept input again */
236  assert_compile(lengthof(_win_console_thread_buffer) <= lengthof(input_line));
237  strecpy(input_line, _win_console_thread_buffer, lastof(input_line));
238  SetEvent(_hWaitForInputHandling);
239 #endif
240 
241  /* Remove trailing \r or \n */
242  for (char *c = input_line; *c != '\0'; c++) {
243  if (*c == '\n' || *c == '\r' || c == lastof(input_line)) {
244  *c = '\0';
245  break;
246  }
247  }
248  str_validate(input_line, lastof(input_line));
249 
250  IConsoleCmdExec(input_line); // execute command
251 }
252 
254 {
255  uint32 cur_ticks = GetTime();
256  uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
257 
258  /* Signal handlers */
259 #if defined(UNIX)
260  signal(SIGTERM, DedicatedSignalHandler);
261  signal(SIGINT, DedicatedSignalHandler);
262  signal(SIGQUIT, DedicatedSignalHandler);
263 #endif
264 
265  /* Load the dedicated server stuff */
266  _is_network_server = true;
267  _network_dedicated = true;
269 
270  /* If SwitchMode is SM_LOAD_GAME, it means that the user used the '-g' options */
271  if (_switch_mode != SM_LOAD_GAME) {
273  SwitchToMode(_switch_mode);
274  _switch_mode = SM_NONE;
275  } else {
276  _switch_mode = SM_NONE;
277  /* First we need to test if the savegame can be loaded, else we will end up playing the
278  * intro game... */
280  /* Loading failed, pop out.. */
281  DEBUG(net, 0, "Loading requested map failed, aborting");
282  _networking = false;
283  } else {
284  /* We can load this game, so go ahead */
285  SwitchToMode(SM_LOAD_GAME);
286  }
287  }
288 
289  /* Done loading, start game! */
290 
291  if (!_networking) {
292  DEBUG(net, 0, "Dedicated server could not be started, aborting");
293  return;
294  }
295 
296  while (!_exit_game) {
297  uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
298  InteractiveRandom(); // randomness
299 
300  if (!_dedicated_forks) DedicatedHandleKeyInput();
301 
302  cur_ticks = GetTime();
303  _realtime_tick += cur_ticks - prev_cur_ticks;
304  if (cur_ticks >= next_tick || cur_ticks < prev_cur_ticks || _ddc_fastforward) {
305  next_tick = cur_ticks + MILLISECONDS_PER_TICK;
306 
307  GameLoop();
308  UpdateWindows();
309  }
310 
311  /* Don't sleep when fast forwarding (for desync debugging) */
312  if (!_ddc_fastforward) {
313  /* Sleep longer on a dedicated server, if the game is paused and no clients connected.
314  * That can allow the CPU to better use deep sleep states. */
315  if (_pause_mode != 0 && !HasClients()) {
316  CSleep(100);
317  } else {
318  CSleep(1);
319  }
320  }
321  }
322 }
323 
324 #endif /* ENABLE_NETWORK */
const char * Start(const char *const *param)
Start this driver.
bool _networking
are we in networking mode?
Definition: network.cpp:56
uint32 _realtime_tick
The real time in the game.
Definition: debug.cpp:52
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:110
Load game, Play Scenario.
Definition: openttd.h:31
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:59
#define _ddc_fastforward
Helper variable to make the dedicated server go fast until the (first) join.
Dimension _cur_resolution
The current resolution.
Definition: driver.cpp:24
void DoExitSave()
Do a save when exiting the game (_settings_client.gui.autosave_on_exit)
Definition: saveload.cpp:2806
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
The client is spectating.
Definition: company_type.h:37
virtual void PostResize()
Post resize event.
Definition: base.hpp:203
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
Definition: genworld.h:25
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:59
CompanyByte _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
Interface for filtering a savegame till it is loaded.
void StartNewGameWithoutGUI(uint32 seed)
Start a normal game without the GUI.
bool _is_network_server
Does this client wants to be a network-server?
Definition: network.cpp:60
void str_validate(char *str, const char *last, StringValidationSettings settings)
Scans the string for valid characters and if it finds invalid ones, replaces them with a question mar...
Definition: string.cpp:196
GameMode
Mode which defines the state of the game.
Definition: openttd.h:18
void IConsoleCmdExec(const char *cmdstr)
Execute a given command passed to us.
Definition: console.cpp:409
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:76
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:92
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition: gfx_type.h:306
Base directory for all subdirectories.
Definition: fileio_type.h:111
bool ToggleFullscreen(bool fullscreen)
Change the full screen setting.
bool autosave_on_exit
save an autosave when you quit the game, but do not ask "Do you really want to quit?"
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
PauseModeByte _pause_mode
The current pause mode.
Definition: gfx.cpp:48
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:147
void Stop()
Stop this driver.
SaveLoadOperation
Operation performed on the file.
Definition: fileio_type.h:49
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:36
void MainLoop()
Perform the actual drawing.
bool HasClients()
Return whether there is any client connected or trying to connect at all.
Definition: network.cpp:104
void MakeDirty(int left, int top, int width, int height)
Mark a particular area dirty.
bool SafeLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf=NULL)
Load the specified savegame but on error do different things.
Definition: openttd.cpp:1013
GUISettings gui
settings related to the GUI
CompanyByte _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:68
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:47
Base for the dedicated video driver.
Factory for the dedicated server video driver.
Definition: dedicated_v.h:36
char name[MAX_PATH]
Name of the file.
Definition: saveload.h:310
SaveLoadOperation file_op
File operation to perform.
Definition: saveload.h:307
virtual uint8 GetScreenDepth()=0
Get the screen depth this blitter works for.
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:114
DetailedFileType detail_ftype
Concrete file type (PNG, BMP, old save, etc).
Definition: saveload.h:308
DetailedFileType
Kinds of files in each AbstractFileType.
Definition: fileio_type.h:30
bool ChangeResolution(int w, int h)
Change the resolution of the window.
void UpdateWindows()
Update the continuously changing contents of the windows, such as the viewports.
Definition: window.cpp:3112