summary refs log tree commit diff stats
path: root/src/game.cpp
blob: b3fa9a829ff009d1dba9b2861df344823c247596 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "game.h"
#include "components/animatable.h"
#include "components/transformable.h"
#include "components/controllable.h"
#include "components/droppable.h"
#include "components/ponderable.h"
#include "systems/rendering.h"
#include "systems/controlling.h"
#include "systems/pondering.h"

void key_callback(GLFWwindow* window, int key, int, int action, int)
{
  Game& game = *((Game*) glfwGetWindowUserPointer(window));
  
  if ((action == GLFW_PRESS) && (key == GLFW_KEY_ESCAPE))
  {
    game.shouldQuit = true;
    
    return;
  }
  
  game.systemManager.getSystem<ControllingSystem>().input(key, action);
}

Game::Game(GLFWwindow* window) : window(window)
{
  systemManager.emplaceSystem<ControllingSystem>(*this);
  systemManager.emplaceSystem<RenderingSystem>(*this);
  systemManager.emplaceSystem<PonderingSystem>(*this);
  
  int player = entityManager.emplaceEntity();
  entityManager.emplaceComponent<AnimatableComponent>(player, "res/Starla.png", 10, 12, 6);
  entityManager.emplaceComponent<TransformableComponent>(player, 203, 44, 10, 12);
  entityManager.emplaceComponent<DroppableComponent>(player);
  entityManager.emplaceComponent<PonderableComponent>(player);
  entityManager.emplaceComponent<ControllableComponent>(player);
  
  glfwSwapInterval(1);
  glfwSetWindowUserPointer(window, this);
  glfwSetKeyCallback(window, key_callback);
}

void Game::execute()
{
  double lastTime = glfwGetTime();
  const double dt = 0.01;
  double accumulator = 0.0;
  
  while (!(shouldQuit || glfwWindowShouldClose(window)))
  {
    double currentTime = glfwGetTime();
    double frameTime = currentTime - lastTime;
    lastTime = currentTime;
    
    glfwPollEvents();
    
    accumulator += frameTime;
    while (accumulator >= dt)
    {
      systemManager.getSystem<ControllingSystem>().tick(dt);
      systemManager.getSystem<PonderingSystem>().tick(dt);
      
      accumulator -= dt;
    }
    
    systemManager.getSystem<RenderingSystem>().tick(frameTime);
  }
}

EntityManager& Game::getEntityManager()
{
  return entityManager;
}