Exemple #1
0
void Authentication_SetKey( char *_key )
{
    strcpy( s_authKey, _key );

    // Trim end whitespace
    int keyLen = strlen(s_authKey);
    for( int i = keyLen-1; i >= 0; --i )
    {
        if( s_authKey[i] == ' ' || 
            s_authKey[i] == '\r' ||
            s_authKey[i] == '\n' )
        {
            s_authKey[i] = '\x0';
        }
        else
        {
            break;
        }
    }


    if( s_enforceDemo &&
        !Authentication_IsDemoKey(s_authKey) )
    {
        strcpy( s_authKey, "authkey not found" );
    }


    AppDebugOut( "Authentication key set : " );
    AppDebugOut( "'%s'\n", s_authKey );    
}
Exemple #2
0
bool NetLib::Initialise()
{
#ifdef WIN32
    WORD versionRequested;
    WSADATA wsaData;
    
    versionRequested = MAKEWORD(2, 2);
 
    if (WSAStartup(versionRequested, &wsaData))
    {
        AppDebugOut("WinSock startup failed\n");
        return false;
    }
 
    // Confirm that the WinSock DLL supports 2.2. Note that if the DLL supports
	// versions greater than 2.2 in addition to 2.2, it will still return
    // 2.2 in wVersion since that is the version we requested.                                       
    if ((LOBYTE(wsaData.wVersion) != 2) || (HIBYTE(wsaData.wVersion) != 2))
    {
        // Tell the user that we could not find a usable WinSock DLL
        WSACleanup();
        AppDebugOut("No valid WinSock DLL found\n");
        return false; 
    }

    AppDebugOut( "WinSock started\n" );
#endif
    
    return true;
}
void Matrix34::WriteToDebugStream()
{
    AppDebugOut("%5.2 %5.2 %5.2\n", r.x, r.y, r.z);
    AppDebugOut("%5.2 %5.2 %5.2\n", u.x, u.y, u.z);
    AppDebugOut("%5.2 %5.2 %5.2\n", f.x, f.y, f.z);
    AppDebugOut("%5.2 %5.2 %5.2\n\n", pos.x, pos.y, pos.z);
}
Exemple #4
0
void GetLocalHostIP( char *str, int len )
{
	static bool retrievedAddress = false;
	static char localHostIP[16] = "127.0.0.1";

	if (!retrievedAddress)
	{
		retrievedAddress = true;

		//
		// Get our host name

		char hostname[256];
		int result = gethostname( hostname, sizeof(hostname) );
		if (result >= 0) 
		{

			//
			// Convert it to a hostent

			struct hostent *lpHostEnt;
			lpHostEnt = gethostbyname( hostname );
			if (lpHostEnt)
			{

				//
				// Print it to an IP

				NetIpAddress addr;
				memcpy( &addr.sin_addr, lpHostEnt->h_addr_list[0], sizeof(addr.sin_addr) );
				addr.sin_port = 0;

				IpAddressToStr( addr, localHostIP );

				//
				// Bogus IP address if begins by '0', most probably the user don't have a configured network card 

				if( localHostIP[0] == '0' )
				{
					strncpy( localHostIP, "127.0.0.1", sizeof(localHostIP) );
					localHostIP[ sizeof(localHostIP) - 1 ] = '\0';
				}
			}
		}

		if (strcmp( localHostIP, "127.0.0.1" ) == 0)
		{
			AppDebugOut( "Local IP address is 127.0.0.1, only local games possible\n" );
		}
		else
		{
			AppDebugOut( "Local IP address is: %s\n", localHostIP );
		}
	}

	strncpy( str, localHostIP, len );
	str[ len - 1 ] = '\0';
}	
NetRetCode NetSocketListener::Bind()
{
	if (int(m_sockfd) >= 0)
		return NetOk;
		 
	if ((m_sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
	{
		return NetFailed;
	}

	// We are starting the binding process (should really get this atomically)
	// The whole point of m_binding and m_listening are flags which can be set
	// from another thread to help the socket close down gracefully.
	m_binding = true;
	
	// Set up the server address
	NetIpAddress servaddr;
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(m_port);

	// Bind socket to port
	int bindAttempts = 0;
	while ((bind(m_sockfd, (sockaddr *)&servaddr, sizeof(servaddr)) == -1) && m_binding)
	{
		if ((bindAttempts++ == 5) || (!NetIsAddrInUse))
		{
			m_binding = false;
			return NetFailed;
		}
		else
		{
			AppDebugOut("NETLIB: Failed to bind to port %d\n", m_port);
			NetSleep(bindAttempts * 100);
		}
	}
	
	// If port was 0, let's see what the system assigned
	if (m_port == 0) {
		NetSocketLenType addr_len = sizeof(servaddr);
		if (getsockname(m_sockfd, (sockaddr *)&servaddr, &addr_len) == -1) {
			AppDebugOut("NETLIB: Failed to get system assigned port number\n");
			return NetFailed;
		}
		m_port = ntohs(servaddr.sin_port);
	}
	
	if (m_binding) 
	{
		m_binding = false;
		return NetOk;
	}
	else
		return NetFailed;
}
void AIObjective::AdvanceStandard()
{
    if( !m_active ) return;
#ifdef TARGET_DEBUG
    AppDebugOut("Updating Active Attack Objective\n");
#endif

    bool objectivesCaptured = true;
    for( int i = 0; i < m_objectiveMarkers.Size(); ++i )
    {
        Building *b = g_app->m_location->GetBuilding( m_objectiveMarkers[i] );
        if( b && b->m_type == Building::TypeAIObjectiveMarker )
        {
            if( b->m_id.GetTeamId() == 255 ||
                g_app->m_location->IsDefending( b->m_id.GetTeamId() ) )
            {
                if( ((AIObjectiveMarker*)b)->m_armourObjective == 0 )
                {
                    objectivesCaptured = false;
                    break;
                }
            }
        }
    }

    if( objectivesCaptured )
    {
        AppDebugOut("Objective Captured!\n");
        m_active = false;
        //SetTeamId( capturingTeam );
        AIObjective *nextObjective = (AIObjective *)g_app->m_location->GetBuilding( m_nextObjective );
        if( nextObjective ) 
        {
            AppDebugOut("Next Objective Activated\n");
            nextObjective->m_active = true;
        }

        for( int i = 0; i < m_objectiveMarkers.Size(); ++i )
        {
            AIObjectiveMarker *m = (AIObjectiveMarker *)g_app->m_location->GetBuilding( m_objectiveMarkers[i] );
            if( m && m->m_type == Building::TypeAIObjectiveMarker )
            {
                if( m->m_armourObjective == 1 && m->m_pickupOnly != -1 )
                {
                    m->m_pickupAvailable = true;
                }
            }
        }
    }
}
Exemple #7
0
void HashTable<T>::DumpKeys() const
{
	for (unsigned i = 0; i < m_size; ++i)
	{
		if (m_keys[i])
		{
			int hash = HashFunc(m_keys[i]);
			int numCollisions = (i - hash + m_size) & m_mask;
			AppDebugOut("%03d: %s - %d\n", i, m_keys[i], numCollisions);
		}
        else
        {
            AppDebugOut("%03d: empty\n", i );
        }
	}
}
Exemple #8
0
void EclRemoveWindow ( char *name )
{
    
    int index = EclGetWindowIndex(name);
    if ( index != -1 )
    {
    
        EclWindow *window = windows.GetData(index);

        if( strcmp( mouseDownWindow, name ) == 0 )
        {
            strcpy( mouseDownWindow, "None" );
        }

        if( strcmp( windowFocus, name ) == 0 )
        {
            strcpy( windowFocus, "None" );
        }

        window->Remove();

        windows.RemoveData(index);
        delete window;
    }
    else
    {
        AppDebugOut( "EclRemoveWindow failed on window %s\n", name );
    }
    
}
Exemple #9
0
void FileSystem::ParseArchive( const char *_filename )
{
	UncompressedArchive	*mainData = NULL;

    AppDebugOut( "Parsing archive %s...", _filename );

	try
	{
		mainData = new UncompressedArchive(_filename,NULL);
        if( mainData && mainData->m_numFiles > 0 )
        {
            AppDebugOut( "DONE\n" );
        }
        else
        {
            AppDebugOut( "NOT FOUND\n" );
        }
	}
	catch( ... )
	{
        AppDebugOut( "FAILED\n" );
		return;
	}

	for (int i = 0; i < mainData->m_numFiles; ++i)
	{
		MemMappedFile *file = mainData->m_files[i];
		if (file->m_size > 0)
		{
			strlwr(file->m_filename);
			
			// Subsequent archives may override existing resources
			
			MemMappedFile *oldFile = m_archiveFiles.GetData(file->m_filename);
			if (oldFile) 
            {
				m_archiveFiles.RemoveData(file->m_filename);
				delete oldFile;
			}
			
			m_archiveFiles.PutData(file->m_filename, file);
		}
	}

	delete mainData;
}
Exemple #10
0
void Authentication_SetHashToken( int _hashToken )
{
    if( _hashToken != s_hashToken )
    {
        AppDebugOut( "Authentication HashToken set to %d\n", _hashToken );
    }

    s_hashToken = _hashToken;
}
void LanguageTable::LoadLanguages()
{
    //
    // Clear out all known languages

    m_languages.EmptyAndDelete();


    //
    // Explore the data/language directory, looking for languages

    LList<char *> *files = g_fileSystem->ListArchive( "data/language/", "*.txt", false );

    for( int i = 0; i < files->Size(); ++i )
    {
        char *thisFile = files->GetData(i);

        Language *lang = new Language();

		snprintf( lang->m_name, sizeof(lang->m_name), thisFile );
		lang->m_name[ sizeof(lang->m_name) - 1 ] = '\0';
		for( char *curName = lang->m_name; *curName; curName++ )
		{
			if( *curName == '.' )
			{
				*curName = '\0';
				break;
			}
		}
		strcpy( lang->m_caption, lang->m_name );

        snprintf( lang->m_path, sizeof(lang->m_path), "data/language/%s", thisFile );
		lang->m_path[ sizeof(lang->m_path) - 1 ] = '\0';

        LoadLanguageCaption( lang );

		if( m_onlyDefaultLanguageSelectable && stricmp( m_defaultLanguage, lang->m_name ) != 0 )
		{
			lang->m_selectable = false;
		}
		else
		{
			lang->m_selectable = true;
		}

        m_languages.PutData( lang );

        AppDebugOut( "Found language '%s' with caption '%s' in '%s'\n", 
                     lang->m_name, 
                     lang->m_caption, 
                     lang->m_path );
    }

    files->EmptyAndDelete();
    delete files;
}
void SoundLibrary3dSoftware::SetChannelFrequency( int _channel, int _frequency )
{
	if (_frequency > 3 * 48000)
	{
		AppDebugOut("Frequency of %d Hz out of range on channel %d\n", _frequency, _channel);
		_frequency = 3 * 48000;
	}
				   
	m_channels[_channel].m_freq = _frequency;
}
Exemple #13
0
void MatchMaker_StopRequestingIdentity( NetSocketListener *_listener )
{
    MatchMakerListener *listener = GetListener(_listener);

    if( listener )
    {
        AppDebugOut( "Stopped requesting public IP:port for socket %d\n", _listener->GetBoundSocketHandle() );

        listener->m_shutDown = true;
    }
}
void DebugOutNetSocketError( int _errorCode )
{
#ifdef WIN32
    switch( _errorCode )
    {
        case WSAEINTR:                          
            // Interrupted function call : not really an error, we've just been shut down            
            break;

        case WSAECONNRESET:
            AppDebugOut( "NetSocketListener : Connection Reset by Peer\n" );
            break;

        default:
            AppDebugOut( "NetSocketListener : Error reading UDP data (errno=%d)\n", _errorCode );            
            break;
    }
#else
	// TODO
#endif
}
SoundLibrary2dSDL::SoundLibrary2dSDL()
:	m_bufferIsThirsty(0), 
	m_callback(NULL),
	m_wavOutput(NULL)
{
	AppReleaseAssert(!g_soundLibrary2d, "SoundLibrary2dSDL already exists");

	m_freq = g_preferences->GetInt("SoundMixFreq", 44100);
	m_samplesPerBuffer = g_preferences->GetInt("SoundBufferSize", 2000);

	// Initialise the output device

	SDL_AudioSpec desired;
	
	desired.freq = m_freq;
	desired.format = AUDIO_S16SYS;
	desired.samples = m_samplesPerBuffer;
	desired.channels = 2;
	desired.userdata = 0;
	desired.callback = sdlAudioCallback;
	
	AppDebugOut("Initialising SDL Audio\n");
	if (SDL_OpenAudio(&desired, &s_audioSpec) < 0) {
		const char *errString = SDL_GetError();
		AppReleaseAssert(false, "Failed to open audio output device: \"%s\"", errString);
	}
	else {
		AppDebugOut("Frequency: %d\nFormat: %d\nChannels: %d\nSamples: %d\n", s_audioSpec.freq, s_audioSpec.format, s_audioSpec.channels, s_audioSpec.samples);
		AppDebugOut("Size of Stereo Sample: %u\n", sizeof(StereoSample));
	}
	
	s_audioStarted = 1;
	
	m_samplesPerBuffer = s_audioSpec.samples;
	
	// Start the callback function
	if (g_preferences->GetInt("Sound", 1)) 
		SDL_PauseAudio(0);
}
Exemple #16
0
NetRetCode NetStartThread(NetThreadFunc functionPtr, void *arg )
{
	NetRetCode retVal = NetOk;
	DWORD dwID = 0;
	
	if (CreateThread(NULL, NULL, functionPtr, arg, NULL, &dwID) == NULL)
	{
		AppDebugOut("Thread creation failed");
		retVal = NetFailed;
	}

	return retVal;
}
Exemple #17
0
void Authentication_SaveKey( const char *_key, const char *_filename )
{
    FILE *file = fopen(_filename, "wt");
    
    if( !file )
    {
        AppDebugOut( "Failed to save AuthKey" );
        return;
    }


    fprintf( file, "%s\n", _key );
    fclose(file);    
}
void Matrix34::Test()
{
    Matrix34 a(Vector3(0,0,1), g_upVector, g_zeroVector);
    Matrix34 b(Vector3(0,0,1), g_upVector, g_zeroVector);
    Matrix34 c=a*b;
    AppDebugOut("c = a * b\n");
    c.WriteToDebugStream();

    Vector3 front(10,20,2);
    front.Normalise();
    Vector3 up(0,1,0);
    Vector3 right = up ^ front;
    right.Normalise();
    up = front ^ right;
    up.Normalise();
    Matrix34 d(front, up, Vector3(-1,2,-3));
    AppDebugOut("d = \n");
    d.WriteToDebugStream();

    Matrix34 e = d * d;
    AppDebugOut("e = d * d\n");
    e.WriteToDebugStream();
}
Exemple #19
0
void EclSetWindowSize ( char *name, int w, int h )
{
    EclWindow *window = EclGetWindow(name);
    if ( window )
    {
        window->Remove();
        window->m_w = w;
        window->m_h = h;
        window->Create();
    }
    else
    {
        AppDebugOut( "EclSetWindowSize failed on window %s\n", name );
    }
}
Exemple #20
0
void EclSetWindowPosition ( char *name, int x, int y )
{

    EclWindow *window = EclGetWindow(name);
    if ( window )
    {
        window->m_x = x;
        window->m_y = y;
    }
    else
    {
        AppDebugOut( "EclSetWindowPosition failed on window %s\n", name );
    }

}
Exemple #21
0
void EclBringWindowToFront ( char *name )
{

    int index = EclGetWindowIndex(name);
    if ( index != -1 )
    {
        EclWindow *window = windows.GetData(index);
        windows.RemoveData(index);
        windows.PutDataAtStart(window);
    }
    else
    {
        AppDebugOut( "EclBringWindowToFront failed on window %s\n", name );
    }

}
Exemple #22
0
void EarthData::LoadCoastlines()
{
    double startTime = GetHighResTime();

    m_islands.EmptyAndDelete();

    int numIslands = 0;

    char coastFile[1024];
    if( g_preferences->GetInt(PREFS_GRAPHICS_LOWRESWORLD) == 0 )
    {
        strcpy(coastFile, "data/earth/coastlines.dat");
    }
    else
    {
        strcpy(coastFile, "data/earth/coastlines-low.dat");
    }

    TextReader *coastlines = g_fileSystem->GetTextReader( coastFile );
    AppAssert( coastlines && coastlines->IsOpen() );
    Island *island = NULL;
    
    while( coastlines->ReadLine() )
    {        
        char *line = coastlines->GetRestOfLine();
        if( line[0] == 'b' )
        {
            if( island )
            {           
                m_islands.PutData( island );                  
            }
            island = new Island();
            ++numIslands;
        }
        else
        {
            float longitude, latitude;
            sscanf( line, "%f %f", &longitude, &latitude );
            island->m_points.PutData( new Vector3<float>( longitude, latitude, 0.0f ) );            
        }
    }

    delete coastlines;

    double totalTime = GetHighResTime() - startTime;
    AppDebugOut( "Parsing Coastline data (%d islands) : %dms\n", numIslands, int( totalTime * 1000.0f ) );
}
Exemple #23
0
NetRetCode NetStartThread(NetThreadFunc functionPtr, void *arg)
{
	pthread_t t;

	if (pthread_create(&t,NULL,functionPtr,arg) != 0) {
		AppDebugOut("thread creation failed");
		return NetFailed;
	}
	
	// detach the thread now, because we are not interested
	// in it's return result. We want to reclaim the memory
	// as soon as the thread terminates.
	
	pthread_detach(t);

	return NetOk;
}
Exemple #24
0
void MatchMaker_StartRequestingIdentity( NetSocketListener *_listener )
{
    AppAssert( s_matchMakerIp );

    if( _listener &&
        !MatchMaker_IsRequestingIdentity(_listener) )
    {
        AppDebugOut( "Started requesting public IP:port for socket %d\n", _listener->GetBoundSocketHandle() );

        MatchMakerListener *listener = new MatchMakerListener();
        listener->m_listener = _listener;

        s_listenersMutex.Lock();
        int index = s_listeners.PutData(listener);
        s_listenersMutex.Unlock();
        
        NetStartThread( RequestIdentityThread, _listener );
    }
}
Exemple #25
0
static void AdjustForBuggyXinerama(int &_xrel, int &_yrel)
{
	/* Linux has buggy multiple screen support which causes the
	   mouse events to be all screwed up */

	// Xinerama offset
	static int offsetX = 0, offsetY = 0;
	static int screenW = 0, screenH = 0;
	static int frameCount = 0;

	if (screenW != g_app->m_renderer->ScreenW() ||
		screenH != g_app->m_renderer->ScreenH()) {
		// Resolution changed

		screenW = g_app->m_renderer->ScreenW();
		screenH = g_app->m_renderer->ScreenH();

		// We want to skip the first few mouse events
		// As we can get some funny behaviour after a resolution change
		frameCount = 3;
	}
	
	if (frameCount >= 0)
		frameCount--;
	
	if (frameCount == 0) {
		// Guess Xinerama offset
		int hypot = sqrt(_xrel*_xrel + _yrel*_yrel);
		if (hypot >= 550) {
			offsetX = (_xrel + SignOf(_xrel)*32) / 64 * 64;
			offsetY = (_yrel + SignOf(_yrel)*32) / 64 * 64;
		}
		else {
			offsetX = 0;
			offsetY = 0;
		}
		AppDebugOut("XINERAMA offset guess: %d, %d\n", offsetX, offsetY);
	}

	_xrel -= offsetX;
	_yrel -= offsetY;
}
Exemple #26
0
void MatchMaker_RequestConnection( char *_targetIp, int _targetPort, Directory *_myDetails )
{
#ifdef WAN_PLAY_ENABLED
    AppDebugOut( "Requesting connection to %s:%d via matchmaker\n", _targetIp, _targetPort );

    Directory request( _myDetails );
    request.SetName     ( NET_MATCHMAKER_MESSAGE );
    request.CreateData  ( NET_METASERVER_COMMAND, NET_MATCHMAKER_REQUEST_CONNECT );
    request.CreateData  ( NET_MATCHMAKER_TARGETIP, _targetIp );
    request.CreateData  ( NET_MATCHMAKER_TARGETPORT, _targetPort );

    AppAssert( s_matchMakerIp );

    NetSocket socket;   
    NetRetCode result = socket.Connect( s_matchMakerIp, s_matchMakerPort );
    AppAssert( result == NetOk );

    MetaServer_SendDirectory( &request, &socket );
#endif
}
Exemple #27
0
void Authentication_LoadKey( char *_key, const char *_filename )
{
    FILE *file = fopen(_filename, "rt" );
    if( file )
    {
        fscanf( file, "%s", _key );
        fclose(file);
    }
    else
    {
        AppDebugOut( "Failed to load AuthKey : '%s'\n", _filename );
        sprintf( _key, "authkey not found" );
    }


    if( s_enforceDemo &&
        !Authentication_IsDemoKey(_key) )
    {
        strcpy( _key, "authkey not found" );
    }
}
Exemple #28
0
void DumpSyncLogs( char *syncId )
{
    static float s_lastDump = 0.0f;
    if( GetHighResTime() > s_lastDump + 10.0f )
    {
        s_lastDump = GetHighResTime();

        char filename[256];
        sprintf( filename, "synclog %s c%d.txt", 
                            syncId, 
                            g_app->GetClientToServer()->m_clientId );
        
        if( !DoesFileExist( filename ) )
        {
            DumpSyncRandLog( filename );
            DumpWorldToSyncLog( filename );

            AppDebugOut( "SYNCERROR log dumped to '%s'\n", filename );
        }
    }
}
void LanguageTable::LoadTranslation(char *_filename)
{
    LoadLanguage( _filename, m_translation );

#ifdef _DEBUG
    DArray<char *> *keys = m_baseLanguage.ConvertIndexToDArray();

    for( int i = 0; i < keys->Size(); ++i )
    {
        if( keys->ValidIndex(i) )
        {
            char *key = keys->GetData(i);
			if( !m_translation.GetData( key ) )
			{
				AppDebugOut( "Warning : base language key '%s' with no translation in language file %s\n", key, _filename );
			}
        }
    }

    delete keys;
#endif
}
Exemple #30
0
unsigned int HashTable<T>::GetInsertPos(char const *_key) const
{
	unsigned int index = HashFunc(_key);

	// Test if the target slot is empty, if not increment until we
	// find an empty one
	while (m_keys[index] != NULL)
	{
		if(stricmp(m_keys[index], _key) == 0)
        {
            AppDebugOut( "GetInsertPos critical error : trying to insert key '%s'\n", _key );
            DumpKeys();
            AppAbort("Error with HashTable");
        }

		index++;
		index &= m_mask;
		m_numCollisions++;
	}

	return index;
}