File: main.cpp

package info (click to toggle)
warmux 1%3A11.04.1%2Brepack2-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 126,388 kB
  • sloc: cpp: 186,040; xml: 8,909; sh: 3,358; makefile: 1,052; ansic: 713
file content (575 lines) | stat: -rw-r--r-- 16,446 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/******************************************************************************
 *  Warmux is a convivial mass murder game.
 *  Copyright (C) 2001-2011 Warmux Team.
 *
 *  This program 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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 ******************************************************************************
 *  Starting file. (the 'main' function is here.)
 *****************************************************************************/

#include <WARMUX_singleton.h>
#include <getopt.h>
#ifndef WIN32
# include <signal.h>
#endif
#include <SDL.h>
#include "game/config.h"
#include "game/game.h"
#include "game/game_time.h"
#include "graphic/font.h"
#include "graphic/sprite.h"
#include "graphic/text.h"
#include "graphic/video.h"
#include "include/action_handler.h"
#include "include/app.h"
#include "include/constant.h"
#include "map/map.h"
#include "menu/benchmark_menu.h"
#include "menu/credits_menu.h"
#include "menu/game_menu.h"
#include "menu/help_menu.h"
#include "menu/main_menu.h"
#include "menu/pause_menu.h"
#include "menu/network_connection_menu.h"
#include "menu/options_menu.h"
#include "menu/replay_menu.h"
#include "network/randomsync.h"
#include "particles/particle.h"
#include "replay/replay.h"
#include "sound/jukebox.h"
#include "tool/stats.h"
#ifdef MAEMO
#include "maemo/osso.h"
#include "menu/pause_menu.h"
#endif
#ifdef WMX_LOG
# include "include/debugmasks.h"
#endif
#ifdef ANDROID
# include <android/log.h>
# define PAUSE_LOG(fmt, ...) __android_log_print(ANDROID_LOG_INFO, "warmux", fmt, ##__VA_ARGS__ )
#else
# define PAUSE_LOG(fmt, ...) MSG_DEBUG("pause", fmt, ##__VA_ARGS__ )
#endif

// Can be accessed by other parts of the code
bool quit_game = false;

static MainMenu::menu_item choice = MainMenu::NONE;
static bool skip_menu = false;
static NetworkConnectionMenu::network_menu_action_t net_action = NetworkConnectionMenu::NET_NOTHING;

AppWarmux *AppWarmux::singleton = NULL;

AppWarmux *AppWarmux::GetInstance()
{
  if (!singleton) {
    singleton = new AppWarmux();
  }
  return singleton;
}

AppWarmux::AppWarmux():
  video(new Video()),
  menu(NULL)
{
  RandomLocal().InitRandom();
  std::cout << "[ " << _("Run game") << " ]" << std::endl;
}

AppWarmux::~AppWarmux()
{
  delete video;
  ParticleEngine::FreeMem();
  Font::ReleaseInstances();
  BaseSingleton::ReleaseSingletons();
  singleton = NULL;
}

static std::string replay;

int AppWarmux::Main(void)
{
  DisplayLoadingPicture();

  // Now that we are displaying a kind of 'please wait', do preload sounds
  JukeBox::GetInstance()->Init();

#ifdef HAVE_LIBCURL
  OptionMenu::CheckUpdates();
#endif

  Action_Handler_Init();

  // Is a replay filename set so that we play it?
  if (!replay.empty()) {
    StartPlaying(replay);
    replay.clear();
    End();
    return 0;
  }

  do {
    if (choice == MainMenu::NONE) {
      MainMenu main_menu;
      SetCurrentMenu(&main_menu);
      choice = main_menu.Run();
    }

    ActionHandler::GetInstance()->Flush();

    switch (choice) {
      case MainMenu::PLAY:
      {
        GameMenu game_menu;
        SetCurrentMenu(&game_menu);
        game_menu.Run(skip_menu);
        break;
      }
      case MainMenu::NETWORK:
      {
        NetworkConnectionMenu network_connection_menu(net_action);
        SetCurrentMenu(&network_connection_menu);
        network_connection_menu.Run(skip_menu);
        break;
      }
      case MainMenu::OPTIONS:
      {
        OptionMenu options_menu;
        SetCurrentMenu(&options_menu);
        options_menu.Run();
        break;
      }
      case MainMenu::BENCHMARK:
      {
        BenchmarkMenu bench_menu;
        SetCurrentMenu(&bench_menu);
        bench_menu.Run();
        break;
      }
      case MainMenu::HELP:
      {
        HelpMenu help_menu;
        SetCurrentMenu(&help_menu);
        help_menu.Run();
        break;
      }
      case MainMenu::CREDITS:
      {
        CreditsMenu credits_menu;
        SetCurrentMenu(&credits_menu);
        credits_menu.Run();
        break;
      }
      case MainMenu::REPLAY:
      {
        ReplayMenu replay_menu;
        SetCurrentMenu(&replay_menu);
        replay_menu.Run();
        break;
      }
      case MainMenu::QUIT:
        quit_game = true;
        break;
      default:
        break;
    }
    SetCurrentMenu(NULL);
    choice = MainMenu::NONE;
    skip_menu = false;
    net_action = NetworkConnectionMenu::NET_NOTHING;
  }
  while (!quit_game);

  End();

  return 0;
}

void AppWarmux::DisplayLoadingPicture()
{
  Config *config = Config::GetInstance();

  std::string txt_version =
    _("Version") + std::string(" ") + Constants::WARMUX_VERSION;
  std::string filename = config->GetDataDir() + "menu" PATH_SEPARATOR "background_loading.jpg";

  Surface surfaceLoading(filename.c_str());
  Sprite loading_image(surfaceLoading);

  loading_image.ScaleSize(video->window.GetSize());
  loading_image.Blit(video->window, 0, 0);

  GameTime::GetInstance()->Reset();

  Text text1(_("Warmux launching..."), white_color,
             Font::FONT_HUGE, Font::FONT_BOLD, true);
  Text text2(txt_version, white_color, Font::FONT_HUGE, Font::FONT_BOLD,
             true);

  Point2i windowCenter = video->window.GetSize() / 2;

  text1.DrawCenter(windowCenter);
  text2.DrawCenter(windowCenter
                   + Point2i(0, Font::GetInstance(Font::FONT_HUGE, Font::FONT_BOLD)->GetHeight() + 20));

  video->window.Flip();
}

void AppWarmux::RefreshDisplay()
{
  if (GameIsRunning()) {
    if (Game::GetCurrentMenu()) {
      Game::GetCurrentMenu()->RedrawMenu();
      return;
    } else {
      GetWorld().DrawSky(true);
      GetWorld().Draw(true);
    }
  }
  else if (GetCurrentMenu()) {
    GetCurrentMenu()->RedrawMenu();
  }
}

void AppWarmux::DisplayError(const std::string &msg)
{
  std::cerr << msg << std::endl;

  if (GameIsRunning()) {
    if (Game::GetCurrentMenu()) {
      Game::GetCurrentMenu()->DisplayError(msg);
    }
    // nothing to do
  } else if (singleton->GetCurrentMenu()) {
    singleton->GetCurrentMenu()->DisplayError(msg);
  }
}

void AppWarmux::ReceiveMsgCallback(const std::string& msg, const Color& color, bool in_game)
{
  if (Replay::GetConstInstance()->IsPlaying() && in_game) {
    Game::GetInstance()->chatsession.NewMessage(msg, color);
  } else if (GameIsRunning()) {
    if (Game::GetCurrentMenu() && !in_game) {
      // Drop message, we should be paused anyway
    } else {
      // Add message to chat session in Game
      Game::GetInstance()->chatsession.NewMessage(msg, color);
    }
  } else if (GetCurrentMenu()) {
    GetCurrentMenu()->ReceiveMsgCallback(msg, color);
  }
}

void AppWarmux::End() const
{
  std::cout << std::endl << "[ " << _("Quit Warmux") << " ]" << std::endl;

  /* FIXME calling Config->Save here sucks: it nothing was ever done, it loads
   * the whole stuff just before exiting... This should be moved, but where? */
  Config::GetInstance()->Save();

  JukeBox::GetInstance()->End();

#ifdef ENABLE_STATS
  SaveStatToXML("stats.xml");
#endif
  std::cout << "o " << _("If you found a bug or have a feature request "
                         "send us an email (in english, please):")
    << " " << Constants::EMAIL << std::endl;
}

bool AppWarmux::CheckInactive(SDL_Event& evnt)
{
#ifdef MAEMO
  Osso::Process();
#endif

#ifdef HAVE_HANDHELD
#  define CHECK_STATE(e) e.type==SDL_ACTIVEEVENT
#else
#  define CHECK_STATE(e) e.type==SDL_ACTIVEEVENT && e.active.state&SDL_APPACTIVE
#endif

  if (CHECK_STATE(evnt) && evnt.active.gain == 0) {
    PAUSE_LOG("Pause: entering, state=%X\n", evnt.active.state);
    JukeBox::GetInstance()->CloseDevice();
    GameTime::GetInstance()->SetWaitingForUser(true);

    Action a(Action::ACTION_ANNOUNCE_PAUSE);
    Network::GetInstance()->SendActionToAll(a);

    while (SDL_WaitEvent(&evnt)) {
#ifdef MAEMO
      Osso::Process();
#endif
      if (evnt.type == SDL_QUIT) AppWarmux::EmergencyExit();
      if (evnt.type == SDL_ACTIVEEVENT && evnt.active.gain == 1) {
        PAUSE_LOG("Active: state=%X\n", evnt.active.state);
        if ((!menu || choice != MainMenu::NONE) && GameIsRunning()) {
          PAUSE_LOG("Pause: menu=%p\n", menu);
          choice = MainMenu::NONE;
          bool exit = false;
          // There shouldn't be any other menu set, right?
          menu = new PauseMenu(exit);
          menu->Run();
          delete menu;
          menu = NULL;
          if (exit)
            Game::GetInstance()->UserAsksForEnd();
        }

        JukeBox::GetInstance()->OpenDevice();
        JukeBox::GetInstance()->NextMusic();
        GameTime::GetInstance()->SetWaitingForUser(false);

        break;
      }

      PAUSE_LOG("Dropping event %u\n", evnt.type);
    }
    return true;
  }
  return false;
}

void AppWarmux::EmergencyExit()
{
  delete AppWarmux::GetInstance();
  exit(EXIT_SUCCESS);
}

void DisplayWelcomeMessage()
{
  std::cout << "=== " << _("Warmux version ") << Constants::WARMUX_VERSION << std::endl;
  std::cout << "=== " << _("Authors:") << ' ';
  for (std::vector < std::string >::iterator it = Constants::GetInstance()->AUTHORS.begin(),
       fin = Constants::GetInstance()->AUTHORS.end(); it != fin; ++it)
    {
      if (it != Constants::GetInstance()->AUTHORS.begin())
        std::cout << ", ";
      std::cout << *it;
    }
  std::cout << std::endl
    << "=== " << _("Website: ") << Constants::WEB_SITE << std::endl
    << std::endl;

  // print the disclaimer
  std::cout << "Warmux version " << Constants::WARMUX_VERSION
    << ", Copyright (C) 2001-2011 Warmux Team" << std::endl
    << "Warmux comes with ABSOLUTELY NO WARRANTY." << std::endl
    << "This is free software and you are welcome to redistribute it" << std::endl
    << "under certain conditions." << std::endl << std::endl
    << "Read the file COPYING for details." << std::endl << std::endl;

#ifdef DEBUG
  std::cout << "This program was compiled in DEBUG mode (development version)"
       << std::endl << std::endl;
#endif
}

void PrintUsage(const char* cmd_name)
{
  printf("usage: \n");
  printf("%s -h|--help : show this help and exit\n", cmd_name);
  printf("%s -v|--version : show the version and exit\n", cmd_name);
  printf("%s -r|--reset-config : reset the configuration to default and exit\n", cmd_name);
  printf("%s -f|--force-refresh : force game to refresh, even very slowly. Useful to run with valgrind\n", cmd_name);
  printf("%s --size <width>x<height> : set the display resolution\n", cmd_name);
  printf("%s [-p|--play] [-g|--game-mode <game_mode>]"
         " [-s|--server] [-c|--client [ip]]\n"
         " [-i|--index-server [ip/hostname of index server]]\n"
         " [-q|--quick-quit : exit the game immediately after first run\n"
#ifdef WMX_LOG
         " [-d|--debug <debug_masks>|all]\n"
#endif
         , cmd_name);
#ifdef WMX_LOG
  printf("\nWith :\n");
  printf(" <debug_masks> ::= { %s }\n", used_debug_masks.c_str());
#endif
}

void ParseArgs(int argc, char * argv[])
{
  int c;
  int option_index = 0;
  struct option long_options[] = {
    {"unrandom",   no_argument,       NULL, 'u'},
    {"force-refresh", no_argument,    NULL, 'f'},
    {"help",       no_argument,       NULL, 'h'},
    {"version",    no_argument,       NULL, 'v'},
    {"play",       no_argument,       NULL, 'p'},
    {"quick-quit", no_argument,       NULL, 'q'},
    {"client",     optional_argument, NULL, 'c'},
    {"server",     no_argument,       NULL, 's'},
    {"index-server", optional_argument, NULL, 'i'},
    {"game-mode",  required_argument, NULL, 'g'},
    {"debug",      required_argument, NULL, 'd'},
    {"reset-config", no_argument,     NULL, 'r'},
    {"size",       required_argument, NULL, 'S'},
    {"replay",     required_argument, NULL, 'R'},
    {NULL,         no_argument,       NULL,  0 }
  };

  while ((c = getopt_long(argc, argv, "ufhvpqc::si::g:d:rS:R:",
                          long_options, &option_index)) != -1) {
    switch (c) {
    case 'u':
      RandomSync().UnRandom();
      RandomLocal().UnRandom();
      break;
    case 'f':
      // This option is useful to run with valgrind
      extern bool force_refresh;
      force_refresh = true;
      break;
    case 'h':
      PrintUsage(argv[0]);
      exit(EXIT_SUCCESS);
      break;
    case 'v':
      DisplayWelcomeMessage();
      exit(EXIT_SUCCESS);
      break;
    case 'p':
      choice = MainMenu::PLAY;
      skip_menu = true;
      break;
    case 'c':
      choice = MainMenu::NETWORK;
      net_action = NetworkConnectionMenu::NET_CONNECT;
      if (optarg)
        {
          Config::GetInstance()->SetNetworkClientHost(optarg);
        }
      skip_menu = true;
      break;
    case 'd':
#ifdef WMX_LOG
      printf("Debug: %s\n", optarg);
      AddDebugMode(optarg);
#else
      fprintf(stderr, "Option -d is not available. Warmux has not been compiled with debug/logging option.\n");
#endif
      break;
    case 'R':
      replay = optarg;
      break;
    case 's':
      choice = MainMenu::NETWORK;
      net_action = NetworkConnectionMenu::NET_HOST;
      skip_menu = true;
      break;
    case 'i':
      {
        std::string index_server_address;
        if (optarg) index_server_address = optarg;
        else index_server_address = "127.0.0.1";
        printf("Using %s as address for index server. This option must be used only for debugging.\n",
               index_server_address.c_str());
        IndexServer::GetInstance()->SetAddress(index_server_address.c_str());
      }
      break;
    case 'g':
      printf("Game-mode: %s\n", optarg);
      Config::GetInstance()->SetGameMode(optarg);
      break;
    case 'q':
      quit_game = true; // immediately exit the game after first run
      break;
    case 'r':
      {
        bool r;
        r = Config::GetInstance()->RemovePersonalConfigFile();
        if (!r)
          exit(EXIT_FAILURE);
        exit(EXIT_SUCCESS);
      }
      break;
    case 'S':
      {
	      uint width, height;
	      int ret = sscanf(optarg, "%ux%u", &width, &height);
	      if (ret == 2) {
	        Config::GetInstance()->SetVideoWidth(width);
	        Config::GetInstance()->SetVideoHeight(height);
	      } else {
	        fprintf(stderr, "Error: %s is not a valid resolution\n", optarg);
	      }
      }
      break;
    case '?': /* returns by getopt if option was invalid */
      PrintUsage(argv[0]);
      exit(EXIT_FAILURE);
      break;

    default:
      fprintf(stderr, "Sorry, it seems that option '-%c' is not implemented!\n", c);
      ASSERT(false);
      exit(EXIT_FAILURE);
      break;
    }
  }
}

extern "C" int main(int argc, char *argv[])
{
#if !defined(WIN32) && !defined(__SYMBIAN32__)
  signal(SIGPIPE, SIG_IGN);
#endif

#ifdef GEKKO
  // External library libfat, but let's not bother including its header
  extern void fatInitDefault(void);
  fatInitDefault();
  freopen("sd:/stdout.txt", "wt", stdout);
  freopen("sd:/stderr.txt", "wt", stderr);
  fprintf(stdout, "Trying to force opening\n");
#endif

#ifdef __SYMBIAN32__
  freopen("warmux_stdout.txt", "w", stdout);
  freopen("warmux_stderr.txt", "w", stderr);
#endif

  std::ios_base::sync_with_stdio(true);

  /* FIXME calling Config::GetInstance here means that there is no need of
   * singleton for Config but simply a global variable. This may look stange
   * but the whole system (directories, translation etc...) is needed, even for
   * the ParseArgs and DisplayWelcomeMessage functions. */
  Config::GetInstance(); // init config first, because it initializes i18n

  ParseArgs(argc, argv);

  DisplayWelcomeMessage();

  if (SDL_Init(SDL_INIT_TIMER) < 0) {
    fprintf(stderr, "Sorry, couldn't initialize SDL'!\n");
    exit(EXIT_FAILURE);
  }

#ifdef MAEMO
  Osso::Init();
#endif

  AppWarmux::GetInstance()->Main();
  delete AppWarmux::GetInstance();
  SDL_QuitSubSystem(SDL_INIT_TIMER);
  SDL_Quit();
  exit(EXIT_SUCCESS);
}