]> git.localhorst.tv Git - blank.git/blob - src/app/app.cpp
increase progress line split to 32 frames
[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 % 32 == 31) {
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                         GetState().OnFocus();
165                         break;
166                 case SDL_WINDOWEVENT_FOCUS_LOST:
167                         GetState().OnBlur();
168                         break;
169                 case SDL_WINDOWEVENT_RESIZED:
170                         env.viewport.Resize(event.data1, event.data2);
171                         GetState().OnResize(env.viewport);
172                         break;
173                 default:
174                         break;
175         }
176 }
177
178 void HeadlessApplication::Update(int dt) {
179         env.counter.EnterUpdate();
180         if (HasState()) {
181                 GetState().Update(dt);
182         }
183         env.counter.ExitUpdate();
184 }
185
186 void Application::Update(int dt) {
187         env.counter.EnterUpdate();
188         env.audio.Update(dt);
189         if (HasState()) {
190                 GetState().Update(dt);
191         }
192         env.counter.ExitUpdate();
193 }
194
195 void Application::Render() {
196         // gl implementation may (and will probably) delay vsync blocking until
197         // the first write after flipping, which is this clear call
198         env.viewport.Clear();
199         env.counter.EnterRender();
200
201         if (HasState()) {
202                 GetState().Render(env.viewport);
203         }
204
205         env.counter.ExitRender();
206         env.window.Flip();
207 }
208
209
210 void HeadlessApplication::PushState(State *s) {
211         if (!states.empty()) {
212                 states.top()->OnPause();
213         }
214         states.emplace(s);
215         ++s->ref_count;
216         if (s->ref_count == 1) {
217                 s->OnEnter();
218         }
219         s->OnResume();
220 }
221
222 State *HeadlessApplication::PopState() {
223         State *s = states.top();
224         states.pop();
225         s->OnPause();
226         s->OnExit();
227         if (!states.empty()) {
228                 states.top()->OnResume();
229         }
230         return s;
231 }
232
233 State *HeadlessApplication::SwitchState(State *s_new) {
234         State *s_old = states.top();
235         states.top() = s_new;
236         --s_old->ref_count;
237         ++s_new->ref_count;
238         s_old->OnPause();
239         if (s_old->ref_count == 0) {
240                 s_old->OnExit();
241         }
242         if (s_new->ref_count == 1) {
243                 s_new->OnEnter();
244         }
245         s_new->OnResume();
246         return s_old;
247 }
248
249 State &HeadlessApplication::GetState() {
250         return *states.top();
251 }
252
253 void HeadlessApplication::CommitStates() {
254         env.state.Commit(*this);
255 }
256
257 bool HeadlessApplication::HasState() const noexcept {
258         return !states.empty();
259 }
260
261
262 void StateControl::Commit(HeadlessApplication &app) {
263         while (!cue.empty()) {
264                 Memo m(cue.front());
265                 cue.pop();
266                 switch (m.cmd) {
267                         case PUSH:
268                                 app.PushState(m.state);
269                                 break;
270                         case SWITCH:
271                                 app.SwitchState(m.state);
272                                 break;
273                         case POP:
274                                 app.PopState();
275                                 break;
276                         case POP_ALL:
277                                 while (app.HasState()) {
278                                         app.PopState();
279                                 }
280                                 break;
281                         case POP_AFTER:
282                                 while (app.HasState() && &app.GetState() != m.state) {
283                                         app.PopState();
284                                 }
285                                 break;
286                         case POP_UNTIL:
287                                 while (app.HasState()) {
288                                         if (app.PopState() == m.state) {
289                                                 break;
290                                         }
291                                 }
292                 }
293         }
294 }
295
296
297 AssetLoader::AssetLoader(const string &base)
298 : fonts(base + "fonts/")
299 , sounds(base + "sounds/")
300 , textures(base + "textures/")
301 , data(base + "data/") {
302
303 }
304
305 Assets::Assets(const AssetLoader &loader)
306 : large_ui_font(loader.LoadFont("DejaVuSans", 24))
307 , small_ui_font(loader.LoadFont("DejaVuSans", 16)) {
308
309 }
310
311 void AssetLoader::LoadBlockTypes(
312         const string &set_name,
313         BlockTypeRegistry &reg,
314         ResourceIndex &snd_index,
315         ResourceIndex &tex_index,
316         const ShapeRegistry &shapes
317 ) const {
318         string full = data + set_name + ".types";
319         std::ifstream file(full);
320         if (!file) {
321                 throw std::runtime_error("failed to open block type file " + full);
322         }
323         TokenStreamReader in(file);
324         string name;
325         while (in.HasMore()) {
326                 in.ReadIdentifier(name);
327                 in.Skip(Token::EQUALS);
328                 BlockType type;
329                 type.Read(in, snd_index, tex_index, shapes);
330                 in.Skip(Token::SEMICOLON);
331                 reg.Add(std::move(type));
332         }
333 }
334
335 CubeMap AssetLoader::LoadCubeMap(const string &name) const {
336         string full = textures + name;
337         string right = full + "-right.png";
338         string left = full + "-left.png";
339         string top = full + "-top.png";
340         string bottom = full + "-bottom.png";
341         string back = full + "-back.png";
342         string front = full + "-front.png";
343
344         CubeMap cm;
345         cm.Bind();
346         SDL_Surface *srf;
347
348         if (!(srf = IMG_Load(right.c_str()))) throw SDLError("IMG_Load");
349         try {
350                 cm.Data(CubeMap::RIGHT, *srf);
351         } catch (...) {
352                 SDL_FreeSurface(srf);
353                 throw;
354         }
355         SDL_FreeSurface(srf);
356
357         if (!(srf = IMG_Load(left.c_str()))) throw SDLError("IMG_Load");
358         try {
359                 cm.Data(CubeMap::LEFT, *srf);
360         } catch (...) {
361                 SDL_FreeSurface(srf);
362                 throw;
363         }
364         SDL_FreeSurface(srf);
365
366         if (!(srf = IMG_Load(top.c_str()))) throw SDLError("IMG_Load");
367         try {
368                 cm.Data(CubeMap::TOP, *srf);
369         } catch (...) {
370                 SDL_FreeSurface(srf);
371                 throw;
372         }
373         SDL_FreeSurface(srf);
374
375         if (!(srf = IMG_Load(bottom.c_str()))) throw SDLError("IMG_Load");
376         try {
377                 cm.Data(CubeMap::BOTTOM, *srf);
378         } catch (...) {
379                 SDL_FreeSurface(srf);
380                 throw;
381         }
382         SDL_FreeSurface(srf);
383
384         if (!(srf = IMG_Load(back.c_str()))) throw SDLError("IMG_Load");
385         try {
386                 cm.Data(CubeMap::BACK, *srf);
387         } catch (...) {
388                 SDL_FreeSurface(srf);
389                 throw;
390         }
391         SDL_FreeSurface(srf);
392
393         if (!(srf = IMG_Load(front.c_str()))) throw SDLError("IMG_Load");
394         try {
395                 cm.Data(CubeMap::FRONT, *srf);
396         } catch (...) {
397                 SDL_FreeSurface(srf);
398                 throw;
399         }
400         SDL_FreeSurface(srf);
401
402         cm.FilterNearest();
403         cm.WrapEdge();
404
405         return cm;
406 }
407
408 Font AssetLoader::LoadFont(const string &name, int size) const {
409         string full = fonts + name + ".ttf";
410         return Font(full.c_str(), size);
411 }
412
413 void AssetLoader::LoadModels(
414         const string &set_name,
415         ModelRegistry &models,
416         ResourceIndex &tex_index,
417         const ShapeRegistry &shapes
418 ) const {
419         string full = data + set_name + ".models";
420         std::ifstream file(full);
421         if (!file) {
422                 throw std::runtime_error("failed to open model file " + full);
423         }
424         TokenStreamReader in(file);
425         string model_name;
426         string prop_name;
427         while (in.HasMore()) {
428                 in.ReadIdentifier(model_name);
429                 in.Skip(Token::EQUALS);
430                 in.Skip(Token::ANGLE_BRACKET_OPEN);
431                 Model &model = models.Add(model_name);
432                 while (in.HasMore() && in.Peek().type != Token::ANGLE_BRACKET_CLOSE) {
433                         in.ReadIdentifier(prop_name);
434                         in.Skip(Token::EQUALS);
435                         if (prop_name == "root") {
436                                 model.RootPart().Read(in, tex_index, shapes);
437                         } else if (prop_name == "body") {
438                                 model.SetBody(in.GetULong());
439                         } else if (prop_name == "eyes") {
440                                 model.SetEyes(in.GetULong());
441                         } else {
442                                 while (in.HasMore() && in.Peek().type != Token::SEMICOLON) {
443                                         in.Next();
444                                 }
445                         }
446                         in.Skip(Token::SEMICOLON);
447                 }
448                 model.Enumerate();
449                 in.Skip(Token::ANGLE_BRACKET_CLOSE);
450                 in.Skip(Token::SEMICOLON);
451         }
452 }
453
454 void AssetLoader::LoadShapes(const string &set_name, ShapeRegistry &shapes) const {
455         string full = data + set_name + ".shapes";
456         std::ifstream file(full);
457         if (!file) {
458                 throw std::runtime_error("failed to open shape file " + full);
459         }
460         TokenStreamReader in(file);
461         string shape_name;
462         while (in.HasMore()) {
463                 in.ReadIdentifier(shape_name);
464                 in.Skip(Token::EQUALS);
465                 Shape &shape = shapes.Add(shape_name);
466                 shape.Read(in);
467                 in.Skip(Token::SEMICOLON);
468         }
469 }
470
471 Sound AssetLoader::LoadSound(const string &name) const {
472         string full = sounds + name + ".wav";
473         return Sound(full.c_str());
474 }
475
476 Texture AssetLoader::LoadTexture(const string &name) const {
477         string full = textures + name + ".png";
478         Texture tex;
479         SDL_Surface *srf = IMG_Load(full.c_str());
480         if (!srf) {
481                 throw SDLError("IMG_Load");
482         }
483         tex.Bind();
484         tex.Data(*srf);
485         SDL_FreeSurface(srf);
486         return tex;
487 }
488
489 void AssetLoader::LoadTexture(const string &name, ArrayTexture &tex, int layer) const {
490         string full = textures + name + ".png";
491         SDL_Surface *srf = IMG_Load(full.c_str());
492         if (!srf) {
493                 throw SDLError("IMG_Load");
494         }
495         tex.Bind();
496         try {
497                 tex.Data(layer, *srf);
498         } catch (...) {
499                 SDL_FreeSurface(srf);
500                 throw;
501         }
502         SDL_FreeSurface(srf);
503 }
504
505 void AssetLoader::LoadTextures(const ResourceIndex &index, ArrayTexture &tex) const {
506         // TODO: where the hell should that size come from?
507         tex.Reserve(16, 16, index.Size(), Format());
508         for (const auto &entry : index.Entries()) {
509                 LoadTexture(entry.first, tex, entry.second);
510         }
511 }
512
513
514 void FrameCounter::EnterFrame() noexcept {
515         last_enter = SDL_GetTicks();
516         last_tick = last_enter;
517 }
518
519 void FrameCounter::EnterHandle() noexcept {
520         Tick();
521 }
522
523 void FrameCounter::ExitHandle() noexcept {
524         current.handle = Tick();
525 }
526
527 void FrameCounter::EnterUpdate() noexcept {
528         Tick();
529 }
530
531 void FrameCounter::ExitUpdate() noexcept {
532         current.update = Tick();
533 }
534
535 void FrameCounter::EnterRender() noexcept {
536         Tick();
537 }
538
539 void FrameCounter::ExitRender() noexcept {
540         current.render = Tick();
541 }
542
543 void FrameCounter::ExitFrame() noexcept {
544         Uint32 now = SDL_GetTicks();
545         current.total = now - last_enter;
546         current.running = current.handle + current.update + current.render;
547         current.waiting = current.total - current.running;
548         Accumulate();
549
550         ++cur_frame;
551         if (cur_frame >= NUM_FRAMES) {
552                 Push();
553                 cur_frame = 0;
554                 changed = true;
555         } else {
556                 changed = false;
557         }
558 }
559
560 int FrameCounter::Tick() noexcept {
561         Uint32 now = SDL_GetTicks();
562         int delta = now - last_tick;
563         last_tick = now;
564         return delta;
565 }
566
567 void FrameCounter::Accumulate() noexcept {
568         sum.handle += current.handle;
569         sum.update += current.update;
570         sum.render += current.render;
571         sum.running += current.running;
572         sum.waiting += current.waiting;
573         sum.total += current.total;
574
575         max.handle = std::max(current.handle, max.handle);
576         max.update = std::max(current.update, max.update);
577         max.render = std::max(current.render, max.render);
578         max.running = std::max(current.running, max.running);
579         max.waiting = std::max(current.waiting, max.waiting);
580         max.total = std::max(current.total, max.total);
581
582         current = Frame<int>();
583 }
584
585 void FrameCounter::Push() noexcept {
586         peak = max;
587         avg.handle = sum.handle * factor;
588         avg.update = sum.update * factor;
589         avg.render = sum.render * factor;
590         avg.running = sum.running * factor;
591         avg.waiting = sum.waiting * factor;
592         avg.total = sum.total * factor;
593
594         sum = Frame<int>();
595         max = Frame<int>();
596 }
597
598 }