device.cpp 24 KB

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