device.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. /*
  2. * Copyright (c) 2012-2025 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. error::abort("%s (code 0x%08x).\n", _str, _code);
  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_command_crash(ConsoleServer &cs, u32 client_id, const JsonArray &args, void *user_data)
  201. {
  202. CE_UNUSED(user_data);
  203. TempAllocator1024 ta;
  204. struct CrashType
  205. {
  206. enum Enum
  207. {
  208. DIVISION_BY_ZERO,
  209. UNALIGNED_ACCESS,
  210. SEGMENTATION_FAULT,
  211. OUT_OF_MEMORY,
  212. ASSERT,
  213. COUNT
  214. };
  215. };
  216. struct
  217. {
  218. const char *type;
  219. const char *desc;
  220. }
  221. crash_info[] =
  222. {
  223. { "div_by_zero", "Divide a number by zero." },
  224. { "unaligned", "Do an unaligned memory access." },
  225. { "segfault", "Trigger a segmentation fault." },
  226. { "oom", "Allocate too much memory." },
  227. { "assert", "Call CE_ASSERT(false)." }
  228. };
  229. CE_STATIC_ASSERT(countof(crash_info) == CrashType::COUNT);
  230. if (array::size(args) < 2) {
  231. cs.error(client_id, "Usage: crash <type>");
  232. return;
  233. }
  234. DynamicString subcmd(ta);
  235. sjson::parse_string(subcmd, args[1]);
  236. if (subcmd == crash_info[CrashType::DIVISION_BY_ZERO].type) {
  237. f32(time::now()) / 0.0f;
  238. } else if (subcmd == crash_info[CrashType::UNALIGNED_ACCESS].type) {
  239. CE_ALIGN_DECL(alignof(s64), u8 buf[16]);
  240. *((s64 *)&buf[1]) = time::now();
  241. } else if (subcmd == crash_info[CrashType::SEGMENTATION_FAULT].type) {
  242. *((s64 *)(uintptr_t)time::now()) = time::now();
  243. } else if (subcmd == crash_info[CrashType::OUT_OF_MEMORY].type) {
  244. while (s64 t = time::now())
  245. *((s64 *)malloc(1024*1024)) = t;
  246. } else if (subcmd == crash_info[CrashType::ASSERT].type) {
  247. CE_ASSERT(false, "False");
  248. } else if (subcmd == "help") {
  249. for (u32 i = 0; i < CrashType::COUNT; ++i) {
  250. logi(DEVICE, "%s %s", crash_info[i].type, crash_info[i].desc);
  251. }
  252. } else {
  253. loge(DEVICE, "Unknown crash parameter");
  254. }
  255. }
  256. static void device_message_resize(ConsoleServer & /*cs*/, u32 /*client_id*/, const char *json, void * /*user_data*/)
  257. {
  258. TempAllocator256 ta;
  259. JsonObject obj(ta);
  260. s32 width;
  261. s32 height;
  262. sjson::parse(obj, json);
  263. width = sjson::parse_int(obj["width"]);
  264. height = sjson::parse_int(obj["height"]);
  265. device()->_window->resize((u16)width, (u16)height);
  266. }
  267. static void device_message_frame(ConsoleServer & /*cs*/, u32 /*client_id*/, const char * /*json*/, void *user_data)
  268. {
  269. ++((Device *)user_data)->_needs_draw;
  270. }
  271. static void device_message_quit(ConsoleServer &cs, u32 client_id, const char *json, void *user_data)
  272. {
  273. CE_UNUSED_3(cs, client_id, json);
  274. ((Device *)user_data)->quit();
  275. }
  276. static void device_message_refresh(ConsoleServer &cs, u32 client_id, const char *json, void *user_data)
  277. {
  278. CE_UNUSED_2(cs, client_id);
  279. ((Device *)user_data)->refresh(json);
  280. TempAllocator512 ta;
  281. StringStream ss(ta);
  282. ss << "{";
  283. ss << "\"type\":\"refresh\",";
  284. ss << "\"success\":" << (true ? "true" : "false");
  285. ss << "}";
  286. cs.send(client_id, string_stream::c_str(ss));
  287. }
  288. Device::Device(const DeviceOptions &opts, ConsoleServer &cs)
  289. : _allocator(default_allocator(), CROWN_MAX_SUBSYSTEMS_HEAP)
  290. , _options(opts)
  291. , _boot_config(default_allocator())
  292. , _console_server(&cs)
  293. , _data_filesystem(NULL)
  294. , _resource_loader(NULL)
  295. , _resource_manager(NULL)
  296. , _bgfx_allocator(NULL)
  297. , _bgfx_callback(NULL)
  298. , _shader_manager(NULL)
  299. , _material_manager(NULL)
  300. , _input_manager(NULL)
  301. , _unit_manager(NULL)
  302. , _lua_environment(NULL)
  303. , _pipeline(NULL)
  304. , _display(NULL)
  305. , _window(NULL)
  306. , _timestep_policy(TimestepPolicy::VARIABLE)
  307. , _width(CROWN_DEFAULT_WINDOW_WIDTH)
  308. , _height(CROWN_DEFAULT_WINDOW_HEIGHT)
  309. , _quit(false)
  310. , _paused(false)
  311. , _needs_draw(1)
  312. {
  313. list::init_head(_worlds);
  314. }
  315. bool Device::process_events()
  316. {
  317. bool exit = false;
  318. OsEvent event;
  319. while (next_event(event)) {
  320. switch (event.type) {
  321. case OsEventType::BUTTON:
  322. case OsEventType::AXIS:
  323. case OsEventType::STATUS:
  324. _input_manager->read(event);
  325. break;
  326. case OsEventType::RESOLUTION:
  327. _width = event.resolution.width;
  328. _height = event.resolution.height;
  329. break;
  330. case OsEventType::EXIT:
  331. exit = true;
  332. break;
  333. case OsEventType::PAUSE:
  334. pause();
  335. break;
  336. case OsEventType::RESUME:
  337. unpause();
  338. break;
  339. case OsEventType::TEXT:
  340. break;
  341. default:
  342. CE_FATAL("Unknown OS event");
  343. break;
  344. }
  345. }
  346. return exit;
  347. }
  348. void Device::set_timestep_policy(TimestepPolicy::Enum tp)
  349. {
  350. if (_timestep_policy == tp)
  351. return;
  352. _timestep_policy = tp;
  353. }
  354. void Device::set_timestep_smoothing(u32 num_samples, u32 num_outliers, f32 average_cap)
  355. {
  356. _delta_time_filter.set_smoothing(num_samples, num_outliers, average_cap);
  357. }
  358. bool Device::frame()
  359. {
  360. if (CE_UNLIKELY(process_events() || _quit))
  361. return true;
  362. const s64 time = time::now();
  363. const s64 raw_dt_ticks = time - _last_time;
  364. const f32 raw_dt = f32(time::seconds(raw_dt_ticks));
  365. _last_time = time;
  366. profiler_globals::clear();
  367. RECORD_FLOAT("device.dt", raw_dt);
  368. RECORD_FLOAT("device.fps", 1.0f/raw_dt);
  369. f32 dt;
  370. if (_timestep_policy == TimestepPolicy::SMOOTHED) {
  371. f32 smoothed_dt = _delta_time_filter.filter(raw_dt_ticks);
  372. RECORD_FLOAT("device.smoothed_dt", smoothed_dt);
  373. RECORD_FLOAT("device.smoothed_fps", 1.0f/smoothed_dt);
  374. dt = smoothed_dt;
  375. } else {
  376. dt = raw_dt;
  377. }
  378. if (CE_UNLIKELY(_width != _prev_width || _height != _prev_height)) {
  379. _prev_width = _width;
  380. _prev_height = _height;
  381. bgfx::reset(_width, _height, (_boot_config.vsync ? BGFX_RESET_VSYNC : BGFX_RESET_NONE));
  382. _pipeline->reset(_width, _height);
  383. // Force pipeline reset in one cycle.
  384. bgfx::frame();
  385. bgfx::frame();
  386. // Force redraw.
  387. ++_needs_draw;
  388. }
  389. // Only block if redraw is not needed.
  390. const bool sync = !_needs_draw;
  391. #if !CROWN_PLATFORM_EMSCRIPTEN
  392. _console_server->execute_message_handlers(sync);
  393. #endif
  394. if (CE_UNLIKELY(!_needs_draw))
  395. return false;
  396. if (CE_LIKELY(!_paused)) {
  397. _resource_manager->complete_requests();
  398. {
  399. const s64 t0 = time::now();
  400. LuaStack stack(_lua_environment->L);
  401. stack.push_float(dt);
  402. _lua_environment->call_global("update", 1);
  403. RECORD_FLOAT("lua.update", f32(time::seconds(time::now() - t0)));
  404. }
  405. {
  406. const s64 t0 = time::now();
  407. LuaStack stack(_lua_environment->L);
  408. stack.push_float(dt);
  409. _lua_environment->call_global("render", 1);
  410. RECORD_FLOAT("lua.render", f32(time::seconds(time::now() - t0)));
  411. }
  412. if (_bgfx_callback->_screenshot_ready) {
  413. _bgfx_callback->_screenshot_ready = 0;
  414. LuaStack stack(_lua_environment->L);
  415. stack.push_string(_bgfx_callback->_screenshot_path.c_str());
  416. _lua_environment->call_global("screenshot", 1);
  417. }
  418. }
  419. _lua_environment->reset_temporaries();
  420. _input_manager->update();
  421. const bgfx::Stats *stats = bgfx::getStats();
  422. RECORD_FLOAT("bgfx.gpu_time", f32(f64(stats->gpuTimeEnd - stats->gpuTimeBegin)/stats->gpuTimerFreq));
  423. RECORD_FLOAT("bgfx.cpu_time", f32(f64(stats->cpuTimeEnd - stats->cpuTimeBegin)/stats->cpuTimerFreq));
  424. profiler_globals::flush();
  425. graph_globals::draw_all(_width, _height);
  426. _pipeline->render(_width, _height);
  427. bgfx::frame();
  428. if (_needs_draw-- == 1)
  429. _needs_draw = (int)!_options._pumped;
  430. return false;
  431. }
  432. void Device::run()
  433. {
  434. s64 run_t0 = time::now();
  435. _console_server->register_command_name("pause", "Pause the engine.", device_command_pause, this);
  436. _console_server->register_command_name("unpause", "Resume the engine.", device_command_unpause, this);
  437. _console_server->register_command_name("game", "Pause/resume the engine.", device_command_game, this);
  438. _console_server->register_command_name("crash", "Crash the engine.", device_command_crash, this);
  439. _console_server->register_message_type("resize", device_message_resize, this);
  440. _console_server->register_message_type("frame", device_message_frame, this);
  441. _console_server->register_message_type("quit", device_message_quit, this);
  442. _console_server->register_message_type("refresh", device_message_refresh, this);
  443. #if !CROWN_PLATFORM_EMSCRIPTEN
  444. _console_server->listen(_options._console_port, _options._wait_console);
  445. #endif
  446. bool is_bundle = true;
  447. #if CROWN_PLATFORM_ANDROID
  448. _data_filesystem = CE_NEW(_allocator, FilesystemApk)(default_allocator(), const_cast<AAssetManager *>((AAssetManager *)_options._asset_manager));
  449. #else
  450. _data_filesystem = CE_NEW(_allocator, FilesystemDisk)(default_allocator());
  451. {
  452. char cwd[1024];
  453. const char *data_dir = NULL;
  454. if (_options._bundle_dir.empty() && _options._data_dir.empty()) {
  455. data_dir = os::getcwd(cwd, sizeof(cwd));
  456. } else {
  457. if (!_options._bundle_dir.empty()) {
  458. data_dir = _options._bundle_dir.c_str();
  459. } else {
  460. is_bundle = false;
  461. if (!_options._data_dir.empty())
  462. data_dir = _options._data_dir.c_str();
  463. else
  464. data_dir = os::getcwd(cwd, sizeof(cwd));
  465. }
  466. }
  467. ((FilesystemDisk *)_data_filesystem)->set_prefix(data_dir);
  468. }
  469. #endif // if CROWN_PLATFORM_ANDROID
  470. logi(DEVICE, "Crown %s %s %s", CROWN_VERSION, CROWN_PLATFORM_NAME, CROWN_ARCH_NAME);
  471. profiler_globals::init();
  472. _shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
  473. namespace smr = state_machine_internal;
  474. namespace cor = config_resource_internal;
  475. namespace ftr = font_resource_internal;
  476. namespace lur = lua_resource_internal;
  477. namespace lvr = level_resource_internal;
  478. namespace mhr = mesh_resource_internal;
  479. namespace mtr = material_resource_internal;
  480. namespace pcr = physics_config_resource_internal;
  481. namespace pkr = package_resource_internal;
  482. namespace sar = sprite_animation_resource_internal;
  483. namespace sdr = sound_resource_internal;
  484. namespace shr = shader_resource_internal;
  485. namespace spr = sprite_resource_internal;
  486. namespace txr = texture_resource_internal;
  487. namespace utr = unit_resource_internal;
  488. _resource_loader = CE_NEW(_allocator, ResourceLoader)(*_data_filesystem, is_bundle);
  489. _resource_loader->register_fallback(RESOURCE_TYPE_TEXTURE, STRING_ID_64("core/fallback/fallback", 0xd09058ae71962248));
  490. _resource_loader->register_fallback(RESOURCE_TYPE_MATERIAL, STRING_ID_64("core/fallback/fallback", 0xd09058ae71962248));
  491. _resource_loader->register_fallback(RESOURCE_TYPE_UNIT, STRING_ID_64("core/fallback/fallback", 0xd09058ae71962248));
  492. _resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);
  493. _resource_manager->register_type(RESOURCE_TYPE_CONFIG, RESOURCE_VERSION_CONFIG, cor::load, cor::unload, NULL, NULL);
  494. _resource_manager->register_type(RESOURCE_TYPE_FONT, RESOURCE_VERSION_FONT, NULL, NULL, NULL, NULL);
  495. _resource_manager->register_type(RESOURCE_TYPE_LEVEL, RESOURCE_VERSION_LEVEL, NULL, NULL, NULL, NULL);
  496. _resource_manager->register_type(RESOURCE_TYPE_MATERIAL, RESOURCE_VERSION_MATERIAL, NULL, NULL, mtr::online, mtr::offline);
  497. _resource_manager->register_type(RESOURCE_TYPE_MESH, RESOURCE_VERSION_MESH, mhr::load, mhr::unload, mhr::online, mhr::offline);
  498. _resource_manager->register_type(RESOURCE_TYPE_PACKAGE, RESOURCE_VERSION_PACKAGE, NULL, NULL, NULL, NULL);
  499. _resource_manager->register_type(RESOURCE_TYPE_PHYSICS_CONFIG, RESOURCE_VERSION_PHYSICS_CONFIG, NULL, NULL, NULL, NULL);
  500. _resource_manager->register_type(RESOURCE_TYPE_SCRIPT, RESOURCE_VERSION_SCRIPT, NULL, NULL, NULL, NULL);
  501. _resource_manager->register_type(RESOURCE_TYPE_SHADER, RESOURCE_VERSION_SHADER, shr::load, shr::unload, shr::online, shr::offline);
  502. _resource_manager->register_type(RESOURCE_TYPE_SOUND, RESOURCE_VERSION_SOUND, NULL, NULL, NULL, NULL);
  503. _resource_manager->register_type(RESOURCE_TYPE_SPRITE, RESOURCE_VERSION_SPRITE, NULL, NULL, NULL, NULL);
  504. _resource_manager->register_type(RESOURCE_TYPE_SPRITE_ANIMATION, RESOURCE_VERSION_SPRITE_ANIMATION, NULL, NULL, NULL, NULL);
  505. _resource_manager->register_type(RESOURCE_TYPE_STATE_MACHINE, RESOURCE_VERSION_STATE_MACHINE, NULL, NULL, NULL, NULL);
  506. _resource_manager->register_type(RESOURCE_TYPE_TEXTURE, RESOURCE_VERSION_TEXTURE, txr::load, txr::unload, txr::online, txr::offline);
  507. _resource_manager->register_type(RESOURCE_TYPE_UNIT, RESOURCE_VERSION_UNIT, NULL, NULL, NULL, NULL);
  508. _material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager, *_shader_manager);
  509. // Read config
  510. {
  511. TempAllocator512 ta;
  512. DynamicString boot_dir(ta);
  513. if (_options._boot_dir != NULL) {
  514. boot_dir += _options._boot_dir;
  515. boot_dir += '/';
  516. }
  517. boot_dir += CROWN_BOOT_CONFIG;
  518. const StringId64 config_name(boot_dir.c_str());
  519. while (!_resource_manager->try_load(PACKAGE_RESOURCE_NONE, RESOURCE_TYPE_CONFIG, config_name, 0)) {
  520. _resource_manager->complete_requests();
  521. #if CROWN_PLATFORM_EMSCRIPTEN
  522. os::sleep(16);
  523. #endif
  524. }
  525. while (!_resource_manager->can_get(RESOURCE_TYPE_CONFIG, config_name)) {
  526. _resource_manager->complete_requests();
  527. #if CROWN_PLATFORM_EMSCRIPTEN
  528. os::sleep(16);
  529. #endif
  530. }
  531. _boot_config.parse((const char *)_resource_manager->get(RESOURCE_TYPE_CONFIG, config_name));
  532. _resource_manager->unload(RESOURCE_TYPE_CONFIG, config_name);
  533. }
  534. // Init all remaining subsystems
  535. _display = display::create(_allocator);
  536. #if !CROWN_PLATFORM_EMSCRIPTEN
  537. if (_options._window_width.has_changed() || _options._window_height.has_changed()) {
  538. _width = _options._window_width.value();
  539. _height = _options._window_height.value();
  540. } else {
  541. _width = _boot_config.window_w;
  542. _height = _boot_config.window_h;
  543. }
  544. #endif
  545. _window = window::create(_allocator);
  546. _window->open(_options._window_x
  547. , _options._window_y
  548. , _width
  549. , _height
  550. , _options._parent_window
  551. );
  552. _window->set_title(_boot_config.window_title.c_str());
  553. _window->set_fullscreen(_boot_config.fullscreen);
  554. if (!_options._hidden)
  555. _window->show();
  556. _bgfx_allocator = CE_NEW(_allocator, BgfxAllocator)(default_allocator());
  557. _bgfx_callback = CE_NEW(_allocator, BgfxCallback)(default_allocator());
  558. bgfx::Init init;
  559. init.resolution.width = _width;
  560. init.resolution.height = _height;
  561. init.resolution.reset = _boot_config.vsync ? BGFX_RESET_VSYNC : BGFX_RESET_NONE;
  562. init.callback = _bgfx_callback;
  563. init.allocator = _bgfx_allocator;
  564. init.platformData.ndt = _window->native_display();
  565. init.platformData.nwh = _window->native_handle();
  566. init.vendorId = BGFX_PCI_ID_NONE;
  567. #if CROWN_PLATFORM_ANDROID || CROWN_PLATFORM_EMSCRIPTEN
  568. init.type = bgfx::RendererType::OpenGLES;
  569. #elif CROWN_PLATFORM_LINUX
  570. init.type = bgfx::RendererType::OpenGL;
  571. #elif CROWN_PLATFORM_WINDOWS
  572. init.type = bgfx::RendererType::Direct3D11;
  573. #else
  574. #error "Unknown platform"
  575. #endif
  576. bgfx::init(init);
  577. _input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
  578. _unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());
  579. _lua_environment = CE_NEW(_allocator, LuaEnvironment)();
  580. _lua_environment->register_console_commands(*_console_server);
  581. audio_globals::init();
  582. physics_globals::init(_allocator);
  583. ResourcePackage *boot_package = create_resource_package(_boot_config.boot_package_name);
  584. boot_package->load();
  585. boot_package->flush();
  586. _lua_environment->load_libs();
  587. _lua_environment->require(_boot_config.boot_script_name.c_str());
  588. _lua_environment->execute_string(_options._lua_string.c_str());
  589. _pipeline = CE_NEW(_allocator, Pipeline)(*_shader_manager);
  590. _pipeline->create(_width, _height);
  591. graph_globals::init(_allocator, *_pipeline, *_console_server);
  592. logi(DEVICE, "Initialized in " TIME_FMT, time::seconds(time::now() - run_t0));
  593. _lua_environment->call_global("init");
  594. _prev_width = _width;
  595. _prev_height = _height;
  596. _last_time = time::now();
  597. #if CROWN_PLATFORM_EMSCRIPTEN
  598. emscripten_set_main_loop_arg([](void *thiz) { ((Device *)thiz)->frame(); }, this, 0, -1);
  599. #else
  600. while (!frame()) { }
  601. #endif
  602. _lua_environment->call_global("shutdown");
  603. boot_package->unload();
  604. destroy_resource_package(*boot_package);
  605. physics_globals::shutdown(_allocator);
  606. audio_globals::shutdown();
  607. graph_globals::shutdown();
  608. _pipeline->destroy();
  609. CE_DELETE(_allocator, _pipeline);
  610. CE_DELETE(_allocator, _lua_environment);
  611. CE_DELETE(_allocator, _unit_manager);
  612. CE_DELETE(_allocator, _input_manager);
  613. CE_DELETE(_allocator, _resource_manager);
  614. CE_DELETE(_allocator, _resource_loader);
  615. CE_DELETE(_allocator, _material_manager);
  616. CE_DELETE(_allocator, _shader_manager);
  617. bgfx::shutdown();
  618. CE_DELETE(_allocator, _bgfx_callback);
  619. CE_DELETE(_allocator, _bgfx_allocator);
  620. _window->close();
  621. window::destroy(_allocator, *_window);
  622. display::destroy(_allocator, *_display);
  623. CE_DELETE(_allocator, _data_filesystem);
  624. profiler_globals::shutdown();
  625. _allocator.clear();
  626. }
  627. void Device::quit()
  628. {
  629. _quit = true;
  630. }
  631. int Device::argc() const
  632. {
  633. return _options._argc;
  634. }
  635. const char **Device::argv() const
  636. {
  637. return (const char **)_options._argv;
  638. }
  639. void Device::pause()
  640. {
  641. _paused = true;
  642. logi(DEVICE, "Paused");
  643. }
  644. void Device::unpause()
  645. {
  646. _paused = false;
  647. logi(DEVICE, "Unpaused");
  648. }
  649. void Device::resolution(u16 &width, u16 &height)
  650. {
  651. width = _width;
  652. height = _height;
  653. }
  654. void Device::render(World &world, UnitId camera_unit)
  655. {
  656. const f32 aspect_ratio = (_boot_config.aspect_ratio == -1.0f
  657. ? (f32)_width/(f32)_height
  658. : _boot_config.aspect_ratio
  659. );
  660. CameraInstance camera = world.camera_instance(camera_unit);
  661. const Matrix4x4 view = world.camera_view_matrix(camera);
  662. const Matrix4x4 proj = world.camera_projection_matrix(camera, aspect_ratio);
  663. const bgfx::Caps *caps = bgfx::getCaps();
  664. f32 bx_ortho[16];
  665. bx::mtxOrtho(bx_ortho, 0, _width, 0, _height, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth, bx::Handedness::Right);
  666. Matrix4x4 ortho_proj = from_array(bx_ortho);
  667. bgfx::setViewClear(VIEW_SPRITE_0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x080808ff, 1.0f, 0);
  668. bgfx::setViewClear(VIEW_SELECTION, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, UNIT_INVALID._idx, 1.0f, 0);
  669. bgfx::setViewTransform(VIEW_SPRITE_0, to_float_ptr(view), to_float_ptr(proj));
  670. bgfx::setViewTransform(VIEW_SPRITE_1, to_float_ptr(view), to_float_ptr(proj));
  671. bgfx::setViewTransform(VIEW_SPRITE_2, to_float_ptr(view), to_float_ptr(proj));
  672. bgfx::setViewTransform(VIEW_SPRITE_3, to_float_ptr(view), to_float_ptr(proj));
  673. bgfx::setViewTransform(VIEW_SPRITE_4, to_float_ptr(view), to_float_ptr(proj));
  674. bgfx::setViewTransform(VIEW_SPRITE_5, to_float_ptr(view), to_float_ptr(proj));
  675. bgfx::setViewTransform(VIEW_SPRITE_6, to_float_ptr(view), to_float_ptr(proj));
  676. bgfx::setViewTransform(VIEW_SPRITE_7, to_float_ptr(view), to_float_ptr(proj));
  677. bgfx::setViewTransform(VIEW_MESH, to_float_ptr(view), to_float_ptr(proj));
  678. bgfx::setViewTransform(VIEW_WORLD_GUI, to_float_ptr(view), to_float_ptr(proj));
  679. bgfx::setViewTransform(VIEW_DEBUG, to_float_ptr(view), to_float_ptr(proj));
  680. bgfx::setViewTransform(VIEW_SELECTION, to_float_ptr(view), to_float_ptr(proj));
  681. bgfx::setViewTransform(VIEW_SCREEN_GUI, to_float_ptr(MATRIX4X4_IDENTITY), to_float_ptr(ortho_proj));
  682. f32 graph_ortho[16];
  683. bx::mtxOrtho(graph_ortho
  684. , -_width / 2.0f
  685. , _width / 2.0f
  686. , -_height / 2.0f
  687. , _height / 2.0f
  688. , 0.0f
  689. , 1.0f
  690. , 0.0f
  691. , caps->homogeneousDepth
  692. , bx::Handedness::Right
  693. );
  694. bgfx::setViewTransform(VIEW_GRAPH, to_float_ptr(MATRIX4X4_IDENTITY), to_float_ptr(from_array(graph_ortho)));
  695. bgfx::setViewRect(VIEW_SPRITE_0, 0, 0, _width, _height);
  696. bgfx::setViewRect(VIEW_SPRITE_1, 0, 0, _width, _height);
  697. bgfx::setViewRect(VIEW_SPRITE_2, 0, 0, _width, _height);
  698. bgfx::setViewRect(VIEW_SPRITE_3, 0, 0, _width, _height);
  699. bgfx::setViewRect(VIEW_SPRITE_4, 0, 0, _width, _height);
  700. bgfx::setViewRect(VIEW_SPRITE_5, 0, 0, _width, _height);
  701. bgfx::setViewRect(VIEW_SPRITE_6, 0, 0, _width, _height);
  702. bgfx::setViewRect(VIEW_SPRITE_7, 0, 0, _width, _height);
  703. bgfx::setViewRect(VIEW_MESH, 0, 0, _width, _height);
  704. bgfx::setViewRect(VIEW_WORLD_GUI, 0, 0, _width, _height);
  705. bgfx::setViewRect(VIEW_DEBUG, 0, 0, _width, _height);
  706. bgfx::setViewRect(VIEW_SELECTION, 0, 0, _width, _height);
  707. bgfx::setViewRect(VIEW_OUTLINE, 0, 0, _width, _height);
  708. bgfx::setViewRect(VIEW_SCREEN_GUI, 0, 0, _width, _height);
  709. bgfx::setViewRect(VIEW_GRAPH, 0, 0, _width, _height);
  710. bgfx::setViewMode(VIEW_SPRITE_0, bgfx::ViewMode::DepthAscending);
  711. bgfx::setViewMode(VIEW_SPRITE_1, bgfx::ViewMode::DepthAscending);
  712. bgfx::setViewMode(VIEW_SPRITE_2, bgfx::ViewMode::DepthAscending);
  713. bgfx::setViewMode(VIEW_SPRITE_3, bgfx::ViewMode::DepthAscending);
  714. bgfx::setViewMode(VIEW_SPRITE_4, bgfx::ViewMode::DepthAscending);
  715. bgfx::setViewMode(VIEW_SPRITE_5, bgfx::ViewMode::DepthAscending);
  716. bgfx::setViewMode(VIEW_SPRITE_6, bgfx::ViewMode::DepthAscending);
  717. bgfx::setViewMode(VIEW_SPRITE_7, bgfx::ViewMode::DepthAscending);
  718. bgfx::setViewMode(VIEW_WORLD_GUI, bgfx::ViewMode::DepthDescending);
  719. bgfx::setViewMode(VIEW_SCREEN_GUI, bgfx::ViewMode::DepthDescending);
  720. bgfx::setViewMode(VIEW_BLIT, bgfx::ViewMode::Sequential);
  721. bgfx::setViewFrameBuffer(VIEW_SPRITE_0, _pipeline->_main_frame_buffer);
  722. bgfx::setViewFrameBuffer(VIEW_SPRITE_1, _pipeline->_main_frame_buffer);
  723. bgfx::setViewFrameBuffer(VIEW_SPRITE_2, _pipeline->_main_frame_buffer);
  724. bgfx::setViewFrameBuffer(VIEW_SPRITE_3, _pipeline->_main_frame_buffer);
  725. bgfx::setViewFrameBuffer(VIEW_SPRITE_4, _pipeline->_main_frame_buffer);
  726. bgfx::setViewFrameBuffer(VIEW_SPRITE_5, _pipeline->_main_frame_buffer);
  727. bgfx::setViewFrameBuffer(VIEW_SPRITE_6, _pipeline->_main_frame_buffer);
  728. bgfx::setViewFrameBuffer(VIEW_SPRITE_7, _pipeline->_main_frame_buffer);
  729. bgfx::setViewFrameBuffer(VIEW_MESH, _pipeline->_main_frame_buffer);
  730. bgfx::setViewFrameBuffer(VIEW_WORLD_GUI, _pipeline->_main_frame_buffer);
  731. bgfx::setViewFrameBuffer(VIEW_DEBUG, _pipeline->_main_frame_buffer);
  732. bgfx::setViewFrameBuffer(VIEW_SELECTION, _pipeline->_selection_frame_buffer);
  733. bgfx::setViewFrameBuffer(VIEW_OUTLINE, _pipeline->_main_frame_buffer);
  734. bgfx::setViewFrameBuffer(VIEW_SCREEN_GUI, _pipeline->_main_frame_buffer);
  735. bgfx::setViewFrameBuffer(VIEW_GRAPH, _pipeline->_main_frame_buffer);
  736. bgfx::setViewFrameBuffer(VIEW_BLIT, BGFX_INVALID_HANDLE);
  737. bgfx::touch(VIEW_SPRITE_0);
  738. bgfx::touch(VIEW_SPRITE_1);
  739. bgfx::touch(VIEW_SPRITE_2);
  740. bgfx::touch(VIEW_SPRITE_3);
  741. bgfx::touch(VIEW_SPRITE_4);
  742. bgfx::touch(VIEW_SPRITE_5);
  743. bgfx::touch(VIEW_SPRITE_6);
  744. bgfx::touch(VIEW_SPRITE_7);
  745. bgfx::touch(VIEW_MESH);
  746. bgfx::touch(VIEW_WORLD_GUI);
  747. bgfx::touch(VIEW_DEBUG);
  748. bgfx::touch(VIEW_SELECTION);
  749. bgfx::touch(VIEW_OUTLINE);
  750. bgfx::touch(VIEW_SCREEN_GUI);
  751. bgfx::touch(VIEW_GRAPH);
  752. bgfx::touch(VIEW_BLIT);
  753. world.render(view);
  754. }
  755. World *Device::create_world()
  756. {
  757. World *world = CE_NEW(default_allocator(), World)(default_allocator()
  758. , *_resource_manager
  759. , *_shader_manager
  760. , *_material_manager
  761. , *_unit_manager
  762. , *_lua_environment
  763. , *_pipeline
  764. );
  765. list::add(world->_node, _worlds);
  766. return world;
  767. }
  768. void Device::destroy_world(World &world)
  769. {
  770. list::remove(world._node);
  771. CE_DELETE(default_allocator(), &world);
  772. }
  773. ResourcePackage *Device::create_resource_package(StringId64 id)
  774. {
  775. return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
  776. }
  777. void Device::destroy_resource_package(ResourcePackage &rp)
  778. {
  779. CE_DELETE(default_allocator(), &rp);
  780. }
  781. void Device::refresh(const char *json)
  782. {
  783. #if CROWN_CAN_RELOAD
  784. TempAllocator4096 ta;
  785. JsonObject obj(ta);
  786. JsonArray list(ta);
  787. DynamicString type(ta);
  788. sjson::parse(obj, json);
  789. bool refresh_lua = false;
  790. sjson::parse_array(list, obj["list"]);
  791. for (u32 i = 0; i < array::size(list); ++i) {
  792. DynamicString resource(ta);
  793. sjson::parse_string(resource, list[i]);
  794. const char *type = resource_type(resource.c_str());
  795. const u32 len = resource_name_length(type, resource.c_str());
  796. StringId64 resource_type(type);
  797. StringId64 resource_name(resource.c_str(), len);
  798. bool is_type_reloadable = resource_type == RESOURCE_TYPE_SCRIPT
  799. || resource_type == RESOURCE_TYPE_TEXTURE
  800. || resource_type == RESOURCE_TYPE_SHADER
  801. || resource_type == RESOURCE_TYPE_MATERIAL
  802. ;
  803. if (is_type_reloadable && _resource_manager->can_get(resource_type, resource_name)) {
  804. const void *old_resource = _resource_manager->get(resource_type, resource_name);
  805. const void *new_resource = _resource_manager->reload(resource_type, resource_name);
  806. if (resource_type == RESOURCE_TYPE_SCRIPT) {
  807. refresh_lua = true;
  808. } else if (resource_type == RESOURCE_TYPE_TEXTURE) {
  809. _material_manager->reload_textures((TextureResource *)old_resource, (TextureResource *)new_resource);
  810. } else if (resource_type == RESOURCE_TYPE_SHADER) {
  811. _pipeline->reload_shaders((ShaderResource *)old_resource, (ShaderResource *)new_resource);
  812. _material_manager->reload_shaders((ShaderResource *)old_resource, (ShaderResource *)new_resource);
  813. } else if (resource_type == RESOURCE_TYPE_MATERIAL) {
  814. ListNode *cur;
  815. list_for_each(cur, &_worlds)
  816. {
  817. World *w = (World *)container_of(cur, World, _node);
  818. w->reload_materials((MaterialResource *)old_resource, (MaterialResource *)new_resource);
  819. }
  820. }
  821. }
  822. }
  823. if (array::size(list)) {
  824. if (refresh_lua)
  825. _lua_environment->reload();
  826. }
  827. if (_paused)
  828. unpause();
  829. #else
  830. CE_UNUSED(json);
  831. #endif // if CROWN_CAN_RELOAD
  832. }
  833. void Device::screenshot(const char *path)
  834. {
  835. bgfx::requestScreenShot(BGFX_INVALID_HANDLE, path);
  836. ++device()->_needs_draw; // 1 frame for the request to be fulfilled.
  837. }
  838. Device *_device = NULL;
  839. void run(const DeviceOptions &opts)
  840. {
  841. CE_ASSERT(_device == NULL, "Crown already initialized");
  842. console_server_globals::init();
  843. _device = CE_NEW(default_allocator(), Device)(opts, *console_server());
  844. _device->run();
  845. CE_DELETE(default_allocator(), _device);
  846. _device = NULL;
  847. console_server_globals::shutdown();
  848. }
  849. Device *device()
  850. {
  851. return crown::_device;
  852. }
  853. } // namespace crown