]> git.localhorst.tv Git - blank.git/blob - src/server/ServerState.cpp
simple test for client
[blank.git] / src / server / ServerState.cpp
1 #include "ServerState.hpp"
2
3 #include "../app/Environment.hpp"
4 #include "../io/WorldSave.hpp"
5 #include "../net/io.hpp"
6
7 #include <iostream>
8
9
10 namespace blank {
11 namespace server {
12
13 ServerState::ServerState(
14         HeadlessEnvironment &env,
15         const Generator::Config &gc,
16         const World::Config &wc,
17         const WorldSave &ws,
18         const Config &config
19 )
20 : env(env)
21 , res()
22 , world(res.block_types, wc)
23 , generator(gc)
24 , chunk_loader(world.Chunks(), generator, ws)
25 , spawner(world, res.models)
26 , server(config.net, world, wc, ws)
27 , loop_timer(16) {
28         res.Load(env.loader, "default");
29         if (res.models.size() < 2) {
30                 throw std::runtime_error("need at least two models to run");
31         }
32         generator.LoadTypes(res.block_types);
33         spawner.LimitModels(1, res.models.size());
34         server.SetPlayerModel(res.models[0]);
35
36         std::cout << "loading spawn chunks" << std::endl;
37         chunk_loader.LoadN(chunk_loader.ToLoad());
38
39         loop_timer.Start();
40
41         std::cout << "listening on UDP port " << config.net.port << std::endl;
42 }
43
44 ServerState::~ServerState() {
45
46 }
47
48
49 void ServerState::Handle(const SDL_Event &event) {
50         if (event.type == SDL_QUIT) {
51                 std::cout << "saving remaining chunks" << std::endl;
52                 for (Chunk &chunk : world.Chunks()) {
53                         if (chunk.ShouldUpdateSave()) {
54                                 chunk_loader.SaveFile().Write(chunk);
55                         }
56                 }
57                 env.state.PopAll();
58         }
59 }
60
61
62 void ServerState::Update(int dt) {
63         loop_timer.Update(dt);
64         if (!loop_timer.HitOnce() && loop_timer.IntervalRemain() > 1) {
65                 server.Wait(loop_timer.IntervalRemain() - 1);
66                 return;
67         }
68         if (dt == 0 && !server.Ready()) {
69                 // effectively wait in a spin loop
70                 return;
71         }
72
73         server.Handle();
74         int world_dt = 0;
75         while (loop_timer.HitOnce()) {
76                 spawner.Update(loop_timer.Interval());
77                 world.Update(loop_timer.Interval());
78                 world_dt += loop_timer.Interval();
79                 loop_timer.PopIteration();
80         }
81         chunk_loader.Update(dt);
82         if (world_dt > 0) {
83                 server.Update(world_dt);
84         }
85         if (world_dt > 32) {
86                 std::cout << "world dt at " << world_dt << "ms!" << std::endl;
87         }
88 }
89
90
91 void ServerState::Render(Viewport &) {
92
93 }
94
95 }
96 }