device.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. /*
  2. * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "array.h"
  6. #include "audio.h"
  7. #include "config.h"
  8. #include "config_resource.h"
  9. #include "console_api.h"
  10. #include "console_server.h"
  11. #include "data_compiler.h"
  12. #include "device.h"
  13. #include "file.h"
  14. #include "filesystem.h"
  15. #include "filesystem_apk.h"
  16. #include "filesystem_disk.h"
  17. #include "font_resource.h"
  18. #include "input_device.h"
  19. #include "input_manager.h"
  20. #include "json_object.h"
  21. #include "level_resource.h"
  22. #include "log.h"
  23. #include "lua_environment.h"
  24. #include "lua_resource.h"
  25. #include "map.h"
  26. #include "material_manager.h"
  27. #include "material_resource.h"
  28. #include "matrix4x4.h"
  29. #include "memory.h"
  30. #include "mesh_resource.h"
  31. #include "os.h"
  32. #include "os_event_queue.h"
  33. #include "package_resource.h"
  34. #include "path.h"
  35. #include "physics.h"
  36. #include "physics_resource.h"
  37. #include "profiler.h"
  38. #include "proxy_allocator.h"
  39. #include "resource_loader.h"
  40. #include "resource_manager.h"
  41. #include "resource_package.h"
  42. #include "shader_manager.h"
  43. #include "shader_resource.h"
  44. #include "sjson.h"
  45. #include "sound_resource.h"
  46. #include "sprite_resource.h"
  47. #include "string_stream.h"
  48. #include "string_utils.h"
  49. #include "temp_allocator.h"
  50. #include "texture_resource.h"
  51. #include "types.h"
  52. #include "unit_manager.h"
  53. #include "unit_resource.h"
  54. #include "vector3.h"
  55. #include "world.h"
  56. #include <bgfx/bgfx.h>
  57. #include <bx/allocator.h>
  58. #define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024
  59. namespace crown
  60. {
  61. extern bool next_event(OsEvent& ev);
  62. struct BgfxCallback : public bgfx::CallbackI
  63. {
  64. virtual void fatal(bgfx::Fatal::Enum _code, const char* _str)
  65. {
  66. CE_ASSERT(false, "Fatal error: 0x%08x: %s", _code, _str);
  67. CE_UNUSED(_code);
  68. CE_UNUSED(_str);
  69. }
  70. virtual void traceVargs(const char* /*_filePath*/, u16 /*_line*/, const char* _format, va_list _argList)
  71. {
  72. char buf[2048];
  73. strncpy(buf, _format, sizeof(buf));
  74. buf[strlen32(buf)-1] = '\0'; // Remove trailing newline
  75. logdv(buf, _argList);
  76. }
  77. virtual u32 cacheReadSize(u64 /*_id*/)
  78. {
  79. return 0;
  80. }
  81. virtual bool cacheRead(u64 /*_id*/, void* /*_data*/, u32 /*_size*/)
  82. {
  83. return false;
  84. }
  85. virtual void cacheWrite(u64 /*_id*/, const void* /*_data*/, u32 /*_size*/)
  86. {
  87. }
  88. virtual void screenShot(const char* /*_filePath*/, u32 /*_width*/, u32 /*_height*/, u32 /*_pitch*/, const void* /*_data*/, u32 /*_size*/, bool /*_yflip*/)
  89. {
  90. }
  91. virtual void captureBegin(u32 /*_width*/, u32 /*_height*/, u32 /*_pitch*/, bgfx::TextureFormat::Enum /*_format*/, bool /*_yflip*/)
  92. {
  93. }
  94. virtual void captureEnd()
  95. {
  96. }
  97. virtual void captureFrame(const void* /*_data*/, u32 /*_size*/)
  98. {
  99. }
  100. };
  101. struct BgfxAllocator : public bx::AllocatorI
  102. {
  103. BgfxAllocator(Allocator& a)
  104. : _allocator(a, "bgfx")
  105. {
  106. }
  107. virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* /*_file*/, u32 /*_line*/)
  108. {
  109. if (!_ptr)
  110. return _allocator.allocate((u32)_size, (u32)_align == 0 ? 1 : (u32)_align);
  111. if (_size == 0)
  112. {
  113. _allocator.deallocate(_ptr);
  114. return NULL;
  115. }
  116. // Realloc
  117. void* p = _allocator.allocate((u32)_size, (u32)_align == 0 ? 1 : (u32)_align);
  118. _allocator.deallocate(_ptr);
  119. return p;
  120. }
  121. private:
  122. ProxyAllocator _allocator;
  123. };
  124. Device::Device(const DeviceOptions& opts)
  125. : _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)
  126. , _device_options(opts)
  127. , _boot_config(default_allocator())
  128. , _console_server(NULL)
  129. , _data_compiler(NULL)
  130. , _bundle_filesystem(NULL)
  131. , _last_log(NULL)
  132. , _resource_loader(NULL)
  133. , _resource_manager(NULL)
  134. , _bgfx_allocator(NULL)
  135. , _bgfx_callback(NULL)
  136. , _shader_manager(NULL)
  137. , _material_manager(NULL)
  138. , _input_manager(NULL)
  139. , _unit_manager(NULL)
  140. , _lua_environment(NULL)
  141. , _display(NULL)
  142. , _window(NULL)
  143. , _worlds(default_allocator())
  144. , _width(0)
  145. , _height(0)
  146. , _quit(false)
  147. , _paused(false)
  148. , _frame_count(0)
  149. , _last_delta_time(0.0f)
  150. , _time_since_start(0.0)
  151. {
  152. }
  153. bool Device::process_events(s16& mouse_x, s16& mouse_y, s16& mouse_last_x, s16& mouse_last_y, bool vsync)
  154. {
  155. OsEvent event;
  156. bool exit = false;
  157. InputManager* im = _input_manager;
  158. const s16 dt_x = mouse_x - mouse_last_x;
  159. const s16 dt_y = mouse_y - mouse_last_y;
  160. im->mouse()->set_axis(MouseAxis::CURSOR_DELTA, vector3(dt_x, dt_y, 0.0f));
  161. mouse_last_x = mouse_x;
  162. mouse_last_y = mouse_y;
  163. while(next_event(event))
  164. {
  165. if (event.type == OsEvent::NONE)
  166. continue;
  167. switch (event.type)
  168. {
  169. case OsEvent::TOUCH:
  170. {
  171. const OsTouchEvent& ev = event.touch;
  172. switch (ev.type)
  173. {
  174. case OsTouchEvent::POINTER:
  175. im->touch()->set_button_state(ev.pointer_id, ev.pressed);
  176. break;
  177. case OsTouchEvent::MOVE:
  178. im->touch()->set_axis(ev.pointer_id, vector3(ev.x, ev.y, 0.0f));
  179. break;
  180. default:
  181. CE_FATAL("Unknown touch event type");
  182. break;
  183. }
  184. }
  185. break;
  186. case OsEvent::MOUSE:
  187. {
  188. const OsMouseEvent& ev = event.mouse;
  189. switch (ev.type)
  190. {
  191. case OsMouseEvent::BUTTON:
  192. im->mouse()->set_button_state(ev.button, ev.pressed);
  193. break;
  194. case OsMouseEvent::MOVE:
  195. mouse_x = ev.x;
  196. mouse_y = ev.y;
  197. im->mouse()->set_axis(MouseAxis::CURSOR, vector3(ev.x, ev.y, 0.0f));
  198. break;
  199. case OsMouseEvent::WHEEL:
  200. im->mouse()->set_axis(MouseAxis::WHEEL, vector3(0.0f, ev.wheel, 0.0f));
  201. break;
  202. default:
  203. CE_FATAL("Unknown mouse event type");
  204. break;
  205. }
  206. }
  207. break;
  208. case OsEvent::KEYBOARD:
  209. im->keyboard()->set_button_state(event.keyboard.button, event.keyboard.pressed);
  210. break;
  211. case OsEvent::JOYPAD:
  212. {
  213. const OsJoypadEvent& ev = event.joypad;
  214. switch (ev.type)
  215. {
  216. case OsJoypadEvent::CONNECTED:
  217. im->joypad(ev.index)->set_connected(ev.connected);
  218. break;
  219. case OsJoypadEvent::BUTTON:
  220. im->joypad(ev.index)->set_button_state(ev.button, ev.pressed);
  221. break;
  222. case OsJoypadEvent::AXIS:
  223. im->joypad(ev.index)->set_axis(ev.button, vector3(ev.x, ev.y, ev.z));
  224. break;
  225. default:
  226. CE_FATAL("Unknown joypad event");
  227. break;
  228. }
  229. }
  230. break;
  231. case OsEvent::METRICS:
  232. {
  233. const OsMetricsEvent& ev = event.metrics;
  234. _width = ev.width;
  235. _height = ev.height;
  236. bgfx::reset(ev.width, ev.height, (vsync ? BGFX_RESET_VSYNC : BGFX_RESET_NONE));
  237. }
  238. break;
  239. case OsEvent::EXIT:
  240. exit = true;
  241. break;
  242. case OsEvent::PAUSE:
  243. pause();
  244. break;
  245. case OsEvent::RESUME:
  246. unpause();
  247. break;
  248. default:
  249. CE_FATAL("Unknown os event");
  250. break;
  251. }
  252. }
  253. return exit;
  254. }
  255. void Device::run()
  256. {
  257. _console_server = CE_NEW(_allocator, ConsoleServer)(default_allocator());
  258. load_console_api(*_console_server);
  259. namespace pcr = physics_config_resource;
  260. namespace phr = physics_resource;
  261. namespace pkr = package_resource;
  262. namespace sdr = sound_resource;
  263. namespace mhr = mesh_resource;
  264. namespace utr = unit_resource;
  265. namespace txr = texture_resource;
  266. namespace mtr = material_resource;
  267. namespace lur = lua_resource;
  268. namespace ftr = font_resource;
  269. namespace lvr = level_resource;
  270. namespace spr = sprite_resource;
  271. namespace shr = shader_resource;
  272. namespace sar = sprite_animation_resource;
  273. namespace cor = config_resource;
  274. bool do_continue = true;
  275. #if CROWN_PLATFORM_LINUX || CROWN_PLATFORM_WINDOWS
  276. if (_device_options._do_compile || _device_options._server)
  277. {
  278. _data_compiler = CE_NEW(_allocator, DataCompiler)();
  279. _data_compiler->register_compiler(RESOURCE_TYPE_SCRIPT, RESOURCE_VERSION_SCRIPT, lur::compile);
  280. _data_compiler->register_compiler(RESOURCE_TYPE_TEXTURE, RESOURCE_VERSION_TEXTURE, txr::compile);
  281. _data_compiler->register_compiler(RESOURCE_TYPE_MESH, RESOURCE_VERSION_MESH, mhr::compile);
  282. _data_compiler->register_compiler(RESOURCE_TYPE_SOUND, RESOURCE_VERSION_SOUND, sdr::compile);
  283. _data_compiler->register_compiler(RESOURCE_TYPE_UNIT, RESOURCE_VERSION_UNIT, utr::compile);
  284. _data_compiler->register_compiler(RESOURCE_TYPE_SPRITE, RESOURCE_VERSION_SPRITE, spr::compile);
  285. _data_compiler->register_compiler(RESOURCE_TYPE_PACKAGE, RESOURCE_VERSION_PACKAGE, pkr::compile);
  286. _data_compiler->register_compiler(RESOURCE_TYPE_PHYSICS, RESOURCE_VERSION_PHYSICS, phr::compile);
  287. _data_compiler->register_compiler(RESOURCE_TYPE_MATERIAL, RESOURCE_VERSION_MATERIAL, mtr::compile);
  288. _data_compiler->register_compiler(RESOURCE_TYPE_PHYSICS_CONFIG, RESOURCE_VERSION_PHYSICS_CONFIG, pcr::compile);
  289. _data_compiler->register_compiler(RESOURCE_TYPE_FONT, RESOURCE_VERSION_FONT, ftr::compile);
  290. _data_compiler->register_compiler(RESOURCE_TYPE_LEVEL, RESOURCE_VERSION_LEVEL, lvr::compile);
  291. _data_compiler->register_compiler(RESOURCE_TYPE_SHADER, RESOURCE_VERSION_SHADER, shr::compile);
  292. _data_compiler->register_compiler(RESOURCE_TYPE_SPRITE_ANIMATION, RESOURCE_VERSION_SPRITE_ANIMATION, sar::compile);
  293. _data_compiler->register_compiler(RESOURCE_TYPE_CONFIG, RESOURCE_VERSION_CONFIG, cor::compile);
  294. _data_compiler->map_source_dir("", _device_options._source_dir);
  295. if (_device_options._map_source_dir_name)
  296. {
  297. _data_compiler->map_source_dir(_device_options._map_source_dir_name
  298. , _device_options._map_source_dir_prefix
  299. );
  300. }
  301. _data_compiler->scan();
  302. if (_device_options._server)
  303. {
  304. _console_server->listen(CROWN_DEFAULT_COMPILER_PORT, false);
  305. while (true)
  306. {
  307. _console_server->update();
  308. os::sleep(60);
  309. }
  310. }
  311. else
  312. {
  313. const char* data_dir = _device_options._data_dir;
  314. const char* platform = _device_options._platform;
  315. do_continue = _data_compiler->compile(data_dir, platform);
  316. do_continue = do_continue && _device_options._do_continue;
  317. }
  318. }
  319. #endif // CROWN_PLATFORM_LINUX || CROWN_PLATFORM_WINDOWS
  320. if (do_continue)
  321. {
  322. _console_server->listen(_device_options._console_port, _device_options._wait_console);
  323. #if CROWN_PLATFORM_ANDROID
  324. _bundle_filesystem = CE_NEW(_allocator, FilesystemApk)(default_allocator(), const_cast<AAssetManager*>((AAssetManager*)_device_options._asset_manager));
  325. #else
  326. const char* data_dir = _device_options._data_dir;
  327. if (!data_dir)
  328. {
  329. char buf[1024];
  330. data_dir = os::getcwd(buf, sizeof(buf));
  331. }
  332. _bundle_filesystem = CE_NEW(_allocator, FilesystemDisk)(default_allocator());
  333. ((FilesystemDisk*)_bundle_filesystem)->set_prefix(data_dir);
  334. if (!_bundle_filesystem->exists(data_dir))
  335. _bundle_filesystem->create_directory(data_dir);
  336. _last_log = _bundle_filesystem->open(CROWN_LAST_LOG, FileOpenMode::WRITE);
  337. #endif // CROWN_PLATFORM_ANDROID
  338. logi("Initializing Crown Engine %s...", version());
  339. profiler_globals::init();
  340. _resource_loader = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem);
  341. _resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);
  342. _resource_manager->register_type(RESOURCE_TYPE_SCRIPT, lur::load, lur::unload, NULL, NULL );
  343. _resource_manager->register_type(RESOURCE_TYPE_TEXTURE, txr::load, txr::unload, txr::online, txr::offline);
  344. _resource_manager->register_type(RESOURCE_TYPE_MESH, mhr::load, mhr::unload, mhr::online, mhr::offline);
  345. _resource_manager->register_type(RESOURCE_TYPE_SOUND, sdr::load, sdr::unload, NULL, NULL );
  346. _resource_manager->register_type(RESOURCE_TYPE_UNIT, utr::load, utr::unload, NULL, NULL );
  347. _resource_manager->register_type(RESOURCE_TYPE_SPRITE, spr::load, spr::unload, spr::online, spr::offline);
  348. _resource_manager->register_type(RESOURCE_TYPE_PACKAGE, pkr::load, pkr::unload, NULL, NULL );
  349. _resource_manager->register_type(RESOURCE_TYPE_PHYSICS, phr::load, phr::unload, NULL, NULL );
  350. _resource_manager->register_type(RESOURCE_TYPE_MATERIAL, mtr::load, mtr::unload, mtr::online, mtr::offline);
  351. _resource_manager->register_type(RESOURCE_TYPE_PHYSICS_CONFIG, pcr::load, pcr::unload, NULL, NULL );
  352. _resource_manager->register_type(RESOURCE_TYPE_FONT, ftr::load, ftr::unload, NULL, NULL );
  353. _resource_manager->register_type(RESOURCE_TYPE_LEVEL, lvr::load, lvr::unload, NULL, NULL );
  354. _resource_manager->register_type(RESOURCE_TYPE_SHADER, shr::load, shr::unload, shr::online, shr::offline);
  355. _resource_manager->register_type(RESOURCE_TYPE_SPRITE_ANIMATION, sar::load, sar::unload, NULL, NULL );
  356. _resource_manager->register_type(RESOURCE_TYPE_CONFIG, cor::load, cor::unload, NULL, NULL );
  357. // Read config
  358. {
  359. TempAllocator512 ta;
  360. DynamicString boot_dir(ta);
  361. if (_device_options._boot_dir != NULL)
  362. {
  363. boot_dir += _device_options._boot_dir;
  364. boot_dir += '/';
  365. }
  366. boot_dir += CROWN_BOOT_CONFIG;
  367. const StringId64 config_name(boot_dir.c_str());
  368. _resource_manager->load(RESOURCE_TYPE_CONFIG, config_name);
  369. _resource_manager->flush();
  370. _boot_config.parse((const char*)_resource_manager->get(RESOURCE_TYPE_CONFIG, config_name));
  371. _resource_manager->unload(RESOURCE_TYPE_CONFIG, config_name);
  372. }
  373. // Init all remaining subsystems
  374. _bgfx_allocator = CE_NEW(_allocator, BgfxAllocator)(default_allocator());
  375. _bgfx_callback = CE_NEW(_allocator, BgfxCallback)();
  376. _display = display::create(_allocator);
  377. _window = window::create(_allocator);
  378. _window->open(_device_options._window_x
  379. , _device_options._window_y
  380. , _boot_config.window_w
  381. , _boot_config.window_h
  382. , _device_options._parent_window
  383. );
  384. _window->set_title(_boot_config.window_title.c_str());
  385. _window->bgfx_setup();
  386. bgfx::init(bgfx::RendererType::Count
  387. , BGFX_PCI_ID_NONE
  388. , 0
  389. , _bgfx_callback
  390. , _bgfx_allocator
  391. );
  392. _shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
  393. _material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager);
  394. _input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
  395. _unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());
  396. _lua_environment = CE_NEW(_allocator, LuaEnvironment)();
  397. audio_globals::init();
  398. physics_globals::init(_allocator);
  399. ResourcePackage* boot_package = create_resource_package(_boot_config.boot_package_name);
  400. boot_package->load();
  401. boot_package->flush();
  402. _lua_environment->load_libs();
  403. _lua_environment->execute((LuaResource*)_resource_manager->get(RESOURCE_TYPE_SCRIPT, _boot_config.boot_script_name));
  404. _lua_environment->call_global("init", 0);
  405. logd("Engine initialized");
  406. s16 mouse_x = 0;
  407. s16 mouse_y = 0;
  408. s16 mouse_last_x = 0;
  409. s16 mouse_last_y = 0;
  410. s64 last_time = os::clocktime();
  411. s64 curr_time;
  412. while (!process_events(mouse_x, mouse_y, mouse_last_x, mouse_last_y, _boot_config.vsync) && !_quit)
  413. {
  414. curr_time = os::clocktime();
  415. const s64 time = curr_time - last_time;
  416. last_time = curr_time;
  417. const f64 freq = (f64)os::clockfrequency();
  418. _last_delta_time = f32(time * (1.0 / freq));
  419. _time_since_start += _last_delta_time;
  420. profiler_globals::clear();
  421. _console_server->update();
  422. RECORD_FLOAT("device.dt", _last_delta_time);
  423. RECORD_FLOAT("device.fps", 1.0f/_last_delta_time);
  424. if (!_paused)
  425. {
  426. _resource_manager->complete_requests();
  427. {
  428. const s64 t0 = os::clocktime();
  429. _lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time());
  430. const s64 t1 = os::clocktime();
  431. RECORD_FLOAT("lua.update", (t1 - t0)*(1.0 / freq));
  432. }
  433. {
  434. const s64 t0 = os::clocktime();
  435. _lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time());
  436. const s64 t1 = os::clocktime();
  437. RECORD_FLOAT("lua.render", (t1 - t0)*(1.0 / freq));
  438. }
  439. }
  440. _input_manager->update();
  441. const bgfx::Stats* stats = bgfx::getStats();
  442. RECORD_FLOAT("bgfx.gpu_time", f32(f64(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq));
  443. RECORD_FLOAT("bgfx.cpu_time", f32(f64(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq));
  444. bgfx::frame();
  445. profiler_globals::flush();
  446. _lua_environment->reset_temporaries();
  447. _frame_count++;
  448. }
  449. _lua_environment->call_global("shutdown", 0);
  450. boot_package->unload();
  451. destroy_resource_package(*boot_package);
  452. physics_globals::shutdown(_allocator);
  453. audio_globals::shutdown();
  454. CE_DELETE(_allocator, _lua_environment);
  455. CE_DELETE(_allocator, _unit_manager);
  456. CE_DELETE(_allocator, _input_manager);
  457. CE_DELETE(_allocator, _material_manager);
  458. CE_DELETE(_allocator, _shader_manager);
  459. CE_DELETE(_allocator, _resource_manager);
  460. CE_DELETE(_allocator, _resource_loader);
  461. bgfx::shutdown();
  462. window::destroy(_allocator, *_window);
  463. display::destroy(_allocator, *_display);
  464. CE_DELETE(_allocator, _bgfx_callback);
  465. CE_DELETE(_allocator, _bgfx_allocator);
  466. if (_last_log)
  467. _bundle_filesystem->close(*_last_log);
  468. CE_DELETE(_allocator, _bundle_filesystem);
  469. profiler_globals::shutdown();
  470. }
  471. _console_server->shutdown();
  472. CE_DELETE(_allocator, _console_server);
  473. CE_DELETE(_allocator, _data_compiler);
  474. _allocator.clear();
  475. }
  476. void Device::quit()
  477. {
  478. _quit = true;
  479. }
  480. void Device::pause()
  481. {
  482. _paused = true;
  483. logi("Engine paused.");
  484. }
  485. void Device::unpause()
  486. {
  487. _paused = false;
  488. logi("Engine unpaused.");
  489. }
  490. void Device::resolution(u16& width, u16& height)
  491. {
  492. width = _width;
  493. height = _height;
  494. }
  495. u64 Device::frame_count() const
  496. {
  497. return _frame_count;
  498. }
  499. f32 Device::last_delta_time() const
  500. {
  501. return _last_delta_time;
  502. }
  503. f64 Device::time_since_start() const
  504. {
  505. return _time_since_start;
  506. }
  507. void Device::render(World& world, CameraInstance camera)
  508. {
  509. bgfx::setViewClear(0
  510. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  511. , 0x353839ff
  512. , 1.0f
  513. , 0
  514. );
  515. bgfx::setViewRect(0, 0, 0, _width, _height);
  516. bgfx::setViewRect(1, 0, 0, _width, _height);
  517. bgfx::setViewRect(2, 0, 0, _width, _height);
  518. const f32* view = to_float_ptr(world.camera_view_matrix(camera));
  519. const f32* proj = to_float_ptr(world.camera_projection_matrix(camera));
  520. bgfx::setViewTransform(0, view, proj);
  521. bgfx::setViewTransform(1, view, proj);
  522. bgfx::setViewTransform(2, to_float_ptr(MATRIX4X4_IDENTITY), to_float_ptr(MATRIX4X4_IDENTITY));
  523. bgfx::setViewSeq(2, true);
  524. bgfx::touch(0);
  525. bgfx::touch(1);
  526. bgfx::touch(2);
  527. float aspect_ratio = (_boot_config.aspect_ratio == -1.0f
  528. ? (float)_width/(float)_height
  529. : _boot_config.aspect_ratio
  530. );
  531. world.camera_set_aspect(camera, aspect_ratio);
  532. world.camera_set_viewport_metrics(camera, 0, 0, _width, _height);
  533. world.render(world.camera_view_matrix(camera), world.camera_projection_matrix(camera));
  534. }
  535. World* Device::create_world()
  536. {
  537. World* w = CE_NEW(default_allocator(), World)(default_allocator()
  538. , *_resource_manager
  539. , *_shader_manager
  540. , *_material_manager
  541. , *_unit_manager
  542. , *_lua_environment
  543. );
  544. array::push_back(_worlds, w);
  545. return w;
  546. }
  547. void Device::destroy_world(World& w)
  548. {
  549. for (u32 i = 0, n = array::size(_worlds); i < n; ++i)
  550. {
  551. if (&w == _worlds[i])
  552. {
  553. CE_DELETE(default_allocator(), &w);
  554. _worlds[i] = _worlds[n - 1];
  555. array::pop_back(_worlds);
  556. return;
  557. }
  558. }
  559. CE_FATAL("Bad world");
  560. }
  561. ResourcePackage* Device::create_resource_package(StringId64 id)
  562. {
  563. return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
  564. }
  565. void Device::destroy_resource_package(ResourcePackage& rp)
  566. {
  567. CE_DELETE(default_allocator(), &rp);
  568. }
  569. void Device::reload(StringId64 type, StringId64 name)
  570. {
  571. _resource_manager->reload(type, name);
  572. const void* new_resource = _resource_manager->get(type, name);
  573. if (type == RESOURCE_TYPE_SCRIPT)
  574. {
  575. _lua_environment->execute((const LuaResource*)new_resource);
  576. }
  577. }
  578. static StringStream& sanitize(StringStream& ss, const char* msg)
  579. {
  580. using namespace string_stream;
  581. const char* ch = msg;
  582. for (; *ch; ch++)
  583. {
  584. if (*ch == '"' || *ch == '\\')
  585. ss << "\\";
  586. ss << *ch;
  587. }
  588. return ss;
  589. }
  590. static const char* s_severity_map[] = { "info", "warning", "error", "debug" };
  591. CE_STATIC_ASSERT(countof(s_severity_map) == LogSeverity::COUNT);
  592. void Device::log(const char* msg, LogSeverity::Enum severity)
  593. {
  594. if (_last_log)
  595. {
  596. _last_log->write(msg, strlen32(msg));
  597. _last_log->write("\n", 1);
  598. _last_log->flush();
  599. }
  600. if (_console_server)
  601. {
  602. TempAllocator4096 ta;
  603. StringStream json(ta);
  604. json << "{\"type\":\"message\",";
  605. json << "\"severity\":\"" << s_severity_map[severity] << "\",";
  606. json << "\"message\":\""; sanitize(json, msg) << "\"}";
  607. _console_server->send(string_stream::c_str(json));
  608. }
  609. }
  610. ConsoleServer* Device::console_server()
  611. {
  612. return _console_server;
  613. }
  614. DataCompiler* Device::data_compiler()
  615. {
  616. return _data_compiler;
  617. }
  618. ResourceManager* Device::resource_manager()
  619. {
  620. return _resource_manager;
  621. }
  622. LuaEnvironment* Device::lua_environment()
  623. {
  624. return _lua_environment;
  625. }
  626. InputManager* Device::input_manager()
  627. {
  628. return _input_manager;
  629. }
  630. ShaderManager* Device::shader_manager()
  631. {
  632. return _shader_manager;
  633. }
  634. MaterialManager* Device::material_manager()
  635. {
  636. return _material_manager;
  637. }
  638. UnitManager* Device::unit_manager()
  639. {
  640. return _unit_manager;
  641. }
  642. Display* Device::display()
  643. {
  644. return _display;
  645. }
  646. Window* Device::window()
  647. {
  648. return _window;
  649. }
  650. char _buffer[sizeof(Device)];
  651. Device* _device = NULL;
  652. void run(const DeviceOptions& opts)
  653. {
  654. CE_ASSERT(_device == NULL, "Crown already initialized");
  655. _device = new (_buffer) Device(opts);
  656. _device->run();
  657. _device->~Device();
  658. _device = NULL;
  659. }
  660. Device* device()
  661. {
  662. return crown::_device;
  663. }
  664. } // namespace crown