device.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. /*
  2. * Copyright (c) 2012-2024 Daniele Bartolini et al.
  3. * SPDX-License-Identifier: MIT
  4. */
  5. #include "config.h"
  6. #include "core/containers/array.inl"
  7. #include "core/filesystem/file.h"
  8. #include "core/filesystem/filesystem.h"
  9. #include "core/filesystem/filesystem_apk.h"
  10. #include "core/filesystem/filesystem_disk.h"
  11. #include "core/json/json_object.inl"
  12. #include "core/json/sjson.h"
  13. #include "core/list.inl"
  14. #include "core/math/constants.h"
  15. #include "core/math/matrix4x4.inl"
  16. #include "core/math/vector3.inl"
  17. #include "core/memory/globals.h"
  18. #include "core/memory/proxy_allocator.h"
  19. #include "core/memory/temp_allocator.inl"
  20. #include "core/network/ip_address.h"
  21. #include "core/network/socket.h"
  22. #include "core/option.inl"
  23. #include "core/os.h"
  24. #include "core/strings/dynamic_string.inl"
  25. #include "core/strings/string.inl"
  26. #include "core/strings/string_id.inl"
  27. #include "core/strings/string_stream.inl"
  28. #include "core/time.h"
  29. #include "core/types.h"
  30. #include "device/console_server.h"
  31. #include "device/device.h"
  32. #include "device/graph.h"
  33. #include "device/input_device.h"
  34. #include "device/input_manager.h"
  35. #include "device/log.h"
  36. #include "device/pipeline.h"
  37. #include "device/profiler.h"
  38. #include "lua/lua_environment.h"
  39. #include "lua/lua_stack.inl"
  40. #include "resource/config_resource.h"
  41. #include "resource/font_resource.h"
  42. #include "resource/level_resource.h"
  43. #include "resource/lua_resource.h"
  44. #include "resource/material_resource.h"
  45. #include "resource/mesh_resource.h"
  46. #include "resource/package_resource.h"
  47. #include "resource/physics_resource.h"
  48. #include "resource/resource_id.inl"
  49. #include "resource/resource_loader.h"
  50. #include "resource/resource_manager.h"
  51. #include "resource/resource_package.h"
  52. #include "resource/shader_resource.h"
  53. #include "resource/sound_resource.h"
  54. #include "resource/sprite_resource.h"
  55. #include "resource/state_machine_resource.h"
  56. #include "resource/texture_resource.h"
  57. #include "resource/unit_resource.h"
  58. #include "world/audio.h"
  59. #include "world/material_manager.h"
  60. #include "world/physics.h"
  61. #include "world/shader_manager.h"
  62. #include "world/unit_manager.h"
  63. #include "world/world.h"
  64. #include <bgfx/bgfx.h>
  65. #include <bimg/bimg.h>
  66. #include <bx/allocator.h>
  67. #include <bx/error.h>
  68. #include <bx/error.h>
  69. #include <bx/file.h>
  70. #include <bx/math.h>
  71. #if CROWN_PLATFORM_EMSCRIPTEN
  72. #include <emscripten/emscripten.h>
  73. #endif
  74. #define CROWN_MAX_SUBSYSTEMS_HEAP (8*1024*1024)
  75. LOG_SYSTEM(DEVICE, "device")
  76. namespace crown
  77. {
  78. extern bool next_event(OsEvent &ev);
  79. struct BgfxCallback : public bgfx::CallbackI
  80. {
  81. DynamicString _screenshot_path;
  82. std::atomic_int _screenshot_ready;
  83. explicit BgfxCallback(Allocator &a)
  84. : _screenshot_path(a)
  85. , _screenshot_ready(0)
  86. {
  87. }
  88. virtual void fatal(const char *_filePath, uint16_t _line, bgfx::Fatal::Enum _code, const char *_str) override
  89. {
  90. CE_UNUSED_4(_filePath, _line, _code, _str);
  91. CE_ASSERT(false, "Fatal error: 0x%08x: %s", _code, _str);
  92. }
  93. virtual void traceVargs(const char *_filePath, u16 _line, const char *_format, va_list _argList) override
  94. {
  95. CE_UNUSED_2(_filePath, _line);
  96. char buf[2048];
  97. strncpy(buf, _format, sizeof(buf) - 1);
  98. buf[strlen32(buf) - 1] = '\0'; // Remove trailing newline
  99. vlogi(DEVICE, buf, _argList);
  100. }
  101. virtual void profilerBegin(const char *_name, uint32_t _abgr, const char *_filePath, uint16_t _line) override
  102. {
  103. CE_UNUSED_4(_name, _abgr, _filePath, _line);
  104. }
  105. virtual void profilerBeginLiteral(const char *_name, uint32_t _abgr, const char *_filePath, uint16_t _line) override
  106. {
  107. CE_UNUSED_4(_name, _abgr, _filePath, _line);
  108. }
  109. virtual void profilerEnd() override
  110. {
  111. }
  112. virtual u32 cacheReadSize(u64 _id) override
  113. {
  114. CE_UNUSED(_id);
  115. return 0;
  116. }
  117. virtual bool cacheRead(u64 _id, void *_data, u32 _size) override
  118. {
  119. CE_UNUSED_3(_id, _data, _size);
  120. return false;
  121. }
  122. virtual void cacheWrite(u64 _id, const void *_data, u32 _size) override
  123. {
  124. CE_UNUSED_3(_id, _data, _size);
  125. }
  126. virtual void screenShot(const char *_filePath, u32 _width, u32 _height, u32 _pitch, const void *_data, u32 _size, bool _yflip) override
  127. {
  128. CE_UNUSED(_size);
  129. bx::Error err;
  130. bx::FileWriter writer;
  131. if (bx::open(&writer, _filePath, false, &err)) {
  132. bimg::imageWritePng(&writer
  133. , _width
  134. , _height
  135. , _pitch
  136. , _data
  137. , bimg::TextureFormat::BGRA8
  138. , _yflip
  139. , &err
  140. );
  141. bx::close(&writer);
  142. }
  143. _screenshot_path = _filePath;
  144. _screenshot_ready = 1;
  145. ++device()->_needs_draw; // 1 frame for _screenshot_ready to be evaluated.
  146. }
  147. virtual void captureBegin(u32 _width, u32 _height, u32 _pitch, bgfx::TextureFormat::Enum _format, bool _yflip) override
  148. {
  149. CE_UNUSED_5(_width, _height, _pitch, _format, _yflip);
  150. }
  151. virtual void captureEnd() override
  152. {
  153. }
  154. virtual void captureFrame(const void *_data, u32 _size) override
  155. {
  156. CE_UNUSED_2(_data, _size);
  157. }
  158. };
  159. struct BgfxAllocator : public bx::AllocatorI
  160. {
  161. ProxyAllocator _allocator;
  162. explicit BgfxAllocator(Allocator &a)
  163. : _allocator(a, "bgfx")
  164. {
  165. }
  166. ~BgfxAllocator()
  167. {
  168. }
  169. virtual void *realloc(void *_ptr, size_t _size, size_t _align, const char * /*_file*/, u32 /*_line*/)
  170. {
  171. return _allocator.reallocate(_ptr, _size, _align);
  172. }
  173. };
  174. static void device_command_pause(ConsoleServer & /*cs*/, u32 /*client_id*/, const JsonArray & /*args*/, void * /*user_data*/)
  175. {
  176. device()->pause();
  177. }
  178. static void device_command_unpause(ConsoleServer & /*cs*/, u32 /*client_id*/, const JsonArray & /*args*/, void * /*user_data*/)
  179. {
  180. device()->unpause();
  181. }
  182. static void device_command_game(ConsoleServer &cs, u32 client_id, const JsonArray &args, void *user_data)
  183. {
  184. CE_UNUSED(user_data);
  185. TempAllocator1024 ta;
  186. if (array::size(args) < 2) {
  187. cs.error(client_id, "Usage: game <pause|resume>");
  188. return;
  189. }
  190. DynamicString subcmd(ta);
  191. sjson::parse_string(subcmd, args[1]);
  192. if (subcmd == "pause") {
  193. device()->pause();
  194. } else if (subcmd == "resume") {
  195. device()->unpause();
  196. } else {
  197. loge(DEVICE, "Unknown game parameter");
  198. }
  199. }
  200. static void device_message_resize(ConsoleServer & /*cs*/, u32 /*client_id*/, const char *json, void * /*user_data*/)
  201. {
  202. TempAllocator256 ta;
  203. JsonObject obj(ta);
  204. s32 width;
  205. s32 height;
  206. sjson::parse(obj, json);
  207. width = sjson::parse_int(obj["width"]);
  208. height = sjson::parse_int(obj["height"]);
  209. device()->_window->resize((u16)width, (u16)height);
  210. }
  211. static void device_message_frame(ConsoleServer & /*cs*/, u32 /*client_id*/, const char * /*json*/, void *user_data)
  212. {
  213. ++((Device *)user_data)->_needs_draw;
  214. }
  215. static void device_message_quit(ConsoleServer &cs, u32 client_id, const char *json, void *user_data)
  216. {
  217. CE_UNUSED_3(cs, client_id, json);
  218. ((Device *)user_data)->quit();
  219. }
  220. static void device_message_refresh(ConsoleServer &cs, u32 client_id, const char *json, void *user_data)
  221. {
  222. CE_UNUSED_2(cs, client_id);
  223. ((Device *)user_data)->refresh(json);
  224. TempAllocator512 ta;
  225. StringStream ss(ta);
  226. ss << "{";
  227. ss << "\"type\":\"refresh\",";
  228. ss << "\"success\":" << (true ? "true" : "false");
  229. ss << "}";
  230. cs.send(client_id, string_stream::c_str(ss));
  231. }
  232. Device::Device(const DeviceOptions &opts, ConsoleServer &cs)
  233. : _allocator(default_allocator(), CROWN_MAX_SUBSYSTEMS_HEAP)
  234. , _options(opts)
  235. , _boot_config(default_allocator())
  236. , _console_server(&cs)
  237. , _data_filesystem(NULL)
  238. , _resource_loader(NULL)
  239. , _resource_manager(NULL)
  240. , _bgfx_allocator(NULL)
  241. , _bgfx_callback(NULL)
  242. , _shader_manager(NULL)
  243. , _material_manager(NULL)
  244. , _input_manager(NULL)
  245. , _unit_manager(NULL)
  246. , _lua_environment(NULL)
  247. , _pipeline(NULL)
  248. , _display(NULL)
  249. , _window(NULL)
  250. , _width(CROWN_DEFAULT_WINDOW_WIDTH)
  251. , _height(CROWN_DEFAULT_WINDOW_HEIGHT)
  252. , _quit(false)
  253. , _paused(false)
  254. , _needs_draw(1)
  255. {
  256. list::init_head(_worlds);
  257. }
  258. bool Device::process_events()
  259. {
  260. bool exit = false;
  261. OsEvent event;
  262. while (next_event(event)) {
  263. switch (event.type) {
  264. case OsEventType::BUTTON:
  265. case OsEventType::AXIS:
  266. case OsEventType::STATUS:
  267. _input_manager->read(event);
  268. break;
  269. case OsEventType::RESOLUTION:
  270. _width = event.resolution.width;
  271. _height = event.resolution.height;
  272. break;
  273. case OsEventType::EXIT:
  274. exit = true;
  275. break;
  276. case OsEventType::PAUSE:
  277. pause();
  278. break;
  279. case OsEventType::RESUME:
  280. unpause();
  281. break;
  282. case OsEventType::TEXT:
  283. break;
  284. default:
  285. CE_FATAL("Unknown OS event");
  286. break;
  287. }
  288. }
  289. return exit;
  290. }
  291. bool Device::frame()
  292. {
  293. if (CE_UNLIKELY(process_events() || _quit))
  294. return true;
  295. const s64 time = time::now();
  296. const f32 dt = f32(time::seconds(time - _last_time));
  297. _last_time = time;
  298. profiler_globals::clear();
  299. if (CE_UNLIKELY(_width != _prev_width || _height != _prev_height)) {
  300. _prev_width = _width;
  301. _prev_height = _height;
  302. bgfx::reset(_width, _height, (_boot_config.vsync ? BGFX_RESET_VSYNC : BGFX_RESET_NONE));
  303. _pipeline->reset(_width, _height);
  304. // Force pipeline reset in one cycle.
  305. bgfx::frame();
  306. bgfx::frame();
  307. // Force redraw.
  308. ++_needs_draw;
  309. }
  310. // Only block if redraw is not needed.
  311. const bool sync = !_needs_draw;
  312. #if !CROWN_PLATFORM_EMSCRIPTEN
  313. _console_server->execute_message_handlers(sync);
  314. #endif
  315. RECORD_FLOAT("device.dt", dt);
  316. RECORD_FLOAT("device.fps", 1.0f/dt);
  317. if (CE_UNLIKELY(!_needs_draw))
  318. return false;
  319. if (CE_LIKELY(!_paused)) {
  320. _resource_manager->complete_requests();
  321. {
  322. const s64 t0 = time::now();
  323. LuaStack stack(_lua_environment->L);
  324. stack.push_float(dt);
  325. _lua_environment->call_global("update", 1);
  326. RECORD_FLOAT("lua.update", f32(time::seconds(time::now() - t0)));
  327. }
  328. {
  329. const s64 t0 = time::now();
  330. LuaStack stack(_lua_environment->L);
  331. stack.push_float(dt);
  332. _lua_environment->call_global("render", 1);
  333. RECORD_FLOAT("lua.render", f32(time::seconds(time::now() - t0)));
  334. }
  335. if (_bgfx_callback->_screenshot_ready) {
  336. _bgfx_callback->_screenshot_ready = 0;
  337. LuaStack stack(_lua_environment->L);
  338. stack.push_string(_bgfx_callback->_screenshot_path.c_str());
  339. _lua_environment->call_global("screenshot", 1);
  340. }
  341. }
  342. _lua_environment->reset_temporaries();
  343. _input_manager->update();
  344. const bgfx::Stats *stats = bgfx::getStats();
  345. RECORD_FLOAT("bgfx.gpu_time", f32(f64(stats->gpuTimeEnd - stats->gpuTimeBegin)/stats->gpuTimerFreq));
  346. RECORD_FLOAT("bgfx.cpu_time", f32(f64(stats->cpuTimeEnd - stats->cpuTimeBegin)/stats->cpuTimerFreq));
  347. profiler_globals::flush();
  348. graph_globals::draw_all(_width, _height);
  349. _pipeline->render(*_shader_manager, STRING_ID_32("blit", UINT32_C(0x045f02bb)), VIEW_BLIT, _width, _height);
  350. bgfx::frame();
  351. if (_needs_draw-- == 1)
  352. _needs_draw = (int)!_options._pumped;
  353. return false;
  354. }
  355. void Device::run()
  356. {
  357. s64 run_t0 = time::now();
  358. _console_server->register_command_name("pause", "Pause the engine.", device_command_pause, this);
  359. _console_server->register_command_name("unpause", "Resume the engine.", device_command_unpause, this);
  360. _console_server->register_command_name("game", "Pause/resume the engine.", device_command_game, this);
  361. _console_server->register_message_type("resize", device_message_resize, this);
  362. _console_server->register_message_type("frame", device_message_frame, this);
  363. _console_server->register_message_type("quit", device_message_quit, this);
  364. _console_server->register_message_type("refresh", device_message_refresh, this);
  365. #if !CROWN_PLATFORM_EMSCRIPTEN
  366. _console_server->listen(_options._console_port, _options._wait_console);
  367. #endif
  368. bool is_bundle = true;
  369. #if CROWN_PLATFORM_ANDROID
  370. _data_filesystem = CE_NEW(_allocator, FilesystemApk)(default_allocator(), const_cast<AAssetManager *>((AAssetManager *)_options._asset_manager));
  371. #else
  372. _data_filesystem = CE_NEW(_allocator, FilesystemDisk)(default_allocator());
  373. {
  374. char cwd[1024];
  375. const char *data_dir = NULL;
  376. if (_options._bundle_dir.empty() && _options._data_dir.empty()) {
  377. data_dir = os::getcwd(cwd, sizeof(cwd));
  378. } else {
  379. if (!_options._bundle_dir.empty()) {
  380. data_dir = _options._bundle_dir.c_str();
  381. } else {
  382. is_bundle = false;
  383. if (!_options._data_dir.empty())
  384. data_dir = _options._data_dir.c_str();
  385. else
  386. data_dir = os::getcwd(cwd, sizeof(cwd));
  387. }
  388. }
  389. ((FilesystemDisk *)_data_filesystem)->set_prefix(data_dir);
  390. }
  391. #endif // if CROWN_PLATFORM_ANDROID
  392. logi(DEVICE, "Crown %s %s %s", CROWN_VERSION, CROWN_PLATFORM_NAME, CROWN_ARCH_NAME);
  393. profiler_globals::init();
  394. _shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
  395. namespace smr = state_machine_internal;
  396. namespace cor = config_resource_internal;
  397. namespace ftr = font_resource_internal;
  398. namespace lur = lua_resource_internal;
  399. namespace lvr = level_resource_internal;
  400. namespace mhr = mesh_resource_internal;
  401. namespace mtr = material_resource_internal;
  402. namespace pcr = physics_config_resource_internal;
  403. namespace pkr = package_resource_internal;
  404. namespace sar = sprite_animation_resource_internal;
  405. namespace sdr = sound_resource_internal;
  406. namespace shr = shader_resource_internal;
  407. namespace spr = sprite_resource_internal;
  408. namespace txr = texture_resource_internal;
  409. namespace utr = unit_resource_internal;
  410. _resource_loader = CE_NEW(_allocator, ResourceLoader)(*_data_filesystem, is_bundle);
  411. _resource_loader->register_fallback(RESOURCE_TYPE_TEXTURE, STRING_ID_64("core/fallback/fallback", 0xd09058ae71962248));
  412. _resource_loader->register_fallback(RESOURCE_TYPE_MATERIAL, STRING_ID_64("core/fallback/fallback", 0xd09058ae71962248));
  413. _resource_loader->register_fallback(RESOURCE_TYPE_UNIT, STRING_ID_64("core/fallback/fallback", 0xd09058ae71962248));
  414. _resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);
  415. _resource_manager->register_type(RESOURCE_TYPE_CONFIG, RESOURCE_VERSION_CONFIG, cor::load, cor::unload, NULL, NULL);
  416. _resource_manager->register_type(RESOURCE_TYPE_FONT, RESOURCE_VERSION_FONT, NULL, NULL, NULL, NULL);
  417. _resource_manager->register_type(RESOURCE_TYPE_LEVEL, RESOURCE_VERSION_LEVEL, NULL, NULL, NULL, NULL);
  418. _resource_manager->register_type(RESOURCE_TYPE_MATERIAL, RESOURCE_VERSION_MATERIAL, NULL, NULL, mtr::online, mtr::offline);
  419. _resource_manager->register_type(RESOURCE_TYPE_MESH, RESOURCE_VERSION_MESH, mhr::load, mhr::unload, mhr::online, mhr::offline);
  420. _resource_manager->register_type(RESOURCE_TYPE_PACKAGE, RESOURCE_VERSION_PACKAGE, NULL, NULL, NULL, NULL);
  421. _resource_manager->register_type(RESOURCE_TYPE_PHYSICS_CONFIG, RESOURCE_VERSION_PHYSICS_CONFIG, NULL, NULL, NULL, NULL);
  422. _resource_manager->register_type(RESOURCE_TYPE_SCRIPT, RESOURCE_VERSION_SCRIPT, NULL, NULL, NULL, NULL);
  423. _resource_manager->register_type(RESOURCE_TYPE_SHADER, RESOURCE_VERSION_SHADER, shr::load, shr::unload, shr::online, shr::offline);
  424. _resource_manager->register_type(RESOURCE_TYPE_SOUND, RESOURCE_VERSION_SOUND, NULL, NULL, NULL, NULL);
  425. _resource_manager->register_type(RESOURCE_TYPE_SPRITE, RESOURCE_VERSION_SPRITE, NULL, NULL, NULL, NULL);
  426. _resource_manager->register_type(RESOURCE_TYPE_SPRITE_ANIMATION, RESOURCE_VERSION_SPRITE_ANIMATION, NULL, NULL, NULL, NULL);
  427. _resource_manager->register_type(RESOURCE_TYPE_STATE_MACHINE, RESOURCE_VERSION_STATE_MACHINE, NULL, NULL, NULL, NULL);
  428. _resource_manager->register_type(RESOURCE_TYPE_TEXTURE, RESOURCE_VERSION_TEXTURE, txr::load, txr::unload, txr::online, txr::offline);
  429. _resource_manager->register_type(RESOURCE_TYPE_UNIT, RESOURCE_VERSION_UNIT, NULL, NULL, NULL, NULL);
  430. _material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager);
  431. // Read config
  432. {
  433. TempAllocator512 ta;
  434. DynamicString boot_dir(ta);
  435. if (_options._boot_dir != NULL) {
  436. boot_dir += _options._boot_dir;
  437. boot_dir += '/';
  438. }
  439. boot_dir += CROWN_BOOT_CONFIG;
  440. const StringId64 config_name(boot_dir.c_str());
  441. while (!_resource_manager->try_load(PACKAGE_RESOURCE_NONE, RESOURCE_TYPE_CONFIG, config_name, 0)) {
  442. _resource_manager->complete_requests();
  443. #if CROWN_PLATFORM_EMSCRIPTEN
  444. os::sleep(16);
  445. #endif
  446. }
  447. while (!_resource_manager->can_get(RESOURCE_TYPE_CONFIG, config_name)) {
  448. _resource_manager->complete_requests();
  449. #if CROWN_PLATFORM_EMSCRIPTEN
  450. os::sleep(16);
  451. #endif
  452. }
  453. _boot_config.parse((const char *)_resource_manager->get(RESOURCE_TYPE_CONFIG, config_name));
  454. _resource_manager->unload(RESOURCE_TYPE_CONFIG, config_name);
  455. }
  456. // Init all remaining subsystems
  457. _display = display::create(_allocator);
  458. #if !CROWN_PLATFORM_EMSCRIPTEN
  459. if (_options._window_width.has_changed() || _options._window_height.has_changed()) {
  460. _width = _options._window_width.value();
  461. _height = _options._window_height.value();
  462. } else {
  463. _width = _boot_config.window_w;
  464. _height = _boot_config.window_h;
  465. }
  466. #endif
  467. _window = window::create(_allocator);
  468. _window->open(_options._window_x
  469. , _options._window_y
  470. , _width
  471. , _height
  472. , _options._parent_window
  473. );
  474. _window->set_title(_boot_config.window_title.c_str());
  475. _window->set_fullscreen(_boot_config.fullscreen);
  476. if (!_options._hidden)
  477. _window->show();
  478. _bgfx_allocator = CE_NEW(_allocator, BgfxAllocator)(default_allocator());
  479. _bgfx_callback = CE_NEW(_allocator, BgfxCallback)(default_allocator());
  480. bgfx::Init init;
  481. init.resolution.width = _width;
  482. init.resolution.height = _height;
  483. init.resolution.reset = _boot_config.vsync ? BGFX_RESET_VSYNC : BGFX_RESET_NONE;
  484. init.callback = _bgfx_callback;
  485. init.allocator = _bgfx_allocator;
  486. init.platformData.ndt = _window->native_display();
  487. init.platformData.nwh = _window->native_handle();
  488. init.vendorId = BGFX_PCI_ID_NONE;
  489. #if CROWN_PLATFORM_ANDROID || CROWN_PLATFORM_EMSCRIPTEN
  490. init.type = bgfx::RendererType::OpenGLES;
  491. #elif CROWN_PLATFORM_LINUX
  492. init.type = bgfx::RendererType::OpenGL;
  493. #elif CROWN_PLATFORM_WINDOWS
  494. init.type = bgfx::RendererType::Direct3D11;
  495. #else
  496. #error "Unknown platform"
  497. #endif
  498. bgfx::init(init);
  499. _input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
  500. _unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());
  501. _lua_environment = CE_NEW(_allocator, LuaEnvironment)();
  502. _lua_environment->register_console_commands(*_console_server);
  503. audio_globals::init();
  504. physics_globals::init(_allocator);
  505. ResourcePackage *boot_package = create_resource_package(_boot_config.boot_package_name);
  506. boot_package->load();
  507. boot_package->flush();
  508. _lua_environment->load_libs();
  509. _lua_environment->require(_boot_config.boot_script_name.c_str());
  510. _lua_environment->execute_string(_options._lua_string.c_str());
  511. _pipeline = CE_NEW(_allocator, Pipeline)();
  512. _pipeline->create(_width, _height);
  513. graph_globals::init(_allocator, *_shader_manager, *_console_server);
  514. logi(DEVICE, "Initialized in " TIME_FMT, time::seconds(time::now() - run_t0));
  515. _lua_environment->call_global("init");
  516. _prev_width = _width;
  517. _prev_height = _height;
  518. _last_time = time::now();
  519. #if CROWN_PLATFORM_EMSCRIPTEN
  520. emscripten_set_main_loop_arg([](void *thiz) { ((Device *)thiz)->frame(); }, this, 0, -1);
  521. #else
  522. while (!frame()) { }
  523. #endif
  524. _lua_environment->call_global("shutdown");
  525. boot_package->unload();
  526. destroy_resource_package(*boot_package);
  527. physics_globals::shutdown(_allocator);
  528. audio_globals::shutdown();
  529. graph_globals::shutdown();
  530. _pipeline->destroy();
  531. CE_DELETE(_allocator, _pipeline);
  532. CE_DELETE(_allocator, _lua_environment);
  533. CE_DELETE(_allocator, _unit_manager);
  534. CE_DELETE(_allocator, _input_manager);
  535. CE_DELETE(_allocator, _resource_manager);
  536. CE_DELETE(_allocator, _resource_loader);
  537. CE_DELETE(_allocator, _material_manager);
  538. CE_DELETE(_allocator, _shader_manager);
  539. bgfx::shutdown();
  540. CE_DELETE(_allocator, _bgfx_callback);
  541. CE_DELETE(_allocator, _bgfx_allocator);
  542. _window->close();
  543. window::destroy(_allocator, *_window);
  544. display::destroy(_allocator, *_display);
  545. CE_DELETE(_allocator, _data_filesystem);
  546. profiler_globals::shutdown();
  547. _allocator.clear();
  548. }
  549. void Device::quit()
  550. {
  551. _quit = true;
  552. if (_console_server)
  553. _console_server->close();
  554. }
  555. int Device::argc() const
  556. {
  557. return _options._argc;
  558. }
  559. const char **Device::argv() const
  560. {
  561. return (const char **)_options._argv;
  562. }
  563. void Device::pause()
  564. {
  565. _paused = true;
  566. logi(DEVICE, "Paused");
  567. }
  568. void Device::unpause()
  569. {
  570. _paused = false;
  571. logi(DEVICE, "Unpaused");
  572. }
  573. void Device::resolution(u16 &width, u16 &height)
  574. {
  575. width = _width;
  576. height = _height;
  577. }
  578. void Device::render(World &world, UnitId camera_unit)
  579. {
  580. const f32 aspect_ratio = (_boot_config.aspect_ratio == -1.0f
  581. ? (f32)_width/(f32)_height
  582. : _boot_config.aspect_ratio
  583. );
  584. CameraInstance camera = world.camera_instance(camera_unit);
  585. world.camera_set_aspect(camera, aspect_ratio);
  586. world.camera_set_viewport_metrics(camera, 0, 0, _width, _height);
  587. const Matrix4x4 view = world.camera_view_matrix(camera);
  588. const Matrix4x4 proj = world.camera_projection_matrix(camera);
  589. const bgfx::Caps *caps = bgfx::getCaps();
  590. f32 bx_ortho[16];
  591. bx::mtxOrtho(bx_ortho, 0, _width, 0, _height, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  592. Matrix4x4 ortho_proj = from_array(bx_ortho);
  593. bgfx::setViewClear(VIEW_SPRITE_0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x080808ff, 1.0f, 0);
  594. bgfx::setViewClear(VIEW_SELECTION, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, UNIT_INVALID._idx, 1.0f, 0);
  595. bgfx::setViewTransform(VIEW_SPRITE_0, to_float_ptr(view), to_float_ptr(proj));
  596. bgfx::setViewTransform(VIEW_SPRITE_1, to_float_ptr(view), to_float_ptr(proj));
  597. bgfx::setViewTransform(VIEW_SPRITE_2, to_float_ptr(view), to_float_ptr(proj));
  598. bgfx::setViewTransform(VIEW_SPRITE_3, to_float_ptr(view), to_float_ptr(proj));
  599. bgfx::setViewTransform(VIEW_SPRITE_4, to_float_ptr(view), to_float_ptr(proj));
  600. bgfx::setViewTransform(VIEW_SPRITE_5, to_float_ptr(view), to_float_ptr(proj));
  601. bgfx::setViewTransform(VIEW_SPRITE_6, to_float_ptr(view), to_float_ptr(proj));
  602. bgfx::setViewTransform(VIEW_SPRITE_7, to_float_ptr(view), to_float_ptr(proj));
  603. bgfx::setViewTransform(VIEW_MESH, to_float_ptr(view), to_float_ptr(proj));
  604. bgfx::setViewTransform(VIEW_DEBUG, to_float_ptr(view), to_float_ptr(proj));
  605. bgfx::setViewTransform(VIEW_GUI, to_float_ptr(MATRIX4X4_IDENTITY), to_float_ptr(ortho_proj));
  606. bgfx::setViewTransform(VIEW_SELECTION, to_float_ptr(view), to_float_ptr(proj));
  607. f32 graph_ortho[16];
  608. bx::mtxOrtho(graph_ortho
  609. , -_width / 2.0f
  610. , _width / 2.0f
  611. , -_height / 2.0f
  612. , _height / 2.0f
  613. , 0.0f
  614. , 1.0f
  615. , 0.0f
  616. , caps->homogeneousDepth
  617. );
  618. bgfx::setViewTransform(VIEW_GRAPH, to_float_ptr(MATRIX4X4_IDENTITY), to_float_ptr(from_array(graph_ortho)));
  619. bgfx::setViewRect(VIEW_SPRITE_0, 0, 0, _width, _height);
  620. bgfx::setViewRect(VIEW_SPRITE_1, 0, 0, _width, _height);
  621. bgfx::setViewRect(VIEW_SPRITE_2, 0, 0, _width, _height);
  622. bgfx::setViewRect(VIEW_SPRITE_3, 0, 0, _width, _height);
  623. bgfx::setViewRect(VIEW_SPRITE_4, 0, 0, _width, _height);
  624. bgfx::setViewRect(VIEW_SPRITE_5, 0, 0, _width, _height);
  625. bgfx::setViewRect(VIEW_SPRITE_6, 0, 0, _width, _height);
  626. bgfx::setViewRect(VIEW_SPRITE_7, 0, 0, _width, _height);
  627. bgfx::setViewRect(VIEW_MESH, 0, 0, _width, _height);
  628. bgfx::setViewRect(VIEW_DEBUG, 0, 0, _width, _height);
  629. bgfx::setViewRect(VIEW_GUI, 0, 0, _width, _height);
  630. bgfx::setViewRect(VIEW_SELECTION, 0, 0, _width, _height);
  631. bgfx::setViewRect(VIEW_GRAPH, 0, 0, _width, _height);
  632. bgfx::setViewMode(VIEW_SPRITE_0, bgfx::ViewMode::DepthAscending);
  633. bgfx::setViewMode(VIEW_SPRITE_1, bgfx::ViewMode::DepthAscending);
  634. bgfx::setViewMode(VIEW_SPRITE_2, bgfx::ViewMode::DepthAscending);
  635. bgfx::setViewMode(VIEW_SPRITE_3, bgfx::ViewMode::DepthAscending);
  636. bgfx::setViewMode(VIEW_SPRITE_4, bgfx::ViewMode::DepthAscending);
  637. bgfx::setViewMode(VIEW_SPRITE_5, bgfx::ViewMode::DepthAscending);
  638. bgfx::setViewMode(VIEW_SPRITE_6, bgfx::ViewMode::DepthAscending);
  639. bgfx::setViewMode(VIEW_SPRITE_7, bgfx::ViewMode::DepthAscending);
  640. bgfx::setViewMode(VIEW_GUI, bgfx::ViewMode::Sequential);
  641. bgfx::setViewMode(VIEW_BLIT, bgfx::ViewMode::Sequential);
  642. bgfx::setViewFrameBuffer(VIEW_SPRITE_0, _pipeline->_main_frame_buffer);
  643. bgfx::setViewFrameBuffer(VIEW_SPRITE_1, _pipeline->_main_frame_buffer);
  644. bgfx::setViewFrameBuffer(VIEW_SPRITE_2, _pipeline->_main_frame_buffer);
  645. bgfx::setViewFrameBuffer(VIEW_SPRITE_3, _pipeline->_main_frame_buffer);
  646. bgfx::setViewFrameBuffer(VIEW_SPRITE_4, _pipeline->_main_frame_buffer);
  647. bgfx::setViewFrameBuffer(VIEW_SPRITE_5, _pipeline->_main_frame_buffer);
  648. bgfx::setViewFrameBuffer(VIEW_SPRITE_6, _pipeline->_main_frame_buffer);
  649. bgfx::setViewFrameBuffer(VIEW_SPRITE_7, _pipeline->_main_frame_buffer);
  650. bgfx::setViewFrameBuffer(VIEW_MESH, _pipeline->_main_frame_buffer);
  651. bgfx::setViewFrameBuffer(VIEW_DEBUG, _pipeline->_main_frame_buffer);
  652. bgfx::setViewFrameBuffer(VIEW_GUI, _pipeline->_main_frame_buffer);
  653. bgfx::setViewFrameBuffer(VIEW_SELECTION, _pipeline->_selection_frame_buffer);
  654. bgfx::setViewFrameBuffer(VIEW_GRAPH, _pipeline->_main_frame_buffer);
  655. bgfx::setViewFrameBuffer(VIEW_BLIT, BGFX_INVALID_HANDLE);
  656. bgfx::touch(VIEW_SPRITE_0);
  657. bgfx::touch(VIEW_SPRITE_1);
  658. bgfx::touch(VIEW_SPRITE_2);
  659. bgfx::touch(VIEW_SPRITE_3);
  660. bgfx::touch(VIEW_SPRITE_4);
  661. bgfx::touch(VIEW_SPRITE_5);
  662. bgfx::touch(VIEW_SPRITE_6);
  663. bgfx::touch(VIEW_SPRITE_7);
  664. bgfx::touch(VIEW_MESH);
  665. bgfx::touch(VIEW_DEBUG);
  666. bgfx::touch(VIEW_GUI);
  667. bgfx::touch(VIEW_SELECTION);
  668. bgfx::touch(VIEW_GRAPH);
  669. bgfx::touch(VIEW_BLIT);
  670. world.render(view);
  671. }
  672. World *Device::create_world()
  673. {
  674. World *world = CE_NEW(default_allocator(), World)(default_allocator()
  675. , *_resource_manager
  676. , *_shader_manager
  677. , *_material_manager
  678. , *_unit_manager
  679. , *_lua_environment
  680. );
  681. list::add(world->_node, _worlds);
  682. return world;
  683. }
  684. void Device::destroy_world(World &world)
  685. {
  686. list::remove(world._node);
  687. CE_DELETE(default_allocator(), &world);
  688. }
  689. ResourcePackage *Device::create_resource_package(StringId64 id)
  690. {
  691. return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
  692. }
  693. void Device::destroy_resource_package(ResourcePackage &rp)
  694. {
  695. CE_DELETE(default_allocator(), &rp);
  696. }
  697. void Device::refresh(const char *json)
  698. {
  699. #if CROWN_DEBUG
  700. TempAllocator4096 ta;
  701. JsonObject obj(ta);
  702. JsonArray list(ta);
  703. DynamicString type(ta);
  704. sjson::parse(obj, json);
  705. bool refresh_lua = false;
  706. sjson::parse_array(list, obj["list"]);
  707. for (u32 i = 0; i < array::size(list); ++i) {
  708. DynamicString resource(ta);
  709. sjson::parse_string(resource, list[i]);
  710. const char *type = resource_type(resource.c_str());
  711. const u32 len = resource_name_length(type, resource.c_str());
  712. StringId64 resource_type(type);
  713. StringId64 resource_name(resource.c_str(), len);
  714. _resource_manager->reload(resource_type, resource_name);
  715. if (resource_type == RESOURCE_TYPE_SCRIPT) {
  716. refresh_lua = true;
  717. }
  718. }
  719. if (array::size(list)) {
  720. if (refresh_lua)
  721. _lua_environment->reload();
  722. }
  723. if (_paused)
  724. unpause();
  725. #endif // if CROWN_DEBUG
  726. }
  727. void Device::screenshot(const char *path)
  728. {
  729. bgfx::requestScreenShot(BGFX_INVALID_HANDLE, path);
  730. ++device()->_needs_draw; // 1 frame for the request to be fulfilled.
  731. }
  732. Device *_device = NULL;
  733. void run(const DeviceOptions &opts)
  734. {
  735. CE_ASSERT(_device == NULL, "Crown already initialized");
  736. console_server_globals::init();
  737. _device = CE_NEW(default_allocator(), Device)(opts, *console_server());
  738. _device->run();
  739. CE_DELETE(default_allocator(), _device);
  740. _device = NULL;
  741. console_server_globals::shutdown();
  742. }
  743. Device *device()
  744. {
  745. return crown::_device;
  746. }
  747. } // namespace crown