Example #1
0
	void Game::CreateAsteroid(Asteroids::Asteroid::AsteroidSize::Size size, int amount, float x, float y)
	{
		for (int i = 0; i < amount; ++i)
		{
			Asteroids::Asteroid* pAsteroid = new Asteroids::Asteroid(size);
			m_entities.push_back(pAsteroid);
			m_asteroids.push_back(pAsteroid);

			if (x == 0 && y == 0)
			{
				const int sideAxis = rand() & 1;
				const float sideDir = (rand() & 1) ? 1.0f : -1.0f;

				const int otherSideAxis = (sideAxis + 1) & 1;

				float point[2];
				point[sideAxis] = sideDir * m_dimensions[sideAxis] * 0.5f;
				point[otherSideAxis] = randInRange(m_dimensions[otherSideAxis] * -0.5f, m_dimensions[otherSideAxis] * 0.5f);

				pAsteroid->Teleport(point[0], point[1]);
			}
			else
			{
				pAsteroid->Teleport(x, y);
			}

			// Applying impulse to the asteroid
			//
			float x = randInRange(-150.0f, 150.0f);
			float y = randInRange(-150.0f, 150.0f);

			pAsteroid->ApplyImpulse(Engine::Vector2(x, y));
		}
	}
bool ParticleEmitterPressure::stepEmissionSite(
	SiteData& siteData,
	ParticleData& spawnData,
	PxU32& spawnNum, 
	const PxU32 spawnMax,
	const PxVec3 &sitePos, 
	const PxVec3 &siteVel,
	const PxReal dt)
{
	PxReal maxDistanceMoved = 5.0f * mSpacingZ;	// don't generate long particle beams

	/**
	 * Find displacement vector of the particle's motion this frame
	 * this is not necessarily v*stepSize because a collision might have occured
	 */
	PxVec3 displacement = siteData.position - sitePos;
	PxVec3 normal = displacement;
	PxReal distanceMoved = normal.normalize();

	if (distanceMoved > maxDistanceMoved)
		distanceMoved = maxDistanceMoved;
	
	/**
	 * Place particles along line between emission point and new position
	 * starting backwards from the new position
	 * spacing between the particles is the rest spacing of the fluid 
	 */
	PxReal lastPlaced = 0.0f;
	while((lastPlaced + mSpacingZ) <= distanceMoved)
	{
		PxVec3 pos = sitePos + normal * (distanceMoved - (lastPlaced + mSpacingZ));

		PxVec3 posNoise;
		posNoise.x = randInRange(-mRandomPos.x, mRandomPos.x);
		posNoise.y = randInRange(-mRandomPos.y, mRandomPos.y);		
		
		pos += mAxisX*posNoise.x + mAxisY*posNoise.y;

		bool isSpawned = spawnParticle(spawnData, spawnNum, spawnMax, pos, siteVel);
		if(isSpawned)
		{
			updatePredecessor(siteData, pos, siteVel);
			lastPlaced += mSpacingZ;
		}
		else
		{
			return false;
		}
	}
	return true;
}
Example #3
0
PxU32 ParticleEmitterRate::pickSparseEmissionSite(PxU32 sparseMax)
{
	PxU32 emissionSite = randInRange(mNumSites);
	PxU32 hashKey = hash(emissionSite);
	PxU32 hashIndex = hashKey % sparseMax;
	PxU32 numTrials = 0;
	while(mSites[hashIndex] != 0xffffffff && numTrials < PARTICLE_EMITTER_NUM_HASH_TRIALS)
	{
		emissionSite = randInRange(mNumSites);
		hashKey = hash(emissionSite);
		hashIndex = hashKey % sparseMax;
		numTrials++;
	}
	//allow sites to be used multiple times if mSites[hashIndex] == 0xffffffff
	return mSites[hashIndex] = emissionSite;
}
/************************************************************************
 * int room_index	Identifies the room to add connection(s) to.
 * char* rooms[]	Array of room names, each to correspond to a file.
 * int connections	Total number of connections the room 
 * 			identified by room_index should have.
 ***********************************************************************/
void initRoom(int room_index, char* rooms[], int connections, char* directory ) {
	char *room_name = rooms[room_index];
	FILE *file_p = NULL;
	// need to open in directory, so craft the string here
	char room_dir[100] = "";
	strcat_safe( room_dir, 100, directory );
	strcat_safe( room_dir, 100, "/" );
	strcat_safe( room_dir, 100, rooms[room_index] );

	file_p = fopen( room_dir, "a+" );
	// Check for successful file opening.
	if ( ! file_p ) {
		printf( "Error opening file in function initRoom!\n" );
		exit( 1 );
	}

	int connections_in_file = countConnections( file_p );
	int connections_to_make = connections - connections_in_file;

	while ( connections_to_make > 0 ) {
		int rand_index = randInRange( 0, 6 );
		if ( makeConnection( room_index, rand_index, rooms, directory, file_p ) ) {
			connections_to_make--;
		}
	}

	fclose(file_p);
}
/**************************************************************
 * Returns 0 on success and -1 if not enough rooms are provided.
 * ALL_ROOMS_SIZE must be the size of allRooms array.
 * Assumes each name in allRooms array is unique.
 *************************************************************/
int makeRooms(char* allRooms[], int ALL_ROOMS_SIZE, char* directory, 
			  char* chosenRooms[], int CHOSEN_ROOMS_SIZE ) {
	if (ALL_ROOMS_SIZE < CHOSEN_ROOMS_SIZE) {
		return -1;
	}
	
	chooseRooms( allRooms, ALL_ROOMS_SIZE, chosenRooms, CHOSEN_ROOMS_SIZE );
	// chosenRooms array is now filled with unique room names
	
	// add the first line to all the files
	makeRoomFiles( chosenRooms, directory ); 
	
	// add connections to all the files
	int connections;
	int MIN_CONNECTIONS = 3;
	int MAX_CONNECTIONS = 6;
	int i;
	for ( i = 0; i < CHOSEN_ROOMS_SIZE; ++i ) {
		connections = randInRange(MIN_CONNECTIONS, MAX_CONNECTIONS);
		initRoom(i, chosenRooms, connections, directory);
	}

	// add the last line to all the files
	addRoomTypes( chosenRooms, directory ); 
	
	return 0;	
}
Example #6
0
/**
 * Write a random sequence of len characters to target
 */
void randomString( char *target, size_t len, const char *alphabet )
{
  size_t asize = strlen( alphabet );
  for ( size_t i = 0; i < len-1; i++ )
    *target++ = alphabet[randInRange(0,asize-1)];
  *target = 0;
}
Example #7
0
void Ball::reset(float norm) {
  stop();

  // Throw the ball in a random direction between -45 and 45 degrees.
  auto angle = randInRange(static_cast<float>(-M_PI_4), static_cast<float>(M_PI_4));
  auto velocity = Vect(norm, 0).rotateByAngle(Point::ZERO, angle);
  getPhysicsBody()->setVelocity(velocity);
}
/**********************************************************************
 * Assigns a subset of allRooms to usedRooms.
 * Rooms are not assigned if allRooms size is less than usedRooms size.
 *********************************************************************/
void chooseRooms( char* allRooms[], int ALL_ROOMS_SIZE, char* usedRooms[], int USED_ROOMS_SIZE ) {
	if ( ALL_ROOMS_SIZE < USED_ROOMS_SIZE ) {
		printf( "in chooseRooms: ALL_ROOMS_SIZE must be at least 7\n" );
		exit(1);
	}

	char *random_room = allRooms[randInRange(0, USED_ROOMS_SIZE - 1)];
	int count = 0;
	char *chosen_room = NULL;
	for ( count; count < USED_ROOMS_SIZE; ++count ) {
		while (isInArray(random_room, usedRooms, USED_ROOMS_SIZE - 1)) {
			 random_room = allRooms[randInRange(0, ALL_ROOMS_SIZE - 1)];
		}
		chosen_room = (char*)malloc( 100 * sizeof(char) );
		strcpy( chosen_room, random_room );
		usedRooms[count] = chosen_room;
	}

}
Example #9
0
void shuffle(vector<int>& vec)
{
	int len = vec.size();
	for (int i = 0; i < len - 1; i++)
	{
		int r = randInRange(i, len);
		int tmp = vec[i];
		vec[i] = vec[r];
		vec[r] = tmp;
	}
}
Example #10
0
void ParticleEmitter::computeSiteVelocity(PxVec3& siteVel, const PxVec3& sitePos)
{
	//velocity dir noise
	PxReal noiseXYAngle = randInRange(0.0f, PxTwoPi);
	PxReal noiseZAngle  = randInRange(0.0f, mRandomAngle);

	PxVec3 noiseDirVec = mAxisX * PxCos(noiseXYAngle) + mAxisY * PxSin(noiseXYAngle);
	noiseDirVec.normalize();
	noiseDirVec = mAxisZ * PxCos(noiseZAngle) + noiseDirVec * PxSin(noiseZAngle);

	siteVel = noiseDirVec * mVelocity;

	//add emitter repulsion
	if (mParticleMass > 0.0f)
	{
		mLinMomentum -= siteVel;
		mAngMomentum -= (sitePos - mBodyCenter).cross(siteVel);
	}

	if (mFrameBody)
		siteVel += mBodyLinVel + (mBodyAngVel.cross(sitePos - mBodyCenter)); 
}
Example #11
0
int eGreedySelect(double* actions){	

	auto value = std::max_element(actions, actions + possibleActions + 1);

	if (((double)rand() / ((double)(RAND_MAX)+(double)(1))) > e && *value != 0.0){
		return std::distance(actions, value );
		
	}

		explore += 1;
		//we take a random, exploratory action
		return randInRange(possibleActions);

}
Example #12
0
void ParticleEmitterRate::shuffleDenseSites()
{
	PxU32 i,j;
	PX_ASSERT(mSites.size() == mNumSites);

	for (i = 0; i < mNumSites; i++) 
	{
		j = randInRange(mNumSites);
		PX_ASSERT(j<mNumSites);

		PxU32 k = mSites[i];
		mSites[i] = mSites[j]; 
		mSites[j] = k;
	}
}
Example #13
0
int egreedy(int state){
	int maxIndex = 0;
	int a = 1;
	int randFrequency=(int)(1.0f/sarsa_epsilon);

	if(!exploring_frozen){
  		if((rand() % randFrequency == 1)) {
    		return randInRange(numActions-1);
  		}
	}

/*otherwise choose the greedy action*/
  maxIndex = 0;
  for(a = 1; a < numActions; a++){
    if(value_function[calculateArrayIndex(state,a)] > value_function[calculateArrayIndex(state,maxIndex)]) {
      maxIndex = a;
    }
  }
  return maxIndex;
}
Example #14
0
const action_t *agent_start(const observation_t *this_observation) {
	// This agent uses some policy~
	lastAction = randInRange(possibleActions);
 	currentAction.intArray[0] = lastAction;

	double* actionArray;

	if (!tableQ.count(this_observation->charArray)){
		actionArray = new double[possibleActions+1]();
		lastState = (char*)malloc(stateSize * sizeof(char));
		memcpy(lastState, this_observation->charArray, stateSize);
		tableQ.insert({ lastState, actionArray });
	}
	else{
		lastState = this_observation->charArray;
		//actionArray = &(tableQ.at(currentState));
	}

	totals += 1;
	totalReward = 0.0;
	return &currentAction;
}
Example #15
0
	ParticleState::ParticleState( PARTICLE_TYPES newType )
	{
		Vector3 randVelocity( randInRange( -1.f, 1.f ), randInRange( -1.f, 1.f ), randInRange( -1.f, 1.f ) );
		Vector3 newLocation;

		switch( newType )
		{
		case EXPLOSION:
			break;
		case  FIREWORKS:
			randVelocity.y = sign( randVelocity.y ) * lerp( FIREWORKS_MIN_Y, FIREWORKS_MAX_Y,	fabs( randVelocity.y ) );
			break;
		case FOUNTAIN:
		case DEBRIS:
			randVelocity.x = lerp( -DEBRIS_MAX_XZ,	DEBRIS_MAX_XZ,	fabs( randVelocity.x ) );
			randVelocity.y = lerp( DEBRIS_MIN_Y,	DEBRIS_MAX_Y,	fabs( randVelocity.y ) );
			randVelocity.z = lerp( -DEBRIS_MAX_XZ,	DEBRIS_MAX_XZ,	fabs( randVelocity.z ) );
			break;
		case SMOKE:
			randVelocity.x = lerp( -SMOKE_MAX_XZ,	SMOKE_MAX_XZ,	fabs( randVelocity.x ) );
			randVelocity.y = lerp( SMOKE_MIN_Y,		SMOKE_MAX_Y,	fabs( randVelocity.y ) );
			randVelocity.z = lerp( -SMOKE_MAX_XZ,	SMOKE_MAX_XZ,	fabs( randVelocity.z ) );
			break;
		case TORNADO:
			//location
			float particleHeight = randInRangeWithDistribution( 0.f, TORNADO_HEIGHT, FilterFunctionSmoothStart );
			float particleHeightRatio = RangeMapFloat( 0.f, 1.f, particleHeight / TORNADO_HEIGHT, 0.1f, 1.f, FilterFunctionSmoothStart );
			newLocation = Vector3( randInRange( -particleHeightRatio, particleHeightRatio ), particleHeight, 
				randInRange( -particleHeightRatio, particleHeightRatio ) );

			//new velocity
			Vector2 flatVelocity( newLocation.x, newLocation.z );
			flatVelocity.rotateMinus90Degrees();
			//velocity in y and z
			randVelocity.setXYZ( flatVelocity.x, randInRange( -TORNADO_VERTICAL_SPEED, TORNADO_VERTICAL_SPEED ), flatVelocity.y );

			break;
		}

		m_Vel = randVelocity;
		m_Loc = newLocation;
	}
Example #16
0
int main(int argc, const char * argv[]) {
    std::cout << "==== NEW RUN ====\n";
    if (argc < 9) {
        displayHelp();
        return 0;
    } else if (1 < argc) {
        MAX_TIME    = atoi(argv[1]);
        LATICE_SIZE = atoi(argv[2]);
        W0          = atof(argv[3]);
        C_MIU       = atof(argv[4]);
        C_SIGMA     = atof(argv[5]);
        C_MODE      = atof(argv[6]);
        VERBOSE     = atoi(argv[7]);
        AVERAGES    = atoi(argv[8]);
    } else {
        LATICE_SIZE = 100;
        W0 = 0.1;
        C_MODE = DISTRIBUTION_GAUSS;
        C_MIU = 0.5;
        C_SIGMA = 0.1;
        MAX_TIME = 1000000;
        AVERAGES = 10;
        VERBOSE = false;
    }
    std::ofstream outputFile( argv[9] , std::ios::out | std::ios::app );
    std::cout << "CHECKING FILE\n";
    std::cout << "Writing to: '" << argv[9] << "' \n";
    if (!outputFile) {
        std::cout << argv[9] << "\n";
        printf("ERR");
        outputFile.close();
        return 1;
    }
    
    std::cout << "FILE OK\n";
    
    gsl_rng_env_setup();

    T = gsl_rng_mt19937;
    r = gsl_rng_alloc (T);
    long seed = time (NULL) * getpid();
    gsl_rng_set(r, seed);

    begin = clock();

    std::cout << "MT OK\n";
    
    short * LATICE           = (short *)malloc(LATICE_SIZE*sizeof(short));
    short * NEXT_STEP_LATICE = (short *)malloc(LATICE_SIZE*sizeof(short));

    std::cout << "INIT SIMULATION\n";

    for (int a = 1; a <= AVERAGES; a++) {
        std::cout << "RESET MCS: " << "\n";
        updateMonteCarloSteps(true);
        
        std::cout << "AVERAGE: " << a << "\n";
        initAntiferromagnet(LATICE);
        double start_rho = bondDensity(LATICE);
        double rho=0, sum_rho=0;
        double sum_c = 0;
        int magnetization = 0;
        
        for (int t = 1; t <= MAX_TIME; t++) {
            if (VERBOSE) {
                arrPrint(LATICE);printf("\n");
            }
            rho = bondDensity(LATICE);

            if (rho == 0.0 || t == MAX_TIME) {
                end = clock();
                time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
                outputFile << " " << t << " ";
                outputFile << " " << monte_carlo_steps << " ";
                outputFile << " " << matnetization(LATICE) << " ";
                outputFile << " " << rho << "\n";
                std::cout << "cputime:"   << time_spent << "\n";
                break;
            }

            double C = distribution(C_MIU, C_SIGMA, C_MODE);
            sum_c += C;

            int first_i = randInRange(0, LATICE_SIZE);
            int last_i = first_i + (C * LATICE_SIZE);

            for (int i = 0; i < LATICE_SIZE; i++) {

                if (first_i <= i && i <= last_i) {
                    int left  = (i-1) % LATICE_SIZE;
                    int right = (i+1) % LATICE_SIZE;

                    if ( LATICE[left] == LATICE[right] ) {
                        NEXT_STEP_LATICE[i] = LATICE[left];
                        updateMonteCarloSteps();
                    } else if ( W0 > randomUniform() ) {
                        NEXT_STEP_LATICE[i] = swaped(LATICE[i]);
                        updateMonteCarloSteps();
                    }
                } else {
                    NEXT_STEP_LATICE[i] = LATICE[i];
                }

            }

            std::swap(LATICE, NEXT_STEP_LATICE);
        }
    
    }
    gsl_rng_free (r);
    free(LATICE);
    free(NEXT_STEP_LATICE);

    return 0;
}
Example #17
0
double distributeUniform(double miu, double sigma) {
    return randInRange(std::max(miu-sigma, 0.0), std::min(miu-sigma, 1.0));
}
void ParticleEmitterPressure::stepInternal(ParticleData& particles, PxReal dt, const PxVec3& externalAcceleration, PxReal maxParticleVelocity)
{
	PX_ASSERT(mNumX > 0 && mNumY > 0);
	
	mSimulationAcceleration = externalAcceleration;
	mSimulationMaxVelocity = maxParticleVelocity;
	
	PxU32 numEmittedParticles = 0;

	PxU32 maxParticlesPerStep = (PxU32)physx::shdfnd::floor(mMaxRate*dt);
	PxU32 maxParticles = PxMin(particles.maxParticles - particles.numParticles, maxParticlesPerStep);

	PxU32 siteNr = 0;	
	for(PxU32 y = 0; y != mNumY; y++)
	{
		PxReal offset = 0.0f;
		if (y%2) offset = mSpacingX * 0.5f;

		for(PxU32 x = 0; x != mNumX; x++)
		{
			if (isOutsideShape(x,y,offset))
				continue;

			SiteData& siteData = mSites[siteNr];

			//position noise
			PxVec3 posNoise;
			posNoise.x = randInRange(-mRandomPos.x, mRandomPos.x);
			posNoise.y = randInRange(-mRandomPos.y, mRandomPos.y);
			
			//special code for Z noise 
			if (!siteData.predecessor) 
				siteData.noiseZ = randInRange(-mRandomPos.z, mRandomPos.z);
			else
			{
				PxReal noiseZOffset = PxMin(mMaxZNoiseOffset, mRandomPos.z);
				siteData.noiseZ += randInRange(-noiseZOffset, noiseZOffset);
				siteData.noiseZ = PxClamp(siteData.noiseZ, mRandomPos.z, -mRandomPos.z);
			}

			posNoise.z = siteData.noiseZ;

			//set position
			PxVec3 sitePos = mBasePos + mAxisX*(offset+mSpacingX*x) + mAxisY*(mSpacingY*y) + mAxisZ*siteData.noiseZ;
			PxVec3 particlePos = sitePos + mAxisX*posNoise.x + mAxisY*posNoise.y;

			PxVec3 siteVel;
			computeSiteVelocity(siteVel, particlePos);

			if (siteData.predecessor)
			{
				predictPredecessorPos(siteData, dt);
			}
			else			{
				bool isSpawned = spawnParticle(particles, numEmittedParticles, maxParticles, particlePos, siteVel);
				if(isSpawned)
				{
					updatePredecessor(siteData, particlePos, siteVel);
				}
				else
				{
					siteData.predecessor = false;
					return;
				}
			}
			
			bool allSpawned = stepEmissionSite(siteData, particles, numEmittedParticles, maxParticles, sitePos, siteVel, dt);
			if(!allSpawned)
				return;

			siteNr++;
		}
	}
}
Example #19
0
void Page_LuaTest::update(const double dt)
{
	Page::update(dt);
}

void Page_LuaTest::resolved()
{
	Page::resolved();
}

bool Page_LuaTest::eventHandler(const Event& event ATTR_UNUSED )
{
//	reload();
	{
		float x = randInRange(0, kernel.getScreenWidth());
		float y = randInRange(0, kernel.getScreenHeight());
		float distance = pow(image1_->transform().getX()-x, 2) + pow(image1_->transform().getY()-y, 2);
		image1_->tweener().moveTo(distance / 100000.0f, x, y, boost::bind(&Page_LuaTest::here, this));
	}

	{
		float x = randInRange(1, 5);
		float y = randInRange(1, 5);
		float distance = pow(image1_->transform().getX()-x, 2) + pow(image1_->transform().getY()-y, 2);
		image1_->tweener().scaleTo(distance / 100000.0f, x, y, boost::bind(&Page_LuaTest::here, this));
	}

	return true;
}
Example #20
0
void ParticleEmitterRate::stepInternal(ParticleData& particles, PxReal dt, const PxVec3& externalAcceleration, PxReal maxParticleVelocity)
{
	PX_ASSERT(mNumX > 0 && mNumY > 0);
	PxU32 numEmittedParticles = 0;

	//figure out how many particle have to be emitted with the given rate.
	mParticlesToEmit += mRate*dt;
	PxU32 numEmit = (PxU32)(mParticlesToEmit);
	if(numEmit == 0)
		return;
	
	PxU32 numLayers = (PxU32)(numEmit / (mNumX * mNumY)) + 1;
	PxReal layerDistance = dt * mVelocity / numLayers;

	PxU32 sparseMax = 0;

	//either shuffle or draw without repeat (approximation)
	bool denseEmission = (PxU32(PARTICLE_EMITTER_SPARSE_FACTOR*numEmit) > mNumSites);
	if(denseEmission)
	{
		initDenseSites();
	}
	else
	{
		sparseMax = PARTICLE_EMITTER_SPARSE_FACTOR*numEmit;
		mSites.resize(sparseMax);
	}

	// generate particles
	PxU32 l = 0;
	while(numEmit > 0)
	{
		PxVec3 layerVec = mAxisZ * (layerDistance * (PxReal)l);
		l++;

		if(denseEmission)
			shuffleDenseSites();
		else
			initSparseSiteHash(numEmit, sparseMax);

		for (PxU32 i = 0; i < mNumSites && numEmit > 0; i++)
		{
			PxU32 emissionSite;
			if (denseEmission)
				emissionSite = mSites[i];
			else
				emissionSite = pickSparseEmissionSite(sparseMax);

			PxU32 x = emissionSite / mNumY;
			PxU32 y = emissionSite % mNumY;

			PxReal offset = 0.0f;
			if (y%2) offset = mSpacingX * 0.5f;
				
			if (isOutsideShape(x,y,offset)) 
				continue;

			//position noise
			PxVec3 posNoise;
			posNoise.x = randInRange(-mRandomPos.x, mRandomPos.x);
			posNoise.y = randInRange(-mRandomPos.y, mRandomPos.y);	
			posNoise.z = randInRange(-mRandomPos.z, mRandomPos.z);	

			PxVec3 emissionPoint = mBasePos + layerVec + 
				mAxisX*(posNoise.x+offset+mSpacingX*x) + mAxisY*(posNoise.y+mSpacingY*y) + mAxisZ*posNoise.z;

			PxVec3 particleVelocity;
			computeSiteVelocity(particleVelocity, emissionPoint);

			bool isSpawned = spawnParticle(particles, numEmittedParticles, particles.maxParticles - particles.numParticles, emissionPoint, particleVelocity);
			if(isSpawned)
			{
				numEmit--;
				mParticlesToEmit -= 1.0f;
			}
			else
				return;
		}
	}
}