device.cpp 24 KB

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