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 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
|
#include "StdAfx.h"
#include "Rendering/GL/myGL.h"
#include <iostream>
#include <signal.h>
#include <SDL.h>
#include <SDL_syswm.h>
#include "mmgr.h"
#include "SpringApp.h"
#undef KeyPress
#undef KeyRelease
#include "Sim/Misc/GlobalSynced.h"
#include "Game/GameVersion.h"
#include "Game/GameSetup.h"
#include "Game/ClientSetup.h"
#include "Game/GameController.h"
#include "Menu/SelectMenu.h"
#include "Game/PreGame.h"
#include "Game/Game.h"
#include "Sim/Misc/Team.h"
#include "Game/UI/KeyBindings.h"
#include "Game/UI/MouseHandler.h"
#include "Lua/LuaOpenGL.h"
#include "Platform/BaseCmd.h"
#include "Platform/Misc.h"
#include "ConfigHandler.h"
#include "Platform/errorhandler.h"
#include "Platform/CrashHandler.h"
#include "FileSystem/FileSystemHandler.h"
#include "FileSystem/FileHandler.h"
#include "ExternalAI/IAILibraryManager.h"
#include "Rendering/glFont.h"
#include "Rendering/GLContext.h"
#include "Rendering/VerticalSync.h"
#include "Rendering/Textures/TAPalette.h"
#include "Rendering/Textures/NamedTextures.h"
#include "Rendering/Textures/TextureAtlas.h"
#include "aGui/Gui.h"
#include "Sim/Projectiles/ExplosionGenerator.h"
#include "Sim/Misc/GlobalConstants.h"
#include "LogOutput.h"
#include "MouseInput.h"
#include "InputHandler.h"
#include "Joystick.h"
#include "bitops.h"
#include "GlobalUnsynced.h"
#include "Util.h"
#include "myMath.h"
#include "FPUCheck.h"
#include "Exceptions.h"
#include "System/TimeProfiler.h"
#include "System/Sound/Sound.h"
#include "mmgr.h"
#ifdef WIN32
#include "Platform/Win/win32.h"
#include <winreg.h>
#include <direct.h>
#include "Platform/Win/WinVersion.h"
#endif // WIN32
#ifdef USE_GML
#include "lib/gml/gmlsrv.h"
extern gmlClientServer<void, int,CUnit*> *gmlProcessor;
#endif
using std::string;
CGameController* activeController = 0;
bool globalQuit = false;
boost::uint8_t *keys = 0;
boost::uint16_t currentUnicode = 0;
bool fullscreen = true;
/**
* @brief xres default
*
* Defines the default X resolution as 1024
*/
const int XRES_DEFAULT = 1024;
/**
* @brief yres default
*
* Defines the default Y resolution as 768
*/
const int YRES_DEFAULT = 768;
/**
* Initializes SpringApp variables
*/
SpringApp::SpringApp()
{
cmdline = 0;
screenWidth = screenHeight = 0;
FSAA = false;
lastRequiredDraw=0;
}
/**
* Destroys SpringApp variables
*/
SpringApp::~SpringApp()
{
if (cmdline) delete cmdline;
if (keys) delete[] keys;
creg::System::FreeClasses ();
}
/**
* @brief Initializes the SpringApp instance
* @return whether initialization was successful
*/
bool SpringApp::Initialize()
{
#if defined(_WIN32) && defined(__GNUC__)
// load QTCreator's gdb helper dll; a variant of this should also work on other OSes
{
// don't display a dialog box if gdb helpers aren't found
UINT olderrors = SetErrorMode(SEM_FAILCRITICALERRORS);
if(LoadLibrary("gdbmacros.dll")) {
LogObject() << "QT Creator's gdbmacros.dll loaded";
}
SetErrorMode(olderrors);
}
#endif
// Initialize class system
creg::System::InitializeClasses();
// Initialize crash reporting
CrashHandler::Install();
ParseCmdLine();
CMyMath::Init();
good_fpu_control_registers("::Run");
// log OS version
// TODO: improve version logging of non-Windows OSes
logOutput.Print("OS: %s", Platform::GetOS().c_str());
if (Platform::Is64Bit())
logOutput.Print("OS: 64bit native mode");
else if (Platform::Is32BitEmulation())
logOutput.Print("OS: emulated 32bit mode");
else
logOutput.Print("OS: 32bit native mode");
FileSystemHandler::Initialize(true);
UpdateOldConfigs();
if (!InitWindow(("Spring " + SpringVersion::Get()).c_str())) {
SDL_Quit();
return false;
}
mouseInput = IMouseInput::Get();
// Global structures
gs = new CGlobalSyncedStuff();
gu = new CGlobalUnsyncedStuff();
if (cmdline->IsSet("minimise")) {
gu->active = false;
SDL_WM_IconifyWindow();
}
InitOpenGL();
agui::InitGui();
palette.Init();
// Initialize keyboard
SDL_EnableUNICODE(1);
SDL_EnableKeyRepeat (SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
SDL_SetModState (KMOD_NONE);
input.AddHandler(boost::bind(&SpringApp::MainEventHandler, this, _1));
keys = new boost::uint8_t[SDLK_LAST];
memset (keys,0,sizeof(boost::uint8_t)*SDLK_LAST);
LoadFonts();
// Initialize GLEW
LoadExtensions();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
SDL_GL_SwapBuffers();
// Runtime compress textures?
if (GLEW_ARB_texture_compression) {
// we don't even need to check it, 'cos groundtextures must have that extension
// default to off because it reduces quality (smallest mipmap level is bigger)
gu->compressTextures = !!configHandler->Get("CompressTextures", 0);
}
// use some ATI bugfixes?
if ((gu->atiHacks = !!configHandler->Get("AtiHacks", gu->haveATI? 1: 0))) {
logOutput.Print("ATI hacks enabled\n");
}
// Initialize named texture handler
CNamedTextures::Init();
// Initialize Lua GL
LuaOpenGL::Init();
#ifdef WIN32
int affinity = configHandler->Get("SetCoreAffinity", 0);
if (affinity>0) {
//! Get the available cores
DWORD curMask;
DWORD cores;
GetProcessAffinityMask(GetCurrentProcess(), &curMask, &cores);
DWORD wantedCore = 0xff;
//! Find an useable core
cores /= 0x1;
while( (wantedCore & cores) == 0x0 ) {
wantedCore >>= 0x1;
}
//! Set the affinity
HANDLE thread = GetCurrentThread();
if (affinity==1) {
SetThreadIdealProcessor(thread,wantedCore);
} else if (affinity>=2) {
SetThreadAffinityMask(thread,wantedCore);
}
}
#endif // WIN32
InitJoystick();
// Create CGameSetup and CPreGame objects
Startup();
return true;
}
/**
* @brief multisample test
* @return whether the multisampling test was successful
*
* Tests if a user has requested FSAA, if it's a valid
* FSAA mode, and if it's supported by the current GL context
*/
static bool MultisampleTest(void)
{
if (!GL_ARB_multisample)
return false;
GLuint fsaa = configHandler->Get("FSAA",0);
if (!fsaa)
return false;
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS,1);
GLuint fsaalevel = std::max(std::min(configHandler->Get("FSAALevel", 2), 8), 0);
make_even_number(fsaalevel);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES,fsaalevel);
return true;
}
/**
* @brief multisample verify
* @return whether verification passed
*
* Tests whether FSAA was actually enabled
*/
static bool MultisampleVerify(void)
{
GLint buffers, samples;
glGetIntegerv(GL_SAMPLE_BUFFERS_ARB, &buffers);
glGetIntegerv(GL_SAMPLES_ARB, &samples);
if (buffers && samples) {
return true;
}
return false;
}
/**
* @return whether window initialization succeeded
* @param title char* string with window title
*
* Initializes the game window
*/
bool SpringApp::InitWindow(const char* title)
{
unsigned int sdlInitFlags = SDL_INIT_VIDEO | SDL_INIT_TIMER;
#ifdef WIN32
// the crash reporter should be catching the errors
sdlInitFlags |= SDL_INIT_NOPARACHUTE;
#endif
if ((SDL_Init(sdlInitFlags) == -1)) {
logOutput.Print("Could not initialize SDL: %s", SDL_GetError());
return false;
}
// Sets window manager properties
SDL_WM_SetIcon(SDL_LoadBMP("spring.bmp"),NULL);
SDL_WM_SetCaption(title, title);
if (!SetSDLVideoMode()) {
logOutput.Print("Failed to set SDL video mode: %s", SDL_GetError());
return false;
}
RestoreWindowPosition();
glClearColor(0.0f,0.0f,0.0f,0.0f);
glClear(GL_COLOR_BUFFER_BIT);
SDL_GL_SwapBuffers();
return true;
}
/**
* @return whether setting the video mode was successful
*
* Sets SDL video mode options/settings
*/
bool SpringApp::SetSDLVideoMode()
{
int sdlflags = SDL_OPENGL | SDL_RESIZABLE;
//conditionally_set_flag(sdlflags, SDL_FULLSCREEN, fullscreen);
sdlflags |= fullscreen ? SDL_FULLSCREEN : 0;
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); // enable alpha channel
depthBufferBits = configHandler->Get("DepthBufferBits", 24);
if (gu) gu->depthBufferBits = depthBufferBits;
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, depthBufferBits);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, configHandler->Get("StencilBufferBits", 8));
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
FSAA = MultisampleTest();
SDL_Surface *screen = SDL_SetVideoMode(screenWidth, screenHeight, 32, sdlflags);
if (!screen) {
char buf[1024];
SNPRINTF(buf, sizeof(buf), "Could not set video mode:\n%s", SDL_GetError());
handleerror(NULL, buf, "ERROR", MBF_OK|MBF_EXCL);
return false;
}
#ifdef STREFLOP_H
// Something in SDL_SetVideoMode (OpenGL drivers?) messes with the FPU control word.
// Set single precision floating point math.
streflop_init<streflop::Simple>();
#endif
if (FSAA) {
FSAA = MultisampleVerify();
}
// setup GL smoothing
const int defaultSmooth = 0; // FSAA ? 0 : 3; // until a few things get fixed
const int lineSmoothing = configHandler->Get("SmoothLines", defaultSmooth);
if (lineSmoothing > 0) {
GLenum hint = GL_FASTEST;
if (lineSmoothing >= 3) {
hint = GL_NICEST;
} else if (lineSmoothing >= 2) {
hint = GL_DONT_CARE;
}
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, hint);
}
const int pointSmoothing = configHandler->Get("SmoothPoints", defaultSmooth);
if (pointSmoothing > 0) {
GLenum hint = GL_FASTEST;
if (pointSmoothing >= 3) {
hint = GL_NICEST;
} else if (pointSmoothing >= 2) {
hint = GL_DONT_CARE;
}
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, hint);
}
// setup LOD bias factor
const float lodBias = std::max(std::min( configHandler->Get("TextureLODBias", 0.0f) , 4.0f), -4.0f);
if (fabs(lodBias)>0.01f) {
glTexEnvf(GL_TEXTURE_FILTER_CONTROL,GL_TEXTURE_LOD_BIAS, lodBias );
}
// there must be a way to see if this is necessary, compare old/new context pointers?
if (!!configHandler->Get("FixAltTab", 0)) {
// free GL resources
GLContext::Free();
// initialize any GL resources that were lost
GLContext::Init();
}
int bits;
SDL_GL_GetAttribute(SDL_GL_BUFFER_SIZE, &bits);
logOutput.Print("Video mode set to %i x %i / %i bit", screenWidth, screenHeight, bits );
VSync.Init();
return true;
}
// origin for our coordinates is the bottom left corner
bool SpringApp::GetDisplayGeometry()
{
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
if (!SDL_GetWMInfo(&info)) {
return false;
}
#ifdef __APPLE__
// todo: enable this function, RestoreWindowPosition() and SaveWindowPosition() on Mac
return false;
#elif !defined(_WIN32)
info.info.x11.lock_func();
{
Display* display = info.info.x11.display;
Window window = info.info.x11.window;
XWindowAttributes attrs;
XGetWindowAttributes(display, window, &attrs);
const Screen* screen = attrs.screen;
gu->screenSizeX = WidthOfScreen(screen);
gu->screenSizeY = HeightOfScreen(screen);
gu->winSizeX = attrs.width;
gu->winSizeY = attrs.height;
Window tmp;
int xp, yp;
XTranslateCoordinates(display, window, attrs.root, 0, 0, &xp, &yp, &tmp);
windowPosX = xp;
windowPosY = yp;
}
info.info.x11.unlock_func();
#else
gu->screenSizeX = GetSystemMetrics(SM_CXFULLSCREEN);
gu->screenSizeY = GetSystemMetrics(SM_CYFULLSCREEN);
RECT rect;
if (!GetClientRect(info.window, &rect)) {
return false;
}
if ((rect.right - rect.left) == 0 || (rect.bottom - rect.top) == 0)
return false;
gu->winSizeX = rect.right - rect.left;
gu->winSizeY = rect.bottom - rect.top;
// translate from client coords to screen coords
MapWindowPoints(info.window, HWND_DESKTOP, (LPPOINT)&rect, 2);
// GetClientRect doesn't do the right thing for restoring window position
if (!fullscreen) {
GetWindowRect(info.window, &rect);
}
windowPosX = rect.left;
windowPosY = rect.top;
#endif // _WIN32
gu->winPosX = windowPosX;
gu->winPosY = gu->screenSizeY - gu->winSizeY - windowPosY; //! origin BOTTOMLEFT
return true;
}
void SpringApp::SetupViewportGeometry()
{
if (!GetDisplayGeometry()) {
gu->screenSizeX = screenWidth;
gu->screenSizeY = screenHeight;
gu->winSizeX = screenWidth;
gu->winSizeY = screenHeight;
gu->winPosX = 0;
gu->winPosY = 0;
}
gu->dualScreenMode = !!configHandler->Get("DualScreenMode", 0);
if (gu->dualScreenMode) {
gu->dualScreenMiniMapOnLeft =
!!configHandler->Get("DualScreenMiniMapOnLeft", 0);
} else {
gu->dualScreenMiniMapOnLeft = false;
}
if (!gu->dualScreenMode) {
gu->viewSizeX = gu->winSizeX;
gu->viewSizeY = gu->winSizeY;
gu->viewPosX = 0;
gu->viewPosY = 0;
}
else {
gu->viewSizeX = gu->winSizeX / 2;
gu->viewSizeY = gu->winSizeY;
if (gu->dualScreenMiniMapOnLeft) {
gu->viewPosX = gu->winSizeX / 2;
gu->viewPosY = 0;
} else {
gu->viewPosX = 0;
gu->viewPosY = 0;
}
}
agui::gui->UpdateScreenGeometry(
gu->viewSizeX,
gu->viewSizeY,
gu->viewPosX,
(gu->winSizeY - gu->viewSizeY - gu->viewPosY) );
gu->pixelX = 1.0f / (float)gu->viewSizeX;
gu->pixelY = 1.0f / (float)gu->viewSizeY;
// NOTE: gu->viewPosY is not currently used
gu->aspectRatio = (float)gu->viewSizeX / (float)gu->viewSizeY;
}
/**
* Initializes OpenGL
*/
void SpringApp::InitOpenGL()
{
SetupViewportGeometry();
glViewport(gu->viewPosX, gu->viewPosY, gu->viewSizeX, gu->viewSizeY);
gluPerspective(45.0f, (GLfloat)gu->viewSizeX / (GLfloat)gu->viewSizeY, 2.8f, MAX_VIEW_RANGE);
// Initialize some GL states
glShadeModel(GL_SMOOTH);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
}
void SpringApp::UpdateOldConfigs()
{
// not very neat, should be done in the installer someday
const int cfgVersion = configHandler->Get("Version",0);
if (cfgVersion < 2) {
// force an update to new defaults
configHandler->Delete("FontFile");
configHandler->Delete("FontSize");
configHandler->Delete("SmallFontSize");
configHandler->Delete("StencilBufferBits"); //! update to 8 bits
configHandler->Delete("DepthBufferBits"); //! update to 24bits
configHandler->Set("Version",2);
}
}
void SpringApp::LoadFonts()
{
// Initialize font
const std::string fontFile = configHandler->GetString("FontFile", "fonts/FreeSansBold.otf");
const std::string smallFontFile = configHandler->GetString("SmallFontFile", "fonts/FreeSansBold.otf");
const int fontSize = configHandler->Get("FontSize", 23);
const int smallFontSize = configHandler->Get("SmallFontSize", 14);
const int outlineWidth = configHandler->Get("FontOutlineWidth", 3);
const float outlineWeight = configHandler->Get("FontOutlineWeight", 25.0f);
const int smallOutlineWidth = configHandler->Get("SmallFontOutlineWidth", 2);
const float smallOutlineWeight = configHandler->Get("SmallFontOutlineWeight", 10.0f);
SafeDelete(font);
SafeDelete(smallFont);
font = CglFont::LoadFont(fontFile, fontSize, outlineWidth, outlineWeight);
smallFont = CglFont::LoadFont(smallFontFile, smallFontSize, smallOutlineWidth, smallOutlineWeight);
if (!font || !smallFont) {
std::vector<std::string> fonts = CFileHandler::DirList("fonts/", "*.*tf", SPRING_VFS_RAW_FIRST);
std::vector<std::string>::iterator fi = fonts.begin();
while (fi != fonts.end()) {
SafeDelete(font);
SafeDelete(smallFont);
font = CglFont::LoadFont(*fi, fontSize, outlineWidth, outlineWeight);
smallFont = CglFont::LoadFont(*fi, smallFontSize, smallOutlineWidth, smallOutlineWeight);
if (font && smallFont) {
break;
} else {
fi++;
}
}
if (!font) {
throw content_error(std::string("Failed to load font: ") + fontFile);
} else if (!smallFont) {
throw content_error(std::string("Failed to load font: ") + smallFontFile);
}
configHandler->SetString("FontFile", *fi);
configHandler->SetString("SmallFontFile", *fi);
}
}
/**
* @return whether commandline parsing was successful
*
* Parse command line arguments
*/
void SpringApp::ParseCmdLine()
{
cmdline->AddSwitch('f', "fullscreen", "Run in fullscreen mode");
cmdline->AddSwitch('w', "window", "Run in windowed mode");
cmdline->AddInt( 'x', "xresolution", "Set X resolution");
cmdline->AddInt( 'y', "yresolution", "Set Y resolution");
cmdline->AddSwitch('m', "minimise", "Start minimised");
cmdline->AddSwitch('s', "server", "Run as a server");
cmdline->AddSwitch('c', "client", "Run as a client");
cmdline->AddSwitch('p', "projectiledump", "Dump projectile class info in projectiles.txt");
cmdline->AddSwitch('t', "textureatlas", "Dump each finalized textureatlas in textureatlasN.tga");
cmdline->AddString('n', "name", "Set your player name");
cmdline->AddString('C', "config", "Configuration file");
cmdline->AddSwitch(0, "list-ai-interfaces", "Dump a list of available AI Interfaces to stdout");
cmdline->AddSwitch(0, "list-skirmish-ais", "Dump a list of available Skirmish AIs to stdout");
try
{
cmdline->Parse();
}
catch (const std::exception& err)
{
std::cerr << err.what() << std::endl << std::endl;
cmdline->PrintUsage("Spring", SpringVersion::GetFull());
exit(1);
}
// mutually exclusive options that cause spring to quit immediately
if (cmdline->IsSet("help")) {
cmdline->PrintUsage("Spring",SpringVersion::GetFull());
exit(0);
} else if (cmdline->IsSet("version")) {
std::cout << "Spring " << SpringVersion::GetFull() << std::endl;
exit(0);
} else if (cmdline->IsSet("projectiledump")) {
CCustomExplosionGenerator::OutputProjectileClassInfo();
exit(0);
}
if (cmdline->IsSet("config")) {
string configSource = cmdline->GetString("config");
logOutput.Print("using configuration source \"" + ConfigHandler::Instantiate(configSource) + "\"");
} else {
logOutput.Print("using default configuration source \"" + ConfigHandler::Instantiate() + "\"");
}
// mutually exclusive options that cause spring to quit immediately
// and require the configHandler
if (cmdline->IsSet("list-ai-interfaces")) {
IAILibraryManager::OutputAIInterfacesInfo();
exit(0);
} else if (cmdline->IsSet("list-skirmish-ais")) {
IAILibraryManager::OutputSkirmishAIInfo();
exit(0);
}
#ifdef _DEBUG
fullscreen = false;
#else
fullscreen = !!configHandler->Get("Fullscreen", 1);
#endif
// flags
if (cmdline->IsSet("window")) {
fullscreen = false;
} else if (cmdline->IsSet("fullscreen")) {
fullscreen = true;
}
if (cmdline->IsSet("textureatlas")) {
CTextureAtlas::debug = true;
}
if (cmdline->IsSet("name")) {
const string name = cmdline->GetString("name");
if (!name.empty()) {
configHandler->SetString("name", StringReplace(name, " ", "_"));
}
}
screenWidth = configHandler->Get("XResolution", XRES_DEFAULT);
if (cmdline->IsSet("xresolution"))
screenWidth = std::max(cmdline->GetInt("xresolution"), 640);
screenHeight = configHandler->Get("YResolution", YRES_DEFAULT);
if (cmdline->IsSet("yresolution"))
screenHeight = std::max(cmdline->GetInt("yresolution"), 480);
windowPosX = configHandler->Get("WindowPosX", 32);
windowPosY = configHandler->Get("WindowPosY", 32);
windowState = configHandler->Get("WindowState", 0);
#ifdef USE_GML
gmlThreadCountOverride = configHandler->Get("HardwareThreadCount", 0);
gmlThreadCount=GML_CPU_COUNT;
#if GML_ENABLE_SIM
extern volatile int gmlMultiThreadSim;
gmlMultiThreadSim=configHandler->Get("MultiThreadSim", 1);
#endif
#endif
}
/**
* Initializes instance of GameSetup
*/
void SpringApp::Startup()
{
std::string inputFile = cmdline->GetInputFile();
if (inputFile.empty())
{
bool server = !cmdline->IsSet("client") || cmdline->IsSet("server");
#ifdef SYNCDEBUG
CSyncDebugger::GetInstance()->Initialize(server, 64);
#endif
activeController = new SelectMenu(server);
}
else if (inputFile.rfind("sdf") == inputFile.size() - 3)
{
std::string demoFileName = inputFile;
std::string demoPlayerName = configHandler->GetString("name", "UnnamedPlayer");
if (demoPlayerName.empty()) {
demoPlayerName = "UnnamedPlayer";
} else {
demoPlayerName = StringReplaceInPlace(demoPlayerName, ' ', '_');
}
demoPlayerName += " (spec)";
ClientSetup* startsetup = new ClientSetup();
startsetup->isHost = true; // local demo play
startsetup->myPlayerName = demoPlayerName;
#ifdef SYNCDEBUG
CSyncDebugger::GetInstance()->Initialize(true, 64); //FIXME: add actual number of player
#endif
pregame = new CPreGame(startsetup);
pregame->LoadDemo(demoFileName);
}
else if (inputFile.rfind("ssf") == inputFile.size() - 3)
{
std::string savefile = inputFile;
ClientSetup* startsetup = new ClientSetup();
startsetup->isHost = true;
startsetup->myPlayerName = configHandler->GetString("name", "unnamed");
#ifdef SYNCDEBUG
CSyncDebugger::GetInstance()->Initialize(true, 64); //FIXME: add actual number of player
#endif
pregame = new CPreGame(startsetup);
pregame->LoadSavefile(savefile);
}
else
{
LogObject() << "Loading startscript from: " << inputFile;
std::string startscript = inputFile;
CFileHandler fh(startscript);
if (!fh.FileExists())
throw content_error("Setup-script does not exist in given location: "+startscript);
std::string buf;
if (!fh.LoadStringData(buf))
throw content_error("Setup-script cannot be read: " + startscript);
ClientSetup* startsetup = new ClientSetup();
startsetup->Init(buf);
// commandline parameters overwrite setup
if (cmdline->IsSet("client"))
startsetup->isHost = false;
else if (cmdline->IsSet("server"))
startsetup->isHost = true;
#ifdef SYNCDEBUG
CSyncDebugger::GetInstance()->Initialize(startsetup->isHost, 64); //FIXME: add actual number of player
#endif
pregame = new CPreGame(startsetup);
if (startsetup->isHost)
pregame->LoadSetupscript(buf);
}
}
#if defined(USE_GML) && GML_ENABLE_SIM
volatile int gmlMultiThreadSim;
volatile int gmlStartSim;
int SpringApp::Sim()
{
while(gmlKeepRunning && !gmlStartSim)
SDL_Delay(100);
while(gmlKeepRunning) {
if(!gmlMultiThreadSim) {
CrashHandler::ClearSimWDT(true);
while(!gmlMultiThreadSim && gmlKeepRunning)
SDL_Delay(200);
}
else if (activeController) {
CrashHandler::ClearSimWDT();
gmlProcessor->ExpandAuxQueue();
{
GML_STDMUTEX_LOCK(sim); // Sim
if (!activeController->Update()) {
return 0;
}
}
gmlProcessor->GetQueue();
}
boost::thread::yield();
}
return 1;
}
#endif
/**
* @return return code of activecontroller draw function
*
* Draw function repeatedly called, it calls all the
* other draw functions
*/
int SpringApp::Update()
{
if (FSAA)
glEnable(GL_MULTISAMPLE_ARB);
int ret = 1;
if (activeController) {
#if !defined(USE_GML) || !GML_ENABLE_SIM
if (!activeController->Update()) {
ret = 0;
} else {
#else
if(gmlMultiThreadSim) {
if(!gs->frameNum) {
GML_STDMUTEX_LOCK(sim); // Update
activeController->Update();
if(gs->frameNum)
gmlStartSim=1;
}
}
else {
GML_STDMUTEX_LOCK(sim); // Update
activeController->Update();
}
#endif
if(game)
CrashHandler::ClearDrawWDT();
gu->drawFrame++;
if (gu->drawFrame == 0) {
gu->drawFrame++;
}
if(
#if defined(USE_GML) && GML_ENABLE_SIM
!gmlMultiThreadSim &&
#endif
gs->frameNum-lastRequiredDraw >= (float)MAX_CONSECUTIVE_SIMFRAMES * gs->userSpeedFactor) {
ScopedTimer cputimer("CPU load"); // Update
ret = activeController->Draw();
lastRequiredDraw=gs->frameNum;
}
else {
ret = activeController->Draw();
}
#if defined(USE_GML) && GML_ENABLE_SIM
gmlProcessor->PumpAux();
#else
}
#endif
}
VSync.Delay();
SDL_GL_SwapBuffers();
if (FSAA)
glDisable(GL_MULTISAMPLE_ARB);
return ret;
}
/**
* Tests SDL keystates and sets values
* in key array
*/
void SpringApp::UpdateSDLKeys ()
{
int numkeys;
boost::uint8_t *state;
state = SDL_GetKeyState(&numkeys);
memcpy(keys, state, sizeof(boost::uint8_t) * numkeys);
const SDLMod mods = SDL_GetModState();
keys[SDLK_LALT] = (mods & KMOD_ALT) ? 1 : 0;
keys[SDLK_LCTRL] = (mods & KMOD_CTRL) ? 1 : 0;
keys[SDLK_LMETA] = (mods & KMOD_META) ? 1 : 0;
keys[SDLK_LSHIFT] = (mods & KMOD_SHIFT) ? 1 : 0;
}
/**
* @param argc argument count
* @param argv array of argument strings
*
* Executes the application
* (contains main game loop)
*/
int SpringApp::Run(int argc, char *argv[])
{
cmdline = new BaseCmd(argc, argv);
if (!Initialize())
return -1;
#ifdef WIN32
//SDL_EventState (SDL_SYSWMEVENT, SDL_ENABLE);
#endif
CrashHandler::InstallHangHandler();
#ifdef USE_GML
gmlProcessor=new gmlClientServer<void, int, CUnit*>;
# if GML_ENABLE_SIM
gmlKeepRunning=1;
gmlStartSim=0;
gmlProcessor->AuxWork(&SpringApp::Simcb,this); // start sim thread
# endif
#endif
while (true) // end is handled by globalQuit
{
#ifdef WIN32
static unsigned lastreset = 0;
unsigned curreset = SDL_GetTicks();
if(gu->active && (curreset - lastreset > 1000)) {
lastreset = curreset;
int timeout; // reset screen saver timer
if(SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT, 0, &timeout, 0))
SystemParametersInfo(SPI_SETSCREENSAVETIMEOUT, timeout, NULL, 0);
}
#endif
{
SCOPED_TIMER("Input");
mouseInput->Update();
SDL_Event event;
while (SDL_PollEvent(&event)) {
input.PushEvent(event);
}
}
if (globalQuit)
break;
try {
if (!Update())
break;
} catch (content_error &e) {
LogObject() << "Caught content exception: " << e.what() << "\n";
handleerror(NULL, e.what(), "Content error", MBF_OK | MBF_EXCL);
}
}
#ifdef USE_GML
#if GML_ENABLE_SIM
gmlKeepRunning=0; // wait for sim to finish
while(!gmlProcessor->PumpAux())
boost::thread::yield();
#endif
if(gmlProcessor)
delete gmlProcessor;
#endif
CrashHandler::UninstallHangHandler();
// Shutdown
Shutdown();
return 0;
}
/**
* Restores position of the window, if we're not in fullscreen
*/
void SpringApp::RestoreWindowPosition()
{
#ifdef __APPLE__
return;
#else
if (!fullscreen) {
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
if (SDL_GetWMInfo(&info)) {
#ifdef _WIN32
bool stateChanged = false;
if (windowState > 0) {
WINDOWPLACEMENT wp;
memset(&wp,0,sizeof(WINDOWPLACEMENT));
wp.length = sizeof(WINDOWPLACEMENT);
stateChanged = true;
int wState;
switch (windowState) {
case 1: wState = SW_SHOWMAXIMIZED; break;
case 2: wState = SW_SHOWMINIMIZED; break;
default: stateChanged = false;
}
if (stateChanged) {
ShowWindow(info.window, wState);
RECT rect;
if (GetClientRect(info.window, &rect)) {
//! translate from client coords to screen coords
MapWindowPoints(info.window, HWND_DESKTOP, (LPPOINT)&rect, 2);
screenWidth = rect.right - rect.left;
screenHeight = rect.bottom - rect.top;
windowPosX = rect.left;
windowPosY = rect.top;
}
}
}
if (!stateChanged) {
MoveWindow(info.window, windowPosX, windowPosY, screenWidth, screenHeight, true);
}
#else
info.info.x11.lock_func();
{
XMoveWindow(info.info.x11.display, info.info.x11.wmwindow, windowPosX, windowPosY);
}
info.info.x11.unlock_func();
#endif
}
}
#endif // ifdef __APPLE__
}
/**
* Saves position of the window, if we're not in fullscreen
*/
void SpringApp::SaveWindowPosition()
{
#ifdef __APPLE__
return;
#else
if (!fullscreen) {
#if defined(_WIN32)
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
if (SDL_GetWMInfo(&info)) {
WINDOWPLACEMENT wp;
wp.length = sizeof(WINDOWPLACEMENT);
if (GetWindowPlacement(info.window, &wp)) {
switch (wp.showCmd) {
case SW_SHOWMAXIMIZED:
windowState = 1;
break;
case SW_SHOWMINIMIZED:
windowState = 2;
break;
default:
configHandler->Set("WindowPosX", windowPosX);
configHandler->Set("WindowPosY", windowPosY);
windowState = 0;
}
}
}
configHandler->Set("WindowState", windowState);
#else
configHandler->Set("WindowPosX", windowPosX);
configHandler->Set("WindowPosY", windowPosY);
#endif
}
#endif
}
/**
* Deallocates and shuts down game
*/
void SpringApp::Shutdown()
{
SaveWindowPosition();
if (pregame)
delete pregame; //in case we exit during init
if (game)
delete game;
delete gameSetup;
delete font;
delete smallFont;
CNamedTextures::Kill();
GLContext::Free();
ConfigHandler::Deallocate();
UnloadExtensions();
delete mouseInput;
SDL_WM_GrabInput(SDL_GRAB_OFF);
SDL_Quit();
delete gs;
delete gu;
#ifdef USE_MMGR
m_dumpMemoryReport();
#endif
}
bool SpringApp::MainEventHandler(const SDL_Event& event)
{
switch (event.type) {
case SDL_VIDEORESIZE: {
GML_STDMUTEX_LOCK(sim); // Run
CrashHandler::ClearDrawWDT(true);
screenWidth = event.resize.w;
screenHeight = event.resize.h;
#ifndef WIN32
// HACK We don't want to break resizing on windows (again?),
// so someone should test this very well before enabling it.
SetSDLVideoMode();
#endif
InitOpenGL();
activeController->ResizeEvent();
break;
}
case SDL_VIDEOEXPOSE: {
GML_STDMUTEX_LOCK(sim); // Run
CrashHandler::ClearDrawWDT(true);
// re-initialize the stencil
glClearStencil(0);
glClear(GL_STENCIL_BUFFER_BIT); SDL_GL_SwapBuffers();
glClear(GL_STENCIL_BUFFER_BIT); SDL_GL_SwapBuffers();
SetupViewportGeometry();
break;
}
case SDL_QUIT: {
globalQuit = true;
break;
}
case SDL_ACTIVEEVENT: {
CrashHandler::ClearDrawWDT(true);
if (event.active.state & SDL_APPACTIVE) {
gu->active = !!event.active.gain;
if (sound)
sound->Iconified(!event.active.gain);
}
if (mouse && mouse->locked) {
mouse->ToggleState();
}
break;
}
case SDL_KEYDOWN: {
int i = event.key.keysym.sym;
currentUnicode = event.key.keysym.unicode;
const bool isRepeat = !!keys[i];
UpdateSDLKeys ();
if (activeController) {
if (i <= SDLK_DELETE) {
i = tolower(i);
}
else if (i == SDLK_RSHIFT) { i = SDLK_LSHIFT; }
else if (i == SDLK_RCTRL) { i = SDLK_LCTRL; }
else if (i == SDLK_RMETA) { i = SDLK_LMETA; }
else if (i == SDLK_RALT) { i = SDLK_LALT; }
if (keyBindings) {
const int fakeMetaKey = keyBindings->GetFakeMetaKey();
if (fakeMetaKey >= 0) {
keys[SDLK_LMETA] |= keys[fakeMetaKey];
}
}
activeController->KeyPressed(i, isRepeat);
if (activeController->userWriting){
// use unicode for printed characters
i = event.key.keysym.unicode;
if ((i >= SDLK_SPACE) && (i <= 255)) {
CGameController* ac = activeController;
if (ac->ignoreNextChar || ac->ignoreChar == char(i)) {
ac->ignoreNextChar = false;
} else {
if (i < 255 && (!isRepeat || ac->userInput.length()>0)) {
const int len = (int)ac->userInput.length();
ac->writingPos = std::max(0, std::min(len, ac->writingPos));
char str[2] = { char(i), 0 };
ac->userInput.insert(ac->writingPos, str);
ac->writingPos++;
}
}
}
}
}
activeController->ignoreNextChar = false;
break;
}
case SDL_KEYUP: {
int i = event.key.keysym.sym;
currentUnicode = event.key.keysym.unicode;
UpdateSDLKeys();
if (activeController) {
if (i <= SDLK_DELETE) {
i = tolower(i);
}
else if (i == SDLK_RSHIFT) { i = SDLK_LSHIFT; }
else if (i == SDLK_RCTRL) { i = SDLK_LCTRL; }
else if (i == SDLK_RMETA) { i = SDLK_LMETA; }
else if (i == SDLK_RALT) { i = SDLK_LALT; }
if (keyBindings) {
const int fakeMetaKey = keyBindings->GetFakeMetaKey();
if (fakeMetaKey >= 0) {
keys[SDLK_LMETA] |= keys[fakeMetaKey];
}
}
activeController->KeyReleased(i);
}
break;
}
default:
break;
}
return false;
}
|