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

1031 lines
37 KiB

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