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

1056 lines
38 KiB

1 year ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
  1. /*
  2. * Copyright (C) 2021 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/states/boot.hpp"
  20. #include "animation/animation.hpp"
  21. #include "animation/animator.hpp"
  22. #include "animation/ease.hpp"
  23. #include "animation/screen-transition.hpp"
  24. #include "animation/timeline.hpp"
  25. #include "application.hpp"
  26. #include "debug/cli.hpp"
  27. #include "debug/console-commands.hpp"
  28. #include "debug/logger.hpp"
  29. #include "game/context.hpp"
  30. #include "gl/framebuffer.hpp"
  31. #include "gl/pixel-format.hpp"
  32. #include "gl/pixel-type.hpp"
  33. #include "gl/rasterizer.hpp"
  34. #include "gl/texture-2d.hpp"
  35. #include "gl/texture-filter.hpp"
  36. #include "gl/texture-wrapping.hpp"
  37. #include "gl/vertex-array.hpp"
  38. #include "gl/vertex-attribute.hpp"
  39. #include "gl/vertex-buffer.hpp"
  40. #include "render/material-flags.hpp"
  41. #include "render/material-property.hpp"
  42. #include "render/passes/bloom-pass.hpp"
  43. #include "render/passes/clear-pass.hpp"
  44. #include "render/passes/final-pass.hpp"
  45. #include "render/passes/material-pass.hpp"
  46. #include "render/passes/outline-pass.hpp"
  47. #include "render/passes/shadow-map-pass.hpp"
  48. #include "render/passes/sky-pass.hpp"
  49. #include "render/passes/simple-pass.hpp"
  50. #include "render/vertex-attribute.hpp"
  51. #include "render/compositor.hpp"
  52. #include "render/renderer.hpp"
  53. #include "resources/resource-manager.hpp"
  54. #include "resources/file-buffer.hpp"
  55. #include "scene/scene.hpp"
  56. #include "game/states/loading.hpp"
  57. #include "entity/systems/behavior.hpp"
  58. #include "entity/systems/camera.hpp"
  59. #include "entity/systems/collision.hpp"
  60. #include "entity/systems/constraint.hpp"
  61. #include "entity/systems/locomotion.hpp"
  62. #include "entity/systems/snapping.hpp"
  63. #include "entity/systems/render.hpp"
  64. #include "entity/systems/samara.hpp"
  65. #include "entity/systems/subterrain.hpp"
  66. #include "entity/systems/terrain.hpp"
  67. #include "entity/systems/vegetation.hpp"
  68. #include "entity/systems/spatial.hpp"
  69. #include "entity/systems/painting.hpp"
  70. #include "entity/systems/astronomy.hpp"
  71. #include "entity/systems/blackbody.hpp"
  72. #include "entity/systems/atmosphere.hpp"
  73. #include "entity/systems/orbit.hpp"
  74. #include "entity/systems/proteome.hpp"
  75. #include "entity/commands.hpp"
  76. #include "utility/paths.hpp"
  77. #include "event/event-dispatcher.hpp"
  78. #include "input/event-router.hpp"
  79. #include "input/mapper.hpp"
  80. #include "input/listener.hpp"
  81. #include "input/gamepad.hpp"
  82. #include "input/mouse.hpp"
  83. #include "input/keyboard.hpp"
  84. #include "configuration.hpp"
  85. #include "input/scancode.hpp"
  86. #include <cxxopts.hpp>
  87. #include <dirent.h>
  88. #include <entt/entt.hpp>
  89. #include <filesystem>
  90. #include <functional>
  91. #include <string>
  92. #include <vector>
  93. #include <execution>
  94. #include <algorithm>
  95. namespace game {
  96. namespace state {
  97. namespace boot {
  98. static constexpr double seconds_per_day = 24.0 * 60.0 * 60.0;
  99. static void parse_options(game::context* ctx, int argc, char** argv);
  100. static void setup_resources(game::context* ctx);
  101. static void load_config(game::context* ctx);
  102. static void load_strings(game::context* ctx);
  103. static void setup_window(game::context* ctx);
  104. static void setup_rendering(game::context* ctx);
  105. static void setup_sound(game::context* ctx);
  106. static void setup_scenes(game::context* ctx);
  107. static void setup_animation(game::context* ctx);
  108. static void setup_entities(game::context* ctx);
  109. static void setup_systems(game::context* ctx);
  110. static void setup_controls(game::context* ctx);
  111. static void setup_cli(game::context* ctx);
  112. static void setup_callbacks(game::context* ctx);
  113. void enter(application* app, int argc, char** argv)
  114. {
  115. // Get application logger
  116. debug::logger* logger = app->get_logger();
  117. // Allocate game context
  118. game::context* ctx = new game::context();
  119. ctx->app = app;
  120. ctx->logger = logger;
  121. // Init game context
  122. try
  123. {
  124. parse_options(ctx, argc, argv);
  125. setup_resources(ctx);
  126. load_config(ctx);
  127. load_strings(ctx);
  128. setup_window(ctx);
  129. setup_rendering(ctx);
  130. setup_sound(ctx);
  131. setup_scenes(ctx);
  132. setup_animation(ctx);
  133. setup_entities(ctx);
  134. setup_systems(ctx);
  135. setup_controls(ctx);
  136. setup_cli(ctx);
  137. setup_callbacks(ctx);
  138. }
  139. catch (const std::exception& e)
  140. {
  141. logger->error("Caught exception: \"" + std::string(e.what()) + "\"");
  142. logger->pop_task(EXIT_FAILURE);
  143. return;
  144. }
  145. // Set update rate
  146. if (ctx->config->contains("update_rate"))
  147. {
  148. app->set_update_rate((*ctx->config)["update_rate"].get<double>());
  149. }
  150. // Queue next application state
  151. application::state next_state;
  152. next_state.name = "loading";
  153. next_state.enter = std::bind(game::state::loading::enter, ctx);
  154. next_state.exit = std::bind(game::state::loading::exit, ctx);
  155. app->queue_state(next_state);
  156. }
  157. void exit(application* app)
  158. {}
  159. void parse_options(game::context* ctx, int argc, char** argv)
  160. {
  161. debug::logger* logger = ctx->logger;
  162. logger->push_task("Parsing command line options");
  163. try
  164. {
  165. cxxopts::Options options("Antkeeper", "Ant colony simulation game");
  166. options.add_options()
  167. ("c,continue", "Continues from the last save")
  168. ("d,data", "Sets the data package path", cxxopts::value<std::string>())
  169. ("f,fullscreen", "Starts in fullscreen mode")
  170. ("n,new-game", "Starts a new game")
  171. ("q,quick-start", "Skips to the main menu")
  172. ("r,reset", "Restores all settings to default")
  173. ("v,vsync", "Enables or disables v-sync", cxxopts::value<int>())
  174. ("w,windowed", "Starts in windowed mode");
  175. auto result = options.parse(argc, argv);
  176. // --continue
  177. if (result.count("continue"))
  178. ctx->option_continue = true;
  179. // --data
  180. if (result.count("data"))
  181. ctx->option_data = result["data"].as<std::string>();
  182. // --fullscreen
  183. if (result.count("fullscreen"))
  184. ctx->option_fullscreen = true;
  185. // --new-game
  186. if (result.count("new-game"))
  187. ctx->option_new_game = true;
  188. // --quick-start
  189. if (result.count("quick-start"))
  190. ctx->option_quick_start = true;
  191. // --reset
  192. if (result.count("reset"))
  193. ctx->option_reset = true;
  194. // --vsync
  195. if (result.count("vsync"))
  196. ctx->option_vsync = (result["vsync"].as<int>()) ? true : false;
  197. // --windowed
  198. if (result.count("windowed"))
  199. ctx->option_windowed = true;
  200. }
  201. catch (const std::exception& e)
  202. {
  203. logger->error("Exception caught: \"" + std::string(e.what()) + "\"");
  204. logger->pop_task(EXIT_FAILURE);
  205. return;
  206. }
  207. logger->pop_task(EXIT_SUCCESS);
  208. }
  209. void setup_resources(game::context* ctx)
  210. {
  211. debug::logger* logger = ctx->logger;
  212. // Setup resource manager
  213. ctx->resource_manager = new resource_manager(logger);
  214. // Determine application name
  215. std::string application_name;
  216. #if defined(_WIN32) || defined(__APPLE__)
  217. application_name = "Antkeeper";
  218. #else
  219. application_name = "antkeeper";
  220. #endif
  221. // Detect paths
  222. ctx->data_path = get_data_path(application_name);
  223. ctx->config_path = get_config_path(application_name);
  224. ctx->mods_path = ctx->config_path + "mods/";
  225. ctx->saves_path = ctx->config_path + "saves/";
  226. ctx->screenshots_path = ctx->config_path + "gallery/";
  227. ctx->controls_path = ctx->config_path + "controls/";
  228. // Log resource paths
  229. logger->log("Detected data path as \"" + ctx->data_path + "\"");
  230. logger->log("Detected config path as \"" + ctx->config_path + "\"");
  231. // Create nonexistent config directories
  232. std::vector<std::string> config_paths;
  233. config_paths.push_back(ctx->config_path);
  234. config_paths.push_back(ctx->mods_path);
  235. config_paths.push_back(ctx->saves_path);
  236. config_paths.push_back(ctx->screenshots_path);
  237. config_paths.push_back(ctx->controls_path);
  238. for (const std::string& path: config_paths)
  239. {
  240. if (!path_exists(path))
  241. {
  242. logger->push_task("Creating directory \"" + path + "\"");
  243. if (create_directory(path))
  244. {
  245. logger->pop_task(EXIT_SUCCESS);
  246. }
  247. else
  248. {
  249. logger->pop_task(EXIT_FAILURE);
  250. }
  251. }
  252. }
  253. // Redirect logger output to log file on non-debug builds
  254. #if defined(NDEBUG)
  255. std::string log_filename = ctx->config_path + "log.txt";
  256. ctx->log_filestream.open(log_filename.c_str());
  257. ctx->log_filestream << logger->get_history();
  258. logger->redirect(&ctx->log_filestream);
  259. #endif
  260. // Scan for mods
  261. std::vector<std::string> mods;
  262. struct dirent** files = nullptr;
  263. if (int n = scandir(ctx->mods_path.c_str(), &files, NULL, alphasort); n >= 0)
  264. {
  265. for (int i = 0; i < n; ++i)
  266. {
  267. struct dirent* file = files[i];
  268. switch (file->d_type)
  269. {
  270. case DT_REG:
  271. case DT_DIR:
  272. {
  273. std::string mod_name = file->d_name;
  274. // Skip hidden files and directories
  275. if (mod_name.front() == '.')
  276. break;
  277. mods.push_back(mod_name);
  278. }
  279. default:
  280. break;
  281. }
  282. }
  283. }
  284. // Determine data package path
  285. if (ctx->option_data.has_value())
  286. {
  287. ctx->data_package_path = ctx->option_data.value();
  288. if (std::filesystem::path(ctx->data_package_path).is_relative())
  289. ctx->data_package_path = ctx->data_path + ctx->data_package_path;
  290. }
  291. else
  292. {
  293. ctx->data_package_path = ctx->data_path + "data.zip";
  294. }
  295. // Mount mods
  296. for (const std::string& mod_name: mods)
  297. ctx->resource_manager->mount(ctx->mods_path + mod_name);
  298. // Mount config path
  299. ctx->resource_manager->mount(ctx->config_path);
  300. // Mount data package
  301. ctx->resource_manager->mount(ctx->data_package_path);
  302. // Include resource search paths in order of priority
  303. ctx->resource_manager->include("/shaders/");
  304. ctx->resource_manager->include("/models/");
  305. ctx->resource_manager->include("/images/");
  306. ctx->resource_manager->include("/textures/");
  307. ctx->resource_manager->include("/materials/");
  308. ctx->resource_manager->include("/entities/");
  309. ctx->resource_manager->include("/behaviors/");
  310. ctx->resource_manager->include("/controls/");
  311. ctx->resource_manager->include("/localization/");
  312. ctx->resource_manager->include("/localization/fonts/");
  313. ctx->resource_manager->include("/biomes/");
  314. ctx->resource_manager->include("/traits/");
  315. ctx->resource_manager->include("/");
  316. }
  317. void load_config(game::context* ctx)
  318. {
  319. debug::logger* logger = ctx->logger;
  320. logger->push_task("Loading config");
  321. // Load config file
  322. ctx->config = ctx->resource_manager->load<json>("config.json");
  323. if (!ctx->config)
  324. {
  325. logger->pop_task(EXIT_FAILURE);
  326. return;
  327. }
  328. logger->pop_task(EXIT_SUCCESS);
  329. }
  330. void load_strings(game::context* ctx)
  331. {
  332. debug::logger* logger = ctx->logger;
  333. logger->push_task("Loading strings");
  334. ctx->string_table = ctx->resource_manager->load<string_table>("strings.csv");
  335. build_string_table_map(&ctx->string_table_map, *ctx->string_table);
  336. ctx->language_code = (*ctx->config)["language"].get<std::string>();
  337. ctx->language_index = -1;
  338. for (int i = 2; i < (*ctx->string_table)[0].size(); ++i)
  339. {
  340. if ((*ctx->string_table)[0][i] == ctx->language_code)
  341. ctx->language_index = i - 2;
  342. }
  343. ctx->language_count = (*ctx->string_table)[0].size() - 2;
  344. logger->log("language count: " + std::to_string(ctx->language_count));
  345. logger->log("language index: " + std::to_string(ctx->language_index));
  346. logger->log("language code: " + ctx->language_code);
  347. ctx->strings = &ctx->string_table_map[ctx->language_code];
  348. logger->pop_task(EXIT_SUCCESS);
  349. }
  350. void setup_window(game::context* ctx)
  351. {
  352. debug::logger* logger = ctx->logger;
  353. logger->push_task("Setting up window");
  354. application* app = ctx->app;
  355. json* config = ctx->config;
  356. // Set fullscreen or windowed mode
  357. bool fullscreen = true;
  358. if (ctx->option_fullscreen.has_value())
  359. fullscreen = true;
  360. else if (ctx->option_windowed.has_value())
  361. fullscreen = false;
  362. else if (config->contains("fullscreen"))
  363. fullscreen = (*config)["fullscreen"].get<bool>();
  364. app->set_fullscreen(fullscreen);
  365. // Set resolution
  366. const auto& display_dimensions = ctx->app->get_display_dimensions();
  367. int2 resolution = {display_dimensions[0], display_dimensions[1]};
  368. if (fullscreen)
  369. {
  370. if (config->contains("fullscreen_resolution"))
  371. {
  372. resolution.x = (*config)["fullscreen_resolution"][0].get<int>();
  373. resolution.y = (*config)["fullscreen_resolution"][1].get<int>();
  374. }
  375. }
  376. else
  377. {
  378. if (config->contains("windowed_resolution"))
  379. {
  380. resolution.x = (*config)["windowed_resolution"][0].get<int>();
  381. resolution.y = (*config)["windowed_resolution"][1].get<int>();
  382. }
  383. }
  384. app->resize_window(resolution.x, resolution.y);
  385. // Set v-sync
  386. bool vsync = true;
  387. if (ctx->option_vsync.has_value())
  388. vsync = (ctx->option_vsync.value() != 0);
  389. else if (config->contains("vsync"))
  390. vsync = (*config)["vsync"].get<bool>();
  391. app->set_vsync(vsync);
  392. // Set title
  393. app->set_title((*ctx->strings)["application_title"]);
  394. // Show window
  395. ctx->app->get_rasterizer()->set_clear_color(0.0f, 0.0f, 0.0f, 1.0f);
  396. ctx->app->get_rasterizer()->clear_framebuffer(true, false, false);
  397. app->show_window();
  398. ctx->app->swap_buffers();
  399. logger->pop_task(EXIT_SUCCESS);
  400. }
  401. void setup_rendering(game::context* ctx)
  402. {
  403. debug::logger* logger = ctx->logger;
  404. logger->push_task("Setting up rendering");
  405. // Get rasterizer from application
  406. ctx->rasterizer = ctx->app->get_rasterizer();
  407. // Get default framebuffer
  408. const gl::framebuffer& default_framebuffer = ctx->rasterizer->get_default_framebuffer();
  409. const auto& viewport_dimensions = default_framebuffer.get_dimensions();
  410. // Create HDR framebuffer (32F color, 32F depth)
  411. ctx->framebuffer_hdr_color = new gl::texture_2d(viewport_dimensions[0], viewport_dimensions[1], gl::pixel_type::float_32, gl::pixel_format::rgb);
  412. ctx->framebuffer_hdr_color->set_wrapping(gl::texture_wrapping::extend, gl::texture_wrapping::extend);
  413. ctx->framebuffer_hdr_color->set_filters(gl::texture_min_filter::linear, gl::texture_mag_filter::linear);
  414. ctx->framebuffer_hdr_color->set_max_anisotropy(0.0f);
  415. ctx->framebuffer_hdr_depth = new gl::texture_2d(viewport_dimensions[0], viewport_dimensions[1], gl::pixel_type::float_32, gl::pixel_format::ds);
  416. ctx->framebuffer_hdr_depth->set_wrapping(gl::texture_wrapping::extend, gl::texture_wrapping::extend);
  417. ctx->framebuffer_hdr_depth->set_filters(gl::texture_min_filter::linear, gl::texture_mag_filter::linear);
  418. ctx->framebuffer_hdr_depth->set_max_anisotropy(0.0f);
  419. ctx->framebuffer_hdr = new gl::framebuffer(viewport_dimensions[0], viewport_dimensions[1]);
  420. ctx->framebuffer_hdr->attach(gl::framebuffer_attachment_type::color, ctx->framebuffer_hdr_color);
  421. ctx->framebuffer_hdr->attach(gl::framebuffer_attachment_type::depth, ctx->framebuffer_hdr_depth);
  422. ctx->framebuffer_hdr->attach(gl::framebuffer_attachment_type::stencil, ctx->framebuffer_hdr_depth);
  423. // Create shadow map framebuffer
  424. int shadow_map_resolution = 4096;
  425. if (ctx->config->contains("shadow_map_resolution"))
  426. {
  427. shadow_map_resolution = (*ctx->config)["shadow_map_resolution"].get<int>();
  428. }
  429. ctx->shadow_map_depth_texture = new gl::texture_2d(shadow_map_resolution, shadow_map_resolution, gl::pixel_type::float_32, gl::pixel_format::d);
  430. ctx->shadow_map_depth_texture->set_wrapping(gl::texture_wrapping::extend, gl::texture_wrapping::extend);
  431. ctx->shadow_map_depth_texture->set_filters(gl::texture_min_filter::linear, gl::texture_mag_filter::linear);
  432. ctx->shadow_map_depth_texture->set_max_anisotropy(0.0f);
  433. ctx->shadow_map_framebuffer = new gl::framebuffer(shadow_map_resolution, shadow_map_resolution);
  434. ctx->shadow_map_framebuffer->attach(gl::framebuffer_attachment_type::depth, ctx->shadow_map_depth_texture);
  435. // Create bloom pingpong framebuffers (16F color, no depth)
  436. int bloom_width = viewport_dimensions[0] >> 1;
  437. int bloom_height = viewport_dimensions[1] >> 1;
  438. ctx->bloom_texture = new gl::texture_2d(bloom_width, bloom_height, gl::pixel_type::float_16, gl::pixel_format::rgb);
  439. ctx->bloom_texture->set_wrapping(gl::texture_wrapping::extend, gl::texture_wrapping::extend);
  440. ctx->bloom_texture->set_filters(gl::texture_min_filter::linear, gl::texture_mag_filter::linear);
  441. ctx->bloom_texture->set_max_anisotropy(0.0f);
  442. ctx->framebuffer_bloom = new gl::framebuffer(bloom_width, bloom_height);
  443. ctx->framebuffer_bloom->attach(gl::framebuffer_attachment_type::color, ctx->bloom_texture);
  444. // Load blue noise texture
  445. gl::texture_2d* blue_noise_map = ctx->resource_manager->load<gl::texture_2d>("blue-noise.tex");
  446. // Load fallback material
  447. ctx->fallback_material = ctx->resource_manager->load<render::material>("fallback.mtl");
  448. // Setup common render passes
  449. {
  450. ctx->common_bloom_pass = new render::bloom_pass(ctx->rasterizer, ctx->framebuffer_bloom, ctx->resource_manager);
  451. ctx->common_bloom_pass->set_source_texture(ctx->framebuffer_hdr_color);
  452. ctx->common_bloom_pass->set_brightness_threshold(1.0f);
  453. ctx->common_bloom_pass->set_blur_iterations(5);
  454. ctx->common_final_pass = new render::final_pass(ctx->rasterizer, &ctx->rasterizer->get_default_framebuffer(), ctx->resource_manager);
  455. ctx->common_final_pass->set_color_texture(ctx->framebuffer_hdr_color);
  456. ctx->common_final_pass->set_bloom_texture(ctx->bloom_texture);
  457. ctx->common_final_pass->set_blue_noise_texture(blue_noise_map);
  458. }
  459. // Setup UI compositor
  460. {
  461. ctx->ui_clear_pass = new render::clear_pass(ctx->rasterizer, &ctx->rasterizer->get_default_framebuffer());
  462. ctx->ui_clear_pass->set_cleared_buffers(false, true, false);
  463. ctx->ui_clear_pass->set_clear_depth(0.0f);
  464. ctx->ui_material_pass = new render::material_pass(ctx->rasterizer, &ctx->rasterizer->get_default_framebuffer(), ctx->resource_manager);
  465. ctx->ui_material_pass->set_fallback_material(ctx->fallback_material);
  466. ctx->ui_compositor = new render::compositor();
  467. ctx->ui_compositor->add_pass(ctx->ui_clear_pass);
  468. ctx->ui_compositor->add_pass(ctx->ui_material_pass);
  469. }
  470. // Setup underground compositor
  471. {
  472. ctx->underground_clear_pass = new render::clear_pass(ctx->rasterizer, ctx->framebuffer_hdr);
  473. ctx->underground_clear_pass->set_cleared_buffers(true, true, false);
  474. ctx->underground_clear_pass->set_clear_color({1, 0, 1, 0});
  475. ctx->underground_clear_pass->set_clear_depth(0.0f);
  476. ctx->underground_material_pass = new render::material_pass(ctx->rasterizer, ctx->framebuffer_hdr, ctx->resource_manager);
  477. ctx->underground_material_pass->set_fallback_material(ctx->fallback_material);
  478. ctx->app->get_event_dispatcher()->subscribe<mouse_moved_event>(ctx->underground_material_pass);
  479. ctx->underground_compositor = new render::compositor();
  480. ctx->underground_compositor->add_pass(ctx->underground_clear_pass);
  481. ctx->underground_compositor->add_pass(ctx->underground_material_pass);
  482. ctx->underground_compositor->add_pass(ctx->common_bloom_pass);
  483. ctx->underground_compositor->add_pass(ctx->common_final_pass);
  484. }
  485. // Setup surface compositor
  486. {
  487. ctx->surface_shadow_map_clear_pass = new render::clear_pass(ctx->rasterizer, ctx->shadow_map_framebuffer);
  488. ctx->surface_shadow_map_clear_pass->set_cleared_buffers(false, true, false);
  489. ctx->surface_shadow_map_clear_pass->set_clear_depth(1.0f);
  490. ctx->surface_shadow_map_pass = new render::shadow_map_pass(ctx->rasterizer, ctx->shadow_map_framebuffer, ctx->resource_manager);
  491. ctx->surface_shadow_map_pass->set_split_scheme_weight(0.75f);
  492. ctx->surface_clear_pass = new render::clear_pass(ctx->rasterizer, ctx->framebuffer_hdr);
  493. ctx->surface_clear_pass->set_cleared_buffers(true, true, true);
  494. ctx->surface_clear_pass->set_clear_depth(0.0f);
  495. ctx->surface_sky_pass = new render::sky_pass(ctx->rasterizer, ctx->framebuffer_hdr, ctx->resource_manager);
  496. ctx->app->get_event_dispatcher()->subscribe<mouse_moved_event>(ctx->surface_sky_pass);
  497. ctx->surface_material_pass = new render::material_pass(ctx->rasterizer, ctx->framebuffer_hdr, ctx->resource_manager);
  498. ctx->surface_material_pass->set_fallback_material(ctx->fallback_material);
  499. ctx->surface_material_pass->shadow_map_pass = ctx->surface_shadow_map_pass;
  500. ctx->surface_material_pass->shadow_map = ctx->shadow_map_depth_texture;
  501. ctx->app->get_event_dispatcher()->subscribe<mouse_moved_event>(ctx->surface_material_pass);
  502. ctx->surface_outline_pass = new render::outline_pass(ctx->rasterizer, ctx->framebuffer_hdr, ctx->resource_manager);
  503. ctx->surface_outline_pass->set_outline_width(0.25f);
  504. ctx->surface_outline_pass->set_outline_color(float4{1.0f, 1.0f, 1.0f, 1.0f});
  505. ctx->surface_compositor = new render::compositor();
  506. ctx->surface_compositor->add_pass(ctx->surface_shadow_map_clear_pass);
  507. ctx->surface_compositor->add_pass(ctx->surface_shadow_map_pass);
  508. ctx->surface_compositor->add_pass(ctx->surface_clear_pass);
  509. ctx->surface_compositor->add_pass(ctx->surface_sky_pass);
  510. ctx->surface_compositor->add_pass(ctx->surface_material_pass);
  511. //ctx->surface_compositor->add_pass(ctx->surface_outline_pass);
  512. ctx->surface_compositor->add_pass(ctx->common_bloom_pass);
  513. ctx->surface_compositor->add_pass(ctx->common_final_pass);
  514. }
  515. // Create billboard VAO
  516. {
  517. const float billboard_vertex_data[] =
  518. {
  519. -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f,
  520. -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
  521. 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
  522. 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
  523. -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
  524. 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f
  525. };
  526. std::size_t billboard_vertex_size = 8;
  527. std::size_t billboard_vertex_stride = sizeof(float) * billboard_vertex_size;
  528. std::size_t billboard_vertex_count = 6;
  529. ctx->billboard_vbo = new gl::vertex_buffer(sizeof(float) * billboard_vertex_size * billboard_vertex_count, billboard_vertex_data);
  530. ctx->billboard_vao = new gl::vertex_array();
  531. std::size_t attribute_offset = 0;
  532. // Define position vertex attribute
  533. gl::vertex_attribute position_attribute;
  534. position_attribute.buffer = ctx->billboard_vbo;
  535. position_attribute.offset = attribute_offset;
  536. position_attribute.stride = billboard_vertex_stride;
  537. position_attribute.type = gl::vertex_attribute_type::float_32;
  538. position_attribute.components = 3;
  539. attribute_offset += position_attribute.components * sizeof(float);
  540. // Define UV vertex attribute
  541. gl::vertex_attribute uv_attribute;
  542. uv_attribute.buffer = ctx->billboard_vbo;
  543. uv_attribute.offset = attribute_offset;
  544. uv_attribute.stride = billboard_vertex_stride;
  545. uv_attribute.type = gl::vertex_attribute_type::float_32;
  546. uv_attribute.components = 2;
  547. attribute_offset += uv_attribute.components * sizeof(float);
  548. // Define barycentric vertex attribute
  549. gl::vertex_attribute barycentric_attribute;
  550. barycentric_attribute.buffer = ctx->billboard_vbo;
  551. barycentric_attribute.offset = attribute_offset;
  552. barycentric_attribute.stride = billboard_vertex_stride;
  553. barycentric_attribute.type = gl::vertex_attribute_type::float_32;
  554. barycentric_attribute.components = 3;
  555. attribute_offset += barycentric_attribute.components * sizeof(float);
  556. // Bind vertex attributes to VAO
  557. ctx->billboard_vao->bind(render::vertex_attribute::position, position_attribute);
  558. ctx->billboard_vao->bind(render::vertex_attribute::uv, uv_attribute);
  559. ctx->billboard_vao->bind(render::vertex_attribute::barycentric, barycentric_attribute);
  560. }
  561. // Create renderer
  562. ctx->renderer = new render::renderer();
  563. ctx->renderer->set_billboard_vao(ctx->billboard_vao);
  564. logger->pop_task(EXIT_SUCCESS);
  565. }
  566. void setup_sound(game::context* ctx)
  567. {
  568. debug::logger* logger = ctx->logger;
  569. logger->push_task("Setting up sound");
  570. // Load master volume
  571. ctx->master_volume = 1.0f;
  572. if (ctx->config->contains("master_volume"))
  573. ctx->master_volume = (*ctx->config)["master_volume"].get<float>();
  574. // Load ambience volume
  575. ctx->ambience_volume = 1.0f;
  576. if (ctx->config->contains("ambience_volume"))
  577. ctx->ambience_volume = (*ctx->config)["ambience_volume"].get<float>();
  578. // Load effects volume
  579. ctx->effects_volume = 1.0f;
  580. if (ctx->config->contains("effects_volume"))
  581. ctx->effects_volume = (*ctx->config)["effects_volume"].get<float>();
  582. logger->pop_task(EXIT_SUCCESS);
  583. }
  584. void setup_scenes(game::context* ctx)
  585. {
  586. debug::logger* logger = ctx->logger;
  587. logger->push_task("Setting up scenes");
  588. // Get default framebuffer
  589. const auto& viewport_dimensions = ctx->rasterizer->get_default_framebuffer().get_dimensions();
  590. const float viewport_aspect_ratio = static_cast<float>(viewport_dimensions[0]) / static_cast<float>(viewport_dimensions[1]);
  591. // Create infinite culling mask
  592. const float inf = std::numeric_limits<float>::infinity();
  593. ctx->no_cull = {{-inf, -inf, -inf}, {inf, inf, inf}};
  594. // Setup UI camera
  595. ctx->ui_camera = new scene::camera();
  596. ctx->ui_camera->set_compositor(ctx->ui_compositor);
  597. auto viewport = ctx->app->get_viewport_dimensions();
  598. float clip_left = -viewport[0] * 0.5f;
  599. float clip_right = viewport[0] * 0.5f;
  600. float clip_top = -viewport[1] * 0.5f;
  601. float clip_bottom = viewport[1] * 0.5f;
  602. float clip_near = 0.0f;
  603. float clip_far = 1000.0f;
  604. ctx->ui_camera->set_orthographic(clip_left, clip_right, clip_top, clip_bottom, clip_near, clip_far);
  605. // Setup underground camera
  606. ctx->underground_camera = new scene::camera();
  607. ctx->underground_camera->set_perspective(math::radians<float>(45.0f), viewport_aspect_ratio, 0.1f, 1000.0f);
  608. ctx->underground_camera->set_compositor(ctx->underground_compositor);
  609. ctx->underground_camera->set_composite_index(0);
  610. ctx->underground_camera->set_active(false);
  611. // Setup surface camera
  612. ctx->surface_camera = new scene::camera();
  613. ctx->surface_camera->set_perspective(math::radians<float>(45.0f), viewport_aspect_ratio, 0.1f, 1000.0f);
  614. ctx->surface_camera->set_compositor(ctx->surface_compositor);
  615. ctx->surface_camera->set_composite_index(0);
  616. ctx->surface_camera->set_active(false);
  617. // Setup UI scene
  618. {
  619. ctx->ui_scene = new scene::collection();
  620. const gl::texture_2d* splash_texture = ctx->resource_manager->load<gl::texture_2d>("splash.tex");
  621. auto splash_dimensions = splash_texture->get_dimensions();
  622. ctx->splash_billboard_material = new render::material();
  623. ctx->splash_billboard_material->set_flags(MATERIAL_FLAG_TRANSLUCENT);
  624. ctx->splash_billboard_material->set_shader_program(ctx->resource_manager->load<gl::shader_program>("ui-element-textured.glsl"));
  625. ctx->splash_billboard_material->add_property<const gl::texture_2d*>("background")->set_value(splash_texture);
  626. ctx->splash_billboard_material->add_property<float4>("tint")->set_value(float4{1, 1, 1, 1});
  627. ctx->splash_billboard_material->update_tweens();
  628. ctx->splash_billboard = new scene::billboard();
  629. ctx->splash_billboard->set_material(ctx->splash_billboard_material);
  630. ctx->splash_billboard->set_scale({(float)std::get<0>(splash_dimensions) * 0.5f, (float)std::get<1>(splash_dimensions) * 0.5f, 1.0f});
  631. ctx->splash_billboard->set_translation({0.0f, 0.0f, 0.0f});
  632. ctx->splash_billboard->update_tweens();
  633. // Create camera flash billboard
  634. render::material* flash_material = new render::material();
  635. flash_material->set_shader_program(ctx->resource_manager->load<gl::shader_program>("ui-element-untextured.glsl"));
  636. auto flash_tint = flash_material->add_property<float4>("tint");
  637. flash_tint->set_value(float4{1, 1, 1, 1});
  638. //flash_tint->set_tween_interpolator(ease<float4>::out_quad);
  639. flash_material->set_flags(MATERIAL_FLAG_TRANSLUCENT);
  640. flash_material->update_tweens();
  641. ctx->camera_flash_billboard = new scene::billboard();
  642. ctx->camera_flash_billboard->set_material(flash_material);
  643. ctx->camera_flash_billboard->set_scale({(float)viewport_dimensions[0] * 0.5f, (float)viewport_dimensions[1] * 0.5f, 1.0f});
  644. ctx->camera_flash_billboard->set_translation({0.0f, 0.0f, 0.0f});
  645. ctx->camera_flash_billboard->update_tweens();
  646. // Create depth debug billboard
  647. /*
  648. material* depth_debug_material = new material();
  649. depth_debug_material->set_shader_program(ctx->resource_manager->load<gl::shader_program>("ui-element-textured.glsl"));
  650. depth_debug_material->add_property<const gl::texture_2d*>("background")->set_value(shadow_map_depth_texture);
  651. depth_debug_material->add_property<float4>("tint")->set_value(float4{1, 1, 1, 1});
  652. billboard* depth_debug_billboard = new billboard();
  653. depth_debug_billboard->set_material(depth_debug_material);
  654. depth_debug_billboard->set_scale({128, 128, 1});
  655. depth_debug_billboard->set_translation({-960 + 128, 1080 * 0.5f - 128, 0});
  656. depth_debug_billboard->update_tweens();
  657. ui_system->get_scene()->add_object(depth_debug_billboard);
  658. */
  659. ctx->ui_scene->add_object(ctx->ui_camera);
  660. }
  661. // Setup underground scene
  662. {
  663. ctx->underground_scene = new scene::collection();
  664. ctx->underground_ambient_light = new scene::ambient_light();
  665. ctx->underground_ambient_light->set_color({1, 1, 1});
  666. ctx->underground_ambient_light->set_intensity(0.1f);
  667. ctx->underground_ambient_light->update_tweens();
  668. ctx->flashlight_spot_light = new scene::spot_light();
  669. ctx->flashlight_spot_light->set_color({1, 1, 1});
  670. ctx->flashlight_spot_light->set_intensity(1.0f);
  671. ctx->flashlight_spot_light->set_attenuation({1.0f, 0.0f, 0.0f});
  672. ctx->flashlight_spot_light->set_cutoff({math::radians(10.0f), math::radians(19.0f)});
  673. ctx->underground_scene->add_object(ctx->underground_camera);
  674. ctx->underground_scene->add_object(ctx->underground_ambient_light);
  675. //ctx->underground_scene->add_object(ctx->flashlight_spot_light);
  676. }
  677. // Setup surface scene
  678. {
  679. ctx->surface_scene = new scene::collection();
  680. ctx->surface_scene->add_object(ctx->surface_camera);
  681. }
  682. // Clear active scene
  683. ctx->active_scene = nullptr;
  684. logger->pop_task(EXIT_SUCCESS);
  685. }
  686. void setup_animation(game::context* ctx)
  687. {
  688. // Setup timeline system
  689. ctx->timeline = new timeline();
  690. ctx->timeline->set_autoremove(true);
  691. // Setup animator
  692. ctx->animator = new animator();
  693. // Create fade transition
  694. ctx->fade_transition = new screen_transition();
  695. ctx->fade_transition->get_material()->set_shader_program(ctx->resource_manager->load<gl::shader_program>("fade-transition.glsl"));
  696. ctx->fade_transition_color = ctx->fade_transition->get_material()->add_property<float3>("color");
  697. ctx->fade_transition_color->set_value({0, 0, 0});
  698. ctx->ui_scene->add_object(ctx->fade_transition->get_billboard());
  699. ctx->animator->add_animation(ctx->fade_transition->get_animation());
  700. // Create inner radial transition
  701. ctx->radial_transition_inner = new screen_transition();
  702. ctx->radial_transition_inner->get_material()->set_shader_program(ctx->resource_manager->load<gl::shader_program>("radial-transition-inner.glsl"));
  703. //ctx->ui_scene->add_object(ctx->radial_transition_inner->get_billboard());
  704. //ctx->animator->add_animation(ctx->radial_transition_inner->get_animation());
  705. // Create outer radial transition
  706. ctx->radial_transition_outer = new screen_transition();
  707. ctx->radial_transition_outer->get_material()->set_shader_program(ctx->resource_manager->load<gl::shader_program>("radial-transition-outer.glsl"));
  708. //ctx->ui_scene->add_object(ctx->radial_transition_outer->get_billboard());
  709. //ctx->animator->add_animation(ctx->radial_transition_outer->get_animation());
  710. // Create camera flash animation
  711. ctx->camera_flash_animation = new animation<float>();
  712. {
  713. ctx->camera_flash_animation->set_interpolator(ease<float>::out_sine);
  714. const float duration = 0.5f;
  715. animation_channel<float>* channel = ctx->camera_flash_animation->add_channel(0);
  716. channel->insert_keyframe({0.0f, 1.0f});
  717. channel->insert_keyframe({duration, 0.0f});
  718. }
  719. }
  720. void setup_entities(game::context* ctx)
  721. {
  722. // Create entity registry
  723. ctx->entity_registry = new entt::registry();
  724. }
  725. void setup_systems(game::context* ctx)
  726. {
  727. event_dispatcher* event_dispatcher = ctx->app->get_event_dispatcher();
  728. const auto& viewport_dimensions = ctx->app->get_viewport_dimensions();
  729. float4 viewport = {0.0f, 0.0f, static_cast<float>(viewport_dimensions[0]), static_cast<float>(viewport_dimensions[1])};
  730. // RGB wavelengths determined by matching wavelengths to XYZ, transforming XYZ to ACEScg, then selecting the max wavelengths for R, G, and B.
  731. const double3 rgb_wavelengths_nm = {602.224, 541.069, 448.143};
  732. // Setup terrain system
  733. ctx->terrain_system = new entity::system::terrain(*ctx->entity_registry);
  734. ctx->terrain_system->set_patch_subdivisions(30);
  735. ctx->terrain_system->set_patch_scene_collection(ctx->surface_scene);
  736. ctx->terrain_system->set_max_error(200.0);
  737. // Setup vegetation system
  738. //ctx->vegetation_system = new entity::system::vegetation(*ctx->entity_registry);
  739. //ctx->vegetation_system->set_terrain_patch_size(TERRAIN_PATCH_SIZE);
  740. //ctx->vegetation_system->set_vegetation_patch_resolution(VEGETATION_PATCH_RESOLUTION);
  741. //ctx->vegetation_system->set_vegetation_density(1.0f);
  742. //ctx->vegetation_system->set_vegetation_model(ctx->resource_manager->load<model>("grass-tuft.mdl"));
  743. //ctx->vegetation_system->set_scene(ctx->surface_scene);
  744. // Setup camera system
  745. ctx->camera_system = new entity::system::camera(*ctx->entity_registry);
  746. ctx->camera_system->set_viewport(viewport);
  747. event_dispatcher->subscribe<window_resized_event>(ctx->camera_system);
  748. // Setup subterrain system
  749. ctx->subterrain_system = new entity::system::subterrain(*ctx->entity_registry, ctx->resource_manager);
  750. ctx->subterrain_system->set_scene(ctx->underground_scene);
  751. // Setup collision system
  752. ctx->collision_system = new entity::system::collision(*ctx->entity_registry);
  753. // Setup samara system
  754. ctx->samara_system = new entity::system::samara(*ctx->entity_registry);
  755. // Setup snapping system
  756. ctx->snapping_system = new entity::system::snapping(*ctx->entity_registry);
  757. // Setup behavior system
  758. ctx->behavior_system = new entity::system::behavior(*ctx->entity_registry);
  759. // Setup locomotion system
  760. ctx->locomotion_system = new entity::system::locomotion(*ctx->entity_registry);
  761. // Setup spatial system
  762. ctx->spatial_system = new entity::system::spatial(*ctx->entity_registry);
  763. // Setup constraint system
  764. ctx->constraint_system = new entity::system::constraint(*ctx->entity_registry);
  765. // Setup painting system
  766. ctx->painting_system = new entity::system::painting(*ctx->entity_registry, event_dispatcher, ctx->resource_manager);
  767. ctx->painting_system->set_scene(ctx->surface_scene);
  768. // Setup orbit system
  769. ctx->orbit_system = new entity::system::orbit(*ctx->entity_registry);
  770. // Setup blackbody system
  771. ctx->blackbody_system = new entity::system::blackbody(*ctx->entity_registry);
  772. ctx->blackbody_system->set_rgb_wavelengths(rgb_wavelengths_nm);
  773. // Setup atmosphere system
  774. ctx->atmosphere_system = new entity::system::atmosphere(*ctx->entity_registry);
  775. ctx->atmosphere_system->set_rgb_wavelengths(rgb_wavelengths_nm);
  776. // Setup astronomy system
  777. ctx->astronomy_system = new entity::system::astronomy(*ctx->entity_registry);
  778. ctx->astronomy_system->set_sky_pass(ctx->surface_sky_pass);
  779. // Setup proteome system
  780. ctx->proteome_system = new entity::system::proteome(*ctx->entity_registry);
  781. // Set time scale
  782. double time_scale = 60.0;
  783. if (ctx->config->contains("time_scale"))
  784. {
  785. time_scale = (*ctx->config)["time_scale"].get<double>();
  786. }
  787. ctx->orbit_system->set_time_scale(time_scale / seconds_per_day);
  788. ctx->astronomy_system->set_time_scale(time_scale / seconds_per_day);
  789. // Setup render system
  790. ctx->render_system = new entity::system::render(*ctx->entity_registry);
  791. ctx->render_system->add_layer(ctx->underground_scene);
  792. ctx->render_system->add_layer(ctx->surface_scene);
  793. ctx->render_system->add_layer(ctx->ui_scene);
  794. ctx->render_system->set_renderer(ctx->renderer);
  795. }
  796. void setup_controls(game::context* ctx)
  797. {
  798. event_dispatcher* event_dispatcher = ctx->app->get_event_dispatcher();
  799. // Setup input event routing
  800. ctx->input_event_router = new input::event_router();
  801. ctx->input_event_router->set_event_dispatcher(event_dispatcher);
  802. // Setup input mapper
  803. ctx->input_mapper = new input::mapper();
  804. ctx->input_mapper->set_event_dispatcher(event_dispatcher);
  805. // Setup input listener
  806. ctx->input_listener = new input::listener();
  807. ctx->input_listener->set_event_dispatcher(event_dispatcher);
  808. // Load SDL game controller mappings database
  809. ctx->logger->push_task("Loading SDL game controller mappings from database");
  810. file_buffer* game_controller_db = ctx->resource_manager->load<file_buffer>("gamecontrollerdb.txt");
  811. if (!game_controller_db)
  812. {
  813. ctx->logger->pop_task(EXIT_FAILURE);
  814. }
  815. else
  816. {
  817. ctx->app->add_game_controller_mappings(game_controller_db->data(), game_controller_db->size());
  818. ctx->resource_manager->unload("gamecontrollerdb.txt");
  819. ctx->logger->pop_task(EXIT_SUCCESS);
  820. }
  821. }
  822. void setup_cli(game::context* ctx)
  823. {
  824. ctx->cli = new debug::cli();
  825. ctx->cli->register_command("echo", debug::cc::echo);
  826. ctx->cli->register_command("exit", std::function<std::string()>(std::bind(&debug::cc::exit, ctx)));
  827. ctx->cli->register_command("scrot", std::function<std::string()>(std::bind(&debug::cc::scrot, ctx)));
  828. ctx->cli->register_command("cue", std::function<std::string(float, std::string)>(std::bind(&debug::cc::cue, ctx, std::placeholders::_1, std::placeholders::_2)));
  829. //std::string cmd = "cue 20 exit";
  830. //logger->log(cmd);
  831. //logger->log(cli.interpret(cmd));
  832. }
  833. void setup_callbacks(game::context* ctx)
  834. {
  835. // Set update callback
  836. ctx->app->set_update_callback
  837. (
  838. [ctx](double t, double dt)
  839. {
  840. // Update controls
  841. for (const auto& control: ctx->controls)
  842. control.second->update();
  843. // Update processes
  844. std::for_each
  845. (
  846. std::execution::par,
  847. ctx->processes.begin(),
  848. ctx->processes.end(),
  849. [t, dt](const auto& process)
  850. {
  851. process.second(t, dt);
  852. }
  853. );
  854. // Update tweens
  855. ctx->surface_sky_pass->update_tweens();
  856. ctx->surface_scene->update_tweens();
  857. ctx->underground_scene->update_tweens();
  858. ctx->ui_scene->update_tweens();
  859. ctx->timeline->advance(dt);
  860. ctx->terrain_system->update(t, dt);
  861. //ctx->vegetation_system->update(t, dt);
  862. ctx->snapping_system->update(t, dt);
  863. ctx->subterrain_system->update(t, dt);
  864. ctx->collision_system->update(t, dt);
  865. ctx->samara_system->update(t, dt);
  866. ctx->behavior_system->update(t, dt);
  867. ctx->locomotion_system->update(t, dt);
  868. ctx->camera_system->update(t, dt);
  869. ctx->orbit_system->update(t, dt);
  870. ctx->blackbody_system->update(t, dt);
  871. ctx->atmosphere_system->update(t, dt);
  872. ctx->astronomy_system->update(t, dt);
  873. ctx->spatial_system->update(t, dt);
  874. ctx->constraint_system->update(t, dt);
  875. ctx->painting_system->update(t, dt);
  876. ctx->proteome_system->update(t, dt);
  877. ctx->render_system->update(t, dt);
  878. ctx->animator->animate(dt);
  879. }
  880. );
  881. // Set render callback
  882. ctx->app->set_render_callback
  883. (
  884. [ctx](double alpha)
  885. {
  886. ctx->render_system->draw(alpha);
  887. }
  888. );
  889. }
  890. } // namespace boot
  891. } // namespace state
  892. } // namespace game