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

989 lines
36 KiB

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