Beispiel #1
0
void AlliancesWindow::Update()
{   
    //
    // Build a list of all teams;

    LList<Team *> teams;
    for( int i = 0; i < g_app->GetWorld()->m_teams.Size(); ++i )
    {
        Team *team = g_app->GetWorld()->m_teams[i];
        teams.PutData( team );
    }


    //
    // Now put the other teams in, in alliance order

    int currentIndex = 0;

    while( teams.Size() > 0 )
    {
        Team *baseTeam = teams[0];
        m_teamOrder[currentIndex] = baseTeam->m_teamId;
        ++currentIndex;
        teams.RemoveData(0);

        for( int i = 0; i < teams.Size(); ++i )
        {
            Team *possibleAlly = teams[i];
            if( possibleAlly->m_allianceId == baseTeam->m_allianceId )
            {
                m_teamOrder[currentIndex] = possibleAlly->m_teamId;
                ++currentIndex;
                teams.RemoveData(i);
                --i;
            }
        }
    }

    //
    // Are there any votes we can see?
    
    for( int i = 0; i < MAX_TEAMS; ++i )
    {
        m_votes[i] = -1;
    }    

    currentIndex = 0;
    
    for( int i = 0; i < g_app->GetWorld()->m_votingSystem.m_votes.Size(); ++i )
    {
        if( g_app->GetWorld()->m_votingSystem.m_votes.ValidIndex(i) )
        {
            Vote *vote = g_app->GetWorld()->m_votingSystem.m_votes[i];
            if( vote->m_result == Vote::VoteUnknown &&
                vote->CanSeeVote( g_app->GetWorld()->m_myTeamId ) )
            {
                m_votes[currentIndex] = i;
                ++currentIndex;
            }
        }
    }


    //
    // Make sure we are the right size
   
    m_h = 120 + g_app->GetWorld()->m_teams.Size() * 42;
    m_h += currentIndex * 45;    

    if( currentIndex > 0 ) m_h += 10;
    
    m_h = max(m_h, 300 );

    GetButton("Close")->m_y = m_h - 25;
}
//Подточка в)
LList<int> firstKTowns(LList<City> cities, LList<int> filteredCitiesByDistance, int k)
{
	int currentCities = 0; // not used ???
	int MaxNumberOfFamousPlaces = 0;	// not used ???
	int CurrNumbOfFamousPlaces = 0; // not used ???
	int* arr = new arr[filteredCitiesByDistance.len()]; // ???
	int i = 0;
	cities.IterStart();
	LList<int> temp;
	elem<City>* e = cities.Iter();
	City a;
	while (e)
	{
		filteredCitiesByDistance.IterStart();
		elem<int>* p = filteredCitiesByDistance.Iter();
		while (p)
		{
			a = e->inf;
			if (a.ID == p->inf)
			{
				arr[i] = a.FamousPlaces;
				i++;
			}
			p = p->link;
		}
		e = e->link;
	}

	for (size_t j = 0; j < filteredCitiesByDistance.len(); j++)
	{
		for (size_t p = 0; p < filteredCitiesByDistance.len() - 1; p++)
		{
			if (arr[j] < arr[p + 1]) swap(arr[j], arr[p + 1]);
		}
	}

	for (size_t q = 0; q < k; q++)
	{
		cities.iterStart();
		elem<City>* p = cities.Iter();
		while (p)
		{
			City b = p->inf;
			if (arr[q] == b.FamousPlaces)
			{
				temp.ToEnd(b.ID);
			}
		}
	}
	delete[]arr;
	return temp;
}
Beispiel #3
0
int main() {
  graph<Person> g;

  LList<string> peshoLikes;
  peshoLikes.ToEnd("rakia");
  peshoLikes.ToEnd("salata");
  peshoLikes.ToEnd("musaka");
  peshoLikes.ToEnd("bob");

  LList<string> pepaLikes;
  pepaLikes.ToEnd("nutela");
  pepaLikes.ToEnd("vino");
  pepaLikes.ToEnd("musaka");

  LList<string> draganLikes;
  draganLikes.ToEnd("rakia");
  draganLikes.ToEnd("nutela");
  draganLikes.ToEnd("bob");

  Person pesho("Pesho", 20, peshoLikes);
  Person ivan("Ivan", 25, LList<string>());
  Person petkan("Petkan", 22, LList<string>());
  Person mimi("Mimi", 20, LList<string>());
  Person mariika("Mariika", 22, LList<string>());
  Person pepa("Pepa", 20, pepaLikes);
  Person dragan("Dragan", 20, draganLikes);

  g.addTop(pesho);
  g.addTop(ivan);
  g.addTop(petkan);
  g.addTop(mimi);
  g.addTop(mariika);
  g.addTop(pepa);
  g.addTop(dragan);

  g.addRib(pesho, ivan);
  g.addRib(pesho, petkan);
  g.addRib(pesho, mimi); // result
  g.addRib(pesho, mariika);

  g.addRib(petkan, mimi);
  g.addRib(petkan, mariika);
  g.addRib(petkan, pepa);
  g.addRib(mimi, dragan);

  // neighbours(g, pesho).print();

  // problem_1(g, pesho);
  problem_2(g, pesho);
  return 0;
}
Beispiel #4
0
	LongInt* Multi(LongInt* otherInt) //multiplication
	{
		LongInt *result = new LongInt();
		//sign
		if(intData->head->value == otherInt->intData->head->value)
			result->intData->head->value = 0;
		else
			result->intData->head->value = 1;

		LList* myList = intData;
        LNode *myNode = intData->FirstRight();
		LList *otherList = otherInt->intData;

        //the length of the result
		for(int i = 0; i < myList->count + otherList->count; i++)
		{
			LNode* zeroNode = new LNode();
			zeroNode->value = 0;
			zeroNode->next = zeroNode->prev = NULL;
			result->intData->InsertLeft(zeroNode);
			zeroNode = NULL;
		}


		for(int i = 1; myNode != myList->head; myNode = myNode->prev, i++)
		{
			LNode* otherNode = otherList->FirstRight();
			for(int j = 1; otherNode != otherList->head; otherNode = otherNode->prev, j++)
			{
				int myValue =  myNode->value;
				int otherValue = otherNode->value;
				int tempResult = myValue * otherValue;
				int carry = OverFlow(tempResult);
				tempResult = tempResult - carry * (int)pow(10.0, (double)EVERY_NODE_LEN);

				LNode* resultNode = result->intData->CountFromRight(i + j - 1);
				LNode* carryNode = result->intData->CountFromRight(i + j);

				resultNode->value += tempResult; //may carry
				int carry2 = OverFlow(resultNode->value);
				resultNode->value = resultNode->value - carry2 * (int)pow(10.0, (double)EVERY_NODE_LEN);

				carryNode->value += carry + carry2; //may carry
				int carry3 = OverFlow(carryNode->value);
				carryNode->value = carryNode->value - carry3 * (int)pow(10.0, (double)EVERY_NODE_LEN);

				carryNode->prev->value += carry3;


			}
		}

		LNode* delNode = result->intData->head->next;
		while(delNode->value == 0)
		{
			result->intData->head->next = result->intData->head->next->next;
			result->intData->head->next->prev = result->intData->head;
			delete delNode;
			delNode = result->intData->head->next;
		}

		return result;

	}
Beispiel #5
0
int main()
{

	LList<int> llist;
	LList<int>::iterator it = llist.begin();
	LList<int>::iterator it2 = llist.end();
	it2 = LList<int>::iterator(it);
#if 1
	it  = llist.insert(it,1);
	it  = llist.insert(it,2);
	it  = llist.insert(it,3);
	it = llist.begin();
	cout<<"--------insert-------------"<<endl;
	for(;it != llist.end();it++)
		cout<<*it<<endl;

	llist.clear();

	llist.push_back(11);
	llist.push_back(12);
	llist.push_back(13);
	llist.erase(llist.begin());
	cout<<"--------push_back-------------"<<endl;
	for(it=llist.begin();it != llist.end();it++)
		cout<<*it<<endl;
	llist.clear();
	cout<<"--------size-------------"<<llist.size()<<endl;
	llist.push_back(14);
	llist.push_back(15);
	llist.push_back(16);
	for(it=llist.begin();it != llist.end();it++)
		cout<<*it<<endl;
	cout<<"--------transfer-------------"<<llist.size()<<endl;
	LList<int>::iterator first= ++llist.begin();
	LList<int>::iterator last= llist.end();
	llist.transfer(++llist.begin(),++first,last);
	for(it=llist.begin();it != llist.end();it++)
		cout<<*it<<endl;
	cout<<"--------reverse-------------"<<llist.size()<<endl;
	llist.reverse();
	for(it=llist.begin();it != llist.end();it++)
		cout<<*it<<endl;
#endif		
	return 0;
}
Beispiel #6
0
void RemoveUser(){
	system("CLS");
	string inputUsername, inputPassword; //for storage
	char input;
	bool Auth = false; //Auth variable
	
	cout << "\t\t" << "Account Removal Service" << endl;
	cout << "\t\t"; cout << "Enter Username: "******"\t\t"; cout << "Enter Password: "******"\t\t" << "Authenticating..." << endl;
	cout << "\t\t"; system("pause");
	Auth = S.authenticate(inputUsername, inputPassword); //Authenticate with the security class

	do{
		system("CLS");

		if (Auth){
			cout << "\t\t" << "Your Account Will be Deleted. Continue?" << endl;
			cout << "\t\t" << "[Y/N] "; cin >> input;
			if (input == 'y' || input == 'Y'){
				cout << "\t\t" << "Removing Data..." << endl;
				int deleted2 = remove((inputUsername + "Status").c_str());
				int deleted1 = remove(inputUsername.c_str());
				
				if (deleted1 != 0 && deleted2 != 0){
					perror("\t\tError deleting files!\n");
				}else{
					cout << "\t\tData successfully removed.\n";
					cout << "\t\t"; system("pause");
				}

				LList<string> *listofusers = new LList<string>();
				ifstream s("Username.txt");
				string users;
				while (getline(s, users)){
					listofusers->appendData(users);
				}

				listofusers->removeData(inputUsername);
				listofusers->FileWrite("Username.txt");
				return;

			}else if (input == 'n' || input == 'N'){
				cout << "\t\t" << "Account Deletion Process Terminated." << endl;
				cout << "\t\t"; system("pause");
				return;
			}else{
				cout << "\t\t" << "Invalid Input." << endl;
				cout << "\t\t"; system("pause");
			}
		}else{
			cout << "\t\t" << "Authentication Failed." << endl;
			cout << "\t\t"; system("pause");
			return;
		}
	} while (true);
Beispiel #7
0
void ReadData ( const char *inFilename,
                FILE *infile,
                LList<BranchPtr> &library )
{
   printf ( "Reading from file '%s'\n", inFilename );

   char line [128];
   LList<BranchPtr> *current = 0;

   while ( fgets ( line, sizeof(line), infile ) )
   {
      if ( StripComments ( line ) )
      {
         if ( line[0] == '[' )
         {
            // We have found the start of a new opening continuation

            current = &library;
            printf ( "processing %s\n", line );
         }
         else
         {
            // We have found the next move in the current continuation

            if ( !current )
            {
               fprintf ( stderr,
                         "Error:  move '%s' is not in a continuation!\n",
                         line );

               exit(1);
            }

            int len = (int) strlen(line);
            int isValid = 0;

            if ( len == 4 || (len == 5 && line[4] == '?') )
            {
               int x1 = line[0] - 'a';
               int y1 = line[1] - '1';
               int x2 = line[2] - 'a';
               int y2 = line[3] - '1';

               if ( x1 >= 0 && x1 <= 7 &&
                    y1 >= 0 && y1 <= 7 &&
                    x2 >= 0 && x2 <= 7 &&
                    y2 >= 0 && y2 <= 7 )
               {
                  isValid = 1;
                  unsigned short source = (x1+2) + (y1+2)*12;
                  unsigned short dest   = (x2+2) + (y2+2)*12;
                  unsigned short move   = (source << 8) | dest;

                  // First, see if this move is already there...
                  Branch *b = 0;

                  for ( unsigned j=0; j < current->numItems(); j++ )
                  {
                     Branch *x = (*current)[j];
                     if ( x->move == move )
                     {
                        b = x;
                        break;
                     }
                  }

                  if ( !b )
                  {
                     // This branch wasn't found, so create it!

                     b = new Branch;
                     if ( !b )
                     {
                        fprintf ( stderr, "Error: out of memory!\n" );
                        exit(1);
                     }

                     b->isBad = (line[4] == '?');
                     b->move  = move;

                     if ( current->addToBack ( b ) != DDC_SUCCESS )
                     {
                        fprintf ( stderr, "Error adding branch to node!\n" );
                        exit(1);
                     }
                  }

                  current = &(b->replies);
               }
            }

            if ( !isValid )
            {
               fprintf ( stderr,
                         "Error:  invalid move syntax: '%s'\n",
                         line );
               exit(1);
            }
         }
      }
   }
}
Beispiel #8
0
void Nuke::FindTarget( int team, int targetTeam, int launchedBy, Fixed range, Fixed *longitude, Fixed *latitude, int *objectId )
{
    START_PROFILE("Nuke::FindTarget");
    
    WorldObject *launcher = g_app->GetWorld()->GetWorldObject(launchedBy);
    if( !launcher ) 
    {
        END_PROFILE("Nuke::FindTarget");
        return;
    }

    LList<int> validTargets;
        
    for( int i = 0; i < g_app->GetWorld()->m_objects.Size(); ++i )
    {
        if( g_app->GetWorld()->m_objects.ValidIndex(i) )
        {
            WorldObject *obj = g_app->GetWorld()->m_objects[i];
            if( obj->m_teamId == targetTeam &&
                obj->m_seen[team] &&
                !obj->IsMovingObject() )
            {
                Fixed distanceSqd = g_app->GetWorld()->GetDistanceSqd( launcher->m_longitude, launcher->m_latitude, obj->m_longitude, obj->m_latitude);
                if( distanceSqd <= range * range )
                {                    
                    int numTargetedNukes = CountTargetedNukes( team, obj->m_longitude, obj->m_latitude );
                    
                    if( (obj->m_type == WorldObject::TypeRadarStation && numTargetedNukes < 2 ) ||
                        (obj->m_type != WorldObject::TypeRadarStation && numTargetedNukes < 4 ) )
                    {
                        validTargets.PutData(obj->m_objectId);
                    }
                }
            }
        }
    }

    if( validTargets.Size() > 0 )
    {
        int targetId = syncrand() % validTargets.Size();
        int objIndex = validTargets[ targetId ];
        WorldObject *obj = g_app->GetWorld()->GetWorldObject(objIndex);
        if( obj )
        {
            *longitude = obj->m_longitude;
            *latitude = obj->m_latitude;
            *objectId = obj->m_objectId;
            END_PROFILE("Nuke::FindTarget");
            return;
        }
    }

    Team *friendlyTeam = g_app->GetWorld()->GetTeam( team );

    int maxPop = 500000;        // Don't bother hitting cities with less than 0.5M survivors

    for( int i = 0; i < g_app->GetWorld()->m_cities.Size(); ++i )
    {
        if( g_app->GetWorld()->m_cities.ValidIndex(i) )
        {
            City *city = g_app->GetWorld()->m_cities[i];

            if( !g_app->GetWorld()->IsFriend( city->m_teamId, team) && 
				g_app->GetWorld()->GetDistanceSqd( city->m_longitude, city->m_latitude, launcher->m_longitude, launcher->m_latitude) <= range * range)               
            {
                int numTargetedNukes = CountTargetedNukes(team, city->m_longitude, city->m_latitude);
                int estimatedPop = City::GetEstimatedPopulation( team, i, numTargetedNukes );
                if( estimatedPop > maxPop )
                {
                    maxPop = estimatedPop;
                    *longitude = city->m_longitude;
                    *latitude = city->m_latitude;
                    *objectId = -1;
                }
            }
        }
    }
    
    END_PROFILE("Nuke::FindTarget");
}
Beispiel #9
0
int TestLList()
{
	LList<char *> *llist = new LList<char *>();
	TEST_ASSERT(llist);

	TEST_ASSERT(!llist->valid((unsigned int)-1));
	TEST_ASSERT(!llist->valid(1));
	TEST_ASSERT(!llist->valid(0));

	llist->insert(newStr("one"));
	llist->insert(newStr("two"));
	llist->insert(newStr("three"));
	llist->insert(newStr("four"));

	TEST_ASSERT(strcmp(llist->get(0), "one") == 0);
	TEST_ASSERT(strcmp(llist->get(2), "three") == 0);
	TEST_ASSERT(strcmp(llist->get(3), "four") == 0);
	TEST_ASSERT(strcmp(llist->get(1), "two") == 0);

	delete [] llist->get(1);
	llist->remove(1);

	TEST_ASSERT(strcmp(llist->get(0), "one") == 0);
	TEST_ASSERT(strcmp(llist->get(1), "three") == 0);
	TEST_ASSERT(strcmp(llist->get(2), "four") == 0);

	while (llist->valid(0))	{
		delete [] llist->get(0);
		llist->remove(0);
	}

	TEST_ASSERT(!llist->valid((unsigned int)-1));
	TEST_ASSERT(!llist->valid(1));
	TEST_ASSERT(!llist->valid(0));

	delete llist;

	return 0;
}
Beispiel #10
0
void SoundSystem::Advance()
{
    if( !m_channels )
	{
		return;
	}

    float timeNow = GetHighResTime();
    if( timeNow >= m_timeSync )
    {
        m_timeSync = timeNow + SOUNDSYSTEM_UPDATEPERIOD;
        
        START_PROFILE("SoundSystem");        
		
#ifndef TARGET_MSVC
		((SoundLibrary2dSDL *)g_soundLibrary2d)->m_callbackLock.Lock();
#endif
		
        //
        // Resync with blueprints (changed by editor)

        START_PROFILE("Propagate Blueprints" );
        if( m_propagateBlueprints )
        {
            PropagateBlueprints();
        }
        END_PROFILE("Propagate Blueprints" );


        //
		// First pass : Recalculate all Perceived Sound Volumes
		// Throw away sounds that have had their chance
        // Build a list of instanceIDs for sorting

        START_PROFILE("Allocate Sorted Array" );
        static int sortedArraySize = 128;
        static SoundInstanceId *sortedIds = NULL;
        if( m_sounds.NumUsed() > sortedArraySize )
        {
            delete [] sortedIds;
            sortedIds = NULL;
            while( sortedArraySize < m_sounds.NumUsed() )
                sortedArraySize *= 2;
        }
        if( !sortedIds )
        {            
            sortedIds = new SoundInstanceId[ sortedArraySize ];
        }

        int numSortedIds = 0;
        END_PROFILE("Allocate Sorted Array" );

        START_PROFILE("Perceived Volumes" );
        for( int i = 0; i < m_sounds.Size(); ++i )
        {
            if( m_sounds.ValidIndex(i) )
            {
                SoundInstance *instance = m_sounds[i];
                if( !instance->IsPlaying() && !instance->m_loopType ) instance->m_restartAttempts--;
                if( instance->m_restartAttempts < 0 )
                {
                    ShutdownSound( instance );
                }
                else if( instance->m_positionType == SoundInstance::Type3DAttachedToObject &&
                         !instance->GetAttachedObject().IsValid() )                
                {
                    ShutdownSound( instance );
                }
                else
                {
                    instance->CalculatePerceivedVolume();
                    sortedIds[numSortedIds] = instance->m_id;
                    numSortedIds++;
                }
            }
        }
        END_PROFILE("Perceived Volumes" );


        //        
		// Sort sounds into perceived volume order
        // NOTE : There are exactly numSortedId elements in sortedIds.  
        // NOTE : It isn't safe to assume numSortedIds == m_sounds.NumUsed()
        
        START_PROFILE("Sort Samples" );
        qsort( sortedIds, numSortedIds, sizeof(SoundInstanceId), SoundInstanceCompare );
        END_PROFILE("Sort Samples" );


        //
		// Second pass : Recalculate all Sound Priorities starting with the nearest sounds
        // Reduce priorities as more of the same sounds are played

        BTree<float> existingInstances;
        
                
        //                
        // Also look out for the highest priority new sound to swap in

        START_PROFILE("Recalculate Priorities" );

        LList<SoundInstance *> newInstances;
        SoundInstance *newInstance = NULL;
        float highestInstancePriority = 0.0f;

        for( int i = 0; i < numSortedIds; ++i )
        {
            SoundInstanceId id = sortedIds[i];
            SoundInstance *instance = GetSoundInstance( id );
            AppDebugAssert( instance );

            instance->m_calculatedPriority = instance->m_perceivedVolume;

            BTree<float> *existingInstance = existingInstances.LookupTree( instance->m_eventName );
            if( existingInstance )
            {
                instance->m_calculatedPriority *= existingInstance->data;
                existingInstance->data *= 0.75f;
            }
            else
            {
                existingInstances.PutData( instance->m_eventName, 0.75f );
            }

            if( !instance->IsPlaying() )
            {
                if( instance->m_positionType == SoundInstance::TypeMusic )
                {
                    newInstances.PutData( instance );
                }
                else if( instance->m_calculatedPriority > highestInstancePriority )
                {
                    newInstance = instance;
                    highestInstancePriority = instance->m_calculatedPriority;
                }
            }
        }

        if( newInstance )
        {
            newInstances.PutData( newInstance );
        }

        END_PROFILE("Recalculate Priorities" );
        
     
        for( int i = 0; i < newInstances.Size(); ++i )
        {            
            SoundInstance *newInstance = newInstances[i];
            bool isMusic = (newInstance->m_positionType == SoundInstance::TypeMusic);

            // Find worst old sound to get rid of  
            START_PROFILE("Find best Channel" );
            int bestAvailableChannel = FindBestAvailableChannel( isMusic );
            END_PROFILE("Find best Channel" );

			// FindBestAvailableChannel can return -1, so let's not access an invalid index later on.
			if ( bestAvailableChannel < 0 )
				continue;

            START_PROFILE("Stop Old Sound" );
			// Stop the old sound
            SoundInstance *existingInstance = GetSoundInstance( m_channels[bestAvailableChannel] );
            if( existingInstance && !existingInstance->m_loopType )
            {
                ShutdownSound( existingInstance );
            }
            else if( existingInstance )
            {
                existingInstance->StopPlaying();
            }            
            END_PROFILE("Stop Old Sound" );


            START_PROFILE( "Start New Sound" );
			// Start the new sound
            bool success = newInstance->StartPlaying( bestAvailableChannel );
            if( success )
            {
                m_channels[bestAvailableChannel] = newInstance->m_id;
            }
            else
            {
                // This is fairly bad, the sound failed to play
                // Which means it failed to load, or to go into a channel
                ShutdownSound( newInstance );
            }
            END_PROFILE("Start New Sound" );
            
            START_PROFILE("Reset Channel" );
            g_soundLibrary3d->ResetChannel( bestAvailableChannel);
            END_PROFILE("Reset Channel" );
        }


        //
        // Advance all sound channels

        START_PROFILE("Advance All Channels" );
        for( int i = 0; i < m_numChannels; ++i )
        {            
            SoundInstanceId soundId = m_channels[i];            
            SoundInstance *currentSound = GetSoundInstance( soundId );                         
            if( currentSound )
            {
                bool amIDone = currentSound->Advance();
                if( amIDone )
                {                    
			        START_PROFILE("Shutdown Sound" );
                    ShutdownSound( currentSound );
			        END_PROFILE("Shutdown Sound" );
                }    
            }
        }
        END_PROFILE("Advance All Channels" );


		//
        // Update our listener position

        START_PROFILE("UpdateListener" );    

        Vector3<float> camPos, camVel, camUp, camFront;
        bool cameraDefined = m_interface->GetCameraPosition( camPos, camFront, camUp, camVel );

        if( cameraDefined )
        {
            if( g_preferences->GetInt("SoundSwapStereo",0) == 0 )
            {
                camUp *= -1.0f;
            }

            g_soundLibrary3d->SetListenerPosition( camPos, camFront, camUp, camVel );
        }
        
        END_PROFILE("UpdateListener" );    


        //
        // Advance our sound library

        START_PROFILE("SoundLibrary3d Advance" );
        g_soundLibrary3d->Advance();
        END_PROFILE("SoundLibrary3d Advance" );
      
#ifdef SOUNDSYSTEM_VERIFY
        RuntimeVerify();
#endif

#ifndef TARGET_MSVC
		((SoundLibrary2dSDL *)g_soundLibrary2d)->m_callbackLock.Unlock();
#endif

        END_PROFILE("SoundSystem");                    
    }
}
Vector3 Entity::PushFromObstructions( Vector3 const &pos, bool killem )
{
    Vector3 result = pos;    
    if( m_onGround )
    {
        result.y = g_app->m_location->m_landscape.m_heightMap->GetValue( result.x, result.z );
    }

    Matrix34 transform( m_front, g_upVector, result );

    //
    // Push from Water

    if( result.y <= 1.0 )
    {        
        double pushAngle = syncsfrand(1.0);
        double distance = 0.0;
        while( distance < 50.0 )
        {
            double angle = distance * pushAngle * M_PI;
            Vector3 offset( iv_cos(angle) * distance, 0.0, iv_sin(angle) * distance );
            Vector3 newPos = result + offset;
            double height = g_app->m_location->m_landscape.m_heightMap->GetValue( newPos.x, newPos.z );
            if( height > 1.0 )
            {
                result = newPos;
                result.y = height;
                break;
            }
            distance += 1.0;
        }
    }
    

    //
    // Push from buildings

    LList<int> *buildings = g_app->m_location->m_obstructionGrid->GetBuildings( result.x, result.z );

    for( int b = 0; b < buildings->Size(); ++b )
    {
        int buildingId = buildings->GetData(b);
        Building *building = g_app->m_location->GetBuilding( buildingId );
        if( building )
        {        
            bool hit = false;
            if( m_shape && building->DoesShapeHit( m_shape, transform ) ) hit = true;
            if( (!m_shape || m_type == TypeOfficer ) && building->DoesSphereHit( result, 1.0 ) ) hit = true;
            // cheap hack, but no point overriding the entire function for this one line
            if( !hit )
            {
                Vector3 oldPos = m_pos - m_vel * SERVER_ADVANCE_PERIOD;
                if( building->DoesRayHit( oldPos, m_front, (m_pos - oldPos).Mag() ) ) hit = true;
            }

            if( hit )
            {            
                if( building->m_type == Building::TypeLaserFence && killem &&
                    ((LaserFence *) building)->IsEnabled())
                {
                    if( !g_app->m_location->IsFriend(building->m_id.GetTeamId(), m_id.GetTeamId() ) )
                    {
                        ChangeHealth( -9999 );
                        ((LaserFence *) building)->Electrocute( m_pos );
                    }
                }
                else
                {               
                    Vector3 pushForce = (building->m_pos - result);
                    pushForce.y = 0.0f;
                    pushForce.SetLength(4.0f);
                    while( building->DoesSphereHit( result, 2.0f ) )
                    {
                        result -= pushForce;   
                        //result.y = g_app->m_location->m_landscape.m_heightMap->GetValue( result.x, result.z );
                    }
                }
            }
        }
    }

    return result;
}
void SWInterface::ToggleVersionMenu ( char *program, int x, int y )
{

	if ( program && 
		 !IsVisibleVersionMenu ( program ) ) {

		// Create it
		
		LList <char *> software;				// Bit of a hack - think about this
		LList <float> versions;

		DataBank *db = &(game->GetWorld ()->GetPlayer ()->gateway.databank);

		for ( int di = 0; di < db->GetDataSize (); ++di ) {

			if ( db->GetDataFile (di) &&
				 db->GetDataFile (di)->TYPE == DATATYPE_PROGRAM &&
				 strcmp ( db->GetDataFile (di)->title, program ) == 0 ) {

				software.PutData ( db->GetDataFile (di)->title );
				versions.PutData ( db->GetDataFile (di)->version );

			}

		}

		// Ensures total time = 500ms

		int timesplit = 500;
		if ( software.Size () > 0 )
			timesplit /= software.Size ();

		for ( int si = 0; si < software.Size (); ++si ) {
	
			char caption [128], tooltip [128], name [128];
			UplinkSnprintf ( caption, sizeof ( caption ), "%s v%1.1f", software.GetData (si), versions.GetData (si) );
			UplinkStrncpy ( tooltip, "Runs this software application", sizeof ( tooltip ) );
			UplinkSnprintf ( name, sizeof ( name ), "hud_version %d", si );
			EclRegisterButton ( x, y, 120, 15, caption, tooltip, name );
			EclRegisterButtonCallbacks ( name, SoftwareDraw, SoftwareClick, button_click, button_highlight );
			EclRegisterMovement ( name, x, y - si * 17, si * timesplit );

		}
		
        SgPlaySound ( RsArchiveFileOpen ("sounds/softwaremenu.wav"), "sounds/softwaremenu.wav", false );

	}
	else {

		// Remove it
		// We don't know how many entries there could be, so keep deleting until they run out

		int i = 0;
		char name [128];
		UplinkSnprintf ( name, sizeof ( name ), "hud_version %d", i );

		while ( EclGetButton ( name ) != NULL ) {

			EclRemoveButton ( name );
			++i;
			UplinkSnprintf ( name, sizeof ( name ), "hud_version %d", i );

		}	

		// Force redraw of the button that fathered this menu

		char bname [32];
		UplinkSnprintf ( bname, sizeof ( bname ), "hud_software %d", currentprogrambutton );
		EclDirtyButton ( bname );

		currentprogrambutton = -1;

	}

}
void SWInterface::ToggleSubMenu ( int softwareTYPE, int x, int y )
{

	if ( !IsVisibleSubMenu ( softwareTYPE ) ) {

		// Create a list of all software in memory

		LList <char *> software;				// Bit of a hack - think about this
		LList <float> versions;

		DataBank *db = &(game->GetWorld ()->GetPlayer ()->gateway.databank);

		for ( int di = 0; di < db->GetDataSize (); ++di ) {

			if ( db->GetDataFile (di) &&
				 db->GetDataFile (di)->TYPE == DATATYPE_PROGRAM &&
				 db->GetDataFile (di)->softwareTYPE == softwareTYPE ) {

				// This sofware is the correct type.  Add it into the list if it isn't already there,
				// or if its version is higher than any existing program of the same name

				// First try to find a software item of the same name
				int existingindex = -1;
				
				for ( int si = 0; si < software.Size (); ++si ) {
					if ( strcmp ( software.GetData (si), db->GetDataFile (di)->title ) == 0 ) {
						existingindex = si;
						break;
					}
				}

				// If it already exists, add this item in only if it has a higher version number

				if ( existingindex == -1 ) {

					software.PutData ( db->GetDataFile (di)->title );
					versions.PutData ( db->GetDataFile (di)->version );

				}
				if ( existingindex != -1 &&	
					 db->GetDataFile (di)->version > versions.GetData (existingindex) ) {
				
					software.RemoveData ( existingindex );
					versions.RemoveData ( existingindex );

					software.PutDataAtIndex ( db->GetDataFile (di)->title, existingindex );
					versions.PutDataAtIndex ( db->GetDataFile (di)->version, existingindex );

				}

			}

		}

		int timesplit = 500;
		if ( software.Size () > 0 )
			timesplit /= software.Size ();				// Ensures total time = 500ms

		for ( int si = 0; si < software.Size (); ++si ) {
	
			char caption [128], tooltip [128], name [128];
			UplinkSnprintf ( caption, sizeof ( caption ), "%s v%1.1f", software.GetData (si), versions.GetData (si) );
			UplinkStrncpy ( tooltip, "Runs this software application", sizeof ( tooltip ) );
			UplinkSnprintf ( name, sizeof ( name ), "hud_software %d", si );
			EclRegisterButton ( x, y, 140, 15, caption, tooltip, name );
			EclRegisterButtonCallbacks ( name, SoftwareDraw, SoftwareClick, button_click, SoftwareHighlight );
			EclRegisterMovement ( name, x, y - si * 17, si * timesplit );

		}

		currentsubmenu = softwareTYPE;

        SgPlaySound ( RsArchiveFileOpen ( "sounds/softwaremenu.wav" ), "sounds/softwaremenu.wav", false );

	}
	else {

		// Remove the software menu
		// We don't know how many entries there could be, so keep deleting until they run out

		int i = 0;
		char name [32];
		UplinkSnprintf ( name, sizeof ( name ), "hud_software %d", i );

		while ( EclGetButton ( name ) != NULL ) {

			EclRemoveButton ( name );
			++i;
			UplinkSnprintf ( name, sizeof ( name ), "hud_software %d", i );

		}

		// Redraw the button that was selected

		char bname [32];
		UplinkSnprintf ( bname, sizeof ( bname ), "hud_swmenu %d", currentsubmenu );
		EclDirtyButton ( bname );

		currentsubmenu = SOFTWARETYPE_NONE;

	}

}
 void enqueue(const E it)
 {
     queue->append(it);
     ++length;
 }
void EclShutdown ()
{
    windows.EmptyAndDelete();
    dirtyrects.EmptyAndDelete();
}
 E dequeue()
 {
     E result=queue->headremove();
     --length;
     return result;
 }
void Officer::SetOrders( Vector3 const &_orders )
{
    static float lastOrderSet = 0.0f;

    if( !g_app->m_location->IsWalkable( m_pos, _orders ) )
    {
        g_app->m_sepulveda->Say( "officer_notwalkable" );
    }
    else
    {
        float distanceToOrders = ( _orders - m_pos ).Mag();

        if( distanceToOrders > 20.0f )
        {
            m_orderPosition = _orders;
            m_orders = OrderGoto;
            m_absorb = false;

            //
            // If there is a teleport nearby,
            // assume he wants us to go in it

            bool foundTeleport = false;

            m_ordersBuildingId = -1;
            LList<int> *nearbyBuildings = g_app->m_location->m_obstructionGrid->GetBuildings( m_orderPosition.x, m_orderPosition.z );
            for( int i = 0; i < nearbyBuildings->Size(); ++i )
            {
                int buildingId = nearbyBuildings->GetData(i);
                Building *building = g_app->m_location->GetBuilding( buildingId );
                if( building->m_type == Building::TypeRadarDish ||
                    building->m_type == Building::TypeBridge )
                {
                    float distance = ( building->m_pos - _orders ).Mag();
                    if( distance < 5.0f )
                    {
                        Teleport *teleport = (Teleport *) building;
                        m_ordersBuildingId = building->m_id.GetUniqueId();
                        Vector3 entrancePos, entranceFront;
                        teleport->GetEntrance( entrancePos, entranceFront );
                        m_orderPosition = entrancePos;
                        foundTeleport = true;
                        break;
                    }
                }
            }

            if( !foundTeleport )
            {
                m_orderPosition = PushFromObstructions( m_orderPosition );
            }


            //
            // Create the line using particles immediately,
            // so the player can see what he's just done

            float timeNow = GetHighResTime();
            if( timeNow > lastOrderSet + 1.0f )
            {
                lastOrderSet = timeNow;
                OfficerOrders orders;
                orders.m_pos = m_pos;
                orders.m_wayPoint = m_orderPosition;
                while( true )
                {
                    if( orders.m_arrivedTimer < 0.0f )
                    {
                        g_app->m_particleSystem->CreateParticle( orders.m_pos, g_zeroVector, Particle::TypeMuzzleFlash, 50.0f );
                        g_app->m_particleSystem->CreateParticle( orders.m_pos, g_zeroVector, Particle::TypeMuzzleFlash, 40.0f );
                    }
                    if( orders.Advance() ) break;
                }

                CancelOrderSounds();
                g_app->m_soundSystem->TriggerEntityEvent( this, "SetOrderGoto" );
            }
        }
        else
        {
            float timeNow = GetHighResTime();
            int researchLevel = g_app->m_globalWorld->m_research->CurrentLevel( GlobalResearch::TypeOfficer );

            if( timeNow > lastOrderSet + 0.3f )
            {
                lastOrderSet = timeNow;

                switch( researchLevel )
                {
                    case 0 :
                    case 1 :
                    case 2 :
                        m_orders = OrderNone;
                        break;

                    case 3 :
                        if      ( m_orders == OrderNone )       m_orders = OrderFollow;
                        else if ( m_orders == OrderFollow )     m_orders = OrderNone;
                        else if ( m_orders == OrderGoto )       m_orders = OrderNone;
                        break;

                    case 4 :
                        if      ( m_orders == OrderNone )                   m_orders = OrderFollow;
                        else if ( m_orders == OrderFollow && !m_absorb )
                        {
                            m_absorb = true;
                            m_absorbTimer = 2.0f;
                        }
                        else if ( m_orders == OrderFollow && m_absorb )
                        {
                                                                            m_orders = OrderNone;
                                                                            m_absorb = false;
                        }
                        else if ( m_orders == OrderGoto )                   m_orders = OrderNone;
                        break;
                }

                CancelOrderSounds();

                switch( m_orders )
                {
                    case OrderNone:     g_app->m_soundSystem->TriggerEntityEvent( this, "SetOrderNone" );       break;
                    case OrderGoto:     g_app->m_soundSystem->TriggerEntityEvent( this, "SetOrderGoto" );       break;
                    case OrderFollow:
                        if( m_absorb )  g_app->m_soundSystem->TriggerEntityEvent( this, "SetOrderAbsorb" );
                        else            g_app->m_soundSystem->TriggerEntityEvent( this, "SetOrderFollow" );
                        break;
                }

                m_buildingId = -1;
            }
        }
    }
}
void ParseMemoryLeakFile(const char *_inputFilename, const char *_outputFilename)
{
	/* */
	/* Start up */
	/* */

	RedBlackTree<char *, int> combined;
	RedBlackTree<char *, int> frequency;
	int                       unrecognised = 0;

	/* */
	/* Open the file and start parsing */
	/* */

	FILE                     *memoryfile = fopen(_inputFilename, "rb");

	while (memoryfile && !feof(memoryfile))	{
		char thisline[1024];

		fgets(thisline, 1024, memoryfile);

		if (!strncmp(thisline, " Data:", 6) == 0) { /* This line is a data line - useless to us */
			if (strchr(thisline, ':')) {                               /* This line does not have a source file location - useless to us */
				/* Get the size */

				char *lastcomma = strrchr(thisline, ',');
				if (lastcomma == 0) continue;

				char *ssize = lastcomma + 2;
				int   size;
				char  unused[32];

				sscanf(ssize, "%d %s", &size, unused);

				/* Get the source file name */

				char *sourcelocation = thisline;
				char *colon = strrchr(thisline, ':');

				*(colon - 1) = '\x0';

				/* Put the result into our BTree */

				int   result = 0;
				bool  found = combined.find(sourcelocation, result);

				if (found)
					combined.replace(sourcelocation, result + size);
				else
					combined.insert(sourcelocation, size);

				found = frequency.find(sourcelocation, result);

				if (frequency.exists(sourcelocation))
					frequency.replace(sourcelocation, result + size);
				else
					frequency.insert(sourcelocation, 1);
			} else {
				char *lastcomma = strrchr(thisline, ',');

				if (lastcomma) {
					char *ssize = lastcomma + 2;
					int   size;
					char  unused[32];

					sscanf(ssize, "%d %s", &size, unused);

					unrecognised += size;
				}
			}
		}
	}

	fclose(memoryfile);


	/* */
	/* Sort the results into a list */
	/* */

	LList<char *>   sorted;
	DArray<char *> *dataI = combined.ConvertIndexToDArray();
	DArray<int>    *dataD = combined.ConvertToDArray();

	int             totalsize = 0;

	for (size_t i = 0; i < dataI->size(); i++) {
		if (dataI->valid(i)) {
			char *newsource = dataI->get(i);
			int   newsize = dataD->get(i);

			totalsize += newsize;
			bool  inserted = false;

			for (size_t i = 0; i < sorted.size(); i++) {
				char *existingsource = sorted.get(i);
				int   existingsize;

				combined.find(existingsource, existingsize);

				if (newsize <= existingsize) {
					sorted.insert_at(newsource, i);
					inserted = true;
					break;
				}
			}

			if (!inserted)
				sorted.insert(newsource);
		}
	}

	delete dataI;
	delete dataD;


	/* */
	/* Open the output file */
	/* */

	if (sorted.size()) {
		FILE *output = fopen(_outputFilename, "wt");

		/* */
		/* Print out our sorted list */
		/* */

		fprintf(output, "Total recognised memory leaks   : %d Kbytes\n",
		        int( totalsize / 1024 ));
		fprintf(output, "Total unrecognised memory leaks : %d Kbytes\n\n",
		        int( unrecognised / 1024 ));

		for (int k = (int)sorted.size() - 1; k >= 0 && k < (int)sorted.size(); k--) {
			char *source = sorted.get(k);
			CoreAssert(source);
			int   size; combined.find(source, size);
			int   freq; frequency.find(source, freq);

			if (size > 1048576) {
				fprintf(output, "%-95s (%d MB in %d leaks)\n", source,
				        int( size / 1048576 ), freq);
			} else if (size > 2048) {
				fprintf(output, "%-95s (%d KB in %d leaks)\n", source,
				        int( size / 1024 ), freq);
			} else {
				fprintf(output, "%-95s (%d  bytes in %d leaks)\n", source, size,
				        freq);
			}
		}

		/* */
		/* Clean up */

		fclose(output);
	}
}
Beispiel #19
0
int main (){
    LList<int> myList;
    myList.insertFront(10);
}
Beispiel #20
0
// Finds all the filenames in the specified directory that match the specified
// filter. Directory should be like "data/textures" or "data/textures/".
// Filter can be NULL or "" or "*.bmp" or "map_*" or "map_*.txt"
// Set FullFilename to true if you want results like "data/textures/blah.bmp" 
// or false for "blah.bmp"
LList <char *> *ListDirectory( const char *_dir, const char *_filter, bool _fullFilename )
{
    if(_filter == NULL || _filter[0] == '\0')
    {
        _filter = "*";
    }

    if(_dir == NULL || _dir[0] == '\0')
    {
        _dir = "";
    }

    // Create a DArray for our results
    LList <char *> *result = new LList<char *>();

    // Now add on all files found locally
#ifdef WIN32
    char searchstring [256];
    AppAssert(strlen(_dir) + strlen(_filter) < sizeof(searchstring) - 1);
    sprintf( searchstring, "%s%s", _dir, _filter );

    _finddata_t thisfile;
    long fileindex = _findfirst( searchstring, &thisfile );

    int exitmeplease = 0;

    while( fileindex != -1 && !exitmeplease ) 
    {
        if( strcmp( thisfile.name, "." ) != 0 &&
            strcmp( thisfile.name, ".." ) != 0 &&
            !(thisfile.attrib & _A_SUBDIR) )
        {
            char *newname = NULL;
            if( _fullFilename ) 
            {
                int len = strlen(_dir) + strlen(thisfile.name);
                newname = new char [len + 1];
                sprintf( newname, "%s%s", _dir, thisfile.name );      
            }
            else
            {
                int len = strlen(thisfile.name);
                newname = new char [len + 1];
                sprintf( newname, "%s", thisfile.name );
            }

            result->PutData( newname );
        }

        exitmeplease = _findnext( fileindex, &thisfile );
    }
#else
    DIR *dir = opendir(_dir[0] ? _dir : ".");
    if (dir == NULL)
        return result;
    for (struct dirent *entry; (entry = readdir(dir)) != NULL; ) {
        if (FilterMatch(entry->d_name, _filter)) {
            char fullname[strlen(_dir) + strlen(entry->d_name) + 2];
            sprintf(fullname, "%s%s%s", 
                _dir, 
                _dir[0] ? "/" : "",
                entry->d_name);
            if (!IsDirectory(fullname)) {
                result->PutData( 
                    newStr(_fullFilename ? fullname : entry->d_name));
            }
        }
    }
    closedir(dir);
#endif

    return result;
}
Beispiel #21
0
void PositionUpdater::run (void)
{
    const char *pszMethodName = "PositionUpdater::run";
    setName (pszMethodName);

    started();

    BufferWriter bw;
    do {
        _m.lock();
        if (!_bMessageRequested) {
            _cv.wait (DSPro::DEFAULT_UPDATE_TIMEOUT);
        }

        if (pTopoLog != nullptr) {
            if ((_pDSPro != nullptr) && (_pDSPro->_pTopology != nullptr)) {
                logTopology (pszMethodName, Logger::L_Info, "\n==== TOPOLOGY ===\n");
                _pDSPro->_pTopology->display (pTopoLog->getLogFileHandle());
                logTopology (pszMethodName, Logger::L_Info, "\n=================\n");
            }
        }

        LList<MsgIdWrapper> msgToRequestCpy;
        int64 i64Now = getTimeInMilliseconds();
        for (MsgIdWrapper *pMsgIdWr = _msgToRequest.getFirst(); pMsgIdWr != nullptr; pMsgIdWr = _msgToRequest.getNext()) {
            msgToRequestCpy.add (*pMsgIdWr); // copy the IDs of the message to request
            pMsgIdWr->ui64LatestRequestTime = i64Now;
        }
        _msgToRequest.removeAll();

        StringHashtable<LList<String> > *pMsgToNotify = _pMsgToNotify;
        _pMsgToNotify = new StringHashtable<LList<String> >(true, true, true, true);

        _m.unlock();

        MsgIdWrapper msgIdWr;
        for (int rc = msgToRequestCpy.getFirst (msgIdWr); rc == 1; rc = msgToRequestCpy.getNext (msgIdWr)) {
            int64 i64Elapsed = i64Now - msgIdWr.ui64LatestRequestTime;
            if (msgIdWr.ui64LatestRequestTime == 0U || (i64Elapsed > DSPro::DEFAULT_UPDATE_TIMEOUT)) {
                Targets **ppTargets;
                if (msgIdWr.senderId.length() <= 0) {
                    ppTargets = _pDSPro->_pTopology->getNeighborsAsTargets();
                }
                else {
                    ppTargets = _pDSPro->_pTopology->getForwardingTargets (_pDSPro->getNodeId(), msgIdWr.senderId);
                }
                if ((ppTargets != nullptr) && (ppTargets[0] != nullptr)) {
                    int rc = 0;
                    String publisher (msgIdWr.publisherId.length() <= 0 ? _pDSPro->getNodeId() : msgIdWr.publisherId.c_str());
                    if (isOnDemandDataID (msgIdWr.msgId)) {
                        rc = _pDSPro->_adaptMgr.sendChunkRequestMessage (msgIdWr.msgId, &(msgIdWr.locallyCachedChunkIds),
                                                                         publisher, ppTargets);
                    }
                    else {
                        rc = _pDSPro->_adaptMgr.sendMessageRequestMessage (msgIdWr.msgId, publisher, ppTargets);
                    }
                    if (rc == 0) {
                        checkAndLogMsg (pszMethodName, Logger::L_Info, "Requested request "
                                        "message with id: <%s>.\n", msgIdWr.msgId.c_str());
                    }
                    else {
                        checkAndLogMsg (pszMethodName, Logger::L_Warning, "Can not request message with "
                                        "id = <%s> failed. Returned %d\n", msgIdWr.msgId.c_str(), rc);
                    }
                }
                Targets::deallocateTargets (ppTargets);
            }
        }

        doMetadataArrived (pMsgToNotify);
        delete pMsgToNotify;

        _m.lock();
        _bMessageRequested = false;
        int64 i64Tmp = _i64TimeStamp;
        _m.unlock();

        if ((getTimeInMilliseconds() - i64Tmp) > DSPro::DEFAULT_UPDATE_TIMEOUT) {

            if (_pNodeContexMgr->getActivePeerNumber() == 0) {
                continue;
            }

            bw.reset();
            int rc = _pNodeContexMgr->updatePosition (&bw);
            if (rc < 0) {
                checkAndLogMsg (pszMethodName, Logger::L_MildError, "Could not write "
                                "the way point message. Error code %d.\n", rc);
                continue;
            }

            _m.lock();
            _i64TimeStamp = getTimeInMilliseconds();
            _m.unlock();

            _pDSPro->sendWaypointMessage (bw.getBuffer(), bw.getBufferLength());
        }

        if (_pDSPro->_bEnableTopologyExchange && _bTopologyHasChanged) {
            _bTopologyHasChanged = false;
            BufferWriter bw (1024, 1024);
            if (_pDSPro->_pTopology->write (&bw, 0) == 0) {
                Targets **ppTargets = _pDSPro->_pTopology->getNeighborsAsTargets();
                if ((ppTargets != nullptr) && (ppTargets[0] != nullptr)) {
                    int rc = _pDSPro->_adaptMgr.sendTopologyReplyMessage (bw.getBuffer(), bw.getBufferLength(), ppTargets);
                    if (rc != 0) {
                        checkAndLogMsg (pszMethodName, Logger::L_Warning, "Can not send "
                                        "topology reply message. Returned %d\n", rc);
                    }
                    else {
                        checkAndLogMsg (pszMethodName, Logger::L_Info,
                                        "sent topology reply.\n");
                    }
                }
                Targets::deallocateTargets (ppTargets);
            }
        }

    } while (!terminationRequested());

    terminating();
}
void NewsScreenInterface::DrawDetails ( Button *button, bool highlighted, bool clicked )
{

	UplinkAssert (button);

	int screenheight = app->GetOptions ()->GetOptionValue ( "graphics_screenheight" );
	glScissor ( button->x, screenheight - (button->y + button->height), button->width, button->height );	
	glEnable ( GL_SCISSOR_TEST );

	// Get the offset

	char name_base [128];
	sscanf ( button->name, "%s", name_base );
    ScrollBox *scrollBox = ScrollBox::GetScrollBox( name_base );
    if ( !scrollBox ) return;
    int offset = scrollBox->currentIndex;
	
	// Draw the button

	glBegin ( GL_QUADS );
		SetColour ( "PanelBackgroundA" );       glVertex2i ( button->x, button->y + button->height );
		SetColour ( "PanelBackgroundB" );       glVertex2i ( button->x, button->y );
		SetColour ( "PanelBackgroundA" );       glVertex2i ( button->x + button->width, button->y );
		SetColour ( "PanelBackgroundB" );       glVertex2i ( button->x + button->width, button->y + button->height );
	glEnd ();

	SetColour ( "PanelBorder" );
	border_draw ( button );


	// Draw the text

	int maxnumlines = (button->height - 10 ) / 15;

	SetColour ( "DefaultText" );

	LList <char *> *wrappedtext = wordwraptext ( button->caption, button->width );

	if ( wrappedtext ) {

		for ( int i = offset; i < wrappedtext->Size (); ++i ) {

			if ( i > maxnumlines + offset )
				break;

			int xpos = button->x + 10;
			int	ypos = button->y + 10 + (i-offset) * 15;

			GciDrawText ( xpos, ypos, wrappedtext->GetData (i), HELVETICA_10 );

		}

		//DeleteLListData ( wrappedtext );							// Only delete first entry - since there is only one string really
		if ( wrappedtext->ValidIndex (0) && wrappedtext->GetData (0) )
			delete [] wrappedtext->GetData (0);
		delete wrappedtext;

	}

	glDisable ( GL_SCISSOR_TEST );
	
}
Beispiel #23
0
void PositionUpdater::doMetadataArrived (StringHashtable<MsgIdList > *pMsgToNotifyByQueryId)
{
    if (pMsgToNotifyByQueryId == nullptr) {
        return;
    }
    const char *pszMethodName = "PositionUpdater::doMetadataArrived";

    String msgId;
    StringHashtable<LList<String> >::Iterator iter = pMsgToNotifyByQueryId->getAllElements();
    for (; !iter.end(); iter.nextElement()) {
        const char *pszQueryId = iter.getKey();
        LList<String> *pMsgToNotify = iter.getValue();

        for (int rc = pMsgToNotify->getFirst (msgId); rc == 1; rc = pMsgToNotify->getNext (msgId)) {

            MessageHeaders::MsgType type;
            Message *pMessage = getCompleteMessageAndRemoveDSProMetadata (_pDSPro->_pDataStore, msgId.c_str(), type);
            if (pMessage == nullptr || (type != MessageHeaders::Data && type != MessageHeaders::Metadata)) {
                // The message to be notified to the application was not found at
                // this time. Re-add it to the list of messages to notify so it can
                // be tried again later.
                static const char * messageIds[2];
                messageIds[0] = msgId.c_str();
                messageIds[1] = nullptr;
                addMetadataToNotify (pszQueryId, messageIds);
            }
            else {
                MessageInfo *pMI = pMessage->getMessageInfo();
                char *pszId = convertFieldToKey (pMI->getGroupName(), pMI->getPublisherNodeId(), pMI->getMsgSeqId());
                const String currMsgId (pszId);
                if (pszId == nullptr) {
                    checkAndLogMsg (pszMethodName, memoryExhausted);
                }
                else {
                    free (pszId);
                    pszId = nullptr;
                }
                String sGrpName (MessageIdGenerator::extractSubgroupFromMsgGroup (pMI->getGroupName()));
                if (sGrpName.length() <= 0) {
                    checkAndLogMsg (pszMethodName, Logger::L_MildError, "could not extract group message id\n");
                    sGrpName = pMI->getGroupName();
                }

                if (type == MessageHeaders::Metadata) {
                    MetaData *pMetadata = toMetadata (pMessage->getData(), pMI->getTotalMessageLength());
                    if (pMetadata != nullptr) {
                        String sReferredObjectId, sReferredInstanceId, sRefersTo;
                        getReferredObjectAndInstanceIds (pMetadata, sReferredObjectId, sReferredInstanceId, sRefersTo);
                        int rc = _pDSPro->metadataArrived (currMsgId, sGrpName, sReferredObjectId,
                                                           sReferredInstanceId, pMetadata, sRefersTo,
                                                           pszQueryId);
                        checkAndLogMsg (pszMethodName, Logger::L_Info, "notified clients "
                                        "with message %s matching query request %s\n/",
                                        currMsgId.c_str(), pszQueryId);
                        delete pMetadata;
                        pMetadata = nullptr;
                        if (rc != 0) {
                            checkAndLogMsg (pszMethodName, Logger::L_Warning, "Can not notify message "
                                            "with id = <%s> failed. Returned %d\n", currMsgId.c_str(), rc);
                        }
                        else {
                            checkAndLogMsg (pszMethodName, Logger::L_Info, "client applications "
                                            "notified message with id: <%s>.\n", currMsgId.c_str());
                        }
                    }
                }
                else {
                    // Data or chunked data
                    uint8 ui8ChunkIndex = pMI->getTotalNumberOfChunks() == 0 ? (uint8) 0 : 1; // HACK: For the general case I need to figure out the current number of chunks from the database
                    rc = _pDSPro->dataArrived (currMsgId, sGrpName, pMI->getObjectId(), pMI->getInstanceId(),
                                               pMI->getAnnotates(), pMI->getMimeType(), pMessage->getData(),
                                               pMI->getTotalMessageLength(), ui8ChunkIndex, pMI->getTotalNumberOfChunks(),
                                               pszQueryId);
                }

                free ((void*) pMessage->getData());
                delete pMessage->getMessageHeader();
                delete pMessage;
            }
        }
    }
}
Beispiel #24
0
	LongInt* Add(LongInt* otherInt) //addition
	{
		LongInt *result = new LongInt();
		LList* otherList = otherInt->intData;
		LList* resultList = result->intData;
		LNode* myNode = intData->FirstRight();
		LNode* otherNode = otherList->FirstRight();

		int addition = 0;
		int carry = 0;
		LNode* tempNode;

		while(intData->count != otherList->count)
		{
			LNode* zeroNode = new LNode();
			zeroNode->value = 0;
			zeroNode->next = zeroNode->prev = NULL;
			if(intData->count > otherList->count)
				otherList->InsertLeft(zeroNode);
			else
				intData->InsertLeft(zeroNode);
			zeroNode = NULL;
		}

		if(intData->head->value == otherList->head->value)
		{
			resultList->head->value = intData->head->value;

			while(myNode != intData->head)
			{
				addition = myNode->value + otherNode->value + carry;
				carry = OverFlow(addition);
				addition = addition - carry * (int)pow(10.0, (double)EVERY_NODE_LEN);

				tempNode = new LNode();
				tempNode->value = addition;
				tempNode->prev = tempNode->next = NULL;
				resultList->InsertLeft(tempNode);
				tempNode = NULL;
				myNode = intData->NextLeft(myNode);
				otherNode = otherList->NextLeft(otherNode);
			}

			if(carry != 0)
			{
				LNode* carryNode = new LNode();
				carryNode->value = carry;
				carryNode->next = carryNode->prev = NULL;
				resultList->InsertLeft(carryNode);
			}
		}
		else //opposite sign
		{
			LList *leftList, *rightList;

			int abs = CompAbs(otherInt);
			if(abs == 0)
			{
				LNode* zeroNode = new LNode();
				zeroNode->value = 0;
				zeroNode->next = zeroNode->prev = NULL;
				resultList->InsertLeft(zeroNode);
				return result;
			}
			else if(abs == 1)
			{
				resultList->head->value = intData->head->value;
				leftList = intData;
				rightList = otherInt->intData;
			}
			else
			{
				resultList->head->value = otherInt->intData->head->value;
				leftList = otherInt->intData;
				rightList = intData;
			}

			myNode = leftList->FirstRight();
			otherNode = rightList->FirstRight();
			carry = 0;

			while(myNode != leftList->head)
			{

				addition = myNode->value - otherNode->value + carry;
				if(addition < 0)
				{
					carry = -1;
					addition = addition + (int)pow(10.0, (double)EVERY_NODE_LEN);
				}
				else
					carry = 0;

				tempNode = new LNode();
				tempNode->value = addition;
				tempNode->prev = tempNode->next = NULL;
				resultList->InsertLeft(tempNode);
				tempNode = NULL;
				myNode = leftList->NextLeft(myNode);
				otherNode = rightList->NextLeft(otherNode);
			}
		}

		return result;
	}
Beispiel #25
0
bool ProcessServerLetters( Directory *letter )
{
    if( strcmp( letter->m_name, NET_DEFCON_MESSAGE ) != 0 ||
        !letter->HasData( NET_DEFCON_COMMAND ) )
    { 
        AppDebugOut( "Client received bogus message, discarded (4)\n" );
        return true;
    }


    char *cmd = letter->GetDataString( NET_DEFCON_COMMAND );


    if( strcmp( cmd, NET_DEFCON_CLIENTHELLO ) == 0 )
    {
        int clientId = letter->GetDataInt(NET_DEFCON_CLIENTID);
        if( clientId == g_app->GetClientToServer()->m_clientId )
        {
            g_app->GetClientToServer()->m_connectionState = ClientToServer::StateConnected;
            AppDebugOut( "CLIENT : Received HelloClient from Server\n" );
            if( !g_app->GetTutorial() )
            {
                g_app->GetClientToServer()->RequestTeam( Team::TypeLocalPlayer );
            }
        }

        // If this is a Demo client, make a note of that
        if( letter->HasData( NET_DEFCON_CLIENTISDEMO ) )
        {
            g_app->GetClientToServer()->SetClientDemo( clientId );
        }

        // This might be a client rejoining the game
        // Need to give him his teams back
        g_app->GetWorld()->ReassignTeams( clientId );        

        return true;
    }
    else if( strcmp( cmd, NET_DEFCON_CLIENTGOODBYE ) == 0 )
    {
        int clientId = letter->GetDataInt(NET_DEFCON_CLIENTID);
        int reason = letter->GetDataInt(NET_DEFCON_DISCONNECT);

        AppDebugOut( "CLIENT : Client %d left the game\n", clientId );
        g_app->GetWorld()->RemoveTeams( clientId, reason );
        g_app->GetWorld()->RemoveSpectator( clientId );
        g_app->GetClientToServer()->SetSyncState( clientId, true );
        return true;
    }
    else if( strcmp( cmd, NET_DEFCON_CLIENTID ) == 0 )
    {
        int clientId = letter->GetDataInt(NET_DEFCON_CLIENTID);        
        AppDebugOut( "CLIENT : Received ClientID of %d\n", clientId );        

        if( g_app->GetClientToServer()->m_clientId != -1 )
        {
            AppAssert( g_app->GetClientToServer()->m_clientId == clientId );
            return true;
        }

        g_app->GetClientToServer()->m_clientId = clientId;
        g_app->GetClientToServer()->m_connectionState = ClientToServer::StateHandshaking;
        g_lastProcessedSequenceId = -1;

        if( letter->HasData( NET_DEFCON_VERSION, DIRECTORY_TYPE_STRING ) )
        {
            char *serverVersion = letter->GetDataString( NET_DEFCON_VERSION );
            strcpy( g_app->GetClientToServer()->m_serverVersion, serverVersion );
            AppDebugOut( "CLIENT : Server version is %s\n", serverVersion );
        }

        if( !VersionManager::DoesSupportModSystem( g_app->GetClientToServer()->m_serverVersion ) )
        {
            // This server is too old to support Mods, so make sure we de-activate any critical ones
            g_modSystem->DeActivateAllCriticalMods();
            if( g_modSystem->CommitRequired() )
            {
                g_modSystem->Commit();
				g_app->RestartAmbienceMusic();
            }
        }

        return true;
    }
    else if( strcmp( cmd, NET_DEFCON_TEAMASSIGN ) == 0 )
    {
        int clientId = letter->GetDataInt(NET_DEFCON_CLIENTID);        
        int teamId   = letter->GetDataInt(NET_DEFCON_TEAMID);
        int teamType = letter->GetDataInt(NET_DEFCON_TEAMTYPE);

        if( teamType != Team::TypeAI &&
            clientId != g_app->GetClientToServer()->m_clientId )
        {
            teamType = Team::TypeRemotePlayer;
        }

        g_app->GetWorld()->InitialiseTeam(teamId, teamType, clientId );
        return true;
    }
    else if( strcmp( cmd, NET_DEFCON_SPECTATORASSIGN ) == 0 )
    {
        int clientId = letter->GetDataInt(NET_DEFCON_CLIENTID);        
        g_app->GetWorld()->InitialiseSpectator(clientId);

        if( clientId == g_app->GetClientToServer()->m_clientId )
        {            
            AppDebugOut( "CLIENT: I am a spectator\n" );
        }
				
        return true;
    }
    else if( strcmp( cmd, NET_DEFCON_NETSYNCERROR ) == 0 )
    {
        int clientId = letter->GetDataInt(NET_DEFCON_CLIENTID);        
        AppDebugOut( "SYNCERROR Server informed us that Client %d is out of Sync\n", clientId );

        g_app->GetClientToServer()->SetSyncState( clientId, false );

        char *syncId = letter->GetDataString( NET_DEFCON_SYNCERRORID );
        DumpSyncLogs(syncId);

        return true;
    }
    else if( strcmp( cmd, NET_DEFCON_NETSYNCFIXED ) == 0 )
    {
        int clientId = letter->GetDataInt(NET_DEFCON_CLIENTID);        
        AppDebugOut( "SYNCFIXED Server informed us that Client %d has repaired his Sync Error\n", clientId );
        g_app->GetClientToServer()->SetSyncState( clientId, true );
        return true;
    }
    else if( strcmp( cmd, NET_DEFCON_DISCONNECT ) == 0 )
    {
        if( g_app->GetClientToServer()->m_connectionState > ClientToServer::StateDisconnected )
        {
            g_app->ShutdownCurrentGame();
            if ( EclGetWindow("LOBBY") )
				EclRemoveWindow( "LOBBY" );
			if ( EclGetWindow("Comms Window") )
				EclRemoveWindow( "Comms Window" );
			if ( EclGetWindow("Preparing Game...") )
				EclRemoveWindow("Preparing Game..." );

            g_app->GetInterface()->OpenSetupWindows();

            char *reason;
			char *reasonLanguagePhrase;
            int reasonDisconnectInt = letter->GetDataInt(NET_DEFCON_DISCONNECT);
            switch( reasonDisconnectInt )
            {
                case Disconnect_ClientLeave:            reason = "You have left the game";
					                                    reasonLanguagePhrase = "dialog_disconnect_client_leave";         break;
                case Disconnect_ServerShutdown:         reason = "The server has shutdown";
					                                    reasonLanguagePhrase = "dialog_disconnect_server_shutdown";      break;
                case Disconnect_InvalidKey:             reason = "You are using an invalid key";
					                                    reasonLanguagePhrase = "dialog_disconnect_invalid_key";          break;
                case Disconnect_DuplicateKey:           reason = "You are using a duplicate key";
					                                    reasonLanguagePhrase = "dialog_disconnect_duplicate_key";        break;
                case Disconnect_KeyAuthFailed:          reason = "Key authentication failed";
					                                    reasonLanguagePhrase = "dialog_disconnect_key_auth_failed";      break;
                case Disconnect_BadPassword:            reason = "Invalid Password Entered";
					                                    reasonLanguagePhrase = "dialog_disconnect_bad_password";         break;
                case Disconnect_GameFull:               reason = "Game is already full";
					                                    reasonLanguagePhrase = "dialog_disconnect_game_full";            break;
                case Disconnect_KickedFromGame:         reason = "Kicked by the Server";
					                                    reasonLanguagePhrase = "dialog_disconnect_kicked_from_game";     break;
                case Disconnect_DemoFull:               reason = "Too many Demo Players already";
					                                    reasonLanguagePhrase = "dialog_disconnect_demo_full";            break;
				default:                                reason = "Unknown";
					                                    reasonLanguagePhrase = "dialog_disconnect_unknown";              break;
            }

            if( reasonDisconnectInt == Disconnect_KeyAuthFailed ||
                reasonDisconnectInt == Disconnect_InvalidKey ||
                reasonDisconnectInt == Disconnect_DuplicateKey )
            {
                char authKey[256];
				if( Authentication_IsKeyFound() )
				{
					Authentication_GetKey( authKey );
				}
				else
				{
					sprintf( authKey, LANGUAGEPHRASE("dialog_authkey_not_found") );
				}

                BadKeyWindow *badKey = new BadKeyWindow();

				sprintf( badKey->m_extraMessage, LANGUAGEPHRASE("dialog_auth_error") );
				LPREPLACESTRINGFLAG( 'E', LANGUAGEPHRASE(reasonLanguagePhrase), badKey->m_extraMessage );
				LPREPLACESTRINGFLAG( 'K', authKey, badKey->m_extraMessage );

				EclRegisterWindow(badKey);
            }
            else if( reasonDisconnectInt == Disconnect_DemoFull )
            {
                int maxGameSize;
                int maxDemoPlayers;
                bool allowDemoServers;
                g_app->GetClientToServer()->GetDemoLimitations( maxGameSize, maxDemoPlayers, allowDemoServers );
                BadKeyWindow *badKey = new BadKeyWindow();

                sprintf( badKey->m_extraMessage, LANGUAGEPHRASE("dialog_server_demo_restricted") );
                LPREPLACEINTEGERFLAG( 'N', maxDemoPlayers, badKey->m_extraMessage );

                badKey->m_offerDemo = false;
                EclRegisterWindow(badKey);                
            }
            else
            {
                MessageDialog *dialog = new MessageDialog( "Disconnected", reasonLanguagePhrase, true, "dialog_disconnected", true );
                EclRegisterWindow( dialog );
            }

            AppDebugOut( "CLIENT : Received Disconnect from server : %s\n", reason );

#ifdef TESTBED
            if( letter->GetDataInt(NET_DEFCON_DISCONNECT) == Disconnect_ServerShutdown )
            {
                RestartTestBed(1, "Client Disconnect");
            }
#endif

        }
        return true;            
    }
    else if( strcmp( cmd, NET_DEFCON_SETMODPATH ) == 0 )
    {
        char *modPath = letter->GetDataString( NET_DEFCON_SETMODPATH );
        AppDebugOut( "Server has set the MOD path: '%s'\n", modPath );
        
        if( !g_modSystem->IsCriticalModPathSet( modPath ) )
        {
            if( g_modSystem->CanSetModPath( modPath ) )
            {
                g_modSystem->DeActivateAllCriticalMods();
                g_modSystem->SetModPath( modPath );
            }
            else
            {
                char reason[8192];
                sprintf( reason, LANGUAGEPHRASE("dialog_error_mod_path_caption") );

                char modPathCopy[4096];
                strcpy( modPathCopy, modPath );
                LList<char *> *tokens = g_modSystem->ParseModPath( modPathCopy );

                for( int i = 0; i < tokens->Size(); i+=2 )
                {
                    char *modName = tokens->GetData(i);
                    char *version = tokens->GetData(i+1);

                    strcat( reason, modName );
                    strcat( reason, " " );
                    strcat( reason, version );

                    if( !g_modSystem->IsModInstalled( modName, version ) )
                    {
                        strcat( reason, "    " );
                        strcat( reason, LANGUAGEPHRASE("dialog_mod_not_installed") );
                    }
                    
                    strcat( reason, "\n" );
                }

                delete tokens;
                
                MessageDialog *dialog = new MessageDialog( "Error setting MOD path", reason, false, "dialog_error_mod_path_title", true );
                EclRegisterWindow( dialog );
            }
        }

        return true;
    }
    else
    {
        return false;
    }
}
int main(){

	LList Identifiers;
	LList Keywords;
	LList Punctuators;
	LList Operators;
	LList Constants;
	numOfStringConstants = 0;
	numOfCharLiterals = 0;
	numOfIdentifiers = 0;
	numOfBooleanConstants = 0;
	numOfKeywords = 0;
	numOfOperators = 0;
	numOfPunctuators = 0;
	numOfIntegerConstants = 0;
	numOfFloatConstants = 0;
	fstream cppfile; //the stream used to open the file.

	int numOfConstants = 0;
	char filename[32];

	output = ""; //initialize output to a blank string
	charPointer = 0; //point to the first character

	cout << "Enter the name of the file you want to analyze.\n";
	cout << "Note: It should within the same directory as your program: ";
	cin.getline(filename, 30);

	//read the file and place the contents to output.
	cppfile.open(filename, ios::in);

	if (!cppfile)
	{
		cout << "\n Unable to open the input file." << endl;
		cout << "\n Press any key to exit.";

		_getch();
		exit(0);
	}

	while (!cppfile.eof()){
		cppfile.get(ch); //get each character from the file
		output = output + ch; //append each character to the output string.
	}

	cppfile.close(); //close the file

	cout << "\nTHE PROGRAM\n\n";
	while (charPointer < output.length() - 1){
		cout << output[charPointer];
		charPointer++;
	}

	cout << "\n\n";
	//read the output string character by character.
	cout << "\nRESULTS...\n\n";

	charPointer = 0;

	while (charPointer < output.length() - 1){
		//if a letter or a _ is found then this may be an identifier...
		if ((isalpha(output[charPointer])) || (output[charPointer] == '_')){

			lexeme = findEndOfIdentifier(charPointer);
			
			if (isKeyword(lexeme)){
				numOfKeywords++; //increment the number of keywords.
				
				char *cstr = new char[lexeme.length() + 1];
				strcpy(cstr, lexeme.c_str());
				Keywords.InsertInBack(cstr);
				// do stuff
				delete[] cstr;
				
			}

		}

		else if (output[charPointer] == '/'){
			skipComment(charPointer);
		}

		else if (output[charPointer] == '#'){
			//skip the directive and move the character pointer
			skipDirective(charPointer);
		}

		else if (strchr("+-/*=<>!&|[]", output[charPointer])){
			lexeme = findEndOperator(charPointer); //check if there are operators beside it too

			if (isOperator(lexeme)){
				numOfOperators++;

				char *cstr = new char[lexeme.length() + 1];
				strcpy(cstr, lexeme.c_str());
				// do stuff
				Operators.InsertInBack(cstr);
				delete[] cstr;
				
				
			}
		}

		else if (isPunctuator((output[charPointer]))){
			numOfPunctuators++;
			lexeme = output[charPointer];
			char *cstr = new char[lexeme.length() + 1];
			strcpy(cstr, lexeme.c_str());
			// do stuff
			Punctuators.InsertInBack(cstr);
			delete[] cstr;
			
			
		}

		else if (isdigit(output[charPointer])){

			//if it is a number, find its end
			lexeme = findEndOfNum(charPointer);

			if (isInteger(lexeme)){ //if the number is an integer, increment the number of integer constants
				numOfIntegerConstants++;
				numOfConstants++;
				char *cstr = new char[lexeme.length() + 1];
				strcpy(cstr, lexeme.c_str());
				// do stuff
				Constants.InsertInBack(cstr);
				delete[] cstr;
				
				

			}
			else if (isFloat(lexeme)) {//if it is a float, increment the number of float constants
				numOfFloatConstants++;
				numOfConstants++;
				char *cstr = new char[lexeme.length() + 1];
				strcpy(cstr, lexeme.c_str());
				// do stuff
				Constants.InsertInBack(cstr);
				delete[] cstr;
				
				
			}
		}

		charPointer++; //move the pointer to the next character.
	}
	cout << "\nNumber of keywords found is: " << numOfKeywords << '\n';
	cout << "\tkeywords found are: ";
	Keywords.PrintList();

	//cout << "\nNumber of boolean constants found is: " << numOfBooleanConstants << "\n";

	cout << "\n\nNumber of identifiers found is: " << numOfIdentifiers << "\n";
	cout << "\tIdentifiers found are: ";
	Identifiers.PrintList();


	cout << "\n\nNumber of operators found is: " << numOfOperators << "\n";
	cout << "\toperators found are: ";
	Operators.PrintList();

	cout << "\n\nNumber of Delimiters found is: " << numOfPunctuators << "\n";
	cout << "\tDelimiters found are: ";
	Punctuators.PrintList();

	cout << "\n\nNumber of Constants found is: " << numOfConstants << "\n";
	cout << "\tConstants found are: ";
	Constants.PrintList();

	cout << "\n\n Press any key to exit.";

	_getch();
	exit(0);


}
void ParseMemoryLeakFile ( char *_inputFilename, char *_outputFilename )
{

    //
    // Start up
    //

    BTree <int> combined;
    BTree <int> frequency;
    int unrecognised = 0;

    //
    // Open the file and start parsing
    //

    ifstream memoryfile ( _inputFilename );

    while ( !memoryfile.eof () ) 
    {
        char thisline [256];
        memoryfile.getline ( thisline, 256 );

        if ( !strncmp ( thisline, " Data:", 6 ) == 0 &&         // This line is a data line - useless to us
              strchr ( thisline, ':' ) ) {                      // This line does not have a source file location - useless to us

            // Get the size

            char *lastcomma = strrchr ( thisline, ',' );
            char *ssize = lastcomma+2;
            int size;
            char unused [32];
            sscanf ( ssize, "%d %s", &size, unused );

            // Get the source file name

            char *sourcelocation = thisline;
            char *colon = strrchr ( thisline, ':' );
            *(colon-1) = '\x0';
            char *lowercasesourcelocation = LowerCaseString ( sourcelocation );
            
            // Put the result into our BTree

            BTree <int> *btree = combined.LookupTree ( lowercasesourcelocation );
            if ( btree ) ((int) btree->data) += size;
            else combined.PutData ( lowercasesourcelocation, size );
            
            BTree <int> *freq = frequency.LookupTree ( lowercasesourcelocation );
            if ( freq ) ((int) freq->data) ++;
            else frequency.PutData ( lowercasesourcelocation, 1 );

            delete lowercasesourcelocation;
        }
        else 
        {
            char *lastcomma = strrchr ( thisline, ',' );
            
            if ( lastcomma ) 
            {

                char *ssize = lastcomma+2;
                int size;
                char unused [32];
                if( sscanf ( ssize, "%d %s", &size, unused ) == 2 )
	                unrecognised += size;
            }
        }
    }

    memoryfile.close ();

    
    //
    // Sort the results into a list
    //

    DArray <int> *sizes = combined.ConvertToDArray ();
    DArray <char *> *sources = combined.ConvertIndexToDArray ();
    LList <char *> sorted;
    int totalsize = 0;

    for ( int i = 0; i < sources->Size (); ++i )
    {
        char *newsource = sources->GetData (i);
        int newsize = sizes->GetData (i);
        totalsize += newsize;
        bool inserted = false;

        for ( int j = 0; j < sorted.Size (); ++j ) {

            char *existingsource = sorted.GetData (j);
            int existingsize = combined.GetData ( existingsource );

            if ( newsize <= existingsize ) {

                sorted.PutDataAtIndex ( newsource, j );
                inserted = true;
                break;

            }

        }

        if ( !inserted ) sorted.PutDataAtEnd ( newsource );
    }


    //
    // Open the output file
    //

    FILE *output = fopen( _outputFilename, "wt" );

    //
    // Print out our sorted list
    // 

    fprintf ( output, "Total recognised memory leaks   : %d Kbytes\n", int(totalsize/1024)  );
    fprintf ( output, "Total unrecognised memory leaks : %d Kbytes\n\n", int(unrecognised/1024) );
    
    for ( int k = sorted.Size () - 1; k >= 0; --k ) 
    {

        char *source = sorted.GetData (k);
        int size = combined.GetData ( source );
        int freq = frequency.GetData ( source );

        if( size > 2048 )
        {
            fprintf ( output, "%-95s (%d Kbytes in %d leaks)\n", source, int(size/1024), freq );
        }
        else
        {
            fprintf ( output, "%-95s (%d  bytes in %d leaks)\n", source, size, freq );
        }
    }


    //
    // Clear up

    fclose( output );

    delete sources;
    delete sizes;
}
void LocationEditor::AdvanceModeLandTile()
{
	Vector3 mousePos3D = g_app->m_userInput->GetMousePos3d();

	int newSelectionId = -1;
	if ( g_inputManager->controlEvent( ControlTileSelect ) )
	{
		newSelectionId = IsPosInLandTile(mousePos3D);
	}

	if (m_selectionId == -1)
	{
		// No selection

		Landscape *land = &g_app->m_location->m_landscape;
		LList<LandscapeTile *> *tiles = &g_app->m_location->m_levelFile->m_landscape.m_tiles;
		
		// Has the user selected a tile
		if (newSelectionId != -1) 
		{
			LandscapeTile *tile = tiles->GetData(newSelectionId);
			m_tool = ToolMove;
			m_selectionId = newSelectionId;
			m_newLandscapeX = tile->m_posX;
			m_newLandscapeZ = tile->m_posZ;
			m_waitingForRelease = true;

			EclWindow *cw = EclGetWindow("editor_landscape");
			AppDebugAssert(cw);
			LandscapeTileEditWindow *ew = new LandscapeTileEditWindow("editor_landscapetile", newSelectionId);
			ew->m_w = cw->m_w;
			ew->m_h = 150;
			ew->m_x = cw->m_x;
			EclRegisterWindow(ew);
			ew->m_y = cw->m_y - ew->m_h - 10;
		}
	}
	
	if (m_selectionId != -1)
	{
		// There is a current selection

		if( g_inputManager->controlEvent( ControlTileDrop ) )
		{
			// Move the selected landscape to the new position and regenerate it
			LandscapeTile *tileDef = g_app->m_location->m_levelFile->m_landscape.m_tiles.GetData(m_selectionId);
			if( m_newLandscapeX != tileDef->m_posX ||
				m_newLandscapeZ != tileDef->m_posZ )
			{
                if( m_moveBuildingsWithLandscape )
                {
                    MoveBuildingsInTile( tileDef, m_newLandscapeX - tileDef->m_posX, m_newLandscapeZ - tileDef->m_posZ );
                }

				tileDef->m_posX = m_newLandscapeX;
				tileDef->m_posZ = m_newLandscapeZ;
				LandscapeDef *def = &g_app->m_location->m_levelFile->m_landscape;
				g_app->m_location->m_landscape.Init(def);
                delete g_app->m_location->m_water;
                g_app->m_location->m_water = new Water();
			}
		}
		if( g_inputManager->controlEvent( ControlTileSelect ) ) // TODO: Should this be ControlTileGrab?
		{
			if (newSelectionId == m_selectionId)
			{
				// The user "grabs" the landscape at this position
				LandscapeDef *landscapeDef = &(g_app->m_location->m_levelFile->m_landscape);
				LandscapeTile *tileDef = g_app->m_location->m_levelFile->m_landscape.m_tiles.GetData(m_selectionId);
				m_landscapeGrabX = mousePos3D.x - tileDef->m_posX;
				m_landscapeGrabZ = mousePos3D.z - tileDef->m_posZ;
			}
			else
			{
				// The user has deselected the landscape
				m_tool = ToolNone;
				m_selectionId = -1;
				m_waitingForRelease = true;
				EclRemoveWindow("editor_landscapetile");
                EclRemoveWindow("editor_guidegrid");
			}
		}
		else if ( g_inputManager->controlEvent( ControlTileDrag ) )
		{
			// The user "drags" the landscape around
			m_newLandscapeX = mousePos3D.x - m_landscapeGrabX;
			m_newLandscapeZ = mousePos3D.z - m_landscapeGrabZ;        
		}
	}
}
int main() {
    LList L;

    srand(77);
    unsigned int r, e, pos;

    r = rand() % 12;
    cout << "Inserting " << r << " elements to the list...." << endl;
    for (int i=0; i<r; i++) {
        e = rand()%100;
        cout << "Inserting " << e << " at position 0" << endl;
        L.insert(e,0);
    }
    cout << "Contents of the list: " << L << endl << endl;

    r = rand() % r;
    cout << "Now erasing elements from random positions ...." << endl;
    for (int i=0; i<r; i++) {
        pos = rand()% L.getSize();
        cout << "Erasing from position " << pos << endl;
        L.erase(pos);
        cout << "Contents of the list: " << L << endl;
    }

    cout << endl;


    /***** Uncomment after you have implemented the push function *

    e = rand()%100;
    cout << "Now lets push a " << e <<" into the list..." << endl;
    cout << "The list is " << L.push(e) << " long " << endl;
    cout << "And contains: " << L << endl << endl;

    ************************************************************/


    /***** Uncomment after you have implemented the shift function *

    cout << "I have removed the element from the front of the list: " 
         << L.shift() << endl;
    cout << "List now contains: " << L << endl << endl;

    ************************************************************/



    /***** Uncomment after you have implemented the pop function *

    cout << "Removing element from the front of the list using pop() " << endl; 
    cout << "The element is: " << L.pop() << endl;
    cout << "List now contains: " << L << endl << endl;

    // Error del profe! No descomente
    // pos = rand() % L.getSize();
    // cout << "Removing element from pos " <<  pos 
    //     << " of the list using pop(" << pos << ")" << endl; 
    // cout << "The element is: " << L.pop(pos) << endl;
    // cout << "List now contains: " << L << endl << endl;

    ************************************************************/


    /***** Uncomment after you have implemented the splice function *
    
    r = rand() % (L.getSize()/2);
    r = 9;
    pos = rand() % (L.getSize()/2);
    cout << "Using the splice function to remove " << r 
         << " elements starting at position " << pos << endl; 
    cout << "The removed elements are: " << L.splice(pos, r) << endl;
    cout << "After splice, the List:" << L << endl << endl;

    ************************************************************/

    /***** Uncomment after you have implemented the join function

    cout << "The following is a string of all elements, using join:" << endl;
    cout << L.join("-") << endl << endl;
    
    ************************************************************/

    


    cout << endl;


    
    
}