// NOTE: This can give back a deleted hash, if it had the same key as this block, // and it was already deleted once, and wasn't overwritten since. internal block_hash * GetZeroHash(world_density *World, world_block_pos *P) { block_hash *Result = 0; uint32 HashValue = GetZeroHashValue(P); uint32 HashMask = (ArrayCount(World->ZeroHash) - 1); for(uint32 Offset = 0; Offset < ArrayCount(World->ZeroHash); ++Offset) { uint32 HashIndex = (HashValue + Offset) & HashMask; Assert(HashIndex < ArrayCount(World->ZeroHash)); block_hash *Hash = World->ZeroHash + HashIndex; // NOTE: return hash, if its uninited, or it has the position we are looking for if(Hash->Index == HASH_UNINITIALIZED || WorldPosEquals(P, &Hash->Key)) { Result = Hash; break; } } Assert(Result); return Result; }
const char* toString(MemoryStack* tmpMemory, TokenType token) { switch (token) { case TOK_IDENTIFIER: return "identifier"; case TOK_STRING_LITERAL: return "string literal"; case TOK_NUMBER_CONSTANT: return "number constant"; case TOK_UNKNOWN: return ""; case TOK_EOF: return "end of file"; default: { for (int i = 0; i < ArrayCount(operatorTokens); ++i) { if (token == operatorTokens[i].tokenIndex) { return operatorTokens[i].stringValue; } } for (int i = 0; i < ArrayCount(keywords); ++i) { if (token == (TokenType)(i + KEYWORDS_STARTS_AT)) { return keywords[i]; } } assert(!"can't convert token type to string"); return ""; }; } }
void PrintTimeStamp(FILE *OutputFile, char *TimeStamp) { int TokenArray[3]; int TokenCount = 0; char *Token = strtok(TimeStamp,":"); while (Token) { TokenArray[TokenCount++] = atoi(Token); Token = strtok(0, ":"); } if (TokenCount == 2) { TokenArray[2] = TokenArray[1]; TokenArray[1] = TokenArray[0]; TokenArray[0] = 0; } int EndTokenArray[3]; int CarryOut = 0; int ElapsedSecond = 8; for (int Index = ArrayCount(EndTokenArray) - 1; Index >= 0; --Index) { int Result = (TokenArray[Index] + ((Index == ArrayCount(EndTokenArray) - 1)? ElapsedSecond : CarryOut)); EndTokenArray[Index] = Result % 60; CarryOut = Result / 60; } // TODO(wheatdog): 5 seconds long to display the subtitles fprintf(OutputFile, "%02d:%02d:%02d,000 --> %02d:%02d:%02d,000\n", TokenArray[0], TokenArray[1], TokenArray[2], EndTokenArray[0], EndTokenArray[1], EndTokenArray[2]); }
void Fitness() { int score = 0; for (int i = 0; i < ArrayCount(genes); i++) { if (genes[i] == target[i]) { score++; } } fitness = (float)score / ArrayCount(genes); }
DNA crossover(DNA partner) { DNA child = DNA(); int midpoint = int(ofRandom(0, ArrayCount(genes))); for (int i = 0; i < ArrayCount(genes); i++) { if (i > midpoint)child.genes[i] = genes[i]; else child.genes[i] = partner.genes[i]; } return child; }
DNA() { for (int i = 0; i < ArrayCount(genes); i++) { genes[i] = (char)ofRandom(32, 128); } }
void PositionNormalPrePass::bindForWriting(Platform *platform, RenderContext *render_context) { RenderTexture *rts[] = { &normal, &position, }; render_context->bindRenderTextures(platform, rts, ArrayCount(rts), 0, true); }
internal void hhxcb_init_replays(hhxcb_state *state) { for (uint8 index = 0; index < ArrayCount(state->replay_buffers); ++index) { hhxcb_replay_buffer *replay_buffer = &state->replay_buffers[index]; hhxcb_get_input_file_location(state, false, index, sizeof(replay_buffer->filename), replay_buffer->filename); replay_buffer->file_handle = open(replay_buffer->filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); int truncate_succeeded = ftruncate(replay_buffer->file_handle, state->total_size); if (truncate_succeeded == -1) { perror("ftruncate"); } replay_buffer->memory_block = mmap(0, state->total_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_POPULATE, replay_buffer->file_handle, 0); if (replay_buffer->memory_block == MAP_FAILED) { perror("mmap"); } } }
internal void UpdateLowerBlocksMapping(world_density *World, world_block_pos *BlockP, int32 ResMapping) { uint32 ResIndex = GetResolutionIndex(BlockP->Resolution); if(ResIndex < RESOLUTION_COUNT-1) { lower_blocks LowerBlocks; GetLowerResBlockPositions(&LowerBlocks, BlockP); for(int32 LowerIndex = 0; LowerIndex < ArrayCount(LowerBlocks.Pos); LowerIndex++) { world_block_pos *LowerP = LowerBlocks.Pos + LowerIndex; block_hash *ResHash = GetHash(World->ResolutionMapping, LowerP); if(HashIsEmpty(ResHash)) { MapBlockPosition(World, LowerP, ResMapping); } else { ResHash->Index = ResMapping; } Assert(ResHash->Index == ResMapping); } } }
internal win32_replay_buffer *Win32GetReplayBuffer(win32_state *State, int unsigned Index) { Assert(Index > 0); Assert(Index < ArrayCount(State->ReplayBuffers)); win32_replay_buffer *Result = &State->ReplayBuffers[Index]; return(Result); }
internal hhxcb_replay_buffer * hhxcb_get_replay_buffer(hhxcb_state *state, uint8 index) { Assert(index < ArrayCount(state->replay_buffers)); hhxcb_replay_buffer *result = &state->replay_buffers[index]; return result; }
void parseNextToken(LexerCarriage* carriage) { skipDelimiters(carriage); if (carriage->posInText < carriage->lexingText.length) { bool(*functions[])(LexerCarriage*, Token*) = { parseNumber, parseOperatorToken, parseKeywordOrIdentifier, parseUnknown // if we coudn't parse this, we'll just return it as a 'unknown' token }; for (int i = 0; i < ArrayCount(functions); ++i) { if (functions[i](carriage, &carriage->topToken)) { break; } } } else { carriage->topToken = Token{ TOK_EOF }; } skipComment(carriage); }
void OSXAddEntry(platform_work_queue* Queue, platform_work_queue_callback* Callback, void* Data) { // TODO(casey): Switch to InterlockedCompareExchange eventually // so that any thread can add? uint32 NewNextEntryToWrite = (Queue->NextEntryToWrite + 1) % ArrayCount(Queue->Entries); Assert(NewNextEntryToWrite != Queue->NextEntryToRead); platform_work_queue_entry *Entry = Queue->Entries + Queue->NextEntryToWrite; Entry->Callback = Callback; Entry->Data = Data; ++Queue->CompletionGoal; OSMemoryBarrier(); // Not needed: _mm_sfence(); Queue->NextEntryToWrite = NewNextEntryToWrite; dispatch_semaphore_signal(Queue->SemaphoreHandle); #if 0 int r = dispatch_semaphore_signal(Queue->SemaphoreHandle); if (r > 0) { printf(" dispatch_semaphore_signal: A thread was woken\n"); } else { printf(" dispatch_semaphore_signal: No thread was woken\n"); } #endif }
bool32 OSXDoNextWorkQueueEntry(platform_work_queue* Queue) { bool32 WeShouldSleep = false; uint32 OriginalNextEntryToRead = Queue->NextEntryToRead; uint32 NewNextEntryToRead = (OriginalNextEntryToRead + 1) % ArrayCount(Queue->Entries); if(OriginalNextEntryToRead != Queue->NextEntryToWrite) { // NOTE(jeff): OSAtomicCompareAndSwapXXX functions return 1 if the swap took place, 0 otherwise! uint32 SwapOccurred = OSAtomicCompareAndSwapIntBarrier(OriginalNextEntryToRead, NewNextEntryToRead, (int volatile*)&Queue->NextEntryToRead); if (SwapOccurred) { platform_work_queue_entry Entry = Queue->Entries[OriginalNextEntryToRead]; Entry.Callback(Queue, Entry.Data); //InterlockedIncrement((int volatile *)&Queue->CompletionCount); OSAtomicIncrement32Barrier((int volatile *)&Queue->CompletionCount); } else { } } else { WeShouldSleep = true; } return(WeShouldSleep); }
void writeEntireFile(String filename, Buffer* buffer, Error* error) { assert(buffer != NULL); assert(buffer->data != NULL); assert(buffer->used >= 0); char cFilename[260]; filename.toCString(cFilename, ArrayCount(cFilename)); FILE* f = fopen(cFilename, "wb"); if (f == 0) { print("writeEntireFile:: Unable to open file for writing. File = %s\n", &filename); if (error) { error->errorCode = FILE_CANT_OPEN; } return; } s32 bytesWritten = fwrite(buffer->data, sizeof(char), buffer->used, f); if (bytesWritten != buffer->used) { print("writeEntireFile:: Failed to write. File = %s\n", &filename); if (error) { error->errorCode = FILE_NO_WRITE; } return; } fclose(f); }
// TODO: Deleting blocks shouldn't be here internal void DowngradeMapping(world_density *World, world_block_pos *BlockP, int32 MappingValue, world_block_pos *DeleteQueue, int32 *DeleteCount) { uint32 ResIndex = GetResolutionIndex(BlockP->Resolution); if(ResIndex < RESOLUTION_COUNT-1) { lower_blocks LowerBlocks; GetLowerResBlockPositions(&LowerBlocks, BlockP); for(int32 LowerIndex = 0; LowerIndex < ArrayCount(LowerBlocks.Pos); LowerIndex++) { world_block_pos *LowerP = LowerBlocks.Pos + LowerIndex; DowngradeMapping(World, LowerP, MappingValue, DeleteQueue, DeleteCount); } block_hash *ResHash = GetHash(World->ResolutionMapping, BlockP); if(!HashIsEmpty(ResHash)) { Assert(ResHash->Index < MappingValue); ResHash->Index = MappingValue; } DeleteQueue[*DeleteCount] = *BlockP; (*DeleteCount)++; } }
//-------------------------------------------------------------- void ofApp::setup() { for (int i = 0; i < ArrayCount(population); i++) { population[i] = DNA(); } myFont.loadFont("LiberationMono-Regular.ttf", 12); }
static osx_replay_buffer* OSXGetReplayBuffer(osx_state* State, int unsigned Index) { Assert(Index < ArrayCount(State->ReplayBuffers)); osx_replay_buffer* Result = &State->ReplayBuffers[Index]; return Result; }
void PrintHelp() { int32 maxdays = ArrayCount(DayList); printf("Usage: \n"); printf(" advent <day>\n\n"); printf("<day> - A day between 1 and %d, or 0 for output from all days.", maxdays); }
internal void GameUpdateAndRender(game_memory *Memory, game_input *Input, game_offscreen_buffer *Buffer) { Assert(sizeof(game_state) <= Memory->PermanentStorageSize); game_state *GameState = (game_state *) Memory->PermanentStorage; if (!Memory->IsInitialized) { char *Filename = __FILE__; debug_read_file_result File = DEBUGPlatformReadEntireFile(Filename); if (File.Contents) { DEBUGPlatformWriteEntireFile("test.out", File.ContentsSize, File.Contents); DEBUGPlatformFreeFileMemory(File.Contents); } GameState->ToneHz = 512; Memory->IsInitialized = true; } for (int ControllerIndex = 0; ControllerIndex < ArrayCount(Input->Controllers); ++ControllerIndex) { game_controller_input *Controller = GetController(Input, ControllerIndex); if (Controller->IsAnalog) { // Use analog movement tuning. GameState->BlueOffset += (int) (4.0f * Controller->StickAverageX); GameState->ToneHz = 512 + (int) (128.0f * Controller->StickAverageY); } else { // Use digital movement tuning. if (Controller->MoveLeft.EndedDown) { GameState->BlueOffset -= 1; } if (Controller->MoveRight.EndedDown) { GameState->BlueOffset += 1; } } // Input.AButtonEndedDown; // Input.AButtonHalfTransitionCount; if (Controller->ActionDown.EndedDown) { GameState->GreenOffset += 1; } } RenderWeirdGradient(Buffer, GameState->BlueOffset, GameState->GreenOffset); }
int main(int argc, char *argv[]) { memory_arena Arena = {}; InitializeArena(&Arena, (size_t)Gigabytes(1)); // freopen("err.log", "w", stderr); if(argc == 1) { int32 day = ArrayCount(DayList)-1; DayList[day](&Arena, true); } else if (argc == 2) { int32 day = (int32) strtol(argv[1], &argv[1], 0); if(day && day <ArrayCount(DayList)) { DayList[day](&Arena, true); } else if (day == 0) { printf("Running All Days.\n"); for (int32 i = 1; i < ArrayCount(DayList); ++i) { printf("---- Day %d ----\n", i); DayList[i](&Arena, false); ResetArena(&Arena); printf("\n"); } } else { PrintHelp(); } } else { PrintHelp(); } FreeArena(&Arena); }
void mutate() { for (int i = 0; i < ArrayCount(genes); i++) { if (ofRandom(0, 1) < mutationRate) { genes[i] = (char)ofRandom(32, 128); } } }
static bool isDelimiter(char ch) { for (int i = 0; i < ArrayCount(delimiters); ++i) { if (delimiters[i] == ch) return true; } return false; }
void TransformAndOutput(FILE *InputFile, FILE *OutputFile) { int FindThreeDashTimes = 0; char Line[1024]; int Number = 1; while (FindThreeDashTimes != 2) { if (!fgets(Line, ArrayCount(Line), InputFile)) { break; } if (strncmp(Line, "---", 2) == 0) { ++FindThreeDashTimes; continue; } char *TestLine = Line; char *QuoteMark[4]; int QuoteMarkCount = 0; while((QuoteMarkCount < 4) && (QuoteMark[QuoteMarkCount] = strchr(TestLine, '\"'))) { TestLine = QuoteMark[QuoteMarkCount] + 1; if ((QuoteMarkCount == 3) && (*(QuoteMark[QuoteMarkCount] - 1) == '\\')) { char *ShiftStart = QuoteMark[QuoteMarkCount]--; while (*ShiftStart != '\0') { *(ShiftStart - 1) = *ShiftStart; ++ShiftStart; } *(ShiftStart - 1) = *ShiftStart; continue; } ++QuoteMarkCount; } if (QuoteMarkCount != 4) { continue; } char *TimeStamp = QuoteMark[0] + 1; *(QuoteMark[1]) = '\0'; char *Comment = QuoteMark[2] + 1; *(QuoteMark[3]) = '\0'; fprintf(OutputFile, "%d\n", Number++); PrintTimeStamp(OutputFile, TimeStamp); fprintf(OutputFile, "%s\n\n", Comment); } }
static void convertToKeywordIfItIs(StringSlice slice, Token* result) { for (int i = 0; i < ArrayCount(keywords); ++i) { if (slice == makeSlice(keywords[i])) { result->type = (TokenType)(KEYWORDS_STARTS_AT + i); break; } } }
internal_func void generateMap() { u32 map_height = ArrayCount(g_color_lookups); FastNoise noise_gen; noise_gen.SetSeed(time(0)); for(int z = 0; z < MAP_SIZE; z++) { for(int x = 0; x < MAP_SIZE; x++) { float noise = (noise_gen.GetValueFractal(x, z) + 1.0f) * 0.5f; u8 y = (u8)(noise * map_height); g_map[z][x] = y; } } }
internal void InitZeroHash(world_density *World) { World->ZeroBlockCount = 0; for(uint32 HashIndex = 0; HashIndex < ArrayCount(World->ZeroHash); ++HashIndex) { block_hash *Hash = World->ZeroHash + HashIndex; Hash->Index = HASH_UNINITIALIZED; } }
//-------------------------------------------------------------- void ofApp::draw() { if (!foundSolution) { for (int i = 0; i < ArrayCount(population); i++) { population[i].Fitness(); } vector<DNA> matingPool = vector<DNA>(); for (int i = 0; i < ArrayCount(population); i++) { int n = int(population[i].fitness * ArrayCount(population)); for (int k = 0; k < n; k++) { matingPool.push_back(population[i]); } } for (int i = 0; i < ArrayCount(population); i++) { int a = int(ofRandom(0, matingPool.size())); int b = int(ofRandom(0, matingPool.size())); DNA parentA = matingPool[a]; DNA parentB = matingPool[b]; DNA child = parentA.crossover(parentB); child.mutate(); population[i] = child; } } ofClear(ofColor::white); ofSetColor(ofColor::black); for (int i = 0; i < ArrayCount(population); i++) { //string str = population[i].genes; population[i].genes[ArrayCount(population[i].genes)] = '\0'; if (population[i].genes == target) { foundSolution = true; ofNoFill(); ofSetLineWidth(6); ofSetCurveResolution(200); ofCircle(ofPoint((int(i / POPULATION_PER_COLUMN) * Y_SPACING) + 100, ((i % POPULATION_PER_COLUMN) * X_SPACING) + BUFFER_SPACING), 120); } myFont.drawString(population[i].genes, (int(i / POPULATION_PER_COLUMN) * Y_SPACING) + BUFFER_SPACING, ((i % POPULATION_PER_COLUMN) * X_SPACING) + BUFFER_SPACING); } }
internal void InitResolutionMapping(world_density *World) { World->BlockMappedCount = 0; for(uint32 HashIndex = 0; HashIndex < ArrayCount(World->ResolutionMapping); ++HashIndex) { block_hash *Hash = World->ResolutionMapping + HashIndex; Hash->Index = HASH_UNINITIALIZED; } }
internal void SDLAddEntry(platform_work_queue *Queue, platform_work_queue_callback *Callback, void *Data) { int NewNextEntryToWrite = (Queue->NextEntryToWrite.value + 1 ) % ArrayCount(Queue->Entries); Assert(NewNextEntryToWrite != Queue->NextEntryToRead.value); platform_work_queue_entry *Entry = Queue->Entries + Queue->NextEntryToWrite.value; Entry->Callback = Callback; Entry->Data = Data; ++Queue->CompletionGoal; SDL_CompilerBarrier(); Queue->NextEntryToWrite.value = NewNextEntryToWrite; SDL_SemPost(Queue->Sem); }