130 lines
2.5 KiB
C++
130 lines
2.5 KiB
C++
#ifndef NETWORK_H
|
|
#define NETWORK_H
|
|
|
|
#include <string>
|
|
#include <vector>
|
|
#include <cstdint>
|
|
|
|
#ifdef _WIN32
|
|
#ifndef WIN32_LEAN_AND_MEAN
|
|
#define WIN32_LEAN_AND_MEAN
|
|
#endif
|
|
#ifndef NOGDI
|
|
#define NOGDI
|
|
#endif
|
|
#ifndef NOUSER
|
|
#define NOUSER
|
|
#endif
|
|
// Rename conflicting functions before including windows/winsock
|
|
#define CloseWindow CloseWindow_Win
|
|
#define ShowCursor ShowCursor_Win
|
|
#define DrawTextEx DrawTextEx_Win
|
|
#define PlaySound PlaySound_Win
|
|
|
|
#include <winsock2.h>
|
|
#include <ws2tcpip.h>
|
|
|
|
#undef CloseWindow
|
|
#undef ShowCursor
|
|
#undef DrawTextEx
|
|
#undef PlaySound
|
|
#undef near
|
|
#undef far
|
|
|
|
#pragma comment(lib, "ws2_32.lib")
|
|
typedef SOCKET Socket;
|
|
#define INVALID_SOCKET_VAL INVALID_SOCKET
|
|
#define SOCKET_ERROR_VAL SOCKET_ERROR
|
|
#else
|
|
#include <sys/socket.h>
|
|
#include <netinet/in.h>
|
|
#include <arpa/inet.h>
|
|
#include <unistd.h>
|
|
#include <fcntl.h>
|
|
typedef int Socket;
|
|
#define INVALID_SOCKET_VAL -1
|
|
#define SOCKET_ERROR_VAL -1
|
|
#define closesocket close
|
|
#endif
|
|
|
|
enum PacketType {
|
|
PACKET_HANDSHAKE = 0,
|
|
PACKET_PLAYER_UPDATE = 1,
|
|
PACKET_BLOCK_CHANGE = 2,
|
|
PACKET_TIME_SYNC = 3,
|
|
PACKET_SEED_SYNC = 4,
|
|
PACKET_CHAT = 5,
|
|
PACKET_DISCONNECT = 6,
|
|
PACKET_PLAYER_HIT = 7
|
|
};
|
|
|
|
struct PacketPlayerHit {
|
|
uint32_t targetID;
|
|
float damage;
|
|
float attackerX, attackerZ;
|
|
};
|
|
|
|
struct PacketHeader {
|
|
uint8_t type;
|
|
uint32_t size;
|
|
};
|
|
|
|
struct PacketHandshake {
|
|
char name[32];
|
|
uint8_t shirtR, shirtG, shirtB;
|
|
uint8_t pantsR, pantsG, pantsB;
|
|
};
|
|
|
|
struct PacketPlayerUpdate {
|
|
float x, y, z;
|
|
float yaw;
|
|
uint32_t playerID; // Assigned by server
|
|
};
|
|
|
|
struct PacketBlockChange {
|
|
int x, y, z;
|
|
int blockType;
|
|
};
|
|
|
|
struct PacketTimeSync {
|
|
float gameTime;
|
|
};
|
|
|
|
struct PacketSeedSync {
|
|
int seed;
|
|
};
|
|
|
|
struct PacketChat {
|
|
char name[32];
|
|
char message[128];
|
|
};
|
|
|
|
// Cross-platform socket initialization
|
|
inline bool InitNetworking() {
|
|
#ifdef _WIN32
|
|
WSADATA wsaData;
|
|
return WSAStartup(MAKEWORD(2, 2), &wsaData) == 0;
|
|
#else
|
|
return true;
|
|
#endif
|
|
}
|
|
|
|
inline void ShutdownNetworking() {
|
|
#ifdef _WIN32
|
|
WSACleanup();
|
|
#endif
|
|
}
|
|
|
|
inline bool SetNonBlocking(Socket s) {
|
|
#ifdef _WIN32
|
|
unsigned long mode = 1;
|
|
return ioctlsocket(s, FIONBIO, &mode) == 0;
|
|
#else
|
|
int flags = fcntl(s, F_GETFL, 0);
|
|
if (flags == -1) return false;
|
|
return fcntl(s, F_SETFL, flags | O_NONBLOCK) == 0;
|
|
#endif
|
|
}
|
|
|
|
#endif
|