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

2313 lines
74 KiB

5 years ago
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/csv-table.hpp"
  21. #include "states/game-state.hpp"
  22. #include "states/splash-state.hpp"
  23. #include "states/sandbox-state.hpp"
  24. #include "filesystem.hpp"
  25. #include "timestamp.hpp"
  26. #include "ui/ui.hpp"
  27. #include "graphics/ui-render-pass.hpp"
  28. #include "graphics/shadow-map-render-pass.hpp"
  29. #include "graphics/clear-render-pass.hpp"
  30. #include "graphics/sky-render-pass.hpp"
  31. #include "graphics/lighting-render-pass.hpp"
  32. #include "graphics/silhouette-render-pass.hpp"
  33. #include "graphics/final-render-pass.hpp"
  34. #include "resources/resource-manager.hpp"
  35. #include "resources/text-file.hpp"
  36. #include "game/camera-rig.hpp"
  37. #include "game/lens.hpp"
  38. #include "game/forceps.hpp"
  39. #include "game/brush.hpp"
  40. #include "entity/component-manager.hpp"
  41. #include "entity/components/transform-component.hpp"
  42. #include "entity/components/model-component.hpp"
  43. #include "entity/components/terrain-patch-component.hpp"
  44. #include "entity/entity-manager.hpp"
  45. #include "entity/entity-template.hpp"
  46. #include "entity/system-manager.hpp"
  47. #include "entity/systems/sound-system.hpp"
  48. #include "entity/systems/collision-system.hpp"
  49. #include "entity/systems/render-system.hpp"
  50. #include "entity/systems/camera-system.hpp"
  51. #include "entity/systems/tool-system.hpp"
  52. #include "entity/systems/locomotion-system.hpp"
  53. #include "entity/systems/behavior-system.hpp"
  54. #include "entity/systems/steering-system.hpp"
  55. #include "entity/systems/particle-system.hpp"
  56. #include "entity/systems/terrain-system.hpp"
  57. #include "stb/stb_image_write.h"
  58. #include <algorithm>
  59. #include <cctype>
  60. #include <fstream>
  61. #include <sstream>
  62. #include <stdexcept>
  63. #include <thread>
  64. template <>
  65. bool Game::readSetting<std::string>(const std::string& name, std::string* value) const
  66. {
  67. auto it = settingsMap.find(name);
  68. if (it == settingsMap.end())
  69. {
  70. return false;
  71. }
  72. *value = (*settingsTable)[it->second][1];
  73. return true;
  74. }
  75. template <>
  76. bool Game::readSetting<bool>(const std::string& name, bool* value) const
  77. {
  78. auto it = settingsMap.find(name);
  79. if (it == settingsMap.end())
  80. {
  81. return false;
  82. }
  83. const std::string& string = (*settingsTable)[it->second][1];
  84. if (string == "true" || string == "on" || string == "1")
  85. {
  86. *value = true;
  87. return true;
  88. }
  89. else if (string == "false" || string == "off" || string == "0")
  90. {
  91. *value = false;
  92. return true;
  93. }
  94. return false;
  95. }
  96. template <>
  97. bool Game::readSetting<int>(const std::string& name, int* value) const
  98. {
  99. auto it = settingsMap.find(name);
  100. if (it == settingsMap.end())
  101. {
  102. return false;
  103. }
  104. std::stringstream stream;
  105. stream << (*settingsTable)[it->second][1];
  106. stream >> (*value);
  107. return (!stream.fail());
  108. }
  109. template <>
  110. bool Game::readSetting<float>(const std::string& name, float* value) const
  111. {
  112. auto it = settingsMap.find(name);
  113. if (it == settingsMap.end())
  114. {
  115. return false;
  116. }
  117. std::stringstream stream;
  118. stream << (*settingsTable)[it->second][1];
  119. stream >> (*value);
  120. return (!stream.fail());
  121. }
  122. template <>
  123. bool Game::readSetting<Vector2>(const std::string& name, Vector2* value) const
  124. {
  125. auto it = settingsMap.find(name);
  126. if (it == settingsMap.end())
  127. {
  128. return false;
  129. }
  130. std::stringstream stream;
  131. stream << (*settingsTable)[it->second][1];
  132. stream >> value->x;
  133. stream.str(std::string());
  134. stream.clear();
  135. stream << (*settingsTable)[it->second][2];
  136. stream >> value->y;
  137. return (!stream.fail());
  138. }
  139. Game::Game(int argc, char* argv[]):
  140. currentState(nullptr),
  141. window(nullptr)
  142. {
  143. // Determine application name
  144. std::string applicationName;
  145. #if defined(_WIN32)
  146. applicationName = "Antkeeper";
  147. #else
  148. applicationName = "antkeeper";
  149. #endif
  150. // Form resource paths
  151. dataPath = getDataPath(applicationName) + "data/";
  152. configPath = getConfigPath(applicationName);
  153. controlsPath = configPath + "controls/";
  154. // Create nonexistent config directories
  155. std::vector<std::string> configPaths;
  156. configPaths.push_back(configPath);
  157. configPaths.push_back(controlsPath);
  158. for (const std::string& path: configPaths)
  159. {
  160. if (!pathExists(path))
  161. {
  162. createDirectory(path);
  163. }
  164. }
  165. // Setup logging
  166. #if !defined(DEBUG)
  167. std::string logFilename = configPath + "log.txt";
  168. logFileStream.open(logFilename.c_str());
  169. std::cout.rdbuf(logFileStream.rdbuf());
  170. #endif
  171. std::cout << "Data path: " << dataPath << std::endl;
  172. std::cout << "Config path: " << configPath << std::endl;
  173. // Setup resource manager
  174. resourceManager = new ResourceManager();
  175. // Include resource search paths in order of priority
  176. resourceManager->include(controlsPath);
  177. resourceManager->include(configPath);
  178. resourceManager->include(dataPath);
  179. splashState = new SplashState(this);
  180. sandboxState = new SandboxState(this);
  181. }
  182. Game::~Game()
  183. {
  184. if (window)
  185. {
  186. windowManager->destroyWindow(window);
  187. }
  188. }
  189. void Game::changeState(GameState* state)
  190. {
  191. if (currentState != nullptr)
  192. {
  193. currentState->exit();
  194. }
  195. currentState = state;
  196. if (currentState != nullptr)
  197. {
  198. currentState->enter();
  199. }
  200. }
  201. std::string Game::getString(std::size_t languageIndex, const std::string& name) const
  202. {
  203. std::string value;
  204. auto it = stringMap.find(name);
  205. if (it != stringMap.end())
  206. {
  207. value = (*stringTable)[it->second][languageIndex + 1];
  208. if (value.empty())
  209. {
  210. value = std::string("# EMPTY STRING: ") + name + std::string(" #");
  211. }
  212. }
  213. else
  214. {
  215. value = std::string("# MISSING STRING: ") + name + std::string(" #");
  216. }
  217. return value;
  218. }
  219. void Game::changeLanguage(std::size_t languageIndex)
  220. {
  221. this->languageIndex = languageIndex;
  222. window->setTitle(getString(getLanguageIndex(), "title").c_str());
  223. restringUI();
  224. resizeUI(w, h);
  225. }
  226. void Game::toggleFullscreen()
  227. {
  228. fullscreen = !fullscreen;
  229. window->setFullscreen(fullscreen);
  230. }
  231. void Game::setUpdateRate(double frequency)
  232. {
  233. stepScheduler.setStepFrequency(frequency);
  234. }
  235. void Game::setup()
  236. {
  237. loadSettings();
  238. setupDebugging();
  239. setupLocalization();
  240. setupWindow();
  241. setupGraphics();
  242. setupUI();
  243. setupControls();
  244. setupGameplay();
  245. #if defined(DEBUG)
  246. toggleWireframe();
  247. #endif // DEBUG
  248. screenshotQueued = false;
  249. // Load model resources
  250. try
  251. {
  252. lensModel = resourceManager->load<Model>("lens.mdl");
  253. forcepsModel = resourceManager->load<Model>("forceps.mdl");
  254. brushModel = resourceManager->load<Model>("brush.mdl");
  255. smokeMaterial = resourceManager->load<Material>("smoke.mtl");
  256. }
  257. catch (const std::exception& e)
  258. {
  259. std::cerr << "Failed to load one or more models: \"" << e.what() << "\"" << std::endl;
  260. close(EXIT_FAILURE);
  261. }
  262. time = 0.0f;
  263. // Tools
  264. currentTool = nullptr;
  265. lens = new Lens(lensModel, &animator);
  266. lens->setOrbitCam(orbitCam);
  267. worldScene->addObject(lens->getModelInstance());
  268. worldScene->addObject(lens->getSpotlight());
  269. lens->setSunDirection(-sunlightCamera.getForward());
  270. ModelInstance* modelInstance = lens->getModelInstance();
  271. for (std::size_t i = 0; i < modelInstance->getModel()->getGroupCount(); ++i)
  272. {
  273. Material* material = modelInstance->getModel()->getGroup(i)->material->clone();
  274. material->setFlags(material->getFlags() | 256);
  275. modelInstance->setMaterialSlot(i, material);
  276. }
  277. // Forceps
  278. forceps = new Forceps(forcepsModel, &animator);
  279. forceps->setOrbitCam(orbitCam);
  280. worldScene->addObject(forceps->getModelInstance());
  281. // Brush
  282. brush = new Brush(brushModel, &animator);
  283. brush->setOrbitCam(orbitCam);
  284. worldScene->addObject(brush->getModelInstance());
  285. // Initialize component manager
  286. componentManager = new ComponentManager();
  287. // Initialize entity manager
  288. entityManager = new EntityManager(componentManager);
  289. // Initialize systems
  290. soundSystem = new SoundSystem(componentManager);
  291. collisionSystem = new CollisionSystem(componentManager);
  292. cameraSystem = new CameraSystem(componentManager);
  293. renderSystem = new RenderSystem(componentManager, worldScene);
  294. toolSystem = new ToolSystem(componentManager);
  295. toolSystem->setPickingCamera(&camera);
  296. toolSystem->setPickingViewport(Vector4(0, 0, w, h));
  297. eventDispatcher.subscribe<MouseMovedEvent>(toolSystem);
  298. behaviorSystem = new BehaviorSystem(componentManager);
  299. steeringSystem = new SteeringSystem(componentManager);
  300. locomotionSystem = new LocomotionSystem(componentManager);
  301. terrainSystem = new TerrainSystem(componentManager);
  302. terrainSystem->setPatchSize(500.0f);
  303. particleSystem = new ParticleSystem(componentManager);
  304. particleSystem->resize(1000);
  305. particleSystem->setMaterial(smokeMaterial);
  306. particleSystem->setDirection(Vector3(0, 1, 0));
  307. lens->setParticleSystem(particleSystem);
  308. particleSystem->getBillboardBatch()->setAlignment(&camera, BillboardAlignmentMode::SPHERICAL);
  309. worldScene->addObject(particleSystem->getBillboardBatch());
  310. // Initialize system manager
  311. systemManager = new SystemManager();
  312. systemManager->addSystem(soundSystem);
  313. systemManager->addSystem(behaviorSystem);
  314. systemManager->addSystem(steeringSystem);
  315. systemManager->addSystem(locomotionSystem);
  316. systemManager->addSystem(collisionSystem);
  317. systemManager->addSystem(toolSystem);
  318. systemManager->addSystem(terrainSystem);
  319. systemManager->addSystem(particleSystem);
  320. systemManager->addSystem(cameraSystem);
  321. systemManager->addSystem(renderSystem);
  322. /*
  323. EntityID sidewalkPanel;
  324. sidewalkPanel = createInstanceOf("sidewalk-panel");
  325. EntityID antHill = createInstanceOf("ant-hill");
  326. setTranslation(antHill, Vector3(20, 0, 40));
  327. EntityID antNest = createInstanceOf("ant-nest");
  328. setTranslation(antNest, Vector3(20, 0, 40));
  329. EntityID lollipop = createInstanceOf("lollipop");
  330. setTranslation(lollipop, Vector3(30.0f, 3.5f * 0.5f, -30.0f));
  331. setRotation(lollipop, glm::angleAxis(glm::radians(8.85f), Vector3(1.0f, 0.0f, 0.0f)));
  332. */
  333. // Load navmesh
  334. TriangleMesh* navmesh = resourceManager->load<TriangleMesh>("sidewalk.mesh");
  335. // Find surface
  336. TriangleMesh::Triangle* surface = nullptr;
  337. Vector3 barycentricPosition;
  338. Ray ray;
  339. ray.origin = Vector3(0, 100, 0);
  340. ray.direction = Vector3(0, -1, 0);
  341. auto intersection = ray.intersects(*navmesh);
  342. if (std::get<0>(intersection))
  343. {
  344. surface = (*navmesh->getTriangles())[std::get<3>(intersection)];
  345. Vector3 position = ray.extrapolate(std::get<1>(intersection));
  346. Vector3 a = surface->edge->vertex->position;
  347. Vector3 b = surface->edge->next->vertex->position;
  348. Vector3 c = surface->edge->previous->vertex->position;
  349. barycentricPosition = barycentric(position, a, b, c);
  350. }
  351. for (int i = 0; i < 0; ++i)
  352. {
  353. EntityID ant = createInstanceOf("worker-ant");
  354. setTranslation(ant, Vector3(0.0f, 0, 0.0f));
  355. BehaviorComponent* behavior = new BehaviorComponent();
  356. SteeringComponent* steering = new SteeringComponent();
  357. LeggedLocomotionComponent* locomotion = new LeggedLocomotionComponent();
  358. componentManager->addComponent(ant, behavior);
  359. componentManager->addComponent(ant, steering);
  360. componentManager->addComponent(ant, locomotion);
  361. locomotion->surface = surface;
  362. behavior->wanderTriangle = surface;
  363. locomotion->barycentricPosition = barycentricPosition;
  364. }
  365. //EntityID tool0 = createInstanceOf("lens");
  366. int highResolutionDiameter = 3;
  367. int mediumResolutionDiameter = highResolutionDiameter + 2;
  368. int lowResolutionDiameter = 20;
  369. float lowResolutionRadius = static_cast<float>(lowResolutionDiameter) / 2.0f;
  370. float mediumResolutionRadius = static_cast<float>(mediumResolutionDiameter) / 2.0f;
  371. float highResolutionRadius = static_cast<float>(highResolutionDiameter) / 2.0f;
  372. for (int i = 0; i < lowResolutionDiameter; ++i)
  373. {
  374. for (int j = 0; j < lowResolutionDiameter; ++j)
  375. {
  376. EntityID patch;
  377. int x = i - lowResolutionDiameter / 2;
  378. int z = j - lowResolutionDiameter / 2;
  379. if (std::abs(x) < highResolutionRadius && std::abs(z) < highResolutionRadius)
  380. {
  381. patch = createInstanceOf("terrain-patch-high-resolution");
  382. }
  383. else if (std::abs(x) < mediumResolutionRadius && std::abs(z) < mediumResolutionRadius)
  384. {
  385. patch = createInstanceOf("terrain-patch-medium-resolution");
  386. }
  387. else
  388. {
  389. patch = createInstanceOf("terrain-patch-low-resolution");
  390. }
  391. setTerrainPatchPosition(patch, {x, z});
  392. }
  393. }
  394. changeState(sandboxState);
  395. }
  396. void Game::update(float t, float dt)
  397. {
  398. this->time = t;
  399. // Execute current state
  400. if (currentState != nullptr)
  401. {
  402. currentState->execute();
  403. }
  404. // Update systems
  405. systemManager->update(t, dt);
  406. // Update animations
  407. animator.animate(dt);
  408. if (fpsLabel->isVisible())
  409. {
  410. std::stringstream stream;
  411. stream.precision(2);
  412. stream << std::fixed << (performanceSampler.getMeanFrameDuration() * 1000.0f);
  413. fpsLabel->setText(stream.str());
  414. }
  415. uiRootElement->update();
  416. }
  417. void Game::input()
  418. {
  419. controls.update();
  420. }
  421. void Game::render()
  422. {
  423. // Perform sub-frame interpolation on UI elements
  424. uiRootElement->interpolate(stepScheduler.getScheduledSubsteps());
  425. // Update and batch UI elements
  426. uiBatcher->batch(uiBatch, uiRootElement);
  427. // Perform sub-frame interpolation particles
  428. particleSystem->getBillboardBatch()->interpolate(stepScheduler.getScheduledSubsteps());
  429. particleSystem->getBillboardBatch()->batch();
  430. // Render scene
  431. renderer.render(*worldScene);
  432. renderer.render(*uiScene);
  433. if (screenshotQueued)
  434. {
  435. screenshot();
  436. screenshotQueued = false;
  437. }
  438. // Swap window framebuffers
  439. window->swapBuffers();
  440. }
  441. void Game::exit()
  442. {}
  443. void Game::handleEvent(const WindowResizedEvent& event)
  444. {
  445. w = event.width;
  446. h = event.height;
  447. defaultRenderTarget.width = event.width;
  448. defaultRenderTarget.height = event.height;
  449. glViewport(0, 0, event.width, event.height);
  450. camera.setPerspective(glm::radians(40.0f), static_cast<float>(w) / static_cast<float>(h), 0.1, 100.0f);
  451. toolSystem->setPickingViewport(Vector4(0, 0, w, h));
  452. resizeUI(event.width, event.height);
  453. }
  454. void Game::handleEvent(const GamepadConnectedEvent& event)
  455. {
  456. // Unmap all controls
  457. inputRouter->reset();
  458. // Reload control profile
  459. loadControlProfile();
  460. }
  461. void Game::handleEvent(const GamepadDisconnectedEvent& event)
  462. {}
  463. void Game::setupDebugging()
  464. {
  465. // Setup performance sampling
  466. performanceSampler.setSampleSize(30);
  467. // Disable wireframe drawing
  468. wireframe = false;
  469. }
  470. void Game::setupLocalization()
  471. {
  472. // Load strings
  473. loadStrings();
  474. // Determine number of available languages
  475. languageCount = (*stringTable)[0].size() - 1;
  476. // Match language code with language index
  477. languageIndex = 0;
  478. CSVRow* languageCodes = &(*stringTable)[0];
  479. for (std::size_t i = 1; i < languageCodes->size(); ++i)
  480. {
  481. if (language == (*languageCodes)[i])
  482. {
  483. languageIndex = i - 1;
  484. break;
  485. }
  486. }
  487. }
  488. void Game::setupWindow()
  489. {
  490. // Get display resolution
  491. const Display* display = deviceManager->getDisplays()->front();
  492. int displayWidth = std::get<0>(display->getDimensions());
  493. int displayHeight = std::get<1>(display->getDimensions());
  494. if (fullscreen)
  495. {
  496. w = static_cast<int>(fullscreenResolution.x);
  497. h = static_cast<int>(fullscreenResolution.y);
  498. }
  499. else
  500. {
  501. w = static_cast<int>(windowedResolution.x);
  502. h = static_cast<int>(windowedResolution.y);
  503. }
  504. // Determine window position
  505. int x = std::get<0>(display->getPosition()) + displayWidth / 2 - w / 2;
  506. int y = std::get<1>(display->getPosition()) + displayHeight / 2 - h / 2;
  507. // Read title string
  508. std::string title = getString(getLanguageIndex(), "title");
  509. // Create window
  510. window = windowManager->createWindow(title.c_str(), x, y, w, h, fullscreen, WindowFlag::RESIZABLE);
  511. if (!window)
  512. {
  513. throw std::runtime_error("Game::Game(): Failed to create window.");
  514. }
  515. // Set v-sync mode
  516. window->setVSync(vsync);
  517. }
  518. void Game::setupGraphics()
  519. {
  520. // Setup OpenGL
  521. glEnable(GL_MULTISAMPLE);
  522. // Setup default render target
  523. defaultRenderTarget.width = w;
  524. defaultRenderTarget.height = h;
  525. defaultRenderTarget.framebuffer = 0;
  526. // Set shadow map resolution
  527. shadowMapResolution = 4096;
  528. // Setup shadow map framebuffer
  529. glGenFramebuffers(1, &shadowMapFramebuffer);
  530. glBindFramebuffer(GL_FRAMEBUFFER, shadowMapFramebuffer);
  531. glGenTextures(1, &shadowMapDepthTextureID);
  532. glBindTexture(GL_TEXTURE_2D, shadowMapDepthTextureID);
  533. glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, shadowMapResolution, shadowMapResolution, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
  534. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  535. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  536. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  537. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  538. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);
  539. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  540. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowMapDepthTextureID, 0);
  541. glDrawBuffer(GL_NONE);
  542. glReadBuffer(GL_NONE);
  543. glBindTexture(GL_TEXTURE_2D, 0);
  544. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  545. // Setup shadow map render target
  546. shadowMapRenderTarget.width = shadowMapResolution;
  547. shadowMapRenderTarget.height = shadowMapResolution;
  548. shadowMapRenderTarget.framebuffer = shadowMapFramebuffer;
  549. // Setup shadow map depth texture
  550. shadowMapDepthTexture.setTextureID(shadowMapDepthTextureID);
  551. shadowMapDepthTexture.setWidth(shadowMapResolution);
  552. shadowMapDepthTexture.setHeight(shadowMapResolution);
  553. // Setup silhouette framebuffer
  554. glGenTextures(1, &silhouetteRenderTarget.texture);
  555. glBindTexture(GL_TEXTURE_2D, silhouetteRenderTarget.texture);
  556. glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
  557. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  558. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  559. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  560. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  561. glGenFramebuffers(1, &silhouetteRenderTarget.framebuffer);
  562. glBindFramebuffer(GL_FRAMEBUFFER, silhouetteRenderTarget.framebuffer);
  563. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, silhouetteRenderTarget.texture, 0);
  564. glDrawBuffer(GL_COLOR_ATTACHMENT0);
  565. glReadBuffer(GL_NONE);
  566. glBindTexture(GL_TEXTURE_2D, 0);
  567. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  568. // Setup silhouette render target
  569. silhouetteRenderTarget.width = w;
  570. silhouetteRenderTarget.height = h;
  571. // Setup shadow map render pass
  572. shadowMapPass = new ShadowMapRenderPass(resourceManager);
  573. shadowMapPass->setRenderTarget(&shadowMapRenderTarget);
  574. shadowMapPass->setViewCamera(&camera);
  575. shadowMapPass->setLightCamera(&sunlightCamera);
  576. // Setup shadow map compositor
  577. shadowMapCompositor.addPass(shadowMapPass);
  578. shadowMapCompositor.load(nullptr);
  579. // Setup clear render pass
  580. clearPass = new ClearRenderPass();
  581. clearPass->setRenderTarget(&defaultRenderTarget);
  582. clearPass->setClear(true, true, false);
  583. clearPass->setClearColor(Vector4(0.0f));
  584. clearPass->setClearDepth(1.0f);
  585. // Setup sky render pass
  586. skyPass = new SkyRenderPass(resourceManager);
  587. skyPass->setRenderTarget(&defaultRenderTarget);
  588. // Setup lighting pass
  589. lightingPass = new LightingRenderPass(resourceManager);
  590. lightingPass->setRenderTarget(&defaultRenderTarget);
  591. lightingPass->setShadowMapPass(shadowMapPass);
  592. lightingPass->setShadowMap(&shadowMapDepthTexture);
  593. // Setup clear silhouette pass
  594. clearSilhouettePass = new ClearRenderPass();
  595. clearSilhouettePass->setRenderTarget(&silhouetteRenderTarget);
  596. clearSilhouettePass->setClear(true, false, false);
  597. clearSilhouettePass->setClearColor(Vector4(0.0f));
  598. // Setup silhouette pass
  599. silhouettePass = new SilhouetteRenderPass(resourceManager);
  600. silhouettePass->setRenderTarget(&silhouetteRenderTarget);
  601. // Setup final pass
  602. finalPass = new FinalRenderPass(resourceManager);
  603. finalPass->setRenderTarget(&defaultRenderTarget);
  604. finalPass->setSilhouetteRenderTarget(&silhouetteRenderTarget);
  605. // Setup default compositor
  606. defaultCompositor.addPass(clearPass);
  607. defaultCompositor.addPass(skyPass);
  608. defaultCompositor.addPass(lightingPass);
  609. defaultCompositor.addPass(clearSilhouettePass);
  610. defaultCompositor.addPass(silhouettePass);
  611. //defaultCompositor.addPass(finalPass);
  612. defaultCompositor.load(nullptr);
  613. // Setup UI render pass
  614. uiPass = new UIRenderPass(resourceManager);
  615. uiPass->setRenderTarget(&defaultRenderTarget);
  616. // Setup UI compositor
  617. uiCompositor.addPass(uiPass);
  618. uiCompositor.load(nullptr);
  619. // Create scenes
  620. worldScene = new Scene(&stepInterpolator);
  621. uiScene = new Scene(&stepInterpolator);
  622. // Setup camera
  623. camera.setPerspective(glm::radians(40.0f), static_cast<float>(w) / static_cast<float>(h), 0.1, 100.0f);
  624. camera.lookAt(Vector3(0.0f, 4.0f, 2.0f), Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f));
  625. camera.setCompositor(&defaultCompositor);
  626. camera.setCompositeIndex(1);
  627. worldScene->addObject(&camera);
  628. // Setup sun
  629. sunlight.setDirection(Vector3(0, -1, 0));
  630. setTimeOfDay(11.0f);
  631. worldScene->addObject(&sunlight);
  632. // Setup sunlight camera
  633. sunlightCamera.setOrthographic(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f);
  634. sunlightCamera.setCompositor(&shadowMapCompositor);
  635. sunlightCamera.setCompositeIndex(0);
  636. sunlightCamera.setCullingEnabled(true);
  637. sunlightCamera.setCullingMask(&camera.getViewFrustum());
  638. worldScene->addObject(&sunlightCamera);
  639. }
  640. void Game::setupUI()
  641. {
  642. // Get DPI and convert font size to pixels
  643. const Display* display = deviceManager->getDisplays()->front();
  644. dpi = display->getDPI();
  645. fontSizePX = fontSizePT * (1.0f / 72.0f) * dpi;
  646. // Load label typeface
  647. labelTypeface = resourceManager->load<Typeface>("caveat-bold.ttf");
  648. labelFont = labelTypeface->createFont(fontSizePX);
  649. // Load debugging typeface
  650. debugTypeface = resourceManager->load<Typeface>("inconsolata-bold.ttf");
  651. debugFont = debugTypeface->createFont(fontSizePX);
  652. debugTypeface->loadCharset(debugFont, UnicodeRange::BASIC_LATIN);
  653. // Character set test
  654. std::set<char32_t> charset;
  655. charset.emplace(U'A');
  656. labelTypeface->loadCharset(labelFont, UnicodeRange::BASIC_LATIN);
  657. labelTypeface->loadCharset(labelFont, charset);
  658. // Load splash screen texture
  659. splashTexture = resourceManager->load<Texture2D>("epigraph.png");
  660. // Load HUD texture
  661. hudSpriteSheetTexture = resourceManager->load<Texture2D>("hud.png");
  662. // Read texture atlas file
  663. CSVTable* atlasTable = resourceManager->load<CSVTable>("hud-atlas.csv");
  664. // Build texture atlas
  665. for (int row = 0; row < atlasTable->size(); ++row)
  666. {
  667. std::stringstream ss;
  668. float x;
  669. float y;
  670. float w;
  671. float h;
  672. ss << (*atlasTable)[row][1];
  673. ss >> x;
  674. ss.str(std::string());
  675. ss.clear();
  676. ss << (*atlasTable)[row][2];
  677. ss >> y;
  678. ss.str(std::string());
  679. ss.clear();
  680. ss << (*atlasTable)[row][3];
  681. ss >> w;
  682. ss.str(std::string());
  683. ss.clear();
  684. ss << (*atlasTable)[row][4];
  685. ss >> h;
  686. ss.str(std::string());
  687. y = static_cast<float>(hudSpriteSheetTexture->getHeight()) - y - h;
  688. x = (int)(x + 0.5f);
  689. y = (int)(y + 0.5f);
  690. w = (int)(w + 0.5f);
  691. h = (int)(h + 0.5f);
  692. hudTextureAtlas.insert((*atlasTable)[row][0], Rect(Vector2(x, y), Vector2(x + w, y + h)));
  693. }
  694. // Setup UI batching
  695. uiBatch = new BillboardBatch();
  696. uiBatch->resize(1024);
  697. uiBatcher = new UIBatcher();
  698. // Setup root UI element
  699. uiRootElement = new UIContainer();
  700. eventDispatcher.subscribe<MouseMovedEvent>(uiRootElement);
  701. eventDispatcher.subscribe<MouseButtonPressedEvent>(uiRootElement);
  702. eventDispatcher.subscribe<MouseButtonReleasedEvent>(uiRootElement);
  703. // Create splash screen background element
  704. splashBackgroundImage = new UIImage();
  705. splashBackgroundImage->setLayerOffset(-1);
  706. splashBackgroundImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  707. splashBackgroundImage->setVisible(false);
  708. uiRootElement->addChild(splashBackgroundImage);
  709. // Create splash screen element
  710. splashImage = new UIImage();
  711. splashImage->setTexture(splashTexture);
  712. splashImage->setVisible(false);
  713. uiRootElement->addChild(splashImage);
  714. Rect hudTextureAtlasBounds(Vector2(0), Vector2(hudSpriteSheetTexture->getWidth(), hudSpriteSheetTexture->getHeight()));
  715. auto normalizeTextureBounds = [](const Rect& texture, const Rect& atlas)
  716. {
  717. Vector2 atlasDimensions = Vector2(atlas.getWidth(), atlas.getHeight());
  718. return Rect(texture.getMin() / atlasDimensions, texture.getMax() / atlasDimensions);
  719. };
  720. // Create HUD elements
  721. hudContainer = new UIContainer();
  722. hudContainer->setVisible(false);
  723. uiRootElement->addChild(hudContainer);
  724. toolIndicatorBGImage = new UIImage();
  725. toolIndicatorBGImage->setTexture(hudSpriteSheetTexture);
  726. toolIndicatorBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds));
  727. hudContainer->addChild(toolIndicatorBGImage);
  728. toolIndicatorsBounds = new Rect[8];
  729. toolIndicatorsBounds[0] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-brush"), hudTextureAtlasBounds);
  730. toolIndicatorsBounds[1] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-spade"), hudTextureAtlasBounds);
  731. toolIndicatorsBounds[2] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-lens"), hudTextureAtlasBounds);
  732. toolIndicatorsBounds[3] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-test-tube"), hudTextureAtlasBounds);
  733. toolIndicatorsBounds[4] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator-forceps"), hudTextureAtlasBounds);
  734. toolIndicatorsBounds[5] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  735. toolIndicatorsBounds[6] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  736. toolIndicatorsBounds[7] = normalizeTextureBounds(hudTextureAtlas.getBounds("tool-indicator"), hudTextureAtlasBounds);
  737. toolIndicatorIconImage = new UIImage();
  738. toolIndicatorIconImage->setTexture(hudSpriteSheetTexture);
  739. toolIndicatorIconImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  740. toolIndicatorBGImage->addChild(toolIndicatorIconImage);
  741. buttonContainer = new UIContainer();
  742. hudContainer->addChild(buttonContainer);
  743. playButtonBGImage = new UIImage();
  744. playButtonBGImage->setTexture(hudSpriteSheetTexture);
  745. playButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  746. //buttonContainer->addChild(playButtonBGImage);
  747. pauseButtonBGImage = new UIImage();
  748. pauseButtonBGImage->setTexture(hudSpriteSheetTexture);
  749. pauseButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  750. //buttonContainer->addChild(pauseButtonBGImage);
  751. fastForwardButtonBGImage = new UIImage();
  752. fastForwardButtonBGImage->setTexture(hudSpriteSheetTexture);
  753. fastForwardButtonBGImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-background"), hudTextureAtlasBounds));
  754. //buttonContainer->addChild(fastForwardButtonBGImage);
  755. playButtonImage = new UIImage();
  756. playButtonImage->setTexture(hudSpriteSheetTexture);
  757. playButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-play"), hudTextureAtlasBounds));
  758. //buttonContainer->addChild(playButtonImage);
  759. fastForwardButtonImage = new UIImage();
  760. fastForwardButtonImage->setTexture(hudSpriteSheetTexture);
  761. fastForwardButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-fast-forward-2x"), hudTextureAtlasBounds));
  762. //buttonContainer->addChild(fastForwardButtonImage);
  763. pauseButtonImage = new UIImage();
  764. pauseButtonImage->setTexture(hudSpriteSheetTexture);
  765. pauseButtonImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("button-pause"), hudTextureAtlasBounds));
  766. //buttonContainer->addChild(pauseButtonImage);
  767. radialMenuContainer = new UIContainer();
  768. radialMenuContainer->setVisible(false);
  769. uiRootElement->addChild(radialMenuContainer);
  770. radialMenuBackgroundImage = new UIImage();
  771. radialMenuBackgroundImage->setTintColor(Vector4(Vector3(0.0f), 0.25f));
  772. radialMenuContainer->addChild(radialMenuBackgroundImage);
  773. radialMenuImage = new UIImage();
  774. radialMenuImage->setTexture(hudSpriteSheetTexture);
  775. radialMenuImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu"), hudTextureAtlasBounds));
  776. radialMenuContainer->addChild(radialMenuImage);
  777. radialMenuSelectorImage = new UIImage();
  778. radialMenuSelectorImage->setTexture(hudSpriteSheetTexture);
  779. radialMenuSelectorImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("radial-menu-selector"), hudTextureAtlasBounds));
  780. radialMenuContainer->addChild(radialMenuSelectorImage);
  781. toolIconBrushImage = new UIImage();
  782. toolIconBrushImage->setTexture(hudSpriteSheetTexture);
  783. toolIconBrushImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-brush"), hudTextureAtlasBounds));
  784. radialMenuImage->addChild(toolIconBrushImage);
  785. toolIconLensImage = new UIImage();
  786. toolIconLensImage->setTexture(hudSpriteSheetTexture);
  787. toolIconLensImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-lens"), hudTextureAtlasBounds));
  788. radialMenuImage->addChild(toolIconLensImage);
  789. toolIconForcepsImage = new UIImage();
  790. toolIconForcepsImage->setTexture(hudSpriteSheetTexture);
  791. toolIconForcepsImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-forceps"), hudTextureAtlasBounds));
  792. radialMenuImage->addChild(toolIconForcepsImage);
  793. toolIconSpadeImage = new UIImage();
  794. toolIconSpadeImage->setTexture(hudSpriteSheetTexture);
  795. toolIconSpadeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-spade"), hudTextureAtlasBounds));
  796. //radialMenuImage->addChild(toolIconSpadeImage);
  797. toolIconCameraImage = new UIImage();
  798. toolIconCameraImage->setTexture(hudSpriteSheetTexture);
  799. toolIconCameraImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-camera"), hudTextureAtlasBounds));
  800. radialMenuImage->addChild(toolIconCameraImage);
  801. toolIconMicrochipImage = new UIImage();
  802. toolIconMicrochipImage->setTexture(hudSpriteSheetTexture);
  803. toolIconMicrochipImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-microchip"), hudTextureAtlasBounds));
  804. radialMenuImage->addChild(toolIconMicrochipImage);
  805. toolIconTestTubeImage = new UIImage();
  806. toolIconTestTubeImage->setTexture(hudSpriteSheetTexture);
  807. toolIconTestTubeImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("tool-icon-test-tube"), hudTextureAtlasBounds));
  808. //radialMenuImage->addChild(toolIconTestTubeImage);
  809. antTag = new UIContainer();
  810. antTag->setLayerOffset(-10);
  811. antTag->setVisible(false);
  812. uiRootElement->addChild(antTag);
  813. antLabelContainer = new UIContainer();
  814. antTag->addChild(antLabelContainer);
  815. antLabelTL = new UIImage();
  816. antLabelTR = new UIImage();
  817. antLabelBL = new UIImage();
  818. antLabelBR = new UIImage();
  819. antLabelCC = new UIImage();
  820. antLabelCT = new UIImage();
  821. antLabelCB = new UIImage();
  822. antLabelCL = new UIImage();
  823. antLabelCR = new UIImage();
  824. antLabelTL->setTexture(hudSpriteSheetTexture);
  825. antLabelTR->setTexture(hudSpriteSheetTexture);
  826. antLabelBL->setTexture(hudSpriteSheetTexture);
  827. antLabelBR->setTexture(hudSpriteSheetTexture);
  828. antLabelCC->setTexture(hudSpriteSheetTexture);
  829. antLabelCT->setTexture(hudSpriteSheetTexture);
  830. antLabelCB->setTexture(hudSpriteSheetTexture);
  831. antLabelCL->setTexture(hudSpriteSheetTexture);
  832. antLabelCR->setTexture(hudSpriteSheetTexture);
  833. Rect labelTLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tl"), hudTextureAtlasBounds);
  834. Rect labelTRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-tr"), hudTextureAtlasBounds);
  835. Rect labelBLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-bl"), hudTextureAtlasBounds);
  836. Rect labelBRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-br"), hudTextureAtlasBounds);
  837. Rect labelCCBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cc"), hudTextureAtlasBounds);
  838. Rect labelCTBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-ct"), hudTextureAtlasBounds);
  839. Rect labelCBBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cb"), hudTextureAtlasBounds);
  840. Rect labelCLBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cl"), hudTextureAtlasBounds);
  841. Rect labelCRBounds = normalizeTextureBounds(hudTextureAtlas.getBounds("label-cr"), hudTextureAtlasBounds);
  842. Vector2 labelTLMin = labelTLBounds.getMin();
  843. Vector2 labelTRMin = labelTRBounds.getMin();
  844. Vector2 labelBLMin = labelBLBounds.getMin();
  845. Vector2 labelBRMin = labelBRBounds.getMin();
  846. Vector2 labelCCMin = labelCCBounds.getMin();
  847. Vector2 labelCTMin = labelCTBounds.getMin();
  848. Vector2 labelCBMin = labelCBBounds.getMin();
  849. Vector2 labelCLMin = labelCLBounds.getMin();
  850. Vector2 labelCRMin = labelCRBounds.getMin();
  851. Vector2 labelTLMax = labelTLBounds.getMax();
  852. Vector2 labelTRMax = labelTRBounds.getMax();
  853. Vector2 labelBLMax = labelBLBounds.getMax();
  854. Vector2 labelBRMax = labelBRBounds.getMax();
  855. Vector2 labelCCMax = labelCCBounds.getMax();
  856. Vector2 labelCTMax = labelCTBounds.getMax();
  857. Vector2 labelCBMax = labelCBBounds.getMax();
  858. Vector2 labelCLMax = labelCLBounds.getMax();
  859. Vector2 labelCRMax = labelCRBounds.getMax();
  860. antLabelTL->setTextureBounds(labelTLBounds);
  861. antLabelTR->setTextureBounds(labelTRBounds);
  862. antLabelBL->setTextureBounds(labelBLBounds);
  863. antLabelBR->setTextureBounds(labelBRBounds);
  864. antLabelCC->setTextureBounds(labelCCBounds);
  865. antLabelCT->setTextureBounds(labelCTBounds);
  866. antLabelCB->setTextureBounds(labelCBBounds);
  867. antLabelCL->setTextureBounds(labelCLBounds);
  868. antLabelCR->setTextureBounds(labelCRBounds);
  869. antLabelContainer->addChild(antLabelTL);
  870. antLabelContainer->addChild(antLabelTR);
  871. antLabelContainer->addChild(antLabelBL);
  872. antLabelContainer->addChild(antLabelBR);
  873. antLabelContainer->addChild(antLabelCC);
  874. antLabelContainer->addChild(antLabelCT);
  875. antLabelContainer->addChild(antLabelCB);
  876. antLabelContainer->addChild(antLabelCL);
  877. antLabelContainer->addChild(antLabelCR);
  878. antLabel = new UILabel();
  879. antLabel->setFont(labelFont);
  880. antLabel->setText("Boggy B.");
  881. antLabel->setTintColor(Vector4(Vector3(0.0f), 1.0f));
  882. antLabel->setLayerOffset(1);
  883. antLabelContainer->addChild(antLabel);
  884. fpsLabel = new UILabel();
  885. fpsLabel->setFont(debugFont);
  886. fpsLabel->setTintColor(Vector4(1, 1, 0, 1));
  887. fpsLabel->setLayerOffset(50);
  888. fpsLabel->setAnchor(Anchor::TOP_LEFT);
  889. uiRootElement->addChild(fpsLabel);
  890. antPin = new UIImage();
  891. antPin->setTexture(hudSpriteSheetTexture);
  892. antPin->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin"), hudTextureAtlasBounds));
  893. antTag->addChild(antPin);
  894. antLabelPinHole = new UIImage();
  895. antLabelPinHole->setTexture(hudSpriteSheetTexture);
  896. antLabelPinHole->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("label-pin-hole"), hudTextureAtlasBounds));
  897. antLabelContainer->addChild(antLabelPinHole);
  898. // Construct box selection
  899. boxSelectionImageBackground = new UIImage();
  900. boxSelectionImageBackground->setAnchor(Anchor::CENTER);
  901. boxSelectionImageTop = new UIImage();
  902. boxSelectionImageTop->setAnchor(Anchor::TOP_LEFT);
  903. boxSelectionImageBottom = new UIImage();
  904. boxSelectionImageBottom->setAnchor(Anchor::BOTTOM_LEFT);
  905. boxSelectionImageLeft = new UIImage();
  906. boxSelectionImageLeft->setAnchor(Anchor::TOP_LEFT);
  907. boxSelectionImageRight = new UIImage();
  908. boxSelectionImageRight->setAnchor(Anchor::TOP_RIGHT);
  909. boxSelectionContainer = new UIContainer();
  910. boxSelectionContainer->setLayerOffset(80);
  911. boxSelectionContainer->addChild(boxSelectionImageBackground);
  912. boxSelectionContainer->addChild(boxSelectionImageTop);
  913. boxSelectionContainer->addChild(boxSelectionImageBottom);
  914. boxSelectionContainer->addChild(boxSelectionImageLeft);
  915. boxSelectionContainer->addChild(boxSelectionImageRight);
  916. boxSelectionContainer->setVisible(false);
  917. uiRootElement->addChild(boxSelectionContainer);
  918. boxSelectionImageBackground->setTintColor(Vector4(1.0f, 1.0f, 1.0f, 0.5f));
  919. boxSelectionContainer->setTintColor(Vector4(1.0f, 0.0f, 0.0f, 1.0f));
  920. boxSelectionBorderWidth = 2.0f;
  921. cameraGridColor = Vector4(1, 1, 1, 0.5f);
  922. cameraReticleColor = Vector4(1, 1, 1, 0.75f);
  923. cameraGridY0Image = new UIImage();
  924. cameraGridY0Image->setAnchor(Vector2(0.5f, (1.0f / 3.0f)));
  925. cameraGridY0Image->setTintColor(cameraGridColor);
  926. cameraGridY1Image = new UIImage();
  927. cameraGridY1Image->setAnchor(Vector2(0.5f, (2.0f / 3.0f)));
  928. cameraGridY1Image->setTintColor(cameraGridColor);
  929. cameraGridX0Image = new UIImage();
  930. cameraGridX0Image->setAnchor(Vector2((1.0f / 3.0f), 0.5f));
  931. cameraGridX0Image->setTintColor(cameraGridColor);
  932. cameraGridX1Image = new UIImage();
  933. cameraGridX1Image->setAnchor(Vector2((2.0f / 3.0f), 0.5f));
  934. cameraGridX1Image->setTintColor(cameraGridColor);
  935. cameraReticleImage = new UIImage();
  936. cameraReticleImage->setAnchor(Anchor::CENTER);
  937. cameraReticleImage->setTintColor(cameraReticleColor);
  938. cameraReticleImage->setTexture(hudSpriteSheetTexture);
  939. cameraReticleImage->setTextureBounds(normalizeTextureBounds(hudTextureAtlas.getBounds("camera-reticle"), hudTextureAtlasBounds));
  940. cameraGridContainer = new UIContainer();
  941. cameraGridContainer->addChild(cameraGridY0Image);
  942. cameraGridContainer->addChild(cameraGridY1Image);
  943. cameraGridContainer->addChild(cameraGridX0Image);
  944. cameraGridContainer->addChild(cameraGridX1Image);
  945. cameraGridContainer->addChild(cameraReticleImage);
  946. cameraGridContainer->setVisible(false);
  947. uiRootElement->addChild(cameraGridContainer);
  948. cameraFlashImage = new UIImage();
  949. cameraFlashImage->setLayerOffset(99);
  950. cameraFlashImage->setTintColor(Vector4(1.0f));
  951. cameraFlashImage->setVisible(false);
  952. uiRootElement->addChild(cameraFlashImage);
  953. blackoutImage = new UIImage();
  954. blackoutImage->setLayerOffset(98);
  955. blackoutImage->setTintColor(Vector4(0.0f, 0.0f, 0.0f, 1.0f));
  956. blackoutImage->setVisible(false);
  957. uiRootElement->addChild(blackoutImage);
  958. // Construct fade-in animation clip
  959. fadeInClip.setInterpolator(easeOutCubic<float>);
  960. AnimationChannel<float>* channel;
  961. channel = fadeInClip.addChannel(0);
  962. channel->insertKeyframe(0.0f, 1.0f);
  963. channel->insertKeyframe(1.0f, 0.0f);
  964. // Construct fade-out animation clip
  965. fadeOutClip.setInterpolator(easeOutCubic<float>);
  966. channel = fadeOutClip.addChannel(0);
  967. channel->insertKeyframe(0.0f, 0.0f);
  968. channel->insertKeyframe(1.0f, 1.0f);
  969. // Setup fade-in animation callbacks
  970. fadeInAnimation.setAnimateCallback
  971. (
  972. [this](std::size_t id, float opacity)
  973. {
  974. Vector3 color = Vector3(blackoutImage->getTintColor());
  975. blackoutImage->setTintColor(Vector4(color, opacity));
  976. }
  977. );
  978. fadeInAnimation.setEndCallback
  979. (
  980. [this]()
  981. {
  982. blackoutImage->setVisible(false);
  983. if (fadeInEndCallback != nullptr)
  984. {
  985. fadeInEndCallback();
  986. }
  987. }
  988. );
  989. // Setup fade-out animation callbacks
  990. fadeOutAnimation.setAnimateCallback
  991. (
  992. [this](std::size_t id, float opacity)
  993. {
  994. Vector3 color = Vector3(blackoutImage->getTintColor());
  995. blackoutImage->setTintColor(Vector4(color, opacity));
  996. }
  997. );
  998. fadeOutAnimation.setEndCallback
  999. (
  1000. [this]()
  1001. {
  1002. blackoutImage->setVisible(false);
  1003. if (fadeOutEndCallback != nullptr)
  1004. {
  1005. fadeOutEndCallback();
  1006. }
  1007. }
  1008. );
  1009. animator.addAnimation(&fadeInAnimation);
  1010. animator.addAnimation(&fadeOutAnimation);
  1011. // Construct camera flash animation clip
  1012. cameraFlashClip.setInterpolator(easeOutQuad<float>);
  1013. channel = cameraFlashClip.addChannel(0);
  1014. channel->insertKeyframe(0.0f, 1.0f);
  1015. channel->insertKeyframe(1.0f, 0.0f);
  1016. // Setup camera flash animation
  1017. float flashDuration = 0.5f;
  1018. cameraFlashAnimation.setSpeed(1.0f / flashDuration);
  1019. cameraFlashAnimation.setLoop(false);
  1020. cameraFlashAnimation.setClip(&cameraFlashClip);
  1021. cameraFlashAnimation.setTimeFrame(cameraFlashClip.getTimeFrame());
  1022. cameraFlashAnimation.setAnimateCallback
  1023. (
  1024. [this](std::size_t id, float opacity)
  1025. {
  1026. cameraFlashImage->setTintColor(Vector4(Vector3(1.0f), opacity));
  1027. }
  1028. );
  1029. cameraFlashAnimation.setStartCallback
  1030. (
  1031. [this]()
  1032. {
  1033. cameraFlashImage->setVisible(true);
  1034. cameraFlashImage->setTintColor(Vector4(1.0f));
  1035. cameraFlashImage->resetTweens();
  1036. }
  1037. );
  1038. cameraFlashAnimation.setEndCallback
  1039. (
  1040. [this]()
  1041. {
  1042. cameraFlashImage->setVisible(false);
  1043. }
  1044. );
  1045. animator.addAnimation(&cameraFlashAnimation);
  1046. // Setup UI scene
  1047. uiScene->addObject(uiBatch);
  1048. uiScene->addObject(&uiCamera);
  1049. // Setup UI camera
  1050. uiCamera.lookAt(Vector3(0), Vector3(0, 0, -1), Vector3(0, 1, 0));
  1051. uiCamera.resetTweens();
  1052. uiCamera.setCompositor(&uiCompositor);
  1053. uiCamera.setCompositeIndex(0);
  1054. uiCamera.setCullingEnabled(false);
  1055. restringUI();
  1056. resizeUI(w, h);
  1057. }
  1058. void Game::setupControls()
  1059. {
  1060. // Get keyboard and mouse
  1061. keyboard = deviceManager->getKeyboards()->front();
  1062. mouse = deviceManager->getMice()->front();
  1063. // Build the master control set
  1064. controls.addControl(&exitControl);
  1065. controls.addControl(&toggleFullscreenControl);
  1066. controls.addControl(&screenshotControl);
  1067. controls.addControl(&menuUpControl);
  1068. controls.addControl(&menuDownControl);
  1069. controls.addControl(&menuLeftControl);
  1070. controls.addControl(&menuRightControl);
  1071. controls.addControl(&menuBackControl);
  1072. controls.addControl(&moveForwardControl);
  1073. controls.addControl(&moveBackControl);
  1074. controls.addControl(&moveLeftControl);
  1075. controls.addControl(&moveRightControl);
  1076. controls.addControl(&zoomInControl);
  1077. controls.addControl(&zoomOutControl);
  1078. controls.addControl(&orbitCCWControl);
  1079. controls.addControl(&orbitCWControl);
  1080. controls.addControl(&adjustCameraControl);
  1081. controls.addControl(&dragCameraControl);
  1082. controls.addControl(&openToolMenuControl);
  1083. controls.addControl(&useToolControl);
  1084. controls.addControl(&toggleEditModeControl);
  1085. controls.addControl(&toggleWireframeControl);
  1086. // Build the system control set
  1087. systemControls.addControl(&exitControl);
  1088. systemControls.addControl(&toggleFullscreenControl);
  1089. systemControls.addControl(&screenshotControl);
  1090. // Build the menu control set
  1091. menuControls.addControl(&menuUpControl);
  1092. menuControls.addControl(&menuDownControl);
  1093. menuControls.addControl(&menuLeftControl);
  1094. menuControls.addControl(&menuRightControl);
  1095. menuControls.addControl(&menuSelectControl);
  1096. menuControls.addControl(&menuBackControl);
  1097. // Build the camera control set
  1098. cameraControls.addControl(&moveForwardControl);
  1099. cameraControls.addControl(&moveBackControl);
  1100. cameraControls.addControl(&moveLeftControl);
  1101. cameraControls.addControl(&moveRightControl);
  1102. cameraControls.addControl(&zoomInControl);
  1103. cameraControls.addControl(&zoomOutControl);
  1104. cameraControls.addControl(&orbitCCWControl);
  1105. cameraControls.addControl(&orbitCWControl);
  1106. cameraControls.addControl(&adjustCameraControl);
  1107. cameraControls.addControl(&dragCameraControl);
  1108. // Build the tool control set
  1109. toolControls.addControl(&openToolMenuControl);
  1110. toolControls.addControl(&useToolControl);
  1111. // Build the editor control set
  1112. editorControls.addControl(&toggleEditModeControl);
  1113. // Setup control callbacks
  1114. exitControl.setActivatedCallback(std::bind(&Application::close, this, EXIT_SUCCESS));
  1115. toggleFullscreenControl.setActivatedCallback(std::bind(&Game::toggleFullscreen, this));
  1116. screenshotControl.setActivatedCallback(std::bind(&Game::queueScreenshot, this));
  1117. toggleWireframeControl.setActivatedCallback(std::bind(&Game::toggleWireframe, this));
  1118. // Build map of control names
  1119. controlNameMap["exit"] = &exitControl;
  1120. controlNameMap["toggle-fullscreen"] = &toggleFullscreenControl;
  1121. controlNameMap["screenshot"] = &screenshotControl;
  1122. controlNameMap["menu-up"] = &menuUpControl;
  1123. controlNameMap["menu-down"] = &menuDownControl;
  1124. controlNameMap["menu-left"] = &menuLeftControl;
  1125. controlNameMap["menu-right"] = &menuRightControl;
  1126. controlNameMap["menu-back"] = &menuBackControl;
  1127. controlNameMap["move-forward"] = &moveForwardControl;
  1128. controlNameMap["move-back"] = &moveBackControl;
  1129. controlNameMap["move-left"] = &moveLeftControl;
  1130. controlNameMap["move-right"] = &moveRightControl;
  1131. controlNameMap["zoom-in"] = &zoomInControl;
  1132. controlNameMap["zoom-out"] = &zoomOutControl;
  1133. controlNameMap["orbit-ccw"] = &orbitCCWControl;
  1134. controlNameMap["orbit-cw"] = &orbitCWControl;
  1135. controlNameMap["adjust-camera"] = &adjustCameraControl;
  1136. controlNameMap["drag-camera"] = &dragCameraControl;
  1137. controlNameMap["open-tool-menu"] = &openToolMenuControl;
  1138. controlNameMap["use-tool"] = &useToolControl;
  1139. controlNameMap["toggle-edit-mode"] = &toggleEditModeControl;
  1140. controlNameMap["toggle-wireframe"] = &toggleWireframeControl;
  1141. // Load control profile
  1142. loadControlProfile();
  1143. // Setup input mapper
  1144. inputMapper = new InputMapper(&eventDispatcher);
  1145. inputMapper->setCallback(std::bind(&Game::mapInput, this, std::placeholders::_1));
  1146. inputMapper->setControl(nullptr);
  1147. inputMapper->setEnabled(false);
  1148. }
  1149. void Game::setupGameplay()
  1150. {
  1151. // Setup step scheduler
  1152. double maxFrameDuration = 0.25;
  1153. double stepFrequency = 60.0;
  1154. stepScheduler.setMaxFrameDuration(maxFrameDuration);
  1155. stepScheduler.setStepFrequency(stepFrequency);
  1156. timestep = stepScheduler.getStepPeriod();
  1157. // Setup camera rigs
  1158. cameraRig = nullptr;
  1159. orbitCam = new OrbitCam();
  1160. orbitCam->attachCamera(&camera);
  1161. freeCam = new FreeCam();
  1162. freeCam->attachCamera(&camera);
  1163. }
  1164. void Game::resetSettings()
  1165. {
  1166. // Set default language
  1167. language = "en-us";
  1168. // Set default resolutions
  1169. const Display* display = deviceManager->getDisplays()->front();
  1170. int displayWidth = std::get<0>(display->getDimensions());
  1171. int displayHeight = std::get<1>(display->getDimensions());
  1172. float windowedResolutionRatio = 5.0f / 6.0f;
  1173. windowedResolution = Vector2(displayWidth, displayHeight) * 5.0f / 6.0f;
  1174. windowedResolution.x = static_cast<int>(windowedResolution.x);
  1175. windowedResolution.y = static_cast<int>(windowedResolution.y);
  1176. fullscreenResolution = Vector2(displayWidth, displayHeight);
  1177. // Set default fullscreen mode
  1178. fullscreen = false;
  1179. // Set default vsync mode
  1180. vsync = true;
  1181. // Set default font size
  1182. fontSizePT = 14.0f;
  1183. // Set default control profile name
  1184. controlProfileName = "default-controls";
  1185. }
  1186. void Game::loadSettings()
  1187. {
  1188. // Reset settings to default values
  1189. resetSettings();
  1190. // Load settings table
  1191. try
  1192. {
  1193. settingsTable = resourceManager->load<CSVTable>("settings.csv");
  1194. }
  1195. catch (const std::exception& e)
  1196. {
  1197. settingsTable = new CSVTable();
  1198. }
  1199. // Build settings map
  1200. for (std::size_t i = 0; i < settingsTable->size(); ++i)
  1201. {
  1202. const CSVRow& row = (*settingsTable)[i];
  1203. settingsMap[row[0]] = i;
  1204. }
  1205. // Read settings from table
  1206. readSetting("language", &language);
  1207. readSetting("windowed-resolution", &windowedResolution);
  1208. readSetting("fullscreen-resolution", &fullscreenResolution);
  1209. readSetting("fullscreen", &fullscreen);
  1210. readSetting("vsync", &vsync);
  1211. readSetting("font-size", &fontSizePT);
  1212. readSetting("control-profile", &controlProfileName);
  1213. }
  1214. void Game::saveSettings()
  1215. {}
  1216. void Game::loadStrings()
  1217. {
  1218. // Read strings file
  1219. stringTable = resourceManager->load<CSVTable>("strings.csv");
  1220. // Build string map
  1221. for (int row = 0; row < stringTable->size(); ++row)
  1222. {
  1223. stringMap[(*stringTable)[row][0]] = row;
  1224. }
  1225. }
  1226. void Game::loadControlProfile()
  1227. {
  1228. // Load control profile
  1229. std::string controlProfilePath = controlProfileName + ".csv";
  1230. CSVTable* controlProfile = resourceManager->load<CSVTable>(controlProfilePath);
  1231. for (const CSVRow& row: *controlProfile)
  1232. {
  1233. // Skip empty rows and comments
  1234. if (row.empty() || row[0].empty() || row[0][0] == '#')
  1235. {
  1236. continue;
  1237. }
  1238. // Get control name
  1239. const std::string& controlName = row[0];
  1240. // Lookup control in control name map
  1241. auto it = controlNameMap.find(controlName);
  1242. if (it == controlNameMap.end())
  1243. {
  1244. std::cerr << "Game::loadControlProfile(): Unknown control name \"" << controlName << "\"" << std::endl;
  1245. continue;
  1246. }
  1247. // Get pointer to the control
  1248. Control* control = it->second;
  1249. // Determine type of input mapping
  1250. const std::string& deviceType = row[1];
  1251. if (deviceType == "keyboard")
  1252. {
  1253. const std::string& eventType = row[2];
  1254. const std::string& scancodeName = row[3];
  1255. // Get scancode from string
  1256. Scancode scancode = Keyboard::getScancodeFromName(scancodeName.c_str());
  1257. // Map control
  1258. if (scancode != Scancode::UNKNOWN)
  1259. {
  1260. inputRouter->addMapping(KeyMapping(control, keyboard, scancode));
  1261. }
  1262. }
  1263. else if (deviceType == "mouse")
  1264. {
  1265. const std::string& eventType = row[2];
  1266. if (eventType == "motion")
  1267. {
  1268. const std::string& axisName = row[3];
  1269. // Get axis from string
  1270. MouseMotionAxis axis;
  1271. bool negative = (axisName.find('-') != std::string::npos);
  1272. if (axisName.find('x') != std::string::npos)
  1273. {
  1274. axis = (negative) ? MouseMotionAxis::NEGATIVE_X : MouseMotionAxis::POSITIVE_X;
  1275. }
  1276. else if (axisName.find('y') != std::string::npos)
  1277. {
  1278. axis = (negative) ? MouseMotionAxis::NEGATIVE_Y : MouseMotionAxis::POSITIVE_Y;
  1279. }
  1280. else
  1281. {
  1282. std::cerr << "Game::loadControlProfile(): Unknown mouse motion axis \"" << axisName << "\"" << std::endl;
  1283. continue;
  1284. }
  1285. // Map control
  1286. inputRouter->addMapping(MouseMotionMapping(control, mouse, axis));
  1287. }
  1288. else if (eventType == "wheel")
  1289. {
  1290. const std::string& axisName = row[3];
  1291. // Get axis from string
  1292. MouseWheelAxis axis;
  1293. bool negative = (axisName.find('-') != std::string::npos);
  1294. if (axisName.find('x') != std::string::npos)
  1295. {
  1296. axis = (negative) ? MouseWheelAxis::NEGATIVE_X : MouseWheelAxis::POSITIVE_X;
  1297. }
  1298. else if (axisName.find('y') != std::string::npos)
  1299. {
  1300. axis = (negative) ? MouseWheelAxis::NEGATIVE_Y : MouseWheelAxis::POSITIVE_Y;
  1301. }
  1302. else
  1303. {
  1304. std::cerr << "Game::loadControlProfile(): Unknown mouse wheel axis \"" << axisName << "\"" << std::endl;
  1305. continue;
  1306. }
  1307. // Map control
  1308. inputRouter->addMapping(MouseWheelMapping(control, mouse, axis));
  1309. }
  1310. else if (eventType == "button")
  1311. {
  1312. const std::string& buttonName = row[3];
  1313. // Get button from string
  1314. int button;
  1315. std::stringstream stream;
  1316. stream << buttonName;
  1317. stream >> button;
  1318. // Map control
  1319. inputRouter->addMapping(MouseButtonMapping(control, mouse, button));
  1320. }
  1321. else
  1322. {
  1323. std::cerr << "Game::loadControlProfile(): Unknown mouse event type \"" << eventType << "\"" << std::endl;
  1324. continue;
  1325. }
  1326. }
  1327. else if (deviceType == "gamepad")
  1328. {
  1329. const std::string& eventType = row[2];
  1330. if (eventType == "axis")
  1331. {
  1332. std::string axisName = row[3];
  1333. // Determine whether axis is negative or positive
  1334. bool negative = (axisName.find('-') != std::string::npos);
  1335. // Remove sign from axis name
  1336. std::size_t plusPosition = axisName.find('+');
  1337. std::size_t minusPosition = axisName.find('-');
  1338. if (plusPosition != std::string::npos)
  1339. {
  1340. axisName.erase(plusPosition);
  1341. }
  1342. else if (minusPosition != std::string::npos)
  1343. {
  1344. axisName.erase(minusPosition);
  1345. }
  1346. // Get axis from string
  1347. int axis;
  1348. std::stringstream stream;
  1349. stream << axisName;
  1350. stream >> axis;
  1351. // Map control to each gamepad
  1352. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  1353. for (Gamepad* gamepad: *gamepads)
  1354. {
  1355. inputRouter->addMapping(GamepadAxisMapping(control, gamepad, axis, negative));
  1356. }
  1357. }
  1358. else if (eventType == "button")
  1359. {
  1360. const std::string& buttonName = row[3];
  1361. // Get button from string
  1362. int button;
  1363. std::stringstream stream;
  1364. stream << buttonName;
  1365. stream >> button;
  1366. // Map control to each gamepad
  1367. const std::list<Gamepad*>* gamepads = deviceManager->getGamepads();
  1368. for (Gamepad* gamepad: *gamepads)
  1369. {
  1370. inputRouter->addMapping(GamepadButtonMapping(control, gamepad, button));
  1371. }
  1372. }
  1373. else
  1374. {
  1375. std::cerr << "Game::loadControlProfile(): Unknown gamepad event type \"" << eventType << "\"" << std::endl;
  1376. continue;
  1377. }
  1378. }
  1379. else
  1380. {
  1381. std::cerr << "Game::loadControlProfile(): Unknown input device type \"" << deviceType << "\"" << std::endl;
  1382. continue;
  1383. }
  1384. }
  1385. }
  1386. void Game::saveControlProfile()
  1387. {
  1388. // Build control profile CSV table
  1389. CSVTable* table = new CSVTable();
  1390. for (auto it = controlNameMap.begin(); it != controlNameMap.end(); ++it)
  1391. {
  1392. // Get control name
  1393. const std::string& controlName = it->first;
  1394. // Get pointer to the control
  1395. Control* control = it->second;
  1396. // Look up list of mappings for the control
  1397. const std::list<InputMapping*>* mappings = inputRouter->getMappings(control);
  1398. if (!mappings)
  1399. {
  1400. continue;
  1401. }
  1402. // For each input mapping
  1403. for (const InputMapping* mapping: *mappings)
  1404. {
  1405. // Add row to the table
  1406. table->push_back(CSVRow());
  1407. CSVRow* row = &table->back();
  1408. // Add control name column
  1409. row->push_back(controlName);
  1410. switch (mapping->getType())
  1411. {
  1412. case InputMappingType::KEY:
  1413. {
  1414. const KeyMapping* keyMapping = static_cast<const KeyMapping*>(mapping);
  1415. row->push_back("keyboard");
  1416. row->push_back("key");
  1417. std::string scancodeName = std::string("\"") + std::string(Keyboard::getScancodeName(keyMapping->scancode)) + std::string("\"");
  1418. row->push_back(scancodeName);
  1419. break;
  1420. }
  1421. case InputMappingType::MOUSE_MOTION:
  1422. {
  1423. const MouseMotionMapping* mouseMotionMapping = static_cast<const MouseMotionMapping*>(mapping);
  1424. row->push_back("mouse");
  1425. row->push_back("motion");
  1426. std::string axisName;
  1427. if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_X)
  1428. {
  1429. axisName = "+x";
  1430. }
  1431. else if (mouseMotionMapping->axis == MouseMotionAxis::NEGATIVE_X)
  1432. {
  1433. axisName = "-x";
  1434. }
  1435. else if (mouseMotionMapping->axis == MouseMotionAxis::POSITIVE_Y)
  1436. {
  1437. axisName = "+y";
  1438. }
  1439. else
  1440. {
  1441. axisName = "-y";
  1442. }
  1443. row->push_back(axisName);
  1444. break;
  1445. }
  1446. case InputMappingType::MOUSE_WHEEL:
  1447. {
  1448. const MouseWheelMapping* mouseWheelMapping = static_cast<const MouseWheelMapping*>(mapping);
  1449. row->push_back("mouse");
  1450. row->push_back("wheel");
  1451. std::string axisName;
  1452. if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_X)
  1453. {
  1454. axisName = "+x";
  1455. }
  1456. else if (mouseWheelMapping->axis == MouseWheelAxis::NEGATIVE_X)
  1457. {
  1458. axisName = "-x";
  1459. }
  1460. else if (mouseWheelMapping->axis == MouseWheelAxis::POSITIVE_Y)
  1461. {
  1462. axisName = "+y";
  1463. }
  1464. else
  1465. {
  1466. axisName = "-y";
  1467. }
  1468. row->push_back(axisName);
  1469. break;
  1470. }
  1471. case InputMappingType::MOUSE_BUTTON:
  1472. {
  1473. const MouseButtonMapping* mouseButtonMapping = static_cast<const MouseButtonMapping*>(mapping);
  1474. row->push_back("mouse");
  1475. row->push_back("button");
  1476. std::string buttonName;
  1477. std::stringstream stream;
  1478. stream << static_cast<int>(mouseButtonMapping->button);
  1479. stream >> buttonName;
  1480. row->push_back(buttonName);
  1481. break;
  1482. }
  1483. case InputMappingType::GAMEPAD_AXIS:
  1484. {
  1485. const GamepadAxisMapping* gamepadAxisMapping = static_cast<const GamepadAxisMapping*>(mapping);
  1486. row->push_back("gamepad");
  1487. row->push_back("axis");
  1488. std::stringstream stream;
  1489. if (gamepadAxisMapping->negative)
  1490. {
  1491. stream << "-";
  1492. }
  1493. else
  1494. {
  1495. stream << "+";
  1496. }
  1497. stream << gamepadAxisMapping->axis;
  1498. std::string axisName;
  1499. stream >> axisName;
  1500. row->push_back(axisName);
  1501. break;
  1502. }
  1503. case InputMappingType::GAMEPAD_BUTTON:
  1504. {
  1505. const GamepadButtonMapping* gamepadButtonMapping = static_cast<const GamepadButtonMapping*>(mapping);
  1506. row->push_back("gamepad");
  1507. row->push_back("button");
  1508. std::string buttonName;
  1509. std::stringstream stream;
  1510. stream << static_cast<int>(gamepadButtonMapping->button);
  1511. stream >> buttonName;
  1512. row->push_back(buttonName);
  1513. break;
  1514. }
  1515. default:
  1516. break;
  1517. }
  1518. }
  1519. }
  1520. // Form full path to control profile file
  1521. std::string controlProfilePath = controlsPath + controlProfileName + ".csv";
  1522. // Save control profile
  1523. resourceManager->save<CSVTable>(table, controlProfilePath);
  1524. // Free control profile CSV table
  1525. delete table;
  1526. }
  1527. void Game::resizeUI(int w, int h)
  1528. {
  1529. // Adjust root element dimensions
  1530. uiRootElement->setDimensions(Vector2(w, h));
  1531. uiRootElement->update();
  1532. splashBackgroundImage->setDimensions(Vector2(w, h));
  1533. splashBackgroundImage->setAnchor(Anchor::TOP_LEFT);
  1534. // Resize splash screen image
  1535. splashImage->setAnchor(Anchor::CENTER);
  1536. splashImage->setDimensions(Vector2(splashTexture->getWidth(), splashTexture->getHeight()));
  1537. // Adjust UI camera projection matrix
  1538. uiCamera.setOrthographic(0.0f, w, h, 0.0f, -1.0f, 1.0f);
  1539. uiCamera.resetTweens();
  1540. // Resize camera flash image
  1541. cameraFlashImage->setDimensions(Vector2(w, h));
  1542. cameraFlashImage->setAnchor(Anchor::CENTER);
  1543. // Resize blackout image
  1544. blackoutImage->setDimensions(Vector2(w, h));
  1545. blackoutImage->setAnchor(Anchor::CENTER);
  1546. // Resize HUD
  1547. float hudPadding = 20.0f;
  1548. hudContainer->setDimensions(Vector2(w - hudPadding * 2.0f, h - hudPadding * 2.0f));
  1549. hudContainer->setAnchor(Anchor::CENTER);
  1550. // Tool indicator
  1551. Rect toolIndicatorBounds = hudTextureAtlas.getBounds("tool-indicator");
  1552. toolIndicatorBGImage->setDimensions(Vector2(toolIndicatorBounds.getWidth(), toolIndicatorBounds.getHeight()));
  1553. toolIndicatorBGImage->setAnchor(Anchor::TOP_LEFT);
  1554. Rect toolIndicatorIconBounds = hudTextureAtlas.getBounds("tool-indicator-lens");
  1555. toolIndicatorIconImage->setDimensions(Vector2(toolIndicatorIconBounds.getWidth(), toolIndicatorIconBounds.getHeight()));
  1556. toolIndicatorIconImage->setAnchor(Anchor::CENTER);
  1557. // Buttons
  1558. Rect playButtonBounds = hudTextureAtlas.getBounds("button-play");
  1559. Rect fastForwardButtonBounds = hudTextureAtlas.getBounds("button-fast-forward-2x");
  1560. Rect pauseButtonBounds = hudTextureAtlas.getBounds("button-pause");
  1561. Rect buttonBackgroundBounds = hudTextureAtlas.getBounds("button-background");
  1562. Vector2 buttonBGDimensions = Vector2(buttonBackgroundBounds.getWidth(), buttonBackgroundBounds.getHeight());
  1563. float buttonMargin = 10.0f;
  1564. float buttonDepth = 15.0f;
  1565. float buttonContainerWidth = fastForwardButtonBounds.getWidth();
  1566. float buttonContainerHeight = fastForwardButtonBounds.getHeight();
  1567. buttonContainer->setDimensions(Vector2(buttonContainerWidth, buttonContainerHeight));
  1568. buttonContainer->setAnchor(Anchor::TOP_RIGHT);
  1569. playButtonImage->setDimensions(Vector2(playButtonBounds.getWidth(), playButtonBounds.getHeight()));
  1570. playButtonImage->setAnchor(Vector2(0.0f, 0.0f));
  1571. playButtonBGImage->setDimensions(buttonBGDimensions);
  1572. playButtonBGImage->setAnchor(Vector2(0.0f, 1.0f));
  1573. fastForwardButtonImage->setDimensions(Vector2(fastForwardButtonBounds.getWidth(), fastForwardButtonBounds.getHeight()));
  1574. fastForwardButtonImage->setAnchor(Vector2(0.5f, 5.0f));
  1575. fastForwardButtonBGImage->setDimensions(buttonBGDimensions);
  1576. fastForwardButtonBGImage->setAnchor(Vector2(0.5f, 0.5f));
  1577. pauseButtonImage->setDimensions(Vector2(pauseButtonBounds.getWidth(), pauseButtonBounds.getHeight()));
  1578. pauseButtonImage->setAnchor(Vector2(1.0f, 0.0f));
  1579. pauseButtonBGImage->setDimensions(buttonBGDimensions);
  1580. pauseButtonBGImage->setAnchor(Vector2(1.0f, 1.0f));
  1581. // Radial menu
  1582. Rect radialMenuBounds = hudTextureAtlas.getBounds("radial-menu");
  1583. radialMenuContainer->setDimensions(Vector2(w, h));
  1584. radialMenuContainer->setAnchor(Anchor::CENTER);
  1585. radialMenuContainer->setLayerOffset(30);
  1586. radialMenuBackgroundImage->setDimensions(Vector2(w, h));
  1587. radialMenuBackgroundImage->setAnchor(Anchor::CENTER);
  1588. radialMenuBackgroundImage->setLayerOffset(-1);
  1589. //radialMenuImage->setDimensions(Vector2(w * 0.5f, h * 0.5f));
  1590. radialMenuImage->setDimensions(Vector2(radialMenuBounds.getWidth(), radialMenuBounds.getHeight()));
  1591. radialMenuImage->setAnchor(Anchor::CENTER);
  1592. Rect radialMenuSelectorBounds = hudTextureAtlas.getBounds("radial-menu-selector");
  1593. radialMenuSelectorImage->setDimensions(Vector2(radialMenuSelectorBounds.getWidth(), radialMenuSelectorBounds.getHeight()));
  1594. radialMenuSelectorImage->setAnchor(Anchor::CENTER);
  1595. Rect toolIconBrushBounds = hudTextureAtlas.getBounds("tool-icon-brush");
  1596. toolIconBrushImage->setDimensions(Vector2(toolIconBrushBounds.getWidth(), toolIconBrushBounds.getHeight()));
  1597. toolIconBrushImage->setAnchor(Anchor::CENTER);
  1598. Rect toolIconLensBounds = hudTextureAtlas.getBounds("tool-icon-lens");
  1599. toolIconLensImage->setDimensions(Vector2(toolIconLensBounds.getWidth(), toolIconLensBounds.getHeight()));
  1600. toolIconLensImage->setAnchor(Anchor::CENTER);
  1601. Rect toolIconForcepsBounds = hudTextureAtlas.getBounds("tool-icon-forceps");
  1602. toolIconForcepsImage->setDimensions(Vector2(toolIconForcepsBounds.getWidth(), toolIconForcepsBounds.getHeight()));
  1603. toolIconForcepsImage->setAnchor(Anchor::CENTER);
  1604. Rect toolIconSpadeBounds = hudTextureAtlas.getBounds("tool-icon-spade");
  1605. toolIconSpadeImage->setDimensions(Vector2(toolIconSpadeBounds.getWidth(), toolIconSpadeBounds.getHeight()));
  1606. toolIconSpadeImage->setAnchor(Anchor::CENTER);
  1607. Rect toolIconCameraBounds = hudTextureAtlas.getBounds("tool-icon-camera");
  1608. toolIconCameraImage->setDimensions(Vector2(toolIconCameraBounds.getWidth(), toolIconCameraBounds.getHeight()));
  1609. toolIconCameraImage->setAnchor(Anchor::CENTER);
  1610. Rect toolIconMicrochipBounds = hudTextureAtlas.getBounds("tool-icon-microchip");
  1611. toolIconMicrochipImage->setDimensions(Vector2(toolIconMicrochipBounds.getWidth(), toolIconMicrochipBounds.getHeight()));
  1612. toolIconMicrochipImage->setAnchor(Anchor::CENTER);
  1613. Rect toolIconTestTubeBounds = hudTextureAtlas.getBounds("tool-icon-test-tube");
  1614. toolIconTestTubeImage->setDimensions(Vector2(toolIconTestTubeBounds.getWidth(), toolIconTestTubeBounds.getHeight()));
  1615. toolIconTestTubeImage->setAnchor(Anchor::CENTER);
  1616. Rect labelCornerBounds = hudTextureAtlas.getBounds("label-tl");
  1617. Vector2 labelCornerDimensions(labelCornerBounds.getWidth(), labelCornerBounds.getHeight());
  1618. Vector2 antLabelPadding(10.0f, 6.0f);
  1619. antLabelContainer->setDimensions(antLabel->getDimensions() + antLabelPadding * 2.0f);
  1620. antLabelContainer->setTranslation(Vector2(0.0f, (int)(-antPin->getDimensions().y * 0.125f)));
  1621. antLabelTL->setDimensions(labelCornerDimensions);
  1622. antLabelTR->setDimensions(labelCornerDimensions);
  1623. antLabelBL->setDimensions(labelCornerDimensions);
  1624. antLabelBR->setDimensions(labelCornerDimensions);
  1625. 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));
  1626. antLabelCT->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  1627. antLabelCB->setDimensions(Vector2(antLabel->getDimensions().x - labelCornerDimensions.x * 2.0f + antLabelPadding.x * 2.0f, labelCornerDimensions.y));
  1628. antLabelCL->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  1629. antLabelCR->setDimensions(Vector2(labelCornerDimensions.x, antLabel->getDimensions().y - labelCornerDimensions.y * 2.0f + antLabelPadding.y * 2.0f));
  1630. antLabelContainer->setAnchor(Vector2(0.5f, 0.5f));
  1631. antLabelTL->setAnchor(Anchor::TOP_LEFT);
  1632. antLabelTR->setAnchor(Anchor::TOP_RIGHT);
  1633. antLabelBL->setAnchor(Anchor::BOTTOM_LEFT);
  1634. antLabelBR->setAnchor(Anchor::BOTTOM_RIGHT);
  1635. antLabelCC->setAnchor(Anchor::CENTER);
  1636. antLabelCT->setAnchor(Vector2(0.5f, 0.0f));
  1637. antLabelCB->setAnchor(Vector2(0.5f, 1.0f));
  1638. antLabelCL->setAnchor(Vector2(0.0f, 0.5f));
  1639. antLabelCR->setAnchor(Vector2(1.0f, 0.5f));
  1640. antLabel->setAnchor(Anchor::CENTER);
  1641. Rect antPinBounds = hudTextureAtlas.getBounds("label-pin");
  1642. antPin->setDimensions(Vector2(antPinBounds.getWidth(), antPinBounds.getHeight()));
  1643. antPin->setAnchor(Vector2(0.5f, 1.0f));
  1644. Rect pinHoleBounds = hudTextureAtlas.getBounds("label-pin-hole");
  1645. antLabelPinHole->setDimensions(Vector2(pinHoleBounds.getWidth(), pinHoleBounds.getHeight()));
  1646. antLabelPinHole->setAnchor(Vector2(0.5f, 0.0f));
  1647. antLabelPinHole->setTranslation(Vector2(0.0f, -antLabelPinHole->getDimensions().y * 0.5f));
  1648. antLabelPinHole->setLayerOffset(2);
  1649. float pinDistance = 20.0f;
  1650. antTag->setAnchor(Anchor::CENTER);
  1651. antTag->setDimensions(Vector2(antLabelContainer->getDimensions().x, antPin->getDimensions().y));
  1652. float cameraGridLineWidth = 2.0f;
  1653. float cameraReticleDiameter = 6.0f;
  1654. cameraGridContainer->setDimensions(Vector2(w, h));
  1655. cameraGridY0Image->setDimensions(Vector2(w, cameraGridLineWidth));
  1656. cameraGridY1Image->setDimensions(Vector2(w, cameraGridLineWidth));
  1657. cameraGridX0Image->setDimensions(Vector2(cameraGridLineWidth, h));
  1658. cameraGridX1Image->setDimensions(Vector2(cameraGridLineWidth, h));
  1659. cameraReticleImage->setDimensions(Vector2(cameraReticleDiameter));
  1660. cameraGridY0Image->setTranslation(Vector2(0));
  1661. cameraGridY1Image->setTranslation(Vector2(0));
  1662. cameraGridX0Image->setTranslation(Vector2(0));
  1663. cameraGridX1Image->setTranslation(Vector2(0));
  1664. cameraReticleImage->setTranslation(Vector2(0));
  1665. UIImage* icons[] =
  1666. {
  1667. toolIconBrushImage,
  1668. nullptr,
  1669. toolIconLensImage,
  1670. nullptr,
  1671. toolIconForcepsImage,
  1672. toolIconMicrochipImage,
  1673. toolIconCameraImage,
  1674. nullptr
  1675. };
  1676. Rect radialMenuIconRingBounds = hudTextureAtlas.getBounds("radial-menu-icon-ring");
  1677. float iconOffset = radialMenuIconRingBounds.getWidth() * 0.5f;
  1678. float sectorAngle = (2.0f * 3.14159264f) / 8.0f;
  1679. for (int i = 0; i < 8; ++i)
  1680. {
  1681. float angle = sectorAngle * static_cast<float>(i - 4);
  1682. Vector2 translation = Vector2(std::cos(angle), std::sin(angle)) * iconOffset;
  1683. translation.x = (int)(translation.x + 0.5f);
  1684. translation.y = (int)(translation.y + 0.5f);
  1685. if (icons[i] != nullptr)
  1686. {
  1687. icons[i]->setTranslation(translation);
  1688. }
  1689. }
  1690. }
  1691. void Game::restringUI()
  1692. {
  1693. }
  1694. void Game::setTimeOfDay(float time)
  1695. {
  1696. Vector3 midnight = Vector3(0.0f, 1.0f, 0.0f);
  1697. Vector3 sunrise = Vector3(-1.0f, 0.0f, 0.0f);
  1698. Vector3 noon = Vector3(0, -1.0f, 0.0f);
  1699. Vector3 sunset = Vector3(1.0f, 0.0f, 0.0f);
  1700. float angles[4] =
  1701. {
  1702. glm::radians(270.0f), // 00:00
  1703. glm::radians(0.0f), // 06:00
  1704. glm::radians(90.0f), // 12:00
  1705. glm::radians(180.0f) // 18:00
  1706. };
  1707. int index0 = static_cast<int>(fmod(time, 24.0f) / 6.0f);
  1708. int index1 = (index0 + 1) % 4;
  1709. float t = (time - (static_cast<float>(index0) * 6.0f)) / 6.0f;
  1710. Quaternion rotation0 = glm::angleAxis(angles[index0], Vector3(1, 0, 0));
  1711. Quaternion rotation1 = glm::angleAxis(angles[index1], Vector3(1, 0, 0));
  1712. Quaternion rotation = glm::normalize(glm::slerp(rotation0, rotation1, t));
  1713. Vector3 direction = glm::normalize(rotation * Vector3(0, 0, 1));
  1714. sunlight.setDirection(direction);
  1715. Vector3 up = glm::normalize(rotation * Vector3(0, 1, 0));
  1716. sunlightCamera.lookAt(Vector3(0, 0, 0), sunlight.getDirection(), up);
  1717. }
  1718. void Game::toggleWireframe()
  1719. {
  1720. wireframe = !wireframe;
  1721. float width = (wireframe) ? 1.0f : 0.0f;
  1722. lightingPass->setWireframeLineWidth(width);
  1723. }
  1724. void Game::queueScreenshot()
  1725. {
  1726. screenshotQueued = true;
  1727. cameraFlashImage->setVisible(false);
  1728. cameraGridContainer->setVisible(false);
  1729. fpsLabel->setVisible(false);
  1730. soundSystem->scrot();
  1731. }
  1732. void Game::screenshot()
  1733. {
  1734. screenshotQueued = false;
  1735. // Read pixel data from framebuffer
  1736. unsigned char* pixels = new unsigned char[w * h * 3];
  1737. glReadBuffer(GL_BACK);
  1738. glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pixels);
  1739. // Get game title in current language
  1740. std::string title = getString(getLanguageIndex(), "title");
  1741. // Convert title to lowercase
  1742. std::transform(title.begin(), title.end(), title.begin(), ::tolower);
  1743. // Create screenshot directory if it doesn't exist
  1744. std::string screenshotDirectory = configPath + std::string("screenshots/");
  1745. if (!pathExists(screenshotDirectory))
  1746. {
  1747. createDirectory(screenshotDirectory);
  1748. }
  1749. // Build screenshot file name
  1750. std::string filename = screenshotDirectory + title + "-" + timestamp() + ".png";
  1751. // Write screenshot to file in separate thread
  1752. std::thread screenshotThread(Game::saveScreenshot, filename, w, h, pixels);
  1753. screenshotThread.detach();
  1754. // Play camera flash animation
  1755. cameraFlashAnimation.stop();
  1756. cameraFlashAnimation.rewind();
  1757. cameraFlashAnimation.play();
  1758. // Play camera shutter sound
  1759. // Restore camera UI visibility
  1760. //cameraGridContainer->setVisible(true);
  1761. fpsLabel->setVisible(true);
  1762. // Whiteout screen immediately
  1763. glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
  1764. glClear(GL_COLOR_BUFFER_BIT);
  1765. }
  1766. void Game::mapInput(const InputMapping& mapping)
  1767. {
  1768. // Skip mouse motion events
  1769. if (mapping.getType() == InputMappingType::MOUSE_MOTION)
  1770. {
  1771. return;
  1772. }
  1773. // Add input mapping to input router
  1774. if (mapping.control != nullptr)
  1775. {
  1776. inputRouter->addMapping(mapping);
  1777. }
  1778. // Disable input mapping generation
  1779. inputMapper->setControl(nullptr);
  1780. inputMapper->setEnabled(false);
  1781. }
  1782. void Game::boxSelect(float x, float y, float w, float h)
  1783. {
  1784. boxSelectionContainer->setTranslation(Vector2(x, y));
  1785. boxSelectionContainer->setDimensions(Vector2(w, h));
  1786. boxSelectionImageBackground->setDimensions(Vector2(w, h));
  1787. boxSelectionImageTop->setDimensions(Vector2(w, boxSelectionBorderWidth));
  1788. boxSelectionImageBottom->setDimensions(Vector2(w, boxSelectionBorderWidth));
  1789. boxSelectionImageLeft->setDimensions(Vector2(boxSelectionBorderWidth, h));
  1790. boxSelectionImageRight->setDimensions(Vector2(boxSelectionBorderWidth, h));
  1791. boxSelectionContainer->setVisible(true);
  1792. }
  1793. void Game::fadeIn(float duration, const Vector3& color, std::function<void()> callback)
  1794. {
  1795. if (fadeInAnimation.isPlaying())
  1796. {
  1797. return;
  1798. }
  1799. fadeOutAnimation.stop();
  1800. this->fadeInEndCallback = callback;
  1801. blackoutImage->setTintColor(Vector4(color, 1.0f));
  1802. blackoutImage->setVisible(true);
  1803. fadeInAnimation.setSpeed(1.0f / duration);
  1804. fadeInAnimation.setLoop(false);
  1805. fadeInAnimation.setClip(&fadeInClip);
  1806. fadeInAnimation.setTimeFrame(fadeInClip.getTimeFrame());
  1807. fadeInAnimation.rewind();
  1808. fadeInAnimation.play();
  1809. blackoutImage->resetTweens();
  1810. uiRootElement->update();
  1811. }
  1812. void Game::fadeOut(float duration, const Vector3& color, std::function<void()> callback)
  1813. {
  1814. if (fadeOutAnimation.isPlaying())
  1815. {
  1816. return;
  1817. }
  1818. fadeInAnimation.stop();
  1819. this->fadeOutEndCallback = callback;
  1820. blackoutImage->setVisible(true);
  1821. blackoutImage->setTintColor(Vector4(color, 0.0f));
  1822. fadeOutAnimation.setSpeed(1.0f / duration);
  1823. fadeOutAnimation.setLoop(false);
  1824. fadeOutAnimation.setClip(&fadeOutClip);
  1825. fadeOutAnimation.setTimeFrame(fadeOutClip.getTimeFrame());
  1826. fadeOutAnimation.rewind();
  1827. fadeOutAnimation.play();
  1828. blackoutImage->resetTweens();
  1829. uiRootElement->update();
  1830. }
  1831. void Game::selectTool(int toolIndex)
  1832. {
  1833. Tool* tools[] =
  1834. {
  1835. brush,
  1836. nullptr,
  1837. lens,
  1838. nullptr,
  1839. forceps,
  1840. nullptr,
  1841. nullptr,
  1842. nullptr
  1843. };
  1844. Tool* nextTool = tools[toolIndex];
  1845. if (nextTool != currentTool)
  1846. {
  1847. if (currentTool)
  1848. {
  1849. currentTool->setActive(false);
  1850. currentTool->update(0.0f);
  1851. }
  1852. currentTool = nextTool;
  1853. if (currentTool)
  1854. {
  1855. currentTool->setActive(true);
  1856. }
  1857. }
  1858. if (1)
  1859. {
  1860. toolIndicatorIconImage->setTextureBounds(toolIndicatorsBounds[toolIndex]);
  1861. toolIndicatorIconImage->setVisible(true);
  1862. }
  1863. else
  1864. {
  1865. toolIndicatorIconImage->setVisible(false);
  1866. }
  1867. }
  1868. EntityID Game::createInstance()
  1869. {
  1870. return entityManager->createEntity();
  1871. }
  1872. EntityID Game::createInstanceOf(const std::string& templateName)
  1873. {
  1874. EntityTemplate* entityTemplate = resourceManager->load<EntityTemplate>(templateName + ".ent");
  1875. EntityID entity = entityManager->createEntity();
  1876. entityTemplate->apply(entity, componentManager);
  1877. return entity;
  1878. }
  1879. void Game::destroyInstance(EntityID entity)
  1880. {
  1881. entityManager->destroyEntity(entity);
  1882. }
  1883. void Game::addComponent(EntityID entity, ComponentBase* component)
  1884. {
  1885. componentManager->addComponent(entity, component);
  1886. }
  1887. void Game::removeComponent(EntityID entity, ComponentType type)
  1888. {
  1889. ComponentBase* component = componentManager->removeComponent(entity, type);
  1890. delete component;
  1891. }
  1892. void Game::setTranslation(EntityID entity, const Vector3& translation)
  1893. {
  1894. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  1895. if (!component)
  1896. {
  1897. return;
  1898. }
  1899. component->transform.translation = translation;
  1900. }
  1901. void Game::setRotation(EntityID entity, const Quaternion& rotation)
  1902. {
  1903. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  1904. if (!component)
  1905. {
  1906. return;
  1907. }
  1908. component->transform.rotation = rotation;
  1909. }
  1910. void Game::setScale(EntityID entity, const Vector3& scale)
  1911. {
  1912. TransformComponent* component = componentManager->getComponent<TransformComponent>(entity);
  1913. if (!component)
  1914. {
  1915. return;
  1916. }
  1917. component->transform.scale = scale;
  1918. }
  1919. void Game::setTerrainPatchPosition(EntityID entity, const std::tuple<int, int>& position)
  1920. {
  1921. TerrainPatchComponent* component = componentManager->getComponent<TerrainPatchComponent>(entity);
  1922. if (!component)
  1923. {
  1924. return;
  1925. }
  1926. component->position = position;
  1927. }
  1928. void Game::saveScreenshot(const std::string& filename, unsigned int width, unsigned int height, unsigned char* pixels)
  1929. {
  1930. stbi_flip_vertically_on_write(1);
  1931. stbi_write_png(filename.c_str(), width, height, 3, pixels, width * 3);
  1932. delete[] pixels;
  1933. }