diff --git a/.gitignore b/.gitignore index 71207d9..ddc6d87 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ .DS_Store +tags + handmadehero handmadehero.dSYM libhandmade.so diff --git a/Makefile b/Makefile index e85d1e8..8ebda66 100644 --- a/Makefile +++ b/Makefile @@ -45,7 +45,7 @@ endif EXE=handmadehero -default: libhandmade $(EXE) +default: tags libhandmade $(EXE) libhandmade: handmade.c @ $(CC) $(FLAGS) $(UFLAGS) -fPIC -shared $(INCLUDE) $^ $(LIBS) $(FRAMEWORKS) -o libhandmade.so @@ -57,7 +57,7 @@ run: @ ./$(EXE) tags: $(OBJS) - ctags -R *.h *.c + @ ctags -R *.h *.c clean: - @rm -rf $(EXE) $(EXE).dSYM libhandmade.so libhandmade.so.dSYM + @rm -rf $(EXE) $(EXE).dSYM libhandmade.so libhandmade.so.dSYM tags diff --git a/core.h b/core.h index abe49f8..2fb0eb6 100644 --- a/core.h +++ b/core.h @@ -1,8 +1,6 @@ #ifndef CORE_H #define CORE_H -#include - /* ---- Switches ------------------------------------------------------- */ #ifndef BUILD_DEBUG @@ -18,7 +16,7 @@ /* Architecture */ #ifndef ARCHITECTURE_X64 -#define ARCHITECTURE_X64 0 +#define ARCHITECTURE_X64 1 #endif #ifndef ARCHITECTURE_X86 @@ -33,24 +31,12 @@ #define ARCHITECTURE_ARM32 0 #endif -#if defined(__x86_64__) || defined(__x86_64) || defined(__amd64__) || defined(__amd64) || defined(_M_AMD64) -#undef ARCHITECTURE_X64 -#define ARCHITECTURE_X64 1 -#elif defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_I86) -#undef ARCHITECTURE_X86 -#define ARCHITECTURE_X86 1 -#elif defined(__aarch64__) -#undef ARCHITECTURE_ARM64 -#define ARCHITECTURE_ARM64 1 -#elif defined(__arm__) -#undef ARCHITECTURE_ARM32 -#define ARCHITECTURE_ARM32 1 -#else -#error Unknown architecture . . . -#endif - /* OS */ +#ifndef OS_LINUX +#define OS_LINUX 1 +#endif + #ifndef OS_WINDOWS #define OS_WINDOWS 0 #endif @@ -59,81 +45,26 @@ #define OS_MACOS 0 #endif -#ifndef OS_LINUX -#define OS_LINUX 0 -#endif - -#if defined(_WIN32) -#undef OS_WINDOWS -#define OS_WINDOWS 1 -#elif defined(__APPLE__) && defined(__MACH__) -#undef OS_MACOS -#define OS_MACOS 1 -#elif defined(__linux__) -#undef OS_LINUX -#define OS_LINUX 1 -#else -#error Unknown operating system . . . -#endif - /* Compiler */ +#ifndef COMPILER_CLANG +#define COMPILER_CLANG 1 +#endif + #ifndef COMPILER_MSVC #define COMPILER_MSVC 0 #endif -#ifndef COMPILER_CLANG -#define COMPILER_CLANG 0 -#endif - #ifndef COMPILER_GCC #define COMPILER_GCC 0 #endif -#if _MSC_VER -#undef COMPILER_MSVC -#define COMPILER_MSVC 1 -#elif __clang__ -#undef COMPILER_CLANG -#define COMPILER_CLANG 1 -#elif __GNUC__ -#undef COMPILER_GCC -#define COMPILER_GCC 1 -#else -#error Unknown compiler . . . -#endif - -/* ---- Types ---------------------------------------------------------- */ - -#ifndef TRUE -#define TRUE 1 -#endif - -#ifndef FALSE -#define FALSE 0 -#endif - -typedef uint8_t U8; -typedef uint16_t U16; -typedef uint32_t U32; -typedef uint64_t U64; -typedef int8_t S8; -typedef int16_t S16; -typedef int32_t S32; -typedef int64_t S64; -typedef S8 B8; -typedef S16 B16; -typedef S32 B32; -typedef S64 B64; -typedef float F32; -typedef double F64; - /* ---- Units ---------------------------------------------------------- */ -#define KB(n) (((U64)(n)) << 10) -#define MB(n) (((U64)(n)) << 20) -#define GB(n) (((U64)(n)) << 30) -#define TB(n) (((U64)(n)) << 40) +#define KB(n) (((unsigned long long)(n)) << 10) +#define MB(n) (((unsigned long long)(n)) << 20) +#define GB(n) (((unsigned long long)(n)) << 30) +#define TB(n) (((unsigned long long)(n)) << 40) /* ---- Clamps, Min/Max ------------------------------------------------ */ diff --git a/handmade.c b/handmade.c index 6fb599f..8c6727b 100644 --- a/handmade.c +++ b/handmade.c @@ -11,11 +11,13 @@ #include #include /* memset */ -static void GameOutputSound(game_state *GameState, game_sound_output_buffer *SoundBuffer, S32 ToneHz) +static void GameOutputSound(struct game_state *GameState, + struct game_sound_output_buffer *SoundBuffer, + int ToneHz) { /* - S16 ToneVolume, *SampleOut; - S32 WavePeriod, SampleIndex; + short ToneVolume, *SampleOut; + int WavePeriod, SampleIndex; ToneVolume = 0; WavePeriod = SoundBuffer->SamplesPerSecond / ToneHz; @@ -26,42 +28,44 @@ static void GameOutputSound(game_state *GameState, game_sound_output_buffer *Sou SampleIndex < SoundBuffer->SampleCount; SampleIndex++) { - F32 SineValue; - S16 SampleValue; + float SineValue; + short SampleValue; SineValue = sinf(GameState->tSine); - SampleValue = (S16)(SineValue * ToneVolume); + SampleValue = (short)(SineValue * ToneVolume); *SampleOut++ = SampleValue; *SampleOut++ = SampleValue; - GameState->tSine += 2.0f * (F32)PI * 1.0f / (F32)WavePeriod; - if(GameState->tSine > 2.0f*(F32)PI) { - GameState->tSine -= 2.0f*(F32)PI; + GameState->tSine += 2.0f * (float)PI * 1.0f / (float)WavePeriod; + if(GameState->tSine > 2.0f*(float)PI) { + GameState->tSine -= 2.0f*(float)PI; } } */ } -static void ClearBackground(game_offscreen_buffer *Buffer) +static void ClearBackground(struct game_offscreen_buffer *Buffer) { - S32 Width = Buffer->Width; - S32 Height = Buffer->Height; + int Width = Buffer->Width; + int Height = Buffer->Height; - for(S32 X = 0; X < Width * Height; X++) { - U32 *Pixel = &((U32 *)Buffer->Memory)[X]; + for(int X = 0; X < Width * Height; X++) { + unsigned int *Pixel = &((unsigned int *)Buffer->Memory)[X]; *Pixel = 0xFFFFFF; } } -static void DrawRectangle(game_offscreen_buffer *Buffer, v2 vMin, v2 vMax, F32 R, F32 G, F32 B) +static void DrawRectangle(struct game_offscreen_buffer *Buffer, + struct v2 vMin, struct v2 vMax, + float R, float G, float B) { - S32 MinX = RoundF32toS32(vMin.X); - S32 MinY = RoundF32toS32(vMin.Y); - S32 MaxX = RoundF32toS32(vMax.X); - S32 MaxY = RoundF32toS32(vMax.Y); + int MinX = RoundFloatToInt(vMin.X); + int MinY = RoundFloatToInt(vMin.Y); + int MaxX = RoundFloatToInt(vMax.X); + int MaxY = RoundFloatToInt(vMax.Y); - S32 Width = Buffer->Width; - S32 Height = Buffer->Height; + int Width = Buffer->Width; + int Height = Buffer->Height; if(MinX < 0) MinX = 0; @@ -73,39 +77,48 @@ static void DrawRectangle(game_offscreen_buffer *Buffer, v2 vMin, v2 vMax, F32 R if(MaxY > Height) MaxY = Height; - U32 Color = (U32)((RoundF32toS32(R * 255.0f) << 16) | (RoundF32toS32(G * 255.0f) << 8) | (RoundF32toS32(B * 255.0f) << 0)); + /*unsigned int Color = (unsigned int)((RoundFloatToInt(R * 255.0f) << 16) | + (RoundFloatToInt(G * 255.0f) << 8) | + (RoundFloatToInt(B * 255.0f) << 0));*/ + unsigned int Color = (unsigned int)((RoundFloatToInt(255.0f) << 24) | + (RoundFloatToInt(R * 255.0f) << 16) | + (RoundFloatToInt(G * 255.0f) << 8) | + (RoundFloatToInt(B * 255.0f) << 0)); - U8 *Row = ((U8 *)Buffer->Memory + MinX*Buffer->BytesPerPixel + MinY*Buffer->Pitch); - for(S32 Y = MinY; Y < MaxY; Y++) { - U32 *Pixel = (U32 *)Row; - for(S32 X = MinX; X < MaxX; X++) { - *(U32 *)Pixel = Color; + unsigned char *Row = ((unsigned char *)Buffer->Memory + + MinX*Buffer->BytesPerPixel + MinY*Buffer->Pitch); + for(int Y = MinY; Y < MaxY; Y++) { + unsigned int *Pixel = (unsigned int *)Row; + for(int X = MinX; X < MaxX; X++) { + *(unsigned int *)Pixel = Color; Pixel++; } Row += Buffer->Pitch; } } -static void DrawBitmap(game_offscreen_buffer *Buffer, loaded_bitmap *Bitmap, F32 RelX, F32 RelY, S32 AlignX, S32 AlignY) +static void DrawBitmap(struct game_offscreen_buffer *Buffer, + struct loaded_bitmap *Bitmap, + float RelX, float RelY, int AlignX, int AlignY) { - RelX -= (F32)AlignX; - RelY -= (F32)AlignY; + RelX -= (float)AlignX; + RelY -= (float)AlignY; - S32 MinX = RoundF32toS32(RelX); - S32 MinY = RoundF32toS32(RelY); - S32 MaxX = RoundF32toS32(RelX + (F32)Bitmap->Width); - S32 MaxY = RoundF32toS32(RelY + (F32)Bitmap->Height); + int MinX = RoundFloatToInt(RelX); + int MinY = RoundFloatToInt(RelY); + int MaxX = RoundFloatToInt(RelX + (float)Bitmap->Width); + int MaxY = RoundFloatToInt(RelY + (float)Bitmap->Height); - S32 Width = Buffer->Width; - S32 Height = Buffer->Height; + int Width = Buffer->Width; + int Height = Buffer->Height; - S32 SourceOffsetX = 0; + int SourceOffsetX = 0; if(MinX < 0) { SourceOffsetX = -MinX; MinX = 0; } - S32 SourceOffsetY = 0; + int SourceOffsetY = 0; if(MinY < 0) { SourceOffsetY = -MinY; MinY = 0; @@ -116,30 +129,35 @@ static void DrawBitmap(game_offscreen_buffer *Buffer, loaded_bitmap *Bitmap, F32 if(MaxY > Height) MaxY = Height; - U32 *SourceRow = Bitmap->Pixels + Bitmap->Width*(Bitmap->Height - 1); + unsigned int *SourceRow = + Bitmap->Pixels + Bitmap->Width*(Bitmap->Height - 1); SourceRow += -Bitmap->Width*SourceOffsetY + SourceOffsetX; - U8 *DestRow = ((U8 *)Buffer->Memory + MinX*Buffer->BytesPerPixel + MinY*Buffer->Pitch); - for(S32 Y = MinY; Y < MaxY; Y++) { - U32 *Dest = (U32 *)DestRow; - U32 *Source = SourceRow; - for(S32 X = MinX; X < MaxX; X++) { - F32 SA = (F32)((*Source >> 24) & 0xFF); - F32 SR = (F32)((*Source >> 16) & 0xFF); - F32 SG = (F32)((*Source >> 8) & 0xFF); - F32 SB = (F32)((*Source >> 0) & 0xFF); + unsigned char *DestRow = ((unsigned char *)Buffer->Memory + + MinX*Buffer->BytesPerPixel + MinY*Buffer->Pitch); + for(int Y = MinY; Y < MaxY; Y++) { + unsigned int *Dest = (unsigned int *)DestRow; + unsigned int *Source = SourceRow; + for(int X = MinX; X < MaxX; X++) { + float SA = (float)((*Source >> 24) & 0xFF); + float SR = (float)((*Source >> 16) & 0xFF); + float SG = (float)((*Source >> 8) & 0xFF); + float SB = (float)((*Source >> 0) & 0xFF); - F32 DR = (F32)((*Dest >> 16) & 0xFF); - F32 DG = (F32)((*Dest >> 8) & 0xFF); - F32 DB = (F32)((*Dest >> 0) & 0xFF); + float DR = (float)((*Dest >> 16) & 0xFF); + float DG = (float)((*Dest >> 8) & 0xFF); + float DB = (float)((*Dest >> 0) & 0xFF); - F32 A = SA / 255.0f; + float A = SA / 255.0f; // TODO: This should be replaced by premultiplied alpha. - F32 R = (1.0f-A)*DR + A*SR; - F32 G = (1.0f-A)*DG + A*SG; - F32 B = (1.0f-A)*DB + A*SB; + float R = (1.0f-A)*DR + A*SR; + float G = (1.0f-A)*DG + A*SG; + float B = (1.0f-A)*DB + A*SB; - *Dest = (((U32)RoundF32toS32(SA) << 24) | ((U32)RoundF32toS32(R) << 16) | ((U32)RoundF32toS32(G) << 8) | ((U32)RoundF32toS32(B) << 0)); + *Dest = (((unsigned int)RoundFloatToInt(SA) << 24) | + ((unsigned int)RoundFloatToInt(R) << 16) | + ((unsigned int)RoundFloatToInt(G) << 8) | + ((unsigned int)RoundFloatToInt(B) << 0)); Dest++; Source++; @@ -150,40 +168,47 @@ static void DrawBitmap(game_offscreen_buffer *Buffer, loaded_bitmap *Bitmap, F32 } #pragma pack(push, 1) -typedef struct bitmap_header { - U16 FileType; - U32 FileSize; - U16 Reserved1; - U16 Reserved2; - U32 BitmapOffset; - U32 Size; - S32 Width; - S32 Height; - U16 Planes; - U16 BitsPerPixel; - U32 Compression; - U32 SizeOfBitmap; - S32 HorzResolution; - S32 VertResolution; - U32 ColorsUsed; - U32 ColorsImportant; +struct bitmap_header { + unsigned short FileType; + unsigned int FileSize; + unsigned short Reserved1; + unsigned short Reserved2; + unsigned int BitmapOffset; + unsigned int Size; + int Width; + int Height; + unsigned short Planes; + unsigned short BitsPerPixel; + unsigned int Compression; + unsigned int SizeOfBitmap; + int HorzResolution; + int VertResolution; + unsigned int ColorsUsed; + unsigned int ColorsImportant; - U32 RedMask; - U32 GreenMask; - U32 BlueMask; -} bitmap_header; + unsigned int RedMask; + unsigned int GreenMask; + unsigned int BlueMask; +}; #pragma pack(pop) -static loaded_bitmap DEBUGLoadBMP(thread_context *Thread, debug_read_file_result (*DEBUGPlatformReadEntireFile)(thread_context *Thread, const char *), char *FileName) +static struct loaded_bitmap DEBUGLoadBMP(struct thread_context *Thread, + struct debug_read_file_result + (*DEBUGPlatformReadEntireFile)(struct thread_context *Thread, + const char *), char *FileName) { - loaded_bitmap Result; + struct loaded_bitmap Result; memset(&Result, 0, sizeof(Result)); - debug_read_file_result ReadResult = DEBUGPlatformReadEntireFile(Thread, FileName); + struct debug_read_file_result ReadResult = + DEBUGPlatformReadEntireFile(Thread, FileName); if(ReadResult.ContentsSize > 0) { - bitmap_header *Header = (bitmap_header *)ReadResult.Contents; + struct bitmap_header *Header = + (struct bitmap_header *)ReadResult.Contents; - U32 *Pixels = (U32 *)((U8 *)ReadResult.Contents + Header->BitmapOffset); + unsigned int *Pixels = + (unsigned int *)((unsigned char *)ReadResult.Contents + + Header->BitmapOffset); Result.Pixels = Pixels; Result.Width = Header->Width; Result.Height = Header->Height; @@ -192,25 +217,29 @@ static loaded_bitmap DEBUGLoadBMP(thread_context *Thread, debug_read_file_result // NOTE: The byte order in memory is determined by the Header. - U32 RedMask = Header->RedMask; - U32 GreenMask = Header->GreenMask; - U32 BlueMask = Header->BlueMask; - U32 AlphaMask = ~(RedMask | GreenMask | BlueMask); + unsigned int RedMask = Header->RedMask; + unsigned int GreenMask = Header->GreenMask; + unsigned int BlueMask = Header->BlueMask; + unsigned int AlphaMask = ~(RedMask | GreenMask | BlueMask); - bit_scan_result RedShift = FindLeastSignificantSetBit(RedMask); - bit_scan_result GreenShift = FindLeastSignificantSetBit(GreenMask); - bit_scan_result BlueShift = FindLeastSignificantSetBit(BlueMask); - bit_scan_result AlphaShift = FindLeastSignificantSetBit(AlphaMask); + struct bit_scan_result RedShift = + FindLeastSignificantSetBit(RedMask); + struct bit_scan_result GreenShift = + FindLeastSignificantSetBit(GreenMask); + struct bit_scan_result BlueShift = + FindLeastSignificantSetBit(BlueMask); + struct bit_scan_result AlphaShift = + FindLeastSignificantSetBit(AlphaMask); ASSERT(RedShift.Found); ASSERT(GreenShift.Found); ASSERT(BlueShift.Found); ASSERT(AlphaShift.Found); - U32 *SourceDest = Pixels; - for(S32 Y = 0; Y < Header->Height; Y++) { - for(S32 X = 0; X < Header->Width; X++) { - U32 C = *SourceDest; + unsigned int *SourceDest = Pixels; + for(int Y = 0; Y < Header->Height; Y++) { + for(int X = 0; X < Header->Width; X++) { + unsigned int C = *SourceDest; *SourceDest = ((((C >> AlphaShift.Index) & 0xFF) << 24) | (((C >> RedShift.Index ) & 0xFF) << 16) | @@ -224,76 +253,284 @@ static loaded_bitmap DEBUGLoadBMP(thread_context *Thread, debug_read_file_result return Result; } -void UpdateAndRender(thread_context *Thread, game_memory *Memory, game_input *Input, game_offscreen_buffer *Buffer, game_sound_output_buffer *SoundBuffer) +static struct entity *GetEntity(struct game_state *GameState, + unsigned int Index) { - ASSERT((&Input->Controllers[0].Terminator - &Input->Controllers[0].Buttons[0]) == ARRAY_SIZE(Input->Controllers[0].Buttons)); - ASSERT(sizeof(game_state) <= Memory->PermanentStorageSize); + struct entity *Entity = NULL; - game_state *GameState; + if((Index > 0) && (Index < ARRAY_SIZE(GameState->Entities))) { + Entity = &GameState->Entities[Index]; + } - F32 PlayerHeight = 1.4f; - F32 PlayerWidth = 0.75f * PlayerHeight; + return Entity; +} - GameState = (game_state *)Memory->PermanentStorage; +static void InitializePlayer(struct entity *Entity) +{ + Entity->Exists = 1; + Entity->P.AbsTileX = 2; + Entity->P.AbsTileY = 3; + Entity->P.Offset.X = 5.0f; + Entity->P.Offset.Y = 5.0f; + Entity->Height = 1.4f; + Entity->Width = 0.75f * Entity->Height; +} + +static unsigned int AddEntity(struct game_state *GameState) +{ + unsigned int EntityIndex = ++GameState->EntityCount; + + ASSERT(GameState->EntityCount < ARRAY_SIZE(GameState->Entities)); + struct entity *Entity = &GameState->Entities[EntityIndex]; + memset(Entity, 0, sizeof(struct entity)); + + return EntityIndex; +} + +static void MovePlayer(struct game_state *GameState, + struct entity *Entity, float dt, struct v2 ddPlayer) +{ + struct tile_map *TileMap = GameState->World->TileMap; + + if((ddPlayer.X != 0.0f) && (ddPlayer.Y != 0.0f)) + ddPlayer = V2Multiply(0.7071067811865475244f, ddPlayer); + + float PlayerSpeed = 10.0f; + ddPlayer = V2Multiply(PlayerSpeed, ddPlayer); + + ddPlayer = V2Add(ddPlayer, V2Unary(V2Multiply(1.5f, Entity->dP))); + + struct tile_map_position OldPlayerP = Entity->P; + struct tile_map_position NewPlayerP = OldPlayerP; + struct v2 PlayerDelta = V2Add(V2Multiply(0.5f, V2Multiply(Square(dt), + ddPlayer)), + V2Multiply(dt, Entity->dP)); + NewPlayerP.Offset = V2Add(PlayerDelta, NewPlayerP.Offset); + Entity->dP = V2Add(V2Multiply(dt, ddPlayer), Entity->dP); + NewPlayerP = RecannonicalizePosition(TileMap, NewPlayerP); + +#if 1 + struct tile_map_position PlayerLeft; + PlayerLeft = NewPlayerP; + PlayerLeft.Offset.X -= 0.5f*Entity->Width; + PlayerLeft = RecannonicalizePosition(TileMap, PlayerLeft); + + struct tile_map_position PlayerRight; + PlayerRight = NewPlayerP; + PlayerRight.Offset.X += 0.5f*Entity->Width; + PlayerRight = RecannonicalizePosition(TileMap, PlayerRight); + + int Collided = 0; + struct tile_map_position ColP; + memset(&ColP, 0, sizeof(ColP)); + if(!IsTileMapPointEmpty(TileMap, NewPlayerP)) { + ColP = NewPlayerP; + Collided = 1; + } + if(!IsTileMapPointEmpty(TileMap, PlayerLeft)) { + ColP = PlayerLeft; + Collided = 1; + } + if(!IsTileMapPointEmpty(TileMap, PlayerRight)) { + ColP = PlayerRight; + Collided = 1; + } + + if(Collided) { + struct v2 r = { 0, 0 }; + if(ColP.AbsTileX < Entity->P.AbsTileX) { + r = (struct v2){ 1, 0 }; + } + if(ColP.AbsTileX > Entity->P.AbsTileX) { + r = (struct v2){ -1, 0 }; + } + if(ColP.AbsTileY < Entity->P.AbsTileY) { + r = (struct v2){ 0, 1 }; + } + if(ColP.AbsTileY > Entity->P.AbsTileY) { + r = (struct v2){ 0, -1 }; + } + + Entity->dP = V2Subtract(Entity->dP, + V2Multiply(1*InnerProduct(Entity->dP, r), r)); + } else { + Entity->P = NewPlayerP; + } +#else + unsigned int MinTileX = 0; + unsigned int MinTileY = 0; + unsigned int OnePastMaxTileX = 0; + unsigned int OnePastMaxTileY = 0; + unsigned int AbsTileZ = GameState->PlayerP.AbsTileZ; + tile_map_position BestPlayerP = GameState->PlayerP; + F32 BestDistance = LengthSq(PlayerDelta); + for(unsigned int AbsTileY = MinTileY; + AbsTileY != OnePastMaxTileY; + AbsTileY++) + { + for(unsigned int AbsTileX = MinTileX; + AbsTileX != OnePastMaxTileX; + AbsTileX++) + { + tile_map_position TestTileP = + CenteredTilePoint(AbsTileX, AbsTileY, AbsTileZ); + unsigned int TileValue = GetTileValueByPos(TileMap, TestTileP); + if(IsTileValueEmpty(TileValue)) { + v2 MinCorner = V2Multiply(-0.5f, + (v2){ TileMap->TileSideInMeters, + TileMap->TileSideInMeters }); + v2 MaxCorner = V2Multiply(-0.5f, + (v2){ TileMap->TileSideInMeters, + TileMap->TileSideInMeters }); + + tile_map_difference RelNewPlayerP = + SubtractInF32(TileMap, &TestTileP, &NewPlayerP); + v2 TestP = ClosestPointInRectangle(MinCorner, MaxCorner, + RelNewPlayerP); + if(...) { + } + } + } + } +#endif + + if(!AreOnSameTile(&OldPlayerP, &Entity->P)) { + unsigned int NewTileValue = GetTileValueByPos(TileMap, Entity->P); + + if(NewTileValue == 3) { + Entity->P.AbsTileZ++; + } else if(NewTileValue == 4) { + Entity->P.AbsTileZ--; + } + } + + if(AbsoluteValue(ddPlayer.X) > AbsoluteValue(ddPlayer.Y)) { + if(ddPlayer.X > 0) { + Entity->FacingDirection = 0; + } else { + Entity->FacingDirection = 2; + } + } else if(AbsoluteValue(ddPlayer.X) < AbsoluteValue(ddPlayer.Y)) { + if(ddPlayer.Y > 0) { + Entity->FacingDirection = 1; + } else { + Entity->FacingDirection = 3; + } + } +} + +void UpdateAndRender(struct thread_context *Thread, + struct game_memory *Memory, struct game_input *Input, + struct game_offscreen_buffer *Buffer, + struct game_sound_output_buffer *SoundBuffer) +{ + ASSERT((&Input->Controllers[0].Terminator - + &Input->Controllers[0].Buttons[0]) == + ARRAY_SIZE(Input->Controllers[0].Buttons)); + ASSERT(sizeof(struct game_state) <= Memory->PermanentStorageSize); + + struct game_state *GameState; + + GameState = (struct game_state *)Memory->PermanentStorage; if(!Memory->IsInitialized) { + // NOTE: Reserve entity slot 0 for null entity + AddEntity(GameState); + + GameState->rect_pos.X = 0.0f; + GameState->rect_pos.Y = 0.0f; + GameState->ProgramIcon.Width = 256; GameState->ProgramIcon.Height = 256; GameState->ProgramIcon.BytesPerPixel = 4; - GameState->ProgramIcon.Pitch = GameState->ProgramIcon.BytesPerPixel * GameState->ProgramIcon.Width; - GameState->ProgramIcon.Memory = malloc(GameState->ProgramIcon.BytesPerPixel * GameState->ProgramIcon.Width * GameState->ProgramIcon.Height); - memset(GameState->ProgramIcon.Memory, 0, GameState->ProgramIcon.BytesPerPixel * GameState->ProgramIcon.Width * GameState->ProgramIcon.Height); + GameState->ProgramIcon.Pitch = GameState->ProgramIcon.BytesPerPixel * + GameState->ProgramIcon.Width; + GameState->ProgramIcon.Memory = + malloc(GameState->ProgramIcon.BytesPerPixel * + GameState->ProgramIcon.Width * + GameState->ProgramIcon.Height); + memset(GameState->ProgramIcon.Memory, 0, + GameState->ProgramIcon.BytesPerPixel * + GameState->ProgramIcon.Width * + GameState->ProgramIcon.Height); - GameState->ProgramIconBMP = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/program_icon.bmp"); - DrawBitmap(&GameState->ProgramIcon, &GameState->ProgramIconBMP, 0.0f, 0.0f, 0, 0); +#if 0 + GameState->ProgramIconBMP = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, "data/program_icon.bmp"); + DrawBitmap(&GameState->ProgramIcon, &GameState->ProgramIconBMP, + 0.0f, 0.0f, 0, 0); Memory->SetProgramIcon(&GameState->ProgramIcon); +#endif - GameState->Backdrop = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_background.bmp"); + GameState->Backdrop = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, "data/test_background.bmp"); - hero_bitmaps *Bitmap; + struct hero_bitmaps *Bitmap; Bitmap = &GameState->HeroBitmaps[0]; Bitmap->AlignX = 72; Bitmap->AlignY = 182; - Bitmap->Head = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_right_head.bmp"); - Bitmap->Cape = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_right_cape.bmp"); - Bitmap->Torso = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_right_torso.bmp"); + Bitmap->Head = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_right_head.bmp"); + Bitmap->Cape = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_right_cape.bmp"); + Bitmap->Torso = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_right_torso.bmp"); Bitmap++; Bitmap->AlignX = 72; Bitmap->AlignY = 182; - Bitmap->Head = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_back_head.bmp"); - Bitmap->Cape = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_back_cape.bmp"); - Bitmap->Torso = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_back_torso.bmp"); + Bitmap->Head = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_back_head.bmp"); + Bitmap->Cape = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_back_cape.bmp"); + Bitmap->Torso = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_back_torso.bmp"); Bitmap++; Bitmap->AlignX = 72; Bitmap->AlignY = 182; - Bitmap->Head = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_left_head.bmp"); - Bitmap->Cape = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_left_cape.bmp"); - Bitmap->Torso = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_left_torso.bmp"); + Bitmap->Head = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_left_head.bmp"); + Bitmap->Cape = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_left_cape.bmp"); + Bitmap->Torso = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_left_torso.bmp"); Bitmap++; Bitmap->AlignX = 72; Bitmap->AlignY = 182; - Bitmap->Head = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_front_head.bmp"); - Bitmap->Cape = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_front_cape.bmp"); - Bitmap->Torso = DEBUGLoadBMP(Thread, Memory->DEBUGPlatformReadEntireFile, "data/test_hero_front_torso.bmp"); + Bitmap->Head = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_front_head.bmp"); + Bitmap->Cape = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_front_cape.bmp"); + Bitmap->Torso = DEBUGLoadBMP(Thread, + Memory->DEBUGPlatformReadEntireFile, + "data/test_hero_front_torso.bmp"); GameState->CameraP.AbsTileX = 17 / 2; GameState->CameraP.AbsTileY = 9 / 2; - GameState->PlayerP.AbsTileX = 2; - GameState->PlayerP.AbsTileY = 3; - GameState->PlayerP.Offset.X = 5.0f; - GameState->PlayerP.Offset.Y = 5.0f; + InitializeArena(&GameState->WorldArena, + Memory->PermanentStorageSize - sizeof(struct game_state), + (unsigned char *)Memory->PermanentStorage + + sizeof(struct game_state)); - InitializeArena(&GameState->WorldArena, Memory->PermanentStorageSize - sizeof(game_state), (U8 *)Memory->PermanentStorage + sizeof(game_state)); + GameState->World = PUSH_STRUCT(&GameState->WorldArena, struct world); + struct world *World = GameState->World; + World->TileMap = PUSH_STRUCT(&GameState->WorldArena, struct tile_map); - GameState->World = PUSH_STRUCT(&GameState->WorldArena, world); - world *World = GameState->World; - World->TileMap = PUSH_STRUCT(&GameState->WorldArena, tile_map); - - tile_map *TileMap = World->TileMap; + struct tile_map *TileMap = World->TileMap; TileMap->ChunkShift = 4; TileMap->ChunkMask = (1 << TileMap->ChunkShift) - 1; @@ -303,71 +540,88 @@ void UpdateAndRender(thread_context *Thread, game_memory *Memory, game_input *In TileMap->TileChunkCountY = 128; TileMap->TileChunkCountZ = 2; - TileMap->TileChunks = PUSH_ARRAY(&GameState->WorldArena, TileMap->TileChunkCountX * TileMap->TileChunkCountY * TileMap->TileChunkCountZ, tile_chunk); + TileMap->TileChunks = PUSH_ARRAY(&GameState->WorldArena, + TileMap->TileChunkCountX * TileMap->TileChunkCountY * + TileMap->TileChunkCountZ, + struct tile_chunk); TileMap->TileSideInMeters = 1.4f; - U32 RandomNumberIndex = 0; + unsigned int RandomNumberIndex = 0; - U32 TilesPerWidth = 17; - U32 TilesPerHeight = 9; - U32 ScreenX = 0; - U32 ScreenY = 0; + unsigned int TilesPerWidth = 17; + unsigned int TilesPerHeight = 9; + unsigned int ScreenX = 0; + unsigned int ScreenY = 0; - U32 AbsTileZ = 0; + unsigned int AbsTileZ = 0; - B32 DoorTop = FALSE; - B32 DoorBottom = FALSE; - B32 DoorLeft = FALSE; - B32 DoorRight = FALSE; - B32 DoorUp = FALSE; - B32 DoorDown = FALSE; - for(U32 ScreenIndex = 0; ScreenIndex < 100; ScreenIndex++) { + int DoorTop = 0; + int DoorBottom = 0; + int DoorLeft = 0; + int DoorRight = 0; + int DoorUp = 0; + int DoorDown = 0; + for(unsigned int ScreenIndex = 0; ScreenIndex < 100; ScreenIndex++) { ASSERT(RandomNumberIndex < ARRAY_SIZE(RandomNumberTable)); /* TODO: Random number generator. */ - U32 RandomChoice; + unsigned int RandomChoice; if(DoorUp || DoorDown) { RandomChoice = RandomNumberTable[RandomNumberIndex++] % 2; } else { RandomChoice = RandomNumberTable[RandomNumberIndex++] % 3; } - B32 CreatedZDoor = FALSE; + int CreatedZDoor = 0; if(RandomChoice == 2) { - CreatedZDoor = TRUE; + CreatedZDoor = 1; if(AbsTileZ == 0) { - DoorUp = TRUE; + DoorUp = 1; } else { - DoorDown = TRUE; + DoorDown = 1; } } else if(RandomChoice == 1) { - DoorRight = TRUE; + DoorRight = 1; } else { - DoorTop = TRUE; + DoorTop = 1; } - for(U32 TileY = 0; TileY < TilesPerHeight; TileY++) { - for(U32 TileX = 0; TileX < TilesPerWidth; TileX++) { - U32 AbsTileX = ScreenX * TilesPerWidth + TileX; - U32 AbsTileY = ScreenY * TilesPerHeight + TileY; + for(unsigned int TileY = 0; + TileY < TilesPerHeight; + TileY++) + { + for(unsigned int TileX = 0; + TileX < TilesPerWidth; + TileX++) + { + unsigned int AbsTileX = ScreenX * TilesPerWidth + TileX; + unsigned int AbsTileY = ScreenY * TilesPerHeight + TileY; - U32 TileValue = 1; - if((TileX == 0) && (!DoorLeft || (TileY != (TilesPerHeight/2)))) { + unsigned int TileValue = 1; + if(TileX == 0 && + (!DoorLeft || (TileY != (TilesPerHeight/2)))) + { TileValue = 2; } - if(((TileX == (TilesPerWidth - 1)) && (!DoorRight || (TileY != (TilesPerHeight/2))))) { + if(TileX == (TilesPerWidth - 1) && + (!DoorRight || (TileY != (TilesPerHeight/2)))) + { TileValue = 2; } - if((TileY == 0) && (!DoorBottom || (TileX != (TilesPerWidth/2)))) { + if(TileY == 0 && + (!DoorBottom || (TileX != (TilesPerWidth/2)))) + { TileValue = 2; } - if((TileY == (TilesPerHeight - 1)) && (!DoorTop || (TileX != (TilesPerWidth/2)))) { + if(TileY == (TilesPerHeight - 1) && + (!DoorTop || (TileX != (TilesPerWidth/2)))) + { TileValue = 2; } @@ -380,7 +634,8 @@ void UpdateAndRender(thread_context *Thread, game_memory *Memory, game_input *In } } - SetTileValue(&GameState->WorldArena, World->TileMap, AbsTileX, AbsTileY, AbsTileZ, TileValue); + SetTileValue(&GameState->WorldArena, World->TileMap, + AbsTileX, AbsTileY, AbsTileZ, TileValue); } } @@ -391,12 +646,12 @@ void UpdateAndRender(thread_context *Thread, game_memory *Memory, game_input *In DoorDown = !DoorDown; DoorUp = !DoorUp; } else { - DoorUp = FALSE; - DoorDown = FALSE; + DoorUp = 0; + DoorDown = 0; } - DoorTop = FALSE; - DoorRight = FALSE; + DoorTop = 0; + DoorRight = 0; if(RandomChoice == 2) { if(AbsTileZ == 0) { @@ -411,172 +666,111 @@ void UpdateAndRender(thread_context *Thread, game_memory *Memory, game_input *In } } - Memory->IsInitialized = TRUE; + Memory->IsInitialized = 1; } - world *World = GameState->World; - tile_map *TileMap = World->TileMap; + struct world *World = GameState->World; + struct tile_map *TileMap = World->TileMap; - S32 TileSideInPixels = 60; - F32 MetersToPixels = (F32)TileSideInPixels / TileMap->TileSideInMeters; + int TileSideInPixels = 60; + float MetersToPixels = + (float)TileSideInPixels / TileMap->TileSideInMeters; - tile_map_position OldPlayerP = GameState->PlayerP; - for(U32 ControllerIndex = 0; ControllerIndex < ARRAY_SIZE(Input->Controllers); ControllerIndex++) { - game_controller_input *Controller = GetController(Input, ControllerIndex); - if(Controller->IsAnalog) { - } else { - v2 ddPlayer; // accerlation + for(unsigned int ControllerIndex = 0; + ControllerIndex < ARRAY_SIZE(Input->Controllers); + ControllerIndex++) + { + struct game_controller_input *Controller = + GetController(Input, ControllerIndex); + struct entity *ControllingEntity = + GetEntity(GameState, + GameState->PlayerIndexForController[ControllerIndex]); + if(ControllingEntity) { + struct v2 ddPlayer; /* accerlation */ memset(&ddPlayer, 0, sizeof(ddPlayer)); - if(Controller->MoveUp.EndedDown) { - ddPlayer.Y = 1.0f; - GameState->FacingDirection = 1; - } - if(Controller->MoveDown.EndedDown) { - ddPlayer.Y = -1.0f; - GameState->FacingDirection = 3; - } - if(Controller->MoveLeft.EndedDown) { - ddPlayer.X = -1.0f; - GameState->FacingDirection = 2; - } - if(Controller->MoveRight.EndedDown) { - ddPlayer.X = 1.0f; - GameState->FacingDirection = 0; - } - - if((ddPlayer.X != 0.0f) && (ddPlayer.Y != 0.0f)) - ddPlayer = V2Multiply(0.7071067811865475244f, ddPlayer); - - F32 PlayerSpeed = 10.0f; - if(Controller->ActionUp.EndedDown) - PlayerSpeed = 20.0f; - ddPlayer = V2Multiply(PlayerSpeed, ddPlayer); - - ddPlayer = V2Add(ddPlayer, V2Unary(V2Multiply(1.5f, GameState->dPlayerP))); - - tile_map_position NewPlayerP = GameState->PlayerP; - v2 PlayerDelta = V2Add(V2Multiply(0.5f, V2Multiply(Square(Input->dtForFrame), ddPlayer)), V2Multiply(Input->dtForFrame, GameState->dPlayerP)); - NewPlayerP.Offset = V2Add(PlayerDelta, NewPlayerP.Offset); - GameState->dPlayerP = V2Add(V2Multiply(Input->dtForFrame, ddPlayer), GameState->dPlayerP); - NewPlayerP = RecannonicalizePosition(TileMap, NewPlayerP); - -#if 1 - tile_map_position PlayerLeft; - PlayerLeft = NewPlayerP; - PlayerLeft.Offset.X -= 0.5f*PlayerWidth; - PlayerLeft = RecannonicalizePosition(TileMap, PlayerLeft); - - tile_map_position PlayerRight; - PlayerRight = NewPlayerP; - PlayerRight.Offset.X += 0.5f*PlayerWidth; - PlayerRight = RecannonicalizePosition(TileMap, PlayerRight); - - B32 Collided = FALSE; - tile_map_position ColP; - memset(&ColP, 0, sizeof(ColP)); - if(!IsTileMapPointEmpty(TileMap, NewPlayerP)) { - ColP = NewPlayerP; - Collided = TRUE; - } - if(!IsTileMapPointEmpty(TileMap, PlayerLeft)) { - ColP = PlayerLeft; - Collided = TRUE; - } - if(!IsTileMapPointEmpty(TileMap, PlayerRight)) { - ColP = PlayerRight; - Collided = TRUE; - } - - if(Collided) { - v2 r = { 0, 0 }; - if(ColP.AbsTileX < GameState->PlayerP.AbsTileX) { - r = (v2){ 1, 0 }; - } - if(ColP.AbsTileX > GameState->PlayerP.AbsTileX) { - r = (v2){ -1, 0 }; - } - if(ColP.AbsTileY < GameState->PlayerP.AbsTileY) { - r = (v2){ 0, 1 }; - } - if(ColP.AbsTileY > GameState->PlayerP.AbsTileY) { - r = (v2){ 0, -1 }; - } - - GameState->dPlayerP = V2Subtract(GameState->dPlayerP, V2Multiply(1*InnerProduct(GameState->dPlayerP, r), r)); + if(Controller->IsAnalog) { + ddPlayer = (struct v2){ Controller->StickAverageX, + Controller->StickAverageY }; } else { - GameState->PlayerP = NewPlayerP; - } -#else - U32 MinTileX = 0; - U32 MinTileY = 0; - U32 OnePastMaxTileX = 0; - U32 OnePastMaxTileY = 0; - U32 AbsTileZ = GameState->PlayerP.AbsTileZ; - tile_map_position BestPlayerP = GameState->PlayerP; - F32 BestDistance = LengthSq(PlayerDelta); - for(U32 AbsTileY = MinTileY; AbsTileY != OnePastMaxTileY; AbsTileY++) { - for(U32 AbsTileX = MinTileX; AbsTileX != OnePastMaxTileX; AbsTileX++) { - tile_map_position TestTileP = CenteredTilePoint(AbsTileX, AbsTileY, AbsTileZ); - U32 TileValue = GetTileValueByPos(TileMap, TestTileP); - if(IsTileValueEmpty(TileValue)) { - v2 MinCorner = V2Multiply(-0.5f, (v2){ TileMap->TileSideInMeters, TileMap->TileSideInMeters }); - v2 MaxCorner = V2Multiply(-0.5f, (v2){ TileMap->TileSideInMeters, TileMap->TileSideInMeters }); - tile_map_difference RelNewPlayerP = SubtractInF32(TileMap, &TestTileP, &NewPlayerP); - v2 TestP = ClosestPointInRectangle(MinCorner, MaxCorner, RelNewPlayerP); - if(...) { - } - } + if(Controller->MoveUp.EndedDown) { + GameState->rect_pos.Y -= 1.0f; + + ddPlayer.Y = 1.0f; } + if(Controller->MoveDown.EndedDown) { + GameState->rect_pos.Y += 1.0f; + + ddPlayer.Y = -1.0f; + } + if(Controller->MoveLeft.EndedDown) { + GameState->rect_pos.X -= 1.0f; + + ddPlayer.X = -1.0f; + } + if(Controller->MoveRight.EndedDown) { + GameState->rect_pos.X += 1.0f; + + ddPlayer.X = 1.0f; + } + + } + + MovePlayer(GameState, ControllingEntity, Input->dtForFrame, + ddPlayer); + } else { + if(Controller->Start.EndedDown) { + unsigned int EntityIndex = AddEntity(GameState); + ControllingEntity = GetEntity(GameState, EntityIndex); + InitializePlayer(ControllingEntity); + GameState->PlayerIndexForController[ControllerIndex] = + EntityIndex; } -#endif } } - if(!AreOnSameTile(&OldPlayerP, &GameState->PlayerP)) { - U32 NewTileValue = GetTileValueByPos(TileMap, GameState->PlayerP); + struct entity *CameraFollowingEntity = + GetEntity(GameState, GameState->CameraFollowingEntityIndex); + if(CameraFollowingEntity) { + GameState->CameraP.AbsTileZ = CameraFollowingEntity->P.AbsTileZ; - if(NewTileValue == 3) { - GameState->PlayerP.AbsTileZ++; - } else if(NewTileValue == 4) { - GameState->PlayerP.AbsTileZ--; + struct tile_map_difference Diff = + SubtractInFloat(TileMap, &CameraFollowingEntity->P, + &GameState->CameraP); + if(Diff.dXY.X > (9.0f*TileMap->TileSideInMeters)) { + GameState->CameraP.AbsTileX += 17; + } + if(Diff.dXY.X < -(9.0f*TileMap->TileSideInMeters)) { + GameState->CameraP.AbsTileX -= 17; + } + if(Diff.dXY.Y > (5.0f*TileMap->TileSideInMeters)) { + GameState->CameraP.AbsTileY += 9; + } + if(Diff.dXY.Y < -(5.0f*TileMap->TileSideInMeters)) { + GameState->CameraP.AbsTileY -= 9; } } - GameState->CameraP.AbsTileZ = GameState->PlayerP.AbsTileZ; - - tile_map_difference Diff = SubtractInF32(TileMap, &GameState->PlayerP, &GameState->CameraP); - if(Diff.dXY.X > (9.0f*TileMap->TileSideInMeters)) { - GameState->CameraP.AbsTileX += 17; - } - if(Diff.dXY.X < -(9.0f*TileMap->TileSideInMeters)) { - GameState->CameraP.AbsTileX -= 17; - } - if(Diff.dXY.Y > (5.0f*TileMap->TileSideInMeters)) { - GameState->CameraP.AbsTileY += 9; - } - if(Diff.dXY.Y < -(5.0f*TileMap->TileSideInMeters)) { - GameState->CameraP.AbsTileY -= 9; - } - Diff = SubtractInF32(TileMap, &GameState->PlayerP, &GameState->CameraP); - - //DrawRectangle(Buffer, 0.0f, 0.0f, (F32)Buffer->Width, (F32)Buffer->Height, 0.0f, 1.0f, 0.0f); + /*DrawRectangle(Buffer, 0.0f, 0.0f, + (F32)Buffer->Width, (F32)Buffer->Height, + 0.0f, 1.0f, 0.0f);*/ DrawBitmap(Buffer, &GameState->Backdrop, 0.0f, 0.0f, 0, 0); - F32 ScreenCenterX = 0.5f * (F32)Buffer->Width; - F32 ScreenCenterY = 0.5f * (F32)Buffer->Height; + float ScreenCenterX = 0.5f * (float)Buffer->Width; + float ScreenCenterY = 0.5f * (float)Buffer->Height; - for(S32 RelRow = -10; RelRow < 10; RelRow++) { - for(S32 RelColumn = -20; RelColumn < 20; RelColumn++) { - U32 Column = GameState->CameraP.AbsTileX + RelColumn; - U32 Row = GameState->CameraP.AbsTileY + RelRow; + for(int RelRow = -10; RelRow < 10; RelRow++) { + for(int RelColumn = -20; RelColumn < 20; RelColumn++) { + unsigned int Column = GameState->CameraP.AbsTileX + RelColumn; + unsigned int Row = GameState->CameraP.AbsTileY + RelRow; - U32 TileID = GetTileValue(TileMap, Column, Row, GameState->CameraP.AbsTileZ); + unsigned int TileID = GetTileValue(TileMap, Column, Row, + GameState->CameraP.AbsTileZ); if(TileID > 1) { - F32 Gray = 0.5f; + float Gray = 0.5f; if(TileID == 2) { Gray = 1.0f; } @@ -585,42 +779,81 @@ void UpdateAndRender(thread_context *Thread, game_memory *Memory, game_input *In Gray = 0.25f; } - if((Column == GameState->CameraP.AbsTileX) && (Row == GameState->CameraP.AbsTileY)) { + if(Column == GameState->CameraP.AbsTileX && + Row == GameState->CameraP.AbsTileY) + { Gray = 0.0f; } - v2 TileSide = { 0.5f*(F32)TileSideInPixels, 0.5f*(F32)TileSideInPixels }; - v2 Center = { ScreenCenterX - MetersToPixels*GameState->CameraP.Offset.X + (F32)RelColumn*(F32)TileSideInPixels, - ScreenCenterY + MetersToPixels*GameState->CameraP.Offset.Y - (F32)RelRow*(F32)TileSideInPixels }; - v2 Min = V2Subtract(Center, TileSide); - v2 Max = V2Add(Center, TileSide); + struct v2 TileSide = { 0.5f*(float)TileSideInPixels, + 0.5f*(float)TileSideInPixels }; + struct v2 Center = { ScreenCenterX - + MetersToPixels*GameState->CameraP.Offset.X + + (float)RelColumn*(float)TileSideInPixels, + ScreenCenterY + MetersToPixels * + GameState->CameraP.Offset.Y - + (float)RelRow*(float)TileSideInPixels }; + struct v2 Min = V2Subtract(Center, TileSide); + struct v2 Max = V2Add(Center, TileSide); DrawRectangle(Buffer, Min, Max, Gray, Gray, Gray); } } } - F32 PlayerR = 1.0f; - F32 PlayerG = 0.0f; - F32 PlayerB = 0.0f; - F32 PlayerGroundPointX = ScreenCenterX + MetersToPixels*Diff.dXY.X; - F32 PlayerGroundPointY = ScreenCenterY - MetersToPixels*Diff.dXY.Y; - v2 PlayerLeftTop = { PlayerGroundPointX - 0.5f * MetersToPixels*PlayerWidth, - PlayerGroundPointY - MetersToPixels*PlayerHeight }; - v2 PlayerWidthHeight = { PlayerWidth, PlayerHeight }; - DrawRectangle(Buffer, PlayerLeftTop, V2Add(PlayerLeftTop, V2Multiply(MetersToPixels, PlayerWidthHeight)), PlayerR, PlayerG, PlayerB); + struct entity *Entity = GameState->Entities; + for(unsigned int EntityIndex = 0; + EntityIndex < GameState->EntityCount; + EntityIndex++, Entity++) + { + if(Entity->Exists) { + struct tile_map_difference Diff = + SubtractInFloat(TileMap, &Entity->P, &GameState->CameraP); - hero_bitmaps *Bitmap = &GameState->HeroBitmaps[GameState->FacingDirection]; - DrawBitmap(Buffer, &Bitmap->Torso, PlayerGroundPointX, PlayerGroundPointY, Bitmap->AlignX, Bitmap->AlignY); - DrawBitmap(Buffer, &Bitmap->Cape, PlayerGroundPointX, PlayerGroundPointY, Bitmap->AlignX, Bitmap->AlignY); - DrawBitmap(Buffer, &Bitmap->Head, PlayerGroundPointX, PlayerGroundPointY, Bitmap->AlignX, Bitmap->AlignY); + float PlayerR = 1.0f; + float PlayerG = 0.0f; + float PlayerB = 0.0f; + float PlayerGroundPointX = + ScreenCenterX + MetersToPixels*Diff.dXY.X; + float PlayerGroundPointY = + ScreenCenterY - MetersToPixels*Diff.dXY.Y; + struct v2 PlayerLeftTop = + { PlayerGroundPointX - 0.5f * MetersToPixels*Entity->Width, + PlayerGroundPointY - MetersToPixels*Entity->Height }; + struct v2 PlayerWidthHeight = { Entity->Width, Entity->Height }; + DrawRectangle(Buffer, PlayerLeftTop, + V2Add(PlayerLeftTop, V2Multiply(MetersToPixels, + PlayerWidthHeight)), + PlayerR, PlayerG, PlayerB); + + struct hero_bitmaps *Bitmap = + &GameState->HeroBitmaps[Entity->FacingDirection]; + DrawBitmap(Buffer, &Bitmap->Torso, + PlayerGroundPointX, PlayerGroundPointY, + Bitmap->AlignX, Bitmap->AlignY); + DrawBitmap(Buffer, &Bitmap->Cape, + PlayerGroundPointX, PlayerGroundPointY, + Bitmap->AlignX, Bitmap->AlignY); + DrawBitmap(Buffer, &Bitmap->Head, + PlayerGroundPointX, PlayerGroundPointY, + Bitmap->AlignX, Bitmap->AlignY); + + /* TODO: Remove this. */ + /*DrawRectangle(&GameState->ProgramIcon, GameState->rect_pos, + (struct v2){ GameState->rect_pos.X + 20.0f, + GameState->rect_pos.Y + 20.0f }, + 0.8f, 0.8f, 0.8f);*/ + /*Memory->SetProgramIcon(&GameState->ProgramIcon);*/ + } + } GameOutputSound(GameState, SoundBuffer, 400); } /* -static void RenderWeirdGradient(game_offscreen_buffer *Buffer, S32 XOffset, S32 YOffset) +static void RenderWeirdGradient(game_offscreen_buffer *Buffer, + int XOffset, int YOffset) { - S32 Width, Height, Y; + int Width, Height, Y; U8 *Row; Width = Buffer->Width; @@ -628,10 +861,10 @@ static void RenderWeirdGradient(game_offscreen_buffer *Buffer, S32 XOffset, S32 Row = (U8 *)Buffer->Memory; for(Y = 0; Y < Height; Y++) { - U32 *Pixel = (U32 *)Row; - S32 X; + unsigned int *Pixel = (unsigned int *)Row; + int X; - Pixel = (U32 *)Row; + Pixel = (unsigned int *)Row; for(X = 0; X < Width; X++) { U8 Blue, Green; diff --git a/handmade.h b/handmade.h index ff08613..a8d7d4f 100644 --- a/handmade.h +++ b/handmade.h @@ -7,137 +7,154 @@ /* NOTE: Servcies that the platform layer provides to the game. */ /* --------------------------------------------------------------------- */ -typedef struct thread_context { - S32 Placeholder; -} thread_context; +struct thread_context { + int Placeholder; +}; #if BUILD_INTERNAL -typedef struct debug_read_file_result { - U32 ContentsSize; - void *Contents; -} debug_read_file_result; +struct debug_read_file_result { + unsigned int ContentsSize; + void *Contents; +}; -debug_read_file_result DEBUGPlatformReadEntireFile(thread_context *Thread, const char *Filename); -B32 DEBUGPlatformWriteEntireFile(thread_context *Thread, const char *Filename, U32 MemorySize, void *Memory); -void DEBUGPlatformFreeFileMemory(thread_context *Thread, void *Memory); +struct debug_read_file_result + DEBUGPlatformReadEntireFile(struct thread_context *Thread, + const char *Filename); +int DEBUGPlatformWriteEntireFile(struct thread_context *Thread, + const char *Filename, + unsigned int MemorySize, void *Memory); +void DEBUGPlatformFreeFileMemory(struct thread_context *Thread, + void *Memory); #endif -typedef struct game_offscreen_buffer game_offscreen_buffer; -void SetProgramIcon(game_offscreen_buffer *ProgramIcon); +struct game_offscreen_buffer game_offscreen_buffer; +void SetProgramIcon(struct game_offscreen_buffer *ProgramIcon); /* --------------------------------------------------------------------- */ /* NOTE: Servcies that the game provides to the platform layer. */ /* --------------------------------------------------------------------- */ -typedef struct game_offscreen_buffer { +struct game_offscreen_buffer { /* Pixels are always 32-bit and have the bytes in BGRX (little-endian). */ void *Memory; - S32 Width; - S32 Height; - S32 BytesPerPixel; - S32 Pitch; -} game_offscreen_buffer; + int Width; + int Height; + int BytesPerPixel; + int Pitch; +}; -typedef struct game_sound_output_buffer { - S32 SamplesPerSecond; - S32 SampleCount; - S16 *Samples; -} game_sound_output_buffer; +struct game_sound_output_buffer { + int SamplesPerSecond; + int SampleCount; + short *Samples; +}; -typedef struct game_button_state { - S32 HalfTransitionCount; - B32 EndedDown; -} game_button_state; +struct game_button_state { + int HalfTransitionCount; + int EndedDown; +}; -typedef struct game_controller_input { - B32 IsConnected; - B32 IsAnalog; +struct game_controller_input { + int IsConnected; + int IsAnalog; - F32 StickAverageX; - F32 StickAverageY; + float StickAverageX; + float StickAverageY; union { - game_button_state Buttons[12]; + struct game_button_state Buttons[12]; struct { - game_button_state MoveUp; - game_button_state MoveDown; - game_button_state MoveLeft; - game_button_state MoveRight; + struct game_button_state MoveUp; + struct game_button_state MoveDown; + struct game_button_state MoveLeft; + struct game_button_state MoveRight; - game_button_state ActionUp; - game_button_state ActionDown; - game_button_state ActionLeft; - game_button_state ActionRight; + struct game_button_state ActionUp; + struct game_button_state ActionDown; + struct game_button_state ActionLeft; + struct game_button_state ActionRight; - game_button_state LeftShoulder; - game_button_state RightShoulder; + struct game_button_state LeftShoulder; + struct game_button_state RightShoulder; - game_button_state Start; - game_button_state Back; + struct game_button_state Start; + struct game_button_state Back; /* NOTE: All buttons must be added above this line. */ - game_button_state Terminator; + struct game_button_state Terminator; }; }; -} game_controller_input; +}; -typedef struct game_input { - game_button_state MouseButtons[5]; - S32 MouseX, MouseY, MouseZ; /* NOTE: MouseZ is the wheel. */ +struct game_input { + struct game_button_state MouseButtons[5]; + int MouseX, MouseY, MouseZ; /* NOTE: MouseZ is the wheel. */ - F32 dtForFrame; + float dtForFrame; - game_controller_input Controllers[5]; -} game_input; + struct game_controller_input Controllers[5]; +}; -game_controller_input *GetController(game_input *Input, S32 ControllerIndex) +struct game_controller_input *GetController(struct game_input *Input, + int ControllerIndex) { - game_controller_input *Result; + struct game_controller_input *Result; - ASSERT((U32)ControllerIndex < ARRAY_SIZE(Input->Controllers)); + ASSERT((unsigned int)ControllerIndex < ARRAY_SIZE(Input->Controllers)); Result = &(Input->Controllers[ControllerIndex]); return Result; } -typedef struct game_memory { - B32 IsInitialized; +struct game_memory { + int IsInitialized; - U64 PermanentStorageSize; - void *PermanentStorage; /* WARNING: This memory is REQUIRED to be zero initialized!!! (Done by the OS layer.) */ + unsigned long long PermanentStorageSize; + void *PermanentStorage; /* WARNING: This memory is REQUIRED to be zero + initialized!!! (Done by the OS layer.) */ - U64 TransientStorageSize; - void *TransientStorage; /* WARNING: This memory is REQUIRED to be zero initialized!!! (Done by the OS layer.) */ + unsigned long long TransientStorageSize; + void *TransientStorage; /* WARNING: This memory is REQUIRED to be zero + initialized!!! (Done by the OS layer.) */ #if BUILD_INTERNAL - debug_read_file_result (*DEBUGPlatformReadEntireFile)(thread_context *Thread,const char *); - B32 (*DEBUGPlatformWriteEntireFile)(thread_context *Thread, const char *, U32, void *); - void (*DEBUGPlatformFreeFileMemory)(thread_context *Thread, void *); - void (*SetProgramIcon)(game_offscreen_buffer *ProgramIcon); + struct debug_read_file_result + (*DEBUGPlatformReadEntireFile)(struct thread_context *Thread, + const char *); + int (*DEBUGPlatformWriteEntireFile)(struct thread_context *Thread, + const char *, unsigned int, void *); + void (*DEBUGPlatformFreeFileMemory)(struct thread_context *Thread, + void *); + void (*SetProgramIcon)(struct game_offscreen_buffer *ProgramIcon); #endif -} game_memory; +}; -/*typedef struct game_clocks { - U64 Ticks; - F32 SecondsElapsed; -} game_clocks;*/ +/*struct game_clocks { + unsigned long long Ticks; + float SecondsElapsed; +};*/ #if OS_WINDOWS __declspec(dllexport) #endif -void UpdateAndRender(thread_context *Thread, game_memory *Memory, game_input *Input, game_offscreen_buffer *Buffer, game_sound_output_buffer *SoundBuffer); +void UpdateAndRender(struct thread_context *Thread, + struct game_memory *Memory, + struct game_input *Input, + struct game_offscreen_buffer *Buffer, + struct game_sound_output_buffer *SoundBuffer); /* * */ -typedef struct memory_arena { - U64 Size; - U8 *Base; - U64 Used; -} memory_arena; +struct memory_arena { + unsigned long long Size; + unsigned char *Base; + unsigned long long Used; +}; -static void InitializeArena(memory_arena *Arena, U64 Size, U8 *Base) +static void InitializeArena(struct memory_arena *Arena, + unsigned long long Size, unsigned char *Base) { Arena->Size = Size; Arena->Base = Base; @@ -145,8 +162,9 @@ static void InitializeArena(memory_arena *Arena, U64 Size, U8 *Base) } #define PUSH_STRUCT(Arena, type) (type *)PushSize_(Arena, sizeof(type)) -#define PUSH_ARRAY(Arena, Count, type) (type *)PushSize_(Arena, (Count)*sizeof(type)) -static void *PushSize_(memory_arena *Arena, U64 Size) +#define PUSH_ARRAY(Arena, Count, type) \ + (type *)PushSize_(Arena, (Count)*sizeof(type)) +static void *PushSize_(struct memory_arena *Arena, unsigned long long Size) { void *Result; @@ -157,41 +175,54 @@ static void *PushSize_(memory_arena *Arena, U64 Size) return Result; } -typedef struct world { - tile_map *TileMap; -} world; +struct world { + struct tile_map *TileMap; +}; -typedef struct loaded_bitmap { - S32 Width; - S32 Height; - U32 *Pixels; -} loaded_bitmap; +struct loaded_bitmap { + int Width; + int Height; + unsigned int *Pixels; +}; -typedef struct hero_bitmaps { - S32 AlignX; - S32 AlignY; +struct hero_bitmaps { + int AlignX; + int AlignY; - loaded_bitmap Head; - loaded_bitmap Cape; - loaded_bitmap Torso; -} hero_bitmaps; + struct loaded_bitmap Head; + struct loaded_bitmap Cape; + struct loaded_bitmap Torso; +}; -typedef struct game_state { - game_offscreen_buffer ProgramIcon; - loaded_bitmap ProgramIconBMP; +struct entity { + int Exists; + struct tile_map_position P; + struct v2 dP; // velocity + unsigned int FacingDirection; + float Height, Width; +}; - memory_arena WorldArena; - world *World; +struct game_state { + struct game_offscreen_buffer ProgramIcon; + struct loaded_bitmap ProgramIconBMP; - tile_map_position CameraP; - tile_map_position PlayerP; - v2 dPlayerP; // velocity + struct memory_arena WorldArena; + struct world *World; + unsigned int CameraFollowingEntityIndex; + struct tile_map_position CameraP; - loaded_bitmap Backdrop; + /*unsigned int + *PlayerIndexForController[ARRAY_SIZE(((game_input *)0)->Controllers];*/ + unsigned int PlayerIndexForController[5]; + unsigned int EntityCount; + struct entity Entities[256]; - U32 FacingDirection; - hero_bitmaps HeroBitmaps[4]; -} game_state; + struct loaded_bitmap Backdrop; + + struct hero_bitmaps HeroBitmaps[4]; + + struct v2 rect_pos; +}; #endif diff --git a/handmade_intrinsics.h b/handmade_intrinsics.h index 9c2f548..96d0419 100644 --- a/handmade_intrinsics.h +++ b/handmade_intrinsics.h @@ -7,63 +7,71 @@ #include #include // memset -S32 RoundF32toS32(F32 Real32) +float AbsoluteValue(float Real32) { - S32 Result = (S32)roundf(Real32); + float Result = fabs(Real32); return Result; } -S32 FloorF32toS32(F32 Real32) +int RoundFloatToInt(float Real32) { - S32 Result = (S32)floorf(Real32); + int Result = (int)roundf(Real32); return Result; } -F32 Sin(F32 Angle) +int FloorFloatToInt(float Real32) { - F32 Result = sinf(Angle); + int Result = (int)floorf(Real32); return Result; } -F32 Cos(F32 Angle) +float Sin(float Angle) { - F32 Result = cosf(Angle); + float Result = sinf(Angle); return Result; } -F32 ATan2(F32 Y, F32 X) +float Cos(float Angle) { - F32 Result = atan2f(Y, X); + float Result = cosf(Angle); return Result; } -typedef struct bit_scan_result { - B32 Found; - U32 Index; -} bit_scan_result; - -static bit_scan_result FindLeastSignificantSetBit(U32 Value) +float ATan2(float Y, float X) { - bit_scan_result Result; + float Result = atan2f(Y, X); + return Result; +} + +struct bit_scan_result { + int Found; + unsigned int Index; +}; + +static struct bit_scan_result FindLeastSignificantSetBit(unsigned int Value) +{ + struct bit_scan_result Result; memset(&Result, 0, sizeof(Result)); #if COMPILER_MSVC unsigned long Index; Result.Found = _BitScanForward(&Index, Value); - Result.Index = (U32)Index; + Result.Index = (unsigned int)Index; #elif COMPILER_CLANG - Result.Index = __builtin_ffsll(Value); // NOTE: It is a GCC function, but is supported by clang compiler. - // https://gcc.gnu.org/onlinedocs/gcc/Bit-Operation-Builtins.html + Result.Index = __builtin_ffsll(Value); /* NOTE: It is a GCC function, + but is supported by clang + compiler. + https://gcc.gnu.org/onlinedocs/gcc/Bit-Operation-Builtins.html*/ if(Result.Index) { - Result.Found = TRUE; + Result.Found = 1; if(Result.Index > 0) Result.Index--; } #else - for(U32 Test = 0; Test < 32; Test++) { + for(unsigned int Test = 0; Test < 32; Test++) { if(Value & (1 << Test)) { Result.Index = Test; - Result.Found = TRUE; + Result.Found = 1; break; } } diff --git a/handmade_math.h b/handmade_math.h index f643ae5..021b6b7 100644 --- a/handmade_math.h +++ b/handmade_math.h @@ -2,14 +2,14 @@ #define HANDMADE_MATH_H // TODO: Make these static. -typedef struct v2 { - F32 X, Y; - F32 E[2]; -} v2; +struct v2 { + float X, Y; + float E[2]; +}; -v2 V2(F32 X, F32 Y) +struct v2 V2(float X, float Y) { - v2 Result; + struct v2 Result; Result.X = X; Result.Y = Y; @@ -17,9 +17,9 @@ v2 V2(F32 X, F32 Y) return Result; } -v2 V2Multiply(F32 A, v2 B) +struct v2 V2Multiply(float A, struct v2 B) { - v2 Result; + struct v2 Result; Result.X = A * B.X; Result.Y = A * B.Y; @@ -27,9 +27,9 @@ v2 V2Multiply(F32 A, v2 B) return Result; } -v2 V2Unary(v2 A) +struct v2 V2Unary(struct v2 A) { - v2 Result; + struct v2 Result; Result.X = -A.X; Result.Y = -A.Y; @@ -37,9 +37,9 @@ v2 V2Unary(v2 A) return Result; } -v2 V2Add(v2 A, v2 B) +struct v2 V2Add(struct v2 A, struct v2 B) { - v2 Result; + struct v2 Result; Result.X = A.X + B.X; Result.Y = A.Y + B.Y; @@ -47,9 +47,9 @@ v2 V2Add(v2 A, v2 B) return Result; } -v2 V2Subtract(v2 A, v2 B) +struct v2 V2Subtract(struct v2 A, struct v2 B) { - v2 Result; + struct v2 Result; Result.X = A.X - B.X; Result.Y = A.Y - B.Y; @@ -57,24 +57,24 @@ v2 V2Subtract(v2 A, v2 B) return Result; } -F32 Square(F32 A) +float Square(float A) { - F32 Result; + float Result; Result = A * A; return Result; } -F32 InnerProduct(v2 A, v2 B) +float InnerProduct(struct v2 A, struct v2 B) { - F32 Result = A.X*B.X + A.Y*B.Y; + float Result = A.X*B.X + A.Y*B.Y; return Result; } -F32 LengthSq(v2 A) +float LengthSq(struct v2 A) { - F32 Result = InnerProduct(A, A); + float Result = InnerProduct(A, A); return Result; } diff --git a/handmade_random.h b/handmade_random.h index 7a49fa0..70f9f3a 100644 --- a/handmade_random.h +++ b/handmade_random.h @@ -1,7 +1,7 @@ #ifndef HANDMADE_RANDOM_H_SENTRY #define HANDMADE_RANDOM_H_SENTRY -static U32 RandomNumberTable[] = { +static unsigned int RandomNumberTable[] = { 0x215cd69f, 0x33960616, 0x200b7d2b, 0x1f908c2d, 0x264590df, 0x0a3cfc19, 0x2fd85a9a, 0x19bd3968, 0x1a36d278, 0x3552bed4, 0x1cf24f52, 0x388993cc, 0x028fb3ea, 0x2c777ded, 0x39ca8471, 0x1badf924, 0x0f95267e, 0x2a4ff029, 0x2c1b26ea, 0x0212c345, 0x304d7fe0, 0x3b4e6efe, 0x11124fce, 0x2352fc4c, diff --git a/handmade_tile.c b/handmade_tile.c index c8379c3..f07cfe9 100644 --- a/handmade_tile.c +++ b/handmade_tile.c @@ -1,22 +1,31 @@ #include "handmade_tile.h" -static tile_chunk *GetTileChunk(tile_map *TileMap, U32 TileChunkX, U32 TileChunkY, U32 TileChunkZ) +static struct tile_chunk * +GetTileChunk(struct tile_map *TileMap, + unsigned int TileChunkX, unsigned int TileChunkY, + unsigned int TileChunkZ) { - tile_chunk *TileChunk = NULL; + struct tile_chunk *TileChunk = NULL; if((TileChunkX >= 0) && (TileChunkX < TileMap->TileChunkCountX) && (TileChunkY >= 0) && (TileChunkY < TileMap->TileChunkCountY) && (TileChunkZ >= 0) && (TileChunkZ < TileMap->TileChunkCountZ)) { - TileChunk = &TileMap->TileChunks[(TileChunkZ*TileMap->TileChunkCountY*TileMap->TileChunkCountX) + (TileChunkY*TileMap->TileChunkCountX) + TileChunkX]; + TileChunk = + &TileMap->TileChunks[(TileChunkZ * TileMap->TileChunkCountY * + TileMap->TileChunkCountX) + + (TileChunkY*TileMap->TileChunkCountX) + TileChunkX]; } return TileChunk; } -static tile_chunk_position GetChunkPositionFor(tile_map *TileMap, U32 AbsTileX, U32 AbsTileY, U32 AbsTileZ) +static struct tile_chunk_position +GetChunkPositionFor(struct tile_map *TileMap, + unsigned int AbsTileX, unsigned int AbsTileY, + unsigned int AbsTileZ) { - tile_chunk_position Result; + struct tile_chunk_position Result; Result.TileChunkX = AbsTileX >> TileMap->ChunkShift; Result.TileChunkY = AbsTileY >> TileMap->ChunkShift; @@ -27,48 +36,68 @@ static tile_chunk_position GetChunkPositionFor(tile_map *TileMap, U32 AbsTileX, return Result; } -static U32 GetTileValueUnchecked(tile_map *TileMap, tile_chunk *TileChunk, U32 TileX, U32 TileY) +static unsigned int +GetTileValueUnchecked(struct tile_map *TileMap, + struct tile_chunk *TileChunk, + unsigned int TileX, unsigned int TileY) { ASSERT(TileChunk); ASSERT(TileX < TileMap->ChunkDim); ASSERT(TileY < TileMap->ChunkDim); - U32 TileChunkValue = TileChunk->Tiles[TileY * TileMap->ChunkDim + TileX]; + unsigned int TileChunkValue = + TileChunk->Tiles[TileY * TileMap->ChunkDim + TileX]; return TileChunkValue; } -static U32 GetTileChunkValue(tile_map *TileMap, tile_chunk *TileChunk, U32 TestTileX, U32 TestTileY) +static unsigned int +GetTileChunkValue(struct tile_map *TileMap, struct tile_chunk *TileChunk, + unsigned int TestTileX, unsigned int TestTileY) { - U32 TileChunkValue = 0; + unsigned int TileChunkValue = 0; if(TileChunk && TileChunk->Tiles) { - TileChunkValue = GetTileValueUnchecked(TileMap, TileChunk, TestTileX, TestTileY); + TileChunkValue = + GetTileValueUnchecked(TileMap, TileChunk, TestTileX, TestTileY); } return TileChunkValue; } -static U32 GetTileValue(tile_map *TileMap, U32 AbsTileX, U32 AbsTileY, U32 AbsTileZ) +static unsigned int +GetTileValue(struct tile_map *TileMap, + unsigned int AbsTileX, unsigned int AbsTileY, + unsigned int AbsTileZ) { - tile_chunk_position ChunkPos = GetChunkPositionFor(TileMap, AbsTileX, AbsTileY, AbsTileZ); - tile_chunk *TileChunk = GetTileChunk(TileMap, ChunkPos.TileChunkX, ChunkPos.TileChunkY, ChunkPos.TileChunkZ); - U32 TileChunkValue = GetTileChunkValue(TileMap, TileChunk, ChunkPos.RelTileX, ChunkPos.RelTileY); + struct tile_chunk_position ChunkPos = + GetChunkPositionFor(TileMap, AbsTileX, AbsTileY, AbsTileZ); + struct tile_chunk *TileChunk = + GetTileChunk(TileMap, ChunkPos.TileChunkX, ChunkPos.TileChunkY, + ChunkPos.TileChunkZ); + unsigned int TileChunkValue = + GetTileChunkValue(TileMap, TileChunk, ChunkPos.RelTileX, + ChunkPos.RelTileY); return TileChunkValue; } -static B32 IsTileValueEmpty(U32 TileValue) +static int IsTileValueEmpty(unsigned int TileValue) { - B32 Empty = ((TileValue == 1) || (TileValue == 3) || (TileValue == 4)); + int Empty = ((TileValue == 1) || (TileValue == 3) || (TileValue == 4)); return Empty; } -static U32 GetTileValueByPos(tile_map *TileMap, tile_map_position Pos) +static unsigned int GetTileValueByPos(struct tile_map *TileMap, + struct tile_map_position Pos) { - U32 TileChunkValue = GetTileValue(TileMap, Pos.AbsTileX, Pos.AbsTileY, Pos.AbsTileZ); + unsigned int TileChunkValue = + GetTileValue(TileMap, Pos.AbsTileX, Pos.AbsTileY, Pos.AbsTileZ); return TileChunkValue; } -static void SetTileValueUnchecked(tile_map *TileMap, tile_chunk *TileChunk, U32 TileX, U32 TileY, U32 TileValue) +static void SetTileValueUnchecked(struct tile_map *TileMap, + struct tile_chunk *TileChunk, + unsigned int TileX, unsigned int TileY, + unsigned int TileValue) { ASSERT(TileChunk); ASSERT(TileX < TileMap->ChunkDim); @@ -77,58 +106,76 @@ static void SetTileValueUnchecked(tile_map *TileMap, tile_chunk *TileChunk, U32 TileChunk->Tiles[TileY * TileMap->ChunkDim + TileX] = TileValue; } -static void SetTileChunkValue(tile_map *TileMap, tile_chunk *TileChunk, U32 TestTileX, U32 TestTileY, U32 TileValue) +static void SetTileChunkValue(struct tile_map *TileMap, + struct tile_chunk *TileChunk, + unsigned int TestTileX, unsigned int TestTileY, + unsigned int TileValue) { if(TileChunk && TileChunk->Tiles) { - SetTileValueUnchecked(TileMap, TileChunk, TestTileX, TestTileY, TileValue); + SetTileValueUnchecked(TileMap, TileChunk, TestTileX, TestTileY, + TileValue); } } -static B32 IsTileMapPointEmpty(tile_map *TileMap, tile_map_position Pos) +static int IsTileMapPointEmpty(struct tile_map *TileMap, + struct tile_map_position Pos) { - U32 TileChunkValue = GetTileValueByPos(TileMap, Pos); - B32 Empty = IsTileValueEmpty(TileChunkValue); + unsigned int TileChunkValue = GetTileValueByPos(TileMap, Pos); + int Empty = IsTileValueEmpty(TileChunkValue); return Empty; } -static void SetTileValue(memory_arena *Arena, tile_map *TileMap, U32 AbsTileX, U32 AbsTileY, U32 AbsTileZ, U32 TileValue) +static void SetTileValue(struct memory_arena *Arena, + struct tile_map *TileMap, + unsigned int AbsTileX, unsigned int AbsTileY, + unsigned int AbsTileZ, unsigned int TileValue) { - tile_chunk_position ChunkPos = GetChunkPositionFor(TileMap, AbsTileX, AbsTileY, AbsTileZ); - tile_chunk *TileChunk = GetTileChunk(TileMap, ChunkPos.TileChunkX, ChunkPos.TileChunkY, ChunkPos.TileChunkZ); + struct tile_chunk_position ChunkPos = + GetChunkPositionFor(TileMap, AbsTileX, AbsTileY, AbsTileZ); + struct tile_chunk *TileChunk = + GetTileChunk(TileMap, ChunkPos.TileChunkX, ChunkPos.TileChunkY, + ChunkPos.TileChunkZ); ASSERT(TileChunk); if(!TileChunk->Tiles) { - U32 TileCount = TileMap->ChunkDim*TileMap->ChunkDim; + unsigned int TileCount = TileMap->ChunkDim*TileMap->ChunkDim; - TileChunk->Tiles = PUSH_ARRAY(Arena, TileCount, U32); - for(U32 TileIndex = 0; TileIndex < TileCount; TileIndex++) { + TileChunk->Tiles = PUSH_ARRAY(Arena, TileCount, unsigned int); + for(unsigned int TileIndex = 0; + TileIndex < TileCount; + TileIndex++) + { TileChunk->Tiles[TileIndex] = 1; } } - SetTileChunkValue(TileMap, TileChunk, ChunkPos.RelTileX, ChunkPos.RelTileY, TileValue); + SetTileChunkValue(TileMap, TileChunk, ChunkPos.RelTileX, + ChunkPos.RelTileY, TileValue); } // // TODO: Do these belong more in a "positioning" or "geometry" file? // -static void CannonicalizeCoord(tile_map *TileMap, U32 *Tile, F32 *TileRel) +static void CannonicalizeCoord(struct tile_map *TileMap, unsigned int *Tile, + float *TileRel) { // NOTE: The world is assumed to be toroidal topology. If you step off // one end, you come back on the other. - S32 Offset = RoundF32toS32(*TileRel / TileMap->TileSideInMeters); + int Offset = RoundFloatToInt(*TileRel / TileMap->TileSideInMeters); *Tile += Offset; - *TileRel -= (F32)Offset * TileMap->TileSideInMeters; + *TileRel -= (float)Offset * TileMap->TileSideInMeters; ASSERT(*TileRel >= -0.5f*TileMap->TileSideInMeters); ASSERT(*TileRel <= 0.5f*TileMap->TileSideInMeters); } -static tile_map_position RecannonicalizePosition(tile_map *TileMap, tile_map_position Pos) +static struct tile_map_position +RecannonicalizePosition(struct tile_map *TileMap, + struct tile_map_position Pos) { - tile_map_position Result = Pos; + struct tile_map_position Result = Pos; CannonicalizeCoord(TileMap, &Result.AbsTileX, &Result.Offset.X); CannonicalizeCoord(TileMap, &Result.AbsTileY, &Result.Offset.Y); @@ -136,20 +183,28 @@ static tile_map_position RecannonicalizePosition(tile_map *TileMap, tile_map_pos return Result; } -static B32 AreOnSameTile(tile_map_position *A, tile_map_position *B) +static int AreOnSameTile(struct tile_map_position *A, + struct tile_map_position *B) { - B32 Result = ((A->AbsTileX == B->AbsTileX) && (A->AbsTileY == B->AbsTileY) && (A->AbsTileZ == B->AbsTileZ)); + int Result = ((A->AbsTileX == B->AbsTileX) && + (A->AbsTileY == B->AbsTileY) && + (A->AbsTileZ == B->AbsTileZ)); return Result; } -static tile_map_difference SubtractInF32(tile_map *TileMap, tile_map_position *A, tile_map_position *B) +static struct tile_map_difference +SubtractInFloat(struct tile_map *TileMap, + struct tile_map_position *A, struct tile_map_position *B) { - tile_map_difference Result; + struct tile_map_difference Result; - v2 dTileXY = { ((F32)A->AbsTileX - (F32)B->AbsTileX), ((F32)A->AbsTileY - (F32)B->AbsTileY) }; - F32 dTileZ = (F32)A->AbsTileZ - (F32)B->AbsTileZ; + struct v2 dTileXY = { ((float)A->AbsTileX - (float)B->AbsTileX), + ((float)A->AbsTileY - (float)B->AbsTileY) }; + float dTileZ = (float)A->AbsTileZ - (float)B->AbsTileZ; - Result.dXY = V2Add(V2Multiply(TileMap->TileSideInMeters, dTileXY), V2Subtract(A->Offset, B->Offset)); + Result.dXY = V2Add(V2Multiply(TileMap->TileSideInMeters, + dTileXY), + V2Subtract(A->Offset, B->Offset)); // TODO: Incomplete . . . Result.dZ = TileMap->TileSideInMeters*dTileZ; @@ -157,9 +212,11 @@ static tile_map_difference SubtractInF32(tile_map *TileMap, tile_map_position *A return Result; } -static tile_map_position CenteredTilePoint(U32 AbsTileX, U32 AbsTileY, U32 AbsTileZ) +static struct tile_map_position +CenteredTilePoint(unsigned int AbsTileX, unsigned int AbsTileY, + unsigned int AbsTileZ) { - tile_map_position Result; + struct tile_map_position Result; memset(&Result, 0, sizeof(Result)); Result.AbsTileX = AbsTileX; diff --git a/handmade_tile.h b/handmade_tile.h index 15e6aee..f76d464 100644 --- a/handmade_tile.h +++ b/handmade_tile.h @@ -3,46 +3,46 @@ #include "handmade_math.h" -typedef struct tile_map_difference { - v2 dXY; - F32 dZ; -} tile_map_difference; +struct tile_map_difference { + struct v2 dXY; + float dZ; +}; -typedef struct tile_map_position { - U32 AbsTileX; - U32 AbsTileY; - U32 AbsTileZ; +struct tile_map_position { + unsigned int AbsTileX; + unsigned int AbsTileY; + unsigned int AbsTileZ; /* NOTE: X and Y relative to tile center. */ - v2 Offset; -} tile_map_position; + struct v2 Offset; +}; -typedef struct tile_chunk_position { - U32 TileChunkX; - U32 TileChunkY; - U32 TileChunkZ; +struct tile_chunk_position { + unsigned int TileChunkX; + unsigned int TileChunkY; + unsigned int TileChunkZ; - U32 RelTileX; - U32 RelTileY; -} tile_chunk_position; + unsigned int RelTileX; + unsigned int RelTileY; +}; -typedef struct tile_chunk { - U32 *Tiles; -} tile_chunk; +struct tile_chunk { + unsigned int *Tiles; +}; -typedef struct tile_map { - U32 ChunkShift; - U32 ChunkMask; - U32 ChunkDim; +struct tile_map { + unsigned int ChunkShift; + unsigned int ChunkMask; + unsigned int ChunkDim; - F32 TileSideInMeters; + float TileSideInMeters; /* TODO: Real sparseness. */ - U32 TileChunkCountX; - U32 TileChunkCountY; - U32 TileChunkCountZ; + unsigned int TileChunkCountX; + unsigned int TileChunkCountY; + unsigned int TileChunkCountZ; - tile_chunk *TileChunks; -} tile_map; + struct tile_chunk *TileChunks; +}; #endif diff --git a/sdl_handmade.c b/sdl_handmade.c index d9fea10..a6612f9 100644 --- a/sdl_handmade.c +++ b/sdl_handmade.c @@ -46,47 +46,49 @@ #define RESOLUTION_WIDTH 960 #define RESOLUTION_HEIGHT 540 -static B32 GlobalRunning; +static int GlobalRunning; -static U64 GlobalPerfCountFrequency; +static unsigned long long GlobalPerfCountFrequency; #define CONTROLLER_LEFT_THUMB_DEADZONE 8000 #define MAX_CONTROLLERS 4 SDL_GameController *ControllerHandles[MAX_CONTROLLERS]; -static offscreen_buffer GlobalBackbuffer; +static struct offscreen_buffer GlobalBackbuffer; SDL_Window *LastWindow; -static B32 IsFullscreen; -static sdl_window_size WindowSize; -static sdl_window_position WindowPosition; +static int IsFullscreen; +static struct sdl_window_size WindowSize; +static struct sdl_window_position WindowPosition; -static S32 str_len(char *str) +static int str_len(char *str) { - S32 count = 0; + int count = 0; while(*str++) count++; return count; } -static U32 SafeTruncateUInt64(U64 Value) +static unsigned int SafeTruncateUInt64(unsigned long long Value) { - ASSERT(Value <= 0xFFFFFFFF); - U32 Result = (U32)Value; + ASSERT(Value <= 0xFFFFFFFF); + unsigned int Result = (unsigned int)Value; return Result; } -debug_read_file_result DEBUGPlatformReadEntireFile(thread_context *Thread, const char *Filename) +struct debug_read_file_result +DEBUGPlatformReadEntireFile(struct thread_context *Thread, + const char *Filename) { (void)Thread; - debug_read_file_result Result; + struct debug_read_file_result Result; memset(&Result, 0, sizeof(Result)); SDL_RWops *FileHandle = SDL_RWFromFile(Filename, "r"); if(FileHandle) { - S64 FileSize = SDL_RWsize(FileHandle); + long long FileSize = SDL_RWsize(FileHandle); if(FileSize >= 0) { Result.ContentsSize = SafeTruncateUInt64(FileSize); } else { @@ -102,7 +104,8 @@ debug_read_file_result DEBUGPlatformReadEntireFile(thread_context *Thread, const return Result; } - size_t ObjectsRead = SDL_RWread(FileHandle, (void *)Result.Contents, (size_t)Result.ContentsSize, 1); + unsigned int ObjectsRead = SDL_RWread(FileHandle, + (void *)Result.Contents, Result.ContentsSize, 1); if(ObjectsRead == 0) { free(Result.Contents); Result.Contents = 0; @@ -117,34 +120,42 @@ debug_read_file_result DEBUGPlatformReadEntireFile(thread_context *Thread, const return Result; } -B32 DEBUGPlatformWriteEntireFile(thread_context *Thread, const char *Filename, U32 MemorySize, void *Memory) +int DEBUGPlatformWriteEntireFile(struct thread_context *Thread, + const char *Filename, + unsigned int MemorySize, void *Memory) { SDL_RWops *FileHandle = SDL_RWFromFile(Filename, "w"); if(FileHandle) { - size_t ObjectsWritten = SDL_RWwrite(FileHandle, (void *)Memory, (size_t)MemorySize, 1); + unsigned int ObjectsWritten = SDL_RWwrite(FileHandle, + (void *)Memory, (unsigned int)MemorySize, 1); if(ObjectsWritten == 0) { SDL_RWclose(FileHandle); - return FALSE; + return 0; } SDL_RWclose(FileHandle); - return TRUE; + return 1; } - return FALSE; + return 0; } -void DEBUGPlatformFreeFileMemory(thread_context *Thread, void *Memory) +void DEBUGPlatformFreeFileMemory(struct thread_context *Thread, void *Memory) { if(Memory) - free(Memory); // TODO: Should we accept debug_read_file_result instead of just memory. + free(Memory); } -void SetProgramIcon(game_offscreen_buffer *ProgramIcon) +void SetProgramIcon(struct game_offscreen_buffer *ProgramIcon) { SDL_Window *Window = LastWindow; - SDL_Surface *Icon = SDL_CreateRGBSurfaceWithFormatFrom((void *)ProgramIcon->Memory, ProgramIcon->Width, ProgramIcon->Height, ProgramIcon->BytesPerPixel * 8, ProgramIcon->BytesPerPixel * ProgramIcon->Width, SDL_PIXELFORMAT_ARGB8888); + SDL_Surface *Icon = + SDL_CreateRGBSurfaceWithFormatFrom((void *)ProgramIcon->Memory, + ProgramIcon->Width, ProgramIcon->Height, + ProgramIcon->BytesPerPixel * 8, + ProgramIcon->BytesPerPixel * ProgramIcon->Width, + SDL_PIXELFORMAT_ARGB8888); if(!Icon) { /* TODO: This didn't work . . . SDL_GetError() */ return ; @@ -154,34 +165,37 @@ void SetProgramIcon(game_offscreen_buffer *ProgramIcon) SDL_FreeSurface(Icon); } -static sdl_border_size SDLGetWindowBorderSizes(SDL_Window *Window) +static struct sdl_border_size SDLGetWindowBorderSizes(SDL_Window *Window) { - sdl_border_size Result; - SDL_GetWindowBordersSize(Window, &Result.Top, &Result.Left, &Result.Bottom, &Result.Right); + struct sdl_border_size Result; + SDL_GetWindowBordersSize(Window, &Result.Top, &Result.Left, + &Result.Bottom, &Result.Right); return Result; } -// NOTE: All SDL window functions (SDL_GetWindowSize, SDL_GetWindowPosition, SDL_SetWindowPosition, SDL_SetWindowSize) -// work ONLY with client area. This has some weird behavior with SDL_SetWindowPosition where SDLGetWindowBorderSizes -// reports left border (of 8 in our case), however it does not have that border in reality, so we ignore left and right borders. -// As a result, we ignore left and right borders, for now. -static sdl_window_size SDLGetBorderedWindowSize(SDL_Window *Window) +/* NOTE: All SDL window functions (SDL_GetWindowSize, SDL_GetWindowPosition, + * SDL_SetWindowPosition, SDL_SetWindowSize) work ONLY with client area. */ +static struct sdl_window_size SDLGetBorderedWindowSize(SDL_Window *Window) { - sdl_border_size Border = SDLGetWindowBorderSizes(Window); + struct sdl_border_size Border = SDLGetWindowBorderSizes(Window); - sdl_window_size Dimension; + struct sdl_window_size Dimension; SDL_GetWindowSize(Window, &Dimension.Width, &Dimension.Height); - Dimension.Height += Border.Top + Border.Bottom; +#if OS_WINDOWS + // On Windows, borders must be added. + Dimension.Height += Border.Top + Border.Bottom; +#endif // Dimension.Width += Border.Left + Border.Right; return Dimension; } -static sdl_window_position SDLGetBorderedWindowPosition(SDL_Window *Window) +static struct sdl_window_position +SDLGetBorderedWindowPosition(SDL_Window *Window) { - sdl_border_size Border = SDLGetWindowBorderSizes(Window); + struct sdl_border_size Border = SDLGetWindowBorderSizes(Window); - sdl_window_position Position; + struct sdl_window_position Position; SDL_GetWindowPosition(Window, &Position.X, &Position.Y); // Position.X -= Border.Left; Position.Y -= Border.Top; @@ -189,22 +203,27 @@ static sdl_window_position SDLGetBorderedWindowPosition(SDL_Window *Window) return Position; } -static void SDLSetBorderedWindowPosition(SDL_Window *Window, S32 X, S32 Y) +static void SDLSetBorderedWindowPosition(SDL_Window *Window, int X, int Y) { - sdl_border_size Border = SDLGetWindowBorderSizes(Window); + struct sdl_border_size Border = SDLGetWindowBorderSizes(Window); SDL_SetWindowPosition(Window, X, Y + Border.Top); } -static void SDLSetBorderedWindowSize(SDL_Window *Window, S32 Width, S32 Height) +static void +SDLSetBorderedWindowSize(SDL_Window *Window, int Width, int Height) { - sdl_border_size Border = SDLGetWindowBorderSizes(Window); + struct sdl_border_size Border = SDLGetWindowBorderSizes(Window); - // SDL_SetWindowSize(Window, Width - (Border.Left + Border.Right), Height - (Border.Top + Border.Bottom)); + /* SDL_SetWindowSize(Window, + Width - (Border.Left + Border.Right), + Height - (Border.Top + Border.Bottom)); */ SDL_SetWindowSize(Window, Width, Height - (Border.Top + Border.Bottom)); } -static void SDLResizeTexture(offscreen_buffer *Buffer, SDL_Renderer *Renderer, int Width, int Height) +static void +SDLResizeTexture(struct offscreen_buffer *Buffer, + SDL_Renderer *Renderer, int Width, int Height) { if(Buffer->Texture) SDL_DestroyTexture(Buffer->Texture); @@ -212,9 +231,12 @@ static void SDLResizeTexture(offscreen_buffer *Buffer, SDL_Renderer *Renderer, i if(Buffer->Memory) free(Buffer->Memory); - S32 BytesPerPixel = 4; + int BytesPerPixel = 4; - Buffer->Texture = SDL_CreateTexture(Renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, Width, Height); + Buffer->Texture = SDL_CreateTexture(Renderer, + SDL_PIXELFORMAT_ARGB8888, + SDL_TEXTUREACCESS_STREAMING, + Width, Height); Buffer->Memory = malloc(Width * Height * BytesPerPixel); Buffer->Height = Height; @@ -222,10 +244,12 @@ static void SDLResizeTexture(offscreen_buffer *Buffer, SDL_Renderer *Renderer, i Buffer->Pitch = Width * BytesPerPixel; } -static void SDLDisplayBufferInWindow(offscreen_buffer *Buffer, SDL_Window *Window, SDL_Renderer *Renderer) +static void SDLDisplayBufferInWindow(struct offscreen_buffer *Buffer, + SDL_Window *Window, + SDL_Renderer *Renderer) { - S32 OffsetX = 10; - S32 OffsetY = 10; + int OffsetX = 10; + int OffsetY = 10; SDL_SetRenderDrawColor(Renderer, 0, 0, 0, 255); SDL_RenderClear(Renderer); @@ -234,29 +258,38 @@ static void SDLDisplayBufferInWindow(offscreen_buffer *Buffer, SDL_Window *Windo /* TODO: Do something about this error! */ } - /* TODO: We temporarily introduce the target rectangle to avoid stretching the canvas. */ + /* TODO: We temporarily introduce the target rectangle to avoid + * stretching the canvas. */ /* SDL_RenderCopy(Renderer, Buffer.Texture, 0, 0); */ - sdl_window_size WinSize = SDLGetBorderedWindowSize(Window); - if(WinSize.Width >= Buffer->Width*2 && WinSize.Height >= Buffer->Height*2) { - SDL_Rect dest_rect = { OffsetX, OffsetY, Buffer->Width*2, Buffer->Height*2 }; - SDL_RenderCopy(Renderer, Buffer->Texture, 0, (const SDL_Rect *)(&dest_rect)); + struct sdl_window_size WinSize = SDLGetBorderedWindowSize(Window); + if(WinSize.Width >= Buffer->Width*2 && + WinSize.Height >= Buffer->Height*2) + { + SDL_Rect dest_rect = + { OffsetX, OffsetY, Buffer->Width*2, Buffer->Height*2 }; + SDL_RenderCopy(Renderer, Buffer->Texture, 0, + (const SDL_Rect *)(&dest_rect)); } else { - SDL_Rect dest_rect = { OffsetX, OffsetY, RESOLUTION_WIDTH, RESOLUTION_HEIGHT }; - SDL_RenderCopy(Renderer, Buffer->Texture, 0, (const SDL_Rect *)(&dest_rect)); + SDL_Rect dest_rect = + { OffsetX, OffsetY, RESOLUTION_WIDTH, RESOLUTION_HEIGHT }; + SDL_RenderCopy(Renderer, Buffer->Texture, 0, + (const SDL_Rect *)(&dest_rect)); } SDL_RenderPresent(Renderer); } static void SDLInitControllers() { - S32 MaxJoysticks = SDL_NumJoysticks(); - S32 ControllerIndex = 0; - for(S32 JoystickIndex = 0; JoystickIndex < MaxJoysticks; JoystickIndex++) { + int MaxJoysticks = SDL_NumJoysticks(); + int ControllerIndex = 0; + for(int JoystickIndex = 0; JoystickIndex < MaxJoysticks; JoystickIndex++) + { if(!SDL_IsGameController(JoystickIndex)) continue; if(ControllerIndex >= MAX_CONTROLLERS) break; - ControllerHandles[ControllerIndex] = SDL_GameControllerOpen(JoystickIndex); + ControllerHandles[ControllerIndex] = + SDL_GameControllerOpen(JoystickIndex); ControllerIndex++; } } @@ -264,14 +297,17 @@ static void SDLInitControllers() /* static void SDLDeinitControllers() { - for(S32 ControllerIndex = 0; ControllerIndex < MAX_CONTROLLERS; ControllerIndex++) { + for(int ControllerIndex = 0; + ControllerIndex < MAX_CONTROLLERS; + ControllerIndex++) + { if(ControllerHandles[ControllerIndex]) SDL_GameControllerClose(ControllerHandles[ControllerIndex]); } } */ -static void SDLInitSound(S32 SamplesPerSecond, S32 BufferSize) +static void SDLInitSound(int SamplesPerSecond, int BufferSize) { SDL_AudioSpec AudioSettings; memset(&AudioSettings, 0, sizeof(AudioSettings)); @@ -279,7 +315,8 @@ static void SDLInitSound(S32 SamplesPerSecond, S32 BufferSize) AudioSettings.freq = SamplesPerSecond; AudioSettings.format = AUDIO_S16LSB; AudioSettings.channels = 2; - AudioSettings.samples = (U16)BufferSize; // TODO: Unsafe truncate from S32 to U16 + /* TODO: Unsafe truncate from S32 to U16 */ + AudioSettings.samples = (unsigned short)BufferSize; SDL_OpenAudio(&AudioSettings, 0); @@ -288,17 +325,19 @@ static void SDLInitSound(S32 SamplesPerSecond, S32 BufferSize) } } -static void SDLFillSoundBuffer(sdl_sound_output *SoundOutput, S32 BytesToWrite) +static void +SDLFillSoundBuffer(struct sdl_sound_output *SoundOutput, int BytesToWrite) { SDL_QueueAudio(1, SoundOutput->Samples, BytesToWrite); } -static void SDLClearSoundBuffer(sdl_sound_output *SoundOutput) +static void SDLClearSoundBuffer(struct sdl_sound_output *SoundOutput) { memset(SoundOutput->Samples, 0, SoundOutput->SecondaryBufferSize); } -static void SDLProcessKeyboardMessage(game_button_state *NewState, B32 IsDown) +static void +SDLProcessKeyboardMessage(struct game_button_state *NewState, int IsDown) { if(NewState->EndedDown != IsDown) { NewState->EndedDown = IsDown; @@ -306,10 +345,15 @@ static void SDLProcessKeyboardMessage(game_button_state *NewState, B32 IsDown) } } -static void SDLProcessInputDigitalButton(SDL_GameController *Controller, game_button_state *OldState, SDL_GameControllerButton Button, game_button_state *NewState) +static void SDLProcessInputDigitalButton(SDL_GameController *Controller, + struct game_button_state *OldState, + SDL_GameControllerButton Button, + struct game_button_state *NewState) { - NewState->EndedDown = SDL_GameControllerGetButton(Controller, Button); - NewState->HalfTransitionCount = (OldState->EndedDown != NewState->EndedDown) ? 1 : 0; + NewState->EndedDown = + SDL_GameControllerGetButton(Controller, Button); + NewState->HalfTransitionCount = + (OldState->EndedDown != NewState->EndedDown) ? 1 : 0; } static void HandleEvent(SDL_Event *Event) @@ -319,7 +363,7 @@ static void HandleEvent(SDL_Event *Event) switch(Event->type) { case SDL_QUIT: { - GlobalRunning = FALSE; + GlobalRunning = 0; } break; case SDL_WINDOWEVENT: { @@ -330,8 +374,10 @@ static void HandleEvent(SDL_Event *Event) #if 0 /* TODO: For now we fix the width and height. */ case SDL_WINDOWEVENT_SIZE_CHANGED: { - sdl_window_dimension Dimension = SDLGetWindowDimension(Window); - SDLResizeTexture(&GlobalBackbuffer, Renderer, Dimension.Width, Dimension.Height); + sdl_window_dimension Dimension = + SDLGetWindowDimension(Window); + SDLResizeTexture(&GlobalBackbuffer, Renderer, + Dimension.Width, Dimension.Height); } break; #endif @@ -358,12 +404,19 @@ static void HandleEvent(SDL_Event *Event) static void SDLToggleFullscreen(SDL_Window *Window) { - if(IsFullscreen) { - if(SDL_SetWindowFullscreen(Window, 0) == 0) { - SDLSetBorderedWindowSize(Window, WindowSize.Width, WindowSize.Height); - SDLSetBorderedWindowPosition(Window, WindowPosition.X, WindowPosition.Y); + int err; - IsFullscreen = FALSE; + if(IsFullscreen) { + err = SDL_SetWindowFullscreen(Window, 0); + if(err == 0) { + SDLSetBorderedWindowSize(Window, + WindowSize.Width, + WindowSize.Height); + SDLSetBorderedWindowPosition(Window, + WindowPosition.X, + WindowPosition.Y); + + IsFullscreen = 0; } else { /* TODO: This didn't work . . . SDL_GetError() */ } @@ -371,15 +424,18 @@ static void SDLToggleFullscreen(SDL_Window *Window) WindowSize = SDLGetBorderedWindowSize(Window); WindowPosition = SDLGetBorderedWindowPosition(Window); - if(SDL_SetWindowFullscreen(Window, SDL_WINDOW_FULLSCREEN_DESKTOP) == 0) { - IsFullscreen = TRUE; + err = SDL_SetWindowFullscreen(Window, + SDL_WINDOW_FULLSCREEN_DESKTOP); + if(err == 0) { + IsFullscreen = 1; } else { /* TODO: This didn't work . . . SDL_GetError() */ } } } -static void SDLProcessMessages(sdl_state *SDLState, game_controller_input *KeyboardController) +static void SDLProcessMessages(struct sdl_state *SDLState, + struct game_controller_input *KeyboardController) { SDL_Event Event; while(SDL_PollEvent(&Event)) { @@ -390,55 +446,68 @@ static void SDLProcessMessages(sdl_state *SDLState, game_controller_input *Keybo case SDL_KEYDOWN: case SDL_KEYUP: { SDL_Keycode KeyCode; - B32 IsDown, WasDown; + int IsDown, WasDown; KeyCode = Event.key.keysym.sym; IsDown = (Event.key.state == SDL_PRESSED); - WasDown = FALSE; + WasDown = 0; if(Event.key.state == SDL_RELEASED) { - WasDown = TRUE; + WasDown = 1; } else if(Event.key.repeat != 0) { - WasDown = TRUE; + WasDown = 1; } if(Event.key.repeat == 0) { if(KeyCode == SDLK_w) { - SDLProcessKeyboardMessage(&KeyboardController->MoveUp, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->MoveUp, IsDown); } else if(KeyCode == SDLK_s) { - SDLProcessKeyboardMessage(&KeyboardController->MoveDown, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->MoveDown, IsDown); } else if(KeyCode == SDLK_a) { - SDLProcessKeyboardMessage(&KeyboardController->MoveLeft, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->MoveLeft, IsDown); } else if(KeyCode == SDLK_d) { - SDLProcessKeyboardMessage(&KeyboardController->MoveRight, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->MoveRight, IsDown); } else if(KeyCode == SDLK_q) { - SDLProcessKeyboardMessage(&KeyboardController->LeftShoulder, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->LeftShoulder, IsDown); } else if(KeyCode == SDLK_e) { - SDLProcessKeyboardMessage(&KeyboardController->RightShoulder, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->RightShoulder, IsDown); } else if(KeyCode == SDLK_UP) { - SDLProcessKeyboardMessage(&KeyboardController->ActionUp, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->ActionUp, IsDown); } else if(KeyCode == SDLK_DOWN) { - SDLProcessKeyboardMessage(&KeyboardController->ActionDown, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->ActionDown, IsDown); } else if(KeyCode == SDLK_LEFT) { - SDLProcessKeyboardMessage(&KeyboardController->ActionLeft, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->ActionLeft, IsDown); } else if(KeyCode == SDLK_RIGHT) { - SDLProcessKeyboardMessage(&KeyboardController->ActionRight, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->ActionRight, IsDown); } else if(KeyCode == SDLK_ESCAPE) { - SDLProcessKeyboardMessage(&KeyboardController->Start, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->Back, IsDown); } else if(KeyCode == SDLK_SPACE) { - SDLProcessKeyboardMessage(&KeyboardController->Back, IsDown); + SDLProcessKeyboardMessage( + &KeyboardController->Start, IsDown); } } if(WasDown) { - /* NOTE: If your window manager already uses an Alt+F4 keybind to close programs, then we are likely - * to see SDL_QUIT event occur before our keybind. */ - B32 AltKeyWasDown = (Event.key.keysym.mod & KMOD_ALT); + /* NOTE: If your window manager already uses an Alt+F4 + * keybind to close programs, then we are likely + * to see SDL_QUIT event occur before our keybind. */ + int AltKeyWasDown = (Event.key.keysym.mod & KMOD_ALT); if(KeyCode == SDLK_F4 && AltKeyWasDown) - GlobalRunning = FALSE; + GlobalRunning = 0; #if BUILD_INTERNAL if(KeyCode == SDLK_ESCAPE) - GlobalRunning = FALSE; + GlobalRunning = 0; #endif if((KeyCode == SDLK_RETURN) && AltKeyWasDown) { @@ -454,21 +523,22 @@ static void SDLProcessMessages(sdl_state *SDLState, game_controller_input *Keybo } } -static F32 SDLProcessInputStickValue(F32 Value, S32 DeadZoneThreshold) +static float SDLProcessInputStickValue(float Value, int DeadZoneThreshold) { - F32 Result = 0.0f; - if(Value < -(F32)DeadZoneThreshold) - Result = ((Value + (F32)DeadZoneThreshold) / (32768.0f - (F32)DeadZoneThreshold)); - else if(Value > (F32)DeadZoneThreshold) - Result = ((Value + (F32)DeadZoneThreshold) / (32767.0f - (F32)DeadZoneThreshold)); - + float Result = 0.0f; + if(Value < -(float)DeadZoneThreshold) + Result = (Value + (float)DeadZoneThreshold) / + (32768.0f - (float)DeadZoneThreshold); + else if(Value > (float)DeadZoneThreshold) + Result = (Value + (float)DeadZoneThreshold) / + (32767.0f - (float)DeadZoneThreshold); return Result; } #define DEFAULT_REFRESH_RATE 60 -static S32 SDLGetWindowRefreshRate(SDL_Window *Window) +static int SDLGetWindowRefreshRate(SDL_Window *Window) { - S32 DisplayIndex = SDL_GetWindowDisplayIndex(Window); + int DisplayIndex = SDL_GetWindowDisplayIndex(Window); SDL_DisplayMode Mode; if(SDL_GetDesktopDisplayMode(DisplayIndex, &Mode) != 0) @@ -479,26 +549,31 @@ static S32 SDLGetWindowRefreshRate(SDL_Window *Window) return Mode.refresh_rate; } -static U64 SDLGetWallClock() +static unsigned long long SDLGetWallClock() { return SDL_GetPerformanceCounter(); } -static F32 SDLGetSecondsElapsed(U64 Start, U64 End) +static float SDLGetSecondsElapsed(unsigned long long Start, + unsigned long long End) { - return (F32)(End - Start) / (F32)GlobalPerfCountFrequency; + return (float)(End - Start) / (float)GlobalPerfCountFrequency; } -typedef struct sdl_game_code { +struct sdl_game_code { void *GameCodeDLL; - U32 DLLLastWriteTime; + unsigned int DLLLastWriteTime; - void (*UpdateAndRender)(thread_context *Thread, game_memory *, game_input *, game_offscreen_buffer *, game_sound_output_buffer *); + void (*UpdateAndRender)(struct thread_context *Thread, + struct game_memory *, + struct game_input *, + struct game_offscreen_buffer *, + struct game_sound_output_buffer *); - B32 IsValid; -} sdl_game_code; + int IsValid; +}; -static U32 GetLastWriteTime(const char *FileName) +static unsigned int GetLastWriteTime(const char *FileName) { struct stat file_info; memset(&file_info, 0, sizeof(file_info)); @@ -507,7 +582,7 @@ static U32 GetLastWriteTime(const char *FileName) /* TODO: Diagnostic. perror("stat failed"); */ } - return (U32)file_info.st_mtime; + return (unsigned int)file_info.st_mtime; } #if OS_MACOS || OS_LINUX @@ -518,9 +593,9 @@ static U32 GetLastWriteTime(const char *FileName) #error Unknown OS: please specify GAME_DLL_NAME #endif -static sdl_game_code SDLLoadGameCode(char *DLLPath) +static struct sdl_game_code SDLLoadGameCode(char *DLLPath) { - sdl_game_code Result; + struct sdl_game_code Result; memset(&Result, 0, sizeof(Result)); #if OS_MACOS || OS_LINUX @@ -535,9 +610,16 @@ static sdl_game_code SDLLoadGameCode(char *DLLPath) Result.DLLLastWriteTime = GetLastWriteTime(DLLPath); #if OS_MACOS || OS_LINUX - Result.UpdateAndRender = (void(*)(thread_context *, game_memory *, game_input *, game_offscreen_buffer *, game_sound_output_buffer *))dlsym(Result.GameCodeDLL, "UpdateAndRender"); + Result.UpdateAndRender = (void(*)(struct thread_context *, + struct game_memory *, + struct game_input *, struct game_offscreen_buffer *, + struct game_sound_output_buffer *))dlsym(Result.GameCodeDLL, + "UpdateAndRender"); #elif OS_WINDOWS - Result.UpdateAndRender = (void(*)(thread_context *, game_memory *, game_input *, game_offscreen_buffer *, game_sound_output_buffer *))GetProcAddress(Result.GameCodeDLL, "UpdateAndRender"); + Result.UpdateAndRender = (void(*)(thread_context *, game_memory *, + game_input *, game_offscreen_buffer *, + game_sound_output_buffer *))GetProcAddress(Result.GameCodeDLL, + "UpdateAndRender"); #else #error Unknown OS: implement DLL loading... #endif @@ -546,19 +628,19 @@ static sdl_game_code SDLLoadGameCode(char *DLLPath) /* TODO: Diagnostic. dlerror() */ } - Result.IsValid = Result.UpdateAndRender ? TRUE : FALSE; + Result.IsValid = Result.UpdateAndRender ? 1 : 0; } else { /* TODO: Diagnostic. dlerror() */ } if(!Result.IsValid) { - Result.UpdateAndRender = NULL; + Result.UpdateAndRender = 0; } return Result; } -static void SDLUnloadGameCode(sdl_game_code *GameCode) +static void SDLUnloadGameCode(struct sdl_game_code *GameCode) { if(GameCode->GameCodeDLL) { #if OS_MACOS || OS_LINUX @@ -569,14 +651,14 @@ static void SDLUnloadGameCode(sdl_game_code *GameCode) #error Unknown OS: implement closing of DLL #endif } - GameCode->IsValid = FALSE; - GameCode->UpdateAndRender = NULL; + GameCode->IsValid = 0; + GameCode->UpdateAndRender = 0; } void GetExecutablePath(char *path, size_t path_size) { #if OS_MACOS - U32 size; + unsigned int size; #elif OS_LINUX ssize_t size; #endif @@ -586,7 +668,8 @@ void GetExecutablePath(char *path, size_t path_size) #if OS_MACOS size = path_size; - if(_NSGetExecutablePath(path, &size) != 0) { /* NOTE: Not an absolute path. */ + if(_NSGetExecutablePath(path, &size) != 0) { /* Not an absolute + path. */ /* TODO: Diagnostics. */ } #elif OS_LINUX @@ -607,15 +690,15 @@ void GetExecutablePath(char *path, size_t path_size) static void SDLGetEXEDirPath(char *path, size_t path_size) { GetExecutablePath(path, path_size); - U32 len = str_len(path); - U32 i = len; + unsigned int len = str_len(path); + unsigned int i = len; #if OS_MACOS || OS_LINUX char delimeter = '/'; #elif OS_WINDOWS char delimeter = '\\'; #else -#error Unknown OS: specify whether your OS uses forward or backward slashes for paths +#error Unknown OS: OS uses forward or backward slashes for paths? #endif while(path[i] != delimeter || i == 0) { @@ -636,13 +719,14 @@ U64 __rdtsc() } #endif -S32 main(S32 argc, char *argv[]) +int main(int argc, char *argv[]) { - sdl_state SDLState; + struct sdl_state SDLState; memset(&SDLState, 0, sizeof(SDLState)); SDLGetEXEDirPath(SDLState.EXEDirPath, sizeof(SDLState.EXEDirPath)); - SDLGetDLLPath(SDLState.DLLPath, sizeof(SDLState.DLLPath), SDLState.EXEDirPath); + SDLGetDLLPath(SDLState.DLLPath, sizeof(SDLState.DLLPath), + SDLState.EXEDirPath); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER)) { /* TODO: This didn't work . . . */ @@ -650,23 +734,27 @@ S32 main(S32 argc, char *argv[]) SDLInitControllers(); - /* NOTE: Floating windows are not supported oficially by Wayland - * protocol. However, SDL_WINDOW_ALWAYS_ON_TOP does work on KDE - * under Wayland. I have not tested GNOME. */ - /* NOTE: We create the window hidden at first. This is so that we do not get a window outline - * that shows up whilst it is waiting for the rendered to be created. We want to display - * the window once everything is ready. */ - // TODO: SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, in non-debug build - SDL_Window *Window = SDL_CreateWindow("Handmade Hero", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, RESOLUTION_WIDTH+20, RESOLUTION_HEIGHT+20, SDL_WINDOW_HIDDEN | SDL_WINDOW_RESIZABLE/* | SDL_WINDOW_ALWAYS_ON_TOP*/); + /* NOTE: Create hidden window so that a blank window doesn't appear + * before everything is ready. */ + /* TODO: SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, in non-debug + * build */ + SDL_Window *Window = SDL_CreateWindow("Handmade Hero", + SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, + RESOLUTION_WIDTH+20, RESOLUTION_HEIGHT+20, + SDL_WINDOW_HIDDEN | SDL_WINDOW_RESIZABLE/* | + SDL_WINDOW_ALWAYS_ON_TOP*/); if(Window) { LastWindow = Window; SDL_DisplayMode display_mode; - SDL_GetCurrentDisplayMode(0, &display_mode); // Various display information. + SDL_GetCurrentDisplayMode(0, &display_mode); - SDL_Renderer *Renderer = SDL_CreateRenderer(Window, -1, SDL_RENDERER_PRESENTVSYNC); + SDL_Renderer *Renderer = + SDL_CreateRenderer(Window, -1, SDL_RENDERER_PRESENTVSYNC); - /* NOTE: For future reference, the custom window bar should use SDL_SetWindowHitTest to define areas that will be used to drag the window. */ + /* NOTE: For future reference, the custom window bar should use + * SDL_SetWindowHitTest to define areas that will be used to drag + * the window. */ /* "Wayland needs an event loop and rendering or it won't function." * https://github.com/libsdl-org/SDL/issues/7699#issuecomment-1545684792 */ @@ -675,29 +763,12 @@ S32 main(S32 argc, char *argv[]) * its actual size. */ /* SDL_RenderPresent(Renderer) is enough to display the window. */ if(Renderer) { - thread_context TempContext; // TODO: + struct thread_context TempContext; memset(&TempContext, 0, sizeof(TempContext)); - // TODO: It should be in the handmade layer. Expose the SDLSetProgramIcon to handmade layer the same way we expose file writing. - // This way, we can use all the drawing functions of handmade. - // https://learn.microsoft.com/en-us/windows/apps/design/iconography/app-icon-construction - // Probably, the icon size should be 256x256, so windows scales it properly. This buffer should be allocated into the arena. -#if 0 - loaded_bitmap ProgramIcon = DEBUGLoadBMPP(&TempContext, DEBUGPlatformReadEntireFile, "data/program_icon.bmp"); - game_offscreen_buffer ProgramIconBuffer; - ProgramIconBuffer.Memory = malloc((ProgramIcon.Width * ProgramIcon.Height) * 4); - ProgramIconBuffer.Width = ProgramIcon.Width; - ProgramIconBuffer.Height = ProgramIcon.Height; - ProgramIconBuffer.BytesPerPixel = 4; - ProgramIconBuffer.Pitch = ProgramIconBuffer.BytesPerPixel * ProgramIcon.Width; - memset(ProgramIconBuffer.Memory, 0, (ProgramIcon.Width * ProgramIcon.Height) * ProgramIconBuffer.BytesPerPixel); - - DrawBitmap(&ProgramIconBuffer, &ProgramIcon, 0, 0, 0, 0); - SDLSetProgramIcon(Window, &ProgramIconBuffer); -#endif - - // TODO: Make it a global. - SDL_Cursor *PointerCursor = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW); + /* TODO: Make it a global. */ + SDL_Cursor *PointerCursor = + SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW); SDL_SetCursor(PointerCursor); #if !BUILD_INTERNAL if(SDL_ShowCursor(SDL_DISABLE) < 0) { @@ -707,197 +778,331 @@ S32 main(S32 argc, char *argv[]) SDL_Rect UsableDisplayRect; SDL_GetDisplayUsableBounds(0, &UsableDisplayRect); - sdl_window_size CurrentWindowSize = SDLGetBorderedWindowSize(Window); - SDLSetBorderedWindowPosition(Window, (UsableDisplayRect.x + UsableDisplayRect.w - CurrentWindowSize.Width), (UsableDisplayRect.y + UsableDisplayRect.h - CurrentWindowSize.Height)); + struct sdl_window_size CurrentWindowSize = + SDLGetBorderedWindowSize(Window); + SDLSetBorderedWindowPosition(Window, + (UsableDisplayRect.x + UsableDisplayRect.w - + CurrentWindowSize.Width), + (UsableDisplayRect.y + UsableDisplayRect.h - + CurrentWindowSize.Height)); - GlobalRunning = TRUE; + GlobalRunning = 1; - //sdl_window_dimension Dimension = SDLGetWindowDimension(Window); - //SDLResizeTexture(&GlobalBackbuffer, Renderer, Dimension.Width, Dimension.Height); - SDLResizeTexture(&GlobalBackbuffer, Renderer, RESOLUTION_WIDTH, RESOLUTION_HEIGHT); + /* sdl_window_dimension Dimension = + SDLGetWindowDimension(Window); */ + /* SDLResizeTexture(&GlobalBackbuffer, Renderer, + Dimension.Width, Dimension.Height); */ + SDLResizeTexture(&GlobalBackbuffer, Renderer, + RESOLUTION_WIDTH, RESOLUTION_HEIGHT); - sdl_sound_output SoundOutput; + struct sdl_sound_output SoundOutput; memset(&SoundOutput, 0, sizeof(SoundOutput)); SoundOutput.SamplesPerSecond = 48000; - SoundOutput.BytesPerSample = sizeof(S16) * 2; - SoundOutput.SecondaryBufferSize = SoundOutput.SamplesPerSecond * SoundOutput.BytesPerSample; - SoundOutput.LatencySampleCount = SoundOutput.SamplesPerSecond / 15; + SoundOutput.BytesPerSample = sizeof(short) * 2; + SoundOutput.SecondaryBufferSize = + SoundOutput.SamplesPerSecond * SoundOutput.BytesPerSample; + SoundOutput.LatencySampleCount = + SoundOutput.SamplesPerSecond / 15; - SDLInitSound(SoundOutput.SamplesPerSecond, SoundOutput.SamplesPerSecond * SoundOutput.BytesPerSample / 60); - SDL_PauseAudio(0); // TODO: This should be paused until we have some actual sound to play. + SDLInitSound(SoundOutput.SamplesPerSecond, + SoundOutput.SamplesPerSecond * SoundOutput.BytesPerSample / + 60); + /* TODO: Should be paused until we have sound to play. */ + SDL_PauseAudio(0); - SoundOutput.Samples = calloc(SoundOutput.SamplesPerSecond, SoundOutput.BytesPerSample); - /* SoundOutput.Samples = malloc(SoundOutput.SecondaryBufferSize); */ + SoundOutput.Samples = calloc(SoundOutput.SamplesPerSecond, + SoundOutput.BytesPerSample); + /*SoundOutput.Samples = malloc(SoundOutput.SecondaryBufferSize);*/ /* NOTE: calloc auto clears to zero */ /* SDLClearSoundBuffer(&SoundOutput); */ #if BUILD_DEBUG - void *BaseAddress = (void *)TB(2); + void *BaseAddress = (void *)TB(2); #else - void *BaseAddress = (void *)(0); + void *BaseAddress = (void *)(0); #endif - game_memory GameMemory; + struct game_memory GameMemory; memset(&GameMemory, 0, sizeof(GameMemory)); GameMemory.PermanentStorageSize = MB(64); GameMemory.TransientStorageSize = GB(1); - GameMemory.DEBUGPlatformReadEntireFile = &DEBUGPlatformReadEntireFile; + GameMemory.DEBUGPlatformReadEntireFile = + &DEBUGPlatformReadEntireFile; GameMemory.SetProgramIcon = &SetProgramIcon; - //GameMemory.DEBUGPlatformWriteEntireFile = &DEBUGPlatformWriteEntireFile; - GameMemory.DEBUGPlatformFreeFileMemory = &DEBUGPlatformFreeFileMemory; + /* GameMemory.DEBUGPlatformWriteEntireFile = + &DEBUGPlatformWriteEntireFile; */ + GameMemory.DEBUGPlatformFreeFileMemory = + &DEBUGPlatformFreeFileMemory; - SDLState.TotalSize = GameMemory.PermanentStorageSize + GameMemory.TransientStorageSize; + SDLState.TotalSize = GameMemory.PermanentStorageSize + + GameMemory.TransientStorageSize; #if OS_MACOS || OS_LINUX - /* NOTE: On MacOS and Linux, mmap seems to zero-fill anonymous memory as a side-effect of security. */ - SDLState.GameMmemoryBlock = mmap(BaseAddress, (size_t)SDLState.TotalSize, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); + /* NOTE: On MacOS and Linux, mmap seems to zero-fill anonymous + * memory as a side-effect of security. */ + SDLState.GameMmemoryBlock = mmap(BaseAddress, + (size_t)SDLState.TotalSize, + PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); #elif OS_WINDOWS - SDLState.GameMmemoryBlock = VirtualAlloc(BaseAddress, SDLState.TotalSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + SDLState.GameMmemoryBlock = VirtualAlloc(BaseAddress, + SDLState.TotalSize, + MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); #else #error Unknown OS: please, allocate memory for arena #endif GameMemory.PermanentStorage = SDLState.GameMmemoryBlock; - GameMemory.TransientStorage = (U8 *)(GameMemory.PermanentStorage) + GameMemory.PermanentStorageSize; + GameMemory.TransientStorage = + (unsigned char *)(GameMemory.PermanentStorage) + + GameMemory.PermanentStorageSize; - if(SoundOutput.Samples && GameMemory.PermanentStorage && GameMemory.TransientStorage) { - game_input Input[2]; + if(SoundOutput.Samples && + GameMemory.PermanentStorage && + GameMemory.TransientStorage) + { + struct game_input Input[2]; - U64 LastCounter; - U64 LastCycleCount; + unsigned long long LastCounter; + unsigned long long LastCycleCount; - S32 MonitorRefreshHz = SDLGetWindowRefreshRate(Window); + int MonitorRefreshHz = SDLGetWindowRefreshRate(Window); /*GameUpdateHz = MonitorRefreshHz;*/ - S32 GameUpdateHz = 30; /* NOTE: Temporarily target 30 FPS. */ - F32 TargetSecondsPerFrame = 1.0f / (F32)GameUpdateHz; + int GameUpdateHz = 30; /* NOTE: Temporarily target 30 FPS. */ + float TargetSecondsPerFrame = 1.0f / (float)GameUpdateHz; - game_input *NewInput = &Input[0]; - game_input *OldInput = &Input[1]; + struct game_input *NewInput = &Input[0]; + struct game_input *OldInput = &Input[1]; memset(Input, 0, sizeof(Input)); GlobalPerfCountFrequency = SDL_GetPerformanceFrequency(); - sdl_game_code Game = SDLLoadGameCode(SDLState.DLLPath); + struct sdl_game_code Game = SDLLoadGameCode(SDLState.DLLPath); SDL_ShowWindow(Window); // Everything is ready; display the window. - U64 FPSLastCounter = SDLGetWallClock(); + unsigned long long FPSLastCounter = SDLGetWallClock(); while(GlobalRunning) { NewInput->dtForFrame = TargetSecondsPerFrame; LastCounter = SDLGetWallClock(); - /* NOTE: rdtsc reports clock cylces, however it is not meant for really precise profiler work as the - * value returned is varied. Also, __rdtsc is not available on MacOS ARM; I have not checked MacOS x64. */ + /* NOTE: rdtsc reports clock cylces, however it is not + * meant for really precise profiler work as the value + * returned is varied. Also, __rdtsc is not available + * on MacOS ARM; I have not checked MacOS x64. */ LastCycleCount = __rdtsc(); - U32 NewDLLWriteTime = GetLastWriteTime(SDLState.DLLPath); + unsigned int NewDLLWriteTime = + GetLastWriteTime(SDLState.DLLPath); if(NewDLLWriteTime > Game.DLLLastWriteTime) { SDLUnloadGameCode(&Game); Game = SDLLoadGameCode(SDLState.DLLPath); } - S32 MouseX, MouseY; + int MouseX, MouseY; SDL_GetGlobalMouseState(&MouseX, &MouseY); - S32 WindowX, WindowY; + int WindowX, WindowY; SDL_GetWindowPosition(Window, &WindowX, &WindowY); NewInput->MouseX = MouseX - WindowX; NewInput->MouseY = MouseY - WindowY; - U32 SDLMouseButtons = SDL_GetMouseState(NULL, NULL); + unsigned int SDLMouseButtons = + SDL_GetMouseState(NULL, NULL); NewInput->MouseZ = 0; /* TODO: Support mouse wheel? */ - SDLProcessKeyboardMessage(&(NewInput->MouseButtons[0]), SDL_BUTTON_LMASK & SDLMouseButtons); - SDLProcessKeyboardMessage(&(NewInput->MouseButtons[1]), SDL_BUTTON_MMASK & SDLMouseButtons); - SDLProcessKeyboardMessage(&(NewInput->MouseButtons[2]), SDL_BUTTON_RMASK & SDLMouseButtons); - /* WARNING: TODO: SDL_BUTTON_X1MASK and SDL_BUTTON_X2MASK cannot be on at the same time for some reason. */ - SDLProcessKeyboardMessage(&(NewInput->MouseButtons[3]), SDL_BUTTON_X1MASK & SDLMouseButtons); - SDLProcessKeyboardMessage(&(NewInput->MouseButtons[4]), SDL_BUTTON_X2MASK & SDLMouseButtons); + SDLProcessKeyboardMessage(&(NewInput->MouseButtons[0]), + SDL_BUTTON_LMASK & SDLMouseButtons); + SDLProcessKeyboardMessage(&(NewInput->MouseButtons[1]), + SDL_BUTTON_MMASK & SDLMouseButtons); + SDLProcessKeyboardMessage(&(NewInput->MouseButtons[2]), + SDL_BUTTON_RMASK & SDLMouseButtons); + /* WARNING: TODO: SDL_BUTTON_X1MASK and SDL_BUTTON_X2MASK + * cannot be on at the same time for some reason. */ + SDLProcessKeyboardMessage(&(NewInput->MouseButtons[3]), + SDL_BUTTON_X1MASK & SDLMouseButtons); + SDLProcessKeyboardMessage(&(NewInput->MouseButtons[4]), + SDL_BUTTON_X2MASK & SDLMouseButtons); - game_controller_input *OldKeyboardController = GetController(OldInput, 0); - game_controller_input *NewKeyboardController = GetController(NewInput, 0); - game_controller_input ZeroController; + struct game_controller_input *OldKeyboardController = + GetController(OldInput, 0); + struct game_controller_input *NewKeyboardController = + GetController(NewInput, 0); + struct game_controller_input ZeroController; memset(&ZeroController, 0, sizeof(ZeroController)); *NewKeyboardController = ZeroController; - NewKeyboardController->IsConnected = TRUE; + NewKeyboardController->IsConnected = 1; - for(U32 ButtonIndex = 0; ButtonIndex < ARRAY_SIZE(NewKeyboardController->Buttons); ButtonIndex++) { - NewKeyboardController->Buttons[ButtonIndex].EndedDown = OldKeyboardController->Buttons[ButtonIndex].EndedDown; + for(unsigned int ButtonIndex = 0; + ButtonIndex < + ARRAY_SIZE(NewKeyboardController->Buttons); + ButtonIndex++) + { + NewKeyboardController-> + Buttons[ButtonIndex].EndedDown = + OldKeyboardController-> + Buttons[ButtonIndex].EndedDown; } SDLProcessMessages(&SDLState, NewKeyboardController); - for(U32 ControllerIndex = 0; ControllerIndex < MAX_CONTROLLERS; ControllerIndex++) { - game_controller_input *OldController = GetController(OldInput, ControllerIndex+1); - game_controller_input *NewController = GetController(NewInput, ControllerIndex+1); + for(unsigned int ControllerIndex = 0; + ControllerIndex < MAX_CONTROLLERS; + ControllerIndex++) + { + struct game_controller_input *OldController = + GetController(OldInput, ControllerIndex+1); + struct game_controller_input *NewController = + GetController(NewInput, ControllerIndex+1); - if(ControllerHandles[ControllerIndex] != 0 && SDL_GameControllerGetAttached(ControllerHandles[ControllerIndex])) { - NewController->IsAnalog = OldController->IsAnalog; - NewController->IsConnected = TRUE; + if(ControllerHandles[ControllerIndex] != 0 && + SDL_GameControllerGetAttached( + ControllerHandles[ControllerIndex])) + { + NewController->IsAnalog = + OldController->IsAnalog; + NewController->IsConnected = 1; - S16 StickX = SDL_GameControllerGetAxis(ControllerHandles[ControllerIndex], SDL_CONTROLLER_AXIS_LEFTX); - S16 StickY = SDL_GameControllerGetAxis(ControllerHandles[ControllerIndex], SDL_CONTROLLER_AXIS_LEFTY); + short StickX = SDL_GameControllerGetAxis( + ControllerHandles[ControllerIndex], + SDL_CONTROLLER_AXIS_LEFTX); + short StickY = SDL_GameControllerGetAxis( + ControllerHandles[ControllerIndex], + SDL_CONTROLLER_AXIS_LEFTY); - NewController->IsAnalog = TRUE; - NewController->StickAverageX = SDLProcessInputStickValue((F32)StickX, CONTROLLER_LEFT_THUMB_DEADZONE); - NewController->StickAverageY = SDLProcessInputStickValue((F32)StickY, CONTROLLER_LEFT_THUMB_DEADZONE); + NewController->IsAnalog = 1; + NewController->StickAverageX = + SDLProcessInputStickValue((float)StickX, + CONTROLLER_LEFT_THUMB_DEADZONE); + NewController->StickAverageY = + SDLProcessInputStickValue((float)StickY, + CONTROLLER_LEFT_THUMB_DEADZONE); - if((NewController->StickAverageX != 0.0f) || (NewController->StickAverageY != 0.0f)) { - NewController->IsAnalog = TRUE; + if(NewController->StickAverageX != 0.0f || + NewController->StickAverageY != 0.0f) + { + NewController->IsAnalog = 1; } - if(SDL_GameControllerGetButton(ControllerHandles[ControllerIndex], SDL_CONTROLLER_BUTTON_DPAD_UP)) { + if(SDL_GameControllerGetButton( + ControllerHandles[ControllerIndex], + SDL_CONTROLLER_BUTTON_DPAD_UP)) + { NewController->StickAverageY = -1.0f; - NewController->IsAnalog = FALSE; + NewController->IsAnalog = 0; } - if(SDL_GameControllerGetButton(ControllerHandles[ControllerIndex], SDL_CONTROLLER_BUTTON_DPAD_DOWN)) { + if(SDL_GameControllerGetButton( + ControllerHandles[ControllerIndex], + SDL_CONTROLLER_BUTTON_DPAD_DOWN)) + { NewController->StickAverageY = 1.0f; - NewController->IsAnalog = FALSE; + NewController->IsAnalog = 0; } - if(SDL_GameControllerGetButton(ControllerHandles[ControllerIndex], SDL_CONTROLLER_BUTTON_DPAD_LEFT)) { + if(SDL_GameControllerGetButton( + ControllerHandles[ControllerIndex], + SDL_CONTROLLER_BUTTON_DPAD_LEFT)) + { NewController->StickAverageX = -1.0f; - NewController->IsAnalog = FALSE; + NewController->IsAnalog = 0; } - if(SDL_GameControllerGetButton(ControllerHandles[ControllerIndex], SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) { + if(SDL_GameControllerGetButton( + ControllerHandles[ControllerIndex], + SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) + { NewController->StickAverageX = 1.0f; - NewController->IsAnalog = FALSE; + NewController->IsAnalog = 0; } - F32 Threshold = 0.5f; - SDLProcessInputDigitalButton(ControllerHandles[(NewController->StickAverageY < -Threshold) ? 1 : 0], &OldController->MoveUp, SDL_CONTROLLER_BUTTON_A, &NewController->MoveUp); - SDLProcessInputDigitalButton(ControllerHandles[(NewController->StickAverageY > Threshold) ? 1 : 0], &OldController->MoveDown, SDL_CONTROLLER_BUTTON_A, &NewController->MoveDown); - SDLProcessInputDigitalButton(ControllerHandles[(NewController->StickAverageX < -Threshold) ? 1 : 0], &OldController->MoveLeft, SDL_CONTROLLER_BUTTON_A, &NewController->MoveLeft); - SDLProcessInputDigitalButton(ControllerHandles[(NewController->StickAverageX > Threshold) ? 1 : 0], &OldController->MoveRight, SDL_CONTROLLER_BUTTON_A, &NewController->MoveRight); + float Threshold = 0.5f; + SDLProcessInputDigitalButton( + ControllerHandles[(NewController-> + StickAverageY < -Threshold) ? 1 : 0], + &OldController->MoveUp, + SDL_CONTROLLER_BUTTON_A, + &NewController->MoveUp); + SDLProcessInputDigitalButton( + ControllerHandles[(NewController-> + StickAverageY > Threshold) ? 1 : 0], + &OldController->MoveDown, + SDL_CONTROLLER_BUTTON_A, + &NewController->MoveDown); + SDLProcessInputDigitalButton( + ControllerHandles[(NewController-> + StickAverageX < -Threshold) ? 1 : 0], + &OldController->MoveLeft, + SDL_CONTROLLER_BUTTON_A, + &NewController->MoveLeft); + SDLProcessInputDigitalButton( + ControllerHandles[(NewController-> + StickAverageX > Threshold) ? 1 : 0], + &OldController->MoveRight, + SDL_CONTROLLER_BUTTON_A, + &NewController->MoveRight); - SDLProcessInputDigitalButton(ControllerHandles[ControllerIndex], &OldController->ActionDown, SDL_CONTROLLER_BUTTON_A, &NewController->ActionDown); - SDLProcessInputDigitalButton(ControllerHandles[ControllerIndex], &OldController->ActionRight, SDL_CONTROLLER_BUTTON_B, &NewController->ActionRight); - SDLProcessInputDigitalButton(ControllerHandles[ControllerIndex], &OldController->ActionLeft, SDL_CONTROLLER_BUTTON_X, &NewController->ActionLeft); - SDLProcessInputDigitalButton(ControllerHandles[ControllerIndex], &OldController->ActionUp, SDL_CONTROLLER_BUTTON_Y, &NewController->ActionUp); - SDLProcessInputDigitalButton(ControllerHandles[ControllerIndex], &OldController->LeftShoulder, SDL_CONTROLLER_BUTTON_LEFTSHOULDER, &NewController->LeftShoulder); - SDLProcessInputDigitalButton( ControllerHandles[ControllerIndex], &OldController->RightShoulder, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, &NewController->RightShoulder); + SDLProcessInputDigitalButton( + ControllerHandles[ControllerIndex], + &OldController->ActionDown, + SDL_CONTROLLER_BUTTON_A, + &NewController->ActionDown); + SDLProcessInputDigitalButton( + ControllerHandles[ControllerIndex], + &OldController->ActionRight, + SDL_CONTROLLER_BUTTON_B, + &NewController->ActionRight); + SDLProcessInputDigitalButton( + ControllerHandles[ControllerIndex], + &OldController->ActionLeft, + SDL_CONTROLLER_BUTTON_X, + &NewController->ActionLeft); + SDLProcessInputDigitalButton( + ControllerHandles[ControllerIndex], + &OldController->ActionUp, + SDL_CONTROLLER_BUTTON_Y, + &NewController->ActionUp); + SDLProcessInputDigitalButton( + ControllerHandles[ControllerIndex], + &OldController->LeftShoulder, + SDL_CONTROLLER_BUTTON_LEFTSHOULDER, + &NewController->LeftShoulder); + SDLProcessInputDigitalButton( + ControllerHandles[ControllerIndex], + &OldController->RightShoulder, + SDL_CONTROLLER_BUTTON_RIGHTSHOULDER, + &NewController->RightShoulder); - SDLProcessInputDigitalButton(ControllerHandles[ControllerIndex], &OldController->Start, SDL_CONTROLLER_BUTTON_START, &NewController->Start); - SDLProcessInputDigitalButton( ControllerHandles[ControllerIndex], &OldController->Back, SDL_CONTROLLER_BUTTON_BACK, &NewController->Back); + SDLProcessInputDigitalButton( + ControllerHandles[ControllerIndex], + &OldController->Start, + SDL_CONTROLLER_BUTTON_START, + &NewController->Start); + SDLProcessInputDigitalButton( + ControllerHandles[ControllerIndex], + &OldController->Back, + SDL_CONTROLLER_BUTTON_BACK, + &NewController->Back); } else { /* NOTE: This controller is not plugged in. */ - NewController->IsConnected = FALSE; + NewController->IsConnected = 0; } } - S32 TargetQueueBytes = SoundOutput.LatencySampleCount * SoundOutput.BytesPerSample; - S32 BytesToWrite = TargetQueueBytes - SDL_GetQueuedAudioSize(1); - game_sound_output_buffer SoundBuffer; - SoundBuffer.SamplesPerSecond = SoundOutput.SamplesPerSecond; - SoundBuffer.SampleCount = BytesToWrite / SoundOutput.BytesPerSample; + int TargetQueueBytes = SoundOutput.LatencySampleCount * + SoundOutput.BytesPerSample; + int BytesToWrite = + TargetQueueBytes - SDL_GetQueuedAudioSize(1); + struct game_sound_output_buffer SoundBuffer; + SoundBuffer.SamplesPerSecond = + SoundOutput.SamplesPerSecond; + SoundBuffer.SampleCount = + BytesToWrite / SoundOutput.BytesPerSample; SoundBuffer.Samples = (short *)SoundOutput.Samples; - thread_context Context; + struct thread_context Context; memset(&Context, 0, sizeof(Context)); - game_offscreen_buffer Buffer; + struct game_offscreen_buffer Buffer; Buffer.Memory = GlobalBackbuffer.Memory; Buffer.Width = GlobalBackbuffer.Width; Buffer.Height = GlobalBackbuffer.Height; @@ -905,46 +1110,69 @@ S32 main(S32 argc, char *argv[]) Buffer.Pitch = GlobalBackbuffer.Pitch; if(Game.UpdateAndRender) { - Game.UpdateAndRender(&Context, &GameMemory, NewInput, &Buffer, &SoundBuffer); + Game.UpdateAndRender(&Context, &GameMemory, + NewInput, &Buffer, + &SoundBuffer); } SDLFillSoundBuffer(&SoundOutput, BytesToWrite); - U64 WorkCounter = SDLGetWallClock(); - F32 WorkSecondsElapsed = SDLGetSecondsElapsed(LastCounter, WorkCounter); + unsigned long long WorkCounter = SDLGetWallClock(); + float WorkSecondsElapsed = + SDLGetSecondsElapsed(LastCounter, WorkCounter); - F32 SecondsElapsedForFrame = WorkSecondsElapsed; + float SecondsElapsedForFrame = WorkSecondsElapsed; if(SecondsElapsedForFrame < TargetSecondsPerFrame) { - while(SecondsElapsedForFrame < TargetSecondsPerFrame) { - SecondsElapsedForFrame = SDLGetSecondsElapsed(LastCounter, SDLGetWallClock()); - if((TargetSecondsPerFrame - SecondsElapsedForFrame) >= 0.0f) - SDL_Delay((U32)((TargetSecondsPerFrame - SecondsElapsedForFrame) * 1000.0)); + while(SecondsElapsedForFrame < TargetSecondsPerFrame) + { + SecondsElapsedForFrame = + SDLGetSecondsElapsed(LastCounter, + SDLGetWallClock()); + if(TargetSecondsPerFrame - + SecondsElapsedForFrame >= 0.0f) + { + SDL_Delay((unsigned int)( + (TargetSecondsPerFrame - + SecondsElapsedForFrame) * 1000.0)); + } } } else { /* TODO: Missed frame rate! */ /* TODO: Logging. */ } - U64 EndCounter = SDLGetWallClock(); + unsigned long long EndCounter = SDLGetWallClock(); - SDLDisplayBufferInWindow(&GlobalBackbuffer, Window, Renderer); + SDLDisplayBufferInWindow(&GlobalBackbuffer, Window, + Renderer); - F64 MSPerFrame = 1000.0 * SDLGetSecondsElapsed(LastCounter, EndCounter); - F64 FPS = 1000.0 / MSPerFrame; + float MSPerFrame = + 1000.0f * + SDLGetSecondsElapsed(LastCounter, EndCounter); + float FPS = 1000.0f / MSPerFrame; LastCounter = EndCounter; #if 1 - if(SDLGetSecondsElapsed(FPSLastCounter, SDLGetWallClock()) > 0.1f) { - U64 EndCycleCount = __rdtsc(); - U64 CyclesElapsed = EndCycleCount - LastCycleCount; - F64 MCPF = ((F64)CyclesElapsed / (1000.0 * 1000.0)); + if(SDLGetSecondsElapsed(FPSLastCounter, + SDLGetWallClock()) > 0.1f) + { + unsigned long long EndCycleCount = __rdtsc(); + unsigned long long CyclesElapsed = + EndCycleCount - LastCycleCount; + double MCPF = + ((double)CyclesElapsed / (1000.0 * 1000.0)); - //fprintf(stderr, "%.02f ms/f, %.02f f/s, %.02f mc/f\n", MSPerFrame, FPS, MCPF); + /*fprintf(stderr, + "%.02f ms/f, %.02f f/s, %.02f mc/f\n", + MSPerFrame, FPS, MCPF);*/ static char fps_buffer[128]; - snprintf(fps_buffer, sizeof(fps_buffer), "%.02f ms/f, %.02f f/s, %.02f mc/f", MSPerFrame, FPS, MCPF); - SDL_SetWindowTitle(Window, (const char *)fps_buffer); + snprintf(fps_buffer, sizeof(fps_buffer), + "%.02f ms/f, %.02f f/s, %.02f mc/f", + MSPerFrame, FPS, MCPF); + SDL_SetWindowTitle(Window, + (const char *)fps_buffer); LastCycleCount = EndCycleCount; @@ -952,7 +1180,7 @@ S32 main(S32 argc, char *argv[]) } #endif - SWAP(game_input *, OldInput, NewInput); + SWAP(struct game_input *, OldInput, NewInput); } } else { /* TODO: Failed to allocate Samples and Sound memory . . . */ diff --git a/sdl_handmade.h b/sdl_handmade.h index 3fea49c..4728ede 100644 --- a/sdl_handmade.h +++ b/sdl_handmade.h @@ -6,50 +6,50 @@ #include "core.h" #include "handmade.h" -typedef struct sdl_border_size { - S32 Top; - S32 Bottom; - S32 Left; - S32 Right; -} sdl_border_size; +struct sdl_border_size { + int Top; + int Bottom; + int Left; + int Right; +}; -typedef struct sdl_window_size { - S32 Width; - S32 Height; -} sdl_window_size; +struct sdl_window_size { + int Width; + int Height; +}; -typedef struct sdl_window_position { - S32 X; - S32 Y; -} sdl_window_position; +struct sdl_window_position { + int X; + int Y; +}; -typedef struct offscreen_buffer { +struct offscreen_buffer { /* Pixels are always 32-bit and have the bytes in BGRX (little-endian). */ SDL_Texture *Texture; void *Memory; - S32 Width; - S32 Height; - S32 Pitch; -} offscreen_buffer; + int Width; + int Height; + int Pitch; +}; -typedef struct sdl_sound_output { - S32 SamplesPerSecond; - S32 BytesPerSample; - S32 SecondaryBufferSize; - S32 LatencySampleCount; +struct sdl_sound_output { + int SamplesPerSecond; + int BytesPerSample; + int SecondaryBufferSize; + int LatencySampleCount; void *Samples; -} sdl_sound_output; +}; /* TODO: We choose 1024 only because MacOS's MAXPATHLEN says such a value. * For example, linux/limits.h PATH_MAX says 4096. Windows has MAX_PATH. */ #define SDL_STATE_PATH_SIZE 1024 -typedef struct sdl_state { - U64 TotalSize; +struct sdl_state { + unsigned long long TotalSize; void *GameMmemoryBlock; char EXEDirPath[SDL_STATE_PATH_SIZE]; char DLLPath[SDL_STATE_PATH_SIZE]; -} sdl_state; +}; #endif