now sounds sort of work in C client

This commit is contained in:
UnknownShadow200 2018-08-07 10:25:56 +10:00
parent 318d722158
commit 9208456be9
47 changed files with 699 additions and 708 deletions

View File

@ -96,7 +96,7 @@ namespace ClassicalSharp.Audio {
}
if (disposingMusic) break;
int delay = 2000 * 60 + rnd.Next(0, 5000 * 60);
int delay = 1000 * 120 + rnd.Next(0, 1000 * 300);
musicHandle.WaitOne(delay, false);
}
}

View File

@ -202,7 +202,7 @@ static void Animations_Draw(struct AnimationData* data, TextureLoc texLoc, Int32
UInt8* ptr = buffer;
if (size > ANIMS_FAST_SIZE) {
/* cannot allocate memory on the stack for very big animation.png frames */
ptr = Platform_MemAlloc(size * size, BITMAP_SIZEOF_PIXEL, "anim frame");
ptr = Mem_Alloc(size * size, BITMAP_SIZEOF_PIXEL, "anim frame");
}
Int32 index_1D = Atlas1D_Index(texLoc);
@ -222,7 +222,7 @@ static void Animations_Draw(struct AnimationData* data, TextureLoc texLoc, Int32
Int32 dstY = rowId_1D * Atlas2D_TileSize;
Gfx_UpdateTexturePart(Atlas1D_TexIds[index_1D], 0, dstY, &animPart, Gfx_Mipmaps);
if (size > ANIMS_FAST_SIZE) Platform_MemFree(&ptr);
if (size > ANIMS_FAST_SIZE) Mem_Free(&ptr);
}
static void Animations_Apply(struct AnimationData* data) {
@ -249,7 +249,7 @@ static bool Animations_IsDefaultZip(void) {
static void Animations_Clear(void) {
anims_count = 0;
Platform_MemFree(&anims_bmp.Scan0);
Mem_Free(&anims_bmp.Scan0);
anims_validated = false;
}

View File

@ -6,7 +6,7 @@
#include "GameStructs.h"
void ASyncRequest_Free(struct AsyncRequest* request) {
Platform_MemFree(&request->ResultData);
Mem_Free(&request->ResultData);
}
#define ASYNCREQUESTLIST_DEFELEMS 10
@ -54,12 +54,12 @@ static void AsyncRequestList_Init(struct AsyncRequestList* list) {
static void AsyncRequestList_Free(struct AsyncRequestList* list) {
if (list->Requests != list->DefaultRequests) {
Platform_MemFree(&list->Requests);
Mem_Free(&list->Requests);
}
AsyncRequestList_Init(list);
}
void* async_eventHandle;
void* async_waitable;
void* async_workerThread;
void* async_pendingMutex;
void* async_processedMutex;
@ -77,7 +77,7 @@ bool KeepAlive;
/* TODO: Connection pooling */
static void AsyncDownloader_Add(String* url, bool priority, String* id, UInt8 type, DateTime* lastModified, String* etag, String* data) {
Platform_MutexLock(async_pendingMutex);
Mutex_Lock(async_pendingMutex);
{
struct AsyncRequest req = { 0 };
String reqUrl = String_FromEmptyArray(req.URL); String_Set(&reqUrl, url);
@ -94,15 +94,15 @@ static void AsyncDownloader_Add(String* url, bool priority, String* id, UInt8 ty
}
/* request.Data = data; TODO: Implement this. do we need to copy or expect caller to malloc it? */
Platform_CurrentUTCTime(&req.TimeAdded);
DateTime_CurrentUTC(&req.TimeAdded);
if (priority) {
AsyncRequestList_Prepend(&async_pending, &req);
} else {
AsyncRequestList_Append(&async_pending, &req);
}
}
Platform_MutexUnlock(async_pendingMutex);
Platform_EventSignal(async_eventHandle);
Mutex_Unlock(async_pendingMutex);
Waitable_Signal(async_waitable);
}
void AsyncDownloader_GetSkin(STRING_PURE String* id, STRING_PURE String* skinName) {
@ -137,9 +137,9 @@ void AsyncDownloader_GetDataEx(STRING_PURE String* url, bool priority, STRING_PU
}
void AsyncDownloader_PurgeOldEntriesTask(struct ScheduledTask* task) {
Platform_MutexLock(async_processedMutex);
Mutex_Lock(async_processedMutex);
{
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
Int32 i;
for (i = async_processed.Count - 1; i >= 0; i--) {
struct AsyncRequest* item = &async_processed.Requests[i];
@ -149,7 +149,7 @@ void AsyncDownloader_PurgeOldEntriesTask(struct ScheduledTask* task) {
AsyncRequestList_RemoveAt(&async_processed, i);
}
}
Platform_MutexUnlock(async_processedMutex);
Mutex_Unlock(async_processedMutex);
}
static Int32 AsyncRequestList_Find(STRING_PURE String* id, struct AsyncRequest* item) {
@ -167,23 +167,23 @@ static Int32 AsyncRequestList_Find(STRING_PURE String* id, struct AsyncRequest*
bool AsyncDownloader_Get(STRING_PURE String* id, struct AsyncRequest* item) {
bool success = false;
Platform_MutexLock(async_processedMutex);
Mutex_Lock(async_processedMutex);
{
Int32 i = AsyncRequestList_Find(id, item);
success = i >= 0;
if (success) AsyncRequestList_RemoveAt(&async_processed, i);
}
Platform_MutexUnlock(async_processedMutex);
Mutex_Unlock(async_processedMutex);
return success;
}
bool AsyncDownloader_GetCurrent(struct AsyncRequest* request, Int32* progress) {
Platform_MutexLock(async_curRequestMutex);
Mutex_Lock(async_curRequestMutex);
{
*request = async_curRequest;
*progress = async_curProgress;
}
Platform_MutexUnlock(async_curRequestMutex);
Mutex_Unlock(async_curRequestMutex);
return request->ID[0];
}
@ -195,7 +195,7 @@ static void AsyncDownloader_ProcessRequest(struct AsyncRequest* request) {
void* handle;
ReturnCode result;
Stopwatch_Start(&stopwatch);
result = Platform_HttpMakeRequest(request, &handle);
result = Http_MakeRequest(request, &handle);
elapsedMS = Stopwatch_ElapsedMicroseconds(&stopwatch) / 1000;
Platform_Log2("HTTP make request: ret code %i, in %i ms", &result, &elapsedMS);
if (!ErrorHandler_Check(result)) return;
@ -203,24 +203,24 @@ static void AsyncDownloader_ProcessRequest(struct AsyncRequest* request) {
async_curProgress = ASYNC_PROGRESS_FETCHING_DATA;
UInt32 size = 0;
Stopwatch_Start(&stopwatch);
result = Platform_HttpGetRequestHeaders(request, handle, &size);
result = Http_GetRequestHeaders(request, handle, &size);
elapsedMS = Stopwatch_ElapsedMicroseconds(&stopwatch) / 1000;
UInt32 status = request->StatusCode;
Platform_Log3("HTTP get headers: ret code %i (http %i), in %i ms", &result, &status, &elapsedMS);
if (!ErrorHandler_Check(result) || request->StatusCode != 200) {
Platform_HttpFreeRequest(handle); return;
Http_FreeRequest(handle); return;
}
void* data = NULL;
if (request->RequestType != REQUEST_TYPE_CONTENT_LENGTH) {
Stopwatch_Start(&stopwatch);
result = Platform_HttpGetRequestData(request, handle, &data, size, &async_curProgress);
result = Http_GetRequestData(request, handle, &data, size, &async_curProgress);
elapsedMS = Stopwatch_ElapsedMicroseconds(&stopwatch) / 1000;
Platform_Log3("HTTP get data: ret code %i (size %i), in %i ms", &result, &size, &elapsedMS);
}
Platform_HttpFreeRequest(handle);
Http_FreeRequest(handle);
if (!ErrorHandler_Check(result)) return;
UInt64 addr = (UInt64)data;
@ -230,8 +230,8 @@ static void AsyncDownloader_ProcessRequest(struct AsyncRequest* request) {
}
static void AsyncDownloader_CompleteResult(struct AsyncRequest* request) {
Platform_CurrentUTCTime(&request->TimeDownloaded);
Platform_MutexLock(async_processedMutex);
DateTime_CurrentUTC(&request->TimeDownloaded);
Mutex_Lock(async_processedMutex);
{
struct AsyncRequest older;
String id = String_FromRawArray(request->ID);
@ -250,7 +250,7 @@ static void AsyncDownloader_CompleteResult(struct AsyncRequest* request) {
AsyncRequestList_Append(&async_processed, request);
}
}
Platform_MutexUnlock(async_processedMutex);
Mutex_Unlock(async_processedMutex);
}
static void AsyncDownloader_WorkerFunc(void) {
@ -258,7 +258,7 @@ static void AsyncDownloader_WorkerFunc(void) {
struct AsyncRequest request;
bool hasRequest = false;
Platform_MutexLock(async_pendingMutex);
Mutex_Lock(async_pendingMutex);
{
if (async_terminate) return;
if (async_pending.Count > 0) {
@ -267,30 +267,30 @@ static void AsyncDownloader_WorkerFunc(void) {
AsyncRequestList_RemoveAt(&async_pending, 0);
}
}
Platform_MutexUnlock(async_pendingMutex);
Mutex_Unlock(async_pendingMutex);
if (hasRequest) {
Platform_LogConst("Got something to do!");
Platform_MutexLock(async_curRequestMutex);
Mutex_Lock(async_curRequestMutex);
{
async_curRequest = request;
async_curProgress = ASYNC_PROGRESS_MAKING_REQUEST;
}
Platform_MutexUnlock(async_curRequestMutex);
Mutex_Unlock(async_curRequestMutex);
Platform_LogConst("Doing it");
AsyncDownloader_ProcessRequest(&request);
AsyncDownloader_CompleteResult(&request);
Platform_MutexLock(async_curRequestMutex);
Mutex_Lock(async_curRequestMutex);
{
async_curRequest.ID[0] = NULL;
async_curProgress = ASYNC_PROGRESS_NOTHING;
}
Platform_MutexUnlock(async_curRequestMutex);
Mutex_Unlock(async_curRequestMutex);
} else {
Platform_LogConst("Going back to sleep...");
Platform_EventWait(async_eventHandle);
Waitable_Wait(async_waitable);
}
}
}
@ -299,38 +299,38 @@ static void AsyncDownloader_WorkerFunc(void) {
static void AsyncDownloader_Init(void) {
AsyncRequestList_Init(&async_pending);
AsyncRequestList_Init(&async_processed);
Platform_HttpInit();
Http_Init();
async_eventHandle = Platform_EventCreate();
async_pendingMutex = Platform_MutexCreate();
async_processedMutex = Platform_MutexCreate();
async_curRequestMutex = Platform_MutexCreate();
async_workerThread = Platform_ThreadStart(AsyncDownloader_WorkerFunc);
async_waitable = Waitable_Create();
async_pendingMutex = Mutex_Create();
async_processedMutex = Mutex_Create();
async_curRequestMutex = Mutex_Create();
async_workerThread = Thread_Start(AsyncDownloader_WorkerFunc);
}
static void AsyncDownloader_Reset(void) {
Platform_MutexLock(async_pendingMutex);
Mutex_Lock(async_pendingMutex);
{
AsyncRequestList_Free(&async_pending);
}
Platform_MutexUnlock(async_pendingMutex);
Platform_EventSignal(async_eventHandle);
Mutex_Unlock(async_pendingMutex);
Waitable_Signal(async_waitable);
}
static void AsyncDownloader_Free(void) {
async_terminate = true;
AsyncDownloader_Reset();
Platform_ThreadJoin(async_workerThread);
Platform_ThreadFreeHandle(async_workerThread);
Thread_Join(async_workerThread);
Thread_FreeHandle(async_workerThread);
AsyncRequestList_Free(&async_pending);
AsyncRequestList_Free(&async_processed);
Platform_HttpFree();
Http_Free();
Platform_EventFree(async_eventHandle);
Platform_MutexFree(async_pendingMutex);
Platform_MutexFree(async_processedMutex);
Platform_MutexFree(async_curRequestMutex);
Waitable_Free(async_waitable);
Mutex_Free(async_pendingMutex);
Mutex_Free(async_processedMutex);
Mutex_Free(async_curRequestMutex);
}
void AsyncDownloader_MakeComponent(struct IGameComponent* comp) {

View File

@ -7,6 +7,7 @@
#include "Funcs.h"
#include "Block.h"
#include "Game.h"
#include "GameStructs.h"
StringsBuffer files;
/*########################################################################################################################*
@ -19,6 +20,7 @@ struct Sound {
#define AUDIO_MAX_SOUNDS 10
struct SoundGroup {
UChar NameBuffer[String_BufferSize(16)];
String Name; UInt8 Count;
struct Sound Sounds[AUDIO_MAX_SOUNDS];
};
@ -37,26 +39,27 @@ static ReturnCode Sound_ReadWaveData(struct Stream* stream, struct Sound* snd) {
UInt32 fourCC, size, pos, len;
ReturnCode res;
fourCC = Stream_ReadU32_LE(stream);
fourCC = Stream_ReadU32_BE(stream);
if (fourCC != WAV_FourCC('R','I','F','F')) return WAV_ERR_STREAM_HDR;
Stream_ReadU32_LE(stream); /* file size, but we don't care */
fourCC = Stream_ReadU32_LE(stream);
fourCC = Stream_ReadU32_BE(stream);
if (fourCC != WAV_FourCC('W','A','V','E')) return WAV_ERR_STREAM_TYPE;
while (!(res = stream->Position(stream, &pos)) && !(res = stream->Length(stream, &len)) && len < pos) {
fourCC = Stream_ReadU32_LE(stream);
while (!(res = stream->Position(stream, &pos)) && !(res = stream->Length(stream, &len)) && pos < len) {
fourCC = Stream_ReadU32_BE(stream);
size = Stream_ReadU32_LE(stream);
if (fourCC == WAV_FourCC('f','m','t',' ')) {
if (Stream_GetU16_LE(stream) != 1) return WAV_ERR_DATA_TYPE;
if (Stream_ReadU16_LE(stream) != 1) return WAV_ERR_DATA_TYPE;
snd->Format.Channels = Stream_ReadU16_LE(stream);
snd->Format.SampleRate = Stream_ReadU32_LE(stream);
Stream_Skip(&stream, 6);
Stream_Skip(stream, 6);
snd->Format.BitsPerSample = Stream_ReadU16_LE(stream);
size -= 16;
} else if (fourCC == WAV_FourCC('d','a','t','a')) {
snd->Data = Platform_MemAlloc(size, sizeof(UInt8), "WAV sound data");
snd->Data = Mem_Alloc(size, sizeof(UInt8), "WAV sound data");
snd->DataSize = size;
Stream_Read(stream, snd->Data, size);
return 0;
}
@ -70,10 +73,10 @@ static ReturnCode Sound_ReadWaveData(struct Stream* stream, struct Sound* snd) {
static ReturnCode Sound_ReadWave(STRING_PURE String* filename, struct Sound* snd) {
UChar pathBuffer[String_BufferSize(FILENAME_SIZE)];
String path = String_InitAndClearArray(pathBuffer);
String_Format2(&path, "audio%r%s", &Platform_DirectorySeparator, filename);
String_Format2(&path, "audio%r%s", &Directory_Separator, filename);
void* file = NULL;
ReturnCode result = Platform_FileOpen(&file, &path);
ReturnCode result = File_Open(&file, &path);
if (result) return result;
ReturnCode fileResult = 0;
@ -99,12 +102,10 @@ static struct SoundGroup* Soundboard_Find(struct Soundboard* board, STRING_PURE
static void Soundboard_Init(struct Soundboard* board, STRING_PURE String* boardName, StringsBuffer* files) {
Int32 i;
for (i = 0; i < files->Count; i++) {
String name = StringsBuffer_UNSAFE_Get(files, i);
Utils_UNSAFE_GetFilename(&name);
String file = StringsBuffer_UNSAFE_Get(files, i), name = file;
/* dig_grass1.wav -> dig_grass1 */
Int32 dotIndex = String_LastIndexOf(&name, '.');
if (dotIndex >= 0) { name = String_UNSAFE_Substring(0, &name, dotIndex); }
if (dotIndex >= 0) { name = String_UNSAFE_Substring(&name, 0, dotIndex); }
if (!String_CaselessStarts(&name, boardName)) continue;
/* Convert dig_grass1 to grass */
@ -113,24 +114,31 @@ static void Soundboard_Init(struct Soundboard* board, STRING_PURE String* boardN
struct SoundGroup* group = Soundboard_Find(board, &name);
if (group == NULL) {
if (board->Count == AUDIO_MAX_SOUNDS) ErrorHandler_Fail("Soundboard_Init - too many sounds");
group = &board->Groups[board->Count++];
group.Name = name;
if (board->Count == Array_Elems(board->Groups)) ErrorHandler_Fail("Soundboard - too many groups");
group = &board->Groups[board->Count++];
group->Name = String_InitAndClearArray(group->NameBuffer);
String_Set(&group->Name, &name);
}
Sound snd = ReadWave(files[i]);
group.Sounds.Add(snd);
if (group->Count == Array_Elems(group->Sounds)) ErrorHandler_Fail("Soundboard - too many sounds");
struct Sound* snd = &group->Sounds[group->Count];
ReturnCode result = Sound_ReadWave(&file, snd);
ErrorHandler_CheckOrFail(result, "Soundboard - reading WAV");
group->Count++;
}
}
struct Sound* Soundboard_PickRandom(struct Soundboard* board, UInt8 type) {
if (type == SOUND_NONE || type >= SOUND_COUNT) return NULL;
if (type == SOUND_METAL) type = SOUND_STONE;
string name = SoundType.Names[type];
String name = String_FromReadonly(Sound_Names[type]);
struct SoundGroup* group = Soundboard_Find(board, name);
struct SoundGroup* group = Soundboard_Find(board, &name);
if (group == NULL) return NULL;
return group.Sounds[rnd.Next(group.Sounds.Count)];
Int32 idx = Random_Range(&board->Rnd, 0, group->Count);
return &group->Sounds[idx];
}
@ -142,34 +150,21 @@ struct Soundboard digBoard, stepBoard;
AudioHandle monoOutputs[AUDIO_MAX_HANDLES] = { -1, -1, -1, -1, -1, -1 };
AudioHandle stereoOutputs[AUDIO_MAX_HANDLES] = { -1, -1, -1, -1, -1, -1 };
static void PlaySound(AudioHandle output, Real32 volume) {
try {
output.SetVolume(volume);
output.PlayRawAsync(chunk);
}
catch (InvalidOperationException ex) {
ErrorHandler.LogError("AudioPlayer.PlayCurrentSound()", ex);
if (ex.Message == "No audio devices found")
game.Chat.Add("&cNo audio devices found, disabling sounds.");
else
game.Chat.Add("&cAn error occured when trying to play sounds, disabling sounds.");
SetSounds(0);
game.SoundsVolume = 0;
}
static void Sounds_PlayRaw(AudioHandle output, struct Sound* snd, struct AudioFormat* fmt, Real32 volume) {
Audio_SetVolume(output, volume);
Audio_SetFormat(output, fmt);
Audio_PlayData(output, 0, snd->Data, snd->DataSize);
/* TODO: handle errors here */
}
AudioChunk chunk = new AudioChunk();
static void PlaySound(UInt8 type, struct Soundboard* board) {
static void Sounds_Play(UInt8 type, struct Soundboard* board) {
if (type == SOUND_NONE || Game_SoundsVolume == 0) return;
struct Sound* snd = Soundboard_PickRandom(board, type);
if (snd == NULL) return;
struct AudioFormat fmt = snd->Format;
chunk.BytesUsed = snd.Data.Length;
chunk.Data = snd.Data;
Real32 volume = Game_SoundsVolume / 100.0f;
if (board == &digBoard) {
if (type == SOUND_METAL) fmt.SampleRate = (fmt.SampleRate * 6) / 5;
else fmt.SampleRate = (fmt.SampleRate * 4) / 5;
@ -188,35 +183,35 @@ static void PlaySound(UInt8 type, struct Soundboard* board) {
for (i = 0; i < AUDIO_MAX_HANDLES; i++) {
AudioHandle output = outputs[i];
if (output == -1) {
Platform_AudioInit(&output, 1);
Audio_Init(&output, 1);
outputs[i] = output;
}
if (!Platform_AudioIsFinished(output)) continue;
if (!Audio_IsFinished(output)) continue;
struct AudioFormat* l = Platform_AudioGetFormat(output);
struct AudioFormat* l = Audio_GetFormat(output);
if (l->Channels == 0 || AudioFormat_Eq(l, &fmt)) {
PlaySound(output, volume); return;
Sounds_PlayRaw(output, snd, &fmt, volume); return;
}
}
/* Try again with all devices, even if need to recreate one (expensive) */
for (i = 0; i < AUDIO_MAX_HANDLES; i++) {
AudioHandle output = outputs[i];
if (!Platform_AudioIsFinished(output)) continue;
if (!Audio_IsFinished(output)) continue;
PlaySound(output, volume); return;
Sounds_PlayRaw(output, snd, &fmt, volume); return;
}
}
static void Audio_PlayBlockSound(void* obj, Vector3I coords, BlockID oldBlock, BlockID block) {
if (block == BLOCK_AIR) {
PlayDigSound(Block_DigSounds[oldBlock]);
Audio_PlayDigSound(Block_DigSounds[oldBlock]);
} else if (!Game_ClassicMode) {
PlayDigSound(Block_StepSounds[block]);
Audio_PlayDigSound(Block_StepSounds[block]);
}
}
static void Audio_FreeOutputs(AudioHandle* outputs) {
static void Sounds_FreeOutputs(AudioHandle* outputs) {
bool anyPlaying = true;
Int32 i;
@ -224,19 +219,19 @@ static void Audio_FreeOutputs(AudioHandle* outputs) {
anyPlaying = false;
for (i = 0; i < AUDIO_MAX_HANDLES; i++) {
if (outputs[i] == -1) continue;
anyPlaying |= !Platform_AudioIsFinished(outputs[i]);
anyPlaying |= !Audio_IsFinished(outputs[i]);
}
if (anyPlaying) Platform_ThreadSleep(1);
if (anyPlaying) Thread_Sleep(1);
}
for (i = 0; i < AUDIO_MAX_HANDLES; i++) {
if (outputs[i] == -1) continue;
Platform_AudioFree(outputs[i]);
Audio_Free(outputs[i]);
outputs[i] = -1;
}
}
static void Audio_InitSounds(void) {
static void Sounds_Init(void) {
if (digBoard.Count || stepBoard.Count) return;
String dig = String_FromConst("dig_");
Soundboard_Init(&digBoard, &dig, &files);
@ -244,122 +239,95 @@ static void Audio_InitSounds(void) {
Soundboard_Init(&stepBoard, &step, &files);
}
static void Audio_FreeSounds(void) {
Audio_FreeOutputs(monoOutputs);
Audio_FreeOutputs(stereoOutputs);
static void Sounds_Free(void) {
Sounds_FreeOutputs(monoOutputs);
Sounds_FreeOutputs(stereoOutputs);
}
void Audio_SetSounds(Int32 volume) {
if (volume) Audio_InitSounds();
else Audio_FreeSounds();
if (volume) Sounds_Init();
else Sounds_Free();
}
void Audio_PlayDigSound(UInt8 type) { Audio_PlaySound(type, &digBoard); }
void Audio_PlayStepSound(UInt8 type) { Audio_PlaySound(type, &stepBoard); }
void Audio_PlayDigSound(UInt8 type) { Sounds_Play(type, &digBoard); }
void Audio_PlayStepSound(UInt8 type) { Sounds_Play(type, &stepBoard); }
/*########################################################################################################################*
*--------------------------------------------------------Music------------------------------------------------------------*
*#########################################################################################################################*/
AudioHandle musicOut = -1;
string[] files, musicFiles;
Thread musicThread;
AudioHandle music_out = -1;
StringsBuffer music_files;
void* music_thread;
void* music_waitable;
volatile bool music_pendingStop;
void SetMusic(int volume) {
if (volume > 0) InitMusic();
else DisposeMusic();
}
#define MUSIC_MAX_FILES 512
static void Music_RunLoop(void) {
UInt32 i, count = 0;
UInt16 musicFiles[MUSIC_MAX_FILES];
String ogg = String_FromConst(".ogg");
void InitMusic() {
if (musicThread != null) { musicOut.SetVolume(game.MusicVolume / 100.0f); return; }
int musicCount = 0;
for (int i = 0; i < files.Length; i++) {
if (Utils.CaselessEnds(files[i], ".ogg")) musicCount++;
for (i = 0; i < files.Count && count < MUSIC_MAX_FILES; i++) {
String file = StringsBuffer_UNSAFE_Get(&files, i);
if (!String_CaselessEnds(&file, &ogg)) continue;
musicFiles[count++] = i;
}
musicFiles = new string[musicCount];
for (int i = 0, j = 0; i < files.Length; i++) {
if (!Utils.CaselessEnds(files[i], ".ogg")) continue;
musicFiles[j] = files[i]; j++;
}
if (!count) return;
Random rnd; Random_InitFromCurrentTime(&rnd);
UInt8 pathBuffer[String_BufferSize(FILENAME_SIZE)];
disposingMusic = false;
musicOut = GetPlatformOut();
musicOut.Create(10);
musicThread = MakeThread(DoMusicThread, "ClassicalSharp.DoMusic");
}
while (!music_pendingStop) {
Int32 idx = Random_Range(&rnd, 0, count);
String file = StringsBuffer_UNSAFE_Get(&files, musicFiles[idx]);
String path = String_InitAndClearArray(pathBuffer);
String_Format2(&path, "audio%r%s", &Directory_Separator, &file);
EventWaitHandle musicHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
void DoMusicThread() {
if (musicFiles.Length == 0) return;
Random rnd = new Random();
while (!disposingMusic) {
string file = musicFiles[rnd.Next(0, musicFiles.Length)];
Utils.LogDebug("playing music file: " + file);
Platform_Log1("playing music file: %s", &file);
//using (Stream fs = Platform.FileOpen(path)) {
// OggContainer container = new OggContainer(fs);
// musicOut.SetVolume(game.MusicVolume / 100.0f);
// musicOut.PlayStreaming(container);
// /* TODO: handle errors */
//}
string path = Path.Combine("audio", file);
using (Stream fs = Platform.FileOpen(path)) {
OggContainer container = new OggContainer(fs);
try {
musicOut.SetVolume(game.MusicVolume / 100.0f);
musicOut.PlayStreaming(container);
} catch (InvalidOperationException ex) {
HandleMusicError(ex);
return;
} catch (Exception ex) {
ErrorHandler.LogError("AudioPlayer.DoMusicThread()", ex);
game.Chat.Add("&cError while trying to play music file " + file);
}
}
if (disposingMusic) break;
int delay = 2000 * 60 + rnd.Next(0, 5000 * 60);
musicHandle.WaitOne(delay, false);
if (music_pendingStop) break;
Int32 delay = 1000 * 120 + Random_Range(&rnd, 0, 1000 * 300);
Waitable_WaitFor(music_waitable, delay);
}
}
void HandleMusicError(InvalidOperationException ex) {
ErrorHandler.LogError("AudioPlayer.DoMusicThread()", ex);
if (ex.Message == "No audio devices found")
game.Chat.Add("&cNo audio devices found, disabling music.");
else
game.Chat.Add("&cAn error occured when trying to play music, disabling music.");
static void Music_Init(void) {
if (music_thread) { Audio_SetVolume(music_out, Game_MusicVolume / 100.0f); return; }
SetMusic(0);
game.MusicVolume = 0;
}
bool disposingMusic;
void DisposeMusic() {
disposingMusic = true;
musicHandle.Set();
DisposeOf(ref musicOut, ref musicThread);
music_pendingStop = false;
Audio_Init(&music_out, AUDIO_MAX_CHUNKS);
music_thread = Thread_Start(Music_RunLoop);
}
Thread MakeThread(ThreadStart func, string name) {
Thread thread = new Thread(func);
thread.Name = name;
thread.IsBackground = true;
thread.Start();
return thread;
static void Music_Free(void) {
music_pendingStop = true;
Waitable_Signal(music_waitable);
if (music_out == -1) return;
Thread_Join(music_thread);
Thread_FreeHandle(music_thread);
Audio_Free(music_out);
music_out = -1;
music_thread = NULL;
}
void DisposeOf(ref IAudioOutput output, ref Thread thread) {
if (output == null) return;
output.Stop();
thread.Join();
output.Dispose();
output = null;
thread = null;
void Audio_SetMusic(Int32 volume) {
if (volume) Music_Init();
else Music_Free();
}
/*########################################################################################################################*
*--------------------------------------------------------General----------------------------------------------------------*
*#########################################################################################################################*/
static Int32 Audio_GetVolume(const UChar* volKey, const UChar* boolKey) {
static Int32 AudioManager_GetVolume(const UChar* volKey, const UChar* boolKey) {
Int32 volume = Options_GetInt(volKey, 0, 100, 0);
if (volume) return volume;
@ -368,23 +336,34 @@ static Int32 Audio_GetVolume(const UChar* volKey, const UChar* boolKey) {
return volume;
}
static void Audio_Init(void) {
static void AudioManager_FilesCallback(STRING_PURE String* filename, void* obj) {
StringsBuffer_Add(&files, filename);
}
static void AudioManager_Init(void) {
StringsBuffer_Init(&files);
music_waitable = Waitable_Create();
String path = String_FromConst("audio");
if (Platform_DirectoryExists(&path)) {
files = Platform.DirectoryFiles("audio");
if (Directory_Exists(&path)) {
Directory_Enum(&path, NULL, AudioManager_FilesCallback);
}
Game_MusicVolume = GetVolume(OPT_MUSIC_VOLUME, OPT_USE_MUSIC);
Game_MusicVolume = AudioManager_GetVolume(OPT_MUSIC_VOLUME, OPT_USE_MUSIC);
Audio_SetMusic(Game_MusicVolume);
Game_SoundsVolume = GetVolume(OPT_SOUND_VOLUME, OPT_USE_SOUND);
Game_SoundsVolume = AudioManager_GetVolume(OPT_SOUND_VOLUME, OPT_USE_SOUND);
Audio_SetSounds(Game_SoundsVolume);
game.UserEvents.BlockChanged += PlayBlockSound;
Event_RegisterBlock(&UserEvents_BlockChanged, NULL, Audio_PlayBlockSound);
}
static void Audio_Free(void) {
DisposeMusic();
DisposeSound();
musicHandle.Close();
game.UserEvents.BlockChanged -= PlayBlockSound;
static void AudioManager_Free(void) {
Music_Free();
Sounds_Free();
Waitable_Free(&music_waitable);
Event_UnregisterBlock(&UserEvents_BlockChanged, NULL, Audio_PlayBlockSound);
}
void Audio_MakeComponent(struct IGameComponent* comp) {
comp->Init = AudioManager_Init;
comp->Free = AudioManager_Free;
}

View File

@ -11,5 +11,4 @@ void Audio_SetMusic(Int32 volume);
void Audio_SetSounds(Int32 volume);
void Audio_PlayDigSound(UInt8 type);
void Audio_PlayStepSound(UInt8 type);
#endif

View File

@ -23,7 +23,7 @@ void Bitmap_CopyBlock(Int32 srcX, Int32 srcY, Int32 dstX, Int32 dstY, struct Bit
void Bitmap_Allocate(struct Bitmap* bmp, Int32 width, Int32 height) {
bmp->Width = width; bmp->Height = height;
bmp->Scan0 = Platform_MemAlloc(width * height, BITMAP_SIZEOF_PIXEL, "bitmap data");
bmp->Scan0 = Mem_Alloc(width * height, BITMAP_SIZEOF_PIXEL, "bitmap data");
}
void Bitmap_AllocateClearedPow2(struct Bitmap* bmp, Int32 width, Int32 height) {
@ -31,7 +31,7 @@ void Bitmap_AllocateClearedPow2(struct Bitmap* bmp, Int32 width, Int32 height) {
height = Math_NextPowOf2(height);
bmp->Width = width; bmp->Height = height;
bmp->Scan0 = Platform_MemAllocCleared(width * height, BITMAP_SIZEOF_PIXEL, "bitmap data");
bmp->Scan0 = Mem_AllocCleared(width * height, BITMAP_SIZEOF_PIXEL, "bitmap data");
}
@ -367,7 +367,7 @@ ReturnCode Bitmap_DecodePng(struct Bitmap* bmp, struct Stream* stream) {
if (bmp->Width < 0 || bmp->Width > PNG_MAX_DIMS) return PNG_ERR_TOO_WIDE;
if (bmp->Height < 0 || bmp->Height > PNG_MAX_DIMS) return PNG_ERR_TOO_TALL;
bmp->Scan0 = Platform_MemAlloc(bmp->Width * bmp->Height, BITMAP_SIZEOF_PIXEL, "PNG bitmap data");
bmp->Scan0 = Mem_Alloc(bmp->Width * bmp->Height, BITMAP_SIZEOF_PIXEL, "PNG bitmap data");
bitsPerSample = buffer[8]; col = buffer[9];
rowExpander = Png_GetExpander(col, bitsPerSample);
if (rowExpander == NULL) return PNG_ERR_INVALID_COL_BPP;
@ -381,7 +381,7 @@ ReturnCode Bitmap_DecodePng(struct Bitmap* bmp, struct Stream* stream) {
scanlineSize = ((samplesPerPixel[col] * bitsPerSample * bmp->Width) + 7) >> 3;
scanlineBytes = scanlineSize + 1; /* Add 1 byte for filter byte of each scanline */
Platform_MemSet(buffer, 0, scanlineBytes); /* Prior row should be 0 per PNG spec */
Mem_Set(buffer, 0, scanlineBytes); /* Prior row should be 0 per PNG spec */
bufferIdx = scanlineBytes;
bufferRows = PNG_BUFFER_SIZE / scanlineBytes;
} break;
@ -512,7 +512,7 @@ static void Png_Filter(UInt8 filter, UInt8* cur, UInt8* prior, UInt8* best, Int3
Int32 i;
switch (filter) {
case PNG_FILTER_NONE:
Platform_MemCpy(best, cur, lineLen);
Mem_Copy(best, cur, lineLen);
break;
case PNG_FILTER_SUB:
@ -620,7 +620,7 @@ void Bitmap_EncodePng(struct Bitmap* bmp, struct Stream* stream) {
UInt8 prevLine[PNG_MAX_DIMS * 3];
UInt8 curLine[PNG_MAX_DIMS * 3];
UInt8 bestLine[PNG_MAX_DIMS * 3 + 1];
Platform_MemSet(prevLine, 0, bmp->Width * 3);
Mem_Set(prevLine, 0, bmp->Width * 3);
Stream_WriteU32_BE(stream, 0);
stream = &crc32Stream;

View File

@ -7,6 +7,11 @@
#include "Inventory.h"
#include "Event.h"
const UChar* Sound_Names[SOUND_COUNT] = {
"none", "wood", "gravel", "grass", "stone",
"metal", "glass", "cloth", "sand", "snow",
};
UInt32 Block_DefinedCustomBlocks[BLOCK_COUNT >> 5];
UChar Block_NamesBuffer[String_BufferSize(STRING_SIZE) * BLOCK_COUNT];
#define Block_NamePtr(i) &Block_NamesBuffer[String_BufferSize(STRING_SIZE) * i]

View File

@ -14,6 +14,7 @@ enum SOUND {
SOUND_STONE, SOUND_METAL, SOUND_GLASS, SOUND_CLOTH,
SOUND_SAND, SOUND_SNOW, SOUND_COUNT,
};
extern const UChar* Sound_Names[SOUND_COUNT];
/* Describes how a block is rendered in the world. */
enum DRAWTYPE {

View File

@ -34,7 +34,7 @@ static void TickQueue_Init(struct TickQueue* queue) {
static void TickQueue_Clear(struct TickQueue* queue) {
if (!queue->Buffer) return;
Platform_MemFree(&queue->Buffer);
Mem_Free(&queue->Buffer);
TickQueue_Init(queue);
}
@ -45,14 +45,14 @@ static void TickQueue_Resize(struct TickQueue* queue) {
UInt32 capacity = queue->BufferSize * 2;
if (capacity < 32) capacity = 32;
UInt32* newBuffer = Platform_MemAlloc(capacity, sizeof(UInt32), "physics tick queue");
UInt32* newBuffer = Mem_Alloc(capacity, sizeof(UInt32), "physics tick queue");
UInt32 i, idx;
for (i = 0; i < queue->Size; i++) {
idx = (queue->Head + i) & queue->BufferMask;
newBuffer[i] = queue->Buffer[idx];
}
Platform_MemFree(&queue->Buffer);
Mem_Free(&queue->Buffer);
queue->Buffer = newBuffer;
queue->BufferSize = capacity;

View File

@ -272,7 +272,7 @@ static bool Builder_BuildChunk(Int32 x1, Int32 y1, Int32 z1, bool* allAir) {
UInt8 counts[CHUNK_SIZE_3 * FACE_COUNT]; Builder_Counts = counts;
Int32 bitFlags[EXTCHUNK_SIZE_3]; Builder_BitFlags = bitFlags;
Platform_MemSet(chunk, BLOCK_AIR, EXTCHUNK_SIZE_3 * sizeof(BlockID));
Mem_Set(chunk, BLOCK_AIR, EXTCHUNK_SIZE_3 * sizeof(BlockID));
bool allSolid;
Builder_ReadChunkData(x1, y1, z1, allAir, &allSolid);
@ -282,7 +282,7 @@ static bool Builder_BuildChunk(Int32 x1, Int32 y1, Int32 z1, bool* allAir) {
if (*allAir || allSolid) return false;
Lighting_LightHint(x1 - 1, z1 - 1);
Platform_MemSet(counts, 1, CHUNK_SIZE_3 * FACE_COUNT);
Mem_Set(counts, 1, CHUNK_SIZE_3 * FACE_COUNT);
Int32 xMax = min(World_Width, x1 + CHUNK_SIZE);
Int32 yMax = min(World_Height, y1 + CHUNK_SIZE);
Int32 zMax = min(World_Length, z1 + CHUNK_SIZE);
@ -360,15 +360,15 @@ static bool Builder_OccludedLiquid(Int32 chunkIndex) {
}
static void Builder_DefaultPreStretchTiles(Int32 x1, Int32 y1, Int32 z1) {
Platform_MemSet(Builder_Parts, 0, sizeof(Builder_Parts));
Mem_Set(Builder_Parts, 0, sizeof(Builder_Parts));
}
static void Builder_DefaultPostStretchTiles(Int32 x1, Int32 y1, Int32 z1) {
Int32 i, vertsCount = Builder_TotalVerticesCount();
if (vertsCount > Builder_VerticesElems) {
Platform_MemFree(&Builder_Vertices);
Mem_Free(&Builder_Vertices);
/* ensure buffer can be accessed with 64 bytes alignment by putting 2 extra vertices at end. */
Builder_Vertices = Platform_MemAlloc(vertsCount + 2, sizeof(VertexP3fT2fC4b), "chunk vertices");
Builder_Vertices = Mem_Alloc(vertsCount + 2, sizeof(VertexP3fT2fC4b), "chunk vertices");
Builder_VerticesElems = vertsCount;
}

View File

@ -26,7 +26,7 @@ void Chat_GetLogTime(UInt32 index, Int64* timeMs) {
}
static void Chat_AppendLogTime(void) {
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
if (Chat_LogTimesCount == Chat_LogTimesMax) {
StringsBuffer_Resize(&Chat_LogTimes, &Chat_LogTimesMax, sizeof(Int64),
CHAT_LOGTIMES_DEF_ELEMS, CHAT_LOGTIMES_EXPAND_ELEMS);
@ -37,7 +37,7 @@ static void Chat_AppendLogTime(void) {
static void ChatLine_Make(struct ChatLine* line, STRING_TRANSIENT String* text) {
String dst = String_InitAndClearArray(line->Buffer);
String_AppendString(&dst, text);
Platform_CurrentUTCTime(&line->Received);
DateTime_CurrentUTC(&line->Received);
}
UChar Chat_LogNameBuffer[String_BufferSize(STRING_SIZE)];
@ -75,8 +75,8 @@ void Chat_SetLogName(STRING_PURE String* name) {
static void Chat_OpenLog(DateTime* now) {
String logsDir = String_FromConst("logs");
if (!Platform_DirectoryExists(&logsDir)) {
Platform_DirectoryCreate(&logsDir);
if (!Directory_Exists(&logsDir)) {
Directory_Create(&logsDir);
}
/* Ensure multiple instances do not end up overwriting each other's log entries. */
@ -84,7 +84,7 @@ static void Chat_OpenLog(DateTime* now) {
for (i = 0; i < 20; i++) {
UChar pathBuffer[String_BufferSize(FILENAME_SIZE)];
String path = String_InitAndClearArray(pathBuffer);
String_Format4(&path, "logs%r%p4-%p2-%p2", &Platform_DirectorySeparator, &year, &month, &day);
String_Format4(&path, "logs%r%p4-%p2-%p2", &Directory_Separator, &year, &month, &day);
if (i > 0) {
String_Format2(&path, "%s _%i.log", &Chat_LogName, &i);
@ -93,7 +93,7 @@ static void Chat_OpenLog(DateTime* now) {
}
void* file;
ReturnCode code = Platform_FileAppend(&file, &path);
ReturnCode code = File_Append(&file, &path);
if (code != 0 && code != ReturnCode_FileShareViolation) {
ErrorHandler_FailWithCode(code, "Chat - opening log file");
}
@ -110,7 +110,7 @@ static void Chat_OpenLog(DateTime* now) {
static void Chat_AppendLog(STRING_PURE String* text) {
if (!Chat_LogName.length || !Game_ChatLogging) return;
DateTime now; Platform_CurrentLocalTime(&now);
DateTime now; DateTime_CurrentLocal(&now);
if (now.Day != ChatLog_LastLogDate.Day || now.Month != ChatLog_LastLogDate.Month || now.Year != ChatLog_LastLogDate.Year) {
Chat_CloseLog();
@ -130,7 +130,12 @@ static void Chat_AppendLog(STRING_PURE String* text) {
Stream_WriteLine(&Chat_LogStream, &str);
}
void Chat_AddRaw(const UChar* raw) {
String str = String_FromReadonly(raw);
Chat_AddOf(&str, MSG_TYPE_NORMAL);
}
void Chat_Add(STRING_PURE String* text) { Chat_AddOf(text, MSG_TYPE_NORMAL); }
void Chat_AddOf(STRING_PURE String* text, Int32 msgType) {
Event_RaiseChat(&ChatEvents_ChatReceived, text, msgType);
@ -211,7 +216,7 @@ static struct ChatCommand* Commands_GetMatch(STRING_PURE String* cmdName) {
if (!match) {
Commands_Log("&e/client: Unrecognised command: \"&f%s&e\".", cmdName);
Chat_AddRaw(tmp, "&e/client: Type &a/client &efor a list of commands.");
Chat_AddRaw("&e/client: Type &a/client &efor a list of commands.");
return NULL;
}
if (match->SingleplayerOnly && !ServerConnection_IsSinglePlayer) {
@ -255,9 +260,9 @@ static void Commands_Execute(STRING_PURE String* input) {
}
if (!text.length) { /* only / or /client */
Chat_AddRaw(tmp1, "&eList of client commands:");
Chat_AddRaw("&eList of client commands:");
Commands_PrintDefined();
Chat_AddRaw(tmp2, "&eTo see help for a command, type &a/client help [cmd name]");
Chat_AddRaw("&eTo see help for a command, type &a/client help [cmd name]");
return;
}
@ -276,9 +281,9 @@ static void Commands_Execute(STRING_PURE String* input) {
*#########################################################################################################################*/
static void HelpCommand_Execute(STRING_PURE String* args, Int32 argsCount) {
if (argsCount == 1) {
Chat_AddRaw(tmp1, "&eList of client commands:");
Chat_AddRaw("&eList of client commands:");
Commands_PrintDefined();
Chat_AddRaw(tmp2, "&eTo see help for a command, type /client help [cmd name]");
Chat_AddRaw("&eTo see help for a command, type /client help [cmd name]");
} else {
struct ChatCommand* cmd = Commands_GetMatch(&args[1]);
if (!cmd) return;
@ -329,7 +334,7 @@ static void GpuInfoCommand_Make(struct ChatCommand* cmd) {
*#########################################################################################################################*/
static void RenderTypeCommand_Execute(STRING_PURE String* args, Int32 argsCount) {
if (argsCount == 1) {
Chat_AddRaw(tmp, "&e/client: &cYou didn't specify a new render type."); return;
Chat_AddRaw("&e/client: &cYou didn't specify a new render type."); return;
}
Int32 flags = Game_CalcRenderType(&args[1]);
@ -357,11 +362,11 @@ static void RenderTypeCommand_Make(struct ChatCommand* cmd) {
static void ResolutionCommand_Execute(STRING_PURE String* args, Int32 argsCount) {
Int32 width, height;
if (argsCount < 3) {
Chat_AddRaw(tmp, "&e/client: &cYou didn't specify width and height");
Chat_AddRaw("&e/client: &cYou didn't specify width and height");
} else if (!Convert_TryParseInt32(&args[1], &width) || !Convert_TryParseInt32(&args[2], &height)) {
Chat_AddRaw(tmp, "&e/client: &cWidth and height must be integers.");
Chat_AddRaw("&e/client: &cWidth and height must be integers.");
} else if (width <= 0 || height <= 0) {
Chat_AddRaw(tmp, "&e/client: &cWidth and height must be above 0.");
Chat_AddRaw("&e/client: &cWidth and height must be above 0.");
} else {
struct Size2D size = { width, height };
Window_SetClientSize(size);
@ -379,7 +384,7 @@ static void ResolutionCommand_Make(struct ChatCommand* cmd) {
static void ModelCommand_Execute(STRING_PURE String* args, Int32 argsCount) {
if (argsCount == 1) {
Chat_AddRaw(tmp, "&e/client model: &cYou didn't specify a model name.");
Chat_AddRaw("&e/client model: &cYou didn't specify a model name.");
} else {
UChar modelBuffer[String_BufferSize(STRING_SIZE)];
String model = String_InitAndClearArray(modelBuffer);
@ -515,11 +520,11 @@ static void CuboidCommand_Make(struct ChatCommand* cmd) {
*#########################################################################################################################*/
static void TeleportCommand_Execute(STRING_PURE String* args, Int32 argsCount) {
if (argsCount != 4) {
Chat_AddRaw(tmp, "&e/client teleport: &cYou didn't specify X, Y and Z coordinates.");
Chat_AddRaw("&e/client teleport: &cYou didn't specify X, Y and Z coordinates.");
} else {
Real32 x, y, z;
if (!Convert_TryParseReal32(&args[1], &x) || !Convert_TryParseReal32(&args[2], &y) || !Convert_TryParseReal32(&args[3], &z)) {
Chat_AddRaw(tmp, "&e/client teleport: &cCoordinates must be decimals");
Chat_AddRaw("&e/client teleport: &cCoordinates must be decimals");
return;
}
@ -575,7 +580,7 @@ static void Chat_Reset(void) {
static void Chat_Free(void) {
Chat_CloseLog();
commands_count = 0;
if (Chat_LogTimes != Chat_DefaultLogTimes) Platform_MemFree(&Chat_LogTimes);
if (Chat_LogTimes != Chat_DefaultLogTimes) Mem_Free(&Chat_LogTimes);
StringsBuffer_Free(&Chat_Log);
StringsBuffer_Free(&Chat_InputLog);

View File

@ -32,5 +32,5 @@ void Chat_SetLogName(STRING_PURE String* name);
void Chat_Send(STRING_PURE String* text, bool logUsage);
void Chat_Add(STRING_PURE String* text);
void Chat_AddOf(STRING_PURE String* text, Int32 messageType);
#define Chat_AddRaw(str, raw) String str = String_FromConst(raw); Chat_Add(&str);
void Chat_AddRaw(const UChar* raw);
#endif

View File

@ -79,32 +79,32 @@ static void ChunkUpdater_ViewDistanceChanged(void* obj) {
static void ChunkUpdater_FreePartsAllocations(void) {
Platform_MemFree(&MapRenderer_PartsBuffer_Raw);
Mem_Free(&MapRenderer_PartsBuffer_Raw);
MapRenderer_PartsNormal = NULL;
MapRenderer_PartsTranslucent = NULL;
}
static void ChunkUpdater_FreeAllocations(void) {
if (!MapRenderer_Chunks) return;
Platform_MemFree(&MapRenderer_Chunks);
Platform_MemFree(&MapRenderer_SortedChunks);
Platform_MemFree(&MapRenderer_RenderChunks);
Platform_MemFree(&ChunkUpdater_Distances);
Mem_Free(&MapRenderer_Chunks);
Mem_Free(&MapRenderer_SortedChunks);
Mem_Free(&MapRenderer_RenderChunks);
Mem_Free(&ChunkUpdater_Distances);
ChunkUpdater_FreePartsAllocations();
}
static void ChunkUpdater_PerformPartsAllocations(void) {
UInt32 count = MapRenderer_ChunksCount * MapRenderer_1DUsedCount;
MapRenderer_PartsBuffer_Raw = Platform_MemAllocCleared(count * 2, sizeof(struct ChunkPartInfo), "chunk parts");
MapRenderer_PartsBuffer_Raw = Mem_AllocCleared(count * 2, sizeof(struct ChunkPartInfo), "chunk parts");
MapRenderer_PartsNormal = MapRenderer_PartsBuffer_Raw;
MapRenderer_PartsTranslucent = MapRenderer_PartsBuffer_Raw + count;
}
static void ChunkUpdater_PerformAllocations(void) {
MapRenderer_Chunks = Platform_MemAlloc(MapRenderer_ChunksCount, sizeof(struct ChunkInfo), "chunk info");
MapRenderer_SortedChunks = Platform_MemAlloc(MapRenderer_ChunksCount, sizeof(struct ChunkInfo*), "sorted chunk info");
MapRenderer_RenderChunks = Platform_MemAlloc(MapRenderer_ChunksCount, sizeof(struct ChunkInfo*), "render chunk info");
ChunkUpdater_Distances = Platform_MemAlloc(MapRenderer_ChunksCount, sizeof(Int32), "chunk distances");
MapRenderer_Chunks = Mem_Alloc(MapRenderer_ChunksCount, sizeof(struct ChunkInfo), "chunk info");
MapRenderer_SortedChunks = Mem_Alloc(MapRenderer_ChunksCount, sizeof(struct ChunkInfo*), "sorted chunk info");
MapRenderer_RenderChunks = Mem_Alloc(MapRenderer_ChunksCount, sizeof(struct ChunkInfo*), "render chunk info");
ChunkUpdater_Distances = Mem_Alloc(MapRenderer_ChunksCount, sizeof(Int32), "chunk distances");
ChunkUpdater_PerformPartsAllocations();
}

View File

@ -57,7 +57,7 @@ static void D3D9_LoopUntilRetrieved(void) {
task.Callback = Gfx_LostContextFunction;
while (true) {
Platform_ThreadSleep(16);
Thread_Sleep(16);
ReturnCode code = IDirect3DDevice9_TestCooperativeLevel(device);
if (code == D3DERR_DEVICENOTRESET) return;
@ -162,7 +162,7 @@ static void D3D9_SetTextureData(IDirect3DTexture9* texture, struct Bitmap* bmp,
ErrorHandler_CheckOrFail(hresult, "D3D9_SetTextureData - Lock");
UInt32 size = Bitmap_DataSize(bmp->Width, bmp->Height);
Platform_MemCpy(rect.pBits, bmp->Scan0, size);
Mem_Copy(rect.pBits, bmp->Scan0, size);
hresult = IDirect3DTexture9_UnlockRect(texture, lvl);
ErrorHandler_CheckOrFail(hresult, "D3D9_SetTextureData - Unlock");
@ -184,7 +184,7 @@ static void D3D9_SetTexturePartData(IDirect3DTexture9* texture, Int32 x, Int32 y
UInt32 stride = (UInt32)(bmp->Width) * BITMAP_SIZEOF_PIXEL;
for (yy = 0; yy < bmp->Height; yy++) {
Platform_MemCpy(dst, src, stride);
Mem_Copy(dst, src, stride);
src += stride;
dst += rect.Pitch;
}
@ -203,7 +203,7 @@ static void D3D9_DoMipmaps(IDirect3DTexture9* texture, Int32 x, Int32 y, struct
if (width > 1) width /= 2;
if (height > 1) height /= 2;
UInt8* cur = Platform_MemAlloc(width * height, BITMAP_SIZEOF_PIXEL, "mipmaps");
UInt8* cur = Mem_Alloc(width * height, BITMAP_SIZEOF_PIXEL, "mipmaps");
GfxCommon_GenMipmaps(width, height, cur, prev);
struct Bitmap mipmap;
@ -214,10 +214,10 @@ static void D3D9_DoMipmaps(IDirect3DTexture9* texture, Int32 x, Int32 y, struct
D3D9_SetTextureData(texture, &mipmap, lvl);
}
if (prev != bmp->Scan0) Platform_MemFree(&prev);
if (prev != bmp->Scan0) Mem_Free(&prev);
prev = cur;
}
if (prev != bmp->Scan0) Platform_MemFree(&prev);
if (prev != bmp->Scan0) Mem_Free(&prev);
}
GfxResourceID Gfx_CreateTexture(struct Bitmap* bmp, bool managedPool, bool mipmaps) {
@ -426,7 +426,7 @@ static void D3D9_SetVbData(IDirect3DVertexBuffer9* buffer, void* data, Int32 siz
ReturnCode hresult = IDirect3DVertexBuffer9_Lock(buffer, 0, size, &dst, lockFlags);
ErrorHandler_CheckOrFail(hresult, lockMsg);
Platform_MemCpy(dst, data, size);
Mem_Copy(dst, data, size);
hresult = IDirect3DVertexBuffer9_Unlock(buffer);
ErrorHandler_CheckOrFail(hresult, unlockMsg);
}
@ -447,7 +447,7 @@ static void D3D9_SetIbData(IDirect3DIndexBuffer9* buffer, void* data, Int32 size
ReturnCode hresult = IDirect3DIndexBuffer9_Lock(buffer, 0, size, &dst, 0);
ErrorHandler_CheckOrFail(hresult, lockMsg);
Platform_MemCpy(dst, data, size);
Mem_Copy(dst, data, size);
hresult = IDirect3DIndexBuffer9_Unlock(buffer);
ErrorHandler_CheckOrFail(hresult, unlockMsg);
}

View File

@ -220,7 +220,7 @@ static void Huffman_Build(struct HuffmanTable* table, UInt8* bitLens, Int32 coun
}
Int32 value = 0;
Platform_MemSet(table->Fast, UInt8_MaxValue, sizeof(table->Fast));
Mem_Set(table->Fast, UInt8_MaxValue, sizeof(table->Fast));
for (i = 0; i < count; i++, value++) {
Int32 len = bitLens[i];
if (!len) continue;
@ -407,13 +407,13 @@ static void Inflate_InflateFast(struct InflateState* state) {
state->WindowIndex = curIdx;
if (copyLen > 0) {
if (copyStart + copyLen < INFLATE_WINDOW_SIZE) {
Platform_MemCpy(state->Output, &state->Window[copyStart], copyLen);
Mem_Copy(state->Output, &state->Window[copyStart], copyLen);
state->Output += copyLen;
} else {
UInt32 partLen = INFLATE_WINDOW_SIZE - copyStart;
Platform_MemCpy(state->Output, &state->Window[copyStart], partLen);
Mem_Copy(state->Output, &state->Window[copyStart], partLen);
state->Output += partLen;
Platform_MemCpy(state->Output, state->Window, copyLen - partLen);
Mem_Copy(state->Output, state->Window, copyLen - partLen);
state->Output += (copyLen - partLen);
}
}
@ -477,14 +477,14 @@ void Inflate_Process(struct InflateState* state) {
UInt32 copyLen = min(state->AvailIn, state->AvailOut);
copyLen = min(copyLen, state->Index);
if (copyLen > 0) {
Platform_MemCpy(state->Output, state->NextIn, copyLen);
Mem_Copy(state->Output, state->NextIn, copyLen);
UInt32 windowCopyLen = INFLATE_WINDOW_SIZE - state->WindowIndex;
windowCopyLen = min(windowCopyLen, copyLen);
Platform_MemCpy(&state->Window[state->WindowIndex], state->Output, windowCopyLen);
Mem_Copy(&state->Window[state->WindowIndex], state->Output, windowCopyLen);
/* Wrap around remainder of copy to start from beginning of window */
if (windowCopyLen < copyLen) {
Platform_MemCpy(state->Window, &state->Output[windowCopyLen], copyLen - windowCopyLen);
Mem_Copy(state->Window, &state->Output[windowCopyLen], copyLen - windowCopyLen);
}
state->WindowIndex = (state->WindowIndex + copyLen) & INFLATE_WINDOW_MASK;
@ -576,7 +576,7 @@ void Inflate_Process(struct InflateState* state) {
ErrorHandler_Fail("DEFLATE - Tried to repeat past end");
}
Platform_MemSet(&state->Buffer[state->Index], repeatValue, repeatCount);
Mem_Set(&state->Buffer[state->Index], repeatValue, repeatCount);
state->Index += repeatCount;
state->State = INFLATE_STATE_DYNAMIC_LITSDISTS;
break;
@ -760,8 +760,8 @@ static ReturnCode Deflate_FlushBlock(struct DeflateState* state, Int32 len) {
}
/* TODO: Hash chains should persist past one block flush */
Platform_MemSet(state->Head, 0, sizeof(state->Head));
Platform_MemSet(state->Prev, 0, sizeof(state->Prev));
Mem_Set(state->Head, 0, sizeof(state->Head));
Mem_Set(state->Prev, 0, sizeof(state->Prev));
/* Based off descriptions from http://www.gzip.org/algorithm.txt and
https://github.com/nothings/stb/blob/master/stb_image_write.h */
@ -841,7 +841,7 @@ static ReturnCode Deflate_StreamWrite(struct Stream* stream, UInt8* data, UInt32
toWrite = DEFLATE_BUFFER_SIZE - state->InputPosition;
}
Platform_MemCpy(dst, data, toWrite);
Mem_Copy(dst, data, toWrite);
count -= toWrite;
state->InputPosition += toWrite;
*modified += toWrite;
@ -888,8 +888,8 @@ void Deflate_MakeStream(struct Stream* stream, struct DeflateState* state, struc
state->Dest = underlying;
state->WroteHeader = false;
Platform_MemSet(state->Head, 0, sizeof(state->Head));
Platform_MemSet(state->Prev, 0, sizeof(state->Prev));
Mem_Set(state->Head, 0, sizeof(state->Head));
Mem_Set(state->Prev, 0, sizeof(state->Prev));
}

View File

@ -56,7 +56,7 @@ static void Drawer2D_CalculateTextWidths(void) {
}
static void Drawer2D_FreeFontBitmap(void) {
Platform_MemFree(&Drawer2D_FontBitmap.Scan0);
Mem_Free(&Drawer2D_FontBitmap.Scan0);
}
void Drawer2D_SetFontBitmap(struct Bitmap* bmp) {
@ -142,7 +142,7 @@ void Drawer2D_MakeTextTexture(struct Texture* tex, struct DrawTextArgs* args, In
Drawer2D_End();
Drawer2D_Make2DTexture(tex, &bmp, size, windowX, windowY);
Platform_MemFree(&bmp.Scan0);
Mem_Free(&bmp.Scan0);
}
void Drawer2D_Make2DTexture(struct Texture* tex, struct Bitmap* bmp, struct Size2D used, Int32 windowX, Int32 windowY) {

View File

@ -444,10 +444,10 @@ void TabList_Set(EntityID id, STRING_PURE String* player, STRING_PURE String* li
static void TabList_Init(void) { StringsBuffer_Init(&TabList_Buffer); }
static void TabList_Free(void) { StringsBuffer_Free(&TabList_Buffer); }
static void TabList_Reset(void) {
Platform_MemSet(TabList_PlayerNames, 0, sizeof(TabList_PlayerNames));
Platform_MemSet(TabList_ListNames, 0, sizeof(TabList_ListNames));
Platform_MemSet(TabList_GroupNames, 0, sizeof(TabList_GroupNames));
Platform_MemSet(TabList_GroupRanks, 0, sizeof(TabList_GroupRanks));
Mem_Set(TabList_PlayerNames, 0, sizeof(TabList_PlayerNames));
Mem_Set(TabList_ListNames, 0, sizeof(TabList_ListNames));
Mem_Set(TabList_GroupNames, 0, sizeof(TabList_GroupNames));
Mem_Set(TabList_GroupRanks, 0, sizeof(TabList_GroupRanks));
StringsBuffer_Free(&TabList_Buffer);
}
@ -464,7 +464,7 @@ void TabList_MakeComponent(struct IGameComponent* comp) {
#define PLAYER_NAME_EMPTY_TEX -30000
static void Player_MakeNameTexture(struct Player* player) {
struct FontDesc font;
Platform_FontMake(&font, &Game_FontName, 24, FONT_STYLE_NORMAL);
Font_Make(&font, &Game_FontName, 24, FONT_STYLE_NORMAL);
String displayName = String_FromRawArray(player->DisplayNameRaw);
struct DrawTextArgs args;
@ -500,7 +500,7 @@ static void Player_MakeNameTexture(struct Player* player) {
Drawer2D_End();
Drawer2D_Make2DTexture(&player->NameTex, &bmp, size, 0, 0);
Platform_MemFree(&bmp.Scan0);
Mem_Free(&bmp.Scan0);
}
Drawer2D_UseBitmappedChat = bitmapped;
}
@ -663,14 +663,14 @@ static void Player_EnsurePow2(struct Player* player, struct Bitmap* bmp) {
for (y = 0; y < bmp->Height; y++) {
UInt32* src = Bitmap_GetRow(bmp, y);
UInt32* dst = Bitmap_GetRow(&scaled, y);
Platform_MemCpy(dst, src, stride);
Mem_Copy(dst, src, stride);
}
struct Entity* entity = &player->Base;
entity->uScale = (Real32)bmp->Width / width;
entity->vScale = (Real32)bmp->Height / height;
Platform_MemFree(&bmp->Scan0);
Mem_Free(&bmp->Scan0);
*bmp = scaled;
}
@ -712,7 +712,7 @@ static void Player_CheckSkin(struct Player* player) {
entity->TextureId = Gfx_CreateTexture(&bmp, true, false);
Player_SetSkinAll(player, false);
}
Platform_MemFree(&bmp.Scan0);
Mem_Free(&bmp.Scan0);
}
static void Player_Despawn(struct Entity* entity) {
@ -898,7 +898,7 @@ void LocalPlayer_MakeComponent(struct IGameComponent* comp) {
struct EntityVTABLE localplayer_VTABLE;
void LocalPlayer_Init(void) {
struct LocalPlayer* p = &LocalPlayer_Instance;
Platform_MemSet(p, 0, sizeof(struct LocalPlayer));
Mem_Set(p, 0, sizeof(struct LocalPlayer));
Player_Init((struct Player*)p);
Player_SetName((struct Player*)p, &Game_Username, &Game_Username);
@ -1026,7 +1026,7 @@ static void NetPlayer_RenderName(struct Entity* entity) {
struct EntityVTABLE netplayer_VTABLE;
void NetPlayer_Init(struct NetPlayer* player, STRING_PURE String* displayName, STRING_PURE String* skinName) {
Platform_MemSet(player, 0, sizeof(struct NetPlayer));
Mem_Set(player, 0, sizeof(struct NetPlayer));
Player_Init((struct Player*)player);
Player_SetName((struct Player*)player, displayName, skinName);

View File

@ -55,7 +55,7 @@ static void AnimatedComp_CalcHumanAnim(struct AnimatedComp* anim, Real32 idleXRo
}
void AnimatedComp_Init(struct AnimatedComp* anim) {
Platform_MemSet(anim, 0, sizeof(struct AnimatedComp));
Mem_Set(anim, 0, sizeof(struct AnimatedComp));
anim->BobStrength = 1.0f; anim->BobStrengthO = 1.0f; anim->BobStrengthN = 1.0f;
}
@ -152,7 +152,7 @@ static void HacksComp_SetAll(struct HacksComp* hacks, bool allowed) {
}
void HacksComp_Init(struct HacksComp* hacks) {
Platform_MemSet(hacks, 0, sizeof(struct HacksComp));
Mem_Set(hacks, 0, sizeof(struct HacksComp));
HacksComp_SetAll(hacks, true);
hacks->SpeedMultiplier = 10.0f;
hacks->Enabled = true;
@ -873,7 +873,7 @@ void Collisions_MoveAndWallSlide(struct CollisionsComp* comp) {
*----------------------------------------------------PhysicsComponent-----------------------------------------------------*
*#########################################################################################################################*/
void PhysicsComp_Init(struct PhysicsComp* comp, struct Entity* entity) {
Platform_MemSet(comp, 0, sizeof(struct PhysicsComp));
Mem_Set(comp, 0, sizeof(struct PhysicsComp));
comp->CanLiquidJump = true;
comp->Entity = entity;
comp->JumpVel = 0.42f;

View File

@ -180,13 +180,13 @@ static void EnvRenderer_UpdateClouds(void) {
VertexP3fT2fC4b v[ENV_SMALL_VERTICES];
VertexP3fT2fC4b* ptr = v;
if (clouds_vertices > ENV_SMALL_VERTICES) {
ptr = Platform_MemAlloc(clouds_vertices, sizeof(VertexP3fT2fC4b), "temp clouds vertices");
ptr = Mem_Alloc(clouds_vertices, sizeof(VertexP3fT2fC4b), "temp clouds vertices");
}
EnvRenderer_DrawCloudsY(x1, z1, x2, z2, WorldEnv_CloudsHeight, ptr);
clouds_vb = Gfx_CreateVb(ptr, VERTEX_FORMAT_P3FT2FC4B, clouds_vertices);
if (clouds_vertices > ENV_SMALL_VERTICES) Platform_MemFree(&ptr);
if (clouds_vertices > ENV_SMALL_VERTICES) Mem_Free(&ptr);
}
@ -252,14 +252,14 @@ static void EnvRenderer_UpdateSky(void) {
VertexP3fC4b v[ENV_SMALL_VERTICES];
VertexP3fC4b* ptr = v;
if (sky_vertices > ENV_SMALL_VERTICES) {
ptr = Platform_MemAlloc(sky_vertices, sizeof(VertexP3fC4b), "temp sky vertices");
ptr = Mem_Alloc(sky_vertices, sizeof(VertexP3fC4b), "temp sky vertices");
}
Int32 height = max((World_Height + 2) + 6, WorldEnv_CloudsHeight + 6);
EnvRenderer_DrawSkyY(x1, z1, x2, z2, height, ptr);
sky_vb = Gfx_CreateVb(ptr, VERTEX_FORMAT_P3FC4B, sky_vertices);
if (sky_vertices > ENV_SMALL_VERTICES) Platform_MemFree(&ptr);
if (sky_vertices > ENV_SMALL_VERTICES) Mem_Free(&ptr);
}
/*########################################################################################################################*
@ -341,7 +341,7 @@ Real64 weather_accumulator;
Vector3I weather_lastPos;
static void EnvRenderer_InitWeatherHeightmap(void) {
Weather_Heightmap = Platform_MemAlloc(World_Width * World_Length, sizeof(Int16), "weather heightmap");
Weather_Heightmap = Mem_Alloc(World_Width * World_Length, sizeof(Int16), "weather heightmap");
Int32 i;
for (i = 0; i < World_Width * World_Length; i++) {
Weather_Heightmap[i] = Int16_MaxValue;
@ -646,7 +646,7 @@ static void EnvRenderer_UpdateMapSides(void) {
VertexP3fT2fC4b v[ENV_SMALL_VERTICES];
VertexP3fT2fC4b* ptr = v;
if (sides_vertices > ENV_SMALL_VERTICES) {
ptr = Platform_MemAlloc(sides_vertices, sizeof(VertexP3fT2fC4b), "temp sides vertices");
ptr = Mem_Alloc(sides_vertices, sizeof(VertexP3fT2fC4b), "temp sides vertices");
}
VertexP3fT2fC4b* temp = ptr;
@ -671,7 +671,7 @@ static void EnvRenderer_UpdateMapSides(void) {
EnvRenderer_DrawBorderX(World_Width, 0, World_Length, y1, y2, col, &temp);
sides_vb = Gfx_CreateVb(ptr, VERTEX_FORMAT_P3FT2FC4B, sides_vertices);
if (sides_vertices > ENV_SMALL_VERTICES) Platform_MemFree(&ptr);
if (sides_vertices > ENV_SMALL_VERTICES) Mem_Free(&ptr);
}
static void EnvRenderer_UpdateMapEdges(void) {
@ -692,7 +692,7 @@ static void EnvRenderer_UpdateMapEdges(void) {
VertexP3fT2fC4b v[ENV_SMALL_VERTICES];
VertexP3fT2fC4b* ptr = v;
if (edges_vertices > ENV_SMALL_VERTICES) {
ptr = Platform_MemAlloc(edges_vertices, sizeof(VertexP3fT2fC4b), "temp edge vertices");
ptr = Mem_Alloc(edges_vertices, sizeof(VertexP3fT2fC4b), "temp edge vertices");
}
VertexP3fT2fC4b* temp = ptr;
@ -709,7 +709,7 @@ static void EnvRenderer_UpdateMapEdges(void) {
}
edges_vb = Gfx_CreateVb(ptr, VERTEX_FORMAT_P3FT2FC4B, edges_vertices);
if (edges_vertices > ENV_SMALL_VERTICES) Platform_MemFree(&ptr);
if (edges_vertices > ENV_SMALL_VERTICES) Mem_Free(&ptr);
}
@ -754,7 +754,7 @@ static void EnvRenderer_ContextRecreated(void* obj) {
static void EnvRenderer_Reset(void) {
Gfx_SetFog(false);
EnvRenderer_DeleteVbs();
Platform_MemFree(&Weather_Heightmap);
Mem_Free(&Weather_Heightmap);
weather_lastPos = Vector3I_MaxValue();
}
@ -846,7 +846,7 @@ static void EnvRenderer_Free(void) {
Event_UnregisterVoid(&GfxEvents_ContextRecreated, NULL, EnvRenderer_ContextRecreated);
EnvRenderer_ContextLost(NULL);
Platform_MemFree(&Weather_Heightmap);
Mem_Free(&Weather_Heightmap);
Gfx_DeleteTexture(&clouds_tex);
Gfx_DeleteTexture(&skybox_tex);

View File

@ -117,7 +117,7 @@ Real64 Math_FastExp(Real64 x) {
void Random_Init(Random* seed, Int32 seedInit) { Random_SetSeed(seed, seedInit); }
void Random_InitFromCurrentTime(Random* rnd) {
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
Int64 totalMs = DateTime_TotalMs(&now);
Random_Init(rnd, (Int32)totalMs);
}

View File

@ -13,7 +13,7 @@
static void Map_ReadBlocks(struct Stream* stream) {
World_BlocksSize = World_Width * World_Length * World_Height;
World_Blocks = Platform_MemAlloc(World_BlocksSize, sizeof(BlockID), "map blocks for load");
World_Blocks = Mem_Alloc(World_BlocksSize, sizeof(BlockID), "map blocks for load");
Stream_Read(stream, World_Blocks, World_BlocksSize);
}
@ -157,7 +157,7 @@ void Fcm_Load(struct Stream* stream) {
/* header[20] (4) date modified */
/* header[24] (4) date created */
Platform_MemCpy(&World_Uuid, &header[28], sizeof(World_Uuid));
Mem_Copy(&World_Uuid, &header[28], sizeof(World_Uuid));
/* header[44] (26) layer index */
Int32 metaSize = (Int32)Stream_GetU32_LE(&header[70]);
@ -280,7 +280,7 @@ static void Nbt_ReadTag(UInt8 typeId, bool readTagName, struct Stream* stream, s
if (count < NBT_SMALL_SIZE) {
Stream_Read(stream, tag.DataSmall, count);
} else {
tag.DataBig = Platform_MemAlloc(count, sizeof(UInt8), "NBT tag data");
tag.DataBig = Mem_Alloc(count, sizeof(UInt8), "NBT tag data");
Stream_Read(stream, tag.DataBig, count);
}
break;
@ -313,7 +313,7 @@ static void Nbt_ReadTag(UInt8 typeId, bool readTagName, struct Stream* stream, s
bool processed = callback(&tag);
/* don't leak memory for unprocessed tags */
if (!processed && tag.DataSize >= NBT_SMALL_SIZE) Platform_MemFree(&tag.DataBig);
if (!processed && tag.DataSize >= NBT_SMALL_SIZE) Mem_Free(&tag.DataBig);
}
static bool IsTag(struct NbtTag* tag, const UChar* tagName) {
@ -358,14 +358,14 @@ static bool Cw_Callback_1(struct NbtTag* tag) {
if (IsTag(tag, "UUID")) {
if (tag->DataSize != sizeof(World_Uuid)) ErrorHandler_Fail("Map UUID must be 16 bytes");
Platform_MemCpy(World_Uuid, tag->DataSmall, sizeof(World_Uuid));
Mem_Copy(World_Uuid, tag->DataSmall, sizeof(World_Uuid));
return true;
}
if (IsTag(tag, "BlockArray")) {
World_BlocksSize = tag->DataSize;
if (tag->DataSize < NBT_SMALL_SIZE) {
World_Blocks = Platform_MemAlloc(World_BlocksSize, sizeof(UInt8), ".cw map blocks");
Platform_MemCpy(World_Blocks, tag->DataSmall, tag->DataSize);
World_Blocks = Mem_Alloc(World_BlocksSize, sizeof(UInt8), ".cw map blocks");
Mem_Copy(World_Blocks, tag->DataSmall, tag->DataSize);
} else {
World_Blocks = tag->DataBig;
}
@ -604,7 +604,7 @@ struct JClassDesc {
};
static void Dat_ReadString(struct Stream* stream, UInt8* buffer) {
Platform_MemSet(buffer, 0, JNAME_SIZE);
Mem_Set(buffer, 0, JNAME_SIZE);
UInt16 len = Stream_ReadU16_BE(stream);
if (len > JNAME_SIZE) ErrorHandler_Fail("Dat string too long");
@ -693,7 +693,7 @@ static void Dat_ReadFieldData(struct Stream* stream, struct JFieldDesc* field) {
if (arrayClassDesc.ClassName[1] != JFIELD_INT8) ErrorHandler_Fail("Only byte array fields supported");
UInt32 size = Stream_ReadU32_BE(stream);
field->Value_Ptr = Platform_MemAlloc(size, sizeof(UInt8), ".dat map blocks");
field->Value_Ptr = Mem_Alloc(size, sizeof(UInt8), ".dat map blocks");
Stream_Read(stream, field->Value_Ptr, size);
field->Value_Size = size;

View File

@ -106,9 +106,9 @@ String game_defTexPack = String_FromEmptyArray(game_defTexPackBuffer);
void Game_GetDefaultTexturePack(STRING_TRANSIENT String* texPack) {
UChar texPathBuffer[String_BufferSize(STRING_SIZE)];
String texPath = String_InitAndClearArray(texPathBuffer);
String_Format2(&texPath, "texpacks%r%s", &Platform_DirectorySeparator, &game_defTexPack);
String_Format2(&texPath, "texpacks%r%s", &Directory_Separator, &game_defTexPack);
if (Platform_FileExists(&texPath) && !Game_ClassicMode) {
if (File_Exists(&texPath) && !Game_ClassicMode) {
String_AppendString(texPack, &game_defTexPack);
} else {
String_AppendConst(texPack, "default.zip");
@ -231,7 +231,7 @@ bool Game_UpdateTexture(GfxResourceID* texId, struct Stream* src, UInt8* skinTyp
*texId = Gfx_CreateTexture(&bmp, true, false);
}
Platform_MemFree(&bmp.Scan0);
Mem_Free(&bmp.Scan0);
return success;
}
@ -314,7 +314,7 @@ static void Game_TextureChangedCore(void* obj, struct Stream* src) {
ErrorHandler_CheckOrFail(result, "Decoding terrain bitmap");
if (Game_ChangeTerrainAtlas(&atlas)) return;
Platform_MemFree(&atlas.Scan0);
Mem_Free(&atlas.Scan0);
} else if (String_CaselessEqualsConst(&src->Name, "default.png")) {
struct Bitmap bmp;
ReturnCode result = Bitmap_DecodePng(&bmp, src);
@ -555,7 +555,7 @@ static void Game_LimitFPS(void) {
/* going faster than limit */
if (leftOver > 0.001f) {
Platform_ThreadSleep((Int32)(leftOver + 0.5f));
Thread_Sleep((Int32)(leftOver + 0.5f));
}
}
@ -632,12 +632,12 @@ static void Game_DoScheduledTasks(Real64 time) {
void Game_TakeScreenshot(void) {
String dir = String_FromConst("screenshots");
if (!Platform_DirectoryExists(&dir)) {
ReturnCode result = Platform_DirectoryCreate(&dir);
if (!Directory_Exists(&dir)) {
ReturnCode result = Directory_Create(&dir);
ErrorHandler_CheckOrFail(result, "Creating screenshots directory");
}
DateTime now; Platform_CurrentLocalTime(&now);
DateTime now; DateTime_CurrentLocal(&now);
Int32 year = now.Year, month = now.Month, day = now.Day;
Int32 hour = now.Hour, min = now.Minute, sec = now.Second;
@ -648,10 +648,10 @@ void Game_TakeScreenshot(void) {
UChar pathBuffer[String_BufferSize(FILENAME_SIZE)];
String path = String_InitAndClearArray(pathBuffer);
String_Format2(&path, "screenshots%r%s", &Platform_DirectorySeparator, &filename);
String_Format2(&path, "screenshots%r%s", &Directory_Separator, &filename);
void* file;
ReturnCode result = Platform_FileCreate(&file, &path);
ReturnCode result = File_Create(&file, &path);
ErrorHandler_CheckOrFail(result, "Taking screenshot - opening file");
struct Stream stream; Stream_FromFile(&stream, file, &path);
{
@ -762,13 +762,8 @@ void Game_Run(Int32 width, Int32 height, STRING_REF String* title, struct Displa
}
/* TODO: fix all these stubs.... */
void Audio_MakeComponent(struct IGameComponent* comp) { }
void Audio_SetMusic(Int32 volume) { }
void Audio_SetSounds(Int32 volume) { }
void Audio_PlayDigSound(UInt8 type) { }
void Audio_PlayStepSound(UInt8 type) { }
void AdvLightingBuilder_SetActive(void) { }
void Audio_SetVolume(AudioHandle handle, Real32 volume) { }
/* TODO: Initalise Shell, see https://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx
https://stackoverflow.com/questions/24590059/c-opening-a-url-in-default-browser-on-windows-without-admin-privileges */
ReturnCode Platform_StartShell(STRING_PURE String* args) { return 0; }

View File

@ -241,7 +241,7 @@ void TextAtlas_Make(struct TextAtlas* atlas, STRING_PURE String* chars, struct F
atlas->FontSize = font->Size;
size.Width += 16 * chars->length;
Platform_MemSet(atlas->Widths, 0, sizeof(atlas->Widths));
Mem_Set(atlas->Widths, 0, sizeof(atlas->Widths));
struct Bitmap bmp; Bitmap_AllocateClearedPow2(&bmp, size.Width, size.Height);
Drawer2D_Begin(&bmp);
{
@ -256,7 +256,7 @@ void TextAtlas_Make(struct TextAtlas* atlas, STRING_PURE String* chars, struct F
Drawer2D_End();
Drawer2D_Make2DTexture(&atlas->Tex, &bmp, size, 0, 0);
Platform_MemFree(&bmp.Scan0);
Mem_Free(&bmp.Scan0);
Drawer2D_ReducePadding_Tex(&atlas->Tex, Math_Floor(font->Size), 4);
atlas->uScale = 1.0f / (Real32)bmp.Width;

View File

@ -59,7 +59,7 @@ static void InputHandler_ButtonStateChanged(MouseButton button, bool pressed) {
void InputHandler_ScreenChanged(struct Screen* oldScreen, struct Screen* newScreen) {
if (oldScreen && oldScreen->HandlesAllInput) {
Platform_CurrentUTCTime(&input_lastClick);
DateTime_CurrentUTC(&input_lastClick);
}
if (ServerConnection_SupportsPlayerClick) {
@ -303,7 +303,7 @@ static bool InputHandler_CheckIsFree(BlockID block) {
}
void InputHandler_PickBlocks(bool cooldown, bool left, bool middle, bool right) {
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
Int64 delta = DateTime_MsBetween(&input_lastClick, &now);
if (cooldown && delta < 250) return; /* 4 times per second */
@ -402,7 +402,7 @@ static void InputHandler_MouseDown(void* obj, Int32 button) {
bool right = button == MouseButton_Right;
InputHandler_PickBlocks(false, left, middle, right);
} else {
Platform_CurrentUTCTime(&input_lastClick);
DateTime_CurrentUTC(&input_lastClick);
}
}

View File

@ -322,7 +322,7 @@ static void Lighting_Init(void) {
}
static void Lighting_Reset(void) {
Platform_MemFree(&Lighting_heightmap);
Mem_Free(&Lighting_heightmap);
}
static void Lighting_OnNewMap(void) {
@ -332,7 +332,7 @@ static void Lighting_OnNewMap(void) {
}
static void Lighting_OnNewMapLoaded(void) {
Lighting_heightmap = Platform_MemAlloc(World_Width * World_Length, sizeof(Int16), "lighting heightmap");
Lighting_heightmap = Mem_Alloc(World_Width * World_Length, sizeof(Int16), "lighting heightmap");
Lighting_Refresh();
}

View File

@ -15,7 +15,7 @@ static void Gen_Init(void) {
Gen_CurrentProgress = 0.0f;
Gen_CurrentState = "";
Gen_Blocks = Platform_MemAlloc(Gen_Width * Gen_Height * Gen_Length, sizeof(BlockID), "map blocks for gen");
Gen_Blocks = Mem_Alloc(Gen_Width * Gen_Height * Gen_Length, sizeof(BlockID), "map blocks for gen");
Gen_Done = false;
}
@ -31,7 +31,7 @@ static void FlatgrassGen_MapSet(Int32 yStart, Int32 yEnd, BlockID block) {
Gen_CurrentProgress = 0.0f;
for (y = yStart; y <= yEnd; y++) {
Platform_MemSet(ptr + y * oneY, block, oneY * (UInt32)sizeof(BlockID));
Mem_Set(ptr + y * oneY, block, oneY * (UInt32)sizeof(BlockID));
Gen_CurrentProgress = (Real32)(y - yStart) / yHeight;
}
}
@ -156,20 +156,20 @@ static Int32 NotchyGen_CreateStrataFast(void) {
Gen_CurrentState = "Filling map";
/* Make lava layer at bottom */
Platform_MemSet(Gen_Blocks, BLOCK_LAVA, oneY * (UInt32)sizeof(BlockID));
Mem_Set(Gen_Blocks, BLOCK_LAVA, oneY * (UInt32)sizeof(BlockID));
/* Invariant: the lowest value dirtThickness can possible be is -14 */
Int32 stoneHeight = minHeight - 14;
/* We can quickly fill in bottom solid layers */
for (y = 1; y <= stoneHeight; y++) {
Platform_MemSet(Gen_Blocks + y * oneY, BLOCK_STONE, oneY * (UInt32)sizeof(BlockID));
Mem_Set(Gen_Blocks + y * oneY, BLOCK_STONE, oneY * (UInt32)sizeof(BlockID));
Gen_CurrentProgress = (Real32)y / Gen_Height;
}
/* Fill in rest of map wih air */
Int32 airHeight = max(0, stoneHeight) + 1;
for (y = airHeight; y < Gen_Height; y++) {
Platform_MemSet(Gen_Blocks + y * oneY, BLOCK_AIR, oneY * (UInt32)sizeof(BlockID));
Mem_Set(Gen_Blocks + y * oneY, BLOCK_AIR, oneY * (UInt32)sizeof(BlockID));
Gen_CurrentProgress = (Real32)y / Gen_Height;
}
@ -467,7 +467,7 @@ static void NotchyGen_PlantTrees(void) {
void NotchyGen_Generate(void) {
Gen_Init();
Heightmap = Platform_MemAlloc(Gen_Width * Gen_Length, sizeof(Int16), "gen heightmap");
Heightmap = Mem_Alloc(Gen_Width * Gen_Length, sizeof(Int16), "gen heightmap");
Random_Init(&rnd, Gen_Seed);
oneY = Gen_Width * Gen_Length;
@ -490,7 +490,7 @@ void NotchyGen_Generate(void) {
NotchyGen_PlantMushrooms();
NotchyGen_PlantTrees();
Platform_MemFree(&Heightmap);
Mem_Free(&Heightmap);
Gen_Done = true;
}

View File

@ -448,7 +448,7 @@ static void ListScreen_Init(struct GuiElem* elem) {
screen->Widgets = screen->ListWidgets;
screen->WidgetsCount = Array_Elems(screen->ListWidgets);
Platform_FontMake(&screen->Font, &Game_FontName, 16, FONT_STYLE_BOLD);
Font_Make(&screen->Font, &Game_FontName, 16, FONT_STYLE_BOLD);
Key_KeyRepeat = true;
screen->WheelAcc = 0.0f;
ListScreen_ContextRecreated(screen);
@ -465,7 +465,7 @@ static void ListScreen_Render(struct GuiElem* elem, Real64 delta) {
static void ListScreen_Free(struct GuiElem* elem) {
struct ListScreen* screen = (struct ListScreen*)elem;
Platform_FontFree(&screen->Font);
Font_Free(&screen->Font);
Key_KeyRepeat = false;
ListScreen_ContextLost(screen);
Event_UnregisterVoid(&GfxEvents_ContextLost, screen, ListScreen_ContextLost);
@ -507,7 +507,7 @@ static void ListScreen_OnResize(struct GuiElem* elem) {
struct ListScreen* ListScreen_MakeInstance(void) {
struct ListScreen* screen = &ListScreen_Instance;
Platform_MemSet(screen, 0, sizeof(struct ListScreen) - sizeof(StringsBuffer));
Mem_Set(screen, 0, sizeof(struct ListScreen) - sizeof(StringsBuffer));
if (screen->Entries.TextBuffer) StringsBuffer_Free(&screen->Entries);
StringsBuffer_Init(&screen->Entries);
@ -570,10 +570,10 @@ static void MenuScreen_Init(struct GuiElem* elem) {
struct MenuScreen* screen = (struct MenuScreen*)elem;
if (!screen->TitleFont.Handle) {
Platform_FontMake(&screen->TitleFont, &Game_FontName, 16, FONT_STYLE_BOLD);
Font_Make(&screen->TitleFont, &Game_FontName, 16, FONT_STYLE_BOLD);
}
if (!screen->TextFont.Handle) {
Platform_FontMake(&screen->TextFont, &Game_FontName, 16, FONT_STYLE_NORMAL);
Font_Make(&screen->TextFont, &Game_FontName, 16, FONT_STYLE_NORMAL);
}
Event_RegisterVoid(&GfxEvents_ContextLost, screen, MenuScreen_ContextLost_Callback);
@ -592,10 +592,10 @@ static void MenuScreen_Free(struct GuiElem* elem) {
screen->ContextLost(screen);
if (screen->TitleFont.Handle) {
Platform_FontFree(&screen->TitleFont);
Font_Free(&screen->TitleFont);
}
if (screen->TextFont.Handle) {
Platform_FontFree(&screen->TextFont);
Font_Free(&screen->TextFont);
}
Event_UnregisterVoid(&GfxEvents_ContextLost, screen, MenuScreen_ContextLost_Callback);
@ -605,7 +605,7 @@ static void MenuScreen_Free(struct GuiElem* elem) {
static void MenuScreen_OnResize(struct GuiElem* elem) { Menu_Reposition((struct MenuBase*)elem); }
static void MenuScreen_MakeInstance(struct MenuScreen* screen, struct Widget** widgets, Int32 count, Menu_ContextFunc contextRecreated) {
Platform_MemSet(screen, 0, sizeof(struct MenuScreen));
Mem_Set(screen, 0, sizeof(struct MenuScreen));
screen->VTABLE = &MenuScreen_VTABLE;
Screen_Reset((struct Screen*)screen);
@ -1279,7 +1279,7 @@ static void SaveLevelScreen_DoSave(struct GuiElem* elem, struct GuiElem* widget,
String_Format2(&path, "maps/%s%c", &file, ext);
struct ButtonWidget* btn = (struct ButtonWidget*)widget;
if (Platform_FileExists(&path) && !btn->OptName) {
if (File_Exists(&path) && !btn->OptName) {
String warnMsg = String_FromConst("&cOverwrite existing?");
ButtonWidget_SetText(btn, &warnMsg);
btn->OptName = "O";
@ -1321,7 +1321,7 @@ static void SaveLevelScreen_Render(struct GuiElem* elem, Real64 delta) {
String path = screen->TextPath;
void* file;
ReturnCode result = Platform_FileCreate(&file, &path);
ReturnCode result = File_Create(&file, &path);
ErrorHandler_CheckOrFail(result, "Saving map - opening file");
struct Stream stream; Stream_FromFile(&stream, file, &path);
{
@ -1422,8 +1422,8 @@ static void TexturePackScreen_EntryClick(struct GuiElem* elem, struct GuiElem* w
String path = String_InitAndClearArray(pathBuffer);
String filename = ListScreen_UNSAFE_GetCur(screen, w);
String_Format2(&path, "texpacks%r%s", &Platform_DirectorySeparator, &filename);
if (!Platform_FileExists(&path)) return;
String_Format2(&path, "texpacks%r%s", &Directory_Separator, &filename);
if (!File_Exists(&path)) return;
Int32 curPage = screen->CurrentIndex;
Game_SetDefaultTexturePack(&filename);
@ -1446,7 +1446,7 @@ struct Screen* TexturePackScreen_MakeInstance(void) {
screen->EntryClick = TexturePackScreen_EntryClick;
String path = String_FromConst("texpacks");
Platform_EnumFiles(&path, &screen->Entries, TexturePackScreen_SelectEntry);
Directory_Enum(&path, &screen->Entries, TexturePackScreen_SelectEntry);
if (screen->Entries.Count > 0) {
ListScreen_QuickSort(0, screen->Entries.Count - 1);
}
@ -1543,7 +1543,7 @@ void LoadLevelScreen_LoadMap(STRING_PURE String* path) {
Inventory_SetDefaultMapping();
void* file;
ReturnCode result = Platform_FileOpen(&file, path);
ReturnCode result = File_Open(&file, path);
ErrorHandler_CheckOrFail(result, "Loading map - open file");
struct Stream stream; Stream_FromFile(&stream, file, path);
{
@ -1576,8 +1576,8 @@ static void LoadLevelScreen_EntryClick(struct GuiElem* elem, struct GuiElem* w)
String path = String_InitAndClearArray(pathBuffer);
String filename = ListScreen_UNSAFE_GetCur(screen, w);
String_Format2(&path, "maps%r%s", &Platform_DirectorySeparator, &filename);
if (!Platform_FileExists(&path)) return;
String_Format2(&path, "maps%r%s", &Directory_Separator, &filename);
if (!File_Exists(&path)) return;
LoadLevelScreen_LoadMap(&path);
}
@ -1587,7 +1587,7 @@ struct Screen* LoadLevelScreen_MakeInstance(void) {
screen->EntryClick = LoadLevelScreen_EntryClick;
String path = String_FromConst("maps");
Platform_EnumFiles(&path, &screen->Entries, LoadLevelScreen_SelectEntry);
Directory_Enum(&path, &screen->Entries, LoadLevelScreen_SelectEntry);
if (screen->Entries.Count > 0) {
ListScreen_QuickSort(0, screen->Entries.Count - 1);
}
@ -2123,7 +2123,7 @@ static void MenuOptionsScreen_Input(struct GuiElem* elem, struct GuiElem* widget
struct Screen* MenuOptionsScreen_MakeInstance(struct Widget** widgets, Int32 count, struct ButtonWidget* buttons, Menu_ContextFunc contextRecreated,
struct MenuInputValidator* validators, const UChar** defaultValues, const UChar** descriptions, Int32 descsCount) {
struct MenuOptionsScreen* screen = &MenuOptionsScreen_Instance;
Platform_MemSet(screen, 0, sizeof(struct MenuOptionsScreen));
Mem_Set(screen, 0, sizeof(struct MenuOptionsScreen));
MenuScreen_MakeInstance((struct MenuScreen*)screen, widgets, count, contextRecreated);
MenuOptionsScreen_VTABLE = *screen->VTABLE;
screen->VTABLE = &MenuOptionsScreen_VTABLE;
@ -3006,7 +3006,7 @@ static void TexIdsOverlay_RenderTextOverlay(struct TexIdsOverlay* screen) {
static void TexIdsOverlay_Init(struct GuiElem* elem) {
struct MenuScreen* screen = (struct MenuScreen*)elem;
Platform_FontMake(&screen->TextFont, &Game_FontName, 8, FONT_STYLE_NORMAL);
Font_Make(&screen->TextFont, &Game_FontName, 8, FONT_STYLE_NORMAL);
Overlay_Init(elem);
}

View File

@ -22,7 +22,7 @@
#define UNIX_EPOCH 62135596800
UChar* Platform_NewLine = "\n";
UChar Platform_DirectorySeparator = '/';
UChar Directory_Separator = '/';
ReturnCode ReturnCode_FileShareViolation = 1000000000; /* TODO: not used apparently */
ReturnCode ReturnCode_FileNotFound = ENOENT;
ReturnCode ReturnCode_NotSupported = EPERM;
@ -84,35 +84,35 @@ static void Platform_AllocFailed(const UChar* place) {
ErrorHandler_Fail(&log.buffer);
}
void* Platform_MemAlloc(UInt32 numElems, UInt32 elemsSize, const UChar* place) {
void* Mem_Alloc(UInt32 numElems, UInt32 elemsSize, const UChar* place) {
void* ptr = malloc(numElems * elemsSize); /* TODO: avoid overflow here */
if (!ptr) Platform_AllocFailed(place);
return ptr;
}
void* Platform_MemAllocCleared(UInt32 numElems, UInt32 elemsSize, const UChar* place) {
void* Mem_AllocCleared(UInt32 numElems, UInt32 elemsSize, const UChar* place) {
void* ptr = calloc(numElems, elemsSize); /* TODO: avoid overflow here */
if (!ptr) Platform_AllocFailed(place);
return ptr;
}
void* Platform_MemRealloc(void* mem, UInt32 numElems, UInt32 elemsSize, const UChar* place) {
void* Mem_Realloc(void* mem, UInt32 numElems, UInt32 elemsSize, const UChar* place) {
void* ptr = realloc(mem, numElems * elemsSize); /* TODO: avoid overflow here */
if (!ptr) Platform_AllocFailed(place);
return ptr;
}
void Platform_MemFree(void** mem) {
void Mem_Free(void** mem) {
if (mem == NULL || *mem == NULL) return;
free(*mem);
*mem = NULL;
}
void Platform_MemSet(void* dst, UInt8 value, UInt32 numBytes) {
void Mem_Set(void* dst, UInt8 value, UInt32 numBytes) {
memset(dst, value, numBytes);
}
void Platform_MemCpy(void* dst, void* src, UInt32 numBytes) {
void Mem_Copy(void* dst, void* src, UInt32 numBytes) {
memcpy(dst, src, numBytes);
}
@ -135,7 +135,7 @@ void Platform_FromSysTime(DateTime* time, struct tm* sysTime) {
time->Milli = 0;
}
void Platform_CurrentUTCTime(DateTime* time_) {
void DateTime_CurrentUTC(DateTime* time_) {
struct timeval cur; struct tm utc_time;
gettimeofday(&cur, NULL);
time_->Milli = cur.tv_usec / 1000;
@ -144,7 +144,7 @@ void Platform_CurrentUTCTime(DateTime* time_) {
Platform_FromSysTime(time_, &utc_time);
}
void Platform_CurrentLocalTime(DateTime* time_) {
void DateTime_CurrentLocal(DateTime* time_) {
struct timeval cur; struct tm loc_time;
gettimeofday(&cur, NULL);
time_->Milli = cur.tv_usec / 1000;
@ -153,26 +153,26 @@ void Platform_CurrentLocalTime(DateTime* time_) {
Platform_FromSysTime(time_, &loc_time);
}
bool Platform_DirectoryExists(STRING_PURE String* path) {
bool Directory_Exists(STRING_PURE String* path) {
UInt8 data[1024]; Platform_UnicodeExpand(data, path);
struct stat sb;
return stat(data, &sb) == 0 && S_ISDIR(sb.st_mode);
}
ReturnCode Platform_DirectoryCreate(STRING_PURE String* path) {
ReturnCode Directory_Create(STRING_PURE String* path) {
UInt8 data[1024]; Platform_UnicodeExpand(data, path);
/* read/write/search permissions for owner and group, and with read/search permissions for others. */
/* TODO: Is the default mode in all cases */
return mkdir(data, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1 ? errno : 0;
}
bool Platform_FileExists(STRING_PURE String* path) {
bool File_Exists(STRING_PURE String* path) {
UInt8 data[1024]; Platform_UnicodeExpand(data, path);
struct stat sb;
return stat(data, &sb) == 0 && S_ISREG(sb.st_mode);
}
ReturnCode Platform_EnumFiles(STRING_PURE String* path, void* obj, Platform_EnumFilesCallback callback) {
ReturnCode Directory_Enum(STRING_PURE String* path, void* obj, Directory_EnumCallback callback) {
UInt8 data[1024]; Platform_UnicodeExpand(data, path);
DIR* dirPtr = opendir(data);
if (!dirPtr) return errno;
@ -196,7 +196,7 @@ ReturnCode Platform_EnumFiles(STRING_PURE String* path, void* obj, Platform_Enum
return result;
}
ReturnCode Platform_FileGetModifiedTime(STRING_PURE String* path, DateTime* time) {
ReturnCode File_GetModifiedTime(STRING_PURE String* path, DateTime* time) {
UInt8 data[1024]; Platform_UnicodeExpand(data, path);
struct stat sb;
if (stat(data, &sb) == -1) return errno;
@ -205,41 +205,41 @@ ReturnCode Platform_FileGetModifiedTime(STRING_PURE String* path, DateTime* time
return 0;
}
ReturnCode Platform_FileDo(void** file, STRING_PURE String* path, int mode) {
ReturnCode File_Do(void** file, STRING_PURE String* path, int mode) {
UInt8 data[1024]; Platform_UnicodeExpand(data, path);
*file = open(data, mode);
return *file == -1 ? errno : 0;
}
ReturnCode Platform_FileOpen(void** file, STRING_PURE String* path) {
return Platform_FileDo(file, path, O_RDONLY);
ReturnCode File_Open(void** file, STRING_PURE String* path) {
return File_Do(file, path, O_RDONLY);
}
ReturnCode Platform_FileCreate(void** file, STRING_PURE String* path) {
return Platform_FileDo(file, path, O_WRONLY | O_CREAT | O_TRUNC);
ReturnCode File_Create(void** file, STRING_PURE String* path) {
return File_Do(file, path, O_WRONLY | O_CREAT | O_TRUNC);
}
ReturnCode Platform_FileAppend(void** file, STRING_PURE String* path) {
ReturnCode code = Platform_FileDo(file, path, O_WRONLY | O_CREAT);
ReturnCode File_Append(void** file, STRING_PURE String* path) {
ReturnCode code = File_Do(file, path, O_WRONLY | O_CREAT);
if (code != 0) return code;
return Platform_FileSeek(*file, 0, STREAM_SEEKFROM_END);
return File_Seek(*file, 0, STREAM_SEEKFROM_END);
}
ReturnCode Platform_FileRead(void* file, UInt8* buffer, UInt32 count, UInt32* bytesRead) {
ReturnCode File_Read(void* file, UInt8* buffer, UInt32 count, UInt32* bytesRead) {
ssize_t bytes = read((int)file, buffer, count);
if (bytes == -1) { *bytesRead = 0; return errno; }
*bytesRead = bytes; return 0;
}
ReturnCode Platform_FileWrite(void* file, UInt8* buffer, UInt32 count, UInt32* bytesWrote) {
ReturnCode File_Write(void* file, UInt8* buffer, UInt32 count, UInt32* bytesWrote) {
ssize_t bytes = write((int)file, buffer, count);
if (bytes == -1) { *bytesWrote = 0; return errno; }
*bytesWrote = bytes; return 0;
}
ReturnCode Platform_FileClose(void* file) {
ReturnCode File_Close(void* file) {
return close((int)file) == -1 ? errno : 0;
}
ReturnCode Platform_FileSeek(void* file, Int32 offset, Int32 seekType) {
ReturnCode File_Seek(void* file, Int32 offset, Int32 seekType) {
int mode = -1;
switch (seekType) {
case STREAM_SEEKFROM_BEGIN: mode = SEEK_SET; break;
@ -250,50 +250,50 @@ ReturnCode Platform_FileSeek(void* file, Int32 offset, Int32 seekType) {
return lseek((int)file, offset, mode) == -1 ? errno : 0;
}
ReturnCode Platform_FilePosition(void* file, UInt32* position) {
ReturnCode File_Position(void* file, UInt32* position) {
off_t pos = lseek((int)file, 0, SEEK_CUR);
if (pos == -1) { *position = -1; return errno; }
*position = pos; return 0;
}
ReturnCode Platform_FileLength(void* file, UInt32* length) {
ReturnCode File_Length(void* file, UInt32* length) {
struct stat st;
if (fstat((int)file, &st) == -1) { *length = -1; return errno; }
*length = st.st_size; return 0;
}
void Platform_ThreadSleep(UInt32 milliseconds) {
void Thread_Sleep(UInt32 milliseconds) {
usleep(milliseconds * 1000);
}
void* Platform_ThreadStartCallback(void* lpParam) {
Platform_ThreadFunc* func = (Platform_ThreadFunc*)lpParam;
void* Thread_StartCallback(void* lpParam) {
Thread_StartFunc* func = (Thread_StartFunc*)lpParam;
(*func)();
return NULL;
}
pthread_t threadList[3]; Int32 threadIndex;
void* Platform_ThreadStart(Platform_ThreadFunc* func) {
void* Thread_Start(Thread_StartFunc* func) {
if (threadIndex == Array_Elems(threadList)) ErrorHandler_Fail("Cannot allocate thread");
pthread_t* ptr = &threadList[threadIndex];
int result = pthread_create(ptr, NULL, Platform_ThreadStartCallback, func);
int result = pthread_create(ptr, NULL, Thread_StartCallback, func);
ErrorHandler_CheckOrFail(result, "Creating thread");
threadIndex++; return ptr;
}
void Platform_ThreadJoin(void* handle) {
void Thread_Join(void* handle) {
int result = pthread_join(*((pthread_t*)handle), NULL);
ErrorHandler_CheckOrFail(result, "Joining thread");
}
void Platform_ThreadFreeHandle(void* handle) {
void Thread_FreeHandle(void* handle) {
int result = pthread_detach(*((pthread_t*)handle));
ErrorHandler_CheckOrFail(result, "Detaching thread");
}
pthread_mutex_t mutexList[3]; Int32 mutexIndex;
void* Platform_MutexCreate(void) {
void* Mutex_Create(void) {
if (mutexIndex == Array_Elems(mutexList)) ErrorHandler_Fail("Cannot allocate mutex");
pthread_mutex_t* ptr = &mutexList[mutexIndex];
int result = pthread_mutex_init(ptr, NULL);
@ -302,23 +302,23 @@ void* Platform_MutexCreate(void) {
mutexIndex++; return ptr;
}
void Platform_MutexFree(void* handle) {
void Mutex_Free(void* handle) {
int result = pthread_mutex_destroy((pthread_mutex_t*)handle);
ErrorHandler_CheckOrFail(result, "Destroying mutex");
}
void Platform_MutexLock(void* handle) {
void Mutex_Lock(void* handle) {
int result = pthread_mutex_lock((pthread_mutex_t*)handle);
ErrorHandler_CheckOrFail(result, "Locking mutex");
}
void Platform_MutexUnlock(void* handle) {
void Mutex_Unlock(void* handle) {
int result = pthread_mutex_unlock((pthread_mutex_t*)handle);
ErrorHandler_CheckOrFail(result, "Unlocking mutex");
}
pthread_cond_t condList[2]; Int32 condIndex;
void* Platform_EventCreate(void) {
void* Waitable_Create(void) {
if (condIndex == Array_Elems(condList)) ErrorHandler_Fail("Cannot allocate event");
pthread_cond_t* ptr = &condList[condIndex];
int result = pthread_cond_init(ptr, NULL);
@ -327,17 +327,17 @@ void* Platform_EventCreate(void) {
condIndex++; return ptr;
}
void Platform_EventFree(void* handle) {
void Waitable_Free(void* handle) {
int result = pthread_cond_destroy((pthread_cond_t*)handle);
ErrorHandler_CheckOrFail(result, "Destroying event");
}
void Platform_EventSignal(void* handle) {
void Waitable_Signal(void* handle) {
int result = pthread_cond_signal((pthread_cond_t*)handle);
ErrorHandler_CheckOrFail(result, "Signalling event");
}
void Platform_EventWait(void* handle) {
void Waitable_Wait(void* handle) {
int result = pthread_cond_wait((pthread_cond_t*)handle, &event_mutex);
ErrorHandler_CheckOrFail(result, "Waiting event");
}
@ -363,18 +363,18 @@ Int32 Stopwatch_ElapsedMicroseconds(struct Stopwatch* timer) {
}
/* TODO: Implement these stubs */
void Platform_FontMake(struct FontDesc* desc, STRING_PURE String* fontName, UInt16 size, UInt16 style) { desc->Size = size; }
void Platform_FontFree(struct FontDesc* desc) { }
void Font_Make(struct FontDesc* desc, STRING_PURE String* fontName, UInt16 size, UInt16 style) { desc->Size = size; }
void Font_Free(struct FontDesc* desc) { }
struct Size2D Platform_TextMeasure(struct DrawTextArgs* args) { }
void Platform_SetBitmap(struct Bitmap* bmp) { }
struct Size2D Platform_TextDraw(struct DrawTextArgs* args, Int32 x, Int32 y, PackedCol col) { }
void Platform_ReleaseBitmap(void) { }
/* TODO: Implement these stubs */
void Platform_HttpInit(void) { }
ReturnCode Platform_HttpMakeRequest(struct AsyncRequest* request, void** handle) { return 1; }
ReturnCode Platform_HttpGetRequestHeaders(struct AsyncRequest* request, void* handle, UInt32* size) { return 1; }
ReturnCode Platform_HttpGetRequestData(struct AsyncRequest* request, void* handle, void** data, UInt32 size, volatile Int32* progress) { return 1; }
ReturnCode Platform_HttpFreeRequest(void* handle) { return 1; }
ReturnCode Platform_HttpFree(void) { return 1; }
void Http_Init(void) { }
ReturnCode Http_MakeRequest(struct AsyncRequest* request, void** handle) { return 1; }
ReturnCode Http_GetRequestHeaders(struct AsyncRequest* request, void* handle, UInt32* size) { return 1; }
ReturnCode Http_GetRequestData(struct AsyncRequest* request, void* handle, void** data, UInt32 size, volatile Int32* progress) { return 1; }
ReturnCode Http_FreeRequest(void* handle) { return 1; }
ReturnCode Http_Free(void) { return 1; }
#endif

View File

@ -226,7 +226,7 @@ void Window_GetClipboardText(STRING_TRANSIENT String* value) {
String_Set(value, &clipboard_paste_text);
return;
} else {
Platform_ThreadSleep(100);
Thread_Sleep(100);
}
}
}

View File

@ -123,7 +123,7 @@ static void GL_DoMipmaps(GfxResourceID texId, Int32 x, Int32 y, struct Bitmap* b
if (width > 1) width /= 2;
if (height > 1) height /= 2;
UInt8* cur = Platform_MemAlloc(width * height, BITMAP_SIZEOF_PIXEL, "mipmaps");
UInt8* cur = Mem_Alloc(width * height, BITMAP_SIZEOF_PIXEL, "mipmaps");
GfxCommon_GenMipmaps(width, height, cur, prev);
if (partial) {
@ -132,10 +132,10 @@ static void GL_DoMipmaps(GfxResourceID texId, Int32 x, Int32 y, struct Bitmap* b
glTexImage2D(GL_TEXTURE_2D, lvl, GL_RGBA, width, height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, cur);
}
if (prev != bmp->Scan0) Platform_MemFree(&prev);
if (prev != bmp->Scan0) Mem_Free(&prev);
prev = cur;
}
if (prev != bmp->Scan0) Platform_MemFree(&prev);
if (prev != bmp->Scan0) Mem_Free(&prev);
}
GfxResourceID Gfx_CreateTexture(struct Bitmap* bmp, bool managedPool, bool mipmaps) {
@ -528,16 +528,16 @@ void Gfx_TakeScreenshot(struct Stream* output, Int32 width, Int32 height) {
UInt32* src = Bitmap_GetRow(&bmp, y);
UInt32* dst = Bitmap_GetRow(&bmp, (height - 1) - y);
Platform_MemCpy(tmp, src, stride);
Platform_MemCpy(src, dst, stride);
Platform_MemCpy(dst, tmp, stride);
Mem_Copy(tmp, src, stride);
Mem_Copy(src, dst, stride);
Mem_Copy(dst, tmp, stride);
/*for (x = 0; x < bmp.Width; x++) {
UInt32 temp = dst[x]; dst[x] = src[x]; src[x] = temp;
}*/
}
Bitmap_EncodePng(&bmp, output);
Platform_MemFree(&bmp.Scan0);
Mem_Free(&bmp.Scan0);
}
void Gfx_MakeApiInfo(void) {
@ -554,18 +554,18 @@ void Gfx_MakeApiInfo(void) {
bool Gfx_WarnIfNecessary(void) {
#if CC_BUILD_GL11
Chat_AddRaw(tmp1, "&cYou are using the very outdated OpenGL backend.");
Chat_AddRaw(tmp2, "&cAs such you may experience poor performance.");
Chat_AddRaw(tmp3, "&cIt is likely you need to install video card drivers.");
Chat_AddRaw("&cYou are using the very outdated OpenGL backend.");
Chat_AddRaw("&cAs such you may experience poor performance.");
Chat_AddRaw("&cIt is likely you need to install video card drivers.");
#endif
String renderer = String_FromReadonly(glGetString(GL_RENDERER));
String intel = String_FromConst("Intel");
if (!String_ContainsString(&renderer, &intel)) return false;
Chat_AddRaw(tmp4, "&cIntel graphics cards are known to have issues with the OpenGL build.");
Chat_AddRaw(tmp5, "&cVSync may not work, and you may see disappearing clouds and map edges.");
Chat_AddRaw(tmp6, "&cFor Windows, try downloading the Direct3D 9 build instead.");
Chat_AddRaw("&cIntel graphics cards are known to have issues with the OpenGL build.");
Chat_AddRaw("&cVSync may not work, and you may see disappearing clouds and map edges.");
Chat_AddRaw("&cFor Windows, try downloading the Direct3D 9 build instead.");
return true;
}

View File

@ -159,7 +159,7 @@ void Options_Set(const UChar* keyRaw, STRING_PURE String* value) {
void Options_Load(void) {
void* file;
String path = String_FromConst("options.txt");
ReturnCode result = Platform_FileOpen(&file, &path);
ReturnCode result = File_Open(&file, &path);
if (result == ReturnCode_FileNotFound) return;
/* TODO: Should we just log failure to open? */
@ -204,7 +204,7 @@ void Options_Load(void) {
void Options_Save(void) {
void* file;
String path = String_FromConst("options.txt");
ReturnCode result = Platform_FileCreate(&file, &path);
ReturnCode result = File_Create(&file, &path);
/* TODO: Should we just log failure to save? */
ErrorHandler_CheckOrFail(result, "Options - Saving");

View File

@ -396,7 +396,7 @@ static void Classic_StartLoading(struct Stream* stream) {
mapSizeIndex = 0;
mapIndex = 0;
Platform_CurrentUTCTime(&mapReceiveStart);
DateTime_CurrentUTC(&mapReceiveStart);
}
static void Classic_LevelInit(struct Stream* stream) {
@ -407,7 +407,7 @@ static void Classic_LevelInit(struct Stream* stream) {
mapVolume = Stream_ReadU32_BE(stream);
gzHeader.Done = true;
mapSizeIndex = sizeof(UInt32);
map = Platform_MemAlloc(mapVolume, sizeof(BlockID), "map blocks");
map = Mem_Alloc(mapVolume, sizeof(BlockID), "map blocks");
}
}
@ -436,7 +436,7 @@ static void Classic_LevelDataChunk(struct Stream* stream) {
if (mapSizeIndex == sizeof(UInt32)) {
if (!map) {
mapVolume = Stream_GetU32_BE(mapSize);
map = Platform_MemAlloc(mapVolume, sizeof(BlockID), "map blocks");
map = Mem_Alloc(mapVolume, sizeof(BlockID), "map blocks");
}
UInt8* src = map + mapIndex;
@ -462,7 +462,7 @@ static void Classic_LevelFinalise(struct Stream* stream) {
Int32 mapHeight = Stream_ReadU16_BE(stream);
Int32 mapLength = Stream_ReadU16_BE(stream);
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
Int32 loadingMs = (Int32)DateTime_MsBetween(&mapReceiveStart, &now);
Platform_Log1("map loading took: %i", &loadingMs);

View File

@ -166,10 +166,10 @@ Int32 Searcher_FindReachableBlocks(struct Entity* entity, struct AABB* entityBB,
UInt32 elements = (max.X - min.X + 1) * (max.Y - min.Y + 1) * (max.Z - min.Z + 1);
if (elements > Searcher_StatesCount) {
if (Searcher_StatesCount > SEARCHER_STATES_MIN) {
Platform_MemFree(&Searcher_States);
Mem_Free(&Searcher_States);
}
Searcher_StatesCount = elements;
Searcher_States = Platform_MemAlloc(elements, sizeof(struct SearcherState), "collision search states");
Searcher_States = Mem_Alloc(elements, sizeof(struct SearcherState), "collision search states");
}
/* Order loops so that we minimise cache misses */
@ -225,6 +225,6 @@ void Searcher_CalcTime(Vector3* vel, struct AABB *entityBB, struct AABB* blockBB
void Searcher_Free(void) {
if (Searcher_StatesCount > SEARCHER_STATES_MIN) {
Platform_MemFree(&Searcher_States);
Mem_Free(&Searcher_States);
}
}

View File

@ -19,7 +19,7 @@ typedef Int32 SocketPtr;
#endif
extern UChar* Platform_NewLine; /* Newline for text */
extern UChar Platform_DirectorySeparator;
extern UChar Directory_Separator;
extern ReturnCode ReturnCode_FileShareViolation;
extern ReturnCode ReturnCode_FileNotFound;
extern ReturnCode ReturnCode_NotSupported;
@ -32,13 +32,14 @@ void Platform_Init(void);
void Platform_Free(void);
void Platform_Exit(ReturnCode code);
STRING_PURE String Platform_GetCommandLineArgs(void);
ReturnCode Platform_StartShell(STRING_PURE String* args);
void* Platform_MemAlloc(UInt32 numElems, UInt32 elemsSize, const UChar* place);
void* Platform_MemAllocCleared(UInt32 numElems, UInt32 elemsSize, const UChar* place);
void* Platform_MemRealloc(void* mem, UInt32 numElems, UInt32 elemsSize, const UChar* place);
void Platform_MemFree(void** mem);
void Platform_MemSet(void* dst, UInt8 value, UInt32 numBytes);
void Platform_MemCpy(void* dst, void* src, UInt32 numBytes);
void* Mem_Alloc(UInt32 numElems, UInt32 elemsSize, const UChar* place);
void* Mem_AllocCleared(UInt32 numElems, UInt32 elemsSize, const UChar* place);
void* Mem_Realloc(void* mem, UInt32 numElems, UInt32 elemsSize, const UChar* place);
void Mem_Free(void** mem);
void Mem_Set(void* dst, UInt8 value, UInt32 numBytes);
void Mem_Copy(void* dst, void* src, UInt32 numBytes);
void Platform_Log(STRING_PURE String* message);
void Platform_LogConst(const UChar* message);
@ -46,83 +47,84 @@ void Platform_LogConst(const UChar* message);
#define Platform_Log2(format, a1, a2) Platform_Log4(format, a1, a2, NULL, NULL)
#define Platform_Log3(format, a1, a2, a3) Platform_Log4(format, a1, a2, a3, NULL)
void Platform_Log4(const UChar* format, const void* a1, const void* a2, const void* a3, const void* a4);
void Platform_CurrentUTCTime(DateTime* time);
void Platform_CurrentLocalTime(DateTime* time);
void DateTime_CurrentUTC(DateTime* time);
void DateTime_CurrentLocal(DateTime* time);
bool Platform_DirectoryExists(STRING_PURE String* path);
ReturnCode Platform_DirectoryCreate(STRING_PURE String* path);
bool Platform_FileExists(STRING_PURE String* path);
typedef void Platform_EnumFilesCallback(STRING_PURE String* filename, void* obj);
ReturnCode Platform_EnumFiles(STRING_PURE String* path, void* obj, Platform_EnumFilesCallback callback);
ReturnCode Platform_FileGetModifiedTime(STRING_PURE String* path, DateTime* time);
bool Directory_Exists(STRING_PURE String* path);
ReturnCode Directory_Create(STRING_PURE String* path);
typedef void Directory_EnumCallback(STRING_PURE String* filename, void* obj);
ReturnCode Directory_Enum(STRING_PURE String* path, void* obj, Directory_EnumCallback callback);
bool File_Exists(STRING_PURE String* path);
ReturnCode File_GetModifiedTime(STRING_PURE String* path, DateTime* time);
ReturnCode Platform_FileCreate(void** file, STRING_PURE String* path);
ReturnCode Platform_FileOpen(void** file, STRING_PURE String* path);
ReturnCode Platform_FileAppend(void** file, STRING_PURE String* path);
ReturnCode Platform_FileRead(void* file, UInt8* buffer, UInt32 count, UInt32* bytesRead);
ReturnCode Platform_FileWrite(void* file, UInt8* buffer, UInt32 count, UInt32* bytesWrote);
ReturnCode Platform_FileClose(void* file);
ReturnCode Platform_FileSeek(void* file, Int32 offset, Int32 seekType);
ReturnCode Platform_FilePosition(void* file, UInt32* position);
ReturnCode Platform_FileLength(void* file, UInt32* length);
ReturnCode File_Create(void** file, STRING_PURE String* path);
ReturnCode File_Open(void** file, STRING_PURE String* path);
ReturnCode File_Append(void** file, STRING_PURE String* path);
ReturnCode File_Read(void* file, UInt8* buffer, UInt32 count, UInt32* bytesRead);
ReturnCode File_Write(void* file, UInt8* buffer, UInt32 count, UInt32* bytesWrote);
ReturnCode File_Close(void* file);
ReturnCode File_Seek(void* file, Int32 offset, Int32 seekType);
ReturnCode File_Position(void* file, UInt32* position);
ReturnCode File_Length(void* file, UInt32* length);
void Platform_ThreadSleep(UInt32 milliseconds);
typedef void Platform_ThreadFunc(void);
void* Platform_ThreadStart(Platform_ThreadFunc* func);
void Platform_ThreadJoin(void* handle);
void Thread_Sleep(UInt32 milliseconds);
typedef void Thread_StartFunc(void);
void* Thread_Start(Thread_StartFunc* func);
void Thread_Join(void* handle);
/* Frees handle to thread - NOT THE THREAD ITSELF */
void Platform_ThreadFreeHandle(void* handle);
void Thread_FreeHandle(void* handle);
void* Platform_MutexCreate(void);
void Platform_MutexFree(void* handle);
void Platform_MutexLock(void* handle);
void Platform_MutexUnlock(void* handle);
void* Mutex_Create(void);
void Mutex_Free(void* handle);
void Mutex_Lock(void* handle);
void Mutex_Unlock(void* handle);
void* Platform_EventCreate(void);
void Platform_EventFree(void* handle);
void Platform_EventSignal(void* handle);
void Platform_EventWait(void* handle);
void* Waitable_Create(void);
void Waitable_Free(void* handle);
void Waitable_Signal(void* handle);
void Waitable_Wait(void* handle);
void Waitable_WaitFor(void* handle, UInt32 milliseconds);
struct Stopwatch { Int64 Data[2]; };
void Stopwatch_Start(struct Stopwatch* timer);
Int32 Stopwatch_ElapsedMicroseconds(struct Stopwatch* timer);
ReturnCode Platform_StartShell(STRING_PURE String* args);
void Platform_FontMake(struct FontDesc* desc, STRING_PURE String* fontName, UInt16 size, UInt16 style);
void Platform_FontFree(struct FontDesc* desc);
void Font_Make(struct FontDesc* desc, STRING_PURE String* fontName, UInt16 size, UInt16 style);
void Font_Free(struct FontDesc* desc);
struct Size2D Platform_TextMeasure(struct DrawTextArgs* args);
void Platform_SetBitmap(struct Bitmap* bmp);
struct Size2D Platform_TextDraw(struct DrawTextArgs* args, Int32 x, Int32 y, PackedCol col);
void Platform_ReleaseBitmap(void);
void Platform_SocketCreate(SocketPtr* socket);
ReturnCode Platform_SocketAvailable(SocketPtr socket, UInt32* available);
ReturnCode Platform_SocketSetBlocking(SocketPtr socket, bool blocking);
ReturnCode Platform_SocketGetError(SocketPtr socket, ReturnCode* result);
void Socket_Create(SocketPtr* socket);
ReturnCode Socket_Available(SocketPtr socket, UInt32* available);
ReturnCode Socket_SetBlocking(SocketPtr socket, bool blocking);
ReturnCode Socket_GetError(SocketPtr socket, ReturnCode* result);
ReturnCode Platform_SocketConnect(SocketPtr socket, STRING_PURE String* ip, Int32 port);
ReturnCode Platform_SocketRead(SocketPtr socket, UInt8* buffer, UInt32 count, UInt32* modified);
ReturnCode Platform_SocketWrite(SocketPtr socket, UInt8* buffer, UInt32 count, UInt32* modified);
ReturnCode Platform_SocketClose(SocketPtr socket);
ReturnCode Platform_SocketSelect(SocketPtr socket, Int32 selectMode, bool* success);
ReturnCode Socket_Connect(SocketPtr socket, STRING_PURE String* ip, Int32 port);
ReturnCode Socket_Read(SocketPtr socket, UInt8* buffer, UInt32 count, UInt32* modified);
ReturnCode Socket_Write(SocketPtr socket, UInt8* buffer, UInt32 count, UInt32* modified);
ReturnCode Socket_Close(SocketPtr socket);
ReturnCode Socket_Select(SocketPtr socket, Int32 selectMode, bool* success);
void Platform_HttpInit(void);
ReturnCode Platform_HttpMakeRequest(struct AsyncRequest* request, void** handle);
ReturnCode Platform_HttpGetRequestHeaders(struct AsyncRequest* request, void* handle, UInt32* size);
ReturnCode Platform_HttpGetRequestData(struct AsyncRequest* request, void* handle, void** data, UInt32 size, volatile Int32* progress);
ReturnCode Platform_HttpFreeRequest(void* handle);
ReturnCode Platform_HttpFree(void);
void Http_Init(void);
ReturnCode Http_MakeRequest(struct AsyncRequest* request, void** handle);
ReturnCode Http_GetRequestHeaders(struct AsyncRequest* request, void* handle, UInt32* size);
ReturnCode Http_GetRequestData(struct AsyncRequest* request, void* handle, void** data, UInt32 size, volatile Int32* progress);
ReturnCode Http_FreeRequest(void* handle);
ReturnCode Http_Free(void);
#define AUDIO_MAX_CHUNKS 5
struct AudioFormat { UInt8 Channels, BitsPerSample; Int32 SampleRate; };
#define AudioFormat_Eq(a, b) ((a)->Channels == (b)->Channels && (a)->BitsPerSample == (b)->BitsPerSample && (a)->SampleRate == (b)->SampleRate)
typedef Int32 AudioHandle;
void Platform_AudioInit(AudioHandle* handle, Int32 buffers);
void Platform_AudioFree(AudioHandle handle);
struct AudioFormat* Platform_AudioGetFormat(AudioHandle handle);
void Platform_AudioSetFormat(AudioHandle handle, struct AudioFormat* format);
void Platform_AudioPlayData(AudioHandle handle, Int32 idx, void* data, UInt32 dataSize);
bool Platform_AudioIsCompleted(AudioHandle handle, Int32 idx);
bool Platform_AudioIsFinished(AudioHandle handle);
void Audio_Init(AudioHandle* handle, Int32 buffers);
void Audio_Free(AudioHandle handle);
struct AudioFormat* Audio_GetFormat(AudioHandle handle);
void Audio_SetFormat(AudioHandle handle, struct AudioFormat* format);
void Audio_SetVolume(AudioHandle handle, Real32 volume);
void Audio_PlayData(AudioHandle handle, Int32 idx, void* data, UInt32 dataSize);
bool Audio_IsCompleted(AudioHandle handle, Int32 idx);
bool Audio_IsFinished(AudioHandle handle);
#endif

View File

@ -34,7 +34,7 @@ int main_imdct() {
void vorbis_test() {
void* file;
String oggPath = String_FromConst("audio/calm1.ogg");
Platform_FileOpen(&file, &oggPath);
File_Open(&file, &oggPath);
struct Stream oggBase;
Stream_FromFile(&oggBase, file, &oggPath);
struct Stream ogg;
@ -46,7 +46,7 @@ void vorbis_test() {
Vorbis_DecodeHeaders(&state);
Int32 size = 0, offset = 0;
Int16* chanData = Platform_MemAlloc(state.Channels * state.SampleRate * 1000, sizeof(Int16), "tmp data");
Int16* chanData = Mem_Alloc(state.Channels * state.SampleRate * 1000, sizeof(Int16), "tmp data");
for (int i = 0; i < 1000; i++) {
Vorbis_DecodeFrame(&state);
Int32 read = Vorbis_OutputFrame(&state, &chanData[offset]);
@ -73,7 +73,7 @@ void vorbis_test() {
unsigned res2 = waveOutPrepareHeader(handle, &header, sizeof(header));
unsigned res3 = waveOutWrite(handle, &header, sizeof(header));
Platform_ThreadSleep(20000);
Thread_Sleep(20000);
unsigned res4 = res3;
}
#endif
@ -86,38 +86,38 @@ int main(void) {
vorbis_test();
#endif
/*Platform_HttpInit();
/*Http_Init();
AsyncRequest req = { 0 };
String url = String_FromEmptyArray(req.URL);
String_AppendConst(&url, "http://static.classicube.net/skins/UnknownShadow200.png");
void* reqHandle = NULL;
ReturnCode ret = Platform_HttpMakeRequest(&req, &reqHandle);
ReturnCode ret2 = Platform_HttpFreeRequest(reqHandle);
ReturnCode ret3 = Platform_HttpFree();*/
ReturnCode ret = Http_MakeRequest(&req, &reqHandle);
ReturnCode ret2 = Http_FreeRequest(reqHandle);
ReturnCode ret3 = Http_Free();*/
String maps = String_FromConst("maps");
if (!Platform_DirectoryExists(&maps)) {
ReturnCode result = Platform_DirectoryCreate(&maps);
if (!Directory_Exists(&maps)) {
ReturnCode result = Directory_Create(&maps);
ErrorHandler_CheckOrFail(result, "Program - creating maps directory");
}
String texPacks = String_FromConst("texpacks");
if (!Platform_DirectoryExists(&texPacks)) {
ReturnCode result = Platform_DirectoryCreate(&texPacks);
if (!Directory_Exists(&texPacks)) {
ReturnCode result = Directory_Create(&texPacks);
ErrorHandler_CheckOrFail(result, "Program - creating texpacks directory");
}
String texCache = String_FromConst("texturecache");
if (!Platform_DirectoryExists(&texCache)) {
ReturnCode result = Platform_DirectoryCreate(&texCache);
if (!Directory_Exists(&texCache)) {
ReturnCode result = Directory_Create(&texCache);
ErrorHandler_CheckOrFail(result, "Program - creating texturecache directory");
}
UChar defPathBuffer[String_BufferSize(STRING_SIZE)];
String defPath = String_InitAndClearArray(defPathBuffer);
String_Format1(&defPath, "texpacks%rdefault.zip", &Platform_DirectorySeparator);
String_Format1(&defPath, "texpacks%rdefault.zip", &Directory_Separator);
if (!Platform_FileExists(&defPath)) {
if (!File_Exists(&defPath)) {
ErrorHandler_ShowDialog("Missing file", "default.zip missing, try running launcher first");
Platform_Exit(1);
return 1;
@ -230,7 +230,7 @@ int main_test(int argc, char* argv[]) {
void* file;
String path = String_FromConstant("H:\\PortableApps\\GitPortable\\App\\Git\\ClassicalSharp\\output\\release\\texpacks\\skybox.png");
ReturnCode openCode = Platform_FileOpen(&file, &path);
ReturnCode openCode = File_Open(&file, &path);
Stream fileStream;
Stream_FromFile(&fileStream, file, &path);
Bitmap bmp;
@ -255,7 +255,7 @@ int main_test(int argc, char* argv[]) {
void* file2;
String path2 = String_FromConstant("H:\\PortableApps\\GitPortable\\App\\Git\\ClassicalSharp\\output\\release\\texpacks\\skybox8.bmp");
openCode = Platform_FileCreate(&file2, &path2);
openCode = File_Create(&file2, &path2);
Stream fileStream2;
Stream_FromFile(&fileStream2, file2, &path2);
Stream_Write(&fileStream2, &bmpfileheader, sizeof(bmpfileheader));
@ -267,7 +267,7 @@ int main_test(int argc, char* argv[]) {
/*void* file;
String path = String_FromConstant("H:\\PortableApps\\GitPortable\\App\\Git\\ClassicalSharp\\output\\release\\texpacks\\default.zip");
ReturnCode openCode = Platform_FileOpen(&file, &path);
ReturnCode openCode = File_Open(&file, &path);
Stream fileStream;
Stream_FromFile(&fileStream, file, &path);
ZipState state;
@ -277,7 +277,7 @@ int main_test(int argc, char* argv[]) {
/*void* file;
String path = String_FromConst("H:\\PortableApps\\GitPortable\\App\\Git\\ClassicalSharp\\src\\x64\\Release\\canyon.lvl");
ReturnCode openCode = Platform_FileOpen(&file, &path);
ReturnCode openCode = File_Open(&file, &path);
Stream fileStream;
Stream_FromFile(&fileStream, file, &path);
Lvl_Load(&fileStream);
@ -285,14 +285,14 @@ int main_test(int argc, char* argv[]) {
/*void* file;
String path = String_FromConstant("H:\\PortableApps\\GitPortable\\App\\Git\\\ClassicalSharp\\src\\Debug\\gunzip.c.gz");
ReturnCode openCode = Platform_FileOpen(&file, &path);
ReturnCode openCode = File_Open(&file, &path);
Stream fileStream;
Stream_FromFile(&fileStream, file, &path);
GZipHeader gzip;
GZipHeader_Init(&gzip);
while (!gzip.Done) { GZipHeader_Read(&fileStream, &gzip); }
UInt32 pos = Platform_FilePosition(file);
UInt32 pos = File_Position(file);
InflateState deflate;
Inflate_Init(&deflate, &fileStream);
@ -307,7 +307,7 @@ int main_test(int argc, char* argv[]) {
Inflate_Process(&deflate);
String path2 = String_FromConstant("H:\\PortableApps\\GitPortable\\App\\Git\\ClassicalSharp\\src\\x64\\Debug\\ffff.c");
openCode = Platform_FileCreate(&file, &path2);
openCode = File_Create(&file, &path2);
Stream_FromFile(&fileStream, file, &path);
UInt32 written;
fileStream.Write(&fileStream, out, 56000 - deflate.AvailOut, &written);
@ -325,7 +325,7 @@ int main_test(int argc, char* argv[]) {
Gfx_ClearColour(PackedCol_Create3(RGB, RGB, RGB));
RGB++;
Window_ProcessEvents();
Platform_ThreadSleep(100);
Thread_Sleep(100);
Gfx_BeginFrame();
Gfx_Clear();
Gfx_EndFrame();

View File

@ -128,7 +128,7 @@ static void InventoryScreen_ContextRecreated(void* obj) {
static void InventoryScreen_Init(struct GuiElem* elem) {
struct InventoryScreen* screen = (struct InventoryScreen*)elem;
Platform_FontMake(&screen->Font, &Game_FontName, 16, FONT_STYLE_NORMAL);
Font_Make(&screen->Font, &Game_FontName, 16, FONT_STYLE_NORMAL);
TableWidget_Create(&screen->Table);
screen->Table.Font = screen->Font;
@ -159,7 +159,7 @@ static void InventoryScreen_OnResize(struct GuiElem* elem) {
static void InventoryScreen_Free(struct GuiElem* elem) {
struct InventoryScreen* screen = (struct InventoryScreen*)elem;
Platform_FontFree(&screen->Font);
Font_Free(&screen->Font);
Elem_TryFree(&screen->Table);
Key_KeyRepeat = false;
@ -235,7 +235,7 @@ static bool InventoryScreen_HandlesMouseScroll(struct GuiElem* elem, Real32 delt
struct Screen* InventoryScreen_MakeInstance(void) {
struct InventoryScreen* screen = &InventoryScreen_Instance;
Platform_MemSet(screen, 0, sizeof(struct InventoryScreen));
Mem_Set(screen, 0, sizeof(struct InventoryScreen));
screen->VTABLE = &InventoryScreen_VTABLE;
Screen_Reset((struct Screen*)screen);
screen->HandlesAllInput = true;
@ -385,7 +385,7 @@ static void StatusScreen_ContextRecreated(void* obj) {
static void StatusScreen_Init(struct GuiElem* elem) {
struct StatusScreen* screen = (struct StatusScreen*)elem;
Platform_FontMake(&screen->Font, &Game_FontName, 16, FONT_STYLE_NORMAL);
Font_Make(&screen->Font, &Game_FontName, 16, FONT_STYLE_NORMAL);
StatusScreen_ContextRecreated(screen);
Event_RegisterVoid(&ChatEvents_FontChanged, screen, StatusScreen_FontChanged);
@ -411,7 +411,7 @@ static void StatusScreen_Render(struct GuiElem* elem, Real64 delta) {
static void StatusScreen_Free(struct GuiElem* elem) {
struct StatusScreen* screen = (struct StatusScreen*)elem;
Platform_FontFree(&screen->Font);
Font_Free(&screen->Font);
StatusScreen_ContextLost(screen);
Event_UnregisterVoid(&ChatEvents_FontChanged, screen, StatusScreen_FontChanged);
@ -421,7 +421,7 @@ static void StatusScreen_Free(struct GuiElem* elem) {
struct Screen* StatusScreen_MakeInstance(void) {
struct StatusScreen* screen = &StatusScreen_Instance;
Platform_MemSet(screen, 0, sizeof(struct StatusScreen));
Mem_Set(screen, 0, sizeof(struct StatusScreen));
screen->VTABLE = &StatusScreen_VTABLE;
Screen_Reset((struct Screen*)screen);
@ -580,7 +580,7 @@ static void LoadingScreen_Render(struct GuiElem* elem, Real64 delta) {
static void LoadingScreen_Free(struct GuiElem* elem) {
struct LoadingScreen* screen = (struct LoadingScreen*)elem;
Platform_FontFree(&screen->Font);
Font_Free(&screen->Font);
LoadingScreen_ContextLost(screen);
Event_UnregisterReal(&WorldEvents_Loading, screen, LoadingScreen_MapLoading);
@ -589,7 +589,7 @@ static void LoadingScreen_Free(struct GuiElem* elem) {
}
static void LoadingScreen_Make(struct LoadingScreen* screen, struct GuiElementVTABLE* vtable, STRING_PURE String* title, STRING_PURE String* message) {
Platform_MemSet(screen, 0, sizeof(struct LoadingScreen));
Mem_Set(screen, 0, sizeof(struct LoadingScreen));
screen->VTABLE = vtable;
Screen_Reset((struct Screen*)screen);
screen->HandlesAllInput = true;
@ -612,7 +612,7 @@ static void LoadingScreen_Make(struct LoadingScreen* screen, struct GuiElementVT
String messageScreen = String_InitAndClearArray(screen->MessageBuffer);
String_AppendString(&messageScreen, message);
Platform_FontMake(&screen->Font, &Game_FontName, 16, FONT_STYLE_NORMAL);
Font_Make(&screen->Font, &Game_FontName, 16, FONT_STYLE_NORMAL);
screen->BlocksWorld = true;
screen->RenderHUDOver = true;
}
@ -638,12 +638,12 @@ static void GeneratingScreen_Init(struct GuiElem* elem) {
void* threadHandle;
if (Gen_Vanilla) {
threadHandle = Platform_ThreadStart(&NotchyGen_Generate);
threadHandle = Thread_Start(&NotchyGen_Generate);
} else {
threadHandle = Platform_ThreadStart(&FlatgrassGen_Generate);
threadHandle = Thread_Start(&FlatgrassGen_Generate);
}
/* don't leak thread handle here */
Platform_ThreadFreeHandle(threadHandle);
Thread_FreeHandle(threadHandle);
}
static void GeneratingScreen_EndGeneration(void) {
@ -651,7 +651,7 @@ static void GeneratingScreen_EndGeneration(void) {
Gen_Done = false;
if (!Gen_Blocks) {
Chat_AddRaw(tmpStr, "&cFailed to generate the map."); return;
Chat_AddRaw("&cFailed to generate the map."); return;
}
World_BlocksSize = Gen_Width * Gen_Height * Gen_Length;
@ -1101,12 +1101,12 @@ static void ChatScreen_Init(struct GuiElem* elem) {
Int32 fontSize = (Int32)(8 * Game_GetChatScale());
Math_Clamp(fontSize, 8, 60);
Platform_FontMake(&screen->ChatFont, &Game_FontName, fontSize, FONT_STYLE_NORMAL);
Platform_FontMake(&screen->ChatUrlFont, &Game_FontName, fontSize, FONT_STYLE_UNDERLINE);
Font_Make(&screen->ChatFont, &Game_FontName, fontSize, FONT_STYLE_NORMAL);
Font_Make(&screen->ChatUrlFont, &Game_FontName, fontSize, FONT_STYLE_UNDERLINE);
fontSize = (Int32)(16 * Game_GetChatScale());
Math_Clamp(fontSize, 8, 60);
Platform_FontMake(&screen->AnnouncementFont, &Game_FontName, fontSize, FONT_STYLE_NORMAL);
Font_Make(&screen->AnnouncementFont, &Game_FontName, fontSize, FONT_STYLE_NORMAL);
ChatScreen_ContextRecreated(elem);
Event_RegisterChat(&ChatEvents_ChatReceived, screen, ChatScreen_ChatReceived);
@ -1132,7 +1132,7 @@ static void ChatScreen_Render(struct GuiElem* elem, Real64 delta) {
Texture_Render(&tex);
}
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
if (screen->HandlesAllInput) {
Elem_Render(&screen->Chat, delta);
} else {
@ -1165,9 +1165,9 @@ static void ChatScreen_Render(struct GuiElem* elem, Real64 delta) {
static void ChatScreen_Free(struct GuiElem* elem) {
struct ChatScreen* screen = (struct ChatScreen*)elem;
ChatScreen_ContextLost(elem);
Platform_FontFree(&screen->ChatFont);
Platform_FontFree(&screen->ChatUrlFont);
Platform_FontFree(&screen->AnnouncementFont);
Font_Free(&screen->ChatFont);
Font_Free(&screen->ChatUrlFont);
Font_Free(&screen->AnnouncementFont);
Event_UnregisterChat(&ChatEvents_ChatReceived, screen, ChatScreen_ChatReceived);
Event_UnregisterVoid(&ChatEvents_FontChanged, screen, ChatScreen_FontChanged);
@ -1178,7 +1178,7 @@ static void ChatScreen_Free(struct GuiElem* elem) {
struct Screen* ChatScreen_MakeInstance(void) {
struct ChatScreen* screen = &ChatScreen_Instance;
Platform_MemSet(screen, 0, sizeof(struct ChatScreen));
Mem_Set(screen, 0, sizeof(struct ChatScreen));
screen->VTABLE = &ChatScreen_VTABLE;
Screen_Reset((struct Screen*)screen);
@ -1314,7 +1314,7 @@ static bool HUDScreen_HandlesMouseDown(struct GuiElem* elem, Int32 x, Int32 y, M
static void HUDScreen_Init(struct GuiElem* elem) {
struct HUDScreen* screen = (struct HUDScreen*)elem;
UInt16 size = Drawer2D_UseBitmappedChat ? 16 : 11;
Platform_FontMake(&screen->PlayerFont, &Game_FontName, size, FONT_STYLE_NORMAL);
Font_Make(&screen->PlayerFont, &Game_FontName, size, FONT_STYLE_NORMAL);
HotbarWidget_Create(&screen->Hotbar);
Elem_Init(&screen->Hotbar);
@ -1365,7 +1365,7 @@ static void HUDScreen_Render(struct GuiElem* elem, Real64 delta) {
static void HUDScreen_Free(struct GuiElem* elem) {
struct HUDScreen* screen = (struct HUDScreen*)elem;
Platform_FontFree(&screen->PlayerFont);
Font_Free(&screen->PlayerFont);
Elem_TryFree(screen->Chat);
HUDScreen_ContextLost(screen);
@ -1375,7 +1375,7 @@ static void HUDScreen_Free(struct GuiElem* elem) {
struct Screen* HUDScreen_MakeInstance(void) {
struct HUDScreen* screen = &HUDScreen_Instance;
Platform_MemSet(screen, 0, sizeof(struct HUDScreen));
Mem_Set(screen, 0, sizeof(struct HUDScreen));
screen->VTABLE = &HUDScreenVTABLE;
Screen_Reset((struct Screen*)screen);
@ -1422,7 +1422,7 @@ struct DisconnectScreen DisconnectScreen_Instance;
#define DISCONNECT_DELAY_MS 5000
static void DisconnectScreen_ReconnectMessage(struct DisconnectScreen* screen, STRING_TRANSIENT String* msg) {
if (screen->CanReconnect) {
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
Int32 elapsedMS = (Int32)(DateTime_TotalMs(&now) - screen->InitTime);
Int32 secsLeft = (DISCONNECT_DELAY_MS - elapsedMS) / DATETIME_MILLISECS_PER_SECOND;
@ -1447,7 +1447,7 @@ static void DisconnectScreen_Redraw(struct DisconnectScreen* screen, Real64 delt
}
static void DisconnectScreen_UpdateDelayLeft(struct DisconnectScreen* screen, Real64 delta) {
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
Int32 elapsedMS = (Int32)(DateTime_TotalMs(&now) - screen->InitTime);
Int32 secsLeft = (DISCONNECT_DELAY_MS - elapsedMS) / DATETIME_MILLISECS_PER_SECOND;
if (secsLeft < 0) secsLeft = 0;
@ -1475,7 +1475,7 @@ static void DisconnectScreen_ContextLost(void* obj) {
static void DisconnectScreen_ContextRecreated(void* obj) {
struct DisconnectScreen* screen = (struct DisconnectScreen*)obj;
if (Gfx_LostContext) return;
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
screen->ClearTime = DateTime_TotalMs(&now) + 500;
String title = String_FromRawArray(screen->TitleBuffer);
@ -1502,7 +1502,7 @@ static void DisconnectScreen_Init(struct GuiElem* elem) {
Event_RegisterVoid(&GfxEvents_ContextRecreated, screen, DisconnectScreen_ContextRecreated);
DisconnectScreen_ContextRecreated(screen);
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
screen->InitTime = DateTime_TotalMs(&now);
screen->LastSecsLeft = DISCONNECT_DELAY_MS / DATETIME_MILLISECS_PER_SECOND;
}
@ -1515,7 +1515,7 @@ static void DisconnectScreen_Render(struct GuiElem* elem, Real64 delta) {
/* NOTE: We need to make sure that both the front and back buffers have
definitely been drawn over, so we redraw the background multiple times. */
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
if (DateTime_TotalMs(&now) < screen->ClearTime) {
DisconnectScreen_Redraw(screen, delta);
}
@ -1528,8 +1528,8 @@ static void DisconnectScreen_Free(struct GuiElem* elem) {
Event_UnregisterVoid(&GfxEvents_ContextRecreated, screen, DisconnectScreen_ContextRecreated);
DisconnectScreen_ContextLost(screen);
Platform_FontFree(&screen->TitleFont);
Platform_FontFree(&screen->MessageFont);
Font_Free(&screen->TitleFont);
Font_Free(&screen->MessageFont);
}
static void DisconnectScreen_OnResize(struct GuiElem* elem) {
@ -1537,7 +1537,7 @@ static void DisconnectScreen_OnResize(struct GuiElem* elem) {
Widget_Reposition(&screen->Title);
Widget_Reposition(&screen->Message);
Widget_Reposition(&screen->Reconnect);
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
screen->ClearTime = DateTime_TotalMs(&now) + 500;
}
@ -1574,7 +1574,7 @@ static bool DisconnectScreen_HandlesMouseUp(struct GuiElem* elem, Int32 x, Int32
struct Screen* DisconnectScreen_MakeInstance(STRING_PURE String* title, STRING_PURE String* message) {
struct DisconnectScreen* screen = &DisconnectScreen_Instance;
Platform_MemSet(screen, 0, sizeof(struct DisconnectScreen));
Mem_Set(screen, 0, sizeof(struct DisconnectScreen));
screen->VTABLE = &DisconnectScreen_VTABLE;
Screen_Reset((struct Screen*)screen);
screen->HandlesAllInput = true;
@ -1592,8 +1592,8 @@ struct Screen* DisconnectScreen_MakeInstance(STRING_PURE String* title, STRING_P
String ban = String_FromConst("Banned ");
screen->CanReconnect = !(String_StartsWith(&reason, &kick) || String_StartsWith(&reason, &ban));
Platform_FontMake(&screen->TitleFont, &Game_FontName, 16, FONT_STYLE_BOLD);
Platform_FontMake(&screen->MessageFont, &Game_FontName, 16, FONT_STYLE_NORMAL);
Font_Make(&screen->TitleFont, &Game_FontName, 16, FONT_STYLE_BOLD);
Font_Make(&screen->MessageFont, &Game_FontName, 16, FONT_STYLE_NORMAL);
screen->BlocksWorld = true;
screen->HidesHUD = true;

View File

@ -94,7 +94,7 @@ struct PingEntry {
struct PingEntry PingList_Entries[10];
UInt16 PingList_Set(Int32 i, UInt16 prev) {
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
PingList_Entries[i].Data = (UInt16)(prev + 1);
PingList_Entries[i].TimeSent = DateTime_TotalMs(&now);
PingList_Entries[i].TimeReceived = 0;
@ -122,7 +122,7 @@ void PingList_Update(UInt16 data) {
Int32 i;
for (i = 0; i < Array_Elems(PingList_Entries); i++) {
if (PingList_Entries[i].Data != data) continue;
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
PingList_Entries[i].TimeReceived = DateTime_TotalMs(&now);
return;
}
@ -161,7 +161,7 @@ static void SPConnection_BeginConnect(void) {
/* For when user drops a map file onto ClassicalSharp.exe */
String path = Game_Username;
if (String_IndexOf(&path, Platform_DirectorySeparator, 0) >= 0 && Platform_FileExists(&path)) {
if (String_IndexOf(&path, Directory_Separator, 0) >= 0 && File_Exists(&path)) {
LoadLevelScreen_LoadMap(&path);
Gui_ReplaceActive(NULL);
return;
@ -285,7 +285,7 @@ static void MPConnection_FinishConnect(void) {
Handlers_Reset();
Classic_WriteLogin(&net_writeStream, &Game_Username, &Game_Mppass);
Net_SendPacket();
Platform_CurrentUTCTime(&net_lastPacket);
DateTime_CurrentUTC(&net_lastPacket);
}
static void MPConnection_FailConnect(ReturnCode result) {
@ -308,21 +308,21 @@ static void MPConnection_FailConnect(ReturnCode result) {
static void MPConnection_TickConnect(void) {
bool poll_error = false;
Platform_SocketSelect(net_socket, SOCKET_SELECT_ERROR, &poll_error);
Socket_Select(net_socket, SOCKET_SELECT_ERROR, &poll_error);
if (poll_error) {
ReturnCode err = 0; Platform_SocketGetError(net_socket, &err);
ReturnCode err = 0; Socket_GetError(net_socket, &err);
MPConnection_FailConnect(err);
return;
}
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
Int64 nowMS = DateTime_TotalMs(&now);
bool poll_write = false;
Platform_SocketSelect(net_socket, SOCKET_SELECT_WRITE, &poll_write);
Socket_Select(net_socket, SOCKET_SELECT_WRITE, &poll_write);
if (poll_write) {
Platform_SocketSetBlocking(net_socket, true);
Socket_SetBlocking(net_socket, true);
MPConnection_FinishConnect();
} else if (nowMS > net_connectTimeout) {
MPConnection_FailConnect(0);
@ -333,16 +333,16 @@ static void MPConnection_TickConnect(void) {
}
static void MPConnection_BeginConnect(void) {
Platform_SocketCreate(&net_socket);
Socket_Create(&net_socket);
Event_RegisterBlock(&UserEvents_BlockChanged, NULL, MPConnection_BlockChanged);
ServerConnection_Disconnected = false;
Platform_SocketSetBlocking(net_socket, false);
Socket_SetBlocking(net_socket, false);
net_connecting = true;
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
net_connectTimeout = DateTime_TotalMs(&now) + NET_TIMEOUT_MS;
ReturnCode result = Platform_SocketConnect(net_socket, &Game_IPAddress, Game_Port);
ReturnCode result = Socket_Connect(net_socket, &Game_IPAddress, Game_Port);
if (result == 0) return;
if (result != ReturnCode_SocketInProgess && result != ReturnCode_SocketWouldBlock) {
MPConnection_FailConnect(result);
@ -380,8 +380,8 @@ static void MPConnection_CheckDisconnection(Real64 delta) {
net_discAccumulator = 0.0;
UInt32 available = 0; bool poll_success = false;
ReturnCode availResult = Platform_SocketAvailable(net_socket, &available);
ReturnCode selectResult = Platform_SocketSelect(net_socket, SOCKET_SELECT_READ, &poll_success);
ReturnCode availResult = Socket_Available(net_socket, &available);
ReturnCode selectResult = Socket_Select(net_socket, SOCKET_SELECT_READ, &poll_success);
if (net_writeFailed || availResult != 0 || selectResult != 0 || (available == 0 && poll_success)) {
String title = String_FromConst("Disconnected!");
@ -394,18 +394,18 @@ static void MPConnection_Tick(struct ScheduledTask* task) {
if (ServerConnection_Disconnected) return;
if (net_connecting) { MPConnection_TickConnect(); return; }
DateTime now; Platform_CurrentUTCTime(&now);
DateTime now; DateTime_CurrentUTC(&now);
if (DateTime_MsBetween(&net_lastPacket, &now) >= 30 * 1000) {
MPConnection_CheckDisconnection(task->Interval);
}
if (ServerConnection_Disconnected) return;
UInt32 modified = 0;
ReturnCode recvResult = Platform_SocketAvailable(net_socket, &modified);
ReturnCode recvResult = Socket_Available(net_socket, &modified);
if (recvResult == 0 && modified > 0) {
/* NOTE: Always using a read call that is a multiple of 4096 (appears to?) improve read performance */
UInt8* src = net_readBuffer + net_readStream.Meta.Mem.Left;
recvResult = Platform_SocketRead(net_socket, src, 4096 * 4, &modified);
recvResult = Socket_Read(net_socket, src, 4096 * 4, &modified);
net_readStream.Meta.Mem.Left += modified;
net_readStream.Meta.Mem.Length += modified;
}
@ -441,7 +441,7 @@ static void MPConnection_Tick(struct ScheduledTask* task) {
Stream_Skip(&net_readStream, 1); /* remove opcode */
net_lastOpcode = opcode;
Net_Handler handler = Net_Handlers[opcode];
Platform_CurrentUTCTime(&net_lastPacket);
DateTime_CurrentUTC(&net_lastPacket);
if (!handler) { ErrorHandler_Fail("Unsupported opcode"); }
handler(&net_readStream);
@ -479,7 +479,7 @@ void Net_SendPacket(void) {
UInt32 count = (UInt32)(net_writeStream.Meta.Mem.Cur - net_writeStream.Meta.Mem.Base), modified = 0;
while (count > 0) {
ReturnCode result = Platform_SocketWrite(net_socket, net_writeBuffer, count, &modified);
ReturnCode result = Socket_Write(net_socket, net_writeBuffer, count, &modified);
if (result != 0 || modified == 0) { net_writeFailed = true; break; }
count -= modified;
}
@ -535,7 +535,7 @@ static void ServerConnection_Free(void) {
} else {
if (ServerConnection_Disconnected) return;
Event_UnregisterBlock(&UserEvents_BlockChanged, NULL, MPConnection_BlockChanged);
Platform_SocketClose(net_socket);
Socket_Close(net_socket);
ServerConnection_Disconnected = true;
}
}

View File

@ -23,7 +23,7 @@ ReturnCode ReturnCode_SocketWouldBlock = EWOULDBLOCK;
#error "You're not using BSD sockets, define the interface in Socket.c"
#endif
void Platform_SocketCreate(SocketPtr* socketResult) {
void Socket_Create(SocketPtr* socketResult) {
*socketResult = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (*socketResult == -1) {
ErrorHandler_FailWithCode(Socket__Error(), "Failed to create socket");
@ -38,20 +38,20 @@ ReturnCode Platform_ioctl(SocketPtr socket, UInt32 cmd, Int32* data) {
#endif
}
ReturnCode Platform_SocketAvailable(SocketPtr socket, UInt32* available) {
ReturnCode Socket_Available(SocketPtr socket, UInt32* available) {
return Platform_ioctl(socket, FIONREAD, available);
}
ReturnCode Platform_SocketSetBlocking(SocketPtr socket, bool blocking) {
ReturnCode Socket_SetBlocking(SocketPtr socket, bool blocking) {
Int32 blocking_raw = blocking ? 0 : -1;
return Platform_ioctl(socket, FIONBIO, &blocking_raw);
}
ReturnCode Platform_SocketGetError(SocketPtr socket, ReturnCode* result) {
ReturnCode Socket_GetError(SocketPtr socket, ReturnCode* result) {
Int32 resultSize = sizeof(ReturnCode);
return getsockopt(socket, SOL_SOCKET, SO_ERROR, result, &resultSize);
}
ReturnCode Platform_SocketConnect(SocketPtr socket, STRING_PURE String* ip, Int32 port) {
ReturnCode Socket_Connect(SocketPtr socket, STRING_PURE String* ip, Int32 port) {
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ip->buffer);
@ -61,19 +61,19 @@ ReturnCode Platform_SocketConnect(SocketPtr socket, STRING_PURE String* ip, Int3
return result == -1 ? Socket__Error() : 0;
}
ReturnCode Platform_SocketRead(SocketPtr socket, UInt8* buffer, UInt32 count, UInt32* modified) {
ReturnCode Socket_Read(SocketPtr socket, UInt8* buffer, UInt32 count, UInt32* modified) {
Int32 recvCount = recv(socket, buffer, count, 0);
if (recvCount != -1) { *modified = recvCount; return 0; }
*modified = 0; return Socket__Error();
}
ReturnCode Platform_SocketWrite(SocketPtr socket, UInt8* buffer, UInt32 count, UInt32* modified) {
ReturnCode Socket_Write(SocketPtr socket, UInt8* buffer, UInt32 count, UInt32* modified) {
Int32 sentCount = send(socket, buffer, count, 0);
if (sentCount != -1) { *modified = sentCount; return 0; }
*modified = 0; return Socket__Error();
}
ReturnCode Platform_SocketClose(SocketPtr socket) {
ReturnCode Socket_Close(SocketPtr socket) {
ReturnCode result = 0;
#if CC_BUILD_WIN
ReturnCode result1 = shutdown(socket, SD_BOTH);
@ -91,7 +91,7 @@ ReturnCode Platform_SocketClose(SocketPtr socket) {
return result;
}
ReturnCode Platform_SocketSelect(SocketPtr socket, Int32 selectMode, bool* success) {
ReturnCode Socket_Select(SocketPtr socket, Int32 selectMode, bool* success) {
fd_set set;
FD_ZERO(&set);
FD_SET(socket, &set);

View File

@ -108,24 +108,24 @@ void Stream_Init(struct Stream* stream, STRING_PURE String* name) {
*-------------------------------------------------------FileStream--------------------------------------------------------*
*#########################################################################################################################*/
static ReturnCode Stream_FileRead(struct Stream* stream, UInt8* data, UInt32 count, UInt32* modified) {
return Platform_FileRead(stream->Meta.File, data, count, modified);
return File_Read(stream->Meta.File, data, count, modified);
}
static ReturnCode Stream_FileWrite(struct Stream* stream, UInt8* data, UInt32 count, UInt32* modified) {
return Platform_FileWrite(stream->Meta.File, data, count, modified);
return File_Write(stream->Meta.File, data, count, modified);
}
static ReturnCode Stream_FileClose(struct Stream* stream) {
ReturnCode code = Platform_FileClose(stream->Meta.File);
ReturnCode code = File_Close(stream->Meta.File);
stream->Meta.File = NULL;
return code;
}
static ReturnCode Stream_FileSeek(struct Stream* stream, Int32 offset, Int32 seekType) {
return Platform_FileSeek(stream->Meta.File, offset, seekType);
return File_Seek(stream->Meta.File, offset, seekType);
}
static ReturnCode Stream_FilePosition(struct Stream* stream, UInt32* position) {
return Platform_FilePosition(stream->Meta.File, position);
return File_Position(stream->Meta.File, position);
}
static ReturnCode Stream_FileLength(struct Stream* stream, UInt32* length) {
return Platform_FileLength(stream->Meta.File, length);
return File_Length(stream->Meta.File, length);
}
void Stream_FromFile(struct Stream* stream, void* file, STRING_PURE String* name) {
@ -176,7 +176,7 @@ void Stream_ReadonlyPortion(struct Stream* stream, struct Stream* source, UInt32
*#########################################################################################################################*/
static ReturnCode Stream_MemoryRead(struct Stream* stream, UInt8* data, UInt32 count, UInt32* modified) {
count = min(count, stream->Meta.Mem.Left);
if (count) { Platform_MemCpy(data, stream->Meta.Mem.Cur, count); }
if (count) { Mem_Copy(data, stream->Meta.Mem.Cur, count); }
stream->Meta.Mem.Cur += count;
stream->Meta.Mem.Left -= count;
@ -186,7 +186,7 @@ static ReturnCode Stream_MemoryRead(struct Stream* stream, UInt8* data, UInt32 c
static ReturnCode Stream_MemoryWrite(struct Stream* stream, UInt8* data, UInt32 count, UInt32* modified) {
count = min(count, stream->Meta.Mem.Left);
if (count) { Platform_MemCpy(stream->Meta.Mem.Cur, data, count); }
if (count) { Mem_Copy(stream->Meta.Mem.Cur, data, count); }
stream->Meta.Mem.Cur += count;
stream->Meta.Mem.Left -= count;

View File

@ -695,10 +695,10 @@ void StringsBuffer_Init(StringsBuffer* buffer) {
void StringsBuffer_Free(StringsBuffer* buffer) {
if (buffer->TextBuffer != buffer->DefaultBuffer) {
Platform_MemFree(&buffer->TextBuffer);
Mem_Free(&buffer->TextBuffer);
}
if (buffer->FlagsBuffer != buffer->DefaultFlags) {
Platform_MemFree(&buffer->FlagsBuffer);
Mem_Free(&buffer->FlagsBuffer);
}
StringsBuffer_Init(buffer);
}
@ -725,10 +725,10 @@ void StringsBuffer_Resize(void** buffer, UInt32* elems, UInt32 elemSize, UInt32
UInt32 curElems = *elems;
if (curElems <= defElems) {
dst = Platform_MemAlloc(curElems + expandElems, elemSize, "StringsBuffer");
Platform_MemCpy(dst, cur, curElems * elemSize);
dst = Mem_Alloc(curElems + expandElems, elemSize, "StringsBuffer");
Mem_Copy(dst, cur, curElems * elemSize);
} else {
dst = Platform_MemRealloc(cur, curElems + expandElems, elemSize, "resizing StringsBuffer");
dst = Mem_Realloc(cur, curElems + expandElems, elemSize, "resizing StringsBuffer");
}
*buffer = dst;
@ -756,7 +756,7 @@ void StringsBuffer_Add(StringsBuffer* buffer, STRING_PURE String* text) {
}
if (text->length) {
Platform_MemCpy(&buffer->TextBuffer[textOffset], text->buffer, text->length);
Mem_Copy(&buffer->TextBuffer[textOffset], text->buffer, text->length);
}
buffer->FlagsBuffer[buffer->Count] = text->length | (textOffset << STRINGSBUFFER_LEN_SHIFT);

View File

@ -28,7 +28,7 @@ GfxResourceID Atlas2D_LoadTile(TextureLoc texLoc) {
if (size > 64) {
Bitmap_Allocate(&tile, size, size);
GfxResourceID texId = Atlas2D_LoadTextureElement_Raw(texLoc, &tile);
Platform_MemFree(&tile.Scan0);
Mem_Free(&tile.Scan0);
return texId;
} else {
UInt8 scan0[Bitmap_DataSize(64, 64)];
@ -38,7 +38,7 @@ GfxResourceID Atlas2D_LoadTile(TextureLoc texLoc) {
}
void Atlas2D_Free(void) {
Platform_MemFree(&Atlas2D_Bitmap.Scan0);
Mem_Free(&Atlas2D_Bitmap.Scan0);
}
@ -71,7 +71,7 @@ static void Atlas1D_Make1DTexture(Int32 i, Int32 atlas1DHeight, Int32* index) {
}
Atlas1D_TexIds[i] = Gfx_CreateTexture(&atlas1D, true, Gfx_Mipmaps);
Platform_MemFree(&atlas1D.Scan0);
Mem_Free(&atlas1D.Scan0);
}
static void Atlas1D_Convert2DTo1D(Int32 atlasesCount, Int32 atlas1DHeight) {

View File

@ -187,10 +187,10 @@ static void EntryList_Load(struct EntryList* list) {
String filename = String_FromRawArray(list->FileBuffer);
UChar pathBuffer[String_BufferSize(FILENAME_SIZE)];
String path = String_InitAndClearArray(pathBuffer);
String_Format3(&path, "%s%r%s", &folder, &Platform_DirectorySeparator, &filename);
String_Format3(&path, "%s%r%s", &folder, &Directory_Separator, &filename);
void* file;
ReturnCode result = Platform_FileOpen(&file, &path);
ReturnCode result = File_Open(&file, &path);
if (result == ReturnCode_FileNotFound) return;
/* TODO: Should we just log failure to save? */
ErrorHandler_CheckOrFail(result, "EntryList_Load - open file");
@ -217,15 +217,15 @@ static void EntryList_Save(struct EntryList* list) {
String filename = String_FromRawArray(list->FileBuffer);
UChar pathBuffer[String_BufferSize(FILENAME_SIZE)];
String path = String_InitAndClearArray(pathBuffer);
String_Format3(&path, "%s%r%s", &folder, &Platform_DirectorySeparator, &filename);
String_Format3(&path, "%s%r%s", &folder, &Directory_Separator, &filename);
if (!Platform_DirectoryExists(&folder)) {
ReturnCode dirResult = Platform_DirectoryCreate(&folder);
if (!Directory_Exists(&folder)) {
ReturnCode dirResult = Directory_Create(&folder);
ErrorHandler_CheckOrFail(dirResult, "EntryList_Save - create directory");
}
void* file;
ReturnCode result = Platform_FileCreate(&file, &path);
ReturnCode result = File_Create(&file, &path);
/* TODO: Should we just log failure to save? */
ErrorHandler_CheckOrFail(result, "EntryList_Save - open file");
struct Stream stream; Stream_FromFile(&stream, file, &path);
@ -297,19 +297,19 @@ void TextureCache_Deny(STRING_PURE String* url) { EntryList_Add(&cache_denied,
static void TextureCache_MakePath(STRING_TRANSIENT String* path, STRING_PURE String* url) {
String crc32; TexCache_Crc32(url);
String_Format2(path, TEXCACHE_FOLDER "%r%s", &Platform_DirectorySeparator, &crc32);
String_Format2(path, TEXCACHE_FOLDER "%r%s", &Directory_Separator, &crc32);
}
bool TextureCache_HasUrl(STRING_PURE String* url) {
String path; TexCache_InitAndMakePath(url);
return Platform_FileExists(&path);
return File_Exists(&path);
}
bool TextureCache_GetStream(STRING_PURE String* url, struct Stream* stream) {
String path; TexCache_InitAndMakePath(url);
void* file;
ReturnCode result = Platform_FileOpen(&file, &path);
ReturnCode result = File_Open(&file, &path);
if (result == ReturnCode_FileNotFound) return false;
ErrorHandler_CheckOrFail(result, "TextureCache - GetStream");
@ -342,7 +342,7 @@ void TextureCache_GetLastModified(STRING_PURE String* url, DateTime* time) {
DateTime_FromTotalMs(time, ticks / TEXCACHE_TICKS_PER_MS);
} else {
String path; TexCache_InitAndMakePath(url);
ReturnCode result = Platform_FileGetModifiedTime(&path, time);
ReturnCode result = File_GetModifiedTime(&path, time);
ErrorHandler_CheckOrFail(result, "TextureCache - get file last modified time")
}
}
@ -356,12 +356,12 @@ void TextureCache_AddData(STRING_PURE String* url, UInt8* data, UInt32 length) {
ReturnCode result;
String folder = String_FromConst(TEXCACHE_FOLDER);
if (!Platform_DirectoryExists(&folder)) {
result = Platform_DirectoryCreate(&folder);
if (!Directory_Exists(&folder)) {
result = Directory_Create(&folder);
ErrorHandler_CheckOrFail(result, "TextureCache_AddData - create directory");
}
void* file; result = Platform_FileCreate(&file, &path);
void* file; result = File_Create(&file, &path);
/* TODO: Should we just log failure to save? */
ErrorHandler_CheckOrFail(result, "TextureCache_AddData - open file");
struct Stream stream; Stream_FromFile(&stream, file, &path);
@ -428,10 +428,10 @@ static ReturnCode TexturePack_ExtractZip(struct Stream* stream) {
void TexturePack_ExtractZip_File(STRING_PURE String* filename) {
UChar pathBuffer[String_BufferSize(FILENAME_SIZE)];
String path = String_InitAndClearArray(pathBuffer);
String_Format2(&path, "texpacks%r%s", &Platform_DirectorySeparator, filename);
String_Format2(&path, "texpacks%r%s", &Directory_Separator, filename);
void* file;
ReturnCode result = Platform_FileOpen(&file, &path);
ReturnCode result = File_Open(&file, &path);
ErrorHandler_CheckOrFail(result, "TexturePack_Extract - opening file");
struct Stream stream; Stream_FromFile(&stream, file, &path);
{
@ -451,7 +451,7 @@ ReturnCode TexturePack_ExtractTerrainPng(struct Stream* stream) {
if (Game_ChangeTerrainAtlas(&bmp)) return 0;
}
Platform_MemFree(&bmp.Scan0);
Mem_Free(&bmp.Scan0);
return result;
}

View File

@ -42,7 +42,7 @@ static ReturnCode Ogg_Read(struct Stream* stream, UInt8* data, UInt32 count, UIn
for (;;) {
if (stream->Meta.Ogg.Left) {
count = min(count, stream->Meta.Ogg.Left);
Platform_MemCpy(data, stream->Meta.Ogg.Cur, count);
Mem_Copy(data, stream->Meta.Ogg.Cur, count);
*modified = count;
stream->Meta.Ogg.Cur += count;
@ -158,9 +158,9 @@ static UInt32 lookup1_values(UInt32 entries, UInt32 dimensions) {
}
static bool Codebook_CalcCodewords(struct Codebook* c, UInt8* len) {
c->Codewords = Platform_MemAlloc(c->NumCodewords, sizeof(UInt32), "codewords");
c->CodewordLens = Platform_MemAlloc(c->NumCodewords, sizeof(UInt8), "raw codeword lens");
c->Values = Platform_MemAlloc(c->NumCodewords, sizeof(UInt32), "values");
c->Codewords = Mem_Alloc(c->NumCodewords, sizeof(UInt32), "codewords");
c->CodewordLens = Mem_Alloc(c->NumCodewords, sizeof(UInt8), "raw codeword lens");
c->Values = Mem_Alloc(c->NumCodewords, sizeof(UInt32), "values");
/* This is taken from stb_vorbis.c because I gave up trying */
UInt32 i, j, depth;
@ -211,7 +211,7 @@ static ReturnCode Codebook_DecodeSetup(struct VorbisState* ctx, struct Codebook*
c->Dimensions = Vorbis_ReadBits(ctx, 16);
c->Entries = Vorbis_ReadBits(ctx, 24);
UInt8* codewordLens = Platform_MemAlloc(c->Entries, sizeof(UInt8), "raw codeword lens");
UInt8* codewordLens = Mem_Alloc(c->Entries, sizeof(UInt8), "raw codeword lens");
Int32 i, ordered = Vorbis_ReadBits(ctx, 1), usedEntries = 0;
if (!ordered) {
@ -251,7 +251,7 @@ static ReturnCode Codebook_DecodeSetup(struct VorbisState* ctx, struct Codebook*
static int booknummm;
Platform_Log1("### BUILDING %i ###", &booknummm);
Codebook_CalcCodewords(c, codewordLens);
Platform_MemFree(&codewordLens);
Mem_Free(&codewordLens);
booknummm++;
c->LookupType = Vorbis_ReadBits(ctx, 4);
@ -271,7 +271,7 @@ static ReturnCode Codebook_DecodeSetup(struct VorbisState* ctx, struct Codebook*
}
c->LookupValues = lookupValues;
c->Multiplicands = Platform_MemAlloc(lookupValues, sizeof(UInt16), "multiplicands");
c->Multiplicands = Mem_Alloc(lookupValues, sizeof(UInt16), "multiplicands");
for (i = 0; i < lookupValues; i++) {
c->Multiplicands[i] = Vorbis_ReadBits(ctx, valueBits);
}
@ -403,7 +403,7 @@ static ReturnCode Floor_DecodeSetup(struct VorbisState* ctx, struct Floor* f) {
/* sort X list for curve computation later */
Int16 xlist_sorted[FLOOR_MAX_VALUES];
Platform_MemCpy(xlist_sorted, f->XList, idx * sizeof(Int16));
Mem_Copy(xlist_sorted, f->XList, idx * sizeof(Int16));
for (i = 0; i < idx; i++) { f->ListOrder[i] = i; }
tmp_xlist = xlist_sorted;
@ -634,7 +634,7 @@ static void Residue_DecodeCore(struct VorbisState* ctx, struct Residue* r, UInt3
UInt32 nToRead = residueEnd - residueBeg;
UInt32 partitionsToRead = nToRead / r->PartitionSize;
UInt8* classifications_raw = Platform_MemAlloc(ch * partitionsToRead * classbook->Dimensions, sizeof(UInt8), "temp classicifcations");
UInt8* classifications_raw = Mem_Alloc(ch * partitionsToRead * classbook->Dimensions, sizeof(UInt8), "temp classicifcations");
UInt8* classifications[VORBIS_MAX_CHANS]; /* TODO ????? */
for (i = 0; i < ch; i++) {
classifications[i] = classifications_raw + (i * partitionsToRead * classbook->Dimensions);
@ -699,7 +699,7 @@ static void Residue_DecodeFrame(struct VorbisState* ctx, struct Residue* r, Int3
if (!decodeAny) return;
decodeAny = false; /* because DecodeCore expects this to be 'false' for 'do not decode' */
Real32* interleaved = Platform_MemAllocCleared(ctx->DataSize * ctx->Channels, sizeof(Real32), "residue 2 temp");
Real32* interleaved = Mem_AllocCleared(ctx->DataSize * ctx->Channels, sizeof(Real32), "residue 2 temp");
Residue_DecodeCore(ctx, r, size * ch, 1, &decodeAny, &interleaved);
/* de interleave type 2 output */
@ -866,7 +866,7 @@ void imdct_fast(Real32* in, Real32* out, Int32 n) {
}
if (l+1 <= ld_n - 4) {
Platform_MemCpy(w, u, sizeof(u));
Mem_Copy(w, u, sizeof(u));
}
}
@ -936,7 +936,7 @@ static ReturnCode Mode_DecodeSetup(struct VorbisState* ctx, struct Mode* m) {
}
void Vorbis_Init(struct VorbisState* ctx, struct Stream* source) {
Platform_MemSet(ctx, 0, sizeof(struct VorbisState));
Mem_Set(ctx, 0, sizeof(struct VorbisState));
ctx->Source = source;
}
@ -997,7 +997,7 @@ static ReturnCode Vorbis_DecodeSetup(struct VorbisState* ctx) {
ReturnCode result;
count = Vorbis_ReadBits(ctx, 8); count++;
ctx->Codebooks = Platform_MemAlloc(count, sizeof(struct Codebook), "vorbis codebooks");
ctx->Codebooks = Mem_Alloc(count, sizeof(struct Codebook), "vorbis codebooks");
for (i = 0; i < count; i++) {
result = Codebook_DecodeSetup(ctx, &ctx->Codebooks[i]);
if (result) return result;
@ -1010,7 +1010,7 @@ static ReturnCode Vorbis_DecodeSetup(struct VorbisState* ctx) {
}
count = Vorbis_ReadBits(ctx, 6); count++;
ctx->Floors = Platform_MemAlloc(count, sizeof(struct Floor), "vorbis floors");
ctx->Floors = Mem_Alloc(count, sizeof(struct Floor), "vorbis floors");
for (i = 0; i < count; i++) {
UInt16 floor = Vorbis_ReadBits(ctx, 16);
if (floor != 1) return VORBIS_ERR_FLOOR_TYPE;
@ -1019,7 +1019,7 @@ static ReturnCode Vorbis_DecodeSetup(struct VorbisState* ctx) {
}
count = Vorbis_ReadBits(ctx, 6); count++;
ctx->Residues = Platform_MemAlloc(count, sizeof(struct Residue), "vorbis residues");
ctx->Residues = Mem_Alloc(count, sizeof(struct Residue), "vorbis residues");
for (i = 0; i < count; i++) {
UInt16 residue = Vorbis_ReadBits(ctx, 16);
if (residue > 2) return VORBIS_ERR_FLOOR_TYPE;
@ -1028,7 +1028,7 @@ static ReturnCode Vorbis_DecodeSetup(struct VorbisState* ctx) {
}
count = Vorbis_ReadBits(ctx, 6); count++;
ctx->Mappings = Platform_MemAlloc(count, sizeof(struct Mapping), "vorbis mappings");
ctx->Mappings = Mem_Alloc(count, sizeof(struct Mapping), "vorbis mappings");
for (i = 0; i < count; i++) {
UInt16 mapping = Vorbis_ReadBits(ctx, 16);
if (mapping != 0) return VORBIS_ERR_MAPPING_TYPE;
@ -1037,7 +1037,7 @@ static ReturnCode Vorbis_DecodeSetup(struct VorbisState* ctx) {
}
count = Vorbis_ReadBits(ctx, 6); count++;
ctx->Modes = Platform_MemAlloc(count, sizeof(struct Mode), "vorbis modes");
ctx->Modes = Mem_Alloc(count, sizeof(struct Mode), "vorbis modes");
for (i = 0; i < count; i++) {
result = Mode_DecodeSetup(ctx, &ctx->Modes[i]);
if (result) return result;
@ -1094,7 +1094,7 @@ ReturnCode Vorbis_DecodeFrame(struct VorbisState* ctx) {
next_window = Vorbis_ReadBits(ctx, 1);
}
ctx->Values = Platform_MemAllocCleared(ctx->Channels * ctx->DataSize, sizeof(Real32), "audio values");
ctx->Values = Mem_AllocCleared(ctx->Channels * ctx->DataSize, sizeof(Real32), "audio values");
/* decode floor */
bool hasFloor[VORBIS_MAX_CHANS], hasResidue[VORBIS_MAX_CHANS];
@ -1189,7 +1189,7 @@ ReturnCode Vorbis_DecodeFrame(struct VorbisState* ctx) {
right_n = n / 2;
}
Real32* window = Platform_MemAlloc(n, sizeof(Real32), "temp window");
Real32* window = Mem_Alloc(n, sizeof(Real32), "temp window");
for (i = 0; i < left_window_beg; i++) window[i] = 0;
for (i = left_window_beg; i < left_window_end; i++) {
Real64 inner = Math_Sin((i - left_window_beg + 0.5) / left_n * (PI/2));
@ -1205,14 +1205,14 @@ ReturnCode Vorbis_DecodeFrame(struct VorbisState* ctx) {
/* inverse monolithic transform of audio spectrum vector */
for (i = 0; i < ctx->Channels; i++) {
if (!hasFloor[i]) {
ctx->CurOutput[i] = Platform_MemAllocCleared(ctx->CurBlockSize, sizeof(Real32), "empty output");
ctx->CurOutput[i] = Mem_AllocCleared(ctx->CurBlockSize, sizeof(Real32), "empty output");
continue;
}
Int32 submap = mapping->Mux[i];
Int32 floorIdx = mapping->FloorIdx[submap];
Real32* data = Vorbis_ChanData(ctx, i);
Real32* output = Platform_MemAlloc(ctx->CurBlockSize, sizeof(Real32), "imdct output");
Real32* output = Mem_Alloc(ctx->CurBlockSize, sizeof(Real32), "imdct output");
imdct_fast(data, output, ctx->CurBlockSize);
/* apply windowing */
@ -1233,7 +1233,7 @@ Int32 Vorbis_OutputFrame(struct VorbisState* ctx, Int16* data) {
/* TODO: There's probably a nicer way of doing this.. */
Real32* combined[VORBIS_MAX_CHANS];
for (i = 0; i < ctx->Channels; i++) {
combined[i] = Platform_MemAllocCleared(size, sizeof(Real32), "temp combined");
combined[i] = Mem_AllocCleared(size, sizeof(Real32), "temp combined");
}
Int32 prevHalf = ctx->PrevBlockSize / 2, curHalf = ctx->CurBlockSize / 2;

View File

@ -1533,7 +1533,7 @@ static void MenuInputWidget_RemakeTexture(struct GuiElem* elem) {
struct Texture* tex = &widget->Base.InputTex;
Drawer2D_Make2DTexture(tex, &bmp, adjSize, 0, 0);
Platform_MemFree(&bmp.Scan0);
Mem_Free(&bmp.Scan0);
Widget_Reposition(&widget->Base);
tex->X = widget->Base.X; tex->Y = widget->Base.Y;
@ -1629,7 +1629,7 @@ static void ChatInputWidget_RemakeTexture(struct GuiElem* elem) {
Drawer2D_End();
Drawer2D_Make2DTexture(&widget->InputTex, &bmp, size, 0, 0);
Platform_MemFree(&bmp.Scan0);
Mem_Free(&bmp.Scan0);
widget->Width = size.Width;
widget->Height = realHeight == 0 ? widget->PrefixHeight : realHeight;
@ -2236,7 +2236,7 @@ void TextGroupWidget_PushUpAndReplaceLast(struct TextGroupWidget* widget, STRING
UChar* src = TextGroupWidget_LineBuffer(widget, i + 1);
UInt8 lineLen = widget->LineLengths[i + 1];
if (lineLen > 0) Platform_MemCpy(dst, src, lineLen);
if (lineLen > 0) Mem_Copy(dst, src, lineLen);
widget->Textures[i] = widget->Textures[i + 1];
widget->LineLengths[i] = lineLen;
@ -2408,7 +2408,7 @@ Int32 TextGroupWidget_Reduce(struct TextGroupWidget* widget, UChar* chars, Int32
if (!lineLen) continue;
begs[i] = total;
Platform_MemCpy(&chars[total], TextGroupWidget_LineBuffer(widget, i), lineLen);
Mem_Copy(&chars[total], TextGroupWidget_LineBuffer(widget, i), lineLen);
total += lineLen; ends[i] = total;
}
@ -2539,7 +2539,7 @@ void TextGroupWidget_DrawAdvanced(struct TextGroupWidget* widget, struct Texture
void TextGroupWidget_SetText(struct TextGroupWidget* widget, Int32 index, STRING_PURE String* text) {
if (text->length > TEXTGROUPWIDGET_LEN) ErrorHandler_Fail("TextGroupWidget - too big text");
Gfx_DeleteTexture(&widget->Textures[index].ID);
Platform_MemCpy(TextGroupWidget_LineBuffer(widget, index), text->buffer, text->length);
Mem_Copy(TextGroupWidget_LineBuffer(widget, index), text->buffer, text->length);
widget->LineLengths[index] = (UInt8)text->length;
struct Texture tex;
@ -2798,7 +2798,7 @@ static void SpecialInputWidget_Make(struct SpecialInputWidget* widget, struct Sp
Drawer2D_End();
Drawer2D_Make2DTexture(&widget->Tex, &bmp, size, widget->X, widget->Y);
Platform_MemFree(&bmp.Scan0);
Mem_Free(&bmp.Scan0);
}
static void SpecialInputWidget_Redraw(struct SpecialInputWidget* widget) {

View File

@ -27,7 +27,7 @@ bool stopwatch_highResolution;
LARGE_INTEGER stopwatch_freq;
UChar* Platform_NewLine = "\r\n";
UChar Platform_DirectorySeparator = '\\';
UChar Directory_Separator = '\\';
ReturnCode ReturnCode_FileShareViolation = ERROR_SHARING_VIOLATION;
ReturnCode ReturnCode_FileNotFound = ERROR_FILE_NOT_FOUND;
ReturnCode ReturnCode_NotSupported = ERROR_NOT_SUPPORTED;
@ -110,38 +110,38 @@ static void Platform_AllocFailed(const UChar* place) {
ErrorHandler_Fail(log.buffer);
}
void* Platform_MemAlloc(UInt32 numElems, UInt32 elemsSize, const UChar* place) {
void* Mem_Alloc(UInt32 numElems, UInt32 elemsSize, const UChar* place) {
UInt32 numBytes = numElems * elemsSize; /* TODO: avoid overflow here */
void* ptr = HeapAlloc(heap, 0, numBytes);
if (!ptr) Platform_AllocFailed(place);
return ptr;
}
void* Platform_MemAllocCleared(UInt32 numElems, UInt32 elemsSize, const UChar* place) {
void* Mem_AllocCleared(UInt32 numElems, UInt32 elemsSize, const UChar* place) {
UInt32 numBytes = numElems * elemsSize; /* TODO: avoid overflow here */
void* ptr = HeapAlloc(heap, HEAP_ZERO_MEMORY, numBytes);
if (!ptr) Platform_AllocFailed(place);
return ptr;
}
void* Platform_MemRealloc(void* mem, UInt32 numElems, UInt32 elemsSize, const UChar* place) {
void* Mem_Realloc(void* mem, UInt32 numElems, UInt32 elemsSize, const UChar* place) {
UInt32 numBytes = numElems * elemsSize; /* TODO: avoid overflow here */
void* ptr = HeapReAlloc(heap, 0, mem, numBytes);
if (!ptr) Platform_AllocFailed(place);
return ptr;
}
void Platform_MemFree(void** mem) {
void Mem_Free(void** mem) {
if (mem == NULL || *mem == NULL) return;
HeapFree(heap, 0, *mem);
*mem = NULL;
}
void Platform_MemSet(void* dst, UInt8 value, UInt32 numBytes) {
void Mem_Set(void* dst, UInt8 value, UInt32 numBytes) {
memset(dst, value, numBytes);
}
void Platform_MemCpy(void* dst, void* src, UInt32 numBytes) {
void Mem_Copy(void* dst, void* src, UInt32 numBytes) {
memcpy(dst, src, numBytes);
}
@ -175,38 +175,38 @@ void Platform_FromSysTime(DateTime* time, SYSTEMTIME* sysTime) {
time->Milli = sysTime->wMilliseconds;
}
void Platform_CurrentUTCTime(DateTime* time) {
void DateTime_CurrentUTC(DateTime* time) {
SYSTEMTIME utcTime;
GetSystemTime(&utcTime);
Platform_FromSysTime(time, &utcTime);
}
void Platform_CurrentLocalTime(DateTime* time) {
void DateTime_CurrentLocal(DateTime* time) {
SYSTEMTIME localTime;
GetLocalTime(&localTime);
Platform_FromSysTime(time, &localTime);
}
bool Platform_FileExists(STRING_PURE String* path) {
bool File_Exists(STRING_PURE String* path) {
WCHAR data[512]; Platform_UnicodeExpand(data, path);
UInt32 attribs = GetFileAttributesW(data);
return attribs != INVALID_FILE_ATTRIBUTES && !(attribs & FILE_ATTRIBUTE_DIRECTORY);
}
bool Platform_DirectoryExists(STRING_PURE String* path) {
bool Directory_Exists(STRING_PURE String* path) {
WCHAR data[512]; Platform_UnicodeExpand(data, path);
UInt32 attribs = GetFileAttributesW(data);
return attribs != INVALID_FILE_ATTRIBUTES && (attribs & FILE_ATTRIBUTE_DIRECTORY);
}
ReturnCode Platform_DirectoryCreate(STRING_PURE String* path) {
ReturnCode Directory_Create(STRING_PURE String* path) {
WCHAR data[512]; Platform_UnicodeExpand(data, path);
BOOL success = CreateDirectoryW(data, NULL);
return success ? 0 : GetLastError();
}
ReturnCode Platform_EnumFiles(STRING_PURE String* path, void* obj, Platform_EnumFilesCallback callback) {
ReturnCode Directory_Enum(STRING_PURE String* path, void* obj, Directory_EnumCallback callback) {
UChar fileBuffer[String_BufferSize(MAX_PATH + 10)];
String file = String_InitAndClearArray(fileBuffer);
/* Need to append \* to search for files in directory */
@ -235,9 +235,9 @@ ReturnCode Platform_EnumFiles(STRING_PURE String* path, void* obj, Platform_Enum
return code == ERROR_NO_MORE_FILES ? 0 : code;
}
ReturnCode Platform_FileGetModifiedTime(STRING_PURE String* path, DateTime* time) {
ReturnCode File_GetModifiedTime(STRING_PURE String* path, DateTime* time) {
void* file;
ReturnCode result = Platform_FileOpen(&file, path);
ReturnCode result = File_Open(&file, path);
if (result != 0) return result;
FILETIME writeTime;
@ -249,44 +249,44 @@ ReturnCode Platform_FileGetModifiedTime(STRING_PURE String* path, DateTime* time
result = GetLastError();
}
Platform_FileClose(file);
File_Close(file);
return result;
}
ReturnCode Platform_FileDo(void** file, STRING_PURE String* path, DWORD access, DWORD createMode) {
ReturnCode File_Do(void** file, STRING_PURE String* path, DWORD access, DWORD createMode) {
WCHAR data[512]; Platform_UnicodeExpand(data, path);
*file = CreateFileW(data, access, FILE_SHARE_READ, NULL, createMode, 0, NULL);
return *file != INVALID_HANDLE_VALUE ? 0 : GetLastError();
}
ReturnCode Platform_FileOpen(void** file, STRING_PURE String* path) {
return Platform_FileDo(file, path, GENERIC_READ, OPEN_EXISTING);
ReturnCode File_Open(void** file, STRING_PURE String* path) {
return File_Do(file, path, GENERIC_READ, OPEN_EXISTING);
}
ReturnCode Platform_FileCreate(void** file, STRING_PURE String* path) {
return Platform_FileDo(file, path, GENERIC_WRITE, CREATE_ALWAYS);
ReturnCode File_Create(void** file, STRING_PURE String* path) {
return File_Do(file, path, GENERIC_WRITE, CREATE_ALWAYS);
}
ReturnCode Platform_FileAppend(void** file, STRING_PURE String* path) {
ReturnCode code = Platform_FileDo(file, path, GENERIC_WRITE, OPEN_ALWAYS);
ReturnCode File_Append(void** file, STRING_PURE String* path) {
ReturnCode code = File_Do(file, path, GENERIC_WRITE, OPEN_ALWAYS);
if (code != 0) return code;
return Platform_FileSeek(*file, 0, STREAM_SEEKFROM_END);
return File_Seek(*file, 0, STREAM_SEEKFROM_END);
}
ReturnCode Platform_FileRead(void* file, UInt8* buffer, UInt32 count, UInt32* bytesRead) {
ReturnCode File_Read(void* file, UInt8* buffer, UInt32 count, UInt32* bytesRead) {
BOOL success = ReadFile((HANDLE)file, buffer, count, bytesRead, NULL);
return success ? 0 : GetLastError();
}
ReturnCode Platform_FileWrite(void* file, UInt8* buffer, UInt32 count, UInt32* bytesWrote) {
ReturnCode File_Write(void* file, UInt8* buffer, UInt32 count, UInt32* bytesWrote) {
BOOL success = WriteFile((HANDLE)file, buffer, count, bytesWrote, NULL);
return success ? 0 : GetLastError();
}
ReturnCode Platform_FileClose(void* file) {
ReturnCode File_Close(void* file) {
return CloseHandle((HANDLE)file) ? 0 : GetLastError();
}
ReturnCode Platform_FileSeek(void* file, Int32 offset, Int32 seekType) {
ReturnCode File_Seek(void* file, Int32 offset, Int32 seekType) {
DWORD mode = -1;
switch (seekType) {
case STREAM_SEEKFROM_BEGIN: mode = FILE_BEGIN; break;
@ -298,67 +298,67 @@ ReturnCode Platform_FileSeek(void* file, Int32 offset, Int32 seekType) {
return pos == INVALID_SET_FILE_POINTER ? GetLastError() : 0;
}
ReturnCode Platform_FilePosition(void* file, UInt32* position) {
ReturnCode File_Position(void* file, UInt32* position) {
*position = SetFilePointer(file, 0, NULL, 1); /* SEEK_CUR */
return *position == INVALID_SET_FILE_POINTER ? GetLastError() : 0;
}
ReturnCode Platform_FileLength(void* file, UInt32* length) {
ReturnCode File_Length(void* file, UInt32* length) {
*length = GetFileSize(file, NULL);
return *length == INVALID_FILE_SIZE ? GetLastError() : 0;
}
void Platform_ThreadSleep(UInt32 milliseconds) {
void Thread_Sleep(UInt32 milliseconds) {
Sleep(milliseconds);
}
DWORD WINAPI Platform_ThreadStartCallback(LPVOID lpParam) {
Platform_ThreadFunc* func = (Platform_ThreadFunc*)lpParam;
DWORD WINAPI Thread_StartCallback(LPVOID lpParam) {
Thread_StartFunc* func = (Thread_StartFunc*)lpParam;
(*func)();
return 0;
}
void* Platform_ThreadStart(Platform_ThreadFunc* func) {
void* Thread_Start(Thread_StartFunc* func) {
DWORD threadID;
void* handle = CreateThread(NULL, 0, Platform_ThreadStartCallback, func, 0, &threadID);
void* handle = CreateThread(NULL, 0, Thread_StartCallback, func, 0, &threadID);
if (!handle) {
ErrorHandler_FailWithCode(GetLastError(), "Creating thread");
}
return handle;
}
void Platform_ThreadJoin(void* handle) {
void Thread_Join(void* handle) {
WaitForSingleObject((HANDLE)handle, INFINITE);
}
void Platform_ThreadFreeHandle(void* handle) {
void Thread_FreeHandle(void* handle) {
if (!CloseHandle((HANDLE)handle)) {
ErrorHandler_FailWithCode(GetLastError(), "Freeing thread handle");
}
}
CRITICAL_SECTION mutexList[3]; Int32 mutexIndex;
void* Platform_MutexCreate(void) {
void* Mutex_Create(void) {
if (mutexIndex == Array_Elems(mutexList)) ErrorHandler_Fail("Cannot allocate mutex");
CRITICAL_SECTION* ptr = &mutexList[mutexIndex];
InitializeCriticalSection(ptr); mutexIndex++;
return ptr;
}
void Platform_MutexFree(void* handle) {
void Mutex_Free(void* handle) {
DeleteCriticalSection((CRITICAL_SECTION*)handle);
}
void Platform_MutexLock(void* handle) {
void Mutex_Lock(void* handle) {
EnterCriticalSection((CRITICAL_SECTION*)handle);
}
void Platform_MutexUnlock(void* handle) {
void Mutex_Unlock(void* handle) {
LeaveCriticalSection((CRITICAL_SECTION*)handle);
}
void* Platform_EventCreate(void) {
void* Waitable_Create(void) {
void* handle = CreateEventW(NULL, false, false, NULL);
if (!handle) {
ErrorHandler_FailWithCode(GetLastError(), "Creating event");
@ -366,20 +366,24 @@ void* Platform_EventCreate(void) {
return handle;
}
void Platform_EventFree(void* handle) {
void Waitable_Free(void* handle) {
if (!CloseHandle((HANDLE)handle)) {
ErrorHandler_FailWithCode(GetLastError(), "Freeing event");
}
}
void Platform_EventSignal(void* handle) {
void Waitable_Signal(void* handle) {
SetEvent((HANDLE)handle);
}
void Platform_EventWait(void* handle) {
void Waitable_Wait(void* handle) {
WaitForSingleObject((HANDLE)handle, INFINITE);
}
void Waitable_WaitFor(void* handle, UInt32 milliseconds) {
WaitForSingleObject((HANDLE)handle, milliseconds);
}
void Stopwatch_Measure(struct Stopwatch* timer) {
if (stopwatch_highResolution) {
LARGE_INTEGER value;
@ -406,7 +410,7 @@ Int32 Stopwatch_ElapsedMicroseconds(struct Stopwatch* timer) {
}
}
void Platform_FontMake(struct FontDesc* desc, STRING_PURE String* fontName, UInt16 size, UInt16 style) {
void Font_Make(struct FontDesc* desc, STRING_PURE String* fontName, UInt16 size, UInt16 style) {
desc->Size = size;
desc->Style = style;
LOGFONTA font = { 0 };
@ -422,7 +426,7 @@ void Platform_FontMake(struct FontDesc* desc, STRING_PURE String* fontName, UInt
if (!desc->Handle) ErrorHandler_Fail("Creating font handle failed");
}
void Platform_FontFree(struct FontDesc* desc) {
void Font_Free(struct FontDesc* desc) {
if (!DeleteObject(desc->Handle)) ErrorHandler_Fail("Deleting font handle failed");
desc->Handle = NULL;
}
@ -504,13 +508,13 @@ void Platform_ReleaseBitmap(void) {
}
HINTERNET hInternet;
void Platform_HttpInit(void) {
void Http_Init(void) {
/* TODO: Should we use INTERNET_OPEN_TYPE_PRECONFIG instead? */
hInternet = InternetOpenA(PROGRAM_APP_NAME, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (!hInternet) ErrorHandler_FailWithCode(GetLastError(), "Failed to init WinINet");
}
ReturnCode Platform_HttpMakeRequest(struct AsyncRequest* request, void** handle) {
ReturnCode Http_MakeRequest(struct AsyncRequest* request, void** handle) {
String url = String_FromRawArray(request->URL);
UChar headersBuffer[String_BufferSize(STRING_SIZE * 2)];
String headers = String_MakeNull();
@ -540,7 +544,7 @@ ReturnCode Platform_HttpMakeRequest(struct AsyncRequest* request, void** handle)
/* TODO: Test last modified and etag even work */
#define Http_Query(flags, result) HttpQueryInfoA(handle, flags, result, &bufferLen, NULL)
ReturnCode Platform_HttpGetRequestHeaders(struct AsyncRequest* request, void* handle, UInt32* size) {
ReturnCode Http_GetRequestHeaders(struct AsyncRequest* request, void* handle, UInt32* size) {
DWORD bufferLen;
UInt32 status;
@ -564,9 +568,9 @@ ReturnCode Platform_HttpGetRequestHeaders(struct AsyncRequest* request, void* ha
return 0;
}
ReturnCode Platform_HttpGetRequestData(struct AsyncRequest* request, void* handle, void** data, UInt32 size, volatile Int32* progress) {
ReturnCode Http_GetRequestData(struct AsyncRequest* request, void* handle, void** data, UInt32 size, volatile Int32* progress) {
if (size == 0) return ERROR_NOT_SUPPORTED;
*data = Platform_MemAlloc(size, sizeof(UInt8), "http get data");
*data = Mem_Alloc(size, sizeof(UInt8), "http get data");
*progress = 0;
UInt8* buffer = *data;
@ -580,7 +584,7 @@ ReturnCode Platform_HttpGetRequestData(struct AsyncRequest* request, void* handl
}
bool success = InternetReadFile(handle, buffer, toRead, &read);
if (!success) { Platform_MemFree(data); return GetLastError(); }
if (!success) { Mem_Free(data); return GetLastError(); }
if (!read) break;
buffer += read; totalRead += read; left -= read;
@ -591,11 +595,11 @@ ReturnCode Platform_HttpGetRequestData(struct AsyncRequest* request, void* handl
return 0;
}
ReturnCode Platform_HttpFreeRequest(void* handle) {
ReturnCode Http_FreeRequest(void* handle) {
return InternetCloseHandle(handle) ? 0 : GetLastError();
}
ReturnCode Platform_HttpFree(void) {
ReturnCode Http_Free(void) {
return InternetCloseHandle(hInternet) ? 0 : GetLastError();
}
@ -608,7 +612,7 @@ struct AudioContext {
};
struct AudioContext Audio_Contexts[20];
void Platform_AudioInit(AudioHandle* handle, Int32 buffers) {
void Audio_Init(AudioHandle* handle, Int32 buffers) {
Int32 i, j;
for (i = 0; i < Array_Elems(Audio_Contexts); i++) {
struct AudioContext* ctx = &Audio_Contexts[i];
@ -624,27 +628,28 @@ void Platform_AudioInit(AudioHandle* handle, Int32 buffers) {
ErrorHandler_Fail("No free audio contexts");
}
void Platform_AudioFree(AudioHandle handle) {
void Audio_Free(AudioHandle handle) {
struct AudioContext* ctx = &Audio_Contexts[handle];
if (!ctx->Handle) return;
ReturnCode result = waveOutClose(ctx->Handle);
Platform_MemSet(ctx, 0, sizeof(struct AudioContext));
Mem_Set(ctx, 0, sizeof(struct AudioContext));
ErrorHandler_CheckOrFail(result, "Audio - closing device");
}
struct AudioFormat* Platform_AudioGetFormat(AudioHandle handle) {
struct AudioFormat* Audio_GetFormat(AudioHandle handle) {
struct AudioContext* ctx = &Audio_Contexts[handle];
return &ctx->Format;
}
void Platform_AudioSetFormat(AudioHandle handle, struct AudioFormat* format) {
void Audio_SetFormat(AudioHandle handle, struct AudioFormat* format) {
struct AudioContext* ctx = &Audio_Contexts[handle];
struct AudioFormat* cur = &ctx->Format;
/* only recreate handle if we need to */
if (AudioFormat_Eq(cur, format)) return;
if (ctx->Handle) Platform_AudioFree(handle);
if (ctx->Handle) Audio_Free(handle);
ctx->Format = *format;
WAVEFORMATEX fmt = { 0 };
fmt.nChannels = format->Channels;
@ -659,10 +664,10 @@ void Platform_AudioSetFormat(AudioHandle handle, struct AudioFormat* format) {
ErrorHandler_CheckOrFail(result, "Audio - opening device");
}
void Platform_AudioPlayData(AudioHandle handle, Int32 idx, void* data, UInt32 dataSize) {
void Audio_PlayData(AudioHandle handle, Int32 idx, void* data, UInt32 dataSize) {
struct AudioContext* ctx = &Audio_Contexts[handle];
WAVEHDR* hdr = &ctx->Headers[idx];
Platform_MemSet(hdr, 0, sizeof(WAVEHDR));
Mem_Set(hdr, 0, sizeof(WAVEHDR));
hdr->lpData = data;
hdr->dwBufferLength = dataSize;
@ -674,7 +679,7 @@ void Platform_AudioPlayData(AudioHandle handle, Int32 idx, void* data, UInt32 da
ErrorHandler_CheckOrFail(result, "Audio - write header");
}
bool Platform_AudioIsCompleted(AudioHandle handle, Int32 idx) {
bool Audio_IsCompleted(AudioHandle handle, Int32 idx) {
struct AudioContext* ctx = &Audio_Contexts[handle];
WAVEHDR* hdr = &ctx->Headers[idx];
if (!(hdr->dwFlags & WHDR_DONE)) return false;
@ -686,11 +691,11 @@ bool Platform_AudioIsCompleted(AudioHandle handle, Int32 idx) {
return true;
}
bool Platform_AudioIsFinished(AudioHandle handle) {
bool Audio_IsFinished(AudioHandle handle) {
struct AudioContext* ctx = &Audio_Contexts[handle];
Int32 i;
for (i = 0; i < ctx->NumBuffers; i++) {
if (!Platform_AudioIsCompleted(handle, i)) return false;
if (!Audio_IsCompleted(handle, i)) return false;
}
return true;
}

View File

@ -434,7 +434,7 @@ void Window_GetClipboardText(STRING_TRANSIENT String* value) {
for (i = 0; i < 10; i++) {
if (!OpenClipboard(win_Handle)) {
Platform_ThreadSleep(100);
Thread_Sleep(100);
continue;
}
@ -471,7 +471,7 @@ void Window_SetClipboardText(STRING_PURE String* value) {
Int32 i;
for (i = 0; i < 10; i++) {
if (!OpenClipboard(win_Handle)) {
Platform_ThreadSleep(100);
Thread_Sleep(100);
continue;
}
@ -660,7 +660,7 @@ void GLContext_SelectGraphicsMode(struct GraphicsMode mode) {
ErrorHandler_Fail("Requested graphics mode not available");
}
Platform_MemSet(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
Mem_Set(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;

View File

@ -11,7 +11,7 @@
#include "Game.h"
void World_Reset(void) {
Platform_MemFree(&World_Blocks);
Mem_Free(&World_Blocks);
World_Width = 0; World_Height = 0; World_Length = 0;
World_MaxX = 0; World_MaxY = 0; World_MaxZ = 0;
World_BlocksSize = 0;