예제 #1
0
//---------------------------------------
void Entity::EventSpawnEntity( Dictionary& params )
{
	Entity* invoker;
	if ( params.Get( "Invoker", invoker ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_WARNING, "Entity '%s' (%d) : EventSetAnimationState : Bad event args for 'invoker'\n",
			mName.c_str(), mEntityId );
		return;
	}

	if ( invoker != this ) return;

	std::string name;
	std::string animName;

	params.Get( "Name", name );
	params.Get( "AnimationName", animName );

	Dictionary p2;
	p2.Set( "EntityName", name );
	p2.Set( "Position", mPosition );
	EventManager::FireEvent( "SpawnEntity", p2 );
	Entity* spawned=0;
	p2.Get( "Entity", spawned );
	if ( spawned )
	{
		spawned->SetAnimationState( animName, 0 );
	}
}
예제 #2
0
void Diagram::_FromDict(const Dictionary& WormDict, WormClass& worm)
{
    name ira, masha;
    WormDict.Get("Ira", ira);
    worm.Ira = Ver(ira);
    WormDict.Get("Masha", masha);
    worm.Masha = Ver(masha);
    WormDict.Get("dSpin", worm.dSpin);
    WormDict.Get("K", worm.K);
}
예제 #3
0
void Diagram::_FromDict(const Dictionary& VerDict, vertex v)
{
    VerDict.Get("Name", v->Name);
    VerDict.Get("Sublat", v->R.Sublattice);
    VerDict.Get("Coordi", v->R.Coordinate);
    VerDict.Get("Tau", v->Tau);
    int spinin, spinout;
    VerDict.Get("SpinIn", spinin);
    VerDict.Get("SpinOut", spinout);
    v->_spin[IN] = spin(spinin);
    v->_spin[OUT] = spin(spinout);
}
예제 #4
0
//--------------------------------------
void RespawnPlayer( Dictionary& params )
{
	int who = -1;
	Player* player;

	params.Get( "PlayerIndex", who );

	if ( who >= 0 )
	{
		player = &gPlayers[ who ];

		// Make sure player is still connected
		if ( player->active )
		{
			player->alive = 1;
			player->pos = RNG::RandomInRange( Vec2f( 100, 100 ), Vec2f( 700, 500 ) );
			player->rotation = 0;
			player->vel = Vec2f::ZERO;
			
			gWriter.Write( NC_RESPAWN );
			gWriter.Write( who );
			gWriter.Write( player->pos );
			gServer.SendData( gWriter );
		}
	}
}
예제 #5
0
void Diagram::_FromDict(const Dictionary& GDict, gLine g)
{
    name g_in, g_out;
    GDict.Get("IN", g_in);
    g->nVer[IN] = Ver(g_in);
    GDict.Get("OUT", g_out);
    g->nVer[OUT] = Ver(g_out);
    GDict.Get("K", g->K);
    AddGHash(g->K);
    GDict.Get("IsMeasure", g->IsMeasure);
    GDict.Get("IsGGGammaG", g->IsGGGammaG);

    if (g->IsMeasure) {
        MeasureGLine = true;
        GMeasure = g;
        WMeasure = nullptr;
    }
}
예제 #6
0
파일: Map.cpp 프로젝트: hydraskillz/Mage2D
//---------------------------------------
void Map::SpawnGameObjectEvent( Dictionary& params )
{
    std::string name;
    Vec2f position;

    // Get name
    if ( params.Get( "ObjectName", name ) != Dictionary::DErr_SUCCESS )
    {
        ConsolePrintf( CONSOLE_ERROR, "Failed to spawn GameObject: missing ObjectName\n" );
        return;
    }

    // Get position
    if ( params.Get( "Position", position ) != Dictionary::DErr_SUCCESS )
    {
        ConsolePrintf( CONSOLE_ERROR, "Failed to spawn GameObject: missing Position\n" );
        return;
    }

    // Spawn entity
    GameObject* gameObject = NULL;

    GameObjectDefinition* def = GameObjectDefinition::GetDefinitionByName( name );
    if ( def )
    {
        gameObject = def->Create();
        gameObject->Position = position;
        gameObject->GameMap = this;
        gameObject->SetBoundsFromSprite();
        gameObject->ObjectId = mObjects.size();

        // Call OnCreate for all logic nodes on the object
        gameObject->FinalizeNodes();

        mObjects.push_back( gameObject );
    }
    else
    {
        ConsolePrintf( CONSOLE_ERROR, "Failed to spawn GameObject: No GameObject found '%s'\n", name.c_str() );
    }
    params.Set( "GameObject", gameObject );
}
예제 #7
0
//---------------------------------------
void Entity::TriggeredEvent( Dictionary& params )
{
	std::string eventName;
	Sprite* sprite;

	params.Get( "EventName", eventName );

	// Event came from sprite, make sure it is ours
	if ( params.Get( "Sprite", sprite ) == Dictionary::DErr_SUCCESS )
	{
		if ( sprite != mSprite ) return;
	}

	TriggerEvent( eventName );
	//EntityDefinition* myDef = EntityDefinition::GetDefinitionByName( mName );
	//myDef->TriggerEvent( eventName, this );

	//ConsolePrintf( "Entity '%s' (%d) TriggeredEvent: %s\n",
	//	mName.c_str(), mEntityId, eventName.c_str() );
}
예제 #8
0
//---------------------------------------
void Entity::EventSetAnimationState( Dictionary& params )
{
	Entity* invoker;
	if ( params.Get( "Invoker", invoker ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_WARNING, "Entity '%s' (%d) : EventSetAnimationState : Bad event args for 'invoker'\n",
			mName.c_str(), mEntityId );
		return;
	}

	if ( invoker != this ) return;

	std::string animName = "Idle";
	int frame = 0;

	params.Get( "AnimationName", animName );
	params.Get( "Frame", frame );

	SetAnimationState( animName, frame );
}
예제 #9
0
//---------------------------------------
void MageGame::SetCameraBoundsEvent( Dictionary& params )
{
	RectI bounds;

	if ( params.Get( "Bounds", bounds ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_ERROR, "Failed to set camera bounds: missing Bounds\n" );
		return;
	}

	mCamera->SetWorldBounds( bounds );
}
예제 #10
0
//---------------------------------------
void MageGame::SpawnSpriteEvent( Dictionary& params )
{
	std::string spriteName;
	Vec2f position;

	// Get name
	if ( params.Get( "SpriteName", spriteName ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_ERROR, "Failed to spawn sprite: missing SpriteName\n" );
		return;
	}

	// Get position
	if ( params.Get( "Position", position ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_ERROR, "Failed to spawn sprite: missing Position\n" );
		return;
	}

	// Spawn sprite
	SpawnSprite( spriteName, position );
}
예제 #11
0
//---------------------------------------
void Entity::EventApplyImpulse( Dictionary& params )
{
	Entity* entity;
	Vec2f force;

	if ( params.Get( "Invoker", entity ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_WARNING, "Entity '%s' (%d) : ApplyImpulse : Bad event args for 'invoker'\n",
			mName.c_str(), mEntityId );
		return;
	}

	if ( entity != this ) return;

	if ( params.Get( "Force", force ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_WARNING, "Entity '%s' (%d) : ApplyImpulse : Bad event args for 'force'\n",
			mName.c_str(), mEntityId );
	}

	ApplyImpulse( force );
}
예제 #12
0
//---------------------------------------
void MageGame::SpawnGameObjectEvent( Dictionary& params )
{
	std::string entityName;
	Vec2f position;

	// Get name
	if ( params.Get( "ObjectName", entityName ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_ERROR, "Failed to spawn GameObject: missing ObjectName\n" );
		return;
	}

	// Get position
	if ( params.Get( "Position", position ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_ERROR, "Failed to spawn GameObject: missing Position\n" );
		return;
	}

	// Spawn entity
	GameObject* gameObject = SpawnGameObject( entityName, position );
	params.Set( "GameObject", gameObject );
}
예제 #13
0
//---------------------------------------
void MageGame::SpawnEntityEvent( Dictionary& params )
{
	std::string entityName;
	Vec2f position;

	// Get name
	if ( params.Get( "EntityName", entityName ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_ERROR, "Failed to spawn entity: missing EntityName\n" );
		return;
	}

	// Get position
	if ( params.Get( "Position", position ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_ERROR, "Failed to spawn entity: missing Position\n" );
		return;
	}

	// Spawn entity
	Entity* entity = SpawnEntity( entityName, position );
	params.Set( "Entity", entity );
}
예제 #14
0
//---------------------------------------
void Entity::EventKill( Dictionary& params )
{
	Entity* invoker;
	if ( params.Get( "Invoker", invoker ) != Dictionary::DErr_SUCCESS )
	{
		ConsolePrintf( CONSOLE_WARNING, "Entity '%s' (%d) : EventSetAnimationState : Bad event args for 'invoker'\n",
			mName.c_str(), mEntityId );
		return;
	}

	if ( invoker != this ) return;

	Kill();
}
예제 #15
0
void BrushToolInputState::OnEnter( const Dictionary& parameters )
{
	EditorState* owner = GetOwnerDerived();

	// Get the selected Tile template (if specified).
	Tile tileTemplate;
	Dictionary::DictionaryError error = parameters.Get( "tileTemplate", tileTemplate );

	if( error == Dictionary::DErr_SUCCESS )
	{
		// Set the selected Tile template.
		SetTileTemplate( tileTemplate );
	}

	// Show the tile palette.
	owner->GetTilePalette()->Show();
}
예제 #16
0
	Tweakable&	AddTweakableValue( const char* _pFilename, size_t _Counter )
	{
		// First, see if this file is in the files list
		U32		Key = DictionaryString<int>::Hash( _pFilename );
		TweakableSourceFile*	pFileEntry = g_TweakableFiles.Get( Key );
		if ( pFileEntry == NULL )
		{	// if it's not found, add to the list of tweakable files, assume it's unmodified since the program has been built 
			TweakableSourceFile&	Value = g_TweakableFiles.Add( Key );
// 			strcpy( Value.pFilename, _pFilename );
			Value.pFilename = _pFilename;
			Value.LastModificationTime = GetFileModTime( _pFilename );
		}

		// Add to the tweakables
		Key = HashKey( _pFilename, _Counter );
		return g_TweakableValues.Add( Key );
	}
예제 #17
0
파일: outline.cpp 프로젝트: chrisforbes/pdf
void NavigateToPage( HWND appHwnd, Document * doc, NMTREEVIEW * info )
{
	if (!info->itemNew.hItem)
		return;
	
	Dictionary * dict = (Dictionary *)info->itemNew.lParam;

	if (!dict)
		return;

	PObject dest = dict->Get( "Dest", doc->xrefTable );
	if (!dest)
		return;

	if (dest->Type() == ObjectType::String)
	{
		String * s = (String *)dest.get();
		dest = Object::ResolveIndirect_<Object>( NameTreeGetValue( doc, *s ), doc->xrefTable );
	}

	PArray destArray;

	if (dest->Type() == ObjectType::Dictionary)
	{
		PDictionary d = boost::shared_static_cast<Dictionary>(dest);
		//TODO: Implement link action
		//For now handle everything as GoTo (here be Raptors)
		//d->Get<Name>("S", doc->xrefTable);
		destArray = d->Get<Array>("D", doc->xrefTable);
	}
	else if (dest->Type() == ObjectType::Array)
		destArray = boost::shared_static_cast<Array>(dest);

	if (destArray)
	{
		if (destArray->elements.empty()) return;
		
		PDictionary page = Object::ResolveIndirect_<Dictionary>( destArray->elements[0], doc->xrefTable );

		SetCurrentPage( page );
	}
}
예제 #18
0
void Diagram::_FromDict(const Dictionary& WDict, wLine w)
{
    name w_in, w_out;
    WDict.Get("IN", w_in);
    w->nVer[IN] = Ver(w_in);
    WDict.Get("OUT", w_out);
    w->nVer[OUT] = Ver(w_out);
    WDict.Get("K", w->K);
    AddWHash(w->K);
    WDict.Print();
    WDict.Get("IsDelta", w->IsDelta);
    WDict.Get("IsMeasure", w->IsMeasure);
    WDict.Get("IsWWGammaW", w->IsWWGammaW);
    if (w->IsMeasure) {
        MeasureGLine = false;
        GMeasure = nullptr;
        WMeasure = w;
    }
}
예제 #19
0
파일: Map.cpp 프로젝트: hydraskillz/Mage2D
//---------------------------------------
void Map::LoadTileLayer( const XmlReader::XmlReaderIterator& itr )
{
    TileLayer* layer = New0 TileLayer;
    layer->Type = LT_TILE;

    LoadLayerBaseInfo( layer, itr );

    itr.ValidateXMLChildElemnts( "data","tile,properties" );
    XmlReader::XmlReaderIterator data = itr.NextChild( "data" );

    const char* encoding = data.GetAttributeAsCString( "encoding", 0 );
    const char* compression = data.GetAttributeAsCString( "compression", 0 );

    // Tile data is encoded
    if ( encoding )
    {
        // Base64 encoded
        if ( !strcmp( encoding, "base64" ) )
        {
            // Get encoded data
            std::string rawData = data.GetPCDataAsString();

            // Decode data
            std::vector< int > tiledata = base64_decode( rawData );

            // Tile data is compressed
            if ( compression )
            {
                if ( !strcmp( compression, "gzip" ) )
                {
                    ConsolePrintf( CONSOLE_WARNING, "Warning: gzip compression not supported yet... no data loaded\n" );
                    return;
                }
                else if ( !strcmp( compression, "zlib" ) )
                {
                    ConsolePrintf( CONSOLE_WARNING, "Warning: zlib compression not supported yet... no data loaded\n" );
                    return;
                }
                else
                {
                    ConsolePrintf( CONSOLE_WARNING, "Warning: Unknown compression: %s\n", compression );
                    return;
                }
            }

            int k = 0, size = (int) tiledata.size();
            for ( int j = 0; j < size; j += 4 )
            {
                Tile tile;

                // Get global tile id
                unsigned int gid = tiledata[ j     ]       |
                                   tiledata[ j + 1 ] << 8  |
                                   tiledata[ j + 2 ] << 16 |
                                   tiledata[ j + 3 ] << 24;

                // Read tile flags (unused)
                //bool flippedHorizontally = ( gid & TMX_FLIPPED_HORIZONTALLY_FLAG ) == 0 ? false : true;
                //bool flippedVertically   = ( gid & TMX_FLIPPED_VERTICALLY_FLAG   ) == 0 ? false : true;
                //bool flippedDiagonally   = ( gid & TMX_FLIPPED_DIAGONALLY_FLAG   ) == 0 ? false : true;

                // Clear flags
                gid &= ~( TMX_FLIPPED_HORIZONTALLY_FLAG |
                          TMX_FLIPPED_VERTICALLY_FLAG   |
                          TMX_FLIPPED_DIAGONALLY_FLAG );

                // Figure out which tileset this tile belongs to
                if ( gid > 0 )
                {
                    int tilesetIndex = 0;
                    for ( int i = (int) mTileSets.size() - 1; i >= 0; --i )
                    {
                        TileSet* tileset = mTileSets[i];

                        if ( tileset->FirstGid <= gid )
                        {
                            tilesetIndex = tileset->TileSetIndex;
                            // Fix gid to be local to this tileset
                            gid = gid - tileset->FirstGid;
                            break;
                        }
                    }

                    const int numXTiles = mTileSets[ tilesetIndex ]->TilesetSurface ? mTileSets[ tilesetIndex ]->TilesetSurface->w / mTileWidth : 1;

                    tile.TileId = gid;
                    tile.TileIndex = k++;
                    tile.TileSetIndex = tilesetIndex;
                    tile.TilePositionX = ( gid % numXTiles ) * mTileWidth;
                    tile.TilePositionY = ( gid / numXTiles ) * mTileHeight;

                    auto tileProps = mTileSets[ tilesetIndex ]->TileProperties.find( gid );
                    if ( tileProps != mTileSets[ tilesetIndex ]->TileProperties.end() )
                    {
                        // Check for collision properties
                        std::string collisionType;
                        if ( tileProps->second.Get( "Collision", collisionType ) == Dictionary::DErr_SUCCESS )
                        {
                            if ( collisionType == "SOLID" )
                            {
                                tile.TileCollision = Tile::TC_SOLID;
                            }
                        }
                    }
                }

                layer->Tiles.push_back( tile );
            }
        }
        // CSV encoded
        else if ( !strcmp( encoding, "csv" ) )
        {
            ConsolePrintf( CONSOLE_WARNING, "Warning: CSV encoding not supported yet... no data loaded\n" );
        }
        else
        {
            ConsolePrintf( CONSOLE_WARNING, "Warning: Unknown encoding: %s\n", encoding );
        }
    }
    // Raw XML tile data
    else
    {
        ConsolePrintf( CONSOLE_WARNING, "Warning: Raw tile data not supported yet... no data loaded\n" );
    }

    XmlReader::XmlReaderIterator propItr = itr.NextChild( "properties" );
    if ( propItr.IsValid() )
    {
        Dictionary layerProperties;
        LoadProperties( layerProperties, propItr );

        // The 'Collision' property specifies a layer is to be used for collision
        std::string _dummy_;
        if ( layerProperties.Get( "Collision", _dummy_ ) == Dictionary::DErr_SUCCESS )
        {
            CollisionLayerIndex = (int) mLayers.size();
        }
    }

    mLayers.push_back( layer );
}
예제 #20
0
	static bool Contains(const Dictionary& dict, const char* key)
	{
		return dict.Get(key) != NULL;
	}
예제 #21
0
void SimulationRun(string RunParameterNames[])
{
	ifstream TraceFile;
	bool RunValid=true;
	if(PrimaryProtocol==NULL)
	{
		cerr<<"RUN ERROR: No protocol specified!"<<endl;
		RunValid=false;
	}
	if(TraceFileName=="")
	{
		cerr<<"RUN ERROR: No trace file specified!"<<endl;
		RunValid=false;
	}
	if(RunValid)
	{
		TraceFile.open(TraceFileName.c_str());
		if(!TraceFile.is_open())
		{
			cerr<<"RUN ERROR: Cannot open trace file!"<<endl;
			RunValid=false;
		}
		else if(TraceFile.bad()||TraceFile.fail())
		{
			cerr<<"RUN ERROR: Stream was corrupted!"<<endl;
			RunValid=false;
		}
	}
	if(!RunValid){return;}//Immediately break and cancel the run if there are execution errors.
	ResetGlobalVariables();
	int VehicleNum,BeginTime,EndTime;
	float x,y;
	int NextSimulationTime;
	int VehicleNumMask=1;//The modulo of the vehicle num and this value determines whether a vehicle is omitted to get a different set of vehicles in the simulation.
	int VehicleNumMaskOffset=0;
	bool MaskExists=CheckRunVariableExists("VehicleNumMask");
	bool OffsetExists=CheckRunVariableExists("VehicleNumMaskOffset");
	if(MaskExists!=OffsetExists){cerr<<"ERROR: Must specify both VehicleNumMask and VehicleNumMaskOffset for this input to be effective!"<<endl;}
	else if(MaskExists)
	{
		VehicleNumMask=GetRunVariableInteger("VehicleNumMask");
		VehicleNumMaskOffset=GetRunVariableInteger("VehicleNumMaskOffset");
	}
	while (TraceFile >> NextSimulationTime >> VehicleNum >> x >> y >> BeginTime >> EndTime)// loop through all input
	{
		TimeMax=max(NextSimulationTime+1,TimeMax);
		if((--VehicleNum)%VehicleNumMask==VehicleNumMaskOffset)
		{
			VehicleNum/=VehicleNumMask;
			VehicleMax=max(VehicleNum+1,VehicleMax);
			for(int i=Vehicles.Count();i<VehicleMax;i++){Vehicles.PushObj(new Vehicle("OBU#"+to_string((long long int)i)));}
			Vehicle* CurrentVehicle=Vehicles[VehicleNum];
			if(CurrentVehicle->v_begin_t==-1)
			{
				CurrentVehicle->v_begin_t=BeginTime;
				CurrentVehicle->v_begin_x=x;
				CurrentVehicle->v_begin_x=y;
				CurrentVehicle->v_end_t=EndTime;
			}
		}
	}
	OutputVariables.Set("VehicleMax",to_string((long long int)VehicleMax));
	OutputVariables.Set("TimeMax",to_string((long long int)TimeMax));
	OutputVariables.Set("TraceFile",TraceFileName);
	OutputVariables.Set("ProtocolName",ProtocolName);
	
	TraceFile.clear();
	TraceFile.seekg(0, TraceFile.beg);  // reposition to beginning of input file
	if(TraceFile.bad()||TraceFile.fail())
	{
		cerr<<"RUN ERROR: Could not reset stream!"<<endl;
		RunValid=false;
	}
	
	int PeakAnonymitySetSize=0;//Used to calculate one of our metrics later.
	float PeakAnonymityDistance=0;
	if(CheckRunVariableExists("GlobalMessageLimit")){NetworkObject::GlobalMessageLimit=GetRunVariableInteger("GlobalMessageLimit");}
	SetGlobalVehicleMaxMessagePerTick(CheckRunVariableExists("VehicleMessageLimit")?GetRunVariableInteger("VehicleMessageLimit"):0);
	time_t SimulationBeginTime=time(NULL);
	RunValid=RunValid&&PrimaryProtocol->SimulationBegin();
	bool TraceFileEOF=false;
	while(!TraceFileEOF)
	{
		TraceFile>>NextSimulationTime>>VehicleNum>>x>>y>>BeginTime>>EndTime;
		TraceFileEOF=TraceFile.eof();
		if(!TraceFileEOF&&(TraceFile.bad()||TraceFile.fail()))
		{
			cerr<<"RUN ERROR: Stream became corrupted during simulation!"<<endl;
			RunValid=false;
			break;
		}
		if(SimulationTime==-1){SimulationTime=NextSimulationTime;}//This prevents a logic error that causes a simulation tick before the first batch of tracefile data has been processed.
		if(TraceFileEOF||SimulationTime!=NextSimulationTime)
		{
			RunValid=RunValid&&PrimaryProtocol->SimulationTick();
			if(!RunValid){break;}//This short-circuits the execution if a critical error as occurred.
			//This loop adds to the average counters in each vehicle.
			//Average counters are processed after the simulation to get various anonymity statistics.
			//As such, these values are not menaingful until they have been finalized later.
			for(int i=0;i<VehicleMax;i++)
			{
				Vehicle* CurrentVehicle=Vehicles[i];
				if(!CurrentVehicle->CurrentlyWithinSimulation()){continue;}
				if(CurrentVehicle->AssignedSet!=NULL)
				{
					AnonymitySet* CurrentSet=CurrentVehicle->AssignedSet;
					int SetSize=CurrentSet->Count();
					CurrentVehicle->AverageAnonymitySetSizeCounter+=SetSize;
					PeakAnonymitySetSize=max(PeakAnonymitySetSize,SetSize);
					ArrayList<Vehicle*>* VehiclesInSet=&(CurrentSet->AnonymousVehicles);
					float SetDistance=0.0;
					for(int io=0;io<VehiclesInSet->Count();io++)
					{
						Vehicle* OtherVehicle=(*VehiclesInSet)[io];
						if(CurrentVehicle==OtherVehicle){continue;}
						float XDist=CurrentVehicle->x-OtherVehicle->x;
						float YDist=CurrentVehicle->y-OtherVehicle->y;
						float Dist=sqrt(XDist*XDist+YDist*YDist);
						SetDistance+=Dist;
						PeakAnonymityDistance=max(PeakAnonymityDistance,Dist);
					}
					CurrentVehicle->AverageAnonymityDistanceCounter+=SetDistance/SetSize;
				}
				else{CurrentVehicle->AverageAnonymitySetSizeCounter++;}
			}
			for(int i=0;i<VehicleMax;i++)
			{
				Vehicle* CurrentVehicle=Vehicles[i];
				if(SimulationTime==CurrentVehicle->v_end_t)
				{
					CurrentVehicle->v_end_x=CurrentVehicle->x;
					CurrentVehicle->v_end_y=CurrentVehicle->y;
					CurrentVehicle->v_terminated=SimulationTime;
					//We set ending data AFTER the protocol text so the set isn't prematurely decremented.
					if(CurrentVehicle->AssignedSet!=NULL){CurrentVehicle->AssignedSet->RemoveVehicle(CurrentVehicle);}
				}
			}
			if(TraceFileEOF){break;}
			SimulationTime=NextSimulationTime;
		}
		if((--VehicleNum)%VehicleNumMask==VehicleNumMaskOffset)
		{
			VehicleNum=VehicleNum/VehicleNumMask;
			Vehicle* CurrentVehicle=Vehicles[VehicleNum];//We decrement VehicleNum because trace files base their lists with 1 as the first index.
			CurrentVehicle->x=x;
			CurrentVehicle->y=y;
		}
	}
	if(RunValid)
	{
		PrimaryProtocol->SimulationEnd();
		time_t SimulationRunTime=time(NULL)-SimulationBeginTime;
		OutputVariables.Set("RunTime",to_string(((long double)SimulationRunTime)/60.0));
		
		//This loop adds inputs as outputs, so the resulting printed line can also reference parameters used in the run.
		for(int i=0;i<RunVariables.Count();i++){OutputVariables.Set(RunVariables.GetKey(i),RunVariables.Get(i));}
		
		//This loop calculates various averages.
		int AnonymousVehicleCount=0;
		int AverageAnonymitySamples=0;
		float AverageAnonymitySetSize=0.0;
		float AverageAnonymityDistance=0.0;
		float AverageAnonymityTime=0.0;
		float PeakAnonymityTime=0.0;
		for(int i=0;i<Vehicles.Count();i++)
		{
			Vehicle* CurrentVehicle=Vehicles[i];
			if(CurrentVehicle->v_terminated==-1)
			{
				cerr<<"TERMINATE ERROR: Vehicle#"<<i<<" was supposed to terminate at "<<CurrentVehicle->v_end_t<<"/"<<SimulationTime<<endl;
				CurrentVehicle->v_terminated=CurrentVehicle->v_end_t;
			}
			AverageAnonymitySamples+=(CurrentVehicle->v_terminated-CurrentVehicle->v_begin_t)+1;
			AverageAnonymitySetSize+=CurrentVehicle->AverageAnonymitySetSizeCounter;
			AverageAnonymityDistance+=CurrentVehicle->AverageAnonymityDistanceCounter;
			if(CurrentVehicle->v_k_assign_t!=-1)
			{
				AnonymousVehicleCount++;
				float AnonTime=CurrentVehicle->v_terminated-CurrentVehicle->v_k_silent_t;
				AverageAnonymityTime+=AnonTime;
				PeakAnonymityTime=max(PeakAnonymityTime,AnonTime);
			}
		}
		if(AnonymousVehicleCount>0){AverageAnonymityTime/=AnonymousVehicleCount;}
		if(AverageAnonymitySamples==0)
		{
			AverageAnonymitySetSize=0.0f;
			AverageAnonymityDistance=0.0f;
		}
		else
		{
			AverageAnonymitySetSize/=AverageAnonymitySamples;
			AverageAnonymityDistance/=AverageAnonymitySamples;
		}
		OutputVariables.Set("AverageAnonymitySetSize",to_string((long double)AverageAnonymitySetSize));
		OutputVariables.Set("PeakAnonymitySetSize",to_string((long long int)PeakAnonymitySetSize));
		OutputVariables.Set("AverageAnonymityDistance",to_string((long double)AverageAnonymityDistance));
		OutputVariables.Set("PeakAnonymityDistance",to_string((long double)PeakAnonymityDistance));
		OutputVariables.Set("AverageAnonymityTime",to_string((long double)AverageAnonymityTime));
		OutputVariables.Set("PeakAnonymityTime",to_string((long double)PeakAnonymityTime));
		OutputVariables.Set("AnonymousVehicleCount",to_string((long long int)AnonymousVehicleCount));
		OutputVariables.Set("TotalAnonymitySets",to_string((long long int)AnonymitySets.Count()));
		
		//This loop calculates the most congested networked unit.
		int CongestionCount=0;
		NetworkObject* CongestedUnit=NULL;
		for(int i=0;i<NetworkObjects.Count();i++)
		{
			NetworkObject* CurrentCounter=NetworkObjects[i];
			int MaxPackets=CurrentCounter->NetworkMessages.GetMostPacketsTransmitted();
			if(MaxPackets>CongestionCount)
			{
				CongestedUnit=CurrentCounter;
				CongestionCount=MaxPackets;
			}
		}
		if(CongestedUnit==NULL){OutputVariables.Set("PeakTrafficUnit","None");}
		else{OutputVariables.Set("PeakTrafficUnit",CongestedUnit->Title);}
		OutputVariables.Set("PeakTrafficAmount",to_string((long long int)CongestionCount));
		
		//This loop adds the traffic counters to the list of OutputVariables.
		for(int i=0;i<=TOTAL_TRAFFIC_TYPES;i++){OutputVariables.Set(string("Packet Count: ")+GetEnumName((TrafficType)i),to_string((long long int)GlobalTraffic[i]));}
		OutputVariables.Set(string("Packet Count: Overhead"),to_string((long long int)GlobalTraffic.Overhead()));
		OutputVariables.Set(string("Packet Count: Overhead Ratio"),to_string((long double)GlobalTraffic.OverheadRatio()));
		OutputVariables.Set(string("Packet Count: Successful"),to_string((long long int)GlobalTraffic.TotalTransmitted()));
		OutputVariables.Set(string("Packet Count: Lost"),to_string((long long int)GlobalTraffic.TotalLost()));
		OutputVariables.Set(string("PacketLoss"),to_string((long double)GlobalTraffic.PacketLoss()));
		OutputVariables.Set(string("Throughput"),to_string((long double)GlobalTraffic.TotalTransmitted()/TimeMax));
		
		//OUTPUT
		if(LegacyOutput)
		{
			cout<<"RUN:";
			for(int i=0;i<MAX_PARAMETERS_PER_LINE&&RunParameterNames[i].length()>0;i++)
			{
				if(i>0){cout<<",";}
				cout<<RunParameterNames[i]<<"="<<setw(3)<<RunVariables.Get(RunParameterNames[i]);
			}
			cout<<": ";
			cout<<fixed<<
				"K="<<setw(5)<<setprecision(2)<<AverageAnonymitySetSize<<"("<<AnonymitySets.Count()<<"), "<<
				"D="<<setw(6)<<setprecision(2)<<AverageAnonymityDistance<<", "<<
				"T="<<setw(5)<<setprecision(2)<<AverageAnonymityTime<<", "<<
				"Anonymous="<<setw(4)<<AnonymousVehicleCount<<"/"<<setw(4)<<VehicleMax;
			for(int i=0;i<=TOTAL_TRAFFIC_TYPES;i++){cout<<", "<<GetEnumName((TrafficType)i)<<":"<<GlobalTraffic[i];}
			if(CongestedUnit!=NULL){cout<<", Congested: "<<CongestedUnit->Title<<"("<<CongestionCount<<")";}
			cout<<endl;
		}
		else if(VerboseOutput)
		{
			for(int i=0;i<OutputVariables.Count();i++)
			{
				if(i!=0){cout<<", ";}
				cout<<OutputVariables.GetKey(i)<<"="<<OutputVariables.Get(i);
			}
			cout<<endl;
		}
		else
		{
			//TODO: Get the output to interpret different variable types.
			int FormatNeedle=0;//This advances through the format string as we process each section.
			while(FormatNeedle<OutputFormat->size())
			{
				//These first few lines find the next special character, or the end of the string, and OutputVariables any part of the string which was passed over.
				size_t FoundIndex=OutputFormat->find(OUTPUT_FORMAT_DELIMITER,FormatNeedle);
				if(FoundIndex==string::npos){FoundIndex=OutputFormat->size();}
				cout<<OutputFormat->substr(FormatNeedle,FoundIndex-FormatNeedle);
				FormatNeedle=FoundIndex+1;
				//If the end of the string was not reached, we then try to parse the next block of characters, which are special notation.
				if(FoundIndex<OutputFormat->size())
				{
					FoundIndex=OutputFormat->find(OUTPUT_FORMAT_DELIMITER,FormatNeedle);
					if(FoundIndex==string::npos)
					{
						cerr<<"ERROR: Misformatted Output String: No Closing '"<<OUTPUT_FORMAT_DELIMITER<<"'!"<<endl;
						break;
					}
					string FormatSpecifierArguments("s");
					size_t FoundSubIndex=OutputFormat->find(OUTPUT_FORMAT_SUB_DELIMITER,FormatNeedle);
					if(FoundSubIndex!=string::npos)
					{
						FormatSpecifierArguments=OutputFormat->substr(FormatNeedle,FoundSubIndex-FormatNeedle);
						FormatNeedle=FoundSubIndex+1;
					}
					string OutputValue("Unspecified");
					string VariableName=OutputFormat->substr(FormatNeedle,FoundIndex-FormatNeedle);
					if(OutputVariables.HasKey(VariableName)){OutputValue=OutputVariables.Get(VariableName);}
					string FormatSpecifier("%");
					FormatSpecifier=FormatSpecifier+FormatSpecifierArguments;
					char VariableTypeSpecifier=FormatSpecifier.at(FormatSpecifier.size()-1);
					switch(VariableTypeSpecifier)
					{
					case 'd': case 'i': case 'u':
						printf(FormatSpecifier.c_str(),atoi(OutputValue.c_str()));
						break;
					case 'f': case 'F':
						printf(FormatSpecifier.c_str(),atof(OutputValue.c_str()));
						break;
					default:
						printf(FormatSpecifier.c_str(),OutputValue.c_str());
						break;
					}
					FormatNeedle=FoundIndex+1;
				}
			}
			cout<<endl<<flush;//We have to use this operator to push a newline to cout, or the Cloud9 interface will cache it in a strange way.
		}
	}
	//CLEANUP
	fflush(NULL);
	TraceFile.close();
	while(AnonymitySets.Count()>0){delete AnonymitySets.PopObj();}
	while(Vehicles.Count()>0){delete Vehicles.PopObj();}
}
예제 #22
0
	Tweakable*	LookupTweakValue( const char* _pFileName, size_t _Counter )
	{
		U32	Hash = HashKey( _pFileName, _Counter );
		return g_TweakableValues.Get( Hash );
	}
예제 #23
0
string GetRunVariableString(string Key){return RunVariables.Get(Key);}