File: GameInit.cpp

package info (click to toggle)
xmoto 0.5.11+dfsg-8
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 80,908 kB
  • sloc: cpp: 96,757; ansic: 22,196; sh: 4,940; makefile: 1,073; yacc: 289; sed: 16
file content (1099 lines) | stat: -rw-r--r-- 34,299 bytes parent folder | download | duplicates (2)
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
/*=============================================================================
XMOTO

This file is part of XMOTO.

XMOTO 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.

XMOTO 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 XMOTO; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
=============================================================================*/

/* 
 *  Game application. (init-related stuff)
 */
 
#include "GameText.h"
#include "Game.h"
#include "VFileIO.h"
#include "Sound.h"
#include "PhysSettings.h"
#include "Input.h"
#include "db/xmDatabase.h"
#include "helpers/Log.h"
#include "helpers/Environment.h"
#include "helpers/Random.h"

#include <curl/curl.h>
#include "XMSession.h"
#include "XMArgs.h"
#include "VXml.h"
#include "drawlib/DrawLib.h"
#include "Packager.h"
#include "helpers/SwapEndian.h"
#include "helpers/Text.h"
#include "SysMessage.h"
#include "gui/specific/GUIXMoto.h"
#include "Credits.h"
#include "Replay.h"
#include "GeomsManager.h"
#include "XMDemo.h"

#include "states/StateManager.h"
#include "states/StateEditProfile.h"
#include "states/StateReplaying.h"
#include "states/StatePreplayingReplay.h"
#include "states/StatePreplayingGame.h"
#include "states/StateWaitServerInstructions.h"
#include "states/StateMainMenu.h"
#include "states/StateMessageBox.h"

#include "thread/UpgradeLevelsThread.h"

#include "UserConfig.h"
#include "net/NetServer.h"
#include "net/NetClient.h"
#include "net/NetActions.h"
#include "net/ActionReader.h"
#include "include/xm_SDL_net.h"

#if !defined(WIN32)
#include <signal.h>
#endif

#define MOUSE_DBCLICK_TIME 0.250f

#define XM_MAX_NB_LOOPS_WITH_NONETWORK 3
#define XM_MAX_NB_LOOPS_WITH_NORENDERING 5
#define XM_MAX_FRAMELATE_TO_FORCE_NORENDERING 10

#define XMSERVER_BUF     80
#define XMSERVER_STRBUF "80"

#ifdef __amigaos4__
#include <dos/dos.h>
#include <proto/exec.h>
BOOL LibraryOK( STRPTR libname, ULONG version, ULONG revision )
 {
     struct Library *libBase;
     BOOL ok = FALSE;
     if( libBase = (struct Library *)IExec->OpenLibrary( libname, version ))
     {
     if (libBase->lib_Version > version || (libBase->lib_Version == version && libBase->lib_Revision >=revision))
       {
             ok =  TRUE;
         }
         IExec->CloseLibrary( libBase );
     }
     return ok;
 }
#endif 

#if defined(WIN32)
int SDL_main(int nNumArgs, char **ppcArgs) {
#else
int main(int nNumArgs, char **ppcArgs) {
#endif

#ifdef __amigaos4__
     /* checking for MiniGL 2.0 */

     if(!LibraryOK( "minigl.library", 2, 0 ))
        {
        printf("I need MiniGL 2.0 Beta or newer. Please upgrade!\n");
         return RETURN_FAIL;
        }
#endif

  /* Start application */
  try {     
    /* Setup basic info */
    GameApp::instance()->run(nNumArgs, ppcArgs);
    GameApp::destroy();
  }
  catch (Exception &e) {
    if(Logger::isInitialized()) {
      LogError((std::string("Exception: ") + e.getMsg()).c_str());
    }    

    printf("fatal exception : %s\n", e.getMsg().c_str());        
    SDL_Quit(); /* make sure SDL shuts down gracefully */

#if defined(WIN32)
    char cBuf[1024];
    snprintf(cBuf, 1024, "Fatal exception occurred: %s\n"
	    "Consult the file xmoto.log for more information about what\n"
	    "might has occurred.\n",e.getMsg().c_str());
    MessageBox(NULL,cBuf,"X-Moto Error",MB_OK|MB_ICONERROR);
#endif
  }
  return 0;
}

void xmexit_term(int i_signal) {
  // it seems that it doesn't help return on first line of this function to go back to the previous function

  if(GameApp::instance()->standAloneServer() != NULL) {
    if(Logger::isInitialized()) {
      LogInfo("signal received.");
    }
    GameApp::instance()->standAloneServer()->stop();
    GameApp::instance()->run_unload();
    GameApp::destroy();
  }
  exit(0);
}

void GameApp::run(int nNumArgs, char** ppcArgs) {
  try {
    run_load(nNumArgs, ppcArgs);
    run_loop();
  } catch(Exception &e) {
    run_unload();
    throw e;
  }
  run_unload();
}

void GameApp::run_load(int nNumArgs, char** ppcArgs) {
  XMArguments v_xmArgs;
  m_isODEInitialized = false;
  bool v_useGraphics = true;
  bool v_missingFont = false;
  std::string v_missingFontError;

  Environment::init();

  /* check args */
  try {
    v_xmArgs.parse(nNumArgs, ppcArgs);
  } catch (Exception &e) {
    printf("syntax error : %s\n", e.getMsg().c_str());
    v_xmArgs.help(nNumArgs >= 1 ? ppcArgs[0] : "xmoto");
    quit();
    return; /* abort */
  }

  /* help */
  if(v_xmArgs.isOptHelp()) {
    v_xmArgs.help(nNumArgs >= 1 ? ppcArgs[0] : "xmoto");
    quit();
    return;
  }

  /* overwrite default by command line */
  if(v_xmArgs.isOptDefaultTheme()) {
    XMDefault::DefaultTheme = v_xmArgs.getOpt_defaultTheme_theme();
  }
  /**/

  /* init sub-systems */
  SwapEndian::Swap_Init();
  srand(time(NULL));

  /* package / unpackage */
  if(v_xmArgs.isOptPack()) {
    Packager::go(v_xmArgs.getOpt_pack_bin() == "" ? "xmoto.bin" : v_xmArgs.getOpt_pack_bin(),
		 v_xmArgs.getOpt_pack_dir() == "" ? "."         : v_xmArgs.getOpt_pack_dir());
    quit();
    return;
  }
  if(v_xmArgs.isOptUnPack()) {
    Packager::goUnpack(v_xmArgs.getOpt_unpack_bin() == "" ? "xmoto.bin" : v_xmArgs.getOpt_unpack_bin(),
		       v_xmArgs.getOpt_unpack_dir() == "" ? "."         : v_xmArgs.getOpt_unpack_dir(),
		       v_xmArgs.getOpt_unpack_noList() == false);
    quit();
    return;
  }
  /* ***** */

  if(v_xmArgs.isOptConfigPath()) {
    XMFS::init("xmoto", "xmoto.bin", "xmoto.log", v_xmArgs.isOptServerOnly() == false, v_xmArgs.getOpt_configPath_path());
  } else {
    XMFS::init("xmoto", "xmoto.bin", "xmoto.log", v_xmArgs.isOptServerOnly() == false);
  }
  Logger::init("xmoto.log");

  /* c xmoto files */
  if(v_xmArgs.isOptBuildQueries()) {
    LevelsManager::writeDefaultPackages(XM_SQLQUERIES_GEN_FILE);
    quit();
    return;
  }

  /* load config file, the session */
  XMSession::createDefaultConfig(m_userConfig);

  try {
    m_userConfig->loadFile();
  } catch(Exception &e) {
    LogWarning("failed to load or parse user configuration file");
  }

  XMSession::setDefaultInstance("live");  
  XMSession::instance()->load(m_userConfig); /* overload default session by userConfig */

  XMSession::instance()->load(&v_xmArgs); /* overload default session by xmargs     */

  Logger::setVerbose(XMSession::instance()->isVerbose()); /* apply verbose mode */
  Logger::setActiv(XMSession::instance()->noLog() == false); /* apply log activ mode */

  LogInfo(std::string("X-Moto " + XMBuild::getVersionString(true)).c_str());
  if(SwapEndian::bigendien) {
    LogInfo("Systeme is bigendien");
  } else {
    LogInfo("Systeme is littleendien");
  }
  LogInfo("User data   directory: %s", XMFS::getUserDir(FDT_DATA).c_str());
  LogInfo("User config directory: %s", XMFS::getUserDir(FDT_CONFIG).c_str());
  LogInfo("User cache  directory: %s", XMFS::getUserDir(FDT_CACHE).c_str());
  LogInfo("System data directory: %s", XMFS::getSystemDataDir().c_str());

  if(v_xmArgs.isOptListLevels() || v_xmArgs.isOptListReplays() || v_xmArgs.isOptReplayInfos() || v_xmArgs.isOptServerOnly() || v_xmArgs.isOptUpdateLevelsOnly()) {
    v_useGraphics = false;
  }

  // doesn't work on windows
#if !defined(WIN32)
  if(v_xmArgs.isOptServerOnly()) {
    struct sigaction v_act;

    memset(&v_act, 0, sizeof(struct sigaction));
    v_act.sa_handler  = xmexit_term;
    sigemptyset(&v_act.sa_mask);

    if(sigaction(SIGTERM, &v_act, NULL) != 0) {
      LogWarning("sigaction failed");
    }

    if(sigaction(SIGINT, &v_act, NULL) != 0) {
      LogWarning("sigaction failed");
    }
  }
#endif

  // init not so random numbers
  NotSoRandom::init();

  //gettext  requires database (pour la config de la langue)
  //database requires drawlib  (pour visualiser les upgrades)
  //drawlib  requires gettext  (pour choisir la fonte)

  /* database */
  /* thus, resolution/bpp/windowed parameters cannot be stored in the db (or some minor modifications are required) */
  xmDatabase* pDb = xmDatabase::instance("main");
  pDb->preInitForProfileLoading(DATABASE_FILE);

  // db trace
  if(XMSession::instance()->sqlTrace()) {
    pDb->setTrace(XMSession::instance()->sqlTrace());
  }

  XMSession::instance("file")->load(m_userConfig);
  XMSession::instance("file")->loadProfile(XMSession::instance("file")->profile(), pDb);
  (* XMSession::instance()) = (* XMSession::instance("file"));

  XMSession::instance()->load(&v_xmArgs); /* overload default session by xmargs */
  // enable propagation only after overloading by command args
  XMSession::enablePropagation("file");

  LogInfo("SiteKey: %s", XMSession::instance()->sitekey().c_str());

#ifdef USE_GETTEXT
  std::string v_locale = Locales::init(XMSession::instance()->language());
  LogInfo("Locales set to '%s' (directory '%s')", v_locale.c_str(), LOCALESDIR);

  // some asian langages require ttf files ; change to us in case of problem
  try {
    DrawLib::checkFontPrerequites();
  } catch(Exception &e) {
    v_missingFont = true;
    v_missingFontError = e.getMsg();
    v_locale = Locales::init("en_US");
    LogWarning("font prerequisites missing, switching to en_US: %s", e.getMsg().c_str());
  }
#endif

  _InitWin(v_useGraphics); // initwin inits sdl (and only sdl if initwin is false)

  /* drawlib */
  if(v_useGraphics) {
    /* init drawLib */
    drawLib = DrawLib::DrawLibFromName(XMSession::instance()->drawlib());

    if(drawLib == NULL) {
      throw Exception("Drawlib not initialized");
    }

    SysMessage::instance()->setDrawLib(drawLib);
    SysMessage::instance()->setConsoleSize(XMSession::instance()->consoleSize());
    
    drawLib->setNoGraphics(v_useGraphics == false);
    drawLib->setDontUseGLExtensions(XMSession::instance()->glExts() == false);
    drawLib->setDontUseGLVOBS(XMSession::instance()->glVOBS() == false);

    LogInfo("Wanted resolution: %ix%i (%i bpp)",
            XMSession::instance()->resolutionWidth(),
	    XMSession::instance()->resolutionHeight(),
	    XMSession::instance()->bpp());
    drawLib->init(XMSession::instance()->resolutionWidth(), XMSession::instance()->resolutionHeight(), XMSession::instance()->bpp(), XMSession::instance()->windowed());
    /* drawlib can change the final resolution if it fails, then, reinit session one's */
    XMSession::instance()->setResolutionWidth(drawLib->getDispWidth());
    XMSession::instance()->setResolutionHeight(drawLib->getDispHeight());
    XMSession::instance()->setBpp(drawLib->getDispBPP());
    XMSession::instance()->setWindowed(drawLib->getWindowed());
    LogInfo("Resolution: %ix%i (%i bpp)",
            XMSession::instance()->resolutionWidth(),
	    XMSession::instance()->resolutionHeight(),
	    XMSession::instance()->bpp());
    /* */
  }

  /* init the database (fully, including upgrades) */
  pDb->init(DATABASE_FILE,
	    XMSession::instance()->profile() == "" ? std::string("") : XMSession::instance()->profile(),
	    XMFS::getSystemDataDir(), XMFS::getUserDir(FDT_DATA), XMFS::binCheckSum(),
	    v_xmArgs.isOptNoDBDirsCheck() == false,
	    this);

  if(v_useGraphics) {
    // allocate the statemanager instance so that if it fails, it's not in a thread (serverThread for example)
    StateManager::instance();
  }

  /* Init sound system */
  if(v_useGraphics) {
    Sound::init(XMSession::instance());
  }

  bool v_graphicAutomaticMode;
  v_graphicAutomaticMode = v_useGraphics && (
  v_xmArgs.isOptLevelID()   ||
  v_xmArgs.isOptLevelFile() ||
  v_xmArgs.isOptReplay()    ||
  v_xmArgs.isOptDemo());

  // network requires the input information (to display the chat command)
  if(v_useGraphics) {
    InputHandler::instance()->init(m_userConfig, pDb, XMSession::instance()->profile(), XMSession::instance()->enableJoysticks());
  }

  // no command line need the network for the moment
  if(v_useGraphics || v_xmArgs.isOptServerOnly()) {
    initNetwork(v_xmArgs.isOptServerOnly(), v_xmArgs.isOptServerOnly() || v_graphicAutomaticMode);
  }

  /* Init renderer */
  if(v_useGraphics) {
    switchUglyMode(XMSession::instance()->ugly());
    switchTestThemeMode(XMSession::instance()->testTheme());
  }    

  //
  bool v_updateAfterInitDone = false;

  /* load theme */
  if(pDb->themes_isIndexUptodate() == false) {
    ThemeChoicer::initThemesFromDir(pDb);
    v_updateAfterInitDone = true;
  }

  if(v_xmArgs.isOptServerOnly() == false) {
    try {
      reloadTheme();
    } catch(Exception &e) {
      /* if the theme cannot be loaded, try to reload from files */
      /* perhaps that the xm.db comes from an other computer */
      LogWarning("Theme cannot be reload, try to update themes into the database");
      ThemeChoicer::initThemesFromDir(pDb);
      reloadTheme();
    }
  }

  /* load levels */
  if(pDb->levels_isIndexUptodate() == false) {
    LevelsManager::instance()->reloadLevelsFromLvl(pDb, v_xmArgs.isOptServerOnly(), this);
    v_updateAfterInitDone = true;
  }
  LevelsManager::instance()->reloadExternalLevels(pDb, this);
  
  /* Update replays */
  if(pDb->replays_isIndexUptodate() == false) {
    initReplaysFromDir(pDb);
    v_updateAfterInitDone = true;
  }
  
  // levels_isIndexUptodate() && replays_isIndexUptodate() && themes_isIndexUptodate() done
  if(v_updateAfterInitDone) {
    pDb->setUpdateAfterInitDone(); // confirm to the database that the job is done
  }

  /* List replays? */  
  if(v_xmArgs.isOptListReplays()) {
    pDb->replays_print();
    quit();
    return;
  }
  
  if(v_xmArgs.isOptReplayInfos()) {
    Replay v_replay;
    std::string v_levelId;
      std::string v_player;
    
    v_levelId = v_replay.openReplay(v_xmArgs.getOpt_replayInfos_file(), v_player, true);
    if(v_levelId == "") {
      throw Exception("Invalid replay");
    }
    
    quit();
    return;	
  }
  
  if(v_xmArgs.isOptLevelID()) {
    m_PlaySpecificLevelId = v_xmArgs.getOpt_levelID_id();
  }
  if(v_xmArgs.isOptLevelFile()) {
    m_PlaySpecificLevelFile = v_xmArgs.getOpt_levelFile_file();
  }
  if(v_xmArgs.isOptReplay()) {
    m_PlaySpecificReplay = v_xmArgs.getOpt_replay_file();
  }
  if(v_xmArgs.isOptDemo()) {
    /* demo : download the level and the replay
       load the level as external,
       play the replay
     */
    try {
      m_xmdemo = new XMDemo(v_xmArgs.getOpt_demo_file());
      LogInfo("Loading demo file %s\n", v_xmArgs.getOpt_demo_file().c_str());

      _UpdateLoadingScreen(GAMETEXT_DLLEVEL);
      m_xmdemo->getLevel(XMSession::instance()->proxySettings());
      _UpdateLoadingScreen(GAMETEXT_DLREPLAY);
      m_xmdemo->getReplay(XMSession::instance()->proxySettings());

      try {
	LevelsManager::instance()->addExternalLevel(m_xmdemo->levelFile(), xmDatabase::instance("main"), v_xmArgs.isOptServerOnly());
      } catch(Exception &e) {
	LogError("Can't add level %s as external level", m_xmdemo->levelFile().c_str());
      }
      m_PlaySpecificReplay = m_xmdemo->replayFile();
    } catch(Exception &e) {
      LogError("Unable to load the demo file");
    }
  }
 
  /* Should we clean the level cache? (can also be done when disabled) */
  if(v_xmArgs.isOptCleanCache()) {
    LevelsManager::cleanCache();
  }
  
  /* Should we clean non www levels ? */
  if(v_xmArgs.isOptCleanNoWWWLevels()) {
    pDb->levels_cleanNoWWWLevels();
  }  

  /* -listlevels? */
  if(v_xmArgs.isOptListLevels()) {
    LevelsManager::instance()->printLevelsList(xmDatabase::instance("main"));
    quit();
    return;
  }

  /* -updateLevels */
  if(v_xmArgs.isOptUpdateLevelsOnly()) {
    UpgradeLevelsThread* m_upgradeLevelsThread;
    bool v_currentVerbosity = Logger::isVerbose();
    int v_res;

    m_upgradeLevelsThread = new UpgradeLevelsThread(XMSession::instance()->theme(), false, true);

    // force verbosity while updating levels
    Logger::setVerbose(true);
    v_res = m_upgradeLevelsThread->runInMain();
    if(v_res != 0 && v_res != 2 /* 2 for no level to update */) {
      LogError("Not able to update levels");
    }
    Logger::setVerbose(v_currentVerbosity);

    quit();
    return;
  }

  /* requires graphics now */
  if(v_useGraphics == false && v_xmArgs.isOptServerOnly() == false) {
    quit();
    return;
  }
  
  if(v_xmArgs.isOptServerOnly() == false) {
    _UpdateLoadingScreen();

    /* Find all files in the textures dir and load them */     
    UITexture::setApp(this);
    UIWindow::setDrawLib(getDrawLib());
  }

  // init physics
  // if(dInitODE2(0) == 0) { /* erreur */} ; // ode 0.10
  dInitODE();

  // check ode configuration
#if HAVEDGETCONFIGURATION == 1
  LogInfo("Ode config: %s", dGetConfiguration());
#ifdef dSINGLE
  LogInfo("Ode config: X-Moto compiled with dSINGLE defined");
  if(dCheckConfiguration("ODE_single_precision") != 1) {
    throw Exception("XMoto compiled with ode single precision, but libode library wasn't.");
  }
#endif
#ifdef dDOUBLE
  LogInfo("Ode config: X-Moto compiled with dDOUBLE defined");
  if(dCheckConfiguration("ODE_double_precision") != 1) {
    throw Exception("XMoto compiled with ode as double precision, but libode library wasn't.");
  }
#endif
#if !defined(dSINGLE) && !defined(dDOUBLE)
  LogInfo("Ode config: X-Moto compiled with dSINGLE and dDOUBLE undefined, dSINGLE is used by default");
  if(dCheckConfiguration("ODE_single_precision") != 1) {
    throw Exception("XMoto compiled with ode single precision, but libode library wasn't.");
  }
#endif
#else
  // old ode version
  LogWarning("You've an old ode library, xmoto is not able to check whether it's compatible or not");
#endif
  m_isODEInitialized = true;

  /* load packs */
  LevelsManager::checkPrerequires();

  // don't need to create packs in server mode
  if(v_xmArgs.isOptServerOnly() == false) {
    LevelsManager::instance()->makePacks(XMSession::instance()->profile(), XMSession::instance()->idRoom(0),
					 XMSession::instance()->debug(), XMSession::instance()->adminMode(), xmDatabase::instance("main"));
  }

  /* Update stats */
  if(v_xmArgs.isOptServerOnly() == false) {
    if(XMSession::instance()->profile() != "") {
      pDb->stats_xmotoStarted(XMSession::instance()->sitekey(), XMSession::instance()->profile());
    }
  }

  // reset the loading screen
  if(DrawLib::isInitialized() == false) {
    _UpdateLoadingShell(); // no more loading screen
  }

  if(v_xmArgs.isOptServerOnly()) {
    try {
      // start the server
      m_standAloneServer = NetServer::instance();
      NetServer::instance()->setStandAloneOptions();
      NetServer::instance()->start(false,
				   v_xmArgs.isOptServerPort()          ? v_xmArgs.getOptServerPort_value()          : XMSession::instance()->serverPort(),
				   v_xmArgs.isOptServerAdminPassword() ? v_xmArgs.getOptServerAdminPassword_value() : "" /* else, no password */);
    } catch(Exception &e) {
      LogError((std::string("Exception: ") + e.getMsg()).c_str());
    }

    quit();
    return;

  } else {

    /* try to not run sql at the same time you enter in the main menu (a thread to compute packs is run (concurrency)) */

    /* What to do? */
    if(m_PlaySpecificLevelFile != "") {
      try {
	LevelsManager::instance()->addExternalLevel(m_PlaySpecificLevelFile, xmDatabase::instance("main"), v_xmArgs.isOptServerOnly());
	m_PlaySpecificLevelId = LevelsManager::instance()->LevelByFileName(m_PlaySpecificLevelFile, xmDatabase::instance("main"));
      } catch(Exception &e) {
	m_PlaySpecificLevelId = m_PlaySpecificLevelFile;
      }
    }
    if((m_PlaySpecificLevelId != "")) {
      /* ======= PLAY SPECIFIC LEVEL ======= */

      if(XMSession::instance()->clientGhostMode() == false && NetClient::instance()->isConnected()) {
	  StateManager::instance()->pushState(new StateWaitServerInstructions());
      } else {
	StateManager::instance()->pushState(new StatePreplayingGame(m_PlaySpecificLevelId, false));
      }
      LogInfo("Playing as '%s'...", XMSession::instance()->profile().c_str());
    }
    else if(m_PlaySpecificReplay != "") {
      /* ======= PLAY SPECIFIC REPLAY ======= */
      StateManager::instance()->pushState(new StatePreplayingReplay(m_PlaySpecificReplay, false));
    }
    else {
      /* display what must be displayed */
      StateManager::instance()->pushState(new StateMainMenu());
      if(XMSession::instance()->clientGhostMode() == false && NetClient::instance()->isConnected()) {
	  StateManager::instance()->pushState(new StateWaitServerInstructions());
      }
    }

    /* display error information to the player */
    if(v_missingFont) {
      SysMessage::instance()->displayError(GAMETEXT_TTF_MISSING + std::string("\n") + v_missingFontError);
    }
  }

  LogInfo("UserInit ended at %.3f", GameApp::getXMTime());
}

void GameApp::manageEvent(SDL_Event* Event) {
  static int nLastMouseClickX = -100,nLastMouseClickY = -100;
  static int nLastMouseClickButton = -100;
  static float fLastMouseClickTime = 0.0f;
  int nX,nY;
  std::string utf8Char;  

  if(Event->type == SDL_KEYDOWN || Event->type == SDL_KEYUP) {
    /* don't allow simple modifier key */
    if(Event->key.keysym.sym == SDLK_RSHIFT ||
       Event->key.keysym.sym == SDLK_LSHIFT ||
       Event->key.keysym.sym == SDLK_RCTRL  ||
       Event->key.keysym.sym == SDLK_LCTRL  ||
       Event->key.keysym.sym == SDLK_RALT   ||
       Event->key.keysym.sym == SDLK_LALT   ||
       Event->key.keysym.sym == SDLK_RMETA  ||
       Event->key.keysym.sym == SDLK_LMETA
       ) {
      return;
    }
  }

  /* What event? */
  switch(Event->type) {
  case SDL_KEYDOWN:
    utf8Char = unicode2utf8(Event->key.keysym.unicode);
    //printf("%i - %i\n", Event->key.keysym.sym, utf8Char.c_str()[0]);
    StateManager::instance()->xmKey(INPUT_DOWN, XMKey(Event->key.keysym.sym, Event->key.keysym.mod, utf8Char));
    break;
  case SDL_KEYUP:
    utf8Char = unicode2utf8(Event->key.keysym.unicode);
    StateManager::instance()->xmKey(INPUT_UP, XMKey(Event->key.keysym.sym, Event->key.keysym.mod, utf8Char));
    break;
  case SDL_QUIT:  
    /* Force quit */
    quit();
    break;
  case SDL_MOUSEBUTTONDOWN:    
    /* Is this a double click? */
    getMousePos(&nX,&nY);
    if(nX == nLastMouseClickX &&
       nY == nLastMouseClickY &&
       nLastMouseClickButton == Event->button.button &&
       (getXMTime() - fLastMouseClickTime) < MOUSE_DBCLICK_TIME) {
      
      /* Pass double click */
      StateManager::instance()->xmKey(INPUT_DOWN, XMKey(Event->button.button, 2));
    } else {
      /* Pass ordinary click */
      StateManager::instance()->xmKey(INPUT_DOWN, XMKey(Event->button.button));
    }
    fLastMouseClickTime = getXMTime();
    nLastMouseClickX = nX;
    nLastMouseClickY = nY;
    nLastMouseClickButton = Event->button.button;
    
    break;
  case SDL_MOUSEBUTTONUP:
    StateManager::instance()->xmKey(INPUT_UP, XMKey(Event->button.button));
    break;

  case SDL_JOYAXISMOTION:
  StateManager::instance()->xmKey(InputHandler::instance()->joystickAxisSens(Event->jaxis.value),
				  XMKey(InputHandler::instance()->getJoyId(Event->jbutton.which),
					Event->jaxis.axis, Event->jaxis.value));
  break;
  
  case SDL_JOYBUTTONDOWN:
  StateManager::instance()->xmKey(INPUT_DOWN, XMKey(InputHandler::instance()->getJoyId(Event->jbutton.which), Event->jbutton.button));
  break;
  
  case SDL_JOYBUTTONUP:
  StateManager::instance()->xmKey(INPUT_UP, XMKey(InputHandler::instance()->getJoyId(Event->jbutton.which), Event->jbutton.button));
  break;
  
  case SDL_ACTIVEEVENT:
    
    if((Event->active.state & SDL_APPMOUSEFOCUS) != 0) { // mouse focus
      if(m_hasKeyboardFocus == false) {
	StateManager::instance()->changeFocus(Event->active.gain == 1);
      }
      m_hasMouseFocus = (Event->active.gain == 1);
    }
    
    if((Event->active.state & SDL_APPINPUTFOCUS) != 0) { // keyboard focus
      if(m_hasMouseFocus == false) {
	StateManager::instance()->changeFocus(Event->active.gain == 1);
      }
      m_hasKeyboardFocus = (Event->active.gain == 1);
    }
    
    if((Event->active.state & SDL_APPACTIVE) != 0) {
      StateManager::instance()->changeVisibility(Event->active.gain == 1);
      m_isIconified = (Event->active.gain == 0);
    }
  }
}

void GameApp::run_loop() {
  SDL_Event Event;
  int v_frameTime = 0;

  while(m_bQuit == false) {

    /* strategie :
       no network :
         update // done on the same computer as rendering, so, if update is late, rendering is late and so on
         render
         wait(so that 0.01 seconds by loop happend)

       network:
         update
	 render // skip rendering if late to let others tasks happend (rendering is the biggest cost)
         update network (wait for network if nothing to do so that 0.01 seconds by loop happend or skip if no time)
    */

    // computer the delta
    if(NetClient::instance()->isConnected()) {
      v_frameTime = 1000/StateManager::instance()->getMaxFps();

      // update the delta time to the reality
      m_frameLate += (GameApp::getXMTimeInt() - m_lastFrameTimeStamp) - v_frameTime; // update the delta

      // too much delta, reset the delta
      if(m_frameLate > 100 || m_frameLate < -100) {
	m_frameLate = 0;
      }
      m_lastFrameTimeStamp = GameApp::getXMTimeInt();
    }
    //

    // update the game

    /* Handle SDL events */            
    SDL_PumpEvents();

    // wait on event if xmoto won't be update/rendered
    if(StateManager::instance()->needUpdateOrRender()) {
      while(SDL_PollEvent(&Event)) {
	manageEvent(&Event);
      }
    } else {
      if(SDL_WaitEvent(&Event) == 1) {
	manageEvent(&Event);
      }
      while(SDL_PollEvent(&Event)) {
	manageEvent(&Event);
      }
    }

    /* Update user app */
    // update sound
    Sound::update();

    // update game
    StateManager::instance()->update();

    // update graphics
    // skip rendering if too much late (network mode)
    if(NetClient::instance()->isConnected()) {
      if(m_frameLate < XM_MAX_FRAMELATE_TO_FORCE_NORENDERING || m_loopWithoutRendering > XM_MAX_NB_LOOPS_WITH_NORENDERING) {
	StateManager::instance()->render();
	m_loopWithoutRendering = 0;
      } else {
	m_loopWithoutRendering++;
	//printf("skip rendering (%i)\n", m_loopWithoutRendering);
      }
    } else {
      StateManager::instance()->render();
    }

    // update network
    // skip network update if not the time
    if(NetClient::instance()->isConnected()) {
      int v_timeout = v_frameTime - (GameApp::getXMTimeInt() - m_lastFrameTimeStamp) - m_frameLate;

      if(m_loopWithoutNetwork > XM_MAX_NB_LOOPS_WITH_NONETWORK) {
	v_timeout = 1; // force a minimum network
	//printf("force networking\n");
      }

      // manage network
      if(v_timeout > 0 || XMSession::instance()->timedemo()) { // only when you've time to do it
	NetClient::instance()->manageNetwork(v_timeout, xmDatabase::instance("main"));
	m_loopWithoutNetwork = 0;
      } else {
	m_loopWithoutNetwork++;
      }
    } else {
      /* pause system without having to wait for the net at the same time */
      if(XMSession::instance()->timedemo() == false) {
	GameApp::wait(m_lastFrameTimeStamp, m_frameLate, StateManager::instance()->getMaxFps());
      }
    }
  }
}

void GameApp::run_unload() {

  if(Logger::isInitialized()) {
    LogInfo("UserUnload started at %.3f", GameApp::getXMTime());
  }

  if(m_pWebHighscores != NULL) {
    delete m_pWebHighscores;
  }        

  if(m_pWebLevels != NULL) {
    delete m_pWebLevels;
  }    

  if(InputHandler::instance() != NULL) {
    InputHandler::instance()->uninit(); // uinit the input, but you can still save the config
  }

  uninitNetwork();

  // detroy the demo
  if(m_xmdemo != NULL) {
    m_xmdemo->destroyFiles();
    delete m_xmdemo;
  }

  StateManager::destroy();
  
  if(Sound::isInitialized()) {
    Sound::uninit();
  }

  if(m_isODEInitialized ==  true){
    dCloseODE(); // uninit ODE
  }

  SysMessage::destroy();  

  if(Logger::isInitialized()) {
    LogDebug("UserUnload saveConfig at %.3f", GameApp::getXMTime());
  }
  if(drawLib != NULL) { /* save config only if drawLib was initialized */
    XMSession::instance("file")->save(m_userConfig, xmDatabase::instance("main"));
    InputHandler::instance()->saveConfig(m_userConfig, xmDatabase::instance("main"), XMSession::instance("file")->profile());
    m_userConfig->saveFile();
  }

  if(Logger::isInitialized()) {
    LogDebug("UserUnload saveConfig ended at %.3f", GameApp::getXMTime());
  }

  if(drawLib != NULL) {
    drawLib->unInit();
  }

  InputHandler::destroy();
  LevelsManager::destroy();
  GeomsManager::destroy();
  Theme::destroy();
  XMSession::destroy("live");
  XMSession::destroy("file");

  if(Logger::isInitialized()) {
    LogInfo("UserUnload ended at %.3f", GameApp::getXMTime());
  }

  /* Shutdown SDL */
  SDL_Quit();

  XMLDocument::clean();
    
  if(Logger::isInitialized()) {
    Logger::uninit();
  }

  Environment::uninit();

  if(XMFS::isInitialized()) {
    XMFS::uninit();
  }
}


 void GameApp::wait(int& io_lastFrameTimeStamp, int& io_frameLate, int i_maxFps)
{
  if(io_lastFrameTimeStamp < 0){
    io_lastFrameTimeStamp = getXMTimeInt();
  }

  /* Does app want us to delay a bit after the frame? */
  int currentTimeStamp        = getXMTimeInt();
  int currentFrameMinDuration = 1000/i_maxFps;
  int lastFrameDuration       = currentTimeStamp - io_lastFrameTimeStamp;
  // late from the lasts frame is not forget
  int delta = currentFrameMinDuration - (lastFrameDuration + io_frameLate);

  // if we have toooo much late (1/10 second), let reset delta
  int maxDelta = -100;
  if(delta < maxDelta){
    delta = 0;
  }

  if(delta > 0){
    // we're in advance
    // -> sleep
    int beforeSleep = getXMTimeInt();
    SDL_Delay(delta);
    int afterSleep  = getXMTimeInt();
    int sleepTime   = afterSleep - beforeSleep;

    // now that we have sleep, see if we don't have too much sleep
    if(sleepTime >= delta){
      int tooMuchSleep = sleepTime - delta;
      io_frameLate      = tooMuchSleep;
    }
  }
  else{
    // we're late
    // -> update late time
    io_frameLate = (-delta);
  }

  // the sleeping time is not included in the next frame time
  io_lastFrameTimeStamp = getXMTimeInt();
}


  /*===========================================================================
  Update loading screen
  ===========================================================================*/
 void GameApp::_UpdateLoadingShell(const std::string &NextTask, int i_percentage) {
   char buf[XMSERVER_BUF]; // max line size allowed

   printf("\r%" XMSERVER_STRBUF "s", ""); // erase
   if(i_percentage >= 0) {
     snprintf(buf, XMSERVER_BUF, "%s (%i%%)", NextTask.c_str(), i_percentage);
   } else {
     snprintf(buf, XMSERVER_BUF, "%s", NextTask.c_str());
   }
   printf("\r%s", buf);
   fflush(stdout);
 }

  void GameApp::_UpdateLoadingScreen(const std::string &NextTask, int i_percentage) {
    FontManager* v_fm;
    FontGlyph* v_fg;
    int v_fh;
    RenderSurface v_screen(Vector2i(0,0), Vector2i(getDrawLib()->getDispWidth(), getDrawLib()->getDispHeight()));

    getDrawLib()->clearGraphics();
    getDrawLib()->resetGraphics();

    v_fm = getDrawLib()->getFontBig();
    v_fg = v_fm->getGlyph(GAMETEXT_LOADING);
    v_fh = v_fg->realHeight();
    v_fm->printString(getDrawLib(), v_fg,
		      v_screen.getDispWidth()/2 - 256,
		      v_screen.getDispHeight()/2 - 30,
		      MAKE_COLOR(255,255,255, 255));
    
    if(NextTask != "") {
      v_fm = getDrawLib()->getFontSmall();
      v_fg = v_fm->getGlyph(NextTask);
      v_fm->printString(getDrawLib(), v_fg,
			v_screen.getDispWidth()/2 - 256,
			v_screen.getDispHeight()/2 -30 + v_fh + 2,
			MAKE_COLOR(255,255,255,255));      
    }

    if(i_percentage != -1) {
      getDrawLib()->drawBox(Vector2f(0,
				     v_screen.getDispHeight() - 5),
			    Vector2f(((int)(v_screen.getDispWidth()*((float)(i_percentage))/100.0)),
				     v_screen.getDispHeight()),
			    0,MAKE_COLOR(255,255,255,255));
    }

    getDrawLib()->flushGraphics();
  }


  void GameApp::initNetwork(bool i_forceNoServerStarted, bool i_forceNoClientStarted) {
  if(SDLNet_Init()==-1) {
    throw Exception(SDLNet_GetError());
  }

  // start server if gui
  if(i_forceNoServerStarted == false) {
    if(XMSession::instance()->serverStartAtStartup()) {
      NetServer::instance()->start(true, XMSession::instance()->serverPort()); // in graphics mode, use the port of the options
    }
  }

  if(i_forceNoClientStarted == false) {
    if(XMSession::instance()->clientConnectAtStartup()) {

      /* special case : if xmoto is it's own server, you must wait that the server is started
	 test ip is not a good solution, by the way, people starting the server
	 should use it or lost less than 1 second at startup
       */
      if(XMSession::instance()->serverStartAtStartup()) {
	// wait that server is started
	unsigned int v_delay = 0;
	while(NetServer::instance()->acceptConnections() == false && v_delay < 5000 /* wait maximum 5 seconds the server */) {
	  LogInfo("Server still not accepting connections, wait (%.2f seconds)", v_delay/1000.0);
	  SDL_Delay(100);
	  v_delay += 100;
	}
      }

      try {
	NetClient::instance()->connect(XMSession::instance()->clientServerName(),
				       XMSession::instance()->clientServerPort());
	// don't send in ghost mode to be compatible with old servers
	if(XMSession::instance()->clientGhostMode() == false) {
	  NetClient::instance()->changeMode(XMSession::instance()->clientGhostMode() ? NETCLIENT_GHOST_MODE : NETCLIENT_SLAVE_MODE);
	}
      } catch(Exception &e) {
	SysMessage::instance()->displayError(GAMETEXT_UNABLETOCONNECTONTHESERVER);
	LogError("Unable to connect to the server");
      }
    }
  }

}

void GameApp::uninitNetwork() {
  // stop the client
  if(NetClient::instance()->isConnected()) {
    NetClient::instance()->disconnect();
  }
  NetClient::destroy();

  if(NetServer::instance()->isStarted()) {
    NetServer::instance()->stop();
  }

  NetServer::destroy();

  if(Logger::isInitialized()) {
    NetAction::logStats();
    ActionReader::logStats();
  }

  SDLNet_Quit();
}