💿🐜 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.

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