]> git.localhorst.tv Git - blank.git/blob - src/app/app.cpp
first draft for client/server architecture
[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 #include "TextureIndex.hpp"
8
9 #include "init.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"
19
20 #include <fstream>
21 #include <iomanip>
22 #include <iostream>
23 #include <stdexcept>
24 #include <SDL_image.h>
25
26 using std::runtime_error;
27 using std::string;
28
29
30 namespace blank {
31
32 HeadlessApplication::HeadlessApplication(HeadlessEnvironment &e)
33 : env(e)
34 , states() {
35
36 }
37
38 HeadlessApplication::~HeadlessApplication() {
39
40 }
41
42
43 Application::Application(Environment &e)
44 : HeadlessApplication(e)
45 , env(e) {
46
47 }
48
49 Application::~Application() {
50         env.audio.StopAll();
51 }
52
53
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;
59                 Loop(delta);
60                 last = now;
61         }
62 }
63
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;
70                 Loop(delta);
71                 last = now;
72         }
73 }
74
75 void HeadlessApplication::RunS(size_t n, size_t t) {
76         for (size_t i = 0; HasState() && i < n; ++i) {
77                 Loop(t);
78                 std::cout << '.';
79                 if (i % 16 == 15) {
80                         std::cout << std::setfill(' ') << std::setw(5) << std::right << (i + 1) << std::endl;
81                 } else {
82                         std::cout << std::flush;
83                 }
84         }
85 }
86
87
88 void HeadlessApplication::Run() {
89         Uint32 last = SDL_GetTicks();
90         while (HasState()) {
91                 Uint32 now = SDL_GetTicks();
92                 int delta = now - last;
93                 Loop(delta);
94                 last = now;
95         }
96 }
97
98 void HeadlessApplication::Loop(int dt) {
99         env.counter.EnterFrame();
100         Update(dt);
101         CommitStates();
102         if (!HasState()) return;
103         env.counter.ExitFrame();
104 }
105
106 void Application::Loop(int dt) {
107         env.counter.EnterFrame();
108         HandleEvents();
109         if (!HasState()) return;
110         Update(dt);
111         CommitStates();
112         if (!HasState()) return;
113         Render();
114         env.counter.ExitFrame();
115 }
116
117
118 void HeadlessApplication::HandleEvents() {
119         env.counter.EnterHandle();
120         SDL_Event event;
121         while (HasState() && SDL_PollEvent(&event)) {
122                 Handle(event);
123                 CommitStates();
124         }
125         env.counter.ExitHandle();
126 }
127
128 void HeadlessApplication::Handle(const SDL_Event &event) {
129         GetState().Handle(event);
130 }
131
132
133 void Application::HandleEvents() {
134         env.counter.EnterHandle();
135         SDL_Event event;
136         while (HasState() && SDL_PollEvent(&event)) {
137                 Handle(event);
138                 CommitStates();
139         }
140         env.counter.ExitHandle();
141 }
142
143 void Application::Handle(const SDL_Event &event) {
144         switch (event.type) {
145                 case SDL_WINDOWEVENT:
146                         Handle(event.window);
147                         break;
148                 default:
149                         GetState().Handle(event);
150                         break;
151         }
152 }
153
154 void Application::Handle(const SDL_WindowEvent &event) {
155         switch (event.event) {
156                 case SDL_WINDOWEVENT_FOCUS_GAINED:
157                         env.window.GrabMouse();
158                         break;
159                 case SDL_WINDOWEVENT_FOCUS_LOST:
160                         env.window.ReleaseMouse();
161                         break;
162                 case SDL_WINDOWEVENT_RESIZED:
163                         env.viewport.Resize(event.data1, event.data2);
164                         break;
165                 default:
166                         break;
167         }
168 }
169
170 void HeadlessApplication::Update(int dt) {
171         env.counter.EnterUpdate();
172         if (HasState()) {
173                 GetState().Update(dt);
174         }
175         env.counter.ExitUpdate();
176 }
177
178 void Application::Update(int dt) {
179         env.counter.EnterUpdate();
180         env.audio.Update(dt);
181         if (HasState()) {
182                 GetState().Update(dt);
183         }
184         env.counter.ExitUpdate();
185 }
186
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();
192
193         if (HasState()) {
194                 GetState().Render(env.viewport);
195         }
196
197         env.counter.ExitRender();
198         env.window.Flip();
199 }
200
201
202 void HeadlessApplication::PushState(State *s) {
203         if (!states.empty()) {
204                 states.top()->OnPause();
205         }
206         states.emplace(s);
207         ++s->ref_count;
208         if (s->ref_count == 1) {
209                 s->OnEnter();
210         }
211         s->OnResume();
212 }
213
214 State *HeadlessApplication::PopState() {
215         State *s = states.top();
216         states.pop();
217         s->OnPause();
218         s->OnExit();
219         if (!states.empty()) {
220                 states.top()->OnResume();
221         }
222         return s;
223 }
224
225 State *HeadlessApplication::SwitchState(State *s_new) {
226         State *s_old = states.top();
227         states.top() = s_new;
228         --s_old->ref_count;
229         ++s_new->ref_count;
230         s_old->OnPause();
231         if (s_old->ref_count == 0) {
232                 s_old->OnExit();
233         }
234         if (s_new->ref_count == 1) {
235                 s_new->OnEnter();
236         }
237         s_new->OnResume();
238         return s_old;
239 }
240
241 State &HeadlessApplication::GetState() {
242         return *states.top();
243 }
244
245 void HeadlessApplication::CommitStates() {
246         env.state.Commit(*this);
247 }
248
249 bool HeadlessApplication::HasState() const noexcept {
250         return !states.empty();
251 }
252
253
254 void StateControl::Commit(HeadlessApplication &app) {
255         while (!cue.empty()) {
256                 Memo m(cue.front());
257                 cue.pop();
258                 switch (m.cmd) {
259                         case PUSH:
260                                 app.PushState(m.state);
261                                 break;
262                         case SWITCH:
263                                 app.SwitchState(m.state);
264                                 break;
265                         case POP:
266                                 app.PopState();
267                                 break;
268                         case POP_ALL:
269                                 while (app.HasState()) {
270                                         app.PopState();
271                                 }
272                                 break;
273                 }
274         }
275 }
276
277
278 AssetLoader::AssetLoader(const string &base)
279 : fonts(base + "fonts/")
280 , sounds(base + "sounds/")
281 , textures(base + "textures/")
282 , data(base + "data/") {
283
284 }
285
286 Assets::Assets(const AssetLoader &loader)
287 : large_ui_font(loader.LoadFont("DejaVuSans", 24))
288 , small_ui_font(loader.LoadFont("DejaVuSans", 16)) {
289
290 }
291
292 namespace {
293
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 }});
297
298 }
299
300 void AssetLoader::LoadBlockTypes(const std::string &set_name, BlockTypeRegistry &reg, TextureIndex &tex_index) const {
301         string full = data + set_name + ".types";
302         std::ifstream file(full);
303         if (!file) {
304                 throw std::runtime_error("failed to open block type file " + full);
305         }
306         TokenStreamReader in(file);
307         string type_name;
308         string name;
309         string tex_name;
310         string shape_name;
311         while (in.HasMore()) {
312                 in.ReadIdentifier(type_name);
313                 in.Skip(Token::EQUALS);
314                 BlockType type;
315
316                 // read block type
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 };
351                                 } else {
352                                         throw runtime_error("unknown block shape: " + shape_name);
353                                 }
354                         } else {
355                                 throw runtime_error("unknown block property: " + name);
356                         }
357                         in.Skip(Token::SEMICOLON);
358                 }
359                 in.Skip(Token::ANGLE_BRACKET_CLOSE);
360                 in.Skip(Token::SEMICOLON);
361
362                 reg.Add(type);
363         }
364 }
365
366 Font AssetLoader::LoadFont(const string &name, int size) const {
367         string full = fonts + name + ".ttf";
368         return Font(full.c_str(), size);
369 }
370
371 Sound AssetLoader::LoadSound(const string &name) const {
372         string full = sounds + name + ".wav";
373         return Sound(full.c_str());
374 }
375
376 Texture AssetLoader::LoadTexture(const string &name) const {
377         string full = textures + name + ".png";
378         Texture tex;
379         SDL_Surface *srf = IMG_Load(full.c_str());
380         if (!srf) {
381                 throw SDLError("IMG_Load");
382         }
383         tex.Bind();
384         tex.Data(*srf);
385         SDL_FreeSurface(srf);
386         return tex;
387 }
388
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());
392         if (!srf) {
393                 throw SDLError("IMG_Load");
394         }
395         tex.Bind();
396         try {
397                 tex.Data(layer, *srf);
398         } catch (...) {
399                 SDL_FreeSurface(srf);
400                 throw;
401         }
402         SDL_FreeSurface(srf);
403 }
404
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);
410         }
411 }
412
413
414 TextureIndex::TextureIndex()
415 : id_map() {
416
417 }
418
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;
424         } else {
425                 return entry->second;
426         }
427 }
428
429
430 void FrameCounter::EnterFrame() noexcept {
431         last_enter = SDL_GetTicks();
432         last_tick = last_enter;
433 }
434
435 void FrameCounter::EnterHandle() noexcept {
436         Tick();
437 }
438
439 void FrameCounter::ExitHandle() noexcept {
440         current.handle = Tick();
441 }
442
443 void FrameCounter::EnterUpdate() noexcept {
444         Tick();
445 }
446
447 void FrameCounter::ExitUpdate() noexcept {
448         current.update = Tick();
449 }
450
451 void FrameCounter::EnterRender() noexcept {
452         Tick();
453 }
454
455 void FrameCounter::ExitRender() noexcept {
456         current.render = Tick();
457 }
458
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;
464         Accumulate();
465
466         ++cur_frame;
467         if (cur_frame >= NUM_FRAMES) {
468                 Push();
469                 cur_frame = 0;
470                 changed = true;
471         } else {
472                 changed = false;
473         }
474 }
475
476 int FrameCounter::Tick() noexcept {
477         Uint32 now = SDL_GetTicks();
478         int delta = now - last_tick;
479         last_tick = now;
480         return delta;
481 }
482
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;
490
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);
497
498         current = Frame<int>();
499 }
500
501 void FrameCounter::Push() noexcept {
502         peak = max;
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;
509
510         sum = Frame<int>();
511         max = Frame<int>();
512 }
513
514 }