
/*
	file : udp.h

	Dragon Wings (c) 2005 Philipp Roßberger, Sebastian Roll
		www.einszunull.net
		www.sebastianroll.de

	This software is provided 'as-is', without any express or implied
	warranty.  In no event will the authors be held liable for any damages
	arising from the use of this software.

	Permission is granted to anyone to use this software for any purpose,
	including commercial applications, and to alter it and redistribute it
	freely, subject to the following restrictions:

	1. The origin of this software must not be misrepresented; you must not
		claim that you wrote the original software. If you use this software
		in a product, an acknowledgment in the product documentation would be
		appreciated but is not required.
	2. Altered source versions must be plainly marked as such, and must not be
		misrepresented as being the original software.
	3. This notice may not be removed or altered from any source distribution.

	Used software libraries from other people (thank you very much):

	The Irrlicht Engine:
		Copyright (c) 2002-2005 Nikolaus Gebhardt
		www.irrlicht.sourceforge.net
  
	The Character Animation Library (cal3D):
		Copyright (c) 2001, 2002 Bruno 'Beosil' Heidelberger
		www.cal3d.sourceforge.net

	The FMOD audio library:
		Copyright (c), Firelight Technologies Pty, Ltd. 1999-2004
		www.fmod.org

	Article - Using Cal3D with Irrlicht:
		Copyright (c) Thomas Suter 2004
		www.thomas.webtracker.ch/jahia/Jahia/cache/off/pid/672

*/


#define UDP_MAX_PACKET_SIZE			1024

extern int TRACKER_BODY_ID_LEFTWING	= 1;
extern int TRACKER_BODY_ID_RIGHTWING = 3;


char*			m_serverName;
int				m_port;
SOCKET			m_socket;
char			m_buffer[UDP_MAX_PACKET_SIZE];
trackedBody		m_leftWing;
trackedBody		m_rightWing;



void setWingsToDefault()
{
	m_leftWing.loc[0] = 200;
	m_leftWing.loc[1] = 300;
	m_leftWing.loc[2] = 300;
	m_leftWing.ang[0] = 0;
	m_leftWing.ang[1] = 0;
	m_leftWing.ang[2] = 0;

	m_rightWing.loc[0] = 400;
	m_rightWing.loc[1] = 300;
	m_rightWing.loc[2] = 300;
	m_rightWing.ang[0] = 0;
	m_rightWing.ang[1] = 0;
	m_rightWing.ang[2] = 0;
}


void udpInit(char* serverName, int port)
{
	m_serverName = serverName;
	m_port = port;
	
	// Must be done at the beginning of every WinSock program
	WSADATA w;    // used to store information about WinSock version
	int error = WSAStartup(0x0202, &w);   // Fill in w

	if (!error)
	{	
		// there was no error
		if (w.wVersion == 0x0202)
		{	
			// correct WinSock version!
			m_socket = socket(AF_INET, SOCK_DGRAM, 0); // Create ip UDP socket with default protokol
	
			sockaddr_in addr; // the address structure for a socket
			addr.sin_family = AF_INET;      // Address family Internet
			addr.sin_port = htons(m_port);   // Assign port 5000 to this socket
			addr.sin_addr.s_addr = htonl(INADDR_ANY);   // No destination
	
			if (bind(m_socket, (LPSOCKADDR)&addr, sizeof(addr)) != SOCKET_ERROR)
			{	
				// everything ok
				cout << "udpInit() connect to " << m_serverName << " ok" << endl;
				return;
			}
		}
	}

	cout << "udpInit() cannot create UDP socket" << endl;
	m_socket = 0;
	WSACleanup ();  // unload WinSock

	setWingsToDefault();
}

void udpClose()
{
	closesocket(m_socket);
	WSACleanup(); // unload ws2_32.dll
}


void udpParse()
{
	//unsigned long framenr = m_buffer[0];
	int nbodies = m_buffer[4];

	if (nbodies > 0)
	{
		if (m_buffer[8] == TRACKER_BODY_ID_RIGHTWING)
		{
			memcpy(&m_rightWing, &m_buffer[8], sizeof(m_rightWing));
		}
		else if (m_buffer[8] == TRACKER_BODY_ID_LEFTWING)
		{
			memcpy(&m_leftWing, &m_buffer[8], sizeof(m_leftWing));
		}
	}
	if (nbodies > 1)
	{
		if (m_buffer[8 + sizeof(m_rightWing)] == TRACKER_BODY_ID_LEFTWING)
		{
			memcpy(&m_leftWing, &m_buffer[8+sizeof(m_rightWing)], sizeof(m_leftWing));
		}
		else if (m_buffer[8 + sizeof(m_leftWing)] == TRACKER_BODY_ID_RIGHTWING)
		{
			memcpy(&m_rightWing, &m_buffer[8+sizeof(m_leftWing)], sizeof(m_rightWing));
		}
	}
}


void udpReceive()
{
	if (m_socket == 0)
	{
		return;
	}

	int rc = 0;
	int nfds = 0;
	fd_set readfds;
	readfds.fd_count = 1;
	readfds.fd_array[0] = m_socket;
	fd_set writefds;
	writefds.fd_count = 0;
	writefds.fd_array[0] = 0;
	fd_set exceptfds;
	exceptfds.fd_count = 0;
	exceptfds.fd_array[0] = 0;
	struct timeval timeout;
	timeout.tv_sec = 0;
	timeout.tv_usec = 0;
	
	// this while secures to get most recent udp data!
	// select has to be checked for pending data, because recv() is a blocking operation!
	while (rc = select(nfds, &readfds, &writefds, &exceptfds, &timeout) > 0)
	{
		if (rc == 1)
		{
			// our socket is ready to receive data
			rc = recv(m_socket, m_buffer, sizeof(m_buffer), 0);
			//cout << "udpReceive() received bytes: " << rc << endl;
			udpParse();
		}
	}
	if (rc == 0)
	{
		// socket not ready to read
		//cout << "udpReceive() no pending data" << endl;
		return;
	}
	if (rc == SOCKET_ERROR)
	{
		cout << "udpReceive() SOCKET_ERROR" << endl;
		setWingsToDefault();
		return;
	}
}


trackedBody* udpGetRightWing()
{
	return &m_rightWing;
}


trackedBody* udpGetLeftWing()
{
	return &m_leftWing;
}

