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

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