1 #include "Application.hpp"
3 #include "Environment.hpp"
4 #include "FrameCounter.hpp"
6 #include "StateControl.hpp"
7 #include "TextureIndex.hpp"
10 #include "../audio/Sound.hpp"
11 #include "../graphics/ArrayTexture.hpp"
12 #include "../graphics/Font.hpp"
13 #include "../graphics/Texture.hpp"
14 #include "../io/TokenStreamReader.hpp"
15 #include "../model/shapes.hpp"
16 #include "../world/BlockType.hpp"
17 #include "../world/BlockTypeRegistry.hpp"
18 #include "../world/Entity.hpp"
24 #include <SDL_image.h>
26 using std::runtime_error;
32 HeadlessApplication::HeadlessApplication(HeadlessEnvironment &e)
38 HeadlessApplication::~HeadlessApplication() {
43 Application::Application(Environment &e)
44 : HeadlessApplication(e)
49 Application::~Application() {
54 void HeadlessApplication::RunN(size_t n) {
55 Uint32 last = SDL_GetTicks();
56 for (size_t i = 0; HasState() && i < n; ++i) {
57 Uint32 now = SDL_GetTicks();
58 int delta = now - last;
64 void HeadlessApplication::RunT(size_t t) {
65 Uint32 last = SDL_GetTicks();
66 Uint32 finish = last + t;
67 while (HasState() && last < finish) {
68 Uint32 now = SDL_GetTicks();
69 int delta = now - last;
75 void HeadlessApplication::RunS(size_t n, size_t t) {
76 for (size_t i = 0; HasState() && i < n; ++i) {
80 std::cout << std::setfill(' ') << std::setw(5) << std::right << (i + 1) << std::endl;
82 std::cout << std::flush;
88 void HeadlessApplication::Run() {
89 Uint32 last = SDL_GetTicks();
91 Uint32 now = SDL_GetTicks();
92 int delta = now - last;
98 void HeadlessApplication::Loop(int dt) {
99 env.counter.EnterFrame();
102 if (!HasState()) return;
103 env.counter.ExitFrame();
106 void Application::Loop(int dt) {
107 env.counter.EnterFrame();
109 if (!HasState()) return;
112 if (!HasState()) return;
114 env.counter.ExitFrame();
118 void HeadlessApplication::HandleEvents() {
119 env.counter.EnterHandle();
121 while (HasState() && SDL_PollEvent(&event)) {
125 env.counter.ExitHandle();
128 void HeadlessApplication::Handle(const SDL_Event &event) {
129 GetState().Handle(event);
133 void Application::HandleEvents() {
134 env.counter.EnterHandle();
136 while (HasState() && SDL_PollEvent(&event)) {
140 env.counter.ExitHandle();
143 void Application::Handle(const SDL_Event &event) {
144 switch (event.type) {
145 case SDL_WINDOWEVENT:
146 Handle(event.window);
149 GetState().Handle(event);
154 void Application::Handle(const SDL_WindowEvent &event) {
155 switch (event.event) {
156 case SDL_WINDOWEVENT_FOCUS_GAINED:
157 env.window.GrabMouse();
159 case SDL_WINDOWEVENT_FOCUS_LOST:
160 env.window.ReleaseMouse();
162 case SDL_WINDOWEVENT_RESIZED:
163 env.viewport.Resize(event.data1, event.data2);
170 void HeadlessApplication::Update(int dt) {
171 env.counter.EnterUpdate();
173 GetState().Update(dt);
175 env.counter.ExitUpdate();
178 void Application::Update(int dt) {
179 env.counter.EnterUpdate();
180 env.audio.Update(dt);
182 GetState().Update(dt);
184 env.counter.ExitUpdate();
187 void Application::Render() {
188 // gl implementation may (and will probably) delay vsync blocking until
189 // the first write after flipping, which is this clear call
190 env.viewport.Clear();
191 env.counter.EnterRender();
194 GetState().Render(env.viewport);
197 env.counter.ExitRender();
202 void HeadlessApplication::PushState(State *s) {
203 if (!states.empty()) {
204 states.top()->OnPause();
208 if (s->ref_count == 1) {
214 State *HeadlessApplication::PopState() {
215 State *s = states.top();
219 if (!states.empty()) {
220 states.top()->OnResume();
225 State *HeadlessApplication::SwitchState(State *s_new) {
226 State *s_old = states.top();
227 states.top() = s_new;
231 if (s_old->ref_count == 0) {
234 if (s_new->ref_count == 1) {
241 State &HeadlessApplication::GetState() {
242 return *states.top();
245 void HeadlessApplication::CommitStates() {
246 env.state.Commit(*this);
249 bool HeadlessApplication::HasState() const noexcept {
250 return !states.empty();
254 void StateControl::Commit(HeadlessApplication &app) {
255 while (!cue.empty()) {
260 app.PushState(m.state);
263 app.SwitchState(m.state);
269 while (app.HasState()) {
278 AssetLoader::AssetLoader(const string &base)
279 : fonts(base + "fonts/")
280 , sounds(base + "sounds/")
281 , textures(base + "textures/")
282 , data(base + "data/") {
286 Assets::Assets(const AssetLoader &loader)
287 : large_ui_font(loader.LoadFont("DejaVuSans", 24))
288 , small_ui_font(loader.LoadFont("DejaVuSans", 16)) {
294 CuboidShape block_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f }});
295 StairShape stair_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f }}, { 0.0f, 0.0f });
296 CuboidShape slab_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.0f, 0.5f }});
300 void AssetLoader::LoadBlockTypes(const std::string &set_name, BlockTypeRegistry ®, TextureIndex &tex_index) const {
301 string full = data + set_name + ".types";
302 std::ifstream file(full);
304 throw std::runtime_error("failed to open block type file " + full);
306 TokenStreamReader in(file);
311 while (in.HasMore()) {
312 in.ReadIdentifier(type_name);
313 in.Skip(Token::EQUALS);
317 in.Skip(Token::ANGLE_BRACKET_OPEN);
318 while (in.Peek().type != Token::ANGLE_BRACKET_CLOSE) {
319 in.ReadIdentifier(name);
320 in.Skip(Token::EQUALS);
321 if (name == "visible") {
322 type.visible = in.GetBool();
323 } else if (name == "texture") {
324 in.ReadString(tex_name);
325 type.texture = tex_index.GetID(tex_name);
326 } else if (name == "color") {
327 in.ReadVec(type.color);
328 } else if (name == "outline") {
329 in.ReadVec(type.outline_color);
330 } else if (name == "label") {
331 in.ReadString(type.label);
332 } else if (name == "luminosity") {
333 type.luminosity = in.GetInt();
334 } else if (name == "block_light") {
335 type.block_light = in.GetBool();
336 } else if (name == "collision") {
337 type.collision = in.GetBool();
338 } else if (name == "collide_block") {
339 type.collide_block = in.GetBool();
340 } else if (name == "shape") {
341 in.ReadIdentifier(shape_name);
342 if (shape_name == "block") {
343 type.shape = &block_shape;
344 type.fill = { true, true, true, true, true, true };
345 } else if (shape_name == "slab") {
346 type.shape = &slab_shape;
347 type.fill = { false, true, false, false, false, false };
348 } else if (shape_name == "stair") {
349 type.shape = &stair_shape;
350 type.fill = { false, true, false, false, false, true };
352 throw runtime_error("unknown block shape: " + shape_name);
355 throw runtime_error("unknown block property: " + name);
357 in.Skip(Token::SEMICOLON);
359 in.Skip(Token::ANGLE_BRACKET_CLOSE);
360 in.Skip(Token::SEMICOLON);
366 Font AssetLoader::LoadFont(const string &name, int size) const {
367 string full = fonts + name + ".ttf";
368 return Font(full.c_str(), size);
371 Sound AssetLoader::LoadSound(const string &name) const {
372 string full = sounds + name + ".wav";
373 return Sound(full.c_str());
376 Texture AssetLoader::LoadTexture(const string &name) const {
377 string full = textures + name + ".png";
379 SDL_Surface *srf = IMG_Load(full.c_str());
381 throw SDLError("IMG_Load");
385 SDL_FreeSurface(srf);
389 void AssetLoader::LoadTexture(const string &name, ArrayTexture &tex, int layer) const {
390 string full = textures + name + ".png";
391 SDL_Surface *srf = IMG_Load(full.c_str());
393 throw SDLError("IMG_Load");
397 tex.Data(layer, *srf);
399 SDL_FreeSurface(srf);
402 SDL_FreeSurface(srf);
405 void AssetLoader::LoadTextures(const TextureIndex &index, ArrayTexture &tex) const {
406 // TODO: where the hell should that size come from?
407 tex.Reserve(16, 16, index.Size(), Format());
408 for (const auto &entry : index.Entries()) {
409 LoadTexture(entry.first, tex, entry.second);
414 TextureIndex::TextureIndex()
419 int TextureIndex::GetID(const string &name) {
420 auto entry = id_map.find(name);
421 if (entry == id_map.end()) {
422 auto result = id_map.emplace(name, Size());
423 return result.first->second;
425 return entry->second;
430 void FrameCounter::EnterFrame() noexcept {
431 last_enter = SDL_GetTicks();
432 last_tick = last_enter;
435 void FrameCounter::EnterHandle() noexcept {
439 void FrameCounter::ExitHandle() noexcept {
440 current.handle = Tick();
443 void FrameCounter::EnterUpdate() noexcept {
447 void FrameCounter::ExitUpdate() noexcept {
448 current.update = Tick();
451 void FrameCounter::EnterRender() noexcept {
455 void FrameCounter::ExitRender() noexcept {
456 current.render = Tick();
459 void FrameCounter::ExitFrame() noexcept {
460 Uint32 now = SDL_GetTicks();
461 current.total = now - last_enter;
462 current.running = current.handle + current.update + current.render;
463 current.waiting = current.total - current.running;
467 if (cur_frame >= NUM_FRAMES) {
476 int FrameCounter::Tick() noexcept {
477 Uint32 now = SDL_GetTicks();
478 int delta = now - last_tick;
483 void FrameCounter::Accumulate() noexcept {
484 sum.handle += current.handle;
485 sum.update += current.update;
486 sum.render += current.render;
487 sum.running += current.running;
488 sum.waiting += current.waiting;
489 sum.total += current.total;
491 max.handle = std::max(current.handle, max.handle);
492 max.update = std::max(current.update, max.update);
493 max.render = std::max(current.render, max.render);
494 max.running = std::max(current.running, max.running);
495 max.waiting = std::max(current.waiting, max.waiting);
496 max.total = std::max(current.total, max.total);
498 current = Frame<int>();
501 void FrameCounter::Push() noexcept {
503 avg.handle = sum.handle * factor;
504 avg.update = sum.update * factor;
505 avg.render = sum.render * factor;
506 avg.running = sum.running * factor;
507 avg.waiting = sum.waiting * factor;
508 avg.total = sum.total * factor;