void _getRKcoeffRadauIIA5(RKOCP r) { // RadauIIA order 5 r->rkMethodName = "RadauIIA5"; r->rk_stages = 3; r->rk_order = 5; r->rk_a = MatrixNew(r->rk_stages, r->rk_stages); r->rk_w = MatrixNew(r->rk_stages, r->rk_stages); r->rk_b = VectorNew(r->rk_stages); r->rk_c = VectorNew(r->rk_stages); r->rk_e = VectorNew(r->rk_stages); double **rk_a, **rk_w, *rk_b, *rk_c; double s6 = sqrt(6.0); rk_a = r->rk_a->e; rk_w = r->rk_w->e; rk_b = r->rk_b->e; rk_c = r->rk_c->e; rk_a[0][0] = (88.0-7.0*s6)/360.0; rk_a[0][1] = (296.0-169.0*s6)/1800.0; rk_a[0][2] = (-2.0+3.0*s6)/225.0; rk_a[1][0] = (296.0+169.0*s6)/1800.0; rk_a[1][1] = (88.0+7.0*s6)/360.0; rk_a[1][2] = (-2.0-3.0*s6)/225.0; rk_a[2][0] = (16.0-s6)/36.0; rk_a[2][1] = (16.0+s6)/36.0; rk_a[2][2] = 1.0/9.0; rk_w[0][0] = 3.2247448713915885e+00; rk_w[0][1] = 1.1678400846904053e+00; rk_w[0][2] = -2.5319726474218074e-01; rk_w[1][0] = -3.5678400846904053e+00; rk_w[1][1] = 7.7525512860841150e-01; rk_w[1][2] = 1.0531972647421806e+00; rk_w[2][0] = 5.5319726474218109e+00; rk_w[2][1] = -7.5319726474218101e+00; rk_w[2][2] = 5.0000000000000000e+00; rk_b[0] = (16.0-s6)/36.0; rk_b[1] = (16.0+s6)/36.0; rk_b[2] = 1.0/9.0; rk_c[0] = (4.0-s6)/10.0; rk_c[1] = (4.0+s6)/10.0; rk_c[2] = 1.0; }
static void ProcessWellFormedWord(char *word, article *a, hashset *stopWords, hashset *wordHash, hashset *articlesSeen) { currWord w; char* word2 = strdup(word); if(HashSetLookup(stopWords, &word2) == NULL) { //not a stopword w.thisWord = word2; VectorNew(&w.articles, sizeof(article),NULL, 100); currWord* elemAddr = (currWord*)HashSetLookup(wordHash,&w); if(elemAddr == NULL){ // Hasn't been seen a->numOccurrences = 1; VectorAppend(&w.articles, a); HashSetEnter(wordHash, &w); } else { UpdateOccurences(&elemAddr->articles,a); // we just need to update, not add // clean up free(word2); VectorDispose(&w.articles); } } else { free(word2); // free stop word } }
int main(int argc, char **argv) { static const char *stopwordFilename = "/home/compilers/media/assn-4-rss-news-search-data/stop-words.txt"; static const int kStopwordBuckets = 1009; static const int kIndexNumBuckets = 10007; rssData allData; HashSetNew(&allData.stopwords, sizeof(char*), kStopwordBuckets, StringHash, StringCmp, StringFree); HashSetNew(&allData.indices, sizeof(indexEntry), kIndexNumBuckets, IndexHash, IndexCmp, IndexFree); // this vector VectorNew(&allData.explored, sizeof(article), ArticleFree, 10); Welcome(kWelcomeTextFile); ReadStopwords(&allData.stopwords, stopwordFilename); BuildIndices((argc == 1) ? kDefaultFeedsFile : argv[1], &allData ); int hcount = HashSetCount(&allData.indices); printf("hcount: %d\n", hcount); printf("Finished BuildIndices\n"); QueryIndices(&allData); return 0; }
static void BuildIndices(rssDatabase *db, const char *feedsFileURL) { url u; urlconnection urlconn; URLNewAbsolute(&u, feedsFileURL); URLConnectionNew(&urlconn, &u); if (urlconn.responseCode / 100 == 3) { BuildIndices(db, urlconn.newUrl); } else { streamtokenizer st; char remoteFileName[2048]; HashSetNew(&db->indices, sizeof(rssIndexEntry), kNumIndexEntryBuckets, IndexEntryHash, IndexEntryCompare, IndexEntryFree); VectorNew(&db->previouslySeenArticles, sizeof(rssNewsArticle), NewsArticleFree, 0); STNew(&st, urlconn.dataStream, kNewLineDelimiters, true); while (STSkipUntil(&st, ":") != EOF) { // ignore everything up to the first selicolon of the line STSkipOver(&st, ": "); // now ignore the semicolon and any whitespace directly after it STNextToken(&st, remoteFileName, sizeof(remoteFileName)); ProcessFeed(db, remoteFileName); } printf("\n"); STDispose(&st); } URLConnectionDispose(&urlconn); URLDispose(&u); }
static void TokenizeAndBuildThesaurus(hashset *thesaurus, streamtokenizer *st) { printf("Loading thesaurus. Be patient! "); fflush(stdout); char buffer[2048]; while (STNextToken(st, buffer, sizeof(buffer))) { thesaurusEntry entry; entry.word = strdup(buffer); VectorNew(&entry.synonyms, sizeof(char *), StringFree, 4); while (STNextToken(st, buffer, sizeof(buffer)) && (buffer[0] == ',')) { STNextToken(st, buffer, sizeof(buffer)); char *synonym = strdup(buffer); VectorAppend(&entry.synonyms, &synonym); } HashSetEnter(thesaurus, &entry); if (HashSetCount(thesaurus) % 1000 == 0) { printf("."); fflush(stdout); } } printf(" [All done!]\n"); fflush(stdout); }
/** * Function: TestHashTable * ----------------------- * Runs a test of the hashset using a frequency structure as the element * type. It will open a file, read each char, and count the number of * times each char occurs. Tests enter, lookup, and mapping for the hashset. * Prints contents of table to stdout. Then it dumps all the table elements * into a vector and sorts them by frequency of occurrences and * prints the array out. Note that this particular stress test passes * 0 as the initialAllocation, which the vector is required to handle * gracefully - be careful! */ static void TestHashTable(void) { hashset counts; vector sortedCounts; HashSetNew(&counts, sizeof(struct frequency), kNumBuckets, HashFrequency, CompareLetter, NULL); fprintf(stdout, "\n\n ------------------------- Starting the HashTable test\n"); BuildTableOfLetterCounts(&counts); fprintf(stdout, "Here is the unordered contents of the table:\n"); HashSetMap(&counts, PrintFrequency, stdout); // print contents of table VectorNew(&sortedCounts, sizeof(struct frequency), NULL, 0); HashSetMap(&counts, AddFrequency, &sortedCounts); // add all freq to array VectorSort(&sortedCounts, CompareLetter); // sort by char fprintf(stdout, "\nHere are the trials sorted by char: \n"); VectorMap(&sortedCounts, PrintFrequency, stdout); VectorSort(&sortedCounts, CompareOccurrences); //sort by occurrences fprintf(stdout, "\nHere are the trials sorted by occurrence & char: \n"); VectorMap(&sortedCounts, PrintFrequency, stdout); // print out array VectorDispose(&sortedCounts); // free all storage HashSetDispose(&counts); }
static void ChallengingTest() { vector lotsOfNumbers; fprintf(stdout, "\n\n------------------------- Starting the more advanced tests...\n"); VectorNew(&lotsOfNumbers, sizeof(long), NULL, 4); InsertPermutationOfNumbers(&lotsOfNumbers, kLargePrime, kEvenLargerPrime); SortPermutation(&lotsOfNumbers); DeleteEverythingVerySlowly(&lotsOfNumbers); VectorDispose(&lotsOfNumbers); }
void setColoursByAcceleration() { int i; particle_t *p, *plast; particleDetail_t *pd; float d; float accMax = 0; float accCurrent; float velSpeed1; float velSpeed2; VectorNew(zero); VectorZero(zero); if (state.currentFrame == 0) return; for (i = 0; i < state.particleCount; i++) { p = getParticleCurrentFrame(i); plast = state.particleHistory + state.particleCount * (state.currentFrame-1) + i; distance(zero, p->vel, velSpeed1); distance(p->vel, plast->vel, velSpeed2); accCurrent = abs(velSpeed2 - velSpeed1); if (i == 0) { accMax = accCurrent; } else { if (accCurrent > accMax) accMax = accCurrent; } } for (i = 0; i < state.particleCount; i++) { p = getParticleCurrentFrame(i); plast = state.particleHistory + state.particleCount * (state.currentFrame-1) + i; distance(zero, p->vel, velSpeed1); distance(p->vel, plast->vel, velSpeed2); accCurrent = velSpeed2 - velSpeed1; pd = getParticleDetail(i); d = accCurrent / accMax; colourFromNormal(pd->col, (float)fabs((double)d)); pd->particleSprite = colourSprite(pd->col, pd->mass); } }
static void SimpleTest() { fprintf(stdout, " ------------------------- Starting the basic test...\n"); vector alphabet; VectorNew(&alphabet, sizeof(char), NULL, 4); TestAppend(&alphabet); TestSortSearch(&alphabet); TestAt(&alphabet); TestInsertDelete(&alphabet); TestReplace(&alphabet); VectorDispose(&alphabet); }
int luag_spawn(lua_State *L) { particle_t *p; particleDetail_t *pd; VectorNew(pos); VectorNew(vel); float mass; int id; VectorZero(pos); VectorZero(vel); mass = lua_tonumber(L, -1); id = -1; lua_pop(L, 1); luag_TableToVector(L, vel); lua_pop(L, 1); luag_TableToVector(L, pos); lua_pop(L, 1); id = lua_tonumber(L, -1); if (id < 0 || id >= state.particleCount) { conAdd(LERR, "Particle %i out of range", id); return 0; } p = getParticleFirstFrame(id); pd = getParticleDetail(id); VectorCopy(pos, p->pos); VectorCopy(vel, p->vel); pd->mass = mass; doVideoUpdateInSpawn(); return 0; }
static void initThreadsData(rssDatabase *db) { VectorNew(&db->threads, sizeof(threadData),ThreadDataFree,0); HashSetNew(&(db->locks.limitConnToServerLock),sizeof(serverLockData),kNumOfServersBuckets, ConnectionsLockHash, ConnectionsLockCompare,ConnectionsLockFree); pthread_mutex_init(&(db->locks.serverDataLock), NULL); pthread_mutex_init(&(db->locks.articlesVectorLock), NULL); pthread_mutex_init(&(db->locks.indicesHashSetLock), NULL); pthread_mutex_init(&(db->locks.stopWordsHashSetLock), NULL); sem_init(&(db->locks.connectionsLock),0,kNumOfConnections); }
static indexData* addWordRecord(hashset *indices, char *word) { indexData index; index.word = word; void *found = HashSetLookup(indices, &index); if(found == NULL) { index.word = strdup(word); VectorNew(&(index.counters), sizeof(wordCounter), NULL, 1); HashSetEnter(indices, &index); return HashSetLookup(indices, &index); } else { return (indexData*)found; } }
Vector* TableSearchParams (Table *v, int from_proc) { Vector *vector = VectorNew(); int i; for (i = 0; i < v->size; i++) { // procura por from_proc if (v->simbolos[i]->from_proc == from_proc) // procura por classe if (v->simbolos[i]->argument == ARGUMENT_TRUE) VectorAdd(vector, i); } return vector; }
void setColoursByKinetic() { int i; particle_t *p; particleDetail_t *pd; float d; float kinMax = 0; float kinValue; float velocity; VectorNew(zero); VectorZero(zero); for (i = 0; i < state.particleCount; i++) { p = getParticleCurrentFrame(i); pd = getParticleDetail(i); distance(zero, p->vel, velocity); velocity = fabs(velocity); kinValue = velocity * velocity * pd->mass * 0.5; if (i == 0) { kinMax = kinValue; } else { if (kinValue > kinMax) kinMax = kinValue; } } for (i = 0; i < state.particleCount; i++) { p = getParticleFirstFrame(i); pd = getParticleDetail(i); distance(zero, p->vel, velocity); kinValue = velocity * velocity * pd->mass * 0.5; d = kinValue / kinMax; colourFromNormal(pd->col, (float)fabs((double)d)); pd->particleSprite = colourSprite(pd->col, pd->mass); } }
static indexData* addWordRecord(hashset *indices, char*someWord){ indexData index; index.word = someWord; indexData * find = HashSetLookup(indices,&index); if(find==NULL){ index.word = strdup(someWord); VectorNew(&index.data,sizeof(wordCounter),NULL,1 ); HashSetEnter(indices,&index); return HashSetLookup(indices,&index); }else return find; }
static void ScanArticle(streamtokenizer *st, article *a, int articleIndex, rssData *allData ) { int numWords = 0; char word[1024]; char longestWord[1024] = {'\0'}; while (STNextToken(st, word, sizeof(word))) { if (strcasecmp(word, "<") == 0) { SkipIrrelevantContent(st); // in html-utls.h } else { RemoveEscapeCharacters(word); if (WordIsWellFormed(word)) { numWords++; char *dummy = word; if ( WordNotInStopwords(&allData->stopwords, word)) { /** Try looking up the word. If the word is not in the indices, create a new indexEntry * initialized with the word and an empty vector and enter it into the hashset */ indexEntry entry = {word}; indexEntry *found = HashSetLookup(&allData->indices, &entry); if (found == NULL) { entry.word = strdup(dummy); VectorNew(&entry.articles, sizeof(wordcountEntry), NULL, 10); HashSetEnter(&allData->indices, &entry); } // now we act as if the entry was in the index all along found = (indexEntry*)HashSetLookup( &allData->indices, &entry); UpdateIndices(&found->articles, articleIndex); } if (strlen(word) > strlen(longestWord)) strcpy(longestWord, word); } } } printf("\tWe counted %d well-formed words [including duplicates].\n", numWords); printf("\tThe longest word scanned was \"%s\".", longestWord); if (strlen(longestWord) >= 15 && (strchr(longestWord, '-') == NULL)) printf(" [Ooooo... long word!]"); printf("\n"); }
void HashSetNew(hashset *h, int elemSize, int numBuckets, HashSetHashFunction hashfn, HashSetCompareFunction comparefn, HashSetFreeFunction freefn){ assert(elemSize > 0 && numBuckets > 0 && hashfn != NULL && comparefn != NULL && "not possible to construct the HashSet"); h->elemSize = elemSize; h->numBuckets = numBuckets; h->hashfn = hashfn; h->comparefn = comparefn; h->freefn = freefn; h->buckets = malloc(sizeof(vector) * numBuckets); int i; for (i = 0; i < numBuckets; i++) { vector *vAddress = h->buckets + i; VectorNew(vAddress, elemSize, freefn, 4); } }
void _getRKcoeffRadauIIA3(RKOCP r) { // RadauIIA order 3 r->rkMethodName = "RadauIIA3"; r->rk_stages = 2; r->rk_order = 3; r->rk_a = MatrixNew(r->rk_stages, r->rk_stages); r->rk_w = MatrixNew(r->rk_stages, r->rk_stages); r->rk_b = VectorNew(r->rk_stages); r->rk_c = VectorNew(r->rk_stages); r->rk_e = VectorNew(r->rk_stages); double **rk_a, **rk_w, *rk_b, *rk_c; rk_a = r->rk_a->e; rk_w = r->rk_w->e; rk_b = r->rk_b->e; rk_c = r->rk_c->e; rk_a[0][0] = 5.0/12.0; rk_a[0][1] = -1.0/12.0; rk_a[1][0] = 0.75; rk_a[1][1] = 0.25; rk_w[0][0] = 1.5; rk_w[0][1] = 0.5; rk_w[1][0] = -4.5; rk_w[1][1] = 2.5; rk_b[0] = 0.75; rk_b[1] = 1.0; rk_c[0] = 1.0/3.0; rk_c[1] = 1.0; }
void HashSetNew(hashset *h, int elemSize, int numBuckets, HashSetHashFunction hashfn, HashSetCompareFunction comparefn, HashSetFreeFunction freefn) { h->elemSize=elemSize; h->numBuckets=numBuckets; h->hashfn=hashfn; h->comparefn=comparefn; h->freefn=freefn; h->buckets=malloc(numBuckets*sizeof(vector)); h->count=0; for(int i=0; i<numBuckets; i++) { VectorNew(h->buckets+i, elemSize, freefn, 4); } }
/* convert text to tokens, remove tags and convert back to string: tokens and keep all positions in array "positions" array: text, tokens, positions must be released by the caller program. */ void convertToken2Text( char*text, char* tokens, int** positions) { cvector tokenVector; int* p; char* t = tokens; Token *token; int i,j,len; assert(text); assert(tokens); assert(positions); VectorNew (&tokenVector, sizeof (Token),free_token, DEF_VECTOR_SIZE); getTokensFromText(text, &tokenVector); assert (text); for (i=0;i<tokenVector.ItemsCount;i++) { token = (Token*)VectorNth(&tokenVector,i); sprintf( t, "%s", token->term); t+=strlen(token->term); //append ' ' to the end of each token if (i!=tokenVector.ItemsCount) *t++=' '; } *t='\0'; //record the position of token in the text *positions = (int*)malloc( sizeof(int) * strlen(text) ); if (!*positions) { printf("Not enough memory!\n"); exit(0); } p=*positions; for (i=0;i<tokenVector.ItemsCount;i++) { token = (Token*)VectorNth(&tokenVector,i); len = strlen(token->term); //printf("\ntoken: %s\n", token->term); //record position of the token (each char will has a position, and value is the positon of first character of the token) for (j=0;j<len;j++) { *p++ = token->position+j; //printf("%c->%d ",*(text+token->position+j), token->position+j); } if (i!=tokenVector.ItemsCount-1) *p++= token->position+j-1; //position as next token } VectorDispose(&tokenVector); }
void translateToCenter() { int i; particle_t *p; VectorNew(pos); VectorZero(pos); for (i = 0; i < state.particleCount; i++) { p = getParticleCurrentFrame(i); VectorAdd(pos, p->pos, pos); } VectorDivide(pos, state.particleCount, pos); glTranslatef(-pos[0], -pos[1], -pos[2]); VectorCopy(pos, view.lastCenter); }
void setColoursByVel() { int i; particle_t *p; particleDetail_t *pd; float d; float velMax = 0; float velSpeed; VectorNew(zero); VectorZero(zero); // works out the highest velocity for (i = 0; i < state.particleCount; i++) { p = getParticleCurrentFrame(i); distance(zero, p->vel, velSpeed); velSpeed = fabs(velSpeed); if (i == 0) { velMax = velSpeed; } else { if (velSpeed > velMax) velMax = velSpeed; } } // applies velocity based on the highest for (i = 0; i < state.particleCount; i++) { p = getParticleFirstFrame(i); pd = getParticleDetail(i); distance(zero, p->vel, velSpeed); d = velSpeed / velMax; colourFromNormal(pd->col, (float)fabs((double)d)); pd->particleSprite = colourSprite(pd->col, pd->mass); } }
int FixedDictionaryAdd( struct FixedDictionary* self, void* key, void* value) { if (!self || !key || !value) { errno = EINVAL; return EINVAL; } if (self->_count >= self->_capacity) { errno = EINVAL; return EINVAL; } size_t hashCode = FixedDictionaryHashFn(key, self->_keySize); size_t bucketIndex = hashCode % self->_capacity; if (self->_buckets[bucketIndex] == NULL) { self->_buckets[bucketIndex] = calloc(1, sizeof(struct Vector)); VectorNew(self->_buckets[bucketIndex], sizeof(struct Slot), NULL); } else { size_t collCount = VectorGetCount(self->_buckets[bucketIndex]); for (size_t i = 0; i < collCount; ++i) { struct Slot slot; VectorGet(self->_buckets[bucketIndex], i, &slot); if (memcmp(slot.key, key, self->_keySize) == 0) { return 0; } } } struct Slot slot; SlotNew(&slot, self, key, value, hashCode); VectorAdd(self->_buckets[bucketIndex], &slot); ++self->_count; return 1; }
void particleInterpolate(int i, float t, float *v) { particle_t *p1; particle_t *p2; VectorNew(moo); p1 = state.particleHistory + state.particleCount * state.currentFrame + i; if (state.currentFrame == state.historyFrames || state.historyFrames == 0 || state.mode & SM_RECORD) { VectorCopy(p1->pos, v); return; } p2 = state.particleHistory + state.particleCount * (state.currentFrame+1) + i; VectorSub(p1->pos, p2->pos, moo); VectorMultiply(moo, t, moo); VectorAdd(p1->pos, moo, v); }
void WordCountEnter(hashset *wordCount, const char *word, const char *articleTitle, const char *articleURL) { /** * Three possible cases: * 1. Word has not been entered * 2. Word has been entered, but word/article combination has not * 3. Word/article combination has been entered */ wordSet *existingWord = (wordSet *) HashSetLookup(wordCount, &word); // ensure that the word exists in the hashset if (existingWord == NULL) { wordSet ws; ws.word = strdup(word); VectorNew(&ws.occ, sizeof(articleCount), articleCountFreeFn, 25); HashSetEnter(wordCount, &ws); } // an entry for the word should always exist now existingWord = (wordSet *) HashSetLookup(wordCount, &word); assert(existingWord != NULL); // now either add the article to the word count vector or increment its current count articleCount articleKey = { { (char *) articleTitle, (char *) articleURL }, 1 }; int existingArticleIndex = VectorSearch(&existingWord->occ, &articleKey, articleCountCompareFn, 0, false); if (existingArticleIndex == -1) { // word/article pairing is new, append it to the vector with a count of 1 articleCount newArticle; (newArticle.source).title = strdup(articleTitle); (newArticle.source).url = strdup(articleURL); newArticle.count = 1; VectorAppend(&existingWord->occ, &newArticle); } else { // word/article pairing exists, increment its count articleCount *existingArticle = (articleCount *) VectorNth(&existingWord->occ, existingArticleIndex); existingArticle->count++; } }
static void MemoryTest() { int i; const char * const kQuestionWords[] = {"who", "what", "where", "how", "why"}; const int kNumQuestionWords = sizeof(kQuestionWords) / sizeof(kQuestionWords[0]); vector questionWords; char *questionWord; fprintf(stdout, "\n\n------------------------- Starting the memory tests...\n"); fprintf(stdout, "Creating a vector designed to store dynamically allocated C-strings.\n"); VectorNew(&questionWords, sizeof(char *), FreeString, kNumQuestionWords); fprintf(stdout, "Populating the char * vector with the question words.\n"); for (i = 0; i < kNumQuestionWords; i++) { questionWord = malloc(strlen(kQuestionWords[i]) + 1); strcpy(questionWord, kQuestionWords[i]); VectorInsert(&questionWords, &questionWord, 0); // why the ampersand? isn't questionWord already a pointer? } fprintf(stdout, "Mapping over the char * vector (ask yourself: why are char **'s passed to PrintString?!!)\n"); VectorMap(&questionWords, PrintString, stdout); fprintf(stdout, "Finally, destroying the char * vector.\n"); VectorDispose(&questionWords); }
static void AddWordToIndices(hashset *indices, const char *word, int articleIndex) { rssIndexEntry indexEntry = { word }; // partial intialization rssIndexEntry *existingIndexEntry = HashSetLookup(indices, &indexEntry); if (existingIndexEntry == NULL) { indexEntry.meaningfulWord = strdup(word); VectorNew(&indexEntry.relevantArticles, sizeof(rssRelevantArticleEntry), NULL, 0); HashSetEnter(indices, &indexEntry); existingIndexEntry = HashSetLookup(indices, &indexEntry); // pretend like it's been there all along assert(existingIndexEntry != NULL); } rssRelevantArticleEntry articleEntry = { articleIndex, 0 }; int existingArticleIndex = VectorSearch(&existingIndexEntry->relevantArticles, &articleEntry, ArticleIndexCompare, 0, false); if (existingArticleIndex == -1) { VectorAppend(&existingIndexEntry->relevantArticles, &articleEntry); existingArticleIndex = VectorLength(&existingIndexEntry->relevantArticles) - 1; } rssRelevantArticleEntry *existingArticleEntry = VectorNth(&existingIndexEntry->relevantArticles, existingArticleIndex); existingArticleEntry->freq++; }
void calculateNext(hashset *hash, vector* keys, int k, char* f, int size) { int currK, i, elems = 0, seedNumber; char *nxt, *cnt, *key2, *storage = (char*)malloc(sizeof(char) * k); FILE *fileR; vectorv keyNext; keysv *rs, key; k+=1; fileR = fopen(f, "r"); assert(fileR != NULL && "Cannot open the file"); VectorNew(keys, sizeof(char*) * k, NULL, 10); while (fgets(storage, k, fileR) != NULL) { currK = strlen(storage); if (currK < k && storage[currK - 1] == '\n') { fgets(&storage[currK], k - currK, fileR); } VectorAppend(keys, storage); } storage = (char*)VectorNth(keys, keys->currentPosition - 1); fclose(fileR); HashSetNew(hash, sizeof(keysv), keys->currentPosition * 3, hashVector, cmpVector, NULL); for (i = 0; i < (keys->currentPosition - 1); i++) { rs = (keysv*)malloc(sizeof(keysv)); vector nexts; cnt = VectorNth(keys, i); nxt = VectorNth(keys, i + 1); rs->string = strdup(cnt); rs = (keysv*)HashSetLookup(hash, rs); keyNext.string = nxt; key.string = cnt; if (rs == NULL) { keyNext.frecuency = 1; VectorNew(&nexts, sizeof(vectorv), NULL, 1); VectorAppend(&nexts, &keyNext); key.frecuency = 1; key.vectorv = nexts; key.amount = 1; HashSetEnter(hash, &key); } else { rs->frecuency++; rs->amount++; vectorv* rSucessor; int idx = VectorSearch(&rs->vectorv, &keyNext, cmpvct, 0, false); if (idx >= 0) { rSucessor = VectorNth(&rs->vectorv, idx); rSucessor->frecuency++; } else { keyNext.frecuency = 1; VectorAppend(&rs->vectorv, &keyNext); } } } key.string = VectorNth(keys, keys->currentPosition - 1); key.frecuency = 1; key.amount = 0; HashSetEnter(hash, &key); if (k == 0) { elems = keys->currentPosition; } else { HashSetMap(hash, mapFn, &elems); } seedNumber = rand() % elems; key2 = (char*)VectorNth(keys, seedNumber); printf("Generated text:\n"); printf("%s", key2); if (k > 0) { for (i = 0; i < size;) { key2 = ran(hash, keys, key2); printf("%s", key2); if (strstr(key2, " ") != NULL || strstr(key2, "\n") != NULL) { i++; } } } else { for (i = 0; i < size;) { seedNumber = rand() % elems; key2 = (char*)VectorNth(keys, seedNumber); printf("%s", key2); if (strstr(key2, " ") != NULL || strstr(key2, "\n") != NULL) { i++; } } } printf("\n"); }
void drawFrame() { particle_t *p; particleDetail_t *pd; int i,j,k; float c; float sc[4]; if (!state.particleHistory) return; switch (view.blendMode) { case 0: glDisable(GL_BLEND); break; case 1: glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; case 2: glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; case 3: glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA_SATURATE, GL_ONE); break; case 4: glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA_SATURATE, GL_ONE_MINUS_SRC_ALPHA); break; } if (view.particleRenderMode == 0) { float pointRange[2]; glDisable(GL_DEPTH_TEST); glBindTexture(GL_TEXTURE_2D, 0); glEnable(GL_POINT_SMOOTH); glGetFloatv(GL_POINT_SIZE_RANGE, pointRange); if (view.particleSizeMin < pointRange[0]) { view.particleSizeMin = pointRange[0]; conAdd(LNORM, "Point Size has reached its minimum of %f", view.particleSizeMin); } if (view.particleSizeMin > pointRange[1]) { view.particleSizeMin = pointRange[1]; conAdd(LNORM, "Point Size has reached its maximum of %f", view.particleSizeMin); } glPointSize(view.particleSizeMin); } if (view.particleRenderMode == 1) { float quadratic[] = { 0.0f, 0.0f, 0.01f }; if (!video.supportPointParameters || !video.supportPointSprite) { conAdd(LNORM, "Sorry, Your video card does not support GL_ARB_point_parameters and/or GL_ARB_point_sprite."); conAdd(LNORM, "This means you can't have really pretty looking particles."); conAdd(LNORM, "Setting particleRenderMode to 2"); view.particleRenderMode = 2; return; } glDisable(GL_DEPTH_TEST); glDisable(GL_POINT_SMOOTH); // enabling this makes particles dissapear glPointParameterfvARB_ptr( GL_POINT_DISTANCE_ATTENUATION_ARB, quadratic ); glPointParameterfARB_ptr( GL_POINT_SIZE_MAX_ARB, view.particleSizeMax ); glPointParameterfARB_ptr( GL_POINT_SIZE_MIN_ARB, view.particleSizeMin ); glPointSize( view.particleSizeMax ); // lets you put textures on the sprite // doesn't work on some cards for some reason :( // so i had to make textures an option with this mode if (view.particleRenderTexture) { glTexEnvf( GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE ); glBindTexture(GL_TEXTURE_2D, particleTextureID); } else { glBindTexture(GL_TEXTURE_2D, 0); } glEnable( GL_POINT_SPRITE_ARB ); } else if (view.particleRenderMode == 2) { glDisable(GL_DEPTH_TEST); if (view.particleRenderTexture) { glBindTexture(GL_TEXTURE_2D, particleTextureID); } else { glBindTexture(GL_TEXTURE_2D, 0); } } if (view.particleRenderMode == 0 || view.particleRenderMode == 1) { glBegin(GL_POINTS); for (i = 0; i < state.particleCount; i++) { VectorNew(pos); pd = state.particleDetail + i; glColor4fv(pd->col); if (view.frameSkip < 0) { particleInterpolate(i, ((float)view.frameSkipCounter / view.frameSkip), pos); glVertex3fv(pos); } else { p = state.particleHistory + state.particleCount * state.currentFrame + i; glVertex3fv(p->pos); } view.vertices++; } glEnd(); } else if (view.particleRenderMode == 2) { // my math mojo is not so great, so this may not be the most efficient way of doing this // this whole bit is dodgy too, as long as it works :) GLdouble matProject[16]; GLdouble matModelView[16]; GLint viewport[4]; GLdouble screen[3]; glMatrixMode(GL_PROJECTION); glPushMatrix(); glCheck(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glCheck(); glGetDoublev(GL_PROJECTION_MATRIX, matProject); glCheck(); glGetDoublev(GL_MODELVIEW_MATRIX, matModelView); glCheck(); glGetIntegerv(GL_VIEWPORT, viewport); glCheck(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (view.stereoMode == 1) { if (view.stereoModeCurrentBit == 0) { glOrtho(0.0,video.screenW/2,0,video.screenH,-1.0,1.0); } else { glOrtho(video.screenW/2,video.screenW,0,video.screenH,-1.0,1.0); } } else { glOrtho(0.0f,video.screenW,0,video.screenH,-1.0f,1.0f); } glCheck(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glCheck(); for (i = 0; i < state.particleCount; i++) { double size; VectorNew(moo); float *pos; int success; pos = moo; pd = state.particleDetail + i; if (view.frameSkip < 0) { particleInterpolate(i, ((float)view.frameSkipCounter / view.frameSkip), moo); } else { p = state.particleHistory + state.particleCount * state.currentFrame + i; pos = p->pos; } success = gluProject( pos[0],pos[1],pos[2], matModelView, matProject, viewport, &screen[0], &screen[1], &screen[2] ); if ((success != GL_TRUE) || (screen[2] > 1)) continue; size = view.particleSizeMin + (1.f - (float)screen[2]) * view.particleSizeMax; glBegin(GL_QUADS); glColor4fv(pd->col); glTexCoord2i(0,0); glVertex2d(screen[0]-size, screen[1]-size); glTexCoord2i(1,0); glVertex2d(screen[0]+size, screen[1]-size); glTexCoord2i(1,1); glVertex2d(screen[0]+size, screen[1]+size); glTexCoord2i(0,1); glVertex2d(screen[0]-size, screen[1]+size); glEnd(); view.vertices += 4; } glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } if (view.particleRenderMode == 1 && video.supportPointParameters && video.supportPointSprite) { glDisable( GL_POINT_SPRITE_ARB ); } glBindTexture(GL_TEXTURE_2D, 0); // sc[3] = 1; if (view.tailLength > 0 || view.tailLength == -1) { // Not sure why this helps but, // it is a fix for one case where only points are drawn instead of lines // on radeon 9600 after switching to particlerendermode 0 from 1 if (view.particleRenderMode == 0) glLineWidth(view.tailWidth+1); glLineWidth(view.tailWidth); for (i = 0; i < state.particleCount; i++) { int to; p = 0; glBegin(GL_LINE_STRIP); if (view.tailLength == -1) k = 0; else if (state.currentFrame < (view.tailLength+2)) k = 0; else k = state.currentFrame - (view.tailLength+2); if (state.mode & SM_RECORD) to = state.currentFrame; else to = state.currentFrame + 1; for (j = k; j <= state.currentFrame; j+=view.tailSkip ) { //for (j = state.currentFrame; j >= k; j-=view.tailSkip ) { if (j >= state.historyFrames) continue; pd = state.particleDetail + i; if (view.tailFaded) c = (float)(j-k) / (float)(state.currentFrame-k) * view.tailOpacity; else c = view.tailOpacity; memcpy(sc, pd->col, sizeof(float)*4); sc[3] *= c; glColor4fv(sc); p = state.particleHistory + state.particleCount * j + i; glVertex3fv(p->pos); view.vertices++; } if (view.frameSkip < 0 && !(state.mode & SM_RECORD)) { VectorNew(pos); particleInterpolate(i, ((float)view.frameSkipCounter / view.frameSkip), pos); glVertex3fv(pos); } else { p = state.particleHistory + state.particleCount * state.currentFrame + i; glVertex3fv(p->pos); } glEnd(); } } }
int pickPositions() { int gals; VectorNew(galPos[100]); VectorNew(galVel[100]); VectorNew(shit); float galSize[100]; float galMassMin[100]; float galMassMax[100]; float spawnRange; int i; int g; particle_t *p; particleDetail_t *pd; float totalMass = 0; float angle; float angle2; float radius; gals = (rand() % (1 + spawnVars.maxGalCount-spawnVars.minGalCount)) + spawnVars.minGalCount; if (gals <= 0) { conAdd(LERR, "For some reason galaxies to spawn is 0 or less. Not possible!"); return 0; } if (gals >= 100) { conAdd(LERR, "Maximum galaxies to spawn is 100"); return 0; } spawnRange = frand(spawnVars.minSpawnRange, spawnVars.maxSpawnRange); conAdd(LNORM, "Spawning new simulation..."); conAdd(LLOW, "- %i particles...", state.particleCount); conAdd(LLOW, "- %i galaxies...", gals); for (g = 0; g < gals; g++) { galMassMin[g] = frand(spawnVars.minGalMass, spawnVars.maxGalMass); galMassMax[g] = frand(spawnVars.minGalMass, spawnVars.maxGalMass); galSize[g] = frand(spawnVars.minGalSize, spawnVars.maxGalSize); setRangePosition(galPos[g], spawnRange); setRangePosition(galVel[g], frand(0,1) * frand(0,1) * frand(spawnVars.minGalVel, spawnVars.maxGalVel)); } for (i = 0; i < state.particleCount; i++) { if (!(i % 100)) { view.recordParticlesDone = i; doVideoUpdateInSpawn(); } if (state.restartSpawning) { return 0; } p = getParticleFirstFrame(i); pd = getParticleDetail(i); g = rand() % gals; pd->mass = frand(galMassMin[g], galMassMax[g]); // if (g % 2 == 0) // pd->mass = -pd->mass; totalMass += pd->mass; // position VectorCopy(galPos[g], p->pos); setRangePosition((float *)&shit, galSize[g]); VectorAdd(p->pos, shit, p->pos); // galaxy structured position angle = frand(0, PI*2); radius = frand(0, galSize[g]); VectorZero(p->pos); p->pos[0] = cos(angle) * radius; p->pos[1] = sin(angle) * radius; p->pos[2] = frand(-radius/10, radius/10); VectorAdd(galPos[g], p->pos, p->pos); angle2 = angle + PI / 2; p->vel[0] = cos(angle2) * radius * 0.05f; p->vel[1] = sin(angle2) * radius * 0.05f; p->vel[2] = 0; VectorAdd(galVel[g], p->vel, p->vel); if (g & 2) { p->vel[0] = -p->vel[0]; p->vel[1] = -p->vel[1]; p->vel[2] = -p->vel[2]; } } conAdd(LLOW, "- %f total mass...", totalMass); conAdd(LLOW, "- %f galaxy mass...", totalMass / gals); conAdd(LLOW, "- %f particle mass...", totalMass / state.particleCount); return 0; }