]> git.localhorst.tv Git - blank.git/blob - src/app/app.cpp
lil cleanup of common and unused stuff
[blank.git] / src / app / app.cpp
1 #include "Application.hpp"
2 #include "Assets.hpp"
3 #include "Environment.hpp"
4 #include "FrameCounter.hpp"
5 #include "State.hpp"
6 #include "StateControl.hpp"
7
8 #include "init.hpp"
9 #include "../audio/Sound.hpp"
10 #include "../graphics/ArrayTexture.hpp"
11 #include "../graphics/CubeMap.hpp"
12 #include "../graphics/Font.hpp"
13 #include "../graphics/Texture.hpp"
14 #include "../io/TokenStreamReader.hpp"
15 #include "../model/bounds.hpp"
16 #include "../model/Model.hpp"
17 #include "../model/ModelRegistry.hpp"
18 #include "../model/Shape.hpp"
19 #include "../model/ShapeRegistry.hpp"
20 #include "../shared/ResourceIndex.hpp"
21 #include "../world/BlockType.hpp"
22 #include "../world/BlockTypeRegistry.hpp"
23 #include "../world/Entity.hpp"
24
25 #include <fstream>
26 #include <iomanip>
27 #include <iostream>
28 #include <stdexcept>
29 #include <SDL_image.h>
30
31 using std::runtime_error;
32 using std::string;
33
34
35 namespace blank {
36
37 HeadlessApplication::HeadlessApplication(HeadlessEnvironment &e)
38 : env(e)
39 , states() {
40
41 }
42
43 HeadlessApplication::~HeadlessApplication() {
44
45 }
46
47
48 Application::Application(Environment &e)
49 : HeadlessApplication(e)
50 , env(e) {
51
52 }
53
54 Application::~Application() {
55         env.audio.StopAll();
56 }
57
58
59 void HeadlessApplication::RunN(size_t n) {
60         Uint32 last = SDL_GetTicks();
61         for (size_t i = 0; HasState() && i < n; ++i) {
62                 Uint32 now = SDL_GetTicks();
63                 int delta = now - last;
64                 Loop(delta);
65                 last = now;
66         }
67 }
68
69 void HeadlessApplication::RunT(size_t t) {
70         Uint32 last = SDL_GetTicks();
71         Uint32 finish = last + t;
72         while (HasState() && last < finish) {
73                 Uint32 now = SDL_GetTicks();
74                 int delta = now - last;
75                 Loop(delta);
76                 last = now;
77         }
78 }
79
80 void HeadlessApplication::RunS(size_t n, size_t t) {
81         for (size_t i = 0; HasState() && i < n; ++i) {
82                 Loop(t);
83                 std::cout << '.';
84                 if (i % 16 == 15) {
85                         std::cout << std::setfill(' ') << std::setw(5) << std::right << (i + 1) << std::endl;
86                 } else {
87                         std::cout << std::flush;
88                 }
89         }
90 }
91
92
93 void HeadlessApplication::Run() {
94         Uint32 last = SDL_GetTicks();
95         while (HasState()) {
96                 Uint32 now = SDL_GetTicks();
97                 int delta = now - last;
98                 Loop(delta);
99                 last = now;
100         }
101 }
102
103 void HeadlessApplication::Loop(int dt) {
104         env.counter.EnterFrame();
105         HandleEvents();
106         if (!HasState()) return;
107         Update(dt);
108         CommitStates();
109         if (!HasState()) return;
110         env.counter.ExitFrame();
111 }
112
113 void Application::Loop(int dt) {
114         env.counter.EnterFrame();
115         HandleEvents();
116         if (!HasState()) return;
117         Update(dt);
118         CommitStates();
119         if (!HasState()) return;
120         Render();
121         env.counter.ExitFrame();
122 }
123
124
125 void HeadlessApplication::HandleEvents() {
126         env.counter.EnterHandle();
127         SDL_Event event;
128         while (HasState() && SDL_PollEvent(&event)) {
129                 Handle(event);
130                 CommitStates();
131         }
132         env.counter.ExitHandle();
133 }
134
135 void HeadlessApplication::Handle(const SDL_Event &event) {
136         GetState().Handle(event);
137 }
138
139
140 void Application::HandleEvents() {
141         env.counter.EnterHandle();
142         SDL_Event event;
143         while (HasState() && SDL_PollEvent(&event)) {
144                 Handle(event);
145                 CommitStates();
146         }
147         env.counter.ExitHandle();
148 }
149
150 void Application::Handle(const SDL_Event &event) {
151         switch (event.type) {
152                 case SDL_WINDOWEVENT:
153                         Handle(event.window);
154                         break;
155                 default:
156                         GetState().Handle(event);
157                         break;
158         }
159 }
160
161 void Application::Handle(const SDL_WindowEvent &event) {
162         switch (event.event) {
163                 case SDL_WINDOWEVENT_FOCUS_GAINED:
164                         env.window.GrabMouse();
165                         break;
166                 case SDL_WINDOWEVENT_FOCUS_LOST:
167                         env.window.ReleaseMouse();
168                         break;
169                 case SDL_WINDOWEVENT_RESIZED:
170                         env.viewport.Resize(event.data1, event.data2);
171                         break;
172                 default:
173                         break;
174         }
175 }
176
177 void HeadlessApplication::Update(int dt) {
178         env.counter.EnterUpdate();
179         if (HasState()) {
180                 GetState().Update(dt);
181         }
182         env.counter.ExitUpdate();
183 }
184
185 void Application::Update(int dt) {
186         env.counter.EnterUpdate();
187         env.audio.Update(dt);
188         if (HasState()) {
189                 GetState().Update(dt);
190         }
191         env.counter.ExitUpdate();
192 }
193
194 void Application::Render() {
195         // gl implementation may (and will probably) delay vsync blocking until
196         // the first write after flipping, which is this clear call
197         env.viewport.Clear();
198         env.counter.EnterRender();
199
200         if (HasState()) {
201                 GetState().Render(env.viewport);
202         }
203
204         env.counter.ExitRender();
205         env.window.Flip();
206 }
207
208
209 void HeadlessApplication::PushState(State *s) {
210         if (!states.empty()) {
211                 states.top()->OnPause();
212         }
213         states.emplace(s);
214         ++s->ref_count;
215         if (s->ref_count == 1) {
216                 s->OnEnter();
217         }
218         s->OnResume();
219 }
220
221 State *HeadlessApplication::PopState() {
222         State *s = states.top();
223         states.pop();
224         s->OnPause();
225         s->OnExit();
226         if (!states.empty()) {
227                 states.top()->OnResume();
228         }
229         return s;
230 }
231
232 State *HeadlessApplication::SwitchState(State *s_new) {
233         State *s_old = states.top();
234         states.top() = s_new;
235         --s_old->ref_count;
236         ++s_new->ref_count;
237         s_old->OnPause();
238         if (s_old->ref_count == 0) {
239                 s_old->OnExit();
240         }
241         if (s_new->ref_count == 1) {
242                 s_new->OnEnter();
243         }
244         s_new->OnResume();
245         return s_old;
246 }
247
248 State &HeadlessApplication::GetState() {
249         return *states.top();
250 }
251
252 void HeadlessApplication::CommitStates() {
253         env.state.Commit(*this);
254 }
255
256 bool HeadlessApplication::HasState() const noexcept {
257         return !states.empty();
258 }
259
260
261 void StateControl::Commit(HeadlessApplication &app) {
262         while (!cue.empty()) {
263                 Memo m(cue.front());
264                 cue.pop();
265                 switch (m.cmd) {
266                         case PUSH:
267                                 app.PushState(m.state);
268                                 break;
269                         case SWITCH:
270                                 app.SwitchState(m.state);
271                                 break;
272                         case POP:
273                                 app.PopState();
274                                 break;
275                         case POP_ALL:
276                                 while (app.HasState()) {
277                                         app.PopState();
278                                 }
279                                 break;
280                         case POP_AFTER:
281                                 while (app.HasState() && &app.GetState() != m.state) {
282                                         app.PopState();
283                                 }
284                                 break;
285                         case POP_UNTIL:
286                                 while (app.HasState()) {
287                                         if (app.PopState() == m.state) {
288                                                 break;
289                                         }
290                                 }
291                 }
292         }
293 }
294
295
296 AssetLoader::AssetLoader(const string &base)
297 : fonts(base + "fonts/")
298 , sounds(base + "sounds/")
299 , textures(base + "textures/")
300 , data(base + "data/") {
301
302 }
303
304 Assets::Assets(const AssetLoader &loader)
305 : large_ui_font(loader.LoadFont("DejaVuSans", 24))
306 , small_ui_font(loader.LoadFont("DejaVuSans", 16)) {
307
308 }
309
310 namespace {
311
312 CuboidBounds block_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f }});
313 StairBounds stair_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.5f, 0.5f }}, { 0.0f, 0.0f });
314 CuboidBounds slab_shape({{ -0.5f, -0.5f, -0.5f }, { 0.5f, 0.0f, 0.5f }});
315
316 }
317
318 void AssetLoader::LoadBlockTypes(
319         const string &set_name,
320         BlockTypeRegistry &reg,
321         ResourceIndex &tex_index,
322         const ShapeRegistry &shapes
323 ) const {
324         string full = data + set_name + ".types";
325         std::ifstream file(full);
326         if (!file) {
327                 throw std::runtime_error("failed to open block type file " + full);
328         }
329         TokenStreamReader in(file);
330         string type_name;
331         string name;
332         string tex_name;
333         string shape_name;
334         while (in.HasMore()) {
335                 in.ReadIdentifier(type_name);
336                 in.Skip(Token::EQUALS);
337                 BlockType type;
338
339                 // read block type
340                 in.Skip(Token::ANGLE_BRACKET_OPEN);
341                 while (in.Peek().type != Token::ANGLE_BRACKET_CLOSE) {
342                         in.ReadIdentifier(name);
343                         in.Skip(Token::EQUALS);
344                         if (name == "visible") {
345                                 type.visible = in.GetBool();
346                         } else if (name == "texture") {
347                                 in.ReadString(tex_name);
348                                 type.textures.push_back(tex_index.GetID(tex_name));
349                         } else if (name == "textures") {
350                                 in.Skip(Token::BRACKET_OPEN);
351                                 while (in.Peek().type != Token::BRACKET_CLOSE) {
352                                         in.ReadString(tex_name);
353                                         type.textures.push_back(tex_index.GetID(tex_name));
354                                         if (in.Peek().type == Token::COMMA) {
355                                                 in.Skip(Token::COMMA);
356                                         }
357                                 }
358                                 in.Skip(Token::BRACKET_CLOSE);
359                         } else if (name == "rgb_mod") {
360                                 in.ReadVec(type.rgb_mod);
361                         } else if (name == "hsl_mod") {
362                                 in.ReadVec(type.hsl_mod);
363                         } else if (name == "outline") {
364                                 in.ReadVec(type.outline_color);
365                         } else if (name == "label") {
366                                 in.ReadString(type.label);
367                         } else if (name == "luminosity") {
368                                 type.luminosity = in.GetInt();
369                         } else if (name == "block_light") {
370                                 type.block_light = in.GetBool();
371                         } else if (name == "collision") {
372                                 type.collision = in.GetBool();
373                         } else if (name == "collide_block") {
374                                 type.collide_block = in.GetBool();
375                         } else if (name == "generate") {
376                                 type.generate = in.GetBool();
377                         } else if (name == "min_solidity") {
378                                 type.min_solidity = in.GetFloat();
379                         } else if (name == "mid_solidity") {
380                                 type.mid_solidity = in.GetFloat();
381                         } else if (name == "max_solidity") {
382                                 type.max_solidity = in.GetFloat();
383                         } else if (name == "min_humidity") {
384                                 type.min_humidity = in.GetFloat();
385                         } else if (name == "mid_humidity") {
386                                 type.mid_humidity = in.GetFloat();
387                         } else if (name == "max_humidity") {
388                                 type.max_humidity = in.GetFloat();
389                         } else if (name == "min_temperature") {
390                                 type.min_temperature = in.GetFloat();
391                         } else if (name == "mid_temperature") {
392                                 type.mid_temperature = in.GetFloat();
393                         } else if (name == "max_temperature") {
394                                 type.max_temperature = in.GetFloat();
395                         } else if (name == "min_richness") {
396                                 type.min_richness = in.GetFloat();
397                         } else if (name == "mid_richness") {
398                                 type.mid_richness = in.GetFloat();
399                         } else if (name == "max_richness") {
400                                 type.max_richness = in.GetFloat();
401                         } else if (name == "commonness") {
402                                 type.commonness = in.GetFloat();
403                         } else if (name == "shape") {
404                                 in.ReadIdentifier(shape_name);
405                                 type.shape = &shapes.Get(shape_name);
406                         } else {
407                                 std::cerr << "warning: unknown block type property " << name << std::endl;
408                                 while (in.Peek().type != Token::SEMICOLON) {
409                                         in.Next();
410                                 }
411                         }
412                         in.Skip(Token::SEMICOLON);
413                 }
414                 in.Skip(Token::ANGLE_BRACKET_CLOSE);
415                 in.Skip(Token::SEMICOLON);
416
417                 reg.Add(type);
418         }
419 }
420
421 CubeMap AssetLoader::LoadCubeMap(const string &name) const {
422         string full = textures + name;
423         string right = full + "-right.png";
424         string left = full + "-left.png";
425         string top = full + "-top.png";
426         string bottom = full + "-bottom.png";
427         string back = full + "-back.png";
428         string front = full + "-front.png";
429
430         CubeMap cm;
431         cm.Bind();
432         SDL_Surface *srf;
433
434         if (!(srf = IMG_Load(right.c_str()))) throw SDLError("IMG_Load");
435         try {
436                 cm.Data(CubeMap::RIGHT, *srf);
437         } catch (...) {
438                 SDL_FreeSurface(srf);
439                 throw;
440         }
441         SDL_FreeSurface(srf);
442
443         if (!(srf = IMG_Load(left.c_str()))) throw SDLError("IMG_Load");
444         try {
445                 cm.Data(CubeMap::LEFT, *srf);
446         } catch (...) {
447                 SDL_FreeSurface(srf);
448                 throw;
449         }
450         SDL_FreeSurface(srf);
451
452         if (!(srf = IMG_Load(top.c_str()))) throw SDLError("IMG_Load");
453         try {
454                 cm.Data(CubeMap::TOP, *srf);
455         } catch (...) {
456                 SDL_FreeSurface(srf);
457                 throw;
458         }
459         SDL_FreeSurface(srf);
460
461         if (!(srf = IMG_Load(bottom.c_str()))) throw SDLError("IMG_Load");
462         try {
463                 cm.Data(CubeMap::BOTTOM, *srf);
464         } catch (...) {
465                 SDL_FreeSurface(srf);
466                 throw;
467         }
468         SDL_FreeSurface(srf);
469
470         if (!(srf = IMG_Load(back.c_str()))) throw SDLError("IMG_Load");
471         try {
472                 cm.Data(CubeMap::BACK, *srf);
473         } catch (...) {
474                 SDL_FreeSurface(srf);
475                 throw;
476         }
477         SDL_FreeSurface(srf);
478
479         if (!(srf = IMG_Load(front.c_str()))) throw SDLError("IMG_Load");
480         try {
481                 cm.Data(CubeMap::FRONT, *srf);
482         } catch (...) {
483                 SDL_FreeSurface(srf);
484                 throw;
485         }
486         SDL_FreeSurface(srf);
487
488         cm.FilterNearest();
489         cm.WrapEdge();
490
491         return cm;
492 }
493
494 Font AssetLoader::LoadFont(const string &name, int size) const {
495         string full = fonts + name + ".ttf";
496         return Font(full.c_str(), size);
497 }
498
499 void AssetLoader::LoadModels(
500         const string &set_name,
501         ModelRegistry &models,
502         ResourceIndex &tex_index,
503         const ShapeRegistry &shapes
504 ) const {
505         string full = data + set_name + ".models";
506         std::ifstream file(full);
507         if (!file) {
508                 throw std::runtime_error("failed to open model file " + full);
509         }
510         TokenStreamReader in(file);
511         string model_name;
512         string prop_name;
513         while (in.HasMore()) {
514                 in.ReadIdentifier(model_name);
515                 in.Skip(Token::EQUALS);
516                 in.Skip(Token::ANGLE_BRACKET_OPEN);
517                 Model &model = models.Add(model_name);
518                 while (in.HasMore() && in.Peek().type != Token::ANGLE_BRACKET_CLOSE) {
519                         in.ReadIdentifier(prop_name);
520                         in.Skip(Token::EQUALS);
521                         if (prop_name == "root") {
522                                 model.RootPart().Read(in, tex_index, shapes);
523                         } else {
524                                 while (in.HasMore() && in.Peek().type != Token::SEMICOLON) {
525                                         in.Next();
526                                 }
527                         }
528                         in.Skip(Token::SEMICOLON);
529                 }
530                 model.Enumerate();
531                 in.Skip(Token::ANGLE_BRACKET_CLOSE);
532                 in.Skip(Token::SEMICOLON);
533         }
534 }
535
536 void AssetLoader::LoadShapes(const string &set_name, ShapeRegistry &shapes) const {
537         string full = data + set_name + ".shapes";
538         std::ifstream file(full);
539         if (!file) {
540                 throw std::runtime_error("failed to open shape file " + full);
541         }
542         TokenStreamReader in(file);
543         string shape_name;
544         while (in.HasMore()) {
545                 in.ReadIdentifier(shape_name);
546                 in.Skip(Token::EQUALS);
547                 Shape &shape = shapes.Add(shape_name);
548                 shape.Read(in);
549                 in.Skip(Token::SEMICOLON);
550         }
551 }
552
553 Sound AssetLoader::LoadSound(const string &name) const {
554         string full = sounds + name + ".wav";
555         return Sound(full.c_str());
556 }
557
558 Texture AssetLoader::LoadTexture(const string &name) const {
559         string full = textures + name + ".png";
560         Texture tex;
561         SDL_Surface *srf = IMG_Load(full.c_str());
562         if (!srf) {
563                 throw SDLError("IMG_Load");
564         }
565         tex.Bind();
566         tex.Data(*srf);
567         SDL_FreeSurface(srf);
568         return tex;
569 }
570
571 void AssetLoader::LoadTexture(const string &name, ArrayTexture &tex, int layer) const {
572         string full = textures + name + ".png";
573         SDL_Surface *srf = IMG_Load(full.c_str());
574         if (!srf) {
575                 throw SDLError("IMG_Load");
576         }
577         tex.Bind();
578         try {
579                 tex.Data(layer, *srf);
580         } catch (...) {
581                 SDL_FreeSurface(srf);
582                 throw;
583         }
584         SDL_FreeSurface(srf);
585 }
586
587 void AssetLoader::LoadTextures(const ResourceIndex &index, ArrayTexture &tex) const {
588         // TODO: where the hell should that size come from?
589         tex.Reserve(16, 16, index.Size(), Format());
590         for (const auto &entry : index.Entries()) {
591                 LoadTexture(entry.first, tex, entry.second);
592         }
593 }
594
595
596 void FrameCounter::EnterFrame() noexcept {
597         last_enter = SDL_GetTicks();
598         last_tick = last_enter;
599 }
600
601 void FrameCounter::EnterHandle() noexcept {
602         Tick();
603 }
604
605 void FrameCounter::ExitHandle() noexcept {
606         current.handle = Tick();
607 }
608
609 void FrameCounter::EnterUpdate() noexcept {
610         Tick();
611 }
612
613 void FrameCounter::ExitUpdate() noexcept {
614         current.update = Tick();
615 }
616
617 void FrameCounter::EnterRender() noexcept {
618         Tick();
619 }
620
621 void FrameCounter::ExitRender() noexcept {
622         current.render = Tick();
623 }
624
625 void FrameCounter::ExitFrame() noexcept {
626         Uint32 now = SDL_GetTicks();
627         current.total = now - last_enter;
628         current.running = current.handle + current.update + current.render;
629         current.waiting = current.total - current.running;
630         Accumulate();
631
632         ++cur_frame;
633         if (cur_frame >= NUM_FRAMES) {
634                 Push();
635                 cur_frame = 0;
636                 changed = true;
637         } else {
638                 changed = false;
639         }
640 }
641
642 int FrameCounter::Tick() noexcept {
643         Uint32 now = SDL_GetTicks();
644         int delta = now - last_tick;
645         last_tick = now;
646         return delta;
647 }
648
649 void FrameCounter::Accumulate() noexcept {
650         sum.handle += current.handle;
651         sum.update += current.update;
652         sum.render += current.render;
653         sum.running += current.running;
654         sum.waiting += current.waiting;
655         sum.total += current.total;
656
657         max.handle = std::max(current.handle, max.handle);
658         max.update = std::max(current.update, max.update);
659         max.render = std::max(current.render, max.render);
660         max.running = std::max(current.running, max.running);
661         max.waiting = std::max(current.waiting, max.waiting);
662         max.total = std::max(current.total, max.total);
663
664         current = Frame<int>();
665 }
666
667 void FrameCounter::Push() noexcept {
668         peak = max;
669         avg.handle = sum.handle * factor;
670         avg.update = sum.update * factor;
671         avg.render = sum.render * factor;
672         avg.running = sum.running * factor;
673         avg.waiting = sum.waiting * factor;
674         avg.total = sum.total * factor;
675
676         sum = Frame<int>();
677         max = Frame<int>();
678 }
679
680 }