void RandomPermutationTrafficPattern::randomize(int seed) { unsigned long prev_seed = RandomIntLong( ); RandomSeed(seed); _dest.assign(_nodes, -1); for(int i = 0; i < _nodes; ++i) { int ind = RandomInt(_nodes - 1 - i); int j = 0; int cnt = 0; while((cnt < ind) || (_dest[j] != -1)) { if(_dest[j] == -1) { ++cnt; } ++j; assert(j < _nodes); } _dest[j] = i; } RandomSeed(prev_seed); }
static void _InitializeGlobals(int argc, char *argv[]) { char fileName[255]; _processArgs(argc, argv); MSetAllocFailFunction(_AllocFailed); if(gUseStartingNet) { gPriorNet = BNReadBIF(gStartingNetFile); if(gPriorNet == 0) { DebugError(1, "couldn't read net specified by -startFrom\n"); } gEs = BNGetExampleSpec(gPriorNet); } else { sprintf(fileName, "%s/%s.names", gSourceDirectory, gFileStem); gEs = ExampleSpecRead(fileName); DebugError(gEs == 0, "Unable to open the .names file"); gPriorNet = BNNewFromSpec(gEs); } gInitialParameterCount = BNGetNumParameters(gPriorNet); gBranchFactor = BNGetNumNodes(gPriorNet) * BNGetNumNodes(gPriorNet); if(gLimitBytes != -1) { gMaxBytesPerModel = gLimitBytes / BNGetNumNodes(gPriorNet); //gMaxBytesPerModel = gLimitBytes / gBranchFactor; DebugMessage(1, 2, "Limit models to %.4lf megs\n", gMaxBytesPerModel / (1024.0 * 1024.0)); } gCurrentNet = BNClone(gPriorNet); BNZeroCPTs(gCurrentNet); RandomInit(); /* seed */ if(gSeed != -1) { RandomSeed(gSeed); } else { gSeed = RandomRange(1, 30000); RandomSeed(gSeed); } DebugMessage(1, 1, "running with seed %d\n", gSeed); DebugMessage(1, 1, "allocation %ld\n", MGetTotalAllocation()); DebugMessage(1, 1, "initial parameters %ld\n", gInitialParameterCount); }
//---------------------------------------- void SingleRandom::Generate() { int loop, offset; table_.clear(); for(loop = range_min_; loop < range_max_; ++loop) { table_.push_back(loop); } int tem; RandomSeed(); for(loop = 0; loop < table_.size(); ++loop) { offset = NormalRandom(0, table_.size() - 1) + loop; //offset = (rand() % (range_max_ - 1)) + loop; if( offset >= table_.size()) offset -= table_.size(); //将数字对调 tem = table_[loop]; table_[loop] = table_[offset]; table_[offset] = tem; } }
void RandomSeedAuto(void) { EFI_TIME t; RT->GetTime(&t, 0); UINT64 a, b = ((((((UINT64) t.Second * 100 + t.Minute) * 100 + t.Hour) * 100 + t.Day) * 100 + t.Month) * 10000 + t.Year) * 300000 + t.Nanosecond; BS->GetNextMonotonicCount(&a); RandomSeed(a, b), Random(), Random(); }
void RandomPermutationTrafficPattern::randomize(int seed) { vector<long> save_x; vector<double> save_u; SaveRandomState(save_x, save_u); RandomSeed(seed); _dest.assign(_nodes, -1); for(int i = 0; i < _nodes; ++i) { int ind = RandomInt(_nodes - 1 - i); int j = 0; int cnt = 0; while((cnt < ind) || (_dest[j] != -1)) { if(_dest[j] == -1) { ++cnt; } ++j; assert(j < _nodes); } _dest[j] = i; } RestoreRandomState(save_x, save_u); }
int SharedRandomInt( const char *sharedname, int iMinVal, int iMaxVal, int additionalSeed /*=0*/ ) { Assert( CBaseEntity::GetPredictionRandomSeed() != -1 ); int seed = SeedFileLineHash( CBaseEntity::GetPredictionRandomSeed(), sharedname, additionalSeed ); RandomSeed( seed ); return RandomInt( iMinVal, iMaxVal ); }
//----------------------------------------------------------------------------- // Purpose: Accessed by SHARED_RANDOMFLOAT macro to get c/s neutral random float for prediction // Input : *filename - // line - // flMinVal - // flMaxVal - // Output : float //----------------------------------------------------------------------------- float SharedRandomFloat( const char *filename, int line, float flMinVal, float flMaxVal, int additionalSeed /*=0*/ ) { Assert( C_BaseEntity::GetPredictionRandomSeed() != -1 ); int seed = SeedFileLineHash( C_BaseEntity::GetPredictionRandomSeed(), filename, line, additionalSeed ); RandomSeed( seed ); return RandomFloat( flMinVal, flMaxVal ); }
void CryptoInitialize() { if (!crypto_initialized) { SetupOpenSSLThreadLocks(); OpenSSL_add_all_algorithms(); OpenSSL_add_all_digests(); ERR_load_crypto_strings(); RandomSeed(); crypto_initialized = true; } }
Vector SharedRandomVector( const char *sharedname, float minVal, float maxVal, int additionalSeed /*=0*/ ) { Assert( CBaseEntity::GetPredictionRandomSeed() != -1 ); int seed = SeedFileLineHash( CBaseEntity::GetPredictionRandomSeed(), sharedname, additionalSeed ); RandomSeed( seed ); // HACK: Can't call RandomVector/Angle because it uses rand() not vstlib Random*() functions! // Get a random vector. Vector random; random.x = RandomFloat( minVal, maxVal ); random.y = RandomFloat( minVal, maxVal ); random.z = RandomFloat( minVal, maxVal ); return random; }
virtual void UpdateBenchmark() { // No benchmark running? if ( m_BenchmarkState == BENCHMARKSTATE_NOT_RUNNING ) return; // Wait a certain number of ticks to start the benchmark. if ( m_BenchmarkState == BENCHMARKSTATE_START_WAIT ) { if ( (Plat_FloatTime() - m_flBenchmarkStartTime) < m_flBenchmarkStartWaitTime ) { UpdateStartWaitCounter(); return; } else { // Ok, now we're officially starting it. Msg( "Starting benchmark!\n" ); m_flLastBenchmarkCounterUpdate = m_flBenchmarkStartTime = Plat_FloatTime(); m_fl_ValidTime_BenchmarkStartTime = Benchmark_ValidTime(); m_nBenchmarkStartTick = gpGlobals->tickcount; m_nLastPhysicsObjectTick = m_nLastPhysicsForceTick = 0; m_BenchmarkState = BENCHMARKSTATE_RUNNING; StartVProfRecord(); RandomSeed( 0 ); m_RandomStream.SetSeed( 0 ); } } int nTicksRunSoFar = gpGlobals->tickcount - m_nBenchmarkStartTick; UpdateBenchmarkCounter(); // Are we finished with the benchmark? if ( nTicksRunSoFar >= sv_benchmark_numticks.GetInt() ) { EndVProfRecord(); OutputResults(); EndBenchmark(); return; } // Ok, update whatever we're doing in the benchmark. UpdatePlayerCreation(); UpdateVPhysicsObjects(); CServerBenchmarkHook::s_pBenchmarkHook->UpdateBenchmark(); }
//----------------------------------------------------------------------------- // Places Detail Objects in the level //----------------------------------------------------------------------------- void EmitDetailObjects() { // Guarantee identical random emission... srand(1); RandomSeed( 1 ); EmitDetailModels(); // Done! Now lets add the lumps (destroy previous ones) SetLumpData( ); if ( s_nDetailOverflow != 0 ) { Warning( "Error! Too many detail props on this map. %d were not emitted!\n", s_nDetailOverflow ); } }
/** Generates random numbers of specified size. If the Random Generator wasn't initiated, initiate it first, then call RandomBytes. @param[out] OutBuffer Pointer to buffer to receive random value. @param[in] Bytes Size of randome bytes to generate. @retval EFI_SUCCESS The operation perfoms successfully. @retval Otherwise The operation is failed. **/ EFI_STATUS IpSecCryptoIoGenerateRandomBytes ( OUT UINT8* OutBuffer, IN UINTN Bytes ) { if (!mInitialRandomSeed) { RandomSeed (NULL, 0); mInitialRandomSeed = TRUE; } if (RandomBytes (OutBuffer, Bytes)) { return EFI_SUCCESS; } else { return EFI_INVALID_PARAMETER; } }
void CryptoInitialize() { if (!crypto_initialized) { SetupOpenSSLThreadLocks(); OpenSSL_add_all_algorithms(); OpenSSL_add_all_digests(); ERR_load_crypto_strings(); RandomSeed(); long seed = 0; RAND_bytes((unsigned char *)&seed, sizeof(seed)); srand48(seed); crypto_initialized = true; } }
//----------------------------------------------------------------------------- // Purpose: Calculate the viewkick //----------------------------------------------------------------------------- void CWeaponAK47::AddViewKick( void ) { CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( pPlayer == NULL ) { return; } int iSeed = CBaseEntity::GetPredictionRandomSeed() & 255; RandomSeed( iSeed ); QAngle viewPunch; viewPunch.x = random->RandomFloat( 0.25f, 0.5f ); viewPunch.y = random->RandomFloat( -.6f, .6f ); viewPunch.z = 0.0f; //Add it to the view punch pPlayer->ViewPunch( viewPunch ); }
void CryptoInitialize() { static bool crypto_initialized = false; if (!crypto_initialized) { OpenSSL_add_all_algorithms(); OpenSSL_add_all_digests(); ERR_load_crypto_strings(); RandomSeed(); long seed = 0; RAND_bytes((unsigned char *)&seed, sizeof(seed)); srand48(seed); crypto_initialized = true; } }
void nospread::ApplySpread(int sequence_number, Entity *pl, Angle &angles, float factor) { Entity *w = pl->GetActiveWeapon(); int random_seed = md5_random(sequence_number) & 0x7fffffff; #if defined(CSS) || defined(CSGO) RandomSeed(random_seed + 1 & 0xff); w->UpdateAccuracyPenalty(); float random1 = RandomFloat(0.0f, pi * 2.0f); float spread1 = RandomFloat(0.0f, w->GetWeaponCone()); float random2 = RandomFloat(0.0f, pi * 2.0f); float spread2 = RandomFloat(0.0f, w->GetWeaponSpread()); float sin1, cos1, sin2, cos2; SinCos(random1, sin1, cos1); SinCos(random2, sin2, cos2); Vector spread = Vector(1.0f, (cos1 * spread1 + cos2 * spread2) * -factor, (sin1 * spread1 + sin2 * spread2) * factor); spread.Normalize(); Angle shake; VectorAngles(spread, shake); angles += shake; #endif #if defined(L4D) || defined(L4D2) static auto SharedRandomFloat = (float (*)(const char *, float, float, int))util::FindProlog(util::FindString(GetModuleHandle("client"), "SharedRandomFloat")); static int &r_random_seed = **(int **)util::FindPattern((void *)SharedRandomFloat, 0x100, ((const pattern *)"\x01\x01\x00\x00\x00\xA1")); r_random_seed = random_seed; float spread = w->GetWeaponSpread(); angles.x += SharedRandomFloat("CTerrorGun::FireBullet HorizSpread", -spread, spread, 0) * factor; angles.y += SharedRandomFloat("CTerrorGun::FireBullet VertSpread", -spread, spread, 0) * factor; #endif }
void CryptoInitialize() { static bool crypto_initialized = false; if (!crypto_initialized) { OpenSSL_add_all_algorithms(); OpenSSL_add_all_digests(); ERR_load_crypto_strings(); RandomSeed(); unsigned char s[16] = { 0 }; int seed = 0; RAND_bytes(s, 16); s[15] = '\0'; seed = ElfHash(s, CF_HASHTABLESIZE); srand48((long) seed); crypto_initialized = true; } }
void CGEPropDynamic::PickNewSkin(bool broken) { // Basically a way of making sure each entity gets a unique skin. // We multiply the different coordinates with different coefficients in order to prevent certain arrangements from generating the same seed. // aka (-2, 0, 0) is the same as (-1, -1, 0) and many more. Overlap is obviously still possible with this system too, but there are only a few // circumstances where the overlap would occour in locations near eachother. RandomSeed((int)(GetAbsOrigin().x * 100 + GetAbsOrigin().y * 10 + GetAbsOrigin().z) + GEMPRules()->GetRandomSeedOffset() + gpGlobals->curtime); int healthyskins = GetModelPtr()->numskinfamilies() - m_iBrokenSkinCount; if (broken) { m_nSkin = rand() % m_iBrokenSkinCount; m_bUsingBrokenSkin = true; } else { m_nSkin = m_iBrokenSkinCount + rand() % healthyskins; m_bUsingBrokenSkin = false; } }
//----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHL2MPMachineGun::DoMachineGunKick( CBasePlayer *pPlayer, float dampEasy, float maxVerticleKickAngle, float fireDurationTime, float slideLimitTime ) { #define KICK_MIN_X 0.2f //Degrees #define KICK_MIN_Y 0.2f //Degrees #define KICK_MIN_Z 0.1f //Degrees QAngle vecScratch; int iSeed = CBaseEntity::GetPredictionRandomSeed() & 255; //Find how far into our accuracy degradation we are float duration = ( fireDurationTime > slideLimitTime ) ? slideLimitTime : fireDurationTime; float kickPerc = duration / slideLimitTime; // do this to get a hard discontinuity, clear out anything under 10 degrees punch pPlayer->ViewPunchReset( 10 ); //Apply this to the view angles as well vecScratch.x = -( KICK_MIN_X + ( maxVerticleKickAngle * kickPerc ) ); vecScratch.y = -( KICK_MIN_Y + ( maxVerticleKickAngle * kickPerc ) ) / 3; vecScratch.z = KICK_MIN_Z + ( maxVerticleKickAngle * kickPerc ) / 8; RandomSeed( iSeed ); //Wibble left and right if ( RandomInt( -1, 1 ) >= 0 ) vecScratch.y *= -1; iSeed++; //Wobble up and down if ( RandomInt( -1, 1 ) >= 0 ) vecScratch.z *= -1; //Clip this to our desired min/max UTIL_ClipPunchAngleOffset( vecScratch, pPlayer->m_Local.m_vecPunchAngle, QAngle( 24.0f, 3.0f, 1.0f ) ); //Add it to the view punch // NOTE: 0.5 is just tuned to match the old effect before the punch became simulated pPlayer->ViewPunch( vecScratch * 0.5 ); }
void SgObjectManager::Update( SgMap *map , SgViewPort *viewport , SgInputManager* pInput ) { //if the game is paused we just draw the objects (and don't animate them) if(m_pTimer->IsPaused()) { return; } //Create a new random seed for randomness. RandomSeed(timeGetTime()); //animate each object individually (if user object we pass the input along) for(int i=0; i<m_dwMaxObjects; i++){ //if object exists if(m_ppObject[i]!=NULL){ if(i!=(m_dwUserObject-1)){ m_ppObject[i]->Animate(m_pTimer, map, NULL, this); }else{ m_ppObject[i]->Animate(m_pTimer, map, pInput, this); } } } //set the viewport to the user objects viewport->update(m_pTimer->Time()); if((m_dwUserObject>0) && (m_ppObject[m_dwUserObject-1]!=NULL) ) { viewport->force_position(m_ppObject[m_dwUserObject-1]->GetX(), m_ppObject[m_dwUserObject-1]->GetY()); } else { viewport->stop_scroll(); } //detect collisions (which will do all necessary steps if there is a collision) DetectCollisions(); Cull(); //cull old objects }
/** Validate UEFI-OpenSSL pseudorandom number generator interfaces. @retval EFI_SUCCESS Validation succeeded. @retval EFI_ABORTED Validation failed. **/ EFI_STATUS ValidateCryptPrng ( VOID ) { UINTN Index; BOOLEAN Status; Print (L" \nUEFI-OpenSSL PRNG Engine Testing:\n"); Print (L"- Random Generation..."); Status = RandomSeed (SeedString, sizeof (SeedString)); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } for (Index = 0; Index < 10; Index ++) { Status = RandomBytes (RandomBuffer, RANDOM_NUMBER_SIZE); if (!Status) { Print (L"[Fail]"); return EFI_ABORTED; } if (CompareMem (PreviousRandomBuffer, RandomBuffer, RANDOM_NUMBER_SIZE) == 0) { Print (L"[Fail]"); return EFI_ABORTED; } CopyMem (PreviousRandomBuffer, RandomBuffer, RANDOM_NUMBER_SIZE); } Print (L"[Pass]\n"); return EFI_SUCCESS; }
void PlayTest_Tune(unsigned int rollbacks, unsigned int plays, unsigned int population_size, unsigned int tournament_size, unsigned int latency) { std::mt19937 rng(RandomSeed()); // create initial population std::vector<TuneElement> population(population_size); for(unsigned int i = 0; i < population_size; ++i) { GetDefaultHeuristicParameters(&population[i].m_parameters); population[i].m_score = 20000; // guess, should be relatively low } // simulate plays std::vector<TuneElement> history(plays); std::vector<std::future<unsigned int> > futures(latency); for(unsigned int p = 0; p < plays + latency; ++p) { std::cout << "Tune progress: " << 100 * p / (plays + latency) << "%" << std::endl; // add completed play to the population if(p >= latency) { history[p - latency].m_score = futures[p % latency].get(); population[(p - latency) % population_size] = history[p - latency]; } // tournament selection TuneElement best1, best2; GetDefaultHeuristicParameters(&best1.m_parameters); GetDefaultHeuristicParameters(&best2.m_parameters); best1.m_score = 0; best2.m_score = 0; for(unsigned int t = 0; t < tournament_size; ++t) { unsigned int sel1 = rng() % population_size; if(population[sel1].m_score > best1.m_score) best1 = population[sel1]; unsigned int sel2 = rng() % population_size; if(population[sel2].m_score > best2.m_score) best2 = population[sel2]; } // create winner HeuristicParameters winner; std::cout << "Winner (" << best1.m_score << "|" << best2.m_score << "): "; for(unsigned int i = 0; i < PARAM_COUNT; ++i) { winner.m_values[i] = (best1.m_parameters.m_values[i] + best2.m_parameters.m_values[i] + (rng() & 1)) / 2; std::cout << winner.m_values[i] << " "; } std::cout << std::endl; if(p < plays) { // do some mutations for(unsigned int i = 0; i < PARAM_COUNT; ++i) { winner.m_values[i] = Mutate(winner.m_values[i], PARAMETERS_MIN[i], PARAMETERS_MAX[i], PARAMETERS_STEP[i], rng); } // start the job history[p].m_parameters = winner; futures[p % latency] = StartJob(PlayTest, winner, rollbacks, (BoardDB*) NULL, (std::mutex*) NULL); } } std::cout << "scores = array([\n\t"; for(unsigned int p = 0; p < plays; ++p) { std::cout << history[p].m_score; if(p != plays - 1) { if(p % 20 == 19) std::cout << ",\n\t"; else std::cout << ", "; } } std::cout << "])" << std::endl; // calculate population average HeuristicParameters population_average; std::cout << "Population average: "; for(unsigned int i = 0; i < PARAM_COUNT; ++i) { population_average.m_values[i] = 0; for(unsigned int p = 0; p < population_size; ++p) { population_average.m_values[i] += population[p].m_parameters.m_values[i]; } population_average.m_values[i] = (population_average.m_values[i] + population_size / 2) / population_size; std::cout << population_average.m_values[i] << " "; } std::cout << std::endl; }
static void _CreateConceptTreeHelper(DecisionTreePtr dt, int seed, long node, int level, AttributeTrackerPtr at) { int prunePercent; int i, activeCount, found, splitAttribute; // VoidListPtr kids; double thresh, min, max; RandomSeed(seed * node); /* test for prune */ prunePercent = gPrunePercent; if(level < gFirstPruneLevel) { prunePercent = 0; } if(level > gMaxLevel || RandomRange(0, 100) < prunePercent || AttributeTrackerAreAllInactive(at)) { DecisionTreeSetTypeLeaf(dt); DecisionTreeSetClass(dt, RandomRange(0, gNumClasses - 1)); return; } /* now pick split attribute */ activeCount = AttributeTrackerNumActive(at); splitAttribute = RandomRange(0, activeCount - 1); found = 0; for(i = 0 ; i < ExampleSpecGetNumAttributes(gEs) && !found; i++) { if(AttributeTrackerIsActive(at, i)) { if(splitAttribute == 0) { splitAttribute = i; found = 1; } else { splitAttribute--; } } } if(ExampleSpecIsAttributeDiscrete(gEs, splitAttribute)) { AttributeTrackerMarkInactive(at, splitAttribute); DecisionTreeSplitOnDiscreteAttribute(dt, splitAttribute); _CreateConceptTreeHelper(DecisionTreeGetChild(dt, 0), seed, node * 2, level + 1, at); _CreateConceptTreeHelper(DecisionTreeGetChild(dt, 1), seed, (node * 2) + 1, level + 1, at); AttributeTrackerMarkActive(at, splitAttribute); } else { /* must be continuous */ thresh = (double)RandomRange(_attMin[splitAttribute] * 10000, _attMax[splitAttribute] * 10000) / (double)10000; DecisionTreeSplitOnContinuousAttribute(dt, splitAttribute, thresh); max = _attMax[splitAttribute]; _attMax[splitAttribute] = thresh; if(_attMax[splitAttribute] - _attMin[splitAttribute] < 0.05) { AttributeTrackerMarkInactive(at, splitAttribute); } _CreateConceptTreeHelper(DecisionTreeGetChild(dt, 0), seed, node * 2, level + 1, at); AttributeTrackerMarkActive(at, splitAttribute); _attMax[splitAttribute] = max; min = _attMin[splitAttribute]; _attMin[splitAttribute] = thresh; if(_attMax[splitAttribute] - _attMin[splitAttribute] < 0.05) { AttributeTrackerMarkInactive(at, splitAttribute); } _CreateConceptTreeHelper(DecisionTreeGetChild(dt, 1), seed, (node * 2) + 1, level + 1, at); AttributeTrackerMarkActive(at, splitAttribute); _attMin[splitAttribute] = min; } }
int main(int argc, char *argv[]) { char fileName[255]; FILE *exampleIn, *names; ExampleSpecPtr es; ExamplePtr e; FILE *outputData; VoidAListPtr list; _processArgs(argc, argv); /* set up the random seed */ RandomInit(); if(gSeed != -1) { RandomSeed(gSeed); } /* read the spec file */ sprintf(fileName, "%s/%s.names", gSourceDirectory, gFileStem); /* TODO check that the file exists */ es = ExampleSpecRead(fileName); /* TODO check that the target directory exists */ sprintf(fileName, "%s/%s.data", gTargetDirectory, gTargetFileStem); outputData = fopen(fileName, "w"); sprintf(fileName, "%s/%s.data", gSourceDirectory, gFileStem); /* TODO check that the file exists */ exampleIn = fopen(fileName, "r"); list = VALNew(); e = ExampleRead(exampleIn, es); while(e != 0) { VALAppend(list, e); e = ExampleRead(exampleIn, es); } fclose(exampleIn); if(gMessageLevel >= 1) { printf("Done reading, begin outputting...\n"); fflush(stdout); } /* now output in random order */ while(VALLength(list)) { e = VALRemove(list, RandomRange(0, VALLength(list) - 1)); ExampleWrite(e, outputData); ExampleFree(e); } /* close the output file */ fclose(outputData); /* output the names files */ /* TODO check that the target directory exists */ sprintf(fileName, "%s/%s.names", gTargetDirectory, gTargetFileStem); names = fopen(fileName, "w"); ExampleSpecWrite(es, names); fclose(names); return 0; }
void C_TEHL2MPFireBullets::CreateEffects( void ) { CAmmoDef* pAmmoDef = GetAmmoDef(); if ( pAmmoDef == NULL ) return; C_BaseEntity *pEnt = ClientEntityList().GetEnt( m_iPlayer ); if ( pEnt ) { C_BasePlayer *pPlayer = dynamic_cast<C_BasePlayer *>(pEnt); if ( pPlayer && pPlayer->GetActiveWeapon() ) { C_BaseCombatWeapon *pWpn = dynamic_cast<C_BaseCombatWeapon *>( pPlayer->GetActiveWeapon() ); if ( pWpn ) { int iSeed = m_iSeed; CShotManipulator Manipulator( m_vecDir ); for (int iShot = 0; iShot < m_iShots; iShot++) { RandomSeed( iSeed ); // init random system with this seed // Don't run the biasing code for the player at the moment. Vector vecDir = Manipulator.ApplySpread( Vector( m_flSpread, m_flSpread, m_flSpread ) ); Vector vecEnd = m_vecOrigin + vecDir * MAX_TRACE_LENGTH; trace_t tr; CTraceFilterSkipPlayerAndViewModelOnly traceFilter; if( m_iShots > 1 && iShot % 2 ) { // Half of the shotgun pellets are hulls that make it easier to hit targets with the shotgun. UTIL_TraceHull( m_vecOrigin, vecEnd, Vector( -3, -3, -3 ), Vector( 3, 3, 3 ), MASK_SHOT, &traceFilter, &tr ); } else { UTIL_TraceLine( m_vecOrigin, vecEnd, MASK_SHOT, &traceFilter, &tr); } if ( m_bDoTracers ) { const char *pTracerName = pWpn->GetTracerType(); CEffectData data; data.m_vStart = tr.startpos; data.m_vOrigin = tr.endpos; data.m_hEntity = pWpn->GetRefEHandle(); data.m_flScale = 0.0f; data.m_fFlags |= TRACER_FLAG_USEATTACHMENT; // Stomp the start, since it's not going to be used anyway data.m_nAttachmentIndex = 1; if ( pTracerName ) { DispatchEffect( pTracerName, data ); } else { DispatchEffect( "Tracer", data ); } } if ( m_bDoImpacts ) { pWpn->DoImpactEffect( tr, pAmmoDef->DamageType( m_iAmmoID ) ); } iSeed++; } } } } }
unsigned int PlayTest(const HeuristicParameters& parameters, unsigned int rollbacks, BoardDB* boarddb, std::mutex* boarddb_mutex) { std::mt19937 rng(RandomSeed()); struct HistoryData { Board board; unsigned int moves, score; }; std::vector<HistoryData> history; std::vector<BoardScore> extra_db; Board board{0}; auto t1 = std::chrono::high_resolution_clock::now(); unsigned int moves = 0, score = 0; for( ; ; ) { history.push_back(HistoryData{board, moves, score}); //PrintBoard(board); // computer unsigned int locations[16], location_count = 0; for(unsigned int location = 0; location < 16; ++location) { if(GetCell(board, location) == 0) { locations[location_count] = location; ++location_count; } } if(location_count == 0) { std::cout << "Can't insert!" << std::endl; exit(1); } board = SetCell(board, locations[rng() % location_count], (rng() % 10 == 0)? 2 : 1); //PrintBoard(board); // player auto move = FindBestMove(board, parameters); extra_db.push_back(BoardScore{board, move.second}); if(move.first == DIRECTION_NONE) { if(rollbacks == 0) break; --rollbacks; unsigned int back = 10 + rng() % 90; unsigned int p = (history.size() > back)? history.size() - back : 0; board = history[p].board; moves = history[p].moves; score = history[p].score; history.resize(p); } else { BoardScore result = Collapse(board, move.first); if(result.m_board.m_data == board.m_data) { std::cout << "Invalid move!" << std::endl; exit(1); } board = result.m_board; score += result.m_score * 2; ++moves; } } auto t2 = std::chrono::high_resolution_clock::now(); unsigned int time = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count(); unsigned int time_per_move = time / moves; std::cout << "Game over - Move: " << moves << ", Time per move: " << time_per_move << ", Score: " << score << std::endl; if(boarddb != NULL) { std::lock_guard<std::mutex> lock(*boarddb_mutex); boarddb->m_results.insert(boarddb->m_results.end(), extra_db.begin(), extra_db.end()); //unsigned int back = 100; //for(size_t i = (history.size() > back)? history.size() - back : 0; i < history.size(); ++i) { /*for(size_t i = 0; i < history.size(); ++i) { BoardScore result; result.m_board = history[i].board; result.m_score = score - history[i].score; boarddb->m_results.push_back(result); }*/ } return score; }
static TrajErr TRADESBenchmark(void) { /* protein is 1CDZ, same as beta protein - mixed alpha/beta protein 96 AA */ static Char sequence[]="ELPDFFQGKHFFLYGEFPGDERRKLIRYVTAFNGELEDYMSDRVQFVITAQEWDPSFEEALMDNPSLAFVRPRWIYSCNEKQKLLPHQLYGVVPQA"; CharPtr pc; FILE *f; Char fnamseq[PATH_MAX]; Char fnam[PATH_MAX]; Char fnamtrj[PATH_MAX]; Char fnuturndb[PATH_MAX]; Int2 err,numAA,cnt; Int4 randseed,dbsize; pMakeTrjParamBlock mkdata; pFoldTrajParamBlock foldtrajprm; CPUTimePtr pTime1,pTime2,pTime3,pTime4; BiostrucPtr bspBiostruc; PDNMS pdnmsModelstruc; PMSD pmsdHead; PDNML pdnmlModel; PMLD pmldThis; BiostrucIdPtr pbi=NULL; BiostrucDescrPtr pbd=NULL; printf("%d is the CODEBASE version here.\n6502:UNIX x86_32, 6503003:UNIX x86_64, 6500:Win32, 6401:UNIX PPC_32\n\n", S4VERSION); sprintf(fnuturndb,"UTURNDB"); /* to clean up errant U-Turn files CWVH 2010 */ if (!OPENMMDBAPI(0,NULL)) { ErrPostEx(SEV_ERROR,2,1,"Unable to open MMDBAPI"); return ERR_FAIL; } printf("One moment, opening rotamer library...\n"); if (LoadRotLib()!=ERR_SUCCESS) { ErrPostEx(SEV_ERROR,1,8,"Cannot open rotamer library (%s%s) - if the file is missing, please re-install the software",CFG_local_datafilepath,NEWSCWRL_FNAM); return ERR_FAIL; } pc=DFPTmpNam(FALSE,FALSE); if ((f=FileOpen(pc,"w"))==NULL) { CLOSEMMDBAPI(); FreeRotLib(); ErrPostEx(SEV_ERROR,errno,1,"Failed to open %s file",pc); return ERR_FAIL; } fprintf(f,"%s\n",sequence); /* Make sure disk space was sufficient to write to file */ if (fflush(f)==EOF) { FileClose(f); CLOSEMMDBAPI(); FreeRotLib(); ErrPostEx(SEV_ERROR,errno,1,"Failed to write to %s file",pc); return ERR_FAIL; } FileClose(f); StringCpy(fnamseq,pc); sprintf(fnam,"%s%s",CFG_local_datafilepath,BENCH_TRAJ); sprintf(fnamtrj,"%s%s%s",CFG_local_datafilepath,BENCH_TRAJ,ASN_EXT); mkdata = (pMakeTrjParamBlock)MemNew(sizeof(MakeTrjParamBlock)); mkdata->TrajMethod = 2; /* from sequence */ mkdata->valfnamin = NULL; mkdata->pcChain = NULL; mkdata->modelnum = 1; mkdata->startres = 1; mkdata->endres = 0; mkdata->peakheight = 100; mkdata->noise = 0; mkdata->savechi = 0; mkdata->sigma_x = 0.0; mkdata->sigma_y = 0.0; mkdata->temperature = 0; mkdata->timestep = 0.0; mkdata->seqfnamin = fnamseq; mkdata->tgtype = 4; mkdata->sstrufname = NULL; mkdata->DoRPS = FALSE; mkdata->uturn = FALSE; mkdata->SStruinput = FALSE; mkdata->trjfnamout = fnam; mkdata->comprtype = USE_RLE; mkdata->constrfnamin = NULL; mkdata->units=UNITS_ARBITRARY; mkdata->templat=NULL; mkdata->zhangwindsize = 0; mkdata->alignfile=NULL; mkdata->ssmask=NULL; mkdata->dumpcsv=0; mkdata->benchmark=1; mkdata->all_coil = (Boolean)(FALSE); mkdata->all_beta = (Boolean)(FALSE); /* ensure config file is set right, even if user may have fudged it */ if (SetConfigFileValues(WALK_PHIPSI,50.0/*errtol*/, 0.25/*abbb*/, 0.50/*absc*/, 0.0/*tunnelprob*/)!=ERR_SUCCESS) { CLOSEMMDBAPI(); FreeRotLib(); mkdata=MemFree(mkdata); FileRemove(pc); #ifdef OS_UNIX ErrPostEx(SEV_ERROR,0,0,"Unable to write config file .foldtrajrc, cannot continue"); #else ErrPostEx(SEV_FATAL,0,0,"Unable to write config file foldtraj.ini, cannot continue"); #endif return ERR_FAIL; } printf("Predicting secondary structure and generating trajectory distribution...\n"); pTime1=CPUTimeMeasure(); MakeTrj((VoidPtr)mkdata); printf("MadeTrj complete, unpacking ASN.1 Trajectory Graph\n"); pTime2=CPUTimeMeasure(); mkdata=MemFree(mkdata); FileRemove(fnamseq); if (UnPackAsnTrajGraph(fnam,&numAA,sequence,NULL,&pbi,&pbd,NULL)==NULL) { CLOSEMMDBAPI(); FreeRotLib(); FileRemove(fnamtrj); ErrPostEx(SEV_ERROR,2,3,"Unable to read trajectory distribution %s, please create a new one",fnam); return ERR_FAIL; } randseed=54374; RandomSeed(randseed); StringCpy(tmpskelfname,DFPTmpNam(FALSE,FALSE)); /* make the ASN.1 file for this protein's chemical graph */ BuildSkelASN(sequence,tmpskelfname); InitBSPLog(randseed,sequence,totalstruc); TGInit(tmpdbasename,DB_READ,&dbsize); printf("Folding protein...\n"); pTime3=CPUTimeMeasure(); for (cnt=0;cnt<100;cnt++) { bspBiostruc=NULL; bspBiostruc=MIMEBiostrucAsnGet(tmpskelfname,"r",NULL); if (bspBiostruc==NULL) { CLOSEMMDBAPI(); FreeRotLib(); FileRemove(fnamtrj); BSFree(bspTempLog); FileRemove(tmpskelfname); TGClose(); CleanUpDB(tmpdbasename); CleanUpDB(fnuturndb); ErrPostEx(SEV_ERROR,3,1,"Unable to fetch Biostruc"); return ERR_FAIL; } if (pbi!=NULL) { if (bspBiostruc->id!=NULL) AsnGenericChoiceSeqOfFree(bspBiostruc->id,(AsnOptFreeFunc)BiostrucIdFree); bspBiostruc->id=pbi; pbi=NULL; } if (pbd!=NULL) { if (bspBiostruc->descr!=NULL) AsnGenericChoiceSeqOfFree(bspBiostruc->descr,(AsnOptFreeFunc)BiostrucDescrFree); bspBiostruc->descr=pbd; pbd=NULL; } /* now the chemical graph is correctly in memory as a modelstruc, with co-ordinates (and hence PALDs) assigned only to a-carbons */ pdnmsModelstruc=MakeAModelstruc(bspBiostruc); if (pdnmsModelstruc==NULL) { CLOSEMMDBAPI(); FreeRotLib(); FileRemove(fnamtrj); BSFree(bspTempLog); FileRemove(tmpskelfname); TGClose(); CleanUpDB(tmpdbasename); CleanUpDB(fnuturndb); ErrPostEx(SEV_ERROR,4,1,"Unable to convert Biostruc to Modelstruc. Please ensure your protein only contains the 20 standard amino acids."); return ERR_FAIL; } pmsdHead=(PMSD)(pdnmsModelstruc->data.ptrvalue); /* remove ppAsnOrder for all models so it will be rebuilt in WriteAsnAllModel */ pdnmlModel=pmsdHead->pdnmlModels; while (pdnmlModel) { pmldThis=(PMLD)(pdnmlModel->data.ptrvalue); if (pmldThis->ppAsnOrder) { PTRVectorFree(pmldThis->ppAsnOrder,0); pmldThis->ppAsnOrder=NULL; } pdnmlModel=pdnmlModel->next; } if (dbsize!=((PMMD)((pmsdHead->pdnmmHead)->data.ptrvalue))->iResCount) { CLOSEMMDBAPI(); FreeRotLib(); FreeAModelstruc(pdnmsModelstruc); BSFree(bspTempLog); FileRemove(fnamtrj); FileRemove(tmpskelfname); TGClose(); CleanUpDB(tmpdbasename); CleanUpDB(fnuturndb); ErrPostEx(SEV_ERROR,1,1,"protein length inconsistency error, expect: %d actual: %d, possibly due to corrupt trajectory file; aborting",((PMMD)((pmsdHead->pdnmmHead)->data.ptrvalue))->iResCount,dbsize); return ERR_FAIL; } foldtrajprm=(pFoldTrajParamBlock)MemNew(sizeof(FoldTrajParamBlock)); foldtrajprm->pmsdRoot=pmsdHead; foldtrajprm->Model=1; foldtrajprm->err=0; foldtrajprm->gen=0; foldtrajprm->errorfile=NULL; /* do the folding here */ TRADEProtein((VoidPtr)foldtrajprm,1); err=foldtrajprm->err; foldtrajprm=MemFree(foldtrajprm); FreeAModelstruc(pdnmsModelstruc); if (err!=ERR_SUCCESS && err!=ERR_INCOMPLETE) { FileRemove(fnamtrj); FileRemove(tmpskelfname); BSFree(bspTempLog); TGClose(); CleanUpDB(tmpdbasename); CleanUpDB(fnuturndb); CLOSEMMDBAPI(); FreeRotLib(); ErrPostEx(SEV_ERROR,1,1,"Benchtraj returned a folding error %d",err); return ERR_FAIL; } } pTime4=CPUTimeMeasure(); FileRemove(fnamtrj); FileRemove(tmpskelfname); BSFree(bspTempLog); TGClose(); CleanUpDB(tmpdbasename); CleanUpDB(fnuturndb); CLOSEMMDBAPI(); FreeRotLib(); printf("Benchmark complete.\n\nSummary\n-------\n Usr time Sys time\n -------- --------\n"); printf("Maketrj %9.3f %9.3f\nFoldtraj %9.3f %9.3f\n\n",CPUTimeGetUser(pTime2)-CPUTimeGetUser(pTime1),CPUTimeGetSys(pTime2)-CPUTimeGetSys(pTime1),CPUTimeGetUser(pTime4)-CPUTimeGetUser(pTime3),CPUTimeGetSys(pTime4)-CPUTimeGetSys(pTime3)); printf("Benchtraj successful\n"); return ERR_SUCCESS; }
int main(int argc, char *argv[]) { char fileName[255]; FILE *exampleIn, *names; ExampleSpecPtr es; ExamplePtr e; FILE *outputData, *outputTest = NULL; _processArgs(argc, argv); /* set up the random seed */ RandomInit(); if(gSeed != -1) { RandomSeed(gSeed); } /* read the spec file */ sprintf(fileName, "%s/%s.names", gSourceDirectory, gFileStem); /* TODO check that the file exists */ es = ExampleSpecRead(fileName); DebugError(es == 0, "Unable to open the .names file"); if(!gStdout) { /* TODO check that the target directory exists */ sprintf(fileName, "%s/%s.data", gTargetDirectory, gOutputStem); outputData = fopen(fileName, "w"); DebugError(outputData == 0, "Unable to open output files."); } else { outputData = stdout; } if(gOutputTest) { /* TODO check that the target directory exists */ sprintf(fileName, "%s/%s.test", gTargetDirectory, gOutputStem); outputTest = fopen(fileName, "w"); DebugError(outputData == 0, "Unable to open test data output files."); } if(!gStdin) { sprintf(fileName, "%s/%s.data", gSourceDirectory, gFileStem); exampleIn = fopen(fileName, "r"); DebugError(exampleIn == 0, "Unable to open .data file"); } else { exampleIn = stdin; } e = ExampleRead(exampleIn, es); while(e != 0) { if(gSamplePercent >= RandomDouble()) { ExampleWrite(e, outputData); } else if(gOutputTest) { ExampleWrite(e, outputTest); } ExampleFree(e); e = ExampleRead(exampleIn, es); } fclose(exampleIn); fclose(outputData); /* output the names file */ /* TODO check that the target directory exists */ sprintf(fileName, "%s/%s.names", gTargetDirectory, gOutputStem); names = fopen(fileName, "w"); DebugError(names == 0, "Unable to open target names file for output."); ExampleSpecWrite(es, names); fclose(names); return 0; }
void zsc(Thd_Tbl* ttb, Seq_Mtf* psm, Qry_Seq* qsq, Cxl_Los** cpr, Cor_Def* cdf, Rcx_Ptl* pmf, Seg_Gsm* spe, Cur_Aln* sai, Rnd_Smp* pvl, double ScalingFactor) { /*---------------------------------------------------------*/ /* ttb: Tables to hold Results of Gibbs sampled threading */ /* qsq: Sequence to thread with alignment contraints */ /* cpr: Contacts by segment, largest possible set */ /* cdf: Core segment locations and loop length limits */ /* pmf: Potential of mean force as a 3-d lookup table */ /* psm: Sequence motif parameters */ /* spe: Partial sums of contact energies by segment pair */ /* sai: Current alignment of query sequence with core */ /* pvl: Storage for sequence permutation parameters */ /*---------------------------------------------------------*/ int i,j,k,nmt, itr,ii,jj; /* Counters */ int i_max; /* Index of the top hit */ int ntr; /* Number of positions to be shuffled */ int nsc; /* Number of core segments */ int ppi; /* Index of the peptide group in potential */ int n_perm; /* Number of permutations */ int mn,mx; int n_thr; /* Number of top threads to calculate Z-score for */ int to,from, tlf=0,tls=0,dln; int *cf; /* Flags residues within the core */ int t1,t2; /* Motif residue types */ int r1,r2; /* Motif residue positions */ int s1,s2; /* Core segment indices */ int d; /* Distance interval */ int ms,cs, ls; /* Energy terms */ float avg,avg2, avgm,avgp, avgm2,avgp2; /* Averages */ int nl,ot; float disp,dispm,dispp;/* Square root of variance */ float tg,tgp,tgm; /* Energy of shuffled sequence */ float tg_max=0.0f; /* Energy of a given thread */ int *gi; int *lsg,*aqi, *r,*o,*sq; int g; Cxl_Los *cr; /* Pointer to segment reference contact lists */ /* Parameters */ nsc=cdf->sll.n; n_perm=10000; n_thr=1; /* Should be less than ttb->n */ ppi=pmf->ppi; nmt=psm->n; cf=sai->cf; sq=pvl->sq; aqi=pvl->aqi; r=pvl->r; o=pvl->o; lsg=pvl->lsg; /* Start loop over n_thr top threads */ i_max=ttb->mx; for(ii=0; ii<n_thr; ii++) { avg = avg2 = avgm = avgp = avgm2 = avgp2 = 0.0; ntr=0; for(jj=0; jj<qsq->n; jj++)sq[jj]=qsq->sq[jj]; /* Collect sequence indices of threaded residues of sequence */ for(i=0; i<=nsc; i++) lsg[i]=1; itr=0; for(j=0; j<nsc; j++) { mn=ttb->al[j][i_max]-ttb->no[j][i_max]; mx=ttb->al[j][i_max]+ttb->co[j][i_max]; for(k=mn; k<=mx; k++) { aqi[itr]=k; itr++; } if(j<nsc-1) { to=ttb->al[j+1][i_max]-ttb->no[j+1][i_max]; from=ttb->al[j][i_max]+ttb->co[j][i_max]; dln=to-from-1; if(dln > cdf->lll.lrfs[j+1] || dln < 1) lsg[j+1]=0; } } for(j=0; j<=nsc; j++) { if(lsg[j]==0) continue; if(j==0) { tlf=ttb->al[j][i_max]-ttb->no[j][i_max]-1; tls=tlf-cdf->lll.lrfs[j]+1; if(tls<1) tls=1; } if(j==nsc) { tls=ttb->al[j-1][i_max]+ttb->co[j-1][i_max]+1; tlf=tls+cdf->lll.lrfs[j]-1; if(tlf>qsq->n) tlf=qsq->n; } if(j!=0 && j!=nsc) { tls=ttb->al[j-1][i_max]+ttb->co[j-1][i_max]+1; tlf=ttb->al[j][i_max]-ttb->no[j][i_max]-1; } for(k=tls; k<=tlf; k++) { aqi[itr]=k; itr++; } } ntr=itr-1; /* Flag residues within the cores */ for(i=0; i<nmt; i++) cf[i]=(-1); for(i=0; i<nsc; i++) { mn=cdf->sll.rfpt[i]-ttb->no[i][i_max]; mx=cdf->sll.rfpt[i]+ttb->co[i][i_max]; for(j=mn; j<=mx; j++) cf[j]=i; } /* Loop over n_perm permutations */ for(k=0; k<=n_perm; k++) { /* srand48(k); */ RandomSeed(k); /* Perform the permutation of the residues of aligned part together with the intercore loops. Tail loops are not included. */ /* for(i=0;i<=ntr;i++)r[i]=lrand48(); */ for(i=0; i<=ntr; i++)r[i]=RandomNum(); for(i=0; i<=ntr; i++)o[i]=i; for(i=ntr; i>0; ) { nl=i; i=0; for(j=0; j<nl; j=j+1) { if(r[o[j]]>r[o[j+1]]) { ot=o[j]; o[j]=o[j+1]; o[j+1]=ot; i=j; } } } if(k!=0) { for(i=0; i<qsq->n; i++) sq[i]=-1; for(i=0; i<=ntr; i++) { r[i]=aqi[o[i]]; sq[aqi[i]]=qsq->sq[r[i]]; } } /* Calculate the energy for a given permuted sequence aligned with the structure*/ /* Loop over core segments */ for(i=0; i<nsc; i++) { cr=cpr[i]; spe->gs[i]=0; spe->ms[i]=0; for(j=0; j<nsc; j++) { spe->gss[i][j]=0; spe->gss[j][i]=0; } /* Loop over residue-residue contacts in the reference list */ for(j=0; j<cr->rr.n; j++) { /* Test that the contact is within the allowed extent range */ r1=cr->rr.r1[j]; s1=cf[r1]; if(s1<0) continue; t1=sq[ttb->al[s1][i_max]-(cdf->sll.rfpt[s1]-r1)]; if(t1<0) continue; r2=cr->rr.r2[j]; s2=cf[r2]; if(s2<0) continue; t2=sq[ttb->al[s2][i_max]-(cdf->sll.rfpt[s2]-r2)]; if(t2<0) continue; d=cr->rr.d[j]; spe->gss[s1][s2]+=pmf->rrt[d][t1][t2]; } /*Loop over residue-peptide contacts in the refernce list */ for(j=0; j<cr->rp.n; j++) { /* Test that the contact is present in the current core */ r1=cr->rp.r1[j]; s1=cf[r1]; if(s1<0) continue; t1=sq[ttb->al[s1][i_max]-(cdf->sll.rfpt[s1]-r1)]; if(t1<0) continue; r2=cr->rp.p2[j]; s2=cf[r2]; if(s2<0) continue; d=cr->rp.d[j]; spe->gss[s1][s2]+=pmf->rrt[d][t1][ppi]; } /* Loop over residue-fixed contacts in the reference list */ for(j=0; j<cr->rf.n; j++) { /* Test that the contact is present in the current list */ r1=cr->rf.r1[j]; s1=cf[r1]; if(s1<0) continue; t1=sq[ttb->al[s1][i_max]-(cdf->sll.rfpt[s1]-r1)]; if(t1<0) continue; t2=cr->rf.t2[j]; d=cr->rf.d[j]; spe->gs[i]+=pmf->rrt[d][t1][t2]; } /* Sum motif energies */ mn=cdf->sll.rfpt[i]-ttb->no[i][i_max]; mx=cdf->sll.rfpt[i]+ttb->co[i][i_max]; for(j=mn; j<=mx; j++) { t1=sq[ttb->al[i][i_max]-(cdf->sll.rfpt[i]-j)]; if(t1<0) continue; spe->ms[i]+=psm->ww[j][t1]; } } g=0; ms=0; cs=0; ls=0; for(i=0; i<nsc; i++) { g+=spe->gs[i]; ms+=spe->ms[i]; cs+=spe->cs[i]; ls+=spe->ls[i]; gi=spe->gss[i]; for(j=0; j<nsc; j++) g+=gi[j]; } /*ms=ms-psm->score0;*/ /* Entire energy for a current permutation */ if(k!=0) { tg=((float)(g+ms+cs+ls))/ScalingFactor; tgm=((float)(ms))/ScalingFactor; tgp=((float)(g))/ScalingFactor; } else { tg = tgm = tgp = 0.0; tg_max=((float)(g+ms+cs+ls))/ScalingFactor; } avg+=tg; avg2+=tg*tg; avgm+=tgm; avgm2+=tgm*tgm; avgp+=tgp; avgp2+=tgp*tgp; } /* End of loop over permutations */ /* Calculate the mean, variance and Z-score */ disp=sqrt(((float)avg2 - (avg*avg)/n_perm)/(n_perm-1)); dispm=sqrt(((float)avgm2 - (avgm*avgm)/n_perm)/(n_perm-1)); dispp=sqrt(((float)avgp2 - (avgp*avgp)/n_perm)/(n_perm-1)); avg=avg/n_perm; avgm=avgm/n_perm; avgp=avgp/n_perm; ttb->zsc[i_max]=ScalingFactor*(tg_max-avg)/disp; ttb->g0[i_max]=avg*ScalingFactor; ttb->m0[i_max]=avgm*ScalingFactor; ttb->errm[i_max]=dispm*ScalingFactor; ttb->errp[i_max]=dispp*ScalingFactor; i_max=ttb->nx[i_max]; } /* End of loop over threads */ }
//***************************************************************************** // // This task manages the scurrying about of a spider. // //***************************************************************************** static void SpiderTask(void *pvParameters) { uint32_t ui32Dir, ui32Image, ui32Temp; int32_t i32X, i32Y, i32Spider; // // Get the spider number from the parameter. // i32Spider = (long)pvParameters; // // Add the current tick count to the random entropy pool. // RandomAddEntropy(xTaskGetTickCount()); // // Reseed the random number generator. // RandomSeed(); // // Indicate that this spider is alive. // HWREGBITW(&g_ui32SpiderAlive, i32Spider) = 1; // // Indicate that this spider is not dead yet. // HWREGBITW(&g_ui32SpiderDead, i32Spider) = 0; // // Get a local copy of the spider's starting position. // i32X = g_pi32SpiderX[i32Spider]; i32Y = g_pi32SpiderY[i32Spider]; // // Choose a random starting direction for the spider. // ui32Dir = RandomNumber() >> 29; // // Start by displaying the first of the two spider animation images. // ui32Image = 0; // // Loop forever. // while(1) { // // See if this spider has been killed. // if(HWREGBITW(&g_ui32SpiderDead, i32Spider) == 1) { // // Wait for 2 seconds. // vTaskDelay((1000 / portTICK_RATE_MS) * 2); // // Clear the spider from the display. // DisplayImage(i32X - (SPIDER_WIDTH / 2), i32Y - (SPIDER_HEIGHT / 2), g_pui8SpiderBlankImage); // // Indicate that this spider is not alive. // HWREGBITW(&g_ui32SpiderAlive, i32Spider) = 0; // // Delete the current task. This should never return. // vTaskDelete(NULL); // // In case it does return, loop forever. // while(1) { } } // // Enter a critical section while the next move for the spider is // determined. Having more than one spider trying to move at a time // (via preemption) would make the collision detection check fail. // taskENTER_CRITICAL(); // // Move the spider. // i32X += g_pi32SpiderStepX[ui32Dir]; i32Y += g_pi32SpiderStepY[ui32Dir]; // // See if the spider has cross the boundary of its area, if it has // collided with another spider, or if random chance says that the // spider should turn despite not having collided with anything. // if((i32X < SPIDER_MIN_X) || (i32X > SPIDER_MAX_X) || (i32Y < SPIDER_MIN_Y) || (i32Y > SPIDER_MAX_Y) || (SpiderCollide(i32Spider, i32X, i32Y) != -1) || (RandomNumber() < 0x08000000)) { // // Undo the previous movement of the spider. // i32X -= g_pi32SpiderStepX[ui32Dir]; i32Y -= g_pi32SpiderStepY[ui32Dir]; // // Get a random number to determine the turn to be made. // ui32Temp = RandomNumber(); // // Determine how to turn the spider based on the random number. // Half the time the spider turns to the left and half the time it // turns to the right. Of each half, it turns a quarter of a turn // 12.5% of the time and an eighth of a turn 87.5% of the time. // if(ui32Temp < 0x10000000) { ui32Dir = (ui32Dir + 2) & 7; } else if(ui32Temp < 0x80000000) { ui32Dir = (ui32Dir + 1) & 7; } else if(ui32Temp < 0xf0000000) { ui32Dir = (ui32Dir - 1) & 7; } else { ui32Dir = (ui32Dir - 2) & 7; } } // // Update the position of the spider. // g_pi32SpiderX[i32Spider] = i32X; g_pi32SpiderY[i32Spider] = i32Y; // // Exit the critical section now that the spider has been moved. // taskEXIT_CRITICAL(); // // Have the display task draw the spider at the new position. Since // there is a one pixel empty border around all the images, and the // position of the spider is incremented by only one pixel, this also // erases any traces of the spider in its previous position. // DisplayImage(i32X - (SPIDER_WIDTH / 2), i32Y - (SPIDER_HEIGHT / 2), g_ppui8SpiderImage[(ui32Dir * 2) + ui32Image]); // // Toggle the spider animation index. // ui32Image ^= 1; // // Delay this task for an amount of time based on the direction the // spider is moving. // vTaskDelay(g_pui32SpiderDelay[ui32Dir & 1]); // // Add the new tick count to the random entropy pool. // RandomAddEntropy(xTaskGetTickCount()); // // Reseed the random number generator. // RandomSeed(); } }