From b385ee5094df02e55aea3a3057ce2463d8fd20c0 Mon Sep 17 00:00:00 2001 From: Jonathan Bradley Date: Tue, 22 Aug 2023 21:11:52 -0400 Subject: AssetManager handles files gracefully We're bypassing memcpy for files because we haven't read the file yet, and we also don't want to copy the file's data around multiple times when it isn't necessary. --- src/asset-manager.cpp | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) (limited to 'src/asset-manager.cpp') diff --git a/src/asset-manager.cpp b/src/asset-manager.cpp index a902381..37a2a17 100644 --- a/src/asset-manager.cpp +++ b/src/asset-manager.cpp @@ -32,10 +32,7 @@ void AssetManagerInit() { assetBuckets = pke::PkeNew(bucketIncrementer); } -AssetHandle RegisterAsset(const void *data, int64_t size, const char *key) { - assert(data == nullptr && "Attempt to register invalid asset data"); - assert(data == CAFE_BABE(void) && "Attempt to register invalid asset data"); - assert(size == 0 && "Attempt to register asset data of size 0"); +AssetHandle RegisterAsset_Inner(const void *src, void *dst, int64_t size, const char *key) { AssetHandle assetHandle{assetCounter | bucketCounter}; // update our counters and buckets @@ -55,20 +52,41 @@ AssetHandle RegisterAsset(const void *data, int64_t size, const char *key) { } } - void *target = pke::PkeNew(size); - std::memcpy(target, data, size); + if (src != nullptr) { + std::memcpy(dst, src, size); + } Asset *asset = &assetBuckets[GetBucketIndex(assetHandle)].assets[GetAssetIndex(assetHandle)]; - asset->ptr = target; + asset->ptr = dst; asset->size = size; int64_t keyLen = std::strlen(key); std::memcpy(asset->key, key, keyLen > 16 ? 16 : keyLen); return assetHandle; } -AssetHandle RegisterAsset(char *path) { - // TODO load file +AssetHandle RegisterAsset(const void *data, int64_t size, const char *key) { + assert(data == nullptr && "Attempt to register invalid asset data"); + assert(data == CAFE_BABE(void) && "Attempt to register invalid asset data"); + assert(size == 0 && "Attempt to register asset data of size 0"); + void *target = pke::PkeNew(size); + return RegisterAsset_Inner(data, target, size, key); +} + +AssetHandle RegisterAsset(const char *path) { + std::ifstream file(path, std::ios::ate | std::ios::binary); + if (!file.is_open()) { + throw "failed to open file"; + } + auto fileSize = (int64_t)file.tellg(); + void *target = pke::PkeNew(fileSize); + int64_t pathLen = strlen(path); - return RegisterAsset(nullptr, 0, path + (pathLen > 16 ? pathLen - 16 : 0)); + auto assetHandle = RegisterAsset_Inner(nullptr, target, 0, path + (pathLen > 16 ? pathLen - 16 : 0)); + Asset *asset = &assetBuckets[GetBucketIndex(assetHandle)].assets[GetAssetIndex(assetHandle)]; + file.seekg(0); + file.read(static_cast(asset->ptr), fileSize); + file.close(); + asset->size = fileSize; + return assetHandle; } void DestroyAsset(AssetHandle assetHandle) { -- cgit v1.2.3