summaryrefslogtreecommitdiff
path: root/src/game.cpp
blob: d933c2f1cdf43f63e572c9da1779c886381fa5aa (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include "game.h"

#include <fstream>
#include <sstream>
#include <string>
#include <iostream>

#include "automation.h"
#include "net/nethandler.h"
#include "net/network.h"
#include "onlinelist.h"

std::string map_path;
volatile int tick_time;
volatile int cur_time;
const int MAX_TIME = 10000;
bool done = false;

OnlineList *onlinelist;

/**
 * Advances game logic counter.
 */
Uint32 nextTick(Uint32 interval, void *param)
{
    tick_time++;
    if (tick_time == MAX_TIME) tick_time = 0;
    return interval;
}

int get_elapsed_time(int start_time)
{
    if (start_time <= tick_time) {
        return (tick_time - start_time) * 10;
    }
    else {
        return (tick_time + (MAX_TIME - start_time)) * 10;
    }
}

Game::Game()
{
    // Initialize timers
    tick_time = 0;
    SDL_AddTimer(10, nextTick, NULL);                     // Logic counter
    onlinelist = new OnlineList();
}

Game::~Game()
{
    delete onlinelist;
}

int stay_awake(void *data)
{
    /* Eathena seems to kick the client after 10 mins of inactivity. 
	A teenky hack to keep it alive.*/
    while (!done)
    {
	NetHandler::getNetInstance()->sit();
	std::cout << "I'm still here." << std::endl;
	SDL_Delay(5 * 60 * 1000);
    }
}

void Game::logic()
{
    done = false;
    int gameTime = tick_time;

    SDL_Thread *wakeywakey;


    Network *mNetwork = NetHandler::getNetInstance()->getNetwork();
    NetHandler::getNetInstance()->mapLoaded();
    NetHandler::getNetInstance()->ping(tick_time);
    //NetHandler::getNetInstance()->sit();
    NetHandler::getNetInstance()->loadHandlers();
    wakeywakey = SDL_CreateThread(stay_awake, NULL);
    
    while (!done)
    {
        if (mNetwork->getState() == Network::ERROR_BROKE) //get out of this loop to allow a restart.
	    done = true;

        mNetwork->flush();
        mNetwork->dispatchMessages();

        while (get_elapsed_time(gameTime) > 0)
        {
            cur_time = static_cast<int>(time(0));
            onlinelist->logic();
    	    Automation::getAutomationHandler()->logic();
            ++gameTime;
        }

        gameTime = tick_time;

        SDL_Delay(10); // Don't steal all the cpu time.
    }

    SDL_KillThread(wakeywakey);
}