device.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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 "console_server.h"
  9. #include "device.h"
  10. #include "disk_filesystem.h"
  11. #include "filesystem.h"
  12. #include "input_device.h"
  13. #include "input_manager.h"
  14. #include "log.h"
  15. #include "lua_environment.h"
  16. #include "map.h"
  17. #include "material_manager.h"
  18. #include "memory.h"
  19. #include "os.h"
  20. #include "path.h"
  21. #include "physics.h"
  22. #include "profiler.h"
  23. #include "proxy_allocator.h"
  24. #include "resource_loader.h"
  25. #include "resource_manager.h"
  26. #include "resource_package.h"
  27. #include "shader_manager.h"
  28. #include "sjson.h"
  29. #include "string_utils.h"
  30. #include "types.h"
  31. #include "unit_manager.h"
  32. #include "vector3.h"
  33. #include "world.h"
  34. #include <bgfx/bgfx.h>
  35. #include <bx/allocator.h>
  36. #if CROWN_PLATFORM_ANDROID
  37. #include "apk_filesystem.h"
  38. #endif // CROWN_PLATFORM_ANDROID
  39. #define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024
  40. namespace crown
  41. {
  42. struct BgfxCallback : public bgfx::CallbackI
  43. {
  44. virtual void fatal(bgfx::Fatal::Enum _code, const char* _str)
  45. {
  46. CE_ASSERT(false, "Fatal error: 0x%08x: %s", _code, _str);
  47. }
  48. virtual void traceVargs(const char* /*_filePath*/, uint16_t /*_line*/, const char* _format, va_list _argList)
  49. {
  50. char buf[2048];
  51. strncpy(buf, _format, sizeof(buf));
  52. buf[strlen32(buf)-1] = '\0'; // Remove trailing newline
  53. CE_LOGDV(buf, _argList);
  54. }
  55. virtual uint32_t cacheReadSize(uint64_t /*_id*/)
  56. {
  57. return 0;
  58. }
  59. virtual bool cacheRead(uint64_t /*_id*/, void* /*_data*/, uint32_t /*_size*/)
  60. {
  61. return false;
  62. }
  63. virtual void cacheWrite(uint64_t /*_id*/, const void* /*_data*/, uint32_t /*_size*/)
  64. {
  65. }
  66. virtual void screenShot(const char* /*_filePath*/, uint32_t /*_width*/, uint32_t /*_height*/, uint32_t /*_pitch*/, const void* /*_data*/, uint32_t /*_size*/, bool /*_yflip*/)
  67. {
  68. }
  69. virtual void captureBegin(uint32_t /*_width*/, uint32_t /*_height*/, uint32_t /*_pitch*/, bgfx::TextureFormat::Enum /*_format*/, bool /*_yflip*/)
  70. {
  71. }
  72. virtual void captureEnd()
  73. {
  74. }
  75. virtual void captureFrame(const void* /*_data*/, uint32_t /*_size*/)
  76. {
  77. }
  78. };
  79. struct BgfxAllocator : public bx::AllocatorI
  80. {
  81. BgfxAllocator(Allocator& a)
  82. : _allocator("bgfx", a)
  83. {
  84. }
  85. virtual void* realloc(void* _ptr, size_t _size, size_t _align, const char* /*_file*/, uint32_t /*_line*/)
  86. {
  87. if (!_ptr)
  88. return _allocator.allocate((uint32_t)_size, (uint32_t)_align == 0 ? 1 : (uint32_t)_align);
  89. if (_size == 0)
  90. {
  91. _allocator.deallocate(_ptr);
  92. return NULL;
  93. }
  94. // Realloc
  95. void* p = _allocator.allocate((uint32_t)_size, (uint32_t)_align == 0 ? 1 : (uint32_t)_align);
  96. _allocator.deallocate(_ptr);
  97. return p;
  98. }
  99. private:
  100. ProxyAllocator _allocator;
  101. };
  102. Device::Device(const DeviceOptions& opts)
  103. : _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)
  104. , _device_options(opts)
  105. , _bundle_filesystem(NULL)
  106. , _resource_loader(NULL)
  107. , _resource_manager(NULL)
  108. , _bgfx_allocator(NULL)
  109. , _bgfx_callback(NULL)
  110. , _shader_manager(NULL)
  111. , _material_manager(NULL)
  112. , _input_manager(NULL)
  113. , _unit_manager(NULL)
  114. , _lua_environment(NULL)
  115. , _window(NULL)
  116. , _boot_package_id(uint64_t(0))
  117. , _boot_script_id(uint64_t(0))
  118. , _boot_package(NULL)
  119. , _worlds(default_allocator())
  120. , _width(0)
  121. , _height(0)
  122. , _mouse_curr_x(0)
  123. , _mouse_curr_y(0)
  124. , _mouse_last_x(0)
  125. , _mouse_last_y(0)
  126. , _is_init(false)
  127. , _is_running(false)
  128. , _is_paused(false)
  129. , _frame_count(0)
  130. , _last_time(0)
  131. , _current_time(0)
  132. , _last_delta_time(0.0f)
  133. , _time_since_start(0.0)
  134. {
  135. }
  136. void Device::init()
  137. {
  138. // Initialize
  139. CE_LOGI("Initializing Crown Engine %s...", version());
  140. profiler_globals::init();
  141. #if CROWN_PLATFORM_ANDROID
  142. _bundle_filesystem = CE_NEW(_allocator, ApkFilesystem)(const_cast<AAssetManager*>(_device_options.asset_manager()));
  143. #else
  144. _bundle_filesystem = CE_NEW(_allocator, DiskFilesystem)(_device_options.bundle_dir());
  145. #endif // CROWN_PLATFORM_ANDROID
  146. _resource_loader = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem);
  147. _resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);
  148. read_config();
  149. _bgfx_allocator = CE_NEW(_allocator, BgfxAllocator)(default_allocator());
  150. _bgfx_callback = CE_NEW(_allocator, BgfxCallback)();
  151. _window = Window::create(_allocator);
  152. _window->open(_device_options.window_x()
  153. , _device_options.window_y()
  154. , _device_options.window_width()
  155. , _device_options.window_height()
  156. , _device_options.parent_window()
  157. );
  158. _window->bgfx_setup();
  159. bgfx::init(bgfx::RendererType::Count
  160. , BGFX_PCI_ID_NONE
  161. , 0
  162. , _bgfx_callback
  163. , _bgfx_allocator
  164. );
  165. _shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
  166. _material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager);
  167. _input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
  168. _unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());
  169. _lua_environment = CE_NEW(_allocator, LuaEnvironment)();
  170. audio_globals::init();
  171. physics_globals::init();
  172. _boot_package = create_resource_package(_boot_package_id);
  173. _boot_package->load();
  174. _boot_package->flush();
  175. _lua_environment->load_libs();
  176. _lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id));
  177. _lua_environment->call_global("init", 0);
  178. _is_init = true;
  179. _is_running = true;
  180. _last_time = os::clocktime();
  181. CE_LOGD("Engine initialized");
  182. }
  183. void Device::shutdown()
  184. {
  185. CE_ASSERT(_is_init, "Engine is not initialized");
  186. _is_running = false;
  187. _is_init = false;
  188. _lua_environment->call_global("shutdown", 0);
  189. _boot_package->unload();
  190. destroy_resource_package(*_boot_package);
  191. physics_globals::shutdown();
  192. audio_globals::shutdown();
  193. CE_DELETE(_allocator, _lua_environment);
  194. CE_DELETE(_allocator, _unit_manager);
  195. CE_DELETE(_allocator, _input_manager);
  196. CE_DELETE(_allocator, _material_manager);
  197. CE_DELETE(_allocator, _shader_manager);
  198. CE_DELETE(_allocator, _resource_manager);
  199. CE_DELETE(_allocator, _resource_loader);
  200. CE_DELETE(_allocator, _bundle_filesystem);
  201. bgfx::shutdown();
  202. Window::destroy(_allocator, *_window);
  203. CE_DELETE(_allocator, _bgfx_callback);
  204. CE_DELETE(_allocator, _bgfx_allocator);
  205. profiler_globals::shutdown();
  206. _allocator.clear();
  207. }
  208. void Device::quit()
  209. {
  210. _is_running = false;
  211. }
  212. void Device::pause()
  213. {
  214. _is_paused = true;
  215. CE_LOGI("Engine paused.");
  216. }
  217. void Device::unpause()
  218. {
  219. _is_paused = false;
  220. CE_LOGI("Engine unpaused.");
  221. }
  222. void Device::resolution(uint16_t& width, uint16_t& height)
  223. {
  224. width = _width;
  225. height = _height;
  226. }
  227. bool Device::is_running() const
  228. {
  229. return _is_running;
  230. }
  231. uint64_t Device::frame_count() const
  232. {
  233. return _frame_count;
  234. }
  235. float Device::last_delta_time() const
  236. {
  237. return _last_delta_time;
  238. }
  239. double Device::time_since_start() const
  240. {
  241. return _time_since_start;
  242. }
  243. void Device::update()
  244. {
  245. while (!process_events() && _is_running)
  246. {
  247. _current_time = os::clocktime();
  248. const int64_t time = _current_time - _last_time;
  249. _last_time = _current_time;
  250. const double freq = (double) os::clockfrequency();
  251. _last_delta_time = time * (1.0 / freq);
  252. _time_since_start += _last_delta_time;
  253. profiler_globals::clear();
  254. console_server_globals::update();
  255. RECORD_FLOAT("device.dt", _last_delta_time);
  256. RECORD_FLOAT("device.fps", 1.0f/_last_delta_time);
  257. if (!_is_paused)
  258. {
  259. _resource_manager->complete_requests();
  260. _lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time());
  261. _lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time());
  262. }
  263. _input_manager->update();
  264. const bgfx::Stats* stats = bgfx::getStats();
  265. RECORD_FLOAT("bgfx.gpu_time", double(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq);
  266. RECORD_FLOAT("bgfx.cpu_time", double(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq);
  267. bgfx::frame();
  268. profiler_globals::flush();
  269. _lua_environment->reset_temporaries();
  270. _frame_count++;
  271. }
  272. }
  273. void Device::render_world(World& world, CameraInstance camera)
  274. {
  275. world.render(camera);
  276. }
  277. World* Device::create_world()
  278. {
  279. World* w = CE_NEW(default_allocator(), World)(default_allocator()
  280. , *_resource_manager
  281. , *_shader_manager
  282. , *_material_manager
  283. , *_unit_manager
  284. , *_lua_environment
  285. );
  286. array::push_back(_worlds, w);
  287. return w;
  288. }
  289. void Device::destroy_world(World& w)
  290. {
  291. for (uint32_t i = 0, n = array::size(_worlds); i < n; ++i)
  292. {
  293. if (&w == _worlds[i])
  294. {
  295. CE_DELETE(default_allocator(), &w);
  296. _worlds[i] = _worlds[n - 1];
  297. array::pop_back(_worlds);
  298. return;
  299. }
  300. }
  301. CE_ASSERT(false, "Bad world");
  302. }
  303. ResourcePackage* Device::create_resource_package(StringId64 id)
  304. {
  305. return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
  306. }
  307. void Device::destroy_resource_package(ResourcePackage& rp)
  308. {
  309. CE_DELETE(default_allocator(), &rp);
  310. }
  311. void Device::reload(StringId64 type, StringId64 name)
  312. {
  313. const void* old_resource = _resource_manager->get(type, name);
  314. _resource_manager->reload(type, name);
  315. const void* new_resource = _resource_manager->get(type, name);
  316. if (type == SCRIPT_TYPE)
  317. {
  318. _lua_environment->execute((const LuaResource*)new_resource);
  319. }
  320. }
  321. ResourceManager* Device::resource_manager()
  322. {
  323. return _resource_manager;
  324. }
  325. LuaEnvironment* Device::lua_environment()
  326. {
  327. return _lua_environment;
  328. }
  329. InputManager* Device::input_manager()
  330. {
  331. return _input_manager;
  332. }
  333. ShaderManager* Device::shader_manager()
  334. {
  335. return _shader_manager;
  336. }
  337. MaterialManager* Device::material_manager()
  338. {
  339. return _material_manager;
  340. }
  341. UnitManager* Device::unit_manager()
  342. {
  343. return _unit_manager;
  344. }
  345. Window* Device::window()
  346. {
  347. return _window;
  348. }
  349. void Device::read_config()
  350. {
  351. TempAllocator4096 ta;
  352. DynamicString boot_dir(ta);
  353. if (_device_options.boot_dir() != NULL)
  354. {
  355. boot_dir += _device_options.boot_dir();
  356. boot_dir += '/';
  357. }
  358. boot_dir += CROWN_BOOT_CONFIG;
  359. const StringId64 config_name(boot_dir.c_str());
  360. _resource_manager->load(CONFIG_TYPE, config_name);
  361. _resource_manager->flush();
  362. const char* cfile = (const char*)_resource_manager->get(CONFIG_TYPE, config_name);
  363. JsonObject config(ta);
  364. sjson::parse(cfile, config);
  365. _boot_script_id = sjson::parse_resource_id(config["boot_script"]);
  366. _boot_package_id = sjson::parse_resource_id(config["boot_package"]);
  367. _resource_manager->unload(CONFIG_TYPE, config_name);
  368. }
  369. bool Device::process_events()
  370. {
  371. OsEvent event;
  372. bool exit = false;
  373. InputManager* im = _input_manager;
  374. const int16_t dt_x = _mouse_curr_x - _mouse_last_x;
  375. const int16_t dt_y = _mouse_curr_y - _mouse_last_y;
  376. im->mouse()->set_axis(MouseAxis::CURSOR_DELTA, vector3(dt_x, dt_y, 0.0f));
  377. _mouse_last_x = _mouse_curr_x;
  378. _mouse_last_y = _mouse_curr_y;
  379. while(next_event(event))
  380. {
  381. if (event.type == OsEvent::NONE) continue;
  382. switch (event.type)
  383. {
  384. case OsEvent::TOUCH:
  385. {
  386. const OsTouchEvent& ev = event.touch;
  387. switch (ev.type)
  388. {
  389. case OsTouchEvent::POINTER:
  390. im->touch()->set_button_state(ev.pointer_id, ev.pressed);
  391. break;
  392. case OsTouchEvent::MOVE:
  393. im->touch()->set_axis(ev.pointer_id, vector3(ev.x, ev.y, 0.0f));
  394. break;
  395. default:
  396. CE_FATAL("Unknown touch event type");
  397. break;
  398. }
  399. break;
  400. }
  401. case OsEvent::MOUSE:
  402. {
  403. const OsMouseEvent& ev = event.mouse;
  404. switch (ev.type)
  405. {
  406. case OsMouseEvent::BUTTON:
  407. im->mouse()->set_button_state(ev.button, ev.pressed);
  408. break;
  409. case OsMouseEvent::MOVE:
  410. _mouse_curr_x = ev.x;
  411. _mouse_curr_y = ev.y;
  412. im->mouse()->set_axis(MouseAxis::CURSOR, vector3(ev.x, ev.y, 0.0f));
  413. break;
  414. case OsMouseEvent::WHEEL:
  415. im->mouse()->set_axis(MouseAxis::WHEEL, vector3(0.0f, ev.wheel, 0.0f));
  416. break;
  417. default:
  418. CE_FATAL("Unknown mouse event type");
  419. break;
  420. }
  421. break;
  422. }
  423. case OsEvent::KEYBOARD:
  424. {
  425. const OsKeyboardEvent& ev = event.keyboard;
  426. im->keyboard()->set_button_state(ev.button, ev.pressed);
  427. break;
  428. }
  429. case OsEvent::JOYPAD:
  430. {
  431. const OsJoypadEvent& ev = event.joypad;
  432. switch (ev.type)
  433. {
  434. case OsJoypadEvent::CONNECTED:
  435. im->joypad(ev.index)->set_connected(ev.connected);
  436. break;
  437. case OsJoypadEvent::BUTTON:
  438. im->joypad(ev.index)->set_button_state(ev.button, ev.pressed);
  439. break;
  440. case OsJoypadEvent::AXIS:
  441. im->joypad(ev.index)->set_axis(ev.button, vector3(ev.x, ev.y, ev.z));
  442. break;
  443. default:
  444. CE_FATAL("Unknown joypad event");
  445. break;
  446. }
  447. break;
  448. }
  449. case OsEvent::METRICS:
  450. {
  451. const OsMetricsEvent& ev = event.metrics;
  452. _width = ev.width;
  453. _height = ev.height;
  454. bgfx::reset(ev.width, ev.height, BGFX_RESET_VSYNC);
  455. break;
  456. }
  457. case OsEvent::EXIT:
  458. {
  459. exit = true;
  460. break;
  461. }
  462. case OsEvent::PAUSE:
  463. {
  464. pause();
  465. break;
  466. }
  467. case OsEvent::RESUME:
  468. {
  469. unpause();
  470. break;
  471. }
  472. default:
  473. {
  474. CE_FATAL("Unknown Os Event");
  475. break;
  476. }
  477. }
  478. }
  479. return exit;
  480. }
  481. char _buffer[sizeof(Device)];
  482. Device* _device = NULL;
  483. void init(const DeviceOptions& opts)
  484. {
  485. CE_ASSERT(_device == NULL, "Crown already initialized");
  486. _device = new (_buffer) Device(opts);
  487. _device->init();
  488. }
  489. void update()
  490. {
  491. _device->update();
  492. }
  493. void shutdown()
  494. {
  495. _device->shutdown();
  496. _device->~Device();
  497. _device = NULL;
  498. }
  499. Device* device()
  500. {
  501. return crown::_device;
  502. }
  503. } // namespace crown