💿🐜 Antkeeper source code https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3248 lines
102 KiB

5 years ago
5 years ago
5 years ago
5 years ago
  1. /*
  2. * Copyright (C) 2017-2019 Christopher J. Howard
  3. *
  4. * This file is part of Antkeeper Source Code.
  5. *
  6. * Antkeeper Source Code is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * Antkeeper Source Code is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with Antkeeper Source Code. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include "game.hpp"
  20. #include "game-states.hpp"
  21. #include "resources/csv-table.hpp"
  22. #include "states/game-state.hpp"
  23. #include "states/sandbox-state.hpp"
  24. #include "filesystem.hpp"
  25. #include "timestamp.hpp"
  26. #include "ui/ui.hpp"
  27. #include "graphics/ui-render-pass.hpp"
  28. #include "graphics/shadow-map-render-pass.hpp"
  29. #include "graphics/clear-render-pass.hpp"
  30. #include "graphics/sky-render-pass.hpp"
  31. #include "graphics/lighting-render-pass.hpp"
  32. #include "graphics/silhouette-render-pass.hpp"
  33. #include "graphics/final-render-pass.hpp"
  34. #include "resources/resource-manager.hpp"
  35. #include "resources/text-file.hpp"
  36. #include "game/camera-rig.hpp"
  37. #include "game/lens.hpp"
  38. #include "game/forceps.hpp"
  39. #include "game/brush.hpp"
  40. #include "entity/component-manager.hpp"
  41. #include "entity/components/transform-component.hpp"
  42. #include "entity/components/model-component.hpp"
  43. #include "entity/components/terrain-patch-component.hpp"
  44. #include "entity/entity-manager.hpp"
  45. #include "entity/entity-template.hpp"
  46. #include "entity/system-manager.hpp"
  47. #include "entity/systems/sound-system.hpp"
  48. #include "entity/systems/collision-system.hpp"
  49. #include "entity/systems/render-system.hpp"
  50. #include "entity/systems/camera-system.hpp"
  51. #include "entity/systems/tool-system.hpp"
  52. #include "entity/systems/locomotion-system.hpp"
  53. #include "entity/systems/behavior-system.hpp"
  54. #include "entity/systems/steering-system.hpp"
  55. #include "entity/systems/particle-system.hpp"
  56. #include "entity/systems/terrain-system.hpp"
  57. #include "stb/stb_image_write.h"
  58. #include "menu.hpp"
  59. #include <algorithm>
  60. #include <cctype>
  61. #include <fstream>
  62. #include <sstream>
  63. #include <stdexcept>
  64. #include <thread>
  65. template <>
  66. bool Game::readSetting<std::string>(const std::string& name, std::string* value) const
  67. {
  68. auto it = settingsMap.find(name);
  69. if (it == settingsMap.end())
  70. {
  71. return false;
  72. }
  73. *value = (*settingsTable)[it->second][1];
  74. return true;
  75. }
  76. template <>
  77. bool Game::readSetting<bool>(const std::string& name, bool* value) const
  78. {
  79. auto it = settingsMap.find(name);
  80. if (it == settingsMap.end())
  81. {
  82. return false;
  83. }
  84. const std::string& string = (*settingsTable)[it->second][1];
  85. if (string == "true" || string == "on" || string == "1")
  86. {
  87. *value = true;
  88. return true;
  89. }
  90. else if (string == "false" || string == "off" || string == "0")
  91. {
  92. *value = false;
  93. return true;
  94. }
  95. return false;
  96. }
  97. template <>
  98. bool Game::readSetting<int>(const std::string& name, int* value) const
  99. {
  100. auto it = settingsMap.find(name);
  101. if (it == settingsMap.end())
  102. {
  103. return false;
  104. }
  105. std::stringstream stream;
  106. stream << (*settingsTable)[it->second][1];
  107. stream >> (*value);
  108. return (!stream.fail());
  109. }
  110. template <>
  111. bool Game::readSetting<float>(const std::string& name, float* value) const
  112. {
  113. auto it = settingsMap.find(name);
  114. if (it == settingsMap.end())
  115. {
  116. return false;
  117. }
  118. std::stringstream stream;
  119. stream << (*settingsTable)[it->second][1];
  120. stream >> (*value);
  121. return (!stream.fail());
  122. }
  123. template <>
  124. bool Game::readSetting<Vector2>(const std::string& name, Vector2* value) const
  125. {
  126. auto it = settingsMap.find(name);
  127. if (it == settingsMap.end())
  128. {
  129. return false;
  130. }
  131. std::stringstream stream;
  132. stream << (*settingsTable)[it->second][1];
  133. stream >> value->x;
  134. stream.str(std::string());
  135. stream.clear();
  136. stream << (*settingsTable)[it->second][2];
  137. stream >> value->y;
  138. return (!stream.fail());
  139. }
  140. Game::Game(int argc, char* argv[]):
  141. currentState(nullptr),
  142. window(nullptr)
  143. {
  144. // Determine application name
  145. std::string applicationName;
  146. #if defined(_WIN32)
  147. applicationName = "Antkeeper";
  148. #else
  149. applicationName = "antkeeper";
  150. #endif
  151. // Form resource paths
  152. dataPath = getDataPath(applicationName) + "data/";
  153. configPath = getConfigPath(applicationName);
  154. controlsPath = configPath + "controls/";
  155. // Create nonexistent config directories
  156. std::vector<std::string> configPaths;
  157. configPaths.push_back(configPath);
  158. configPaths.push_back(controlsPath);
  159. for (const std::string& path: configPaths)
  160. {
  161. if (!pathExists(path))
  162. {
  163. createDirectory(path);
  164. }
  165. }
  166. // Setup logging
  167. #if !defined(DEBUG)
  168. std::string logFilename = configPath + "log.txt";
  169. logFileStream.open(logFilename.c_str());
  170. std::cout.rdbuf(logFileStream.rdbuf());
  171. #endif
  172. std::cout << "Data path: " << dataPath << std::endl;
  173. std::cout << "Config path: " << configPath << std::endl;
  174. // Setup resource manager
  175. resourceManager = new ResourceManager();
  176. // Include resource search paths in order of priority
  177. resourceManager->include(controlsPath);
  178. resourceManager->include(configPath);
  179. resourceManager->include(dataPath);
  180. // Subscribe the game to scheduled function events
  181. eventDispatcher.subscribe<ScheduledFunctionEvent>(this);
  182. toggleFullscreenDisabled = false;
  183. sandboxState = new SandboxState(this);
  184. }
  185. Game::~Game()
  186. {
  187. if (window)
  188. {
  189. windowManager->destroyWindow(window);
  190. }
  191. }
  192. void Game::changeState(GameState* state)
  193. {
  194. if (currentState != nullptr)
  195. {
  196. currentState->exit();
  197. }
  198. currentState = state;
  199. if (currentState != nullptr)
  200. {
  201. currentState->enter();
  202. }
  203. }
  204. std::string Game::getString(const std::string& name) const
  205. {
  206. std::string value;
  207. auto it = stringMap.find(name);
  208. if (it != stringMap.end())
  209. {
  210. value = (*stringTable)[it->second][languageIndex + 2];
  211. if (value.empty())
  212. {
  213. value = std::string("# EMPTY STRING: ") + name + std::string(" #");
  214. }
  215. }
  216. else
  217. {
  218. value = std::string("# MISSING STRING: ") + name + std::string(" #");
  219. }
  220. return value;
  221. }
  222. void Game::changeLanguage(std::size_t nextLanguageIndex)
  223. {
  224. // Get names of fonts
  225. std::string menuFontFilename = getString("menu-font-filename");
  226. // Unload fonts
  227. delete menuFont;
  228. resourceManager->unload(menuFontFilename);
  229. // Change current language index
  230. languageIndex = nextLanguageIndex;
  231. // Reload fonts
  232. loadFonts();
  233. // Set window title
  234. window->setTitle(getString("title").c_str());
  235. // Repopulate UI element strings
  236. restringUI();
  237. // Resize the UI
  238. resizeUI(w, h);
  239. // Reselect menu item
  240. if (currentMenuItem)
  241. {
  242. menuSelectorSlideAnimation.stop();
  243. selectMenuItem(menuItemIndex, false);
  244. uiRootElement->update();
  245. currentMenu->getContainer()->resetTweens();
  246. }
  247. }
  248. void Game::nextLanguage()
  249. {
  250. changeLanguage((getLanguageIndex() + 1) % getLanguageCount());
  251. }
  252. void Game::openMenu(Menu* menu, int selectedItemIndex)
  253. {
  254. if (currentMenu)
  255. {
  256. closeCurrentMenu();
  257. }
  258. currentMenu = menu;
  259. uiRootElement->addChild(currentMenu->getContainer());
  260. currentMenu->getContainer()->addChild(menuSelectorImage);
  261. currentMenu->getContainer()->setTintColor(Vector4(1.0f));
  262. for (MenuItem* item: *currentMenu->getItems())
  263. {
  264. item->getContainer()->setTintColor(menuItemInactiveColor);
  265. }
  266. selectMenuItem(selectedItemIndex, false);
  267. uiRootElement->update();
  268. currentMenu->getContainer()->resetTweens();
  269. }
  270. void Game::closeCurrentMenu()
  271. {
  272. uiRootElement->removeChild(currentMenu->getContainer());
  273. currentMenu->getContainer()->removeChild(menuSelectorImage);
  274. currentMenu->getContainer()->setTintColor(Vector4(1.0f));
  275. for (MenuItem* item: *currentMenu->getItems())
  276. {
  277. item->getContainer()->setTintColor(menuItemInactiveColor);
  278. }
  279. currentMenu = nullptr;
  280. currentMenuItem = nullptr;
  281. menuItemIndex = -1;
  282. menuFadeAnimation.stop();
  283. menuSelectorSlideAnimation.stop();
  284. menuItemSelectAnimation.stop();
  285. menuItemDeselectAnimation.stop();
  286. previousMenu = currentMenu;
  287. currentMenu = nullptr;
  288. }
  289. void Game::selectMenuItem(int index, bool tween)
  290. {
  291. bool reselected = false;
  292. if (index != menuItemIndex)
  293. {
  294. if (menuItemSelectAnimation.isPlaying())
  295. {
  296. menuItemSelectAnimation.stop();
  297. currentMenuItem->getContainer()->setTintColor(menuItemActiveColor);
  298. }
  299. if (menuItemDeselectAnimation.isPlaying())
  300. {
  301. menuItemDeselectAnimation.stop();
  302. previousMenuItem->getContainer()->setTintColor(menuItemInactiveColor);
  303. }
  304. // Save previous menu item
  305. previousMenuItem = currentMenuItem;
  306. // Determine current menu item
  307. menuItemIndex = index;
  308. currentMenuItem = (*(currentMenu->getItems()))[index];
  309. }
  310. else
  311. {
  312. reselected = true;
  313. }
  314. // Determine target position of menu item selector
  315. Vector2 itemTranslation = currentMenuItem->getContainer()->getTranslation();
  316. Vector2 itemDimensions = currentMenuItem->getContainer()->getDimensions();
  317. float spacing = currentMenuItem->getNameLabel()->getFont()->getWidth("A");
  318. Vector2 translation;
  319. translation.x = itemTranslation.x - menuSelectorImage->getDimensions().x - spacing;
  320. translation.y = itemTranslation.y + itemDimensions.y * 0.5f - menuSelectorImage->getDimensions().y * 0.5;
  321. // Create tween animations
  322. if (!reselected && tween && previousMenuItem != nullptr)
  323. {
  324. float tweenDuration = 0.2f;
  325. Vector2 oldTranslation = menuSelectorImage->getTranslation();
  326. Vector2 newTranslation = translation;
  327. // Slide animation
  328. {
  329. menuSelectorSlideClip.removeChannels();
  330. AnimationChannel<float>* channel = menuSelectorSlideClip.addChannel(0);
  331. channel->insertKeyframe(0.0f, oldTranslation.y);
  332. channel->insertKeyframe(tweenDuration, newTranslation.y);
  333. menuSelectorSlideAnimation.setTimeFrame(menuSelectorSlideClip.getTimeFrame());
  334. menuSelectorSlideAnimation.rewind();
  335. menuSelectorSlideAnimation.play();
  336. }
  337. // Color animations
  338. {
  339. menuItemSelectClip.removeChannels();
  340. AnimationChannel<Vector4>* channel = menuItemSelectClip.addChannel(0);
  341. channel->insertKeyframe(0.0f, menuItemInactiveColor);
  342. channel->insertKeyframe(tweenDuration, menuItemActiveColor);
  343. menuItemSelectAnimation.setTimeFrame(menuItemSelectClip.getTimeFrame());
  344. menuItemSelectAnimation.rewind();
  345. menuItemSelectAnimation.play();
  346. if (previousMenuItem)
  347. {
  348. menuItemDeselectClip.removeChannels();
  349. channel = menuItemDeselectClip.addChannel(0);
  350. channel->insertKeyframe(0.0f, menuItemActiveColor);
  351. channel->insertKeyframe(tweenDuration, menuItemInactiveColor);
  352. menuItemDeselectAnimation.setTimeFrame(menuItemDeselectClip.getTimeFrame());
  353. menuItemDeselectAnimation.rewind();
  354. menuItemDeselectAnimation.play();
  355. }
  356. }
  357. menuSelectorImage->setTranslation(Vector2(newTranslation.x, oldTranslation.y));
  358. }
  359. else if (!tween)
  360. {
  361. menuSelectorImage->setTranslation(translation);
  362. currentMenuItem->getContainer()->setTintColor(menuItemActiveColor);
  363. if (previousMenuItem)
  364. {
  365. previousMenuItem->getContainer()->setTintColor(menuItemInactiveColor);
  366. }
  367. }
  368. }
  369. void Game::selectNextMenuItem()
  370. {
  371. int index = (menuItemIndex + 1) % currentMenu->getItems()->size();
  372. selectMenuItem(index, true);
  373. }
  374. void Game::selectPreviousMenuItem()
  375. {
  376. int index = (menuItemIndex + (currentMenu->getItems()->size() - 1)) % currentMenu->getItems()->size();
  377. selectMenuItem(index, true);
  378. }
  379. void Game::activateMenuItem()
  380. {
  381. currentMenuItem->activate();
  382. }
  383. void Game::activateLastMenuItem()
  384. {
  385. if (currentMenu)
  386. {
  387. (*currentMenu->getItems())[currentMenu->getItems()->size() - 1]->activate();
  388. }
  389. }
  390. void Game::toggleFullscreen()
  391. {
  392. if (!toggleFullscreenDisabled)
  393. {
  394. fullscreen = !fullscreen;
  395. window->setFullscreen(fullscreen);
  396. restringUI();
  397. // Disable fullscreen toggles for 500ms
  398. toggleFullscreenDisabled = true;
  399. ScheduledFunctionEvent event;
  400. event.caller = static_cast<void*>(this);
  401. event.function = [this]()
  402. {
  403. toggleFullscreenDisabled = false;
  404. };
  405. eventDispatcher.schedule(event, time + 0.5f);
  406. }
  407. }
  408. void Game::toggleVSync()
  409. {
  410. vsync = !vsync;
  411. window->setVSync(vsync);
  412. restringUI();
  413. }
  414. void Game::setUpdateRate(double frequency)
  415. {
  416. stepScheduler.setStepFrequency(frequency);
  417. }
  418. void Game::setup()
  419. {
  420. loadSettings();
  421. setupDebugging();
  422. setupLocalization();
  423. setupWindow();
  424. setupGraphics();
  425. setupControls();
  426. setupUI();
  427. setupGameplay();
  428. screenshotQueued = false;
  429. // Load model resources
  430. try
  431. {
  432. lensModel = resourceManager->load<Model>("lens.mdl");
  433. forcepsModel = resourceManager->load<Model>("forceps.mdl");
  434. brushModel = resourceManager->load<Model>("brush.mdl");
  435. smokeMaterial = resourceManager->load<Material>("smoke.mtl");
  436. }
  437. catch (const std::exception& e)
  438. {
  439. std::cerr << "Failed to load one or more models: \"" << e.what() << "\"" << std::endl;
  440. close(EXIT_FAILURE);
  441. }
  442. time = 0.0f;
  443. // Tools
  444. currentTool = nullptr;
  445. lens = new Lens(lensModel, &animator);
  446. lens->setOrbitCam(orbitCam);
  447. worldScene->addObject(lens->getModelInstance());
  448. worldScene->addObject(lens->getSpotlight());
  449. lens->setSunDirection(-sunlightCamera.getForward());
  450. // Forceps
  451. forceps = new Forceps(forcepsModel, &animator);
  452. forceps->setOrbitCam(orbitCam);
  453. worldScene->addObject(forceps->getModelInstance());
  454. // Brush
  455. brush = new Brush(brushModel, &animator);
  456. brush->setOrbitCam(orbitCam);
  457. worldScene->addObject(brush->getModelInstance());
  458. // Initialize component manager
  459. componentManager = new ComponentManager();
  460. // Initialize entity manager
  461. entityManager = new EntityManager(componentManager);
  462. // Initialize systems
  463. soundSystem = new SoundSystem(componentManager);
  464. collisionSystem = new CollisionSystem(componentManager);
  465. cameraSystem = new CameraSystem(componentManager);
  466. renderSystem = new RenderSystem(componentManager, worldScene);
  467. toolSystem = new ToolSystem(componentManager);
  468. toolSystem->setPickingCamera(&camera);
  469. toolSystem->setPickingViewport(Vector4(0, 0, w, h));
  470. eventDispatcher.subscribe<MouseMovedEvent>(toolSystem);
  471. behaviorSystem = new BehaviorSystem(componentManager);
  472. steeringSystem = new SteeringSystem(componentManager);
  473. locomotionSystem = new LocomotionSystem(componentManager);
  474. terrainSystem = new TerrainSystem(componentManager);
  475. terrainSystem->setPatchSize(500.0f);
  476. particleSystem = new ParticleSystem(componentManager);
  477. particleSystem->resize(1000);
  478. particleSystem->setMaterial(smokeMaterial);
  479. particleSystem->setDirection(Vector3(0, 1, 0));
  480. lens->setParticleSystem(particleSystem);
  481. particleSystem->getBillboardBatch()->setAlignment(&camera, BillboardAlignmentMode::SPHERICAL);
  482. worldScene->addObject(particleSystem->getBillboardBatch());
  483. // Initialize system manager
  484. systemManager = new SystemManager();
  485. systemManager->addSystem(soundSystem);
  486. systemManager->addSystem(behaviorSystem);
  487. systemManager->addSystem(steeringSystem);
  488. systemManager->addSystem(locomotionSystem);
  489. systemManager->addSystem(collisionSystem);
  490. systemManager->addSystem(toolSystem);
  491. systemManager->addSystem(terrainSystem);
  492. systemManager->addSystem(particleSystem);
  493. systemManager->addSystem(cameraSystem);
  494. systemManager->addSystem(renderSystem);
  495. // Load navmesh
  496. TriangleMesh* navmesh = resourceManager->load<TriangleMesh>("sidewalk.mesh");
  497. // Find surface
  498. TriangleMesh::Triangle* surface = nullptr;
  499. Vector3 barycentricPosition;
  500. Ray ray;
  501. ray.origin = Vector3(0, 100, 0);
  502. ray.direction = Vector3(0, -1, 0);
  503. auto intersection = ray.intersects(*navmesh);
  504. if (std::get<0>(intersection))
  505. {
  506. surface = (*navmesh->getTriangles())[std::get<3>(intersection)];
  507. Vector3 position = ray.extrapolate(std::get<1>(intersection));
  508. Vector3 a = surface->edge->vertex->position;
  509. Vector3 b = surface->edge->next->vertex->position;
  510. Vector3 c = surface->edge->previous->vertex->position;
  511. barycentricPosition = barycentric(position, a, b, c);
  512. }
  513. for (int i = 0; i < 0; ++i)
  514. {
  515. EntityID ant = createInstanceOf("worker-ant");
  516. setTranslation(ant, Vector3(0.0f, 0, 0.0f));
  517. BehaviorComponent* behavior = new BehaviorComponent();
  518. SteeringComponent* steering = new SteeringComponent();
  519. LeggedLocomotionComponent* locomotion = new LeggedLocomotionComponent();
  520. componentManager->addComponent(ant, behavior);
  521. componentManager->addComponent(ant, steering);
  522. componentManager->addComponent(ant, locomotion);
  523. locomotion->surface = surface;
  524. behavior->wanderTriangle = surface;
  525. locomotion->barycentricPosition = barycentricPosition;
  526. }
  527. //EntityID tool0 = createInstanceOf("lens");
  528. int highResolutionDiameter = 3;
  529. int mediumResolutionDiameter = highResolutionDiameter + 2;
  530. int lowResolutionDiameter = 20;
  531. float lowResolutionRadius = static_cast<float>(lowResolutionDiameter) / 2.0f;
  532. float mediumResolutionRadius = static_cast<float>(mediumResolutionDiameter) / 2.0f;
  533. float highResolutionRadius = static_cast<float>(highResolutionDiameter) / 2.0f;
  534. for (int i = 0; i < lowResolutionDiameter; ++i)
  535. {
  536. for (int j = 0; j < lowResolutionDiameter; ++j)
  537. {
  538. EntityID patch;
  539. int x = i - lowResolutionDiameter / 2;
  540. int z = j - lowResolutionDiameter / 2;
  541. if (std::abs(x) < highResolutionRadius && std::abs(z) < highResolutionRadius)
  542. {
  543. patch = createInstanceOf("terrain-patch-high-resolution");
  544. }
  545. else if (std::abs(x) < mediumResolutionRadius && std::abs(z) < mediumResolutionRadius)
  546. {
  547. patch = createInstanceOf("terrain-patch-medium-resolution");
  548. }
  549. else
  550. {
  551. patch = createInstanceOf("terrain-patch-low-resolution");
  552. }
  553. setTerrainPatchPosition(patch, {x, z});
  554. }
  555. }
  556. // Setup state machine states
  557. splashState =
  558. {
  559. std::bind(&Game::enterSplashState, this),
  560. std::bind(&Game::exitSplashState, this)
  561. };
  562. loadingState =
  563. {
  564. std::bind(&Game::enterLoadingState, this),
  565. std::bind(&Game::exitLoadingState, this)
  566. };
  567. titleState =
  568. {
  569. std::bind(&Game::enterTitleState, this),
  570. std::bind(&Game::exitTitleState, this)
  571. };
  572. playState =
  573. {
  574. std::bind(&Game::enterPlayState, this),
  575. std::bind(&Game::exitPlayState, this)
  576. };
  577. // Initialize state machine
  578. StateMachine::changeState(&titleState);
  579. changeState(sandboxState);
  580. }
  581. void Game::update(float t, float dt)
  582. {
  583. this->time = t;
  584. // Execute current state
  585. if (currentState != nullptr)
  586. {
  587. currentState->execute();
  588. }
  589. // Update systems
  590. systemManager->update(t, dt);
  591. // Update animations
  592. animator.animate(dt);
  593. if (fpsLabel->isVisible())
  594. {
  595. std::stringstream stream;
  596. stream.precision(2);
  597. stream << std::fixed << (performanceSampler.getMeanFrameDuration() * 1000.0f);
  598. fpsLabel->setText(stream.str());
  599. }
  600. uiRootElement->update();
  601. }
  602. void Game::input()
  603. {
  604. controls.update();
  605. }
  606. void Game::render()
  607. {
  608. // Perform sub-frame interpolation on UI elements
  609. uiRootElement->interpolate(stepScheduler.getScheduledSubsteps());
  610. // Update and batch UI elements
  611. uiBatcher->batch(uiBatch, uiRootElement);
  612. // Perform sub-frame interpolation particles
  613. particleSystem->getBillboardBatch()->interpolate(stepScheduler.getScheduledSubsteps());
  614. particleSystem->getBillboardBatch()->batch();
  615. // Render scene
  616. renderer.render(*worldScene);
  617. renderer.render(*uiScene);
  618. if (screenshotQueued)
  619. {
  620. screenshot();
  621. screenshotQueued = false;
  622. }
  623. // Swap window framebuffers
  624. window->swapBuffers();
  625. }
  626. void Game::exit()
  627. {}
  628. void Game::handleEvent(const WindowResizedEvent& event)
  629. {
  630. w = event.width;
  631. h = event.height;
  632. defaultRenderTarget.width = event.width;
  633. defaultRenderTarget.height = event.height;
  634. glViewport(0, 0, event.width, event.height);
  635. camera.setPerspective(glm::radians(40.0f), static_cast<float>(w) / static_cast<float>(h), 0.1, 100.0f);
  636. toolSystem->setPickingViewport(Vector4(0, 0, w, h));
  637. resizeUI(event.width, event.height);
  638. skipSplash();
  639. }
  640. void Game::handleEvent(const GamepadConnectedEvent& event)
  641. {
  642. // Unmap all controls
  643. inputRouter->reset();
  644. // Reload control profile
  645. loadControlProfile(controlProfileName);
  646. }
  647. void Game::handleEvent(const GamepadDisconnectedEvent& event)
  648. {}
  649. void Game::handleEvent(const ScheduledFunctionEvent& event)
  650. {
  651. if (event.caller == static_cast<void*>(this))
  652. {
  653. event.function();
  654. }
  655. }
  656. void Game::setupDebugging()
  657. {
  658. // Setup performance sampling
  659. performanceSampler.setSampleSize(30);
  660. // Disable wireframe drawing
  661. wireframe = false;
  662. }
  663. void Game::setupLocalization()
  664. {
  665. // Load strings
  666. loadStrings();
  667. // Determine number of available languages
  668. languageCount = (*stringTable)[0].size() - 2;
  669. // Match language code with language index
  670. languageIndex = 0;
  671. CSVRow* languageCodes = &(*stringTable)[1];
  672. for (std::size_t i = 2; i < languageCodes->size(); ++i)
  673. {
  674. if (language == (*languageCodes)[i])
  675. {
  676. languageIndex = i - 2;
  677. break;
  678. }
  679. }
  680. }
  681. void Game::setupWindow()
  682. {
  683. // Get display resolution
  684. const Display* display = deviceManager->getDisplays()->front();
  685. int displayWidth = std::get<0>(display->getDimensions());
  686. int displayHeight = std::get<1>(display->getDimensions());
  687. if (fullscreen)
  688. {
  689. w = static_cast<int>(fullscreenResolution.x);
  690. h = static_cast<int>(fullscreenResolution.y);
  691. }
  692. else
  693. {
  694. w = static_cast<int>(windowedResolution.x);
  695. h = static_cast<int>(windowedResolution.y);
  696. }
  697. // Determine window position
  698. int x = std::get<0>(display->getPosition()) + displayWidth / 2 - w / 2;
  699. int y = std::get<1>(display->getPosition()) + displayHeight / 2 - h / 2;
  700. // Read title string
  701. std::string title = getString("title");
  702. // Create window
  703. window = windowManager->createWindow(title.c_str(), x, y, w, h, fullscreen, WindowFlag::RESIZABLE);
  704. if (!window)
  705. {
  706. throw std::runtime_error("Game::Game(): Failed to create window.");
  707. }
  708. // Set v-sync mode
  709. window->setVSync(vsync);
  710. debugTypeface = nullptr;
  711. debugFont = nullptr;
  712. menuTypeface = nullptr;
  713. menuFont = nullptr;
  714. }
  715. void Game::setupGraphics()
  716. {
  717. // Setup OpenGL
  718. glEnable(GL_MULTISAMPLE);
  719. // Setup default render target
  720. defaultRenderTarget.width = w;
  721. defaultRenderTarget.height = h;
  722. defaultRenderTarget.framebuffer = 0;
  723. // Set shadow map resolution
  724. shadowMapResolution = 4096;
  725. // Setup shadow map framebuffer
  726. glGenFramebuffers(1, &shadowMapFramebuffer);
  727. glBindFramebuffer(GL_FRAMEBUFFER, shadowMapFramebuffer);
  728. glGenTextures(1, &shadowMapDepthTextureID);
  729. glBindTexture(GL_TEXTURE_2D, shadowMapDepthTextureID);
  730. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, shadowMapResolution, shadowMapResolution, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
  731. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  732. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  733. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  734. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  735. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
  736. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  737. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowMapDepthTextureID, 0);
  738. glDrawBuffer(GL_NONE);
  739. glReadBuffer(GL_NONE);
  740. glBindTexture(GL_TEXTURE_2D, 0);
  741. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  742. // Setup shadow map render target
  743. shadowMapRenderTarget.width = shadowMapResolution;
  744. shadowMapRenderTarget.height = shadowMapResolution;
  745. shadowMapRenderTarget.framebuffer = shadowMapFramebuffer;
  746. // Setup shadow map depth texture
  747. shadowMapDepthTexture.setTextureID(shadowMapDepthTextureID);
  748. shadowMapDepthTexture.setWidth(shadowMapResolution);
  749. shadowMapDepthTexture.setHeight(shadowMapResolution);
  750. // Setup silhouette framebuffer
  751. glGenTextures(1, &silhouetteRenderTarget.texture);
  752. glBindTexture(GL_TEXTURE_2D, silhouetteRenderTarget.texture);
  753. glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
  754. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  755. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  756. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  757. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  758. glGenFramebuffers(1, &silhouetteRenderTarget.framebuffer);
  759. glBindFramebuffer(GL_FRAMEBUFFER, silhouetteRenderTarget.framebuffer);
  760. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, silhouetteRenderTarget.texture, 0);
  761. glDrawBuffer(GL_COLOR_ATTACHMENT0);
  762. glReadBuffer(GL_NONE);
  763. glBindTexture(GL_TEXTURE_2D, 0);
  764. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  765. // Setup silhouette render target
  766. silhouetteRenderTarget.width = w;
  767. silhouetteRenderTarget.height = h;
  768. // Setup shadow map render pass
  769. shadowMapPass = new ShadowMapRenderPass(resourceManager);
  770. shadowMapPass->setRenderTarget(&shadowMapRenderTarget);
  771. shadowMapPass->setViewCamera(&camera);
  772. shadowMapPass->setLightCamera(&sunlightCamera);
  773. // Setup shadow map compositor
  774. shadowMapCompositor.addPass(shadowMapPass);
  775. shadowMapCompositor.load(nullptr);
  776. // Setup clear render pass
  777. clearPass = new ClearRenderPass();
  778. clearPass->setRenderTarget(&defaultRenderTarget);
  779. clearPass->setClear(true, true, false);
  780. clearPass->setClearColor(Vector4(0.0f));
  781. clearPass->setClearDepth(1.0f);
  782. // Setup sky render pass
  783. skyPass = new SkyRenderPass(resourceManager);
  784. skyPass->setRenderTarget(&defaultRenderTarget);
  785. // Setup lighting pass
  786. lightingPass = new LightingRenderPass(resourceManager);
  787. lightingPass->setRenderTarget(&defaultRenderTarget);
  788. lightingPass->setShadowMapPass(shadowMapPass);
  789. lightingPass->setShadowMap(&shadowMapDepthTexture);
  790. // Setup clear silhouette pass
  791. clearSilhouettePass = new ClearRenderPass();
  792. clearSilhouettePass->setRenderTarget(&silhouetteRenderTarget);
  793. clearSilhouettePass->setClear(true, false, false);
  794. clearSilhouettePass->setClearColor(Vector4(0.0f));
  795. // Setup silhouette pass
  796. silhouettePass = new SilhouetteRenderPass(resourceManager);
  797. silhouettePass->setRenderTarget(&silhouetteRenderTarget);
  798. // Setup final pass
  799. finalPass = new FinalRenderPass(resourceManager);
  800. finalPass->setRenderTarget(&defaultRenderTarget);
  801. finalPass->setSilhouetteRenderTarget(&silhouetteRenderTarget);
  802. // Setup default compositor
  803. defaultCompositor.addPass(clearPass);
  804. defaultCompositor.addPass(skyPass);
  805. defaultCompositor.addPass(lightingPass);
  806. defaultCompositor.addPass(clearSilhouettePass);
  807. defaultCompositor.addPass(silhouettePass);
  808. //defaultCompositor.addPass(finalPass);
  809. defaultCompositor.load(nullptr);
  810. // Setup UI render pass
  811. uiPass = new UIRenderPass(resourceManager);
  812. uiPass->setRenderTarget(&defaultRenderTarget);
  813. // Setup UI compositor
  814. uiCompositor.addPass(uiPass);
  815. uiCompositor.load(nullptr);
  816. // Create scenes
  817. worldScene = new Scene(&stepInterpolator);
  818. uiScene = new Scene(&stepInterpolator);
  819. // Setup camera
  820. camera.setPerspective(glm::radians(40.0f), static_cast<float>(w) / static_cast<float>(h), 0.1, 100.0f);
  821. camera.lookAt(Vector3(0.0f, 4.0f, 2.0f), Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f));
  822. camera.setCompositor(&defaultCompositor);
  823. camera.setCompositeIndex(1);
  824. worldScene->addObject(&camera);
  825. // Setup sun
  826. sunlight.setDirection(Vector3(0, -1, 0));
  827. setTimeOfDay(11.0f);
  828. worldScene->addObject(&sunlight);
  829. // Setup sunlight camera
  830. sunlightCamera.setOrthographic(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);
  831. sunlightCamera.setCompositor(&shadowMapCompositor);
  832. sunlightCamera.setCompositeIndex(0);
  833. sunlightCamera.setCullingEnabled(true);
  834. sunlightCamera.setCullingMask(&camera.getViewFrustum());
  835. worldScene->addObject(&sunlightCamera);
  836. }
  837. void Game::setupUI()
  838. {
  839. // Get DPI and convert font size to pixels
  840. const Display* display = deviceManager->getDisplays()->front();
  841. dpi = display->getDPI();
  842. fontSizePX = fontSizePT * (1.0f / 72.0f) * dpi;
  843. // Load fonts
  844. loadFonts();
  845. // Load splash screen texture
  846. splashTexture = resourceManager->load<Texture2D>("epigraph.png");
  847. // Load HUD texture
  848. hudSpriteSheetTexture = resourceManager->load<Texture2D>("hud.png");
  849. // Read texture atlas file
  850. CSVTable* atlasTable = resourceManager->load<CSVTable>("hud-atlas.csv");
  851. // Build texture atlas
  852. for (int row = 0; row < atlasTable->size(); ++row)
  853. {
  854. std::stringstream ss;
  855. float x;
  856. float y;
  857. float w;
  858. float h;
  859. ss << (*atlasTable)[row][1];
  860. ss >> x;
  861. ss.str(std::string());
  862. ss.clear();
  863. ss << (*atlasTable)[row][2];
  864. ss >> y;
  865. ss.str(std::string());
  866. ss.clear();
  867. ss << (*atlasTable)[row][3];
  868. ss >> w;
  869. ss.str(std::string());
  870. ss.clear();
  871. ss << (*atlasTable)[row][4];
  872. ss >> h;
  873. ss.str(std::string());
  874. y = static_cast<float>(hudSpriteSheetTexture->getHeight()) - y - h;
  875. x = (int)(x + 0.5f);
  876. y = (int)(y + 0.5f);
  877. w = (int)(w + 0.5f);
  878. h = (int)(h + 0.5f);
  879. hudTextureAtlas.insert((*atlasTable)[row][0], Rect(Vector2(x, y), Vector2(x + w, y + h)));
  880. }
  881. // Setup UI batching
  882. uiBatch = new BillboardBatch();
  883. uiBatch->resize(1024);
  884. uiBatcher = new UIBatcher();
  885. // Setup root UI element
  886. uiRootElement = new UIContainer();
  887. eventDispatcher.subscribe<MouseMovedEvent>(uiRootElement);
  888. eventDispatcher.subscribe<MouseButtonPressedEvent>(uiRootElement);
  889. eventDispatcher.subscribe<MouseButtonReleasedEvent>(uiRootElement);
  890. // Create splash screen background element
  891. splashBackgroundImage = new UIImage();
  892. splashBackgroundImage->setLayerOffset(-1);
  893. splashBackgroundImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  894. splashBackgroundImage->setVisible(false);
  895. uiRootElement->addChild(splashBackgroundImage);
  896. // Create splash screen element
  897. splashImage = new UIImage();
  898. splashImage->setTexture(splashTexture);
  899. splashImage->setVisible(false);
  900. uiRootElement->addChild(splashImage);
  901. Rect hudTextureAtlasBounds(Vector2(0), Vector2(hudSpriteSheetTexture->getWidth(), hudSpriteSheetTexture->getHeight()));
  902. auto normalizeTextureBounds = [](const Rect& texture, const Rect& atlas)
  903. {
  904. Vector2 atlasDimensions = Vector2(atlas.getWidth(), atlas.getHeight());
  905. return Rect(texture.getMin() / atlasDimensions, texture.getMax() / atlasDimensions);
  906. };
  907. // Create HUD elements
  908. hudContainer = new UIContainer();
  909. hudContainer->setVisible(false);
  910. uiRootElement->addChild(hudContainer);
  911. toolIndicatorBGImage = new UIImage();
  912. toolIndicatorBGImage->setTexture(hudSpriteSheetTexture);
  913. toolIndicatorBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds));
  914. hudContainer->addChild(toolIndicatorBGImage);
  915. toolIndicatorsBounds = new Rect[8];
  916. toolIndicatorsBounds[0] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-brush"), hudTextureAtlasBounds);
  917. toolIndicatorsBounds[1] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-spade"), hudTextureAtlasBounds);
  918. toolIndicatorsBounds[2] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-lens"), hudTextureAtlasBounds);
  919. toolIndicatorsBounds[3] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-test-tube"), hudTextureAtlasBounds);
  920. toolIndicatorsBounds[4] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-forceps"), hudTextureAtlasBounds);
  921. toolIndicatorsBounds[5] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  922. toolIndicatorsBounds[6] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  923. toolIndicatorsBounds[7] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  924. toolIndicatorIconImage = new UIImage();
  925. toolIndicatorIconImage->setTexture(hudSpriteSheetTexture);
  926. toolIndicatorIconImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  927. toolIndicatorBGImage->addChild(toolIndicatorIconImage);
  928. buttonContainer = new UIContainer();
  929. hudContainer->addChild(buttonContainer);
  930. playButtonBGImage = new UIImage();
  931. playButtonBGImage->setTexture(hudSpriteSheetTexture);
  932. playButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  933. //buttonContainer->addChild(playButtonBGImage);
  934. pauseButtonBGImage = new UIImage();
  935. pauseButtonBGImage->setTexture(hudSpriteSheetTexture);
  936. pauseButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  937. //buttonContainer->addChild(pauseButtonBGImage);
  938. fastForwardButtonBGImage = new UIImage();
  939. fastForwardButtonBGImage->setTexture(hudSpriteSheetTexture);
  940. fastForwardButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  941. //buttonContainer->addChild(fastForwardButtonBGImage);
  942. playButtonImage = new UIImage();
  943. playButtonImage->setTexture(hudSpriteSheetTexture);
  944. playButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-play"), hudTextureAtlasBounds));
  945. //buttonContainer->addChild(playButtonImage);
  946. fastForwardButtonImage = new UIImage();
  947. fastForwardButtonImage->setTexture(hudSpriteSheetTexture);
  948. fastForwardButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-fast-forward-2x"), hudTextureAtlasBounds));
  949. //buttonContainer->addChild(fastForwardButtonImage);
  950. pauseButtonImage = new UIImage();
  951. pauseButtonImage->setTexture(hudSpriteSheetTexture);
  952. pauseButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-pause"), hudTextureAtlasBounds));
  953. //buttonContainer->addChild(pauseButtonImage);
  954. radialMenuContainer = new UIContainer();
  955. radialMenuContainer->setVisible(false);
  956. uiRootElement->addChild(radialMenuContainer);
  957. radialMenuBackgroundImage = new UIImage();
  958. radialMenuBackgroundImage->setTintColor(Vector4(Vector3(0.0f), 0.25f));
  959. radialMenuContainer->addChild(radialMenuBackgroundImage);
  960. radialMenuImage = new UIImage();
  961. radialMenuImage->setTexture(hudSpriteSheetTexture);
  962. radialMenuImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu"), hudTextureAtlasBounds));
  963. radialMenuContainer->addChild(radialMenuImage);
  964. radialMenuSelectorImage = new UIImage();
  965. radialMenuSelectorImage->setTexture(hudSpriteSheetTexture);
  966. radialMenuSelectorImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu-selector"), hudTextureAtlasBounds));
  967. radialMenuContainer->addChild(radialMenuSelectorImage);
  968. toolIconBrushImage = new UIImage();
  969. toolIconBrushImage->setTexture(hudSpriteSheetTexture);
  970. toolIconBrushImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  971. radialMenuImage->addChild(toolIconBrushImage);
  972. toolIconLensImage = new UIImage();
  973. toolIconLensImage->setTexture(hudSpriteSheetTexture);
  974. toolIconLensImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-lens"), hudTextureAtlasBounds));
  975. radialMenuImage->addChild(toolIconLensImage);
  976. toolIconForcepsImage = new UIImage();
  977. toolIconForcepsImage->setTexture(hudSpriteSheetTexture);
  978. toolIconForcepsImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-forceps"), hudTextureAtlasBounds));
  979. radialMenuImage->addChild(toolIconForcepsImage);
  980. toolIconSpadeImage = new UIImage();
  981. toolIconSpadeImage->setTexture(hudSpriteSheetTexture);
  982. toolIconSpadeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-spade"), hudTextureAtlasBounds));
  983. //radialMenuImage->addChild(toolIconSpadeImage);
  984. toolIconCameraImage = new UIImage();
  985. toolIconCameraImage->setTexture(hudSpriteSheetTexture);
  986. toolIconCameraImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-camera"), hudTextureAtlasBounds));
  987. radialMenuImage->addChild(toolIconCameraImage);
  988. toolIconMicrochipImage = new UIImage();
  989. toolIconMicrochipImage->setTexture(hudSpriteSheetTexture);
  990. toolIconMicrochipImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-microchip"), hudTextureAtlasBounds));
  991. radialMenuImage->addChild(toolIconMicrochipImage);
  992. toolIconTestTubeImage = new UIImage();
  993. toolIconTestTubeImage->setTexture(hudSpriteSheetTexture);
  994. toolIconTestTubeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-test-tube"), hudTextureAtlasBounds));
  995. //radialMenuImage->addChild(toolIconTestTubeImage);
  996. antTag = new UIContainer();
  997. antTag->setLayerOffset(-10);
  998. antTag->setVisible(false);
  999. uiRootElement->addChild(antTag);
  1000. antLabelContainer = new UIContainer();
  1001. antTag->addChild(antLabelContainer);
  1002. antLabelTL = new UIImage();
  1003. antLabelTR = new UIImage();
  1004. antLabelBL = new UIImage();
  1005. antLabelBR = new UIImage();
  1006. antLabelCC = new UIImage();
  1007. antLabelCT = new UIImage();
  1008. antLabelCB = new UIImage();
  1009. antLabelCL = new UIImage();
  1010. antLabelCR = new UIImage();
  1011. antLabelTL->setTexture(hudSpriteSheetTexture);
  1012. antLabelTR->setTexture(hudSpriteSheetTexture);
  1013. antLabelBL->setTexture(hudSpriteSheetTexture);
  1014. antLabelBR->setTexture(hudSpriteSheetTexture);
  1015. antLabelCC->setTexture(hudSpriteSheetTexture);
  1016. antLabelCT->setTexture(hudSpriteSheetTexture);
  1017. antLabelCB->setTexture(hudSpriteSheetTexture);
  1018. antLabelCL->setTexture(hudSpriteSheetTexture);
  1019. antLabelCR->setTexture(hudSpriteSheetTexture);
  1020. Rect labelTLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tl"), hudTextureAtlasBounds);
  1021. Rect labelTRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tr"), hudTextureAtlasBounds);
  1022. Rect labelBLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-bl"), hudTextureAtlasBounds);
  1023. Rect labelBRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-br"), hudTextureAtlasBounds);
  1024. Rect labelCCBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cc"), hudTextureAtlasBounds);
  1025. Rect labelCTBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-ct"), hudTextureAtlasBounds);
  1026. Rect labelCBBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cb"), hudTextureAtlasBounds);
  1027. Rect labelCLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cl"), hudTextureAtlasBounds);
  1028. Rect labelCRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cr"), hudTextureAtlasBounds);
  1029. Vector2 labelTLMin = labelTLBounds.getMin();
  1030. Vector2 labelTRMin = labelTRBounds.getMin();
  1031. Vector2 labelBLMin = labelBLBounds.getMin();
  1032. Vector2 labelBRMin = labelBRBounds.getMin();
  1033. Vector2 labelCCMin = labelCCBounds.getMin();
  1034. Vector2 labelCTMin = labelCTBounds.getMin();
  1035. Vector2 labelCBMin = labelCBBounds.getMin();
  1036. Vector2 labelCLMin = labelCLBounds.getMin();
  1037. Vector2 labelCRMin = labelCRBounds.getMin();
  1038. Vector2 labelTLMax = labelTLBounds.getMax();
  1039. Vector2 labelTRMax = labelTRBounds.getMax();
  1040. Vector2 labelBLMax = labelBLBounds.getMax();
  1041. Vector2 labelBRMax = labelBRBounds.getMax();
  1042. Vector2 labelCCMax = labelCCBounds.getMax();
  1043. Vector2 labelCTMax = labelCTBounds.getMax();
  1044. Vector2 labelCBMax = labelCBBounds.getMax();
  1045. Vector2 labelCLMax = labelCLBounds.getMax();
  1046. Vector2 labelCRMax = labelCRBounds.getMax();
  1047. antLabelTL->setTextureBounds(labelTLBounds);
  1048. antLabelTR->setTextureBounds(labelTRBounds);
  1049. antLabelBL->setTextureBounds(labelBLBounds);
  1050. antLabelBR->setTextureBounds(labelBRBounds);
  1051. antLabelCC->setTextureBounds(labelCCBounds);
  1052. antLabelCT->setTextureBounds(labelCTBounds);
  1053. antLabelCB->setTextureBounds(labelCBBounds);
  1054. antLabelCL->setTextureBounds(labelCLBounds);
  1055. antLabelCR->setTextureBounds(labelCRBounds);
  1056. antLabelContainer->addChild(antLabelTL);
  1057. antLabelContainer->addChild(antLabelTR);
  1058. antLabelContainer->addChild(antLabelBL);
  1059. antLabelContainer->addChild(antLabelBR);
  1060. antLabelContainer->addChild(antLabelCC);
  1061. antLabelContainer->addChild(antLabelCT);
  1062. antLabelContainer->addChild(antLabelCB);
  1063. antLabelContainer->addChild(antLabelCL);
  1064. antLabelContainer->addChild(antLabelCR);
  1065. antLabel = new UILabel();
  1066. antLabel->setFont(nullptr);
  1067. antLabel->setText("");
  1068. antLabel->setTintColor(Vector4(Vector3(0.0f), 1.0f));
  1069. antLabel->setLayerOffset(1);
  1070. antLabelContainer->addChild(antLabel);
  1071. fpsLabel = new UILabel();
  1072. fpsLabel->setFont(debugFont);
  1073. fpsLabel->setTintColor(Vector4(1, 1, 0, 1));
  1074. fpsLabel->setLayerOffset(50);
  1075. fpsLabel->setAnchor(Anchor::TOP_LEFT);
  1076. uiRootElement->addChild(fpsLabel);
  1077. antPin = new UIImage();
  1078. antPin->setTexture(hudSpriteSheetTexture);
  1079. antPin->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin"), hudTextureAtlasBounds));
  1080. antTag->addChild(antPin);
  1081. antLabelPinHole = new UIImage();
  1082. antLabelPinHole->setTexture(hudSpriteSheetTexture);
  1083. antLabelPinHole->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin-hole"), hudTextureAtlasBounds));
  1084. antLabelContainer->addChild(antLabelPinHole);
  1085. // Construct box selection
  1086. boxSelectionImageBackground = new UIImage();
  1087. boxSelectionImageBackground->setAnchor(Anchor::CENTER);
  1088. boxSelectionImageTop = new UIImage();
  1089. boxSelectionImageTop->setAnchor(Anchor::TOP_LEFT);
  1090. boxSelectionImageBottom = new UIImage();
  1091. boxSelectionImageBottom->setAnchor(Anchor::BOTTOM_LEFT);
  1092. boxSelectionImageLeft = new UIImage();
  1093. boxSelectionImageLeft->setAnchor(Anchor::TOP_LEFT);
  1094. boxSelectionImageRight = new UIImage();
  1095. boxSelectionImageRight->setAnchor(Anchor::TOP_RIGHT);
  1096. boxSelectionContainer = new UIContainer();
  1097. boxSelectionContainer->setLayerOffset(80);
  1098. boxSelectionContainer->addChild(boxSelectionImageBackground);
  1099. boxSelectionContainer->addChild(boxSelectionImageTop);
  1100. boxSelectionContainer->addChild(boxSelectionImageBottom);
  1101. boxSelectionContainer->addChild(boxSelectionImageLeft);
  1102. boxSelectionContainer->addChild(boxSelectionImageRight);
  1103. boxSelectionContainer->setVisible(false);
  1104. uiRootElement->addChild(boxSelectionContainer);
  1105. boxSelectionImageBackground->setTintColor(Vector4(1.0f, 1.0f, 1.0f, 0.5f));
  1106. boxSelectionContainer->setTintColor(Vector4(1.0f, 0.0f, 0.0f, 1.0f));
  1107. boxSelectionBorderWidth = 2.0f;
  1108. cameraGridColor = Vector4(1, 1, 1, 0.5f);
  1109. cameraReticleColor = Vector4(1, 1, 1, 0.75f);
  1110. cameraGridY0Image = new UIImage();
  1111. cameraGridY0Image->setAnchor(Vector2(0.5f, (1.0f / 3.0f)));
  1112. cameraGridY0Image->setTintColor(cameraGridColor);
  1113. cameraGridY1Image = new UIImage();
  1114. cameraGridY1Image->setAnchor(Vector2(0.5f, (2.0f / 3.0f)));
  1115. cameraGridY1Image->setTintColor(cameraGridColor);
  1116. cameraGridX0Image = new UIImage();
  1117. cameraGridX0Image->setAnchor(Vector2((1.0f / 3.0f), 0.5f));
  1118. cameraGridX0Image->setTintColor(cameraGridColor);
  1119. cameraGridX1Image = new UIImage();
  1120. cameraGridX1Image->setAnchor(Vector2((2.0f / 3.0f), 0.5f));
  1121. cameraGridX1Image->setTintColor(cameraGridColor);
  1122. cameraReticleImage = new UIImage();
  1123. cameraReticleImage->setAnchor(Anchor::CENTER);
  1124. cameraReticleImage->setTintColor(cameraReticleColor);
  1125. cameraReticleImage->setTexture(hudSpriteSheetTexture);
  1126. cameraReticleImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("camera-reticle"), hudTextureAtlasBounds));
  1127. cameraGridContainer = new UIContainer();
  1128. cameraGridContainer->addChild(cameraGridY0Image);
  1129. cameraGridContainer->addChild(cameraGridY1Image);
  1130. cameraGridContainer->addChild(cameraGridX0Image);
  1131. cameraGridContainer->addChild(cameraGridX1Image);
  1132. cameraGridContainer->addChild(cameraReticleImage);
  1133. cameraGridContainer->setVisible(false);
  1134. uiRootElement->addChild(cameraGridContainer);
  1135. cameraFlashImage = new UIImage();
  1136. cameraFlashImage->setLayerOffset(99);
  1137. cameraFlashImage->setTintColor(Vector4(1.0f));
  1138. cameraFlashImage->setVisible(false);
  1139. uiRootElement->addChild(cameraFlashImage);
  1140. blackoutImage = new UIImage();
  1141. blackoutImage->setLayerOffset(98);
  1142. blackoutImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  1143. blackoutImage->setVisible(false);
  1144. uiRootElement->addChild(blackoutImage);
  1145. menuItemActiveColor = Vector4(Vector3(0.2f), 1.0f);
  1146. menuItemInactiveColor = Vector4(Vector3(0.2f), 0.5f);
  1147. menuItemIndex = -1;
  1148. currentMenu = nullptr;
  1149. currentMenuItem = nullptr;
  1150. previousMenuItem = nullptr;
  1151. previousMenu = nullptr;
  1152. menuSelectorImage = new UIImage();
  1153. menuSelectorImage->setAnchor(Anchor::TOP_LEFT);
  1154. menuSelectorImage->setTexture(hudSpriteSheetTexture);
  1155. menuSelectorImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("menu-selector"), hudTextureAtlasBounds));
  1156. menuSelectorImage->setTintColor(menuItemActiveColor);
  1157. // Build main menu
  1158. mainMenu = new Menu();
  1159. mainMenuContinueItem = mainMenu->addItem();
  1160. mainMenuNewGameItem = mainMenu->addItem();
  1161. mainMenuColoniesItem = mainMenu->addItem();
  1162. mainMenuSettingsItem = mainMenu->addItem();
  1163. mainMenuQuitItem = mainMenu->addItem();
  1164. // Build settings menu
  1165. settingsMenu = new Menu();
  1166. settingsMenuControlsItem = settingsMenu->addItem();
  1167. settingsMenuFullscreenItem = settingsMenu->addItem();
  1168. settingsMenuVSyncItem = settingsMenu->addItem();
  1169. settingsMenuLanguageItem = settingsMenu->addItem();
  1170. settingsMenuBackItem = settingsMenu->addItem();
  1171. // Build controls menu
  1172. controlsMenu = new Menu();
  1173. controlsMenuMoveForwardItem = controlsMenu->addItem();
  1174. controlsMenuMoveLeftItem = controlsMenu->addItem();
  1175. controlsMenuMoveBackItem = controlsMenu->addItem();
  1176. controlsMenuMoveRightItem = controlsMenu->addItem();
  1177. controlsMenuChangeToolItem = controlsMenu->addItem();
  1178. controlsMenuUseToolItem = controlsMenu->addItem();
  1179. controlsMenuAdjustCameraItem = controlsMenu->addItem();
  1180. controlsMenuToggleFullscreenItem = controlsMenu->addItem();
  1181. controlsMenuTakeScreenshotItem = controlsMenu->addItem();
  1182. controlsMenuResetToDefaultItem = controlsMenu->addItem();
  1183. controlsMenuBackItem = controlsMenu->addItem();
  1184. // Setup main menu callbacks
  1185. mainMenuSettingsItem->setActivatedCallback(std::bind(&Game::openMenu, this, settingsMenu, 0));
  1186. mainMenuQuitItem->setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1187. // Setup settings menu callbacks
  1188. settingsMenuControlsItem->setActivatedCallback(std::bind(&Game::openMenu, this, controlsMenu, 0));
  1189. settingsMenuFullscreenItem->setActivatedCallback(std::bind(&Game::toggleFullscreen, this));
  1190. settingsMenuVSyncItem->setActivatedCallback(std::bind(&Game::toggleVSync, this));
  1191. settingsMenuLanguageItem->setActivatedCallback(std::bind(&Game::nextLanguage, this));
  1192. settingsMenuBackItem->setActivatedCallback(std::bind(&Game::openMenu, this, mainMenu, 3));
  1193. // Setup controls menu callbacks
  1194. controlsMenuMoveForwardItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveForwardControl));
  1195. controlsMenuMoveLeftItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveLeftControl));
  1196. controlsMenuMoveBackItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveBackControl));
  1197. controlsMenuMoveRightItem->setActivatedCallback(std::bind(&Game::remapControl, this, &moveRightControl));
  1198. controlsMenuChangeToolItem->setActivatedCallback(std::bind(&Game::remapControl, this, &changeToolControl));
  1199. controlsMenuUseToolItem->setActivatedCallback(std::bind(&Game::remapControl, this, &useToolControl));
  1200. controlsMenuAdjustCameraItem->setActivatedCallback(std::bind(&Game::remapControl, this, &adjustCameraControl));
  1201. controlsMenuToggleFullscreenItem->setActivatedCallback(std::bind(&Game::remapControl, this, &toggleFullscreenControl));
  1202. controlsMenuTakeScreenshotItem->setActivatedCallback(std::bind(&Game::remapControl, this, &takeScreenshotControl));
  1203. controlsMenuResetToDefaultItem->setActivatedCallback(std::bind(&Game::resetControls, this));
  1204. controlsMenuBackItem->setActivatedCallback(std::bind(&Game::openMenu, this, settingsMenu, 0));
  1205. // Setup standard callbacks for all menu items
  1206. for (std::size_t i = 0; i < mainMenu->getItems()->size(); ++i)
  1207. {
  1208. MenuItem* item = (*mainMenu->getItems())[i];
  1209. item->getContainer()->setTintColor(menuItemInactiveColor);
  1210. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1211. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1212. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1213. }
  1214. for (std::size_t i = 0; i < settingsMenu->getItems()->size(); ++i)
  1215. {
  1216. MenuItem* item = (*settingsMenu->getItems())[i];
  1217. item->getContainer()->setTintColor(menuItemInactiveColor);
  1218. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1219. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1220. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1221. }
  1222. for (std::size_t i = 0; i < controlsMenu->getItems()->size(); ++i)
  1223. {
  1224. MenuItem* item = (*controlsMenu->getItems())[i];
  1225. item->getContainer()->setTintColor(menuItemInactiveColor);
  1226. item->getContainer()->setMouseOverCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1227. item->getContainer()->setMouseMovedCallback(std::bind(&Game::selectMenuItem, this, i, true));
  1228. item->getContainer()->setMousePressedCallback(std::bind(&Game::activateMenuItem, this));
  1229. }
  1230. // Set fonts for all menus
  1231. mainMenu->setFonts(menuFont);
  1232. settingsMenu->setFonts(menuFont);
  1233. controlsMenu->setFonts(menuFont);
  1234. AnimationChannel<float>* channel;
  1235. // Setup splash fade-in animation
  1236. splashFadeInClip.setInterpolator(easeOutCubic<float>);
  1237. channel = splashFadeInClip.addChannel(0);
  1238. channel->insertKeyframe(0.0f, 0.0f);
  1239. channel->insertKeyframe(1.0f, 1.0f);
  1240. channel->insertKeyframe(3.0f, 1.0f);
  1241. splashFadeInAnimation.setClip(&splashFadeInClip);
  1242. splashFadeInAnimation.setTimeFrame(splashFadeInClip.getTimeFrame());
  1243. splashFadeInAnimation.setAnimateCallback
  1244. (
  1245. [this](std::size_t id, float opacity)
  1246. {
  1247. Vector3 color = Vector3(splashImage->getTintColor());
  1248. splashImage->setTintColor(Vector4(color, opacity));
  1249. }
  1250. );
  1251. splashFadeInAnimation.setEndCallback
  1252. (
  1253. [this]()
  1254. {
  1255. splashFadeOutAnimation.rewind();
  1256. splashFadeOutAnimation.play();
  1257. }
  1258. );
  1259. // Setup splash fade-out animation
  1260. splashFadeOutClip.setInterpolator(easeOutCubic<float>);
  1261. channel = splashFadeOutClip.addChannel(0);
  1262. channel->insertKeyframe(0.0f, 1.0f);
  1263. channel->insertKeyframe(1.0f, 0.0f);
  1264. channel->insertKeyframe(1.5f, 0.0f);
  1265. splashFadeOutAnimation.setClip(&splashFadeOutClip);
  1266. splashFadeOutAnimation.setTimeFrame(splashFadeOutClip.getTimeFrame());
  1267. splashFadeOutAnimation.setAnimateCallback
  1268. (
  1269. [this](std::size_t id, float opacity)
  1270. {
  1271. Vector3 color = Vector3(splashImage->getTintColor());
  1272. splashImage->setTintColor(Vector4(color, opacity));
  1273. }
  1274. );
  1275. splashFadeOutAnimation.setEndCallback(std::bind(&StateMachine::changeState, this, &titleState));
  1276. // Ant-hill zoom animation
  1277. antHillZoomClip.setInterpolator(easeOutCubic<float>);
  1278. channel = antHillZoomClip.addChannel(0);
  1279. channel->insertKeyframe(0.0f, 0.0f);
  1280. channel->insertKeyframe(3.0f, 40.0f);
  1281. antHillZoomAnimation.setClip(&antHillZoomClip);
  1282. antHillZoomAnimation.setTimeFrame(antHillZoomClip.getTimeFrame());
  1283. antHillZoomAnimation.setAnimateCallback
  1284. (
  1285. [this](std::size_t id, float distance)
  1286. {
  1287. orbitCam->setFocalDistance(distance);
  1288. orbitCam->setTargetFocalDistance(distance);
  1289. }
  1290. );
  1291. // Menu fade animation
  1292. menuFadeInClip.setInterpolator(easeOutCubic<float>);
  1293. channel = menuFadeInClip.addChannel(0);
  1294. channel->insertKeyframe(0.0f, 0.0f);
  1295. channel->insertKeyframe(3.0f, 0.0f);
  1296. channel->insertKeyframe(5.0f, 1.0f);
  1297. menuFadeAnimation.setClip(&menuFadeInClip);
  1298. menuFadeAnimation.setTimeFrame(menuFadeInClip.getTimeFrame());
  1299. menuFadeAnimation.setAnimateCallback
  1300. (
  1301. [this](std::size_t id, float opacity)
  1302. {
  1303. mainMenu->getContainer()->setTintColor(Vector4(opacity));
  1304. }
  1305. );
  1306. // Menu selector animation
  1307. menuSelectorSlideClip.setInterpolator(easeOutCubic<float>);
  1308. menuSelectorSlideAnimation.setClip(&menuSelectorSlideClip);
  1309. menuSelectorSlideAnimation.setAnimateCallback
  1310. (
  1311. [this](std::size_t id, float offset)
  1312. {
  1313. Vector2 translation = menuSelectorImage->getTranslation();
  1314. translation.y = offset;
  1315. menuSelectorImage->setTranslation(translation);
  1316. }
  1317. );
  1318. animator.addAnimation(&menuSelectorSlideAnimation);
  1319. // Menu item select animation
  1320. menuItemSelectClip.setInterpolator(easeOutCubic<Vector4>);
  1321. menuItemSelectAnimation.setClip(&menuItemSelectClip);
  1322. menuItemSelectAnimation.setAnimateCallback
  1323. (
  1324. [this](std::size_t id, const Vector4& color)
  1325. {
  1326. currentMenuItem->getContainer()->setTintColor(color);
  1327. }
  1328. );
  1329. // Menu item deselect animation
  1330. menuItemDeselectClip.setInterpolator(easeOutCubic<Vector4>);
  1331. menuItemDeselectAnimation.setClip(&menuItemDeselectClip);
  1332. menuItemDeselectAnimation.setAnimateCallback
  1333. (
  1334. [this](std::size_t id, const Vector4& color)
  1335. {
  1336. previousMenuItem->getContainer()->setTintColor(color);
  1337. }
  1338. );
  1339. animator.addAnimation(&menuItemSelectAnimation);
  1340. animator.addAnimation(&menuItemDeselectAnimation);
  1341. // Construct fade-in animation clip
  1342. fadeInClip.setInterpolator(easeOutCubic<float>);
  1343. channel = fadeInClip.addChannel(0);
  1344. channel->insertKeyframe(0.0f, 1.0f);
  1345. channel->insertKeyframe(1.0f, 0.0f);
  1346. // Construct fade-out animation clip
  1347. fadeOutClip.setInterpolator(easeOutCubic<float>);
  1348. channel = fadeOutClip.addChannel(0);
  1349. channel->insertKeyframe(0.0f, 0.0f);
  1350. channel->insertKeyframe(1.0f, 1.0f);
  1351. // Setup fade-in animation callbacks
  1352. fadeInAnimation.setAnimateCallback
  1353. (
  1354. [this](std::size_t id, float opacity)
  1355. {
  1356. Vector3 color = Vector3(blackoutImage->getTintColor());
  1357. blackoutImage->setTintColor(Vector4(color, opacity));
  1358. }
  1359. );
  1360. fadeInAnimation.setEndCallback
  1361. (
  1362. [this]()
  1363. {
  1364. blackoutImage->setVisible(false);
  1365. if (fadeInEndCallback != nullptr)
  1366. {
  1367. fadeInEndCallback();
  1368. }
  1369. }
  1370. );
  1371. // Setup fade-out animation callbacks
  1372. fadeOutAnimation.setAnimateCallback
  1373. (
  1374. [this](std::size_t id, float opacity)
  1375. {
  1376. Vector3 color = Vector3(blackoutImage->getTintColor());
  1377. blackoutImage->setTintColor(Vector4(color, opacity));
  1378. }
  1379. );
  1380. fadeOutAnimation.setEndCallback
  1381. (
  1382. [this]()
  1383. {
  1384. blackoutImage->setVisible(false);
  1385. if (fadeOutEndCallback != nullptr)
  1386. {
  1387. fadeOutEndCallback();
  1388. }
  1389. }
  1390. );
  1391. animator.addAnimation(&fadeInAnimation);
  1392. animator.addAnimation(&fadeOutAnimation);
  1393. // Construct camera flash animation clip
  1394. cameraFlashClip.setInterpolator(easeOutQuad<float>);
  1395. channel = cameraFlashClip.addChannel(0);
  1396. channel->insertKeyframe(0.0f, 1.0f);
  1397. channel->insertKeyframe(1.0f, 0.0f);
  1398. // Setup camera flash animation
  1399. float flashDuration = 0.5f;
  1400. cameraFlashAnimation.setSpeed(1.0f / flashDuration);
  1401. cameraFlashAnimation.setLoop(false);
  1402. cameraFlashAnimation.setClip(&cameraFlashClip);
  1403. cameraFlashAnimation.setTimeFrame(cameraFlashClip.getTimeFrame());
  1404. cameraFlashAnimation.setAnimateCallback
  1405. (
  1406. [this](std::size_t id, float opacity)
  1407. {
  1408. cameraFlashImage->setTintColor(Vector4(Vector3(1.0f), opacity));
  1409. }
  1410. );
  1411. cameraFlashAnimation.setStartCallback
  1412. (
  1413. [this]()
  1414. {
  1415. cameraFlashImage->setVisible(true);
  1416. cameraFlashImage->setTintColor(Vector4(1.0f));
  1417. cameraFlashImage->resetTweens();
  1418. }
  1419. );
  1420. cameraFlashAnimation.setEndCallback
  1421. (
  1422. [this]()
  1423. {
  1424. cameraFlashImage->setVisible(false);
  1425. }
  1426. );
  1427. animator.addAnimation(&cameraFlashAnimation);
  1428. // Setup UI scene
  1429. uiScene->addObject(uiBatch);
  1430. uiScene->addObject(&uiCamera);
  1431. // Setup UI camera
  1432. uiCamera.lookAt(Vector3(0), Vector3(0, 0, -1), Vector3(0, 1, 0));
  1433. uiCamera.resetTweens();
  1434. uiCamera.setCompositor(&uiCompositor);
  1435. uiCamera.setCompositeIndex(0);
  1436. uiCamera.setCullingEnabled(false);
  1437. restringUI();
  1438. resizeUI(w, h);
  1439. }
  1440. void Game::setupControls()
  1441. {
  1442. // Get keyboard and mouse
  1443. keyboard = deviceManager->getKeyboards()->front();
  1444. mouse = deviceManager->getMice()->front();
  1445. // Build the master control set
  1446. controls.addControl(&exitControl);
  1447. controls.addControl(&toggleFullscreenControl);
  1448. controls.addControl(&takeScreenshotControl);
  1449. controls.addControl(&menuUpControl);
  1450. controls.addControl(&menuDownControl);
  1451. controls.addControl(&menuLeftControl);
  1452. controls.addControl(&menuRightControl);
  1453. controls.addControl(&menuActivateControl);
  1454. controls.addControl(&menuBackControl);
  1455. controls.addControl(&moveForwardControl);
  1456. controls.addControl(&moveBackControl);
  1457. controls.addControl(&moveLeftControl);
  1458. controls.addControl(&moveRightControl);
  1459. controls.addControl(&zoomInControl);
  1460. controls.addControl(&zoomOutControl);
  1461. controls.addControl(&orbitCCWControl);
  1462. controls.addControl(&orbitCWControl);
  1463. controls.addControl(&adjustCameraControl);
  1464. controls.addControl(&dragCameraControl);
  1465. controls.addControl(&changeToolControl);
  1466. controls.addControl(&useToolControl);
  1467. controls.addControl(&toggleEditModeControl);
  1468. controls.addControl(&toggleWireframeControl);
  1469. // Build the system control set
  1470. systemControls.addControl(&exitControl);
  1471. systemControls.addControl(&toggleFullscreenControl);
  1472. systemControls.addControl(&takeScreenshotControl);
  1473. // Build the menu control set
  1474. menuControls.addControl(&menuUpControl);
  1475. menuControls.addControl(&menuDownControl);
  1476. menuControls.addControl(&menuLeftControl);
  1477. menuControls.addControl(&menuRightControl);
  1478. menuControls.addControl(&menuActivateControl);
  1479. menuControls.addControl(&menuBackControl);
  1480. // Build the camera control set
  1481. cameraControls.addControl(&moveForwardControl);
  1482. cameraControls.addControl(&moveBackControl);
  1483. cameraControls.addControl(&moveLeftControl);
  1484. cameraControls.addControl(&moveRightControl);
  1485. cameraControls.addControl(&zoomInControl);
  1486. cameraControls.addControl(&zoomOutControl);
  1487. cameraControls.addControl(&orbitCCWControl);
  1488. cameraControls.addControl(&orbitCWControl);
  1489. cameraControls.addControl(&adjustCameraControl);
  1490. cameraControls.addControl(&dragCameraControl);
  1491. // Build the tool control set
  1492. toolControls.addControl(&changeToolControl);
  1493. toolControls.addControl(&useToolControl);
  1494. // Build the editor control set
  1495. editorControls.addControl(&toggleEditModeControl);
  1496. // Setup control callbacks
  1497. menuDownControl.setActivatedCallback(std::bind(&Game::selectNextMenuItem, this));
  1498. menuUpControl.setActivatedCallback(std::bind(&Game::selectPreviousMenuItem, this));
  1499. menuActivateControl.setActivatedCallback(std::bind(&Game::activateMenuItem, this));
  1500. menuBackControl.setActivatedCallback(std::bind(&Game::activateLastMenuItem, this));
  1501. exitControl.setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1502. toggleFullscreenControl.setActivatedCallback(std::bind(&Game::toggleFullscreen, this));
  1503. takeScreenshotControl.setActivatedCallback(std::bind(&Game::queueScreenshot, this));
  1504. toggleWireframeControl.setActivatedCallback(std::bind(&Game::toggleWireframe, this));
  1505. // Build map of control names
  1506. controlNameMap["exit"] = &exitControl;
  1507. controlNameMap["toggle-fullscreen"] = &toggleFullscreenControl;
  1508. controlNameMap["take-screenshot"] = &takeScreenshotControl;
  1509. controlNameMap["menu-up"] = &menuUpControl;
  1510. controlNameMap["menu-down"] = &menuDownControl;
  1511. controlNameMap["menu-left"] = &menuLeftControl;
  1512. controlNameMap["menu-right"] = &menuRightControl;
  1513. controlNameMap["menu-activate"] = &menuActivateControl;
  1514. controlNameMap["menu-back"] = &menuBackControl;
  1515. controlNameMap["move-forward"] = &moveForwardControl;
  1516. controlNameMap["move-back"] = &moveBackControl;
  1517. controlNameMap["move-left"] = &moveLeftControl;
  1518. controlNameMap["move-right"] = &moveRightControl;
  1519. controlNameMap["zoom-in"] = &zoomInControl;
  1520. controlNameMap["zoom-out"] = &zoomOutControl;
  1521. controlNameMap["orbit-ccw"] = &orbitCCWControl;
  1522. controlNameMap["orbit-cw"] = &orbitCWControl;
  1523. controlNameMap["adjust-camera"] = &adjustCameraControl;
  1524. controlNameMap["drag-camera"] = &dragCameraControl;
  1525. controlNameMap["change-tool"] = &changeToolControl;
  1526. controlNameMap["use-tool"] = &useToolControl;
  1527. controlNameMap["toggle-edit-mode"] = &toggleEditModeControl;
  1528. controlNameMap["toggle-wireframe"] = &toggleWireframeControl;
  1529. // Load control profile
  1530. if (pathExists(controlsPath + controlProfileName + ".csv"))
  1531. {
  1532. loadControlProfile(controlProfileName);
  1533. }
  1534. else
  1535. {
  1536. loadControlProfile("default-controls");
  1537. saveControlProfile(controlProfileName);
  1538. }
  1539. // Setup input mapper
  1540. inputMapper = new InputMapper(&eventDispatcher);
  1541. inputMapper->setCallback(std::bind(&Game::mapInput, this, std::placeholders::_1));
  1542. inputMapper->setControl(nullptr);
  1543. inputMapper->setEnabled(false);
  1544. }
  1545. void Game::setupGameplay()
  1546. {
  1547. // Setup step scheduler
  1548. double maxFrameDuration = 0.25;
  1549. double stepFrequency = 60.0;
  1550. stepScheduler.setMaxFrameDuration(maxFrameDuration);
  1551. stepScheduler.setStepFrequency(stepFrequency);
  1552. timestep = stepScheduler.getStepPeriod();
  1553. // Setup camera rigs
  1554. cameraRig = nullptr;
  1555. orbitCam = new OrbitCam();
  1556. orbitCam->attachCamera(&camera);
  1557. freeCam = new FreeCam();
  1558. freeCam->attachCamera(&camera);
  1559. }
  1560. void Game::resetSettings()
  1561. {
  1562. // Set default language
  1563. language = "en-us";
  1564. // Set default resolutions
  1565. const Display* display = deviceManager->getDisplays()->front();
  1566. int displayWidth = std::get<0>(display->getDimensions());
  1567. int displayHeight = std::get<1>(display->getDimensions());
  1568. float windowedResolutionRatio = 5.0f / 6.0f;
  1569. windowedResolution = Vector2(displayWidth, displayHeight) * 5.0f / 6.0f;
  1570. windowedResolution.x = static_cast<int>(windowedResolution.x);
  1571. windowedResolution.y = static_cast<int>(windowedResolution.y);
  1572. fullscreenResolution = Vector2(displayWidth, displayHeight);
  1573. // Set default fullscreen mode
  1574. fullscreen = false;
  1575. // Set default vsync mode
  1576. vsync = true;
  1577. // Set default font size
  1578. fontSizePT = 14.0f;
  1579. // Set control profile name
  1580. controlProfileName = "controls";
  1581. }
  1582. void Game::loadSettings()
  1583. {
  1584. // Reset settings to default values
  1585. resetSettings();
  1586. // Load settings table
  1587. try
  1588. {
  1589. settingsTable = resourceManager->load<CSVTable>("settings.csv");
  1590. }
  1591. catch (const std::exception& e)
  1592. {
  1593. settingsTable = new CSVTable();
  1594. }
  1595. // Build settings map
  1596. for (std::size_t i = 0; i < settingsTable->size(); ++i)
  1597. {
  1598. const CSVRow& row = (*settingsTable)[i];
  1599. settingsMap[row[0]] = i;
  1600. }
  1601. // Read settings from table
  1602. readSetting("language", &language);
  1603. readSetting("windowed-resolution", &windowedResolution);
  1604. readSetting("fullscreen-resolution", &fullscreenResolution);
  1605. readSetting("fullscreen", &fullscreen);
  1606. readSetting("vsync", &vsync);
  1607. readSetting("font-size", &fontSizePT);
  1608. readSetting("control-profile", &controlProfileName);
  1609. }
  1610. void Game::saveSettings()
  1611. {}
  1612. void Game::loadStrings()
  1613. {
  1614. // Read strings file
  1615. stringTable = resourceManager->load<CSVTable>("strings.csv");
  1616. // Build string map
  1617. for (int row = 0; row < stringTable->size(); ++row)
  1618. {
  1619. stringMap[(*stringTable)[row][0]] = row;
  1620. }
  1621. }
  1622. void Game::loadFonts()
  1623. {
  1624. // Get filenames of fonts
  1625. std::string menuFontFilename = getString("menu-font-filename");
  1626. std::string debugFontFilename = "inconsolata-bold.ttf";
  1627. // Load debugging font
  1628. if (!debugFont)
  1629. {
  1630. debugTypeface = resourceManager->load<Typeface>(debugFontFilename);
  1631. debugFont = debugTypeface->createFont(fontSizePX);
  1632. debugTypeface->loadCharset(debugFont, UnicodeRange::BASIC_LATIN);
  1633. }
  1634. // Load menu typeface
  1635. menuTypeface = resourceManager->load<Typeface>(menuFontFilename);
  1636. menuFont = menuTypeface->createFont(fontSizePX * 1.5f);
  1637. menuTypeface->loadCharset(menuFont, UnicodeRange::BASIC_LATIN);
  1638. // Load menu font typeface
  1639. menuTypeface = resourceManager->load<Typeface>(menuFontFilename);
  1640. // Create menu font
  1641. menuFont = menuTypeface->createFont(fontSizePX * 1.5f);
  1642. // Load basic latin character set
  1643. menuTypeface->loadCharset(menuFont, UnicodeRange::BASIC_LATIN);
  1644. // Build character set for all strings in current language
  1645. std::set<char32_t> characterSet;
  1646. for (const CSVRow& row: *stringTable)
  1647. {
  1648. // Convert to UTF-8 string to UTF-32
  1649. std::u32string string = toUTF32(row[languageIndex + 2]);
  1650. // Add each character in the string to the charater set
  1651. for (char32_t charcode: string)
  1652. {
  1653. characterSet.emplace(charcode);
  1654. }
  1655. }
  1656. // Load custom character set
  1657. menuTypeface->loadCharset(menuFont, characterSet);
  1658. }
  1659. void Game::loadControlProfile(const std::string& profileName)
  1660. {
  1661. // Load control profile
  1662. std::string controlProfilePath = profileName + ".csv";
  1663. CSVTable* controlProfile = resourceManager->load<CSVTable>(controlProfilePath);
  1664. for (const CSVRow& row: *controlProfile)
  1665. {
  1666. // Skip empty rows and comments
  1667. if (row.empty() || row[0].empty() || row[0][0] == '#')
  1668. {
  1669. continue;
  1670. }
  1671. // Get control name
  1672. const std::string& controlName = row[0];
  1673. // Lookup control in control name map
  1674. auto it = controlNameMap.find(controlName);
  1675. if (it == controlNameMap.end())
  1676. {
  1677. std::cerr << "Game::loadControlProfile(): Unknown control name \"" << controlName << "\"" << std::endl;
  1678. continue;
  1679. }
  1680. // Get pointer to the control
  1681. Control* control = it->second;
  1682. // Determine type of input mapping
  1683. const std::string& deviceType = row[1];
  1684. if (deviceType == "keyboard")
  1685. {
  1686. const std::string& eventType = row[2];
  1687. const std::string& scancodeName = row[3];
  1688. // Get scancode from string
  1689. Scancode scancode = Keyboard::getScancodeFromName(scancodeName.c_str());
  1690. // Map control
  1691. if (scancode != Scancode::UNKNOWN)
  1692. {
  1693. inputRouter->addMapping(KeyMapping(control, keyboard, scancode));
  1694. }
  1695. }
  1696. else if (deviceType == "mouse")
  1697. {
  1698. const std::string& eventType = row[2];
  1699. if (eventType == "motion")
  1700. {
  1701. const std::string& axisName = row[3];
  1702. // Get axis from string
  1703. MouseMotionAxis axis;
  1704. bool negative = (axisName.find('-') != std::string::npos);
  1705. if (axisName.find('x') != std::string::npos)
  1706. {
  1707. axis = (negative) ? MouseMotionAxis::NEGATIVE_X : MouseMotionAxis::POSITIVE_X;
  1708. }
  1709. else if (axisName.find('y') != std::string::npos)
  1710. {
  1711. axis = (negative) ? MouseMotionAxis::NEGATIVE_Y : MouseMotionAxis::POSITIVE_Y;
  1712. }
  1713. else
  1714. {
  1715. std::cerr << "Game::loadControlProfile(): Unknown mouse motion axis \"" << axisName << "\"" << std::endl;
  1716. continue;
  1717. }
  1718. // Map control
  1719. inputRouter->addMapping(MouseMotionMapping(control, mouse, axis));
  1720. }
  1721. else if (eventType == "wheel")
  1722. {
  1723. const std::string& axisName = row[3];
  1724. // Get axis from string
  1725. MouseWheelAxis axis;
  1726. bool negative = (axisName.find('-') != std::string::npos);
  1727. if (axisName.find('x') != std::string::npos)
  1728. {
  1729. axis = (negative) ? MouseWheelAxis::NEGATIVE_X : MouseWheelAxis::POSITIVE_X;
  1730. }
  1731. else if (axisName.find('y') != std::string::npos)
  1732. {
  1733. axis = (negative) ? MouseWheelAxis::NEGATIVE_Y : MouseWheelAxis::POSITIVE_Y;
  1734. }
  1735. else
  1736. {
  1737. std::cerr << "Game::loadControlProfile(): Unknown mouse wheel axis \"" << axisName << "\"" << std::endl;
  1738. continue;
  1739. }
  1740. // Map control
  1741. inputRouter->addMapping(MouseWheelMapping(control, mouse, axis));
  1742. }
  1743. else if (eventType == "button")
  1744. {
  1745. const std::string& buttonName = row[3];
  1746. // Get button from string
  1747. int button;
  1748. std::stringstream stream;
  1749. stream << buttonName;
  1750. stream >> button;
  1751. // Map control
  1752. inputRouter->addMapping(MouseButtonMapping(control, mouse, button));
  1753. }
  1754. else
  1755. {
  1756. std::cerr << "Game::loadControlProfile(): Unknown mouse event type \"" << eventType << "\"" << std::endl;
  1757. continue;
  1758. }
  1759. }
  1760. else if (deviceType == "gamepad")
  1761. {
  1762. const std::string& eventType = row[2];
  1763. if (eventType == "axis")
  1764. {
  1765. std::string axisName = row[3];
  1766. // Determine whether axis is negative or positive
  1767. bool negative = (axisName.find('-') != std::string::npos);
  1768. // Remove sign from axis name
  1769. std::size_t plusPosition = axisName.find('+');
  1770. std::size_t minusPosition = axisName.find('-');
  1771. if (plusPosition != std::string::npos)
  1772. {
  1773. axisName.erase(plusPosition);
  1774. }
  1775. else if (minusPosition != std::string::npos)
  1776. {
  1777. axisName.erase(minusPosition);
  1778. }
  1779. // Get axis from string
  1780. int axis;
  1781. std::stringstream stream;
  1782. stream << axisName;
  1783. stream >> axis;
  1784. // Map control to each gamepad
  1785. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  1786. for (Gamepad* gamepad: *gamepads)
  1787. {
  1788. inputRouter->addMapping(GamepadAxisMapping(control, gamepad, axis, negative));
  1789. }
  1790. }
  1791. else if (eventType == "button")
  1792. {
  1793. const std::string& buttonName = row[3];
  1794. // Get button from string
  1795. int button;
  1796. std::stringstream stream;
  1797. stream << buttonName;
  1798. stream >> button;
  1799. // Map control to each gamepad
  1800. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  1801. for (Gamepad* gamepad: *gamepads)
  1802. {
  1803. inputRouter->addMapping(GamepadButtonMapping(control, gamepad, button));
  1804. }
  1805. }
  1806. else
  1807. {
  1808. std::cerr << "Game::loadControlProfile(): Unknown gamepad event type \"" << eventType << "\"" << std::endl;
  1809. continue;
  1810. }
  1811. }
  1812. else
  1813. {
  1814. std::cerr << "Game::loadControlProfile(): Unknown input device type \"" << deviceType << "\"" << std::endl;
  1815. continue;
  1816. }
  1817. }
  1818. }
  1819. void Game::saveControlProfile(const std::string& profileName)
  1820. {
  1821. // Build control profile CSV table
  1822. CSVTable* table = new CSVTable();
  1823. for (auto it = controlNameMap.begin(); it != controlNameMap.end(); ++it)
  1824. {
  1825. // Get control name
  1826. const std::string& controlName = it->first;
  1827. // Get pointer to the control
  1828. Control* control = it->second;
  1829. // Look up list of mappings for the control
  1830. const std::list<InputMapping*>* mappings = inputRouter->getMappings(control);
  1831. if (!mappings)
  1832. {
  1833. continue;
  1834. }
  1835. // For each input mapping
  1836. for (const InputMapping* mapping: *mappings)
  1837. {
  1838. // Add row to the table
  1839. table->push_back(CSVRow());
  1840. CSVRow* row = &table->back();
  1841. // Add control name column
  1842. row->push_back(controlName);
  1843. switch (mapping->getType())
  1844. {
  1845. case InputMappingType::KEY:
  1846. {
  1847. const KeyMapping* keyMapping = static_cast<const KeyMapping*>(mapping);
  1848. row->push_back("keyboard");
  1849. row->push_back("key");
  1850. std::string scancodeName = std::string("\"") + std::string(Keyboard::getScancodeName(keyMapping->scancode)) + std::string("\"");
  1851. row->push_back(scancodeName);
  1852. break;
  1853. }
  1854. case InputMappingType::MOUSE_MOTION:
  1855. {
  1856. const MouseMotionMapping* mouseMotionMapping = static_cast<const MouseMotionMapping*>(mapping);
  1857. row->push_back("mouse");
  1858. row->push_back("motion");
  1859. std::string axisName;
  1860. if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_X)
  1861. {
  1862. axisName = "+x";
  1863. }
  1864. else if (mouseMotionMapping->axis == MouseMotionAxis::NEGATIVE_X)
  1865. {
  1866. axisName = "-x";
  1867. }
  1868. else if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_Y)
  1869. {
  1870. axisName = "+y";
  1871. }
  1872. else
  1873. {
  1874. axisName = "-y";
  1875. }
  1876. row->push_back(axisName);
  1877. break;
  1878. }
  1879. case InputMappingType::MOUSE_WHEEL:
  1880. {
  1881. const MouseWheelMapping* mouseWheelMapping = static_cast<const MouseWheelMapping*>(mapping);
  1882. row->push_back("mouse");
  1883. row->push_back("wheel");
  1884. std::string axisName;
  1885. if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_X)
  1886. {
  1887. axisName = "+x";
  1888. }
  1889. else if (mouseWheelMapping->axis == MouseWheelAxis::NEGATIVE_X)
  1890. {
  1891. axisName = "-x";
  1892. }
  1893. else if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_Y)
  1894. {
  1895. axisName = "+y";
  1896. }
  1897. else
  1898. {
  1899. axisName = "-y";
  1900. }
  1901. row->push_back(axisName);
  1902. break;
  1903. }
  1904. case InputMappingType::MOUSE_BUTTON:
  1905. {
  1906. const MouseButtonMapping* mouseButtonMapping = static_cast<const MouseButtonMapping*>(mapping);
  1907. row->push_back("mouse");
  1908. row->push_back("button");
  1909. std::string buttonName;
  1910. std::stringstream stream;
  1911. stream << static_cast<int>(mouseButtonMapping->button);
  1912. stream >> buttonName;
  1913. row->push_back(buttonName);
  1914. break;
  1915. }
  1916. case InputMappingType::GAMEPAD_AXIS:
  1917. {
  1918. const GamepadAxisMapping* gamepadAxisMapping = static_cast<const GamepadAxisMapping*>(mapping);
  1919. row->push_back("gamepad");
  1920. row->push_back("axis");
  1921. std::stringstream stream;
  1922. if (gamepadAxisMapping->negative)
  1923. {
  1924. stream << "-";
  1925. }
  1926. else
  1927. {
  1928. stream << "+";
  1929. }
  1930. stream << gamepadAxisMapping->axis;
  1931. std::string axisName;
  1932. stream >> axisName;
  1933. row->push_back(axisName);
  1934. break;
  1935. }
  1936. case InputMappingType::GAMEPAD_BUTTON:
  1937. {
  1938. const GamepadButtonMapping* gamepadButtonMapping = static_cast<const GamepadButtonMapping*>(mapping);
  1939. row->push_back("gamepad");
  1940. row->push_back("button");
  1941. std::string buttonName;
  1942. std::stringstream stream;
  1943. stream << static_cast<int>(gamepadButtonMapping->button);
  1944. stream >> buttonName;
  1945. row->push_back(buttonName);
  1946. break;
  1947. }
  1948. default:
  1949. break;
  1950. }
  1951. }
  1952. }
  1953. // Form full path to control profile file
  1954. std::string controlProfilePath = controlsPath + profileName + ".csv";
  1955. // Save control profile
  1956. resourceManager->save<CSVTable>(table, controlProfilePath);
  1957. // Free control profile CSV table
  1958. delete table;
  1959. }
  1960. std::array<std::string, 3> Game::getInputMappingStrings(const InputMapping* mapping)
  1961. {
  1962. std::string deviceString;
  1963. std::string typeString;
  1964. std::string eventString;
  1965. switch (mapping->getType())
  1966. {
  1967. case InputMappingType::KEY:
  1968. {
  1969. const KeyMapping* keyMapping = static_cast<const KeyMapping*>(mapping);
  1970. deviceString = "keyboard";
  1971. typeString = "key";
  1972. eventString = std::string(Keyboard::getScancodeName(keyMapping->scancode));
  1973. break;
  1974. }
  1975. case InputMappingType::MOUSE_MOTION:
  1976. {
  1977. const MouseMotionMapping* mouseMotionMapping = static_cast<const MouseMotionMapping*>(mapping);
  1978. deviceString = "mouse";
  1979. eventString = "motion";
  1980. if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_X)
  1981. {
  1982. eventString = "+x";
  1983. }
  1984. else if (mouseMotionMapping->axis == MouseMotionAxis::NEGATIVE_X)
  1985. {
  1986. eventString = "-x";
  1987. }
  1988. else if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_Y)
  1989. {
  1990. eventString = "+y";
  1991. }
  1992. else
  1993. {
  1994. eventString = "-y";
  1995. }
  1996. break;
  1997. }
  1998. case InputMappingType::MOUSE_WHEEL:
  1999. {
  2000. const MouseWheelMapping* mouseWheelMapping = static_cast<const MouseWheelMapping*>(mapping);
  2001. deviceString = "mouse";
  2002. typeString = "wheel";
  2003. if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_X)
  2004. {
  2005. eventString = "+x";
  2006. }
  2007. else if (mouseWheelMapping->axis == MouseWheelAxis::NEGATIVE_X)
  2008. {
  2009. eventString = "-x";
  2010. }
  2011. else if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_Y)
  2012. {
  2013. eventString = "+y";
  2014. }
  2015. else
  2016. {
  2017. eventString = "-y";
  2018. }
  2019. break;
  2020. }
  2021. case InputMappingType::MOUSE_BUTTON:
  2022. {
  2023. const MouseButtonMapping* mouseButtonMapping = static_cast<const MouseButtonMapping*>(mapping);
  2024. deviceString = "mouse";
  2025. typeString = "button";
  2026. std::stringstream stream;
  2027. stream << static_cast<int>(mouseButtonMapping->button);
  2028. stream >> eventString;
  2029. break;
  2030. }
  2031. case InputMappingType::GAMEPAD_AXIS:
  2032. {
  2033. const GamepadAxisMapping* gamepadAxisMapping = static_cast<const GamepadAxisMapping*>(mapping);
  2034. deviceString = "gamepad";
  2035. typeString = "axis";
  2036. std::stringstream stream;
  2037. if (gamepadAxisMapping->negative)
  2038. {
  2039. stream << "-";
  2040. }
  2041. else
  2042. {
  2043. stream << "+";
  2044. }
  2045. stream << gamepadAxisMapping->axis;
  2046. stream >> eventString;
  2047. break;
  2048. }
  2049. case InputMappingType::GAMEPAD_BUTTON:
  2050. {
  2051. const GamepadButtonMapping* gamepadButtonMapping = static_cast<const GamepadButtonMapping*>(mapping);
  2052. deviceString = "gamepad";
  2053. typeString = "button";
  2054. std::stringstream stream;
  2055. stream << static_cast<int>(gamepadButtonMapping->button);
  2056. stream >> eventString;
  2057. break;
  2058. }
  2059. default:
  2060. break;
  2061. }
  2062. return {deviceString, typeString, eventString};
  2063. }
  2064. void Game::remapControl(Control* control)
  2065. {
  2066. // Remove previously set input mappings for the control
  2067. inputRouter->removeMappings(control);
  2068. // Start mapping new input
  2069. inputMapper->setControl(control);
  2070. inputMapper->setEnabled(true);
  2071. // Restring UI to show control mappings have been removed.
  2072. restringUI();
  2073. // Disable UI callbacks
  2074. uiRootElement->setCallbacksEnabled(false);
  2075. // Disable menu control callbacks
  2076. menuControls.setCallbacksEnabled(false);
  2077. }
  2078. void Game::resetControls()
  2079. {
  2080. inputRouter->reset();
  2081. loadControlProfile("default-controls");
  2082. saveControlProfile(controlProfileName);
  2083. restringUI();
  2084. }
  2085. void Game::resizeUI(int w, int h)
  2086. {
  2087. // Adjust root element dimensions
  2088. uiRootElement->setDimensions(Vector2(w, h));
  2089. uiRootElement->update();
  2090. splashBackgroundImage->setDimensions(Vector2(w, h));
  2091. splashBackgroundImage->setAnchor(Anchor::TOP_LEFT);
  2092. // Resize splash screen image
  2093. splashImage->setAnchor(Anchor::CENTER);
  2094. splashImage->setDimensions(Vector2(splashTexture->getWidth(), splashTexture->getHeight()));
  2095. // Adjust UI camera projection matrix
  2096. uiCamera.setOrthographic(0.0f, w, h, 0.0f, -1.0f, 1.0f);
  2097. uiCamera.resetTweens();
  2098. // Resize camera flash image
  2099. cameraFlashImage->setDimensions(Vector2(w, h));
  2100. cameraFlashImage->setAnchor(Anchor::CENTER);
  2101. // Resize blackout image
  2102. blackoutImage->setDimensions(Vector2(w, h));
  2103. blackoutImage->setAnchor(Anchor::CENTER);
  2104. // Resize HUD
  2105. float hudPadding = 20.0f;
  2106. hudContainer->setDimensions(Vector2(w - hudPadding * 2.0f, h - hudPadding * 2.0f));
  2107. hudContainer->setAnchor(Anchor::CENTER);
  2108. // Tool indicator
  2109. Rect toolIndicatorBounds = hudTextureAtlas.getBounds("tool-indicator");
  2110. toolIndicatorBGImage->setDimensions(Vector2(toolIndicatorBounds.getWidth(), toolIndicatorBounds.getHeight()));
  2111. toolIndicatorBGImage->setAnchor(Anchor::TOP_LEFT);
  2112. Rect toolIndicatorIconBounds = hudTextureAtlas.getBounds("tool-indicator-lens");
  2113. toolIndicatorIconImage->setDimensions(Vector2(toolIndicatorIconBounds.getWidth(), toolIndicatorIconBounds.getHeight()));
  2114. toolIndicatorIconImage->setAnchor(Anchor::CENTER);
  2115. // Buttons
  2116. Rect playButtonBounds = hudTextureAtlas.getBounds("button-play");
  2117. Rect fastForwardButtonBounds = hudTextureAtlas.getBounds("button-fast-forward-2x");
  2118. Rect pauseButtonBounds = hudTextureAtlas.getBounds("button-pause");
  2119. Rect buttonBackgroundBounds = hudTextureAtlas.getBounds("button-background");
  2120. Vector2 buttonBGDimensions = Vector2(buttonBackgroundBounds.getWidth(), buttonBackgroundBounds.getHeight());
  2121. float buttonMargin = 10.0f;
  2122. float buttonDepth = 15.0f;
  2123. float buttonContainerWidth = fastForwardButtonBounds.getWidth();
  2124. float buttonContainerHeight = fastForwardButtonBounds.getHeight();
  2125. buttonContainer->setDimensions(Vector2(buttonContainerWidth, buttonContainerHeight));
  2126. buttonContainer->setAnchor(Anchor::TOP_RIGHT);
  2127. playButtonImage->setDimensions(Vector2(playButtonBounds.getWidth(), playButtonBounds.getHeight()));
  2128. playButtonImage->setAnchor(Vector2(0.0f, 0.0f));
  2129. playButtonBGImage->setDimensions(buttonBGDimensions);
  2130. playButtonBGImage->setAnchor(Vector2(0.0f, 1.0f));
  2131. fastForwardButtonImage->setDimensions(Vector2(fastForwardButtonBounds.getWidth(), fastForwardButtonBounds.getHeight()));
  2132. fastForwardButtonImage->setAnchor(Vector2(0.5f, 5.0f));
  2133. fastForwardButtonBGImage->setDimensions(buttonBGDimensions);
  2134. fastForwardButtonBGImage->setAnchor(Vector2(0.5f, 0.5f));
  2135. pauseButtonImage->setDimensions(Vector2(pauseButtonBounds.getWidth(), pauseButtonBounds.getHeight()));
  2136. pauseButtonImage->setAnchor(Vector2(1.0f, 0.0f));
  2137. pauseButtonBGImage->setDimensions(buttonBGDimensions);
  2138. pauseButtonBGImage->setAnchor(Vector2(1.0f, 1.0f));
  2139. // Radial menu
  2140. Rect radialMenuBounds = hudTextureAtlas.getBounds("radial-menu");
  2141. radialMenuContainer->setDimensions(Vector2(w, h));
  2142. radialMenuContainer->setAnchor(Anchor::CENTER);
  2143. radialMenuContainer->setLayerOffset(30);
  2144. radialMenuBackgroundImage->setDimensions(Vector2(w, h));
  2145. radialMenuBackgroundImage->setAnchor(Anchor::CENTER);
  2146. radialMenuBackgroundImage->setLayerOffset(-1);
  2147. //radialMenuImage->setDimensions(Vector2(w * 0.5f, h * 0.5f));
  2148. radialMenuImage->setDimensions(Vector2(radialMenuBounds.getWidth(), radialMenuBounds.getHeight()));
  2149. radialMenuImage->setAnchor(Anchor::CENTER);
  2150. Rect radialMenuSelectorBounds = hudTextureAtlas.getBounds("radial-menu-selector");
  2151. radialMenuSelectorImage->setDimensions(Vector2(radialMenuSelectorBounds.getWidth(), radialMenuSelectorBounds.getHeight()));
  2152. radialMenuSelectorImage->setAnchor(Anchor::CENTER);
  2153. Rect toolIconBrushBounds = hudTextureAtlas.getBounds("tool-icon-brush");
  2154. toolIconBrushImage->setDimensions(Vector2(toolIconBrushBounds.getWidth(), toolIconBrushBounds.getHeight()));
  2155. toolIconBrushImage->setAnchor(Anchor::CENTER);
  2156. Rect toolIconLensBounds = hudTextureAtlas.getBounds("tool-icon-lens");
  2157. toolIconLensImage->setDimensions(Vector2(toolIconLensBounds.getWidth(), toolIconLensBounds.getHeight()));
  2158. toolIconLensImage->setAnchor(Anchor::CENTER);
  2159. Rect toolIconForcepsBounds = hudTextureAtlas.getBounds("tool-icon-forceps");
  2160. toolIconForcepsImage->setDimensions(Vector2(toolIconForcepsBounds.getWidth(), toolIconForcepsBounds.getHeight()));
  2161. toolIconForcepsImage->setAnchor(Anchor::CENTER);
  2162. Rect toolIconSpadeBounds = hudTextureAtlas.getBounds("tool-icon-spade");
  2163. toolIconSpadeImage->setDimensions(Vector2(toolIconSpadeBounds.getWidth(), toolIconSpadeBounds.getHeight()));
  2164. toolIconSpadeImage->setAnchor(Anchor::CENTER);
  2165. Rect toolIconCameraBounds = hudTextureAtlas.getBounds("tool-icon-camera");
  2166. toolIconCameraImage->setDimensions(Vector2(toolIconCameraBounds.getWidth(), toolIconCameraBounds.getHeight()));
  2167. toolIconCameraImage->setAnchor(Anchor::CENTER);
  2168. Rect toolIconMicrochipBounds = hudTextureAtlas.getBounds("tool-icon-microchip");
  2169. toolIconMicrochipImage->setDimensions(Vector2(toolIconMicrochipBounds.getWidth(), toolIconMicrochipBounds.getHeight()));
  2170. toolIconMicrochipImage->setAnchor(Anchor::CENTER);
  2171. Rect toolIconTestTubeBounds = hudTextureAtlas.getBounds("tool-icon-test-tube");
  2172. toolIconTestTubeImage->setDimensions(Vector2(toolIconTestTubeBounds.getWidth(), toolIconTestTubeBounds.getHeight()));
  2173. toolIconTestTubeImage->setAnchor(Anchor::CENTER);
  2174. Rect labelCornerBounds = hudTextureAtlas.getBounds("label-tl");
  2175. Vector2 labelCornerDimensions(labelCornerBounds.getWidth(), labelCornerBounds.getHeight());
  2176. Vector2 antLabelPadding(10.0f, 6.0f);
  2177. antLabelContainer->setDimensions(antLabel->getDimensions() + antLabelPadding * 2.0f);
  2178. antLabelContainer->setTranslation(Vector2(0.0f, (int)(-antPin->getDimensions().y * 0.125f)));
  2179. antLabelTL->setDimensions(labelCornerDimensions);
  2180. antLabelTR->setDimensions(labelCornerDimensions);
  2181. antLabelBL->setDimensions(labelCornerDimensions);
  2182. antLabelBR->setDimensions(labelCornerDimensions);
  2183. antLabelCC->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  2184. antLabelCT->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  2185. antLabelCB->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  2186. antLabelCL->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  2187. antLabelCR->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  2188. antLabelContainer->setAnchor(Vector2(0.5f, 0.5f));
  2189. antLabelTL->setAnchor(Anchor::TOP_LEFT);
  2190. antLabelTR->setAnchor(Anchor::TOP_RIGHT);
  2191. antLabelBL->setAnchor(Anchor::BOTTOM_LEFT);
  2192. antLabelBR->setAnchor(Anchor::BOTTOM_RIGHT);
  2193. antLabelCC->setAnchor(Anchor::CENTER);
  2194. antLabelCT->setAnchor(Vector2(0.5f, 0.0f));
  2195. antLabelCB->setAnchor(Vector2(0.5f, 1.0f));
  2196. antLabelCL->setAnchor(Vector2(0.0f, 0.5f));
  2197. antLabelCR->setAnchor(Vector2(1.0f, 0.5f));
  2198. antLabel->setAnchor(Anchor::CENTER);
  2199. Rect antPinBounds = hudTextureAtlas.getBounds("label-pin");
  2200. antPin->setDimensions(Vector2(antPinBounds.getWidth(), antPinBounds.getHeight()));
  2201. antPin->setAnchor(Vector2(0.5f, 1.0f));
  2202. Rect pinHoleBounds = hudTextureAtlas.getBounds("label-pin-hole");
  2203. antLabelPinHole->setDimensions(Vector2(pinHoleBounds.getWidth(), pinHoleBounds.getHeight()));
  2204. antLabelPinHole->setAnchor(Vector2(0.5f, 0.0f));
  2205. antLabelPinHole->setTranslation(Vector2(0.0f, -antLabelPinHole->getDimensions().y * 0.5f));
  2206. antLabelPinHole->setLayerOffset(2);
  2207. float pinDistance = 20.0f;
  2208. antTag->setAnchor(Anchor::CENTER);
  2209. antTag->setDimensions(Vector2(antLabelContainer->getDimensions().x, antPin->getDimensions().y));
  2210. float cameraGridLineWidth = 2.0f;
  2211. float cameraReticleDiameter = 6.0f;
  2212. cameraGridContainer->setDimensions(Vector2(w, h));
  2213. cameraGridY0Image->setDimensions(Vector2(w, cameraGridLineWidth));
  2214. cameraGridY1Image->setDimensions(Vector2(w, cameraGridLineWidth));
  2215. cameraGridX0Image->setDimensions(Vector2(cameraGridLineWidth, h));
  2216. cameraGridX1Image->setDimensions(Vector2(cameraGridLineWidth, h));
  2217. cameraReticleImage->setDimensions(Vector2(cameraReticleDiameter));
  2218. cameraGridY0Image->setTranslation(Vector2(0));
  2219. cameraGridY1Image->setTranslation(Vector2(0));
  2220. cameraGridX0Image->setTranslation(Vector2(0));
  2221. cameraGridX1Image->setTranslation(Vector2(0));
  2222. cameraReticleImage->setTranslation(Vector2(0));
  2223. Rect menuSelectorBounds = hudTextureAtlas.getBounds("menu-selector");
  2224. menuSelectorImage->setDimensions(Vector2(menuSelectorBounds.getWidth(), menuSelectorBounds.getHeight()));
  2225. UIImage* icons[] =
  2226. {
  2227. toolIconBrushImage,
  2228. nullptr,
  2229. toolIconLensImage,
  2230. nullptr,
  2231. toolIconForcepsImage,
  2232. toolIconMicrochipImage,
  2233. toolIconCameraImage,
  2234. nullptr
  2235. };
  2236. Rect radialMenuIconRingBounds = hudTextureAtlas.getBounds("radial-menu-icon-ring");
  2237. float iconOffset = radialMenuIconRingBounds.getWidth() * 0.5f;
  2238. float sectorAngle = (2.0f * 3.14159264f) / 8.0f;
  2239. for (int i = 0; i < 8; ++i)
  2240. {
  2241. float angle = sectorAngle * static_cast<float>(i - 4);
  2242. Vector2 translation = Vector2(std::cos(angle), std::sin(angle)) * iconOffset;
  2243. translation.x = (int)(translation.x + 0.5f);
  2244. translation.y = (int)(translation.y + 0.5f);
  2245. if (icons[i] != nullptr)
  2246. {
  2247. icons[i]->setTranslation(translation);
  2248. }
  2249. }
  2250. // Main menu size
  2251. float mainMenuWidth = 0.0f;
  2252. float mainMenuHeight = 0.0f;
  2253. float mainMenuSpacing = 0.5f * fontSizePX;
  2254. float mainMenuPadding = fontSizePX * 4.0f;
  2255. for (const MenuItem* item: *mainMenu->getItems())
  2256. {
  2257. mainMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2258. mainMenuHeight += mainMenuSpacing;
  2259. mainMenuWidth = std::max<float>(mainMenuWidth, item->getNameLabel()->getDimensions().x);
  2260. }
  2261. mainMenuHeight -= mainMenuSpacing;
  2262. mainMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2263. mainMenu->resize(mainMenuWidth, mainMenuHeight);
  2264. mainMenu->getContainer()->setTranslation(Vector2(-mainMenuPadding));
  2265. // Settings menu size
  2266. float settingsMenuWidth = 0.0f;
  2267. float settingsMenuHeight = 0.0f;
  2268. float settingsMenuSpacing = 0.5f * fontSizePX;
  2269. float settingsMenuPadding = fontSizePX * 4.0f;
  2270. float settingsMenuValueMargin = fontSizePX * 4.0f;
  2271. for (const MenuItem* item: *settingsMenu->getItems())
  2272. {
  2273. settingsMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2274. settingsMenuHeight += settingsMenuSpacing;
  2275. float itemWidth = item->getNameLabel()->getDimensions().x;
  2276. if (!item->getValueLabel()->getText().empty())
  2277. {
  2278. itemWidth += item->getValueLabel()->getDimensions().x + settingsMenuValueMargin;
  2279. }
  2280. settingsMenuWidth = std::max<float>(settingsMenuWidth, itemWidth);
  2281. }
  2282. settingsMenuHeight -= settingsMenuSpacing;
  2283. settingsMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2284. settingsMenu->resize(settingsMenuWidth, settingsMenuHeight);
  2285. settingsMenu->getContainer()->setTranslation(Vector2(-settingsMenuPadding));
  2286. // Controls menu size
  2287. float controlsMenuWidth = 0.0f;
  2288. float controlsMenuHeight = 0.0f;
  2289. float controlsMenuSpacing = 0.5f * fontSizePX;
  2290. float controlsMenuPadding = fontSizePX * 4.0f;
  2291. float controlsMenuValueMargin = fontSizePX * 4.0f;
  2292. for (const MenuItem* item: *controlsMenu->getItems())
  2293. {
  2294. controlsMenuHeight += item->getNameLabel()->getFont()->getMetrics().getHeight();
  2295. controlsMenuHeight += controlsMenuSpacing;
  2296. float itemWidth = item->getNameLabel()->getDimensions().x;
  2297. if (!item->getValueLabel()->getText().empty())
  2298. {
  2299. itemWidth += item->getValueLabel()->getDimensions().x + controlsMenuValueMargin;
  2300. }
  2301. controlsMenuWidth = std::max<float>(controlsMenuWidth, itemWidth);
  2302. }
  2303. controlsMenuWidth += controlsMenuValueMargin;
  2304. controlsMenuHeight -= controlsMenuSpacing;
  2305. controlsMenu->getContainer()->setAnchor(Anchor::BOTTOM_RIGHT);
  2306. controlsMenu->resize(controlsMenuWidth, controlsMenuHeight);
  2307. controlsMenu->getContainer()->setTranslation(Vector2(-controlsMenuPadding));
  2308. }
  2309. void Game::restringUI()
  2310. {
  2311. // Reset fonts
  2312. mainMenu->setFonts(menuFont);
  2313. settingsMenu->setFonts(menuFont);
  2314. controlsMenu->setFonts(menuFont);
  2315. // Get common strings
  2316. std::string offString = getString("off");
  2317. std::string onString = getString("on");
  2318. std::string backString = getString("back");
  2319. // Main menu strings
  2320. mainMenuContinueItem->setName(getString("continue"));
  2321. mainMenuNewGameItem->setName(getString("new-game"));
  2322. mainMenuColoniesItem->setName(getString("colonies"));
  2323. mainMenuSettingsItem->setName(getString("settings"));
  2324. mainMenuQuitItem->setName(getString("quit"));
  2325. // Settings menu strings
  2326. settingsMenuControlsItem->setName(getString("controls"));
  2327. settingsMenuControlsItem->setValue(getString("dotdotdot"));
  2328. settingsMenuFullscreenItem->setName(getString("fullscreen"));
  2329. settingsMenuFullscreenItem->setValue((fullscreen) ? onString : offString);
  2330. settingsMenuVSyncItem->setName(getString("v-sync"));
  2331. settingsMenuVSyncItem->setValue((vsync) ? onString : offString);
  2332. settingsMenuLanguageItem->setName(getString("language"));
  2333. settingsMenuLanguageItem->setValue(getString("language-name"));
  2334. settingsMenuBackItem->setName(backString);
  2335. // Controls menu strings
  2336. restringControlMenuItem(controlsMenuMoveForwardItem, "move-forward");
  2337. restringControlMenuItem(controlsMenuMoveLeftItem, "move-left");
  2338. restringControlMenuItem(controlsMenuMoveBackItem, "move-back");
  2339. restringControlMenuItem(controlsMenuMoveRightItem, "move-right");
  2340. restringControlMenuItem(controlsMenuChangeToolItem, "change-tool");
  2341. restringControlMenuItem(controlsMenuUseToolItem, "use-tool");
  2342. restringControlMenuItem(controlsMenuAdjustCameraItem, "adjust-camera");
  2343. restringControlMenuItem(controlsMenuToggleFullscreenItem, "toggle-fullscreen");
  2344. restringControlMenuItem(controlsMenuTakeScreenshotItem, "take-screenshot");
  2345. controlsMenuResetToDefaultItem->setName(getString("reset-to-default"));
  2346. controlsMenuBackItem->setName(backString);
  2347. // Reset menu tweens
  2348. uiRootElement->update();
  2349. mainMenu->getContainer()->resetTweens();
  2350. settingsMenu->getContainer()->resetTweens();
  2351. controlsMenu->getContainer()->resetTweens();
  2352. }
  2353. void Game::restringControlMenuItem(MenuItem* item, const std::string& name)
  2354. {
  2355. item->setName(getString(name));
  2356. Control* control = controlNameMap.find(name)->second;
  2357. std::string value;
  2358. const std::list<InputMapping*>* mappings = inputRouter->getMappings(control);
  2359. if (mappings != nullptr)
  2360. {
  2361. std::size_t i = 0;
  2362. for (const InputMapping* mapping: *mappings)
  2363. {
  2364. std::array<std::string, 3> mappingStrings = getInputMappingStrings(mapping);
  2365. // keyboard-key, mouse-button, gamepad-axis, etc.
  2366. std::string typeName = mappingStrings[0] + "-" + mappingStrings[1];
  2367. std::string type = getString(typeName);
  2368. if (mapping->getType() != InputMappingType::KEY)
  2369. {
  2370. value += type;
  2371. value += " ";
  2372. }
  2373. value += mappingStrings[2];
  2374. if (i < mappings->size() - 1)
  2375. {
  2376. value += ", ";
  2377. }
  2378. ++i;
  2379. }
  2380. }
  2381. item->setValue(value);
  2382. }
  2383. void Game::setTimeOfDay(float time)
  2384. {
  2385. Vector3 midnight = Vector3(0.0f, 1.0f, 0.0f);
  2386. Vector3 sunrise = Vector3(-1.0f, 0.0f, 0.0f);
  2387. Vector3 noon = Vector3(0, -1.0f, 0.0f);
  2388. Vector3 sunset = Vector3(1.0f, 0.0f, 0.0f);
  2389. float angles[4] =
  2390. {
  2391. glm::radians(270.0f), // 00:00
  2392. glm::radians(0.0f), // 06:00
  2393. glm::radians(90.0f), // 12:00
  2394. glm::radians(180.0f) // 18:00
  2395. };
  2396. int index0 = static_cast<int>(fmod(time, 24.0f) / 6.0f);
  2397. int index1 = (index0 + 1) % 4;
  2398. float t = (time - (static_cast<float>(index0) * 6.0f)) / 6.0f;
  2399. Quaternion rotation0 = glm::angleAxis(angles[index0], Vector3(1, 0, 0));
  2400. Quaternion rotation1 = glm::angleAxis(angles[index1], Vector3(1, 0, 0));
  2401. Quaternion rotation = glm::normalize(glm::slerp(rotation0, rotation1, t));
  2402. Vector3 direction = glm::normalize(rotation * Vector3(0, 0, 1));
  2403. sunlight.setDirection(direction);
  2404. Vector3 up = glm::normalize(rotation * Vector3(0, 1, 0));
  2405. sunlightCamera.lookAt(Vector3(0, 0, 0), sunlight.getDirection(), up);
  2406. }
  2407. void Game::toggleWireframe()
  2408. {
  2409. wireframe = !wireframe;
  2410. float width = (wireframe) ? 1.0f : 0.0f;
  2411. lightingPass->setWireframeLineWidth(width);
  2412. }
  2413. void Game::queueScreenshot()
  2414. {
  2415. screenshotQueued = true;
  2416. cameraFlashImage->setVisible(false);
  2417. cameraGridContainer->setVisible(false);
  2418. fpsLabel->setVisible(false);
  2419. soundSystem->scrot();
  2420. }
  2421. void Game::screenshot()
  2422. {
  2423. screenshotQueued = false;
  2424. // Read pixel data from framebuffer
  2425. unsigned char* pixels = new unsigned char[w * h * 3];
  2426. glReadBuffer(GL_BACK);
  2427. glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pixels);
  2428. // Get game title in current language
  2429. std::string title = getString("title");
  2430. // Convert title to lowercase
  2431. std::transform(title.begin(), title.end(), title.begin(), ::tolower);
  2432. // Create screenshot directory if it doesn't exist
  2433. std::string screenshotDirectory = configPath + std::string("screenshots/");
  2434. if (!pathExists(screenshotDirectory))
  2435. {
  2436. createDirectory(screenshotDirectory);
  2437. }
  2438. // Build screenshot file name
  2439. std::string filename = screenshotDirectory + title + "-" + timestamp() + ".png";
  2440. // Write screenshot to file in separate thread
  2441. std::thread screenshotThread(Game::saveScreenshot, filename, w, h, pixels);
  2442. screenshotThread.detach();
  2443. // Play camera flash animation
  2444. cameraFlashAnimation.stop();
  2445. cameraFlashAnimation.rewind();
  2446. cameraFlashAnimation.play();
  2447. // Play camera shutter sound
  2448. // Restore camera UI visibility
  2449. //cameraGridContainer->setVisible(true);
  2450. fpsLabel->setVisible(true);
  2451. // Whiteout screen immediately
  2452. glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
  2453. glClear(GL_COLOR_BUFFER_BIT);
  2454. }
  2455. void Game::mapInput(const InputMapping& mapping)
  2456. {
  2457. // Skip mouse motion events
  2458. if (mapping.getType() == InputMappingType::MOUSE_MOTION)
  2459. {
  2460. return;
  2461. }
  2462. // Add input mapping to input router
  2463. if (mapping.control != nullptr)
  2464. {
  2465. inputRouter->addMapping(mapping);
  2466. }
  2467. // Disable input mapping generation
  2468. inputMapper->setControl(nullptr);
  2469. inputMapper->setEnabled(false);
  2470. // Restring UI
  2471. restringUI();
  2472. // Schedule callbacks to be enabled in 100ms
  2473. ScheduledFunctionEvent event;
  2474. event.caller = static_cast<void*>(this);
  2475. event.function = [this]()
  2476. {
  2477. // Re-enable UI callbacks
  2478. uiRootElement->setCallbacksEnabled(true);
  2479. // Re-enable menu controls
  2480. menuControls.setCallbacksEnabled(true);
  2481. };
  2482. eventDispatcher.schedule(event, time + 0.1f);
  2483. // Save control profile
  2484. saveControlProfile(controlProfileName);
  2485. }
  2486. void Game::enterSplashState()
  2487. {
  2488. // Show splash screen
  2489. splashBackgroundImage->setVisible(true);
  2490. splashImage->setVisible(true);
  2491. splashImage->setTintColor({1, 1, 1, 0});
  2492. splashBackgroundImage->setTintColor({0, 0, 0, 1});
  2493. splashImage->resetTweens();
  2494. splashBackgroundImage->resetTweens();
  2495. uiRootElement->update();
  2496. // Add splash animations to animator
  2497. animator.addAnimation(&splashFadeInAnimation);
  2498. animator.addAnimation(&splashFadeOutAnimation);
  2499. // Play splash fade-in animation
  2500. splashFadeInAnimation.rewind();
  2501. splashFadeInAnimation.play();
  2502. }
  2503. void Game::exitSplashState()
  2504. {
  2505. // Hide splash screen
  2506. splashImage->setVisible(false);
  2507. splashBackgroundImage->setVisible(false);
  2508. uiRootElement->update();
  2509. // Remove splash animations from animator
  2510. animator.removeAnimation(&splashFadeInAnimation);
  2511. animator.removeAnimation(&splashFadeOutAnimation);
  2512. }
  2513. void Game::enterLoadingState()
  2514. {}
  2515. void Game::exitLoadingState()
  2516. {}
  2517. void Game::enterTitleState()
  2518. {
  2519. // Setup scene
  2520. Vector3 antHillTranslation = {0, 0, 0};
  2521. EntityID antHill = createInstanceOf("ant-hill");
  2522. setTranslation(antHill, antHillTranslation);
  2523. // Setup camera
  2524. cameraRig = orbitCam;
  2525. orbitCam->setTargetFocalPoint(antHillTranslation);
  2526. orbitCam->setTargetFocalDistance(0.0f);
  2527. orbitCam->setTargetElevation(glm::radians(80.0f));
  2528. orbitCam->setTargetAzimuth(0.0f);
  2529. orbitCam->setFocalPoint(orbitCam->getTargetFocalPoint());
  2530. orbitCam->setFocalDistance(orbitCam->getTargetFocalDistance());
  2531. orbitCam->setElevation(orbitCam->getTargetElevation());
  2532. orbitCam->setAzimuth(orbitCam->getTargetAzimuth());
  2533. float fov = glm::radians(30.0f);
  2534. orbitCam->getCamera()->setPerspective(fov, (float)w / (float)h, 1.0f, 1000.0f);
  2535. // Begin fade-in
  2536. fadeIn(6.0f, {0, 0, 0}, nullptr);
  2537. //
  2538. animator.addAnimation(&antHillZoomAnimation);
  2539. antHillZoomAnimation.rewind();
  2540. antHillZoomAnimation.play();
  2541. animator.addAnimation(&menuFadeAnimation);
  2542. menuFadeAnimation.rewind();
  2543. menuFadeAnimation.play();
  2544. // Select the first menu item
  2545. openMenu(mainMenu, 0);
  2546. }
  2547. void Game::exitTitleState()
  2548. {
  2549. animator.removeAnimation(&antHillZoomAnimation);
  2550. animator.removeAnimation(&menuFadeAnimation);
  2551. }
  2552. void Game::enterPlayState()
  2553. {}
  2554. void Game::exitPlayState()
  2555. {}
  2556. void Game::skipSplash()
  2557. {
  2558. if (StateMachine::getCurrentState() == &splashState)
  2559. {
  2560. StateMachine::changeState(&titleState);
  2561. }
  2562. }
  2563. void Game::boxSelect(float x, float y, float w, float h)
  2564. {
  2565. boxSelectionContainer->setTranslation(Vector2(x, y));
  2566. boxSelectionContainer->setDimensions(Vector2(w, h));
  2567. boxSelectionImageBackground->setDimensions(Vector2(w, h));
  2568. boxSelectionImageTop->setDimensions(Vector2(w, boxSelectionBorderWidth));
  2569. boxSelectionImageBottom->setDimensions(Vector2(w, boxSelectionBorderWidth));
  2570. boxSelectionImageLeft->setDimensions(Vector2(boxSelectionBorderWidth, h));
  2571. boxSelectionImageRight->setDimensions(Vector2(boxSelectionBorderWidth, h));
  2572. boxSelectionContainer->setVisible(true);
  2573. }
  2574. void Game::fadeIn(float duration, const Vector3& color, std::function<void()> callback)
  2575. {
  2576. if (fadeInAnimation.isPlaying())
  2577. {
  2578. return;
  2579. }
  2580. fadeOutAnimation.stop();
  2581. this->fadeInEndCallback = callback;
  2582. blackoutImage->setTintColor(Vector4(color, 1.0f));
  2583. blackoutImage->setVisible(true);
  2584. fadeInAnimation.setSpeed(1.0f / duration);
  2585. fadeInAnimation.setLoop(false);
  2586. fadeInAnimation.setClip(&fadeInClip);
  2587. fadeInAnimation.setTimeFrame(fadeInClip.getTimeFrame());
  2588. fadeInAnimation.rewind();
  2589. fadeInAnimation.play();
  2590. blackoutImage->resetTweens();
  2591. uiRootElement->update();
  2592. }
  2593. void Game::fadeOut(float duration, const Vector3& color, std::function<void()> callback)
  2594. {
  2595. if (fadeOutAnimation.isPlaying())
  2596. {
  2597. return;
  2598. }
  2599. fadeInAnimation.stop();
  2600. this->fadeOutEndCallback = callback;
  2601. blackoutImage->setVisible(true);
  2602. blackoutImage->setTintColor(Vector4(color, 0.0f));
  2603. fadeOutAnimation.setSpeed(1.0f / duration);
  2604. fadeOutAnimation.setLoop(false);
  2605. fadeOutAnimation.setClip(&fadeOutClip);
  2606. fadeOutAnimation.setTimeFrame(fadeOutClip.getTimeFrame());
  2607. fadeOutAnimation.rewind();
  2608. fadeOutAnimation.play();
  2609. blackoutImage->resetTweens();
  2610. uiRootElement->update();
  2611. }
  2612. void Game::stopFade()
  2613. {
  2614. fadeInAnimation.stop();
  2615. fadeOutAnimation.stop();
  2616. blackoutImage->setVisible(false);
  2617. uiRootElement->update();
  2618. }
  2619. void Game::selectTool(int toolIndex)
  2620. {
  2621. Tool* tools[] =
  2622. {
  2623. brush,
  2624. nullptr,
  2625. lens,
  2626. nullptr,
  2627. forceps,
  2628. nullptr,
  2629. nullptr,
  2630. nullptr
  2631. };
  2632. Tool* nextTool = tools[toolIndex];
  2633. if (nextTool != currentTool)
  2634. {
  2635. if (currentTool)
  2636. {
  2637. currentTool->setActive(false);
  2638. currentTool->update(0.0f);
  2639. }
  2640. currentTool = nextTool;
  2641. if (currentTool)
  2642. {
  2643. currentTool->setActive(true);
  2644. }
  2645. }
  2646. if (1)
  2647. {
  2648. toolIndicatorIconImage->setTextureBounds(toolIndicatorsBounds[toolIndex]);
  2649. toolIndicatorIconImage->setVisible(true);
  2650. }
  2651. else
  2652. {
  2653. toolIndicatorIconImage->setVisible(false);
  2654. }
  2655. }
  2656. EntityID Game::createInstance()
  2657. {
  2658. return entityManager->createEntity();
  2659. }
  2660. EntityID Game::createInstanceOf(const std::string& templateName)
  2661. {
  2662. EntityTemplate* entityTemplate = resourceManager->load<EntityTemplate>(templateName + ".ent");
  2663. EntityID entity = entityManager->createEntity();
  2664. entityTemplate->apply(entity, componentManager);
  2665. return entity;
  2666. }
  2667. void Game::destroyInstance(EntityID entity)
  2668. {
  2669. entityManager->destroyEntity(entity);
  2670. }
  2671. void Game::addComponent(EntityID entity, ComponentBase* component)
  2672. {
  2673. componentManager->addComponent(entity, component);
  2674. }
  2675. void Game::removeComponent(EntityID entity, ComponentType type)
  2676. {
  2677. ComponentBase* component = componentManager->removeComponent(entity, type);
  2678. delete component;
  2679. }
  2680. void Game::setTranslation(EntityID entity, const Vector3& translation)
  2681. {
  2682. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  2683. if (!component)
  2684. {
  2685. return;
  2686. }
  2687. component->transform.translation = translation;
  2688. }
  2689. void Game::setRotation(EntityID entity, const Quaternion& rotation)
  2690. {
  2691. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  2692. if (!component)
  2693. {
  2694. return;
  2695. }
  2696. component->transform.rotation = rotation;
  2697. }
  2698. void Game::setScale(EntityID entity, const Vector3& scale)
  2699. {
  2700. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  2701. if (!component)
  2702. {
  2703. return;
  2704. }
  2705. component->transform.scale = scale;
  2706. }
  2707. void Game::setTerrainPatchPosition(EntityID entity, const std::tuple<int, int>& position)
  2708. {
  2709. TerrainPatchComponent* component = componentManager->getComponent<TerrainPatchComponent>(entity);
  2710. if (!component)
  2711. {
  2712. return;
  2713. }
  2714. component->position = position;
  2715. }
  2716. void Game::saveScreenshot(const std::string& filename, unsigned int width, unsigned int height, unsigned char* pixels)
  2717. {
  2718. stbi_flip_vertically_on_write(1);
  2719. stbi_write_png(filename.c_str(), width, height, 3, pixels, width * 3);
  2720. delete[] pixels;
  2721. }