source: network-game/common/Common.cpp@ 1e250bf

Last change on this file since 1e250bf was 8554263, checked in by dportnoy <dmp1488@…>, 11 years ago

Restructuring and code cleanup

  • Property mode set to 100644
File size: 2.1 KB
RevLine 
[edfd1d0]1#include "Common.h"
2
[248e3c1]3#include "Compiler.h"
4
5#if defined WINDOWS
6 #include <winsock2.h>
[e437a19]7#elif defined LINUX
8 #include <fcntl.h>
9 #include <assert.h>
[248e3c1]10#endif
11
[d05086b]12#include <sstream>
[b07eeac]13#include <cmath>
[8271c78]14#include <ctime>
[8554263]15#include <cstdlib>
16#include <cstdio>
[8271c78]17
[b07eeac]18using namespace std;
19
[0693e25]20FLOAT_POSITION POSITION::toFloat() {
21 FLOAT_POSITION floatPosition;
22 floatPosition.x = x;
23 floatPosition.y = y;
24
25 return floatPosition;
26}
27
28POSITION FLOAT_POSITION::toInt() {
29 POSITION position;
30 position.x = x;
31 position.y = y;
32
33 return position;
34}
35
[8554263]36// This might not be cross-platform. Verify that this works correctly or fix it.
37void error(const char *msg)
38{
39 perror(msg);
40 exit(0);
41}
42
[edfd1d0]43void set_nonblock(int sock)
44{
[4c202e0]45 #if defined WINDOWS
[edfd1d0]46 unsigned long mode = 1;
47 ioctlsocket(sock, FIONBIO, &mode);
[4c202e0]48 #elif defined LINUX
[248e3c1]49 int flags = fcntl(sock, F_GETFL,0);
[edfd1d0]50 assert(flags != -1);
51 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
52 #endif
53}
[8f85180]54
55unsigned long long getCurrentMillis()
56{
57 unsigned long long numMilliseconds;
58
59 #if defined WINDOWS
60 numMilliseconds = GetTickCount();
61 #elif defined LINUX
62 timespec curTime;
63 clock_gettime(CLOCK_REALTIME, &curTime);
64
65 numMilliseconds = curTime.tv_sec*(unsigned long long)1000+curTime.tv_nsec/(unsigned long long)1000000;
66 #endif
67
68 return numMilliseconds;
69}
[b07eeac]70
[d05086b]71string getCurrentDateTimeString() {
[8271c78]72 ostringstream timeString;
73
[d05086b]74 time_t millis = time(NULL);
75 struct tm *time = localtime(&millis);
76
77 timeString << time->tm_hour << ":" << time->tm_min << ":"<< time->tm_sec << " " << (time->tm_mon+1) << "/" << time->tm_mday << "/" << (time->tm_year+1900);
78
79 return timeString.str();
80}
81
[b07eeac]82float posDistance(FLOAT_POSITION pos1, FLOAT_POSITION pos2) {
83 float xDiff = pos2.x - pos1.x;
84 float yDiff = pos2.y - pos1.y;
85
86 return sqrt( pow(xDiff,2) + pow(yDiff,2) );
87}
[0693e25]88
89POSITION screenToMap(POSITION pos)
90{
91 pos.x = pos.x-300;
92 pos.y = pos.y-100;
93
94 if (pos.x < 0 || pos.y < 0)
95 {
96 pos.x = -1;
97 pos.y = -1;
98 }
99
100 return pos;
101}
102
103POSITION mapToScreen(POSITION pos)
104{
105 pos.x = pos.x+300;
106 pos.y = pos.y+100;
107
108 return pos;
109}
Note: See TracBrowser for help on using the repository browser.