2 Commits
Author SHA1 Message Date
rboullard 33a79ed12f Game analysis for SonarQube (#5)
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: game) (push) Successful in 46s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang (Unity Build: ON, Variant: game) (push) Successful in 29s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: game) (push) Successful in 1m23s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: game) (push) Successful in 49s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: game) (push) Successful in 1m8s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang (Unity Build: ON, Variant: toolmode) (push) Successful in 45s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: toolmode) (push) Successful in 1m8s
Bigfoot / Clang Format Checks (push) Successful in 13s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: toolmode) (push) Successful in 49s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang (Unity Build: ON, Variant: toolmode) (push) Successful in 31s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: toolmode) (push) Successful in 1m30s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: game) (push) Successful in 1m3s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: toolmode) (push) Successful in 1m10s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: toolmode) (push) Successful in 56s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang (Unity Build: ON, Variant: game) (push) Successful in 34s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang (Unity Build: ON, Variant: toolmode) (push) Successful in 41s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: game) (push) Successful in 1m27s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: toolmode) (push) Successful in 1m35s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: toolmode) (push) Successful in 1m16s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: game) (push) Successful in 37s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: toolmode) (push) Successful in 56s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang (Unity Build: ON, Variant: game) (push) Successful in 29s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: game) (push) Successful in 1m2s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: game) (push) Successful in 53s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: toolmode) (push) Successful in 1m3s
Bigfoot / Sonarqube (game) (push) Successful in 5m17s
Bigfoot / Sonarqube (toolmode) (push) Successful in 5m39s
Reviewed-on: #5
Co-authored-by: Romain BOULLARD <romain.boullard@protonmail.com>
2026-09-02 13:55:27 +00:00
rboullard 9fd1cd0d68 Asset System (#2)
Bigfoot / Sonarqube (push) Successful in 5m42s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: toolmode) (push) Successful in 1m25s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: toolmode) (push) Successful in 1m5s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang (Unity Build: ON, Variant: game) (push) Successful in 32s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: game) (push) Successful in 1m4s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: toolmode) (push) Successful in 1m27s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: toolmode) (push) Successful in 1m11s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang (Unity Build: ON, Variant: game) (push) Successful in 29s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: toolmode) (push) Successful in 55s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: game) (push) Successful in 1m0s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: toolmode) (push) Successful in 1m5s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: toolmode) (push) Successful in 56s
Bigfoot / Clang Format Checks (push) Successful in 12s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: game) (push) Successful in 43s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang (Unity Build: ON, Variant: game) (push) Successful in 25s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: toolmode) (push) Successful in 52s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang (Unity Build: ON, Variant: toolmode) (push) Successful in 30s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: game) (push) Successful in 1m19s
Bigfoot / Build & Test Debug with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: game) (push) Successful in 1m1s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: game) (push) Successful in 48s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: toolmode) (push) Successful in 49s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang (Unity Build: ON, Variant: toolmode) (push) Successful in 35s
Bigfoot / Build & Test RelWithDebInfo with ./ConanProfiles/host/clang_asan (Unity Build: OFF, Variant: game) (push) Successful in 1m20s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang (Unity Build: OFF, Variant: game) (push) Successful in 36s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang (Unity Build: ON, Variant: toolmode) (push) Successful in 42s
Bigfoot / Build & Test Release with ./ConanProfiles/host/clang_asan (Unity Build: ON, Variant: game) (push) Successful in 50s
Only time I'm allowing a merge of single feature inside main (we prefer merging a version)
But I need a first Sonarqube run

Reviewed-on: #2
Co-authored-by: Romain BOULLARD <romain.boullard@protonmail.com>
2026-09-01 17:32:16 +00:00
86 changed files with 2070 additions and 821 deletions
+5 -1
View File
@@ -11,9 +11,13 @@ Checks: >
portability-*,
-modernize-use-trailing-return-type,
-modernize-use-auto,
-readability-avoid-const-params-in-decls,
-cppcoreguidelines-macro-usage,
-cppcoreguidelines-avoid-do-while
-cppcoreguidelines-avoid-do-while,
-cppcoreguidelines-pro-bounds-avoid-unchecked-container-access,
-cppcoreguidelines-pro-bounds-pointer-arithmetic,
-cppcoreguidelines-pro-type-reinterpret-cast
ExcludeHeaderFilterRegex: '_generated.*'
+12 -12
View File
@@ -18,10 +18,10 @@ jobs:
build_type: ["Debug", "RelWithDebInfo", "Release"]
unity_build: ["ON", "OFF"]
conan_profile: ["./ConanProfiles/host/clang", "./ConanProfiles/host/clang_asan"]
toolmode:
variant:
- { value: "True", name: "toolmode" }
- { value: "False", name: "game" }
name: "Build & Test ${{ matrix.build_type }} with ${{ matrix.conan_profile }} (Unity Build: ${{ matrix.unity_build }}, Variant: ${{ matrix.toolmode.name }})"
name: "Build & Test ${{ matrix.build_type }} with ${{ matrix.conan_profile }} (Unity Build: ${{ matrix.unity_build }}, Variant: ${{ matrix.variant.name }})"
steps:
- name: Install Node.js
run: apt-get update && apt-get install -y nodejs
@@ -33,18 +33,18 @@ jobs:
- name: Build
run: |
conan install . --remote=bigfootpackages -pr:h=${{ matrix.conan_profile }} -pr:b=./ConanProfiles/build/clang --build=missing -s build_type=${{ matrix.build_type }} -o bigfoot/*:build_tests=True -o bigfoot/*:build_benchmarks=True -o bigfoot/*:tracy=False -o bigfoot/*:vulkan=True -o bigfoot/*:toolmode=${{ matrix.toolmode.value }} -of build-${{ matrix.toolmode.name }}
. ./build-${{ matrix.toolmode.name }}/build/${{ matrix.build_type }}/generators/conanbuild.sh
cmake -S . -B ./build-${{ matrix.toolmode.name }}/${{ matrix.build_type }} --toolchain ./build-${{ matrix.toolmode.name }}/build/${{ matrix.build_type }}/generators/conan_toolchain.cmake -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} -DCMAKE_UNITY_BUILD=${{ matrix.unity_build }} -G "Ninja"
cmake --build build-${{ matrix.toolmode.name }}/${{ matrix.build_type }} --parallel $(nproc)
. ./build-${{ matrix.toolmode.name }}/build/${{ matrix.build_type }}/generators/deactivate_conanbuild.sh
conan install . --remote=bigfootpackages -pr:h=${{ matrix.conan_profile }} -pr:b=./ConanProfiles/build/clang --build=missing -s build_type=${{ matrix.build_type }} -o bigfoot/*:build_tests=True -o bigfoot/*:build_benchmarks=True -o bigfoot/*:tracy=False -o bigfoot/*:vulkan=True -o bigfoot/*:toolmode=${{ matrix.variant.value }} -of build-${{ matrix.variant.name }}
. ./build-${{ matrix.variant.name }}/build/${{ matrix.build_type }}/generators/conanbuild.sh
cmake -S . -B ./build-${{ matrix.variant.name }}/${{ matrix.build_type }} --toolchain ./build-${{ matrix.variant.name }}/build/${{ matrix.build_type }}/generators/conan_toolchain.cmake -DCMAKE_BUILD_TYPE=${{ matrix.build_type }} -DCMAKE_UNITY_BUILD=${{ matrix.unity_build }} -G "Ninja"
cmake --build build-${{ matrix.variant.name }}/${{ matrix.build_type }} --parallel $(nproc)
. ./build-${{ matrix.variant.name }}/build/${{ matrix.build_type }}/generators/deactivate_conanbuild.sh
- name: Unit Tests
run: |
cd ./build-${{ matrix.toolmode.name }}/${{ matrix.build_type }}
. ../../build-${{ matrix.toolmode.name }}/build/${{ matrix.build_type }}/generators/conanbuild.sh
cd ./build-${{ matrix.variant.name }}/${{ matrix.build_type }}
. ../../build-${{ matrix.variant.name }}/build/${{ matrix.build_type }}/generators/conanbuild.sh
xvfb-run ctest . --output-on-failure
. ../../build-${{ matrix.toolmode.name }}/build/${{ matrix.build_type }}/generators/deactivate_conanbuild.sh
. ../../build-${{ matrix.variant.name }}/build/${{ matrix.build_type }}/generators/deactivate_conanbuild.sh
clang-format:
runs-on: ubuntu-latest
@@ -60,6 +60,6 @@ jobs:
uses: actions/checkout@v6
with:
submodules: recursive
- name: Clang Format Checks
run: chmod +x format.sh && ./format.sh --check Bigfoot
run: chmod +x format.sh && ./format.sh --check Bigfoot
+59 -12
View File
@@ -5,6 +5,10 @@ on:
branches:
- main
- Development
pull_request:
branches:
- main
- Development
jobs:
build-and-test:
@@ -13,7 +17,14 @@ jobs:
container:
image: git.romainboullard.com/bigfootdev/linuxcppbuilder:development
name: "Sonarqube"
strategy:
fail-fast: false
matrix:
variant:
- { value: "True", name: "toolmode", projectKey: "Bigfoot-Tool", projectName: "Bigfoot Tool" }
- { value: "False", name: "game", projectKey: "Bigfoot-Game", projectName: "Bigfoot Game" }
name: "Sonarqube (${{ matrix.variant.name }})"
steps:
- name: Install Node.js
run: apt-get update && apt-get install -y nodejs
@@ -23,28 +34,64 @@ jobs:
with:
fetch-depth: 0
submodules: recursive
ref: ${{ github.event.pull_request.head.sha || github.sha }}
- name: Read version
id: version
run: echo "version=$(cat VERSION)" >> "$GITHUB_OUTPUT"
- name: Build
run: |
conan install . --remote=bigfootpackages -pr:h=./ConanProfiles/host/clang_coverage -pr:b=./ConanProfiles/build/clang --build=missing -s build_type=Debug -o bigfoot/*:build_tests=True -o bigfoot/*:build_benchmarks=True -o bigfoot/*:tracy=False -o bigfoot/*:build_tools=True -o bigfoot/*:vulkan=True
. ./build/Debug/generators/conanbuild.sh
cmake -S . -B ./build/Debug --toolchain ./build/Debug/generators/conan_toolchain.cmake -DCMAKE_BUILD_TYPE=Debug -G "Ninja"
cmake --build build/Debug --parallel $(nproc)
. ./build/Debug/generators/deactivate_conanbuild.sh
conan install . --remote=bigfootpackages -pr:h=./ConanProfiles/host/clang_coverage -pr:b=./ConanProfiles/build/clang --build=missing -s build_type=Debug -o bigfoot/*:build_tests=True -o bigfoot/*:build_benchmarks=True -o bigfoot/*:tracy=False -o bigfoot/*:toolmode=${{ matrix.variant.value }} -o bigfoot/*:vulkan=True -of build-${{ matrix.variant.name }}
. ./build-${{ matrix.variant.name }}/build/Debug/generators/conanbuild.sh
cmake -S . -B ./build-${{ matrix.variant.name }}/Debug --toolchain ./build-${{ matrix.variant.name }}/build/Debug/generators/conan_toolchain.cmake -DCMAKE_BUILD_TYPE=Debug -G "Ninja"
cmake --build build-${{ matrix.variant.name }}/Debug --parallel $(nproc)
. ./build-${{ matrix.variant.name }}/build/Debug/generators/deactivate_conanbuild.sh
- name: Run tests
run: |
cd ./build-${{ matrix.variant.name }}/Debug
. ../../build-${{ matrix.variant.name }}/build/Debug/generators/conanbuild.sh
LLVM_PROFILE_FILE="%p.profraw%c" xvfb-run ctest --output-on-failure
. ../../build-${{ matrix.variant.name }}/build/Debug/generators/deactivate_conanbuild.sh
- name: Clang-Tidy
run: run-clang-tidy -p ./build/Debug/ >> tidy_result.txt
run: run-clang-tidy -p ./build-${{ matrix.variant.name }}/Debug/ > tidy_result.txt
- name: Infer
run: infer run --compilation-database build/Debug/compile_commands.json
run: infer run --compilation-database build-${{ matrix.variant.name }}/Debug/compile_commands.json
- name: Generate coverage report
shell: bash
run: |
# gcovr's own LLVM-JSON reader only understands coverage-mapping format
# 2.x; this image's clang 22 llvm-cov emits format 3.x, which gcovr
# rejects outright ("Wrong major version"). Bypassing gcovr's JSON
# path entirely: llvm-cov's lcov exporter is a separate, unaffected
# code path, so merge -> export lcov -> convert lcov to Cobertura.
llvm-profdata merge -sparse $(find build-${{ matrix.variant.name }}/Debug -name "*.profraw") -o merged.profdata
BINARIES=($(find build-${{ matrix.variant.name }}/Debug -maxdepth 8 -type f -executable -iname "*Tests"))
OBJECT_ARGS=$(printf -- '-object %s ' "${BINARIES[@]:1}")
llvm-cov export -format=lcov -instr-profile=merged.profdata "${BINARIES[0]}" $OBJECT_ARGS > coverage.lcov
# lcov_cobertura isn't preinstalled on the image; inject it into
# gcovr's existing pipx venv and expose its CLI on PATH.
pipx inject gcovr lcov_cobertura --include-apps
lcov_cobertura coverage.lcov -b . -o coverage.xml
- name: SonarQube Scan
if: github.head_ref == 'main' || github.ref_name == 'main'
uses: SonarSource/sonarqube-scan-action@v7.0.0
with:
args: >
-Dsonar.cxx.jsonCompilationDatabase=./build/Debug/compile_commands.json
-Dsonar.verbose=true
-Dsonar.projectKey=${{ matrix.variant.projectKey }}
"-Dsonar.projectName=${{ matrix.variant.projectName }}"
-Dsonar.projectVersion=${{ steps.version.outputs.version }}
-Dsonar.cxx.jsonCompilationDatabase=./build-${{ matrix.variant.name }}/Debug/compile_commands.json
-Dsonar.cxx.xunit.reportPaths=build-${{ matrix.variant.name }}/Debug/TestResults/*.xml
-Dsonar.qualitygate.wait=true
${{ github.event_name == 'pull_request' &&
format('-Dsonar.pullrequest.key={0} -Dsonar.pullrequest.branch={1} -Dsonar.pullrequest.base={2} -Dsonar.analysis.sqbot={3}',
github.event.pull_request.number, github.head_ref, github.base_ref, github.event.pull_request.head.sha)
|| format('-Dsonar.branch.name={0}', github.ref_name) }}
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST }}
+5
View File
@@ -0,0 +1,5 @@
InheritParentConfig: true
Checks: >
-cppcoreguidelines-non-private-member-variables-in-classes,
-cppcoreguidelines-avoid-magic-numbers,
-readability-magic-numbers
@@ -30,7 +30,7 @@ class ReferenceFixture: public benchmark::Fixture
SetActiveAssetLibrary(&m_library);
std::ignore = m_library.Insert(&m_container);
m_uuid = m_container.Insert()->GetAsset()->GetHeader().uuid;
m_uuid = CreateAsset<BenchmarkAsset>()->GetHeader().uuid;
m_reference.emplace(m_uuid);
}
+91 -49
View File
@@ -14,6 +14,8 @@
#include <AssetsForBenchmarking/Asset/BenchmarkAsset.hpp>
#include <AssetsForBenchmarking/Asset/BenchmarkAssetReferred.hpp>
#include <EASTL/optional.h>
#include <EASTL/span.h>
#include <EASTL/vector.h>
#include <benchmark/benchmark.h>
#include <effolkronium/random.hpp>
@@ -30,40 +32,22 @@ class BigFileFixture: public benchmark::Fixture
{
protected:
static constexpr std::uint32_t ASSET_COUNT = 20'000;
static constexpr std::uint32_t REFS_PER_ASSET = 4;
static constexpr std::size_t ASSET_PAYLOAD_SIZE = 256;
void SetUp(benchmark::State&) override
void SetUp([[maybe_unused]] benchmark::State& p_state) override
{
m_bigFile.Clear();
// The DB is populated exactly once for the entire benchmark process.
// SetUp is called before every calibration round (Google Benchmark doubles
// iteration counts until it reaches a stable measurement), so rebuilding
// the DB each time would dominate the total benchmark time.
m_uuids = BuildData();
m_bigFile.emplace(File {BIGFILE_ENGINEBENCHMARKS_LOCATION});
}
m_uuids.clear();
m_uuids.reserve(ASSET_COUNT);
eastl::vector<eastl::vector<std::byte>> flatbuffers;
eastl::vector<eastl::vector<UUID>> hardReferences;
flatbuffers.reserve(ASSET_COUNT);
hardReferences.reserve(ASSET_COUNT);
for (std::uint32_t i = 0; i < ASSET_COUNT; ++i)
{
BenchmarkAsset asset;
asset.SetName(asset.GetHeader().uuid.ToString().c_str());
asset.GetAsset().payload.assign(ASSET_PAYLOAD_SIZE, std::uint8_t {0xAB});
for (std::uint32_t j = 0; j < 4; ++j)
{
BenchmarkAssetReferred assetReferred;
assetReferred.SetName(assetReferred.GetHeader().uuid.ToString().c_str());
asset.GetAsset().refs.emplace_back(assetReferred.GetHeader().uuid);
}
const eastl::vector<std::byte> flatbuffer = asset.Pack();
flatbuffers.push_back(flatbuffer);
hardReferences.push_back(asset.GetHardReferences(flatbuffer));
m_uuids.push_back(asset.GetHeader().uuid);
}
m_bigFile.SaveAssetFlatbuffers(m_uuids, flatbuffers, hardReferences);
void TearDown([[maybe_unused]] benchmark::State& p_state) override
{
m_bigFile.reset();
}
[[nodiscard]]
@@ -93,8 +77,49 @@ class BigFileFixture: public benchmark::Fixture
return pool;
}
BigFile m_bigFile {File {BIGFILE_ENGINEBENCHMARKS_LOCATION}};
eastl::vector<UUID> m_uuids;
eastl::optional<BigFile> m_bigFile;
eastl::span<const UUID> m_uuids;
private:
static const eastl::vector<UUID>& BuildData()
{
static const eastl::vector<UUID> s_uuids = []()
{
eastl::vector<UUID> uuids;
eastl::vector<eastl::vector<std::byte>> flatbuffers;
eastl::vector<eastl::vector<UUID>> hardReferences;
uuids.reserve(ASSET_COUNT);
flatbuffers.reserve(ASSET_COUNT);
hardReferences.reserve(ASSET_COUNT);
for (std::uint32_t i = 0; i < ASSET_COUNT; ++i)
{
BenchmarkAsset asset;
asset.SetName(asset.GetHeader().uuid.ToString());
asset.GetAsset().payload.assign(ASSET_PAYLOAD_SIZE, std::uint8_t {0xAB});
for (std::uint32_t j = 0; j < REFS_PER_ASSET; ++j)
{
BenchmarkAssetReferred assetReferred;
assetReferred.SetName(assetReferred.GetHeader().uuid.ToString());
asset.GetAsset().refs.emplace_back(assetReferred.GetHeader().uuid);
}
eastl::vector<std::byte> flatbuffer = asset.Pack();
hardReferences.push_back(asset.GetHardReferences(flatbuffer));
flatbuffers.push_back(std::move(flatbuffer));
uuids.push_back(asset.GetHeader().uuid);
}
BigFile bigFile {File {BIGFILE_ENGINEBENCHMARKS_LOCATION}};
bigFile.Clear();
bigFile.SaveAssetFlatbuffers(uuids, flatbuffers, hardReferences);
return uuids;
}();
return s_uuids;
}
};
/****************************************************************************************/
@@ -105,7 +130,7 @@ BENCHMARK_DEFINE_F(BigFileFixture, GetAssetFlatbuffer)(benchmark::State& state)
for (auto _: state)
{
eastl::vector<std::byte> flatbuffer = m_bigFile.GetAssetFlatbuffer(
eastl::vector<std::byte> flatbuffer = m_bigFile->GetAssetFlatbuffer(
m_uuids[Random::get<std::size_t>(0, m_uuids.size() - 1)]);
benchmark::DoNotOptimize(flatbuffer);
@@ -116,7 +141,7 @@ BENCHMARK_DEFINE_F(BigFileFixture, GetAssetFlatbuffer)(benchmark::State& state)
state.SetBytesProcessed(bytesProcessed);
}
BENCHMARK_REGISTER_F(BigFileFixture, GetAssetFlatbuffer)->Name("BigFile/GetAssetFlatbuffer");
BENCHMARK_REGISTER_F(BigFileFixture, GetAssetFlatbuffer)->Name("BigFile/GetAssetFlatbuffer")->UseRealTime();
/****************************************************************************************/
@@ -132,7 +157,7 @@ BENCHMARK_DEFINE_F(BigFileFixture, GetAssetFlatbuffers)(benchmark::State& state)
for (auto _: state)
{
eastl::vector<eastl::vector<std::byte>> flatbuffers = m_bigFile.GetAssetFlatbuffers(batchPool[batchIndex]);
eastl::vector<eastl::vector<std::byte>> flatbuffers = m_bigFile->GetAssetFlatbuffers(batchPool[batchIndex]);
benchmark::DoNotOptimize(flatbuffers);
for (const eastl::vector<std::byte>& flatbuffer: flatbuffers)
@@ -153,7 +178,8 @@ BENCHMARK_REGISTER_F(BigFileFixture, GetAssetFlatbuffers)
->Arg(8)
->Arg(64)
->Arg(512)
->Arg(4096);
->Arg(4096)
->UseRealTime();
/****************************************************************************************/
@@ -162,13 +188,14 @@ BENCHMARK_DEFINE_F(BigFileFixture, GetAssetHardReferences)(benchmark::State& sta
for (auto _: state)
{
benchmark::DoNotOptimize(
m_bigFile.GetAssetHardReferences(m_uuids[Random::get<std::size_t>(0, m_uuids.size() - 1)]));
m_bigFile->GetAssetHardReferences(m_uuids[Random::get<std::size_t>(0, m_uuids.size() - 1)]));
}
state.SetItemsProcessed(state.iterations());
state.SetBytesProcessed(static_cast<std::int64_t>(state.iterations()) * REFS_PER_ASSET * UUID::UUID_BYTE_SIZE);
}
BENCHMARK_REGISTER_F(BigFileFixture, GetAssetHardReferences)->Name("BigFile/GetAssetHardReferences");
BENCHMARK_REGISTER_F(BigFileFixture, GetAssetHardReferences)->Name("BigFile/GetAssetHardReferences")->UseRealTime();
/****************************************************************************************/
@@ -182,11 +209,13 @@ BENCHMARK_DEFINE_F(BigFileFixture, GetAssetsHardReferences)(benchmark::State& st
std::size_t batchIndex = 0;
for (auto _: state)
{
benchmark::DoNotOptimize(m_bigFile.GetAssetsHardReferences(batchPool[batchIndex]));
benchmark::DoNotOptimize(m_bigFile->GetAssetsHardReferences(batchPool[batchIndex]));
batchIndex = (batchIndex + 1) % BATCH_POOL_SIZE;
}
state.SetItemsProcessed(state.iterations() * batchSize);
state.SetBytesProcessed(static_cast<std::int64_t>(state.iterations()) * batchSize * REFS_PER_ASSET *
UUID::UUID_BYTE_SIZE);
}
BENCHMARK_REGISTER_F(BigFileFixture, GetAssetsHardReferences)
@@ -195,7 +224,8 @@ BENCHMARK_REGISTER_F(BigFileFixture, GetAssetsHardReferences)
->Arg(8)
->Arg(64)
->Arg(512)
->Arg(4096);
->Arg(4096)
->UseRealTime();
/****************************************************************************************/
@@ -207,22 +237,26 @@ BENCHMARK_DEFINE_F(BigFileFixture, SaveAssetFlatbuffer)(benchmark::State& state)
{
state.PauseTiming();
BenchmarkAsset asset;
asset.SetName(asset.GetHeader().uuid.ToString().c_str());
asset.SetName(asset.GetHeader().uuid.ToString());
asset.GetAsset().payload.assign(ASSET_PAYLOAD_SIZE, std::uint8_t {0xAB});
for (std::uint32_t j = 0; j < REFS_PER_ASSET; ++j)
{
asset.GetAsset().refs.emplace_back(m_uuids[Random::get<std::size_t>(0, m_uuids.size() - 1)]);
}
const eastl::vector<std::byte> flatbuffer = asset.Pack();
const eastl::vector<UUID> hardReferences = asset.GetHardReferences(flatbuffer);
bytesProcessed += static_cast<std::int64_t>(flatbuffer.size());
state.ResumeTiming();
m_bigFile.SaveAssetFlatbuffer(asset.GetHeader().uuid, flatbuffer, hardReferences);
m_bigFile->SaveAssetFlatbuffer(asset.GetHeader().uuid, flatbuffer, hardReferences);
}
state.SetItemsProcessed(state.iterations());
state.SetBytesProcessed(bytesProcessed);
}
BENCHMARK_REGISTER_F(BigFileFixture, SaveAssetFlatbuffer)->Name("BigFile/SaveAssetFlatbuffer");
BENCHMARK_REGISTER_F(BigFileFixture, SaveAssetFlatbuffer)->Name("BigFile/SaveAssetFlatbuffer")->UseRealTime();
/****************************************************************************************/
@@ -234,25 +268,32 @@ BENCHMARK_DEFINE_F(BigFileFixture, SaveAssetFlatbuffers)(benchmark::State& state
for (auto _: state)
{
state.PauseTiming();
eastl::vector<UUID> uuids;
eastl::vector<eastl::vector<std::byte>> flatbuffers;
eastl::vector<eastl::vector<UUID>> hardReferences;
uuids.reserve(batchSize);
flatbuffers.reserve(batchSize);
hardReferences.reserve(batchSize);
for (std::size_t i = 0; i < batchSize; ++i)
{
BenchmarkAsset asset;
asset.SetName(asset.GetHeader().uuid.ToString().c_str());
asset.SetName(asset.GetHeader().uuid.ToString());
asset.GetAsset().payload.assign(ASSET_PAYLOAD_SIZE, std::uint8_t {0xAB});
for (std::uint32_t j = 0; j < REFS_PER_ASSET; ++j)
{
asset.GetAsset().refs.emplace_back(m_uuids[Random::get<std::size_t>(0, m_uuids.size() - 1)]);
}
const eastl::vector<std::byte> flatbuffer = asset.Pack();
flatbuffers.push_back(flatbuffer);
hardReferences.push_back(asset.GetHardReferences(flatbuffer));
eastl::vector<std::byte> flatbuffer = asset.Pack();
uuids.push_back(asset.GetHeader().uuid);
bytesProcessed += static_cast<std::int64_t>(flatbuffer.size());
hardReferences.push_back(asset.GetHardReferences(flatbuffer));
flatbuffers.push_back(std::move(flatbuffer));
}
state.ResumeTiming();
m_bigFile.SaveAssetFlatbuffers(m_uuids, flatbuffers, hardReferences);
m_bigFile->SaveAssetFlatbuffers(uuids, flatbuffers, hardReferences);
}
state.SetItemsProcessed(state.iterations() * batchSize);
@@ -265,6 +306,7 @@ BENCHMARK_REGISTER_F(BigFileFixture, SaveAssetFlatbuffers)
->Arg(8)
->Arg(64)
->Arg(512)
->Arg(4096);
->Arg(4096)
->UseRealTime();
#endif
} // namespace Bigfoot
@@ -15,6 +15,7 @@
#include <AssetsForBenchmarking/Asset/BenchmarkAssetReferred.hpp>
#include <EASTL/optional.h>
#include <EASTL/span.h>
#include <EASTL/vector.h>
#include <benchmark/benchmark.h>
#include <effolkronium/random.hpp>
@@ -30,79 +31,21 @@ using Random = effolkronium::random_static;
class SasquatchFixture: public benchmark::Fixture
{
protected:
struct SasquatchData
{
UUID m_uuid;
eastl::span<const std::byte> m_flatbuffer;
eastl::span<const UUID> m_hardReferences;
};
static constexpr std::uint32_t ASSET_COUNT = 20'000;
static constexpr std::uint32_t REFS_PER_ASSET = 4;
static constexpr std::size_t ASSET_PAYLOAD_SIZE = 256;
void SetUp([[maybe_unused]] benchmark::State& p_state) override
{
File {SASQUATCH_ENGINEBENCHMARKS_LOCATION}.Delete();
eastl::vector<eastl::vector<std::byte>> flatbuffers;
eastl::vector<eastl::vector<UUID>> hardReferences;
flatbuffers.reserve(ASSET_COUNT);
hardReferences.reserve(ASSET_COUNT);
m_uuids.clear();
m_uuids.reserve(ASSET_COUNT);
for (std::uint32_t i = 0; i < ASSET_COUNT; ++i)
{
BenchmarkAsset asset;
asset.SetName(asset.GetHeader().uuid.ToString().c_str());
asset.GetAsset().payload.assign(ASSET_PAYLOAD_SIZE, std::uint8_t {0xAB});
for (std::uint32_t j = 0; j < 4; ++j)
{
BenchmarkAssetReferred assetReferred;
assetReferred.SetName(assetReferred.GetHeader().uuid.ToString().c_str());
asset.GetAsset().refs.emplace_back(assetReferred.GetHeader().uuid);
}
const eastl::vector<std::byte> flatbuffer = asset.Pack();
flatbuffers.push_back(flatbuffer);
hardReferences.push_back(asset.GetHardReferences(flatbuffer));
m_uuids.push_back(asset.GetHeader().uuid);
}
eastl::vector<SasquatchData> assets;
assets.reserve(ASSET_COUNT);
for (std::uint32_t i = 0; i < ASSET_COUNT; ++i)
{
assets.push_back(SasquatchData {.m_uuid = m_uuids[i],
.m_flatbuffer = flatbuffers[i],
.m_hardReferences = hardReferences[i]});
}
std::size_t totalFlatbufferBytes = 0;
std::size_t totalHardReferencesBytes = 0;
for (const SasquatchData& asset: assets)
{
totalFlatbufferBytes += asset.m_flatbuffer.size();
totalHardReferencesBytes += asset.m_hardReferences.size() * UUID::UUID_BYTE_SIZE;
}
{
SasquatchWriter writer {File {SASQUATCH_ENGINEBENCHMARKS_LOCATION},
assets.size(),
totalFlatbufferBytes,
totalHardReferencesBytes};
for (const SasquatchData& asset: assets)
{
writer.WriteAsset(asset.m_uuid, asset.m_flatbuffer, asset.m_hardReferences);
}
}
// The Sasquatch file is built exactly once for the entire benchmark process.
// SetUp is called before every calibration round (Google Benchmark doubles
// iteration counts until it reaches a stable measurement), so rebuilding
// the file each time would dominate the total benchmark time.
m_uuids = BuildData();
m_sasquatch.emplace(File {SASQUATCH_ENGINEBENCHMARKS_LOCATION});
}
void TearDown(benchmark::State&) override
void TearDown([[maybe_unused]] benchmark::State& p_state) override
{
m_sasquatch.reset();
}
@@ -135,7 +78,63 @@ class SasquatchFixture: public benchmark::Fixture
}
eastl::optional<Sasquatch> m_sasquatch;
eastl::vector<UUID> m_uuids;
eastl::span<const UUID> m_uuids;
private:
static const eastl::vector<UUID>& BuildData()
{
static const eastl::vector<UUID> s_uuids = []()
{
File {SASQUATCH_ENGINEBENCHMARKS_LOCATION}.Delete();
eastl::vector<UUID> uuids;
eastl::vector<eastl::vector<std::byte>> flatbuffers;
eastl::vector<eastl::vector<UUID>> hardReferences;
uuids.reserve(ASSET_COUNT);
flatbuffers.reserve(ASSET_COUNT);
hardReferences.reserve(ASSET_COUNT);
for (std::uint32_t i = 0; i < ASSET_COUNT; ++i)
{
BenchmarkAsset asset;
asset.SetName(asset.GetHeader().uuid.ToString());
asset.GetAsset().payload.assign(ASSET_PAYLOAD_SIZE, std::uint8_t {0xAB});
for (std::uint32_t j = 0; j < REFS_PER_ASSET; ++j)
{
BenchmarkAssetReferred assetReferred;
assetReferred.SetName(assetReferred.GetHeader().uuid.ToString());
asset.GetAsset().refs.emplace_back(assetReferred.GetHeader().uuid);
}
eastl::vector<std::byte> flatbuffer = asset.Pack();
hardReferences.push_back(asset.GetHardReferences(flatbuffer));
flatbuffers.push_back(std::move(flatbuffer));
uuids.push_back(asset.GetHeader().uuid);
}
std::size_t totalFlatbufferBytes = 0;
std::size_t totalHardReferencesBytes = 0;
for (std::size_t i = 0; i < uuids.size(); ++i)
{
totalFlatbufferBytes += flatbuffers[i].size();
totalHardReferencesBytes += hardReferences[i].size() * UUID::UUID_BYTE_SIZE;
}
SasquatchWriter writer {File {SASQUATCH_ENGINEBENCHMARKS_LOCATION},
uuids.size(),
totalFlatbufferBytes,
totalHardReferencesBytes};
for (std::size_t i = 0; i < uuids.size(); ++i)
{
writer.WriteAsset(uuids[i], flatbuffers[i], hardReferences[i]);
}
return uuids;
}();
return s_uuids;
}
};
/****************************************************************************************/
@@ -149,9 +148,10 @@ BENCHMARK_DEFINE_F(SasquatchFixture, GetAssetHardReferences)(benchmark::State& s
}
state.SetItemsProcessed(state.iterations());
state.SetBytesProcessed(static_cast<std::int64_t>(state.iterations()) * REFS_PER_ASSET * UUID::UUID_BYTE_SIZE);
}
BENCHMARK_REGISTER_F(SasquatchFixture, GetAssetHardReferences)->Name("Sasquatch/GetAssetHardReferences");
BENCHMARK_REGISTER_F(SasquatchFixture, GetAssetHardReferences)->Name("Sasquatch/GetAssetHardReferences")->UseRealTime();
/****************************************************************************************/
@@ -170,6 +170,8 @@ BENCHMARK_DEFINE_F(SasquatchFixture, GetAssetsHardReferences)(benchmark::State&
}
state.SetItemsProcessed(state.iterations() * batchSize);
state.SetBytesProcessed(static_cast<std::int64_t>(state.iterations()) * batchSize * REFS_PER_ASSET *
UUID::UUID_BYTE_SIZE);
}
BENCHMARK_REGISTER_F(SasquatchFixture, GetAssetsHardReferences)
@@ -178,7 +180,8 @@ BENCHMARK_REGISTER_F(SasquatchFixture, GetAssetsHardReferences)
->Arg(8)
->Arg(64)
->Arg(512)
->Arg(4096);
->Arg(4096)
->UseRealTime();
/****************************************************************************************/
@@ -199,7 +202,7 @@ BENCHMARK_DEFINE_F(SasquatchFixture, GetAssetFlatbuffer)(benchmark::State& state
state.SetBytesProcessed(bytesProcessed);
}
BENCHMARK_REGISTER_F(SasquatchFixture, GetAssetFlatbuffer)->Name("Sasquatch/GetAssetFlatbuffer");
BENCHMARK_REGISTER_F(SasquatchFixture, GetAssetFlatbuffer)->Name("Sasquatch/GetAssetFlatbuffer")->UseRealTime();
/****************************************************************************************/
@@ -236,6 +239,7 @@ BENCHMARK_REGISTER_F(SasquatchFixture, GetAssetFlatbuffers)
->Arg(8)
->Arg(64)
->Arg(512)
->Arg(4096);
->Arg(4096)
->UseRealTime();
#endif
} // namespace Bigfoot
@@ -0,0 +1,391 @@
/*********************************************************************
* \file SerializationManager.cpp
*
* \author Romain BOULLARD
* \date August 2026
*********************************************************************/
#include <Engine/SerializationManager/SerializationManager.hpp>
#include <Engine/Asset/AssetLibrary.hpp>
#include <Engine/DataAccessor/DataAccessor.hpp>
#if defined BIGFOOT_TOOLMODE
#include <Engine/BigFile/BigFile.hpp>
#include <EngineBenchmarks/BigFileInfo_generated.hpp>
#elif defined BIGFOOT_GAME
#include <Engine/Sasquatch/Sasquatch.hpp>
#include <EngineBenchmarks/SasquatchInfo_generated.hpp>
#endif
#include <System/File/File.hpp>
#include <System/UUID/UUID.hpp>
#include <AssetsForBenchmarking/Asset/BenchmarkAsset.hpp>
#include <AssetsForBenchmarking/Asset/BenchmarkAssetReferred.hpp>
#include <EASTL/optional.h>
#include <EASTL/span.h>
#include <EASTL/vector.h>
#include <ankerl/unordered_dense.h>
#include <benchmark/benchmark.h>
#include <effolkronium/random.hpp>
#include <cstddef>
#include <cstdint>
#include <tuple>
namespace Bigfoot
{
using Random = effolkronium::random_static;
class SerializationManagerFixture: public benchmark::Fixture
{
protected:
static constexpr std::uint32_t ROOT_ASSET_COUNT = 20'000;
static constexpr std::uint32_t REFS_PER_ROOT = 4;
static constexpr std::size_t ASSET_PAYLOAD_SIZE = 256;
void SetUp([[maybe_unused]] benchmark::State& p_state) override
{
m_previousDataAccessor = g_dataAccessor;
m_previousAssetLibrary = g_activeAssetLibrary;
// The data store is populated exactly once for the entire benchmark process.
// SetUp is called before every calibration round (Google Benchmark doubles
// iteration counts until it reaches a stable measurement), so rebuilding
// the data store each time would dominate the total benchmark time.
static const SharedData& s_data = BuildData();
m_rootUuids = s_data.rootUuids;
m_leafUuids = s_data.leafUuids;
m_rootTotalBytes = &s_data.rootTotalBytes;
#if defined BIGFOOT_TOOLMODE
m_bigFile.emplace(File {BIGFILE_ENGINEBENCHMARKS_LOCATION});
SetDataAccessor(&*m_bigFile);
#elif defined BIGFOOT_GAME
m_sasquatch.emplace(File {SASQUATCH_ENGINEBENCHMARKS_LOCATION});
SetDataAccessor(&*m_sasquatch);
#endif
}
void TearDown([[maybe_unused]] benchmark::State& p_state) override
{
#if defined BIGFOOT_TOOLMODE
m_bigFile.reset();
#elif defined BIGFOOT_GAME
m_sasquatch.reset();
#endif
SetDataAccessor(m_previousDataAccessor);
SetActiveAssetLibrary(m_previousAssetLibrary);
}
/*
* Registers a fresh, empty AssetLibrary as the active one, so that every root and leaf asset appears unloaded
*
* \param p_library The library to register
* \param p_leafContainer The container to register leaves into
* \param p_rootContainer The container to register roots into
*/
static void ResetActiveLibrary(AssetLibrary& p_library,
AssetContainer<BenchmarkAssetReferred>& p_leafContainer,
AssetContainer<BenchmarkAsset>& p_rootContainer)
{
std::ignore = p_library.Insert(&p_leafContainer);
std::ignore = p_library.Insert(&p_rootContainer);
SetActiveAssetLibrary(&p_library);
}
[[nodiscard]]
eastl::vector<UUID> RandomRootBatch(const std::size_t p_batchSize) const
{
eastl::vector<UUID> batch;
batch.reserve(p_batchSize);
for (std::size_t i = 0; i < p_batchSize; ++i)
{
batch.push_back(m_rootUuids[Random::get<std::size_t>(0, m_rootUuids.size() - 1)]);
}
return batch;
}
/*
* Total flatbuffer bytes (root + its leaves) that loading p_roots will actually read, deduplicated the same way
* SerializationManager::LoadAssets deduplicates its own transitive discovery
*
* \param p_roots The root assets that would be loaded
* \return The total flatbuffer bytes across the unique roots
*/
[[nodiscard]]
std::int64_t TotalBytes(const eastl::vector<UUID>& p_roots) const
{
ankerl::unordered_dense::set<UUID> unique;
unique.reserve(p_roots.size());
for (const UUID& uuid: p_roots)
{
unique.insert(uuid);
}
std::int64_t bytes = 0;
for (const UUID& uuid: unique)
{
bytes += static_cast<std::int64_t>(m_rootTotalBytes->at(uuid));
}
return bytes;
}
DataAccessor* m_previousDataAccessor = nullptr;
AssetLibrary* m_previousAssetLibrary = nullptr;
eastl::span<const UUID> m_rootUuids;
eastl::span<const UUID> m_leafUuids;
const ankerl::unordered_dense::map<UUID, std::size_t>* m_rootTotalBytes = nullptr;
#if defined BIGFOOT_TOOLMODE
eastl::optional<BigFile> m_bigFile;
#elif defined BIGFOOT_GAME
eastl::optional<Sasquatch> m_sasquatch;
#endif
private:
struct SharedData
{
eastl::vector<UUID> rootUuids;
eastl::vector<UUID> leafUuids;
ankerl::unordered_dense::map<UUID, std::size_t> rootTotalBytes;
};
static const SharedData& BuildData()
{
static const SharedData s_data = []()
{
SharedData data;
data.rootUuids.reserve(ROOT_ASSET_COUNT);
data.leafUuids.reserve(ROOT_ASSET_COUNT * REFS_PER_ROOT);
data.rootTotalBytes.reserve(ROOT_ASSET_COUNT);
eastl::vector<UUID> uuids;
eastl::vector<eastl::vector<std::byte>> flatbuffers;
eastl::vector<eastl::vector<UUID>> hardReferences;
uuids.reserve(ROOT_ASSET_COUNT * (1 + REFS_PER_ROOT));
flatbuffers.reserve(uuids.capacity());
hardReferences.reserve(uuids.capacity());
for (std::uint32_t i = 0; i < ROOT_ASSET_COUNT; ++i)
{
BenchmarkAsset root;
root.SetName(root.GetHeader().uuid.ToString());
root.GetAsset().payload.assign(ASSET_PAYLOAD_SIZE, std::uint8_t {0xAB});
std::size_t totalBytes = 0;
for (std::uint32_t j = 0; j < REFS_PER_ROOT; ++j)
{
BenchmarkAssetReferred leaf;
leaf.SetName(leaf.GetHeader().uuid.ToString());
root.GetAsset().refs.emplace_back(leaf.GetHeader().uuid);
eastl::vector<std::byte> leafFlatbuffer = leaf.Pack();
totalBytes += leafFlatbuffer.size();
data.leafUuids.push_back(leaf.GetHeader().uuid);
uuids.push_back(leaf.GetHeader().uuid);
hardReferences.push_back(leaf.GetHardReferences(leafFlatbuffer));
flatbuffers.push_back(std::move(leafFlatbuffer));
}
eastl::vector<std::byte> rootFlatbuffer = root.Pack();
totalBytes += rootFlatbuffer.size();
data.rootTotalBytes.emplace(root.GetHeader().uuid, totalBytes);
data.rootUuids.push_back(root.GetHeader().uuid);
uuids.push_back(root.GetHeader().uuid);
hardReferences.push_back(root.GetHardReferences(rootFlatbuffer));
flatbuffers.push_back(std::move(rootFlatbuffer));
}
#if defined BIGFOOT_TOOLMODE
BigFile bigFile {File { BIGFILE_ENGINEBENCHMARKS_LOCATION }};
bigFile.Clear();
bigFile.SaveAssetFlatbuffers(uuids, flatbuffers, hardReferences);
#elif defined BIGFOOT_GAME
std::size_t totalFlatbufferBytes = 0;
std::size_t totalHardReferencesBytes = 0;
for (std::size_t i = 0; i < uuids.size(); ++i)
{
totalFlatbufferBytes += flatbuffers[i].size();
totalHardReferencesBytes += hardReferences[i].size() * UUID::UUID_BYTE_SIZE;
}
File {SASQUATCH_ENGINEBENCHMARKS_LOCATION}.Delete();
SasquatchWriter writer {File {SASQUATCH_ENGINEBENCHMARKS_LOCATION},
uuids.size(),
totalFlatbufferBytes,
totalHardReferencesBytes};
for (std::size_t i = 0; i < uuids.size(); ++i)
{
writer.WriteAsset(uuids[i], flatbuffers[i], hardReferences[i]);
}
#endif
return data;
}();
return s_data;
}
};
/****************************************************************************************/
BENCHMARK_DEFINE_F(SerializationManagerFixture, LoadAsset)(benchmark::State& state)
{
std::int64_t bytesProcessed = 0;
for (auto _: state)
{
state.PauseTiming();
AssetLibrary library;
// leafContainer must outlive rootContainer: the loaded root's HardReferences release into leafContainer's
// handles on destruction, so declaring it second would tear it down first and use-after-free those handles.
AssetContainer<BenchmarkAssetReferred> leafContainer;
AssetContainer<BenchmarkAsset> rootContainer;
ResetActiveLibrary(library, leafContainer, rootContainer);
const UUID uuid = m_rootUuids[Random::get<std::size_t>(0, m_rootUuids.size() - 1)];
const std::size_t uuidBytes = m_rootTotalBytes->at(uuid);
state.ResumeTiming();
SerializationManager::LoadAsset(uuid);
bytesProcessed += static_cast<std::int64_t>(uuidBytes);
}
state.SetItemsProcessed(state.iterations() * (1 + REFS_PER_ROOT));
state.SetBytesProcessed(bytesProcessed);
}
BENCHMARK_REGISTER_F(SerializationManagerFixture, LoadAsset)->Name("SerializationManager/LoadAsset")->UseRealTime();
/****************************************************************************************/
BENCHMARK_DEFINE_F(SerializationManagerFixture, LoadAssets)(benchmark::State& state)
{
const auto batchSize = static_cast<std::size_t>(state.range(0));
std::int64_t bytesProcessed = 0;
for (auto _: state)
{
state.PauseTiming();
AssetLibrary library;
// leafContainer must outlive rootContainer, see the same comment in the LoadAsset benchmark above.
AssetContainer<BenchmarkAssetReferred> leafContainer;
AssetContainer<BenchmarkAsset> rootContainer;
ResetActiveLibrary(library, leafContainer, rootContainer);
const eastl::vector<UUID> batch = RandomRootBatch(batchSize);
const std::int64_t batchBytes = TotalBytes(batch);
state.ResumeTiming();
SerializationManager::LoadAssets(batch);
bytesProcessed += batchBytes;
}
state.SetItemsProcessed(state.iterations() * batchSize * (1 + REFS_PER_ROOT));
state.SetBytesProcessed(bytesProcessed);
}
BENCHMARK_REGISTER_F(SerializationManagerFixture, LoadAssets)
->Name("SerializationManager/LoadAssets")
->Arg(1)
->Arg(8)
->Arg(64)
->Arg(512)
->Arg(4096)
->UseRealTime();
/****************************************************************************************/
#if defined BIGFOOT_TOOLMODE
BENCHMARK_DEFINE_F(SerializationManagerFixture, SaveAsset)(benchmark::State& state)
{
AssetLibrary library;
AssetContainer<BenchmarkAsset> container;
std::ignore = library.Insert(&container);
SetActiveAssetLibrary(&library);
std::int64_t bytesProcessed = 0;
for (auto _: state)
{
state.PauseTiming();
auto* asset = CreateAsset<BenchmarkAsset>();
asset->SetName(asset->GetHeader().uuid.ToString());
asset->GetAsset().payload.assign(ASSET_PAYLOAD_SIZE, std::uint8_t {0xAB});
for (std::uint32_t j = 0; j < REFS_PER_ROOT; ++j)
{
asset->GetAsset().refs.emplace_back(m_leafUuids[Random::get<std::size_t>(0, m_leafUuids.size() - 1)]);
}
const UUID uuid = asset->GetHeader().uuid;
const std::size_t assetBytes = asset->Pack().size();
bytesProcessed += static_cast<std::int64_t>(assetBytes);
state.ResumeTiming();
benchmark::DoNotOptimize(SerializationManager::SaveAsset(uuid));
}
state.SetItemsProcessed(state.iterations());
state.SetBytesProcessed(bytesProcessed);
}
BENCHMARK_REGISTER_F(SerializationManagerFixture, SaveAsset)->Name("SerializationManager/SaveAsset")->UseRealTime();
/****************************************************************************************/
BENCHMARK_DEFINE_F(SerializationManagerFixture, SaveAssets)(benchmark::State& state)
{
const auto batchSize = static_cast<std::size_t>(state.range(0));
AssetLibrary library;
AssetContainer<BenchmarkAsset> container;
std::ignore = library.Insert(&container);
SetActiveAssetLibrary(&library);
std::int64_t bytesProcessed = 0;
for (auto _: state)
{
state.PauseTiming();
eastl::vector<UUID> uuids;
uuids.reserve(batchSize);
std::size_t batchBytes = 0;
for (std::size_t i = 0; i < batchSize; ++i)
{
auto* asset = CreateAsset<BenchmarkAsset>();
asset->SetName(asset->GetHeader().uuid.ToString());
asset->GetAsset().payload.assign(ASSET_PAYLOAD_SIZE, std::uint8_t {0xAB});
for (std::uint32_t j = 0; j < REFS_PER_ROOT; ++j)
{
asset->GetAsset().refs.emplace_back(m_leafUuids[Random::get<std::size_t>(0, m_leafUuids.size() - 1)]);
}
batchBytes += asset->Pack().size();
uuids.push_back(asset->GetHeader().uuid);
}
state.ResumeTiming();
benchmark::DoNotOptimize(SerializationManager::SaveAssets(uuids));
bytesProcessed += static_cast<std::int64_t>(batchBytes);
}
state.SetItemsProcessed(state.iterations() * batchSize);
state.SetBytesProcessed(bytesProcessed);
}
BENCHMARK_REGISTER_F(SerializationManagerFixture, SaveAssets)
->Name("SerializationManager/SaveAssets")
->Arg(1)
->Arg(8)
->Arg(64)
->Arg(512)
->UseRealTime();
#endif
} // namespace Bigfoot
@@ -44,7 +44,7 @@ class SasquatchBakerFixture: public benchmark::Fixture
for (std::uint32_t i = 0; i < ASSET_COUNT; ++i)
{
BenchmarkAsset asset;
asset.SetName(asset.GetHeader().uuid.ToString().c_str());
asset.SetName(asset.GetHeader().uuid.ToString());
asset.GetAsset().payload.assign(ASSET_PAYLOAD_SIZE, std::uint8_t {0xAB});
const eastl::vector<std::byte> flatbuffer = asset.Pack();
@@ -1,10 +1,10 @@
/*********************************************************************
* \file Asset.cpp
* \file AssetBase.cpp
*
* \author Romain BOULLARD
* \date April 2026
*********************************************************************/
#include <Engine/Asset/Asset.hpp>
#include <Engine/Asset/AssetBase.hpp>
#include <Engine/Asset/Reference_generated.hpp>
@@ -40,14 +40,7 @@ eastl::vector<UUID> AssetBase::HardReferenceVisitor::GetUUIDs() const
{
eastl::vector<UUID> uuids;
uuids.reserve(m_uuids.size());
std::transform(m_uuids.begin(),
m_uuids.end(),
eastl::back_inserter(uuids),
[](const UUID& p_uuid)
{
return p_uuid;
});
std::copy(m_uuids.begin(), m_uuids.end(), eastl::back_inserter(uuids));
return uuids;
}
@@ -63,7 +56,8 @@ void AssetBase::HardReferenceVisitor::Visit(const flatbuffers::ElementaryType p_
return;
}
const ::Flat::Bigfoot::HardReference* hardReference = std::bit_cast<const ::Flat::Bigfoot::HardReference*>(p_val);
const ::Flat::Bigfoot::HardReference* hardReference = reinterpret_cast<const ::Flat::Bigfoot::HardReference*>(
p_val);
m_uuids.emplace(flatbuffers::UnPack(hardReference->uuid()));
}
} // namespace Bigfoot
+11 -11
View File
@@ -128,10 +128,10 @@ void AssetContainerBase::QueueForRemoval(const UUID& p_uuid)
void AssetContainerBase::CancelRemoval(const UUID& p_uuid)
{
const auto it = eastl::find(m_pendingRemovalUuids.begin(), m_pendingRemovalUuids.end(), p_uuid);
if (it != m_pendingRemovalUuids.end())
auto* const pendingIt = eastl::find(m_pendingRemovalUuids.begin(), m_pendingRemovalUuids.end(), p_uuid);
if (pendingIt != m_pendingRemovalUuids.end())
{
m_pendingRemovalUuids.erase_unsorted(it);
m_pendingRemovalUuids.erase_unsorted(pendingIt);
}
}
@@ -160,29 +160,29 @@ bool AssetContainerBase::IsMarkedForRemove(const UUID& p_uuid)
AssetContainerBase::Entry* AssetContainerBase::FindEntry(const UUID& p_uuid)
{
const auto it = m_uuidToEntry.find(p_uuid);
return it != m_uuidToEntry.end() ? &it->second : nullptr;
const auto entryIt = m_uuidToEntry.find(p_uuid);
return entryIt != m_uuidToEntry.end() ? &entryIt->second : nullptr;
}
/****************************************************************************************/
const AssetContainerBase::Entry* AssetContainerBase::FindEntry(const UUID& p_uuid) const
{
const auto it = m_uuidToEntry.find(p_uuid);
return it != m_uuidToEntry.end() ? &it->second : nullptr;
const auto entryIt = m_uuidToEntry.find(p_uuid);
return entryIt != m_uuidToEntry.end() ? &entryIt->second : nullptr;
}
/****************************************************************************************/
AssetContainerBase::Entry& AssetContainerBase::GetOrCreateEntry(const UUID& p_uuid)
{
auto [it, inserted] = m_uuidToEntry.try_emplace(p_uuid);
auto [entryIt, inserted] = m_uuidToEntry.try_emplace(p_uuid);
if (inserted)
{
it->second.m_handleSlotKey = m_handles.Insert(this, p_uuid);
it->second.m_handle = m_handles.Get(it->second.m_handleSlotKey);
entryIt->second.m_handleSlotKey = m_handles.Insert(this, p_uuid);
entryIt->second.m_handle = m_handles.Get(entryIt->second.m_handleSlotKey);
}
return it->second;
return entryIt->second;
}
} // namespace Bigfoot
@@ -69,9 +69,9 @@ bool AssetLibrary::IsLoaded(const UUID& p_uuid) const
/****************************************************************************************/
void AssetLibrary::ProcessPendingRemovals() {
for (const auto [typeId, container] : m_assetContainers)
void AssetLibrary::ProcessPendingRemovals()
{
for (const auto [typeId, container]: m_assetContainers)
{
container->ProcessPendingRemovals();
}
+94 -82
View File
@@ -8,8 +8,9 @@
#include <Engine/EngineAssertHandler.hpp>
#include <Utils/Format.hpp>
#include <EASTL/algorithm.h>
#include <fmt/format.h>
namespace Bigfoot
{
@@ -149,9 +150,9 @@ eastl::vector<eastl::vector<std::byte>> BigFile::GetAssetFlatbuffers(const eastl
placeholders += "?";
}
const std::string sql = fmt::format("SELECT UUID, Asset FROM Asset WHERE UUID IN ({});", placeholders);
const eastl::string sql = Format("SELECT UUID, Asset FROM Asset WHERE UUID IN ({});", placeholders);
BigFile::Request assetRequest {*this, sql.c_str()};
BigFile::Request assetRequest {*this, sql};
for (std::size_t i = 0; i < chunkSize; ++i)
{
assetRequest.Bind(static_cast<std::uint32_t>(i + 1), distinctUUIDs[chunkStart + i].ToBytes());
@@ -159,19 +160,19 @@ eastl::vector<eastl::vector<std::byte>> BigFile::GetAssetFlatbuffers(const eastl
while (assetRequest.Step())
{
const eastl::span<const std::byte, UUID::UUID_BYTE_SIZE> rawUUID =
static_cast<eastl::span<const std::byte>>(assetRequest.Get(0));
const UUID uuid {std::span<const std::byte, UUID::UUID_BYTE_SIZE> {rawUUID.begin(), rawUUID.end()}};
const std::span<const std::byte, UUID::UUID_BYTE_SIZE> rawUUID {
static_cast<std::span<const std::byte>>(assetRequest.Get(0))};
const UUID uuid {rawUUID};
const auto it = uuidToIndices.find(uuid);
const auto indicesIt = uuidToIndices.find(uuid);
ASSERT(EngineAssertHandler,
it != uuidToIndices.end(),
indicesIt != uuidToIndices.end(),
"Returned UUID {} not found in requested UUIDs",
uuid);
const eastl::span<const std::byte> flatbuffer = assetRequest.Get(1);
for (const std::size_t index: it->second)
for (const std::size_t index: indicesIt->second)
{
flatbuffers[index].assign(flatbuffer.begin(), flatbuffer.end());
}
@@ -191,9 +192,9 @@ eastl::vector<UUID> BigFile::GetAssetHardReferences(const UUID& p_uuid) const
eastl::vector<UUID> hardReferences;
while (hardReferencesRequest.Step())
{
const eastl::span<const std::byte, UUID::UUID_BYTE_SIZE> rawUUID = static_cast<eastl::span<const std::byte>>(
hardReferencesRequest.Get(0));
hardReferences.emplace_back(std::span<const std::byte, UUID::UUID_BYTE_SIZE>(rawUUID.begin(), rawUUID.end()));
const std::span<const std::byte, UUID::UUID_BYTE_SIZE> rawUUID {
static_cast<std::span<const std::byte>>(hardReferencesRequest.Get(0))};
hardReferences.emplace_back(rawUUID);
}
return hardReferences;
@@ -244,10 +245,10 @@ eastl::vector<eastl::vector<UUID>> BigFile::GetAssetsHardReferences(eastl::span<
placeholders += "?";
}
const std::string sql = fmt::format("SELECT UUID, HardReference FROM AssetHardReference WHERE UUID IN ({});",
placeholders);
const eastl::string sql = Format("SELECT UUID, HardReference FROM AssetHardReference WHERE UUID IN ({});",
placeholders);
BigFile::Request hardReferencesRequest {*this, sql.c_str()};
BigFile::Request hardReferencesRequest {*this, sql};
for (std::size_t i = 0; i < chunkSize; ++i)
{
hardReferencesRequest.Bind(static_cast<std::uint32_t>(i + 1), distinctUUIDs[chunkStart + i].ToBytes());
@@ -255,25 +256,22 @@ eastl::vector<eastl::vector<UUID>> BigFile::GetAssetsHardReferences(eastl::span<
while (hardReferencesRequest.Step())
{
const eastl::span<const std::byte, UUID::UUID_BYTE_SIZE> rawOwnerUUID =
static_cast<eastl::span<const std::byte>>(hardReferencesRequest.Get(0));
const UUID ownerUUID {
std::span<const std::byte, UUID::UUID_BYTE_SIZE> {rawOwnerUUID.begin(), rawOwnerUUID.end()}};
const std::span<const std::byte, UUID::UUID_BYTE_SIZE> rawOwnerUUID {
static_cast<std::span<const std::byte>>(hardReferencesRequest.Get(0))};
const UUID ownerUUID {rawOwnerUUID};
const auto it = uuidToIndices.find(ownerUUID);
const auto indicesIt = uuidToIndices.find(ownerUUID);
ASSERT(EngineAssertHandler,
it != uuidToIndices.end(),
indicesIt != uuidToIndices.end(),
"Returned UUID {} not found in requested UUIDs",
ownerUUID);
const eastl::span<const std::byte, UUID::UUID_BYTE_SIZE> rawHardReference =
static_cast<eastl::span<const std::byte>>(hardReferencesRequest.Get(1));
const std::span<const std::byte, UUID::UUID_BYTE_SIZE> rawHardReference {
static_cast<std::span<const std::byte>>(hardReferencesRequest.Get(1))};
for (const std::size_t index: it->second)
for (const std::size_t index: indicesIt->second)
{
hardReferences[index].emplace_back(
std::span<const std::byte, UUID::UUID_BYTE_SIZE> {rawHardReference.begin(),
rawHardReference.end()});
hardReferences[index].emplace_back(rawHardReference);
}
}
}
@@ -342,11 +340,11 @@ eastl::vector<eastl::optional<BigFile::AssetTime>> BigFile::GetAssetsTime(const
placeholders += "?";
}
const std::string sql = fmt::format(
const eastl::string sql = Format(
"SELECT UUID, CreateTime, ModificationTime FROM AssetMetadata WHERE UUID IN ({});",
placeholders);
BigFile::Request timeRequest {*this, sql.c_str()};
BigFile::Request timeRequest {*this, sql};
for (std::size_t i = 0; i < chunkSize; ++i)
{
timeRequest.Bind(static_cast<std::uint32_t>(i + 1), distinctUUIDs[chunkStart + i].ToBytes());
@@ -354,20 +352,20 @@ eastl::vector<eastl::optional<BigFile::AssetTime>> BigFile::GetAssetsTime(const
while (timeRequest.Step())
{
const eastl::span<const std::byte, UUID::UUID_BYTE_SIZE> rawUUID =
static_cast<eastl::span<const std::byte>>(timeRequest.Get(0));
const UUID uuid {std::span<const std::byte, UUID::UUID_BYTE_SIZE> {rawUUID.begin(), rawUUID.end()}};
const std::span<const std::byte, UUID::UUID_BYTE_SIZE> rawUUID {
static_cast<std::span<const std::byte>>(timeRequest.Get(0))};
const UUID uuid {rawUUID};
const auto it = uuidToIndices.find(uuid);
const auto indicesIt = uuidToIndices.find(uuid);
ASSERT(EngineAssertHandler,
it != uuidToIndices.end(),
indicesIt != uuidToIndices.end(),
"Returned UUID {} not found in requested UUIDs",
uuid);
const AssetTime assetTime {.m_creationTime = Time {static_cast<std::uint64_t>(timeRequest.Get(1))},
.m_modificationTime = Time {static_cast<std::uint64_t>(timeRequest.Get(2))}};
for (const std::size_t index: it->second)
for (const std::size_t index: indicesIt->second)
{
times[index] = assetTime;
}
@@ -403,6 +401,7 @@ void BigFile::SaveAssetFlatbuffer(const UUID& p_uuid,
deleteHardReferencesRequest.Execute();
constexpr std::size_t HARDREF_PARAMS_PER_ROW = 2;
constexpr std::size_t HARDREF_PLACEHOLDER_RESERVE_CHARS_PER_ROW = 8;
const std::size_t maxHardRefRowsPerStatement = static_cast<std::size_t>(
sqlite3_limit(m_db, SQLITE_LIMIT_VARIABLE_NUMBER, -1)) /
HARDREF_PARAMS_PER_ROW;
@@ -412,7 +411,7 @@ void BigFile::SaveAssetFlatbuffer(const UUID& p_uuid,
const std::size_t chunkSize = eastl::min(maxHardRefRowsPerStatement, p_hardReferences.size() - chunkStart);
eastl::string hardReferencePlaceholders;
hardReferencePlaceholders.reserve(chunkSize * 8);
hardReferencePlaceholders.reserve(chunkSize * HARDREF_PLACEHOLDER_RESERVE_CHARS_PER_ROW);
for (std::size_t i = 0; i < chunkSize; ++i)
{
if (i > 0)
@@ -422,12 +421,11 @@ void BigFile::SaveAssetFlatbuffer(const UUID& p_uuid,
hardReferencePlaceholders += "(?, ?)";
}
const std::string hardReferenceSQL = fmt::format(
"INSERT INTO AssetHardReference (UUID, HardReference) VALUES {} "
"ON CONFLICT(UUID, HardReference) DO NOTHING;",
hardReferencePlaceholders);
const eastl::string hardReferenceSQL = Format("INSERT INTO AssetHardReference (UUID, HardReference) VALUES {} "
"ON CONFLICT(UUID, HardReference) DO NOTHING;",
hardReferencePlaceholders);
BigFile::Request hardReferenceRequest {*this, hardReferenceSQL.c_str()};
BigFile::Request hardReferenceRequest {*this, hardReferenceSQL};
std::uint32_t bindIndex = 1;
for (std::size_t i = 0; i < chunkSize; ++i)
{
@@ -458,6 +456,8 @@ void BigFile::SaveAssetFlatbuffers(const eastl::span<const UUID> p_uuids,
BeginTransaction();
constexpr std::size_t METADATA_PARAMS_PER_ROW = 4;
constexpr std::size_t METADATA_PLACEHOLDER_RESERVE_CHARS_PER_ROW = 14;
constexpr std::size_t ASSET_PLACEHOLDER_RESERVE_CHARS_PER_ROW = 8;
const std::size_t maxRowsPerStatement = static_cast<std::size_t>(
sqlite3_limit(m_db, SQLITE_LIMIT_VARIABLE_NUMBER, -1)) /
METADATA_PARAMS_PER_ROW;
@@ -467,7 +467,7 @@ void BigFile::SaveAssetFlatbuffers(const eastl::span<const UUID> p_uuids,
const std::size_t chunkSize = eastl::min(maxRowsPerStatement, p_uuids.size() - chunkStart);
eastl::string metadataPlaceholders;
metadataPlaceholders.reserve(chunkSize * 14);
metadataPlaceholders.reserve(chunkSize * METADATA_PLACEHOLDER_RESERVE_CHARS_PER_ROW);
for (std::size_t i = 0; i < chunkSize; ++i)
{
if (i > 0)
@@ -477,11 +477,11 @@ void BigFile::SaveAssetFlatbuffers(const eastl::span<const UUID> p_uuids,
metadataPlaceholders += "(?)";
}
const std::string metadataSQL = fmt::format(
const eastl::string metadataSQL = Format(
"INSERT INTO AssetMetadata (UUID) VALUES {} ON CONFLICT(UUID) DO NOTHING;",
metadataPlaceholders);
BigFile::Request metadataRequest {*this, metadataSQL.c_str()};
BigFile::Request metadataRequest {*this, metadataSQL};
std::uint32_t metadataBindIndex = 1;
for (std::size_t i = 0; i < chunkSize; ++i)
{
@@ -490,7 +490,7 @@ void BigFile::SaveAssetFlatbuffers(const eastl::span<const UUID> p_uuids,
metadataRequest.Execute();
eastl::string assetPlaceholders;
assetPlaceholders.reserve(chunkSize * 8);
assetPlaceholders.reserve(chunkSize * ASSET_PLACEHOLDER_RESERVE_CHARS_PER_ROW);
for (std::size_t i = 0; i < chunkSize; ++i)
{
if (i > 0)
@@ -500,11 +500,11 @@ void BigFile::SaveAssetFlatbuffers(const eastl::span<const UUID> p_uuids,
assetPlaceholders += "(?, ?)";
}
const std::string assetSQL = fmt::format(
const eastl::string assetSQL = Format(
"INSERT INTO Asset (UUID, Asset) VALUES {} ON CONFLICT(UUID) DO UPDATE SET Asset = excluded.Asset;",
assetPlaceholders);
BigFile::Request assetRequest {*this, assetSQL.c_str()};
BigFile::Request assetRequest {*this, assetSQL};
std::uint32_t assetBindIndex = 1;
for (std::size_t i = 0; i < chunkSize; ++i)
{
@@ -525,10 +525,10 @@ void BigFile::SaveAssetFlatbuffers(const eastl::span<const UUID> p_uuids,
deleteInPlaceholders += "?";
}
const std::string deleteHardReferencesSQL = fmt::format("DELETE FROM AssetHardReference WHERE UUID IN ({});",
deleteInPlaceholders);
const eastl::string deleteHardReferencesSQL = Format("DELETE FROM AssetHardReference WHERE UUID IN ({});",
deleteInPlaceholders);
BigFile::Request deleteHardReferencesRequest {*this, deleteHardReferencesSQL.c_str()};
BigFile::Request deleteHardReferencesRequest {*this, deleteHardReferencesSQL};
for (std::size_t i = 0; i < chunkSize; ++i)
{
deleteHardReferencesRequest.Bind(static_cast<std::uint32_t>(i + 1), p_uuids[chunkStart + i].ToBytes());
@@ -545,6 +545,7 @@ void BigFile::SaveAssetFlatbuffers(const eastl::span<const UUID> p_uuids,
}
constexpr std::size_t HARDREF_PARAMS_PER_ROW = 2;
constexpr std::size_t HARDREF_PLACEHOLDER_RESERVE_CHARS_PER_ROW = 8;
const std::size_t maxHardRefRowsPerStatement = static_cast<std::size_t>(
sqlite3_limit(m_db, SQLITE_LIMIT_VARIABLE_NUMBER, -1)) /
HARDREF_PARAMS_PER_ROW;
@@ -556,7 +557,7 @@ void BigFile::SaveAssetFlatbuffers(const eastl::span<const UUID> p_uuids,
hardReferencePairs.size() - hardRefChunkStart);
eastl::string hardReferencePlaceholders;
hardReferencePlaceholders.reserve(hardRefChunkSize * 8);
hardReferencePlaceholders.reserve(hardRefChunkSize * HARDREF_PLACEHOLDER_RESERVE_CHARS_PER_ROW);
for (std::size_t i = 0; i < hardRefChunkSize; ++i)
{
if (i > 0)
@@ -566,12 +567,12 @@ void BigFile::SaveAssetFlatbuffers(const eastl::span<const UUID> p_uuids,
hardReferencePlaceholders += "(?, ?)";
}
const std::string hardReferenceSQL = fmt::format(
const eastl::string hardReferenceSQL = Format(
"INSERT INTO AssetHardReference (UUID, HardReference) VALUES {} "
"ON CONFLICT(UUID, HardReference) DO NOTHING;",
hardReferencePlaceholders);
BigFile::Request hardReferenceRequest {*this, hardReferenceSQL.c_str()};
BigFile::Request hardReferenceRequest {*this, hardReferenceSQL};
std::uint32_t bindIndex = 1;
for (std::size_t i = 0; i < hardRefChunkSize; ++i)
{
@@ -604,7 +605,7 @@ BigFile::Request::Request(const BigFile& p_bigFile, const eastl::string_view p_r
[[maybe_unused]]
const int result = sqlite3_prepare_v2(m_db,
p_request.data(),
static_cast<std::uint32_t>(p_request.size()),
static_cast<int>(p_request.size()),
&m_statement,
nullptr);
CRITICAL_ASSERT(EngineAssertHandler,
@@ -618,11 +619,11 @@ BigFile::Request::Request(const BigFile& p_bigFile, const eastl::string_view p_r
void BigFile::Request::Bind(const std::uint32_t p_index, const std::int32_t p_value)
{
ASSERT(EngineAssertHandler,
(p_index >= 1) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
(p_index >= 1U) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
"Invalid index for statement");
[[maybe_unused]]
const int result = sqlite3_bind_int(m_statement, p_index, p_value);
const int result = sqlite3_bind_int(m_statement, static_cast<int>(p_index), p_value);
ASSERT(EngineAssertHandler, result == SQLITE_OK, "Failed to bind value for statement: {}", sqlite3_errmsg(m_db));
}
@@ -631,11 +632,11 @@ void BigFile::Request::Bind(const std::uint32_t p_index, const std::int32_t p_va
void BigFile::Request::Bind(const std::uint32_t p_index, const std::uint32_t p_value)
{
ASSERT(EngineAssertHandler,
(p_index >= 1) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
(p_index >= 1U) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
"Invalid index for statement");
[[maybe_unused]]
const int result = sqlite3_bind_int(m_statement, p_index, p_value);
const int result = sqlite3_bind_int(m_statement, static_cast<int>(p_index), static_cast<int>(p_value));
ASSERT(EngineAssertHandler, result == SQLITE_OK, "Failed to bind value for statement: {}", sqlite3_errmsg(m_db));
}
@@ -644,11 +645,11 @@ void BigFile::Request::Bind(const std::uint32_t p_index, const std::uint32_t p_v
void BigFile::Request::Bind(const std::uint32_t p_index, const std::int64_t p_value)
{
ASSERT(EngineAssertHandler,
(p_index >= 1) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
(p_index >= 1U) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
"Invalid index for statement");
[[maybe_unused]]
const int result = sqlite3_bind_int64(m_statement, p_index, p_value);
const int result = sqlite3_bind_int64(m_statement, static_cast<int>(p_index), p_value);
ASSERT(EngineAssertHandler, result == SQLITE_OK, "Failed to bind value for statement: {}", sqlite3_errmsg(m_db));
}
@@ -657,11 +658,11 @@ void BigFile::Request::Bind(const std::uint32_t p_index, const std::int64_t p_va
void BigFile::Request::Bind(const std::uint32_t p_index, const std::uint64_t p_value)
{
ASSERT(EngineAssertHandler,
(p_index >= 1) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
(p_index >= 1U) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
"Invalid index for statement");
[[maybe_unused]]
const int result = sqlite3_bind_int64(m_statement, p_index, std::bit_cast<std::int64_t>(p_value));
const int result = sqlite3_bind_int64(m_statement, static_cast<int>(p_index), std::bit_cast<std::int64_t>(p_value));
ASSERT(EngineAssertHandler, result == SQLITE_OK, "Failed to bind value for statement: {}", sqlite3_errmsg(m_db));
}
@@ -670,11 +671,11 @@ void BigFile::Request::Bind(const std::uint32_t p_index, const std::uint64_t p_v
void BigFile::Request::Bind(const std::uint32_t p_index, const float p_value)
{
ASSERT(EngineAssertHandler,
(p_index >= 1) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
(p_index >= 1U) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
"Invalid index for statement");
[[maybe_unused]]
const int result = sqlite3_bind_double(m_statement, p_index, p_value);
const int result = sqlite3_bind_double(m_statement, static_cast<int>(p_index), p_value);
ASSERT(EngineAssertHandler, result == SQLITE_OK, "Failed to bind value for statement: {}", sqlite3_errmsg(m_db));
}
@@ -683,11 +684,11 @@ void BigFile::Request::Bind(const std::uint32_t p_index, const float p_value)
void BigFile::Request::Bind(const std::uint32_t p_index, const double p_value)
{
ASSERT(EngineAssertHandler,
(p_index >= 1) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
(p_index >= 1U) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
"Invalid index for statement");
[[maybe_unused]]
const int result = sqlite3_bind_double(m_statement, p_index, p_value);
const int result = sqlite3_bind_double(m_statement, static_cast<int>(p_index), p_value);
ASSERT(EngineAssertHandler, result == SQLITE_OK, "Failed to bind value for statement: {}", sqlite3_errmsg(m_db));
}
@@ -696,14 +697,14 @@ void BigFile::Request::Bind(const std::uint32_t p_index, const double p_value)
void BigFile::Request::Bind(const std::uint32_t p_index, const eastl::string_view p_value, const CopyValue p_copy)
{
ASSERT(EngineAssertHandler,
(p_index >= 1) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
(p_index >= 1U) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
"Invalid index for statement");
[[maybe_unused]]
const int result = sqlite3_bind_text(m_statement,
p_index,
static_cast<int>(p_index),
p_value.data(),
static_cast<std::uint32_t>(p_value.size()),
static_cast<int>(p_value.size()),
p_copy ? SQLITE_TRANSIENT : SQLITE_STATIC);
ASSERT(EngineAssertHandler, result == SQLITE_OK, "Failed to bind value for statement: {}", sqlite3_errmsg(m_db));
}
@@ -715,14 +716,14 @@ void BigFile::Request::Bind(const std::uint32_t p_index,
const CopyValue p_copy)
{
ASSERT(EngineAssertHandler,
(p_index >= 1) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
(p_index >= 1U) && (p_index <= static_cast<std::uint32_t>(sqlite3_bind_parameter_count(m_statement))),
"Invalid index for statement");
[[maybe_unused]]
const int result = sqlite3_bind_blob(m_statement,
p_index,
static_cast<int>(p_index),
p_value.data(),
static_cast<std::uint32_t>(p_value.size()),
static_cast<int>(p_value.size()),
p_copy ? SQLITE_TRANSIENT : SQLITE_STATIC);
ASSERT(EngineAssertHandler, result == SQLITE_OK, "Failed to bind value for statement: {}", sqlite3_errmsg(m_db));
}
@@ -763,58 +764,69 @@ BigFile::Request::Column::Column(const Request& p_request, const std::uint32_t p
BigFile::Request::Column::operator std::int32_t() const
{
return sqlite3_column_int(m_statement, m_index);
return sqlite3_column_int(m_statement, static_cast<int>(m_index));
}
/****************************************************************************************/
BigFile::Request::Column::operator std::uint32_t() const
{
return sqlite3_column_int(m_statement, m_index);
return sqlite3_column_int(m_statement, static_cast<int>(m_index));
}
/****************************************************************************************/
BigFile::Request::Column::operator std::int64_t() const
{
return sqlite3_column_int64(m_statement, m_index);
return sqlite3_column_int64(m_statement, static_cast<int>(m_index));
}
/****************************************************************************************/
BigFile::Request::Column::operator std::uint64_t() const
{
return std::bit_cast<std::uint64_t>(sqlite3_column_int64(m_statement, m_index));
return std::bit_cast<std::uint64_t>(sqlite3_column_int64(m_statement, static_cast<int>(m_index)));
}
/****************************************************************************************/
BigFile::Request::Column::operator float() const
{
return static_cast<float>(sqlite3_column_double(m_statement, m_index));
return static_cast<float>(sqlite3_column_double(m_statement, static_cast<int>(m_index)));
}
/****************************************************************************************/
BigFile::Request::Column::operator double() const
{
return sqlite3_column_double(m_statement, m_index);
return sqlite3_column_double(m_statement, static_cast<int>(m_index));
}
/****************************************************************************************/
BigFile::Request::Column::operator eastl::string_view() const
{
return eastl::string_view {reinterpret_cast<const char*>(sqlite3_column_text(m_statement, m_index)),
static_cast<std::size_t>(sqlite3_column_bytes(m_statement, m_index))};
return eastl::string_view {
reinterpret_cast<const char*>(sqlite3_column_text(m_statement, static_cast<int>(m_index))),
static_cast<std::size_t>(sqlite3_column_bytes(m_statement, static_cast<int>(m_index)))};
}
/****************************************************************************************/
BigFile::Request::Column::operator eastl::span<const std::byte>() const
{
return eastl::span<const std::byte> {static_cast<const std::byte*>(sqlite3_column_blob(m_statement, m_index)),
static_cast<std::size_t>(sqlite3_column_bytes(m_statement, m_index))};
return eastl::span<const std::byte> {
static_cast<const std::byte*>(sqlite3_column_blob(m_statement, static_cast<int>(m_index))),
static_cast<std::size_t>(sqlite3_column_bytes(m_statement, static_cast<int>(m_index)))};
}
/****************************************************************************************/
BigFile::Request::Column::operator std::span<const std::byte>() const
{
return std::span<const std::byte> {
static_cast<const std::byte*>(sqlite3_column_blob(m_statement, static_cast<int>(m_index))),
static_cast<std::size_t>(sqlite3_column_bytes(m_statement, static_cast<int>(m_index)))};
}
/****************************************************************************************/
@@ -6,7 +6,10 @@
*********************************************************************/
#ifndef BIGFOOT_ENGINE_ASSET_ASSET_HPP
#define BIGFOOT_ENGINE_ASSET_ASSET_HPP
#include <Engine/Asset/AssetBase.hpp>
#include <Engine/Asset/AssetConcepts.hpp>
#include <Engine/Asset/AssetContainer.hpp>
#include <Engine/Asset/AssetLibrary.hpp>
#include <Engine/Asset/Asset_generated.hpp>
#include <Engine/EngineAssertHandler.hpp>
@@ -18,101 +21,12 @@
namespace Bigfoot
{
class AssetBase
{
public:
virtual ~AssetBase() = default;
/**
* Get the header of the asset
*
* \return The header of the asset
*/
[[nodiscard]]
virtual const ::Flat::Bigfoot::AssetHeaderT& GetHeader() const = 0;
/**
* Get the HardReferences the flatbuffer has
*
* \param p_flatbuffer The flatbuffer
* \return The UUIDs of the HardReferences
*/
[[nodiscard]]
virtual eastl::vector<UUID> GetHardReferences(const eastl::span<const std::byte> p_flatbuffer) const = 0;
/**
* Unpack a flatbuffer to the asset
*
* \param p_flatbuffer The flatbuffer to unpack
*/
virtual void Unpack(const eastl::span<const std::byte> p_flatbuffer) = 0;
/**
* Pack the asset to a flatbuffer
*
* \return The packed asset
*/
[[nodiscard]]
virtual eastl::vector<std::byte> Pack() const = 0;
protected:
AssetBase() = default;
AssetBase(const AssetBase& p_asset) = delete;
AssetBase(AssetBase&& p_asset) = default;
AssetBase& operator=(const AssetBase& p_asset) = delete;
AssetBase& operator=(AssetBase&& p_asset) = default;
class HardReferenceVisitor: public flatbuffers::IterationVisitor
{
public:
void Field(size_t p_fieldIndex,
size_t p_setIndex,
const flatbuffers::ElementaryType p_type,
const bool p_isVector,
const flatbuffers::TypeTable* p_typeTable,
const char* p_name,
const std::uint8_t* p_val) override;
void Element(size_t p_index,
const flatbuffers::ElementaryType p_type,
const flatbuffers::TypeTable* p_typeTable,
const std::uint8_t* p_val) override;
/**
* Get the visited HardReference
*
* \return The visited HardReferences
*/
[[nodiscard]]
eastl::vector<UUID> GetUUIDs() const;
private:
/**
* Visit an element in the flatbuffer
*
* \param p_type The element type
* \param p_typeTable The element typetable
* \param p_val The element
*/
void Visit(const flatbuffers::ElementaryType p_type,
const flatbuffers::TypeTable* p_typeTable,
const std::uint8_t* p_val);
/**
* The HardReferences visited so far
*/
ankerl::unordered_dense::set<UUID> m_uuids;
};
};
template<class ASSET>
requires AssetTraits<ASSET>
class Asset: public AssetBase
{
public:
using FLAT_ASSET = typename ASSET::FLAT;
using FLAT_ASSET = ASSET::FLAT;
/**
* Constructor
@@ -153,7 +67,7 @@ class Asset: public AssetBase
* \return The asset
*/
[[nodiscard]]
const typename FLAT_ASSET::NativeTableType& GetAsset() const
const FLAT_ASSET::NativeTableType& GetAsset() const
{
return m_asset;
}
@@ -164,7 +78,7 @@ class Asset: public AssetBase
* \return The asset
*/
[[nodiscard]]
typename FLAT_ASSET::NativeTableType& GetAsset()
FLAT_ASSET::NativeTableType& GetAsset()
{
return m_asset;
}
@@ -177,7 +91,8 @@ class Asset: public AssetBase
void Unpack(const eastl::span<const std::byte> p_flatbuffer) override
{
#ifdef BIGFOOT_NOT_OPTIMIZED
flatbuffers::Verifier verifier {std::bit_cast<std::uint8_t*>(p_flatbuffer.data()), p_flatbuffer.size()};
flatbuffers::Verifier verifier {reinterpret_cast<const std::uint8_t*>(p_flatbuffer.data()),
p_flatbuffer.size()};
const bool assetVerified = ::Flat::Bigfoot::VerifyAssetBuffer(verifier);
CRITICAL_ASSERT(EngineAssertHandler, assetVerified, "Given asset could not be verified!");
#endif
@@ -210,8 +125,9 @@ class Asset: public AssetBase
const auto innerAsset = assetFbb.CreateVector(innerAssetFbb.GetBufferPointer(), innerAssetFbb.GetSize());
assetFbb.Finish(::Flat::Bigfoot::CreateAsset(assetFbb, header, innerAsset));
return eastl::vector<std::byte> {std::bit_cast<std::byte*>(assetFbb.GetBufferPointer()),
std::bit_cast<std::byte*>(assetFbb.GetBufferPointer() + assetFbb.GetSize())};
return eastl::vector<std::byte> {
reinterpret_cast<std::byte*>(assetFbb.GetBufferPointer()),
reinterpret_cast<std::byte*>(assetFbb.GetBufferPointer() + assetFbb.GetSize())};
}
/**
@@ -224,7 +140,8 @@ class Asset: public AssetBase
eastl::vector<UUID> GetHardReferences(const eastl::span<const std::byte> p_flatbuffer) const override
{
#ifdef BIGFOOT_NOT_OPTIMIZED
flatbuffers::Verifier verifier {std::bit_cast<std::uint8_t*>(p_flatbuffer.data()), p_flatbuffer.size()};
flatbuffers::Verifier verifier {reinterpret_cast<const std::uint8_t*>(p_flatbuffer.data()),
p_flatbuffer.size()};
const bool assetVerified = ::Flat::Bigfoot::VerifyAssetBuffer(verifier);
CRITICAL_ASSERT(EngineAssertHandler, assetVerified, "Given asset could not be verified!");
#endif
@@ -271,12 +188,30 @@ class Asset: public AssetBase
/**
* The asset
*/
typename FLAT_ASSET::NativeTableType m_asset;
FLAT_ASSET::NativeTableType m_asset;
/**
* The asset header
*/
::Flat::Bigfoot::AssetHeaderT m_header;
};
/**
* Create an asset and insert it into its corresponding AssetContainer
*
* \tparam ASSET The Asset type
* \return The created asset, nullptr if no AssetContainer is registered for ASSET
*/
template<class ASSET>
requires AssetType<ASSET>
[[nodiscard]]
ASSET* CreateAsset()
{
AssetContainerBase* container = g_activeAssetLibrary->GetAssetContainer(ASSET::GetTypeID());
CRITICAL_ASSERT(EngineAssertHandler, container != nullptr, "No AssetContainer registered for this asset type!");
ContainerHandle* handle = container->Insert();
return static_cast<ASSET*>(handle->GetAsset());
}
} // namespace Bigfoot
#endif
@@ -0,0 +1,111 @@
/*********************************************************************
* \file AssetBase.hpp
*
* \author Romain BOULLARD
* \date April 2026
*********************************************************************/
#ifndef BIGFOOT_ENGINE_ASSET_ASSETBASE_HPP
#define BIGFOOT_ENGINE_ASSET_ASSETBASE_HPP
#include <Engine/Asset/Asset_generated.hpp>
#include <System/UUID/UUID.hpp>
#include <EASTL/span.h>
#include <EASTL/vector.h>
#include <ankerl/unordered_dense.h>
#include <flatbuffers/minireflect.h>
namespace Bigfoot
{
class AssetBase
{
public:
virtual ~AssetBase() = default;
/**
* Get the header of the asset
*
* \return The header of the asset
*/
[[nodiscard]]
virtual const ::Flat::Bigfoot::AssetHeaderT& GetHeader() const = 0;
/**
* Get the HardReferences the flatbuffer has
*
* \param p_flatbuffer The flatbuffer
* \return The UUIDs of the HardReferences
*/
[[nodiscard]]
virtual eastl::vector<UUID> GetHardReferences(const eastl::span<const std::byte> p_flatbuffer) const = 0;
/**
* Unpack a flatbuffer to the asset
*
* \param p_flatbuffer The flatbuffer to unpack
*/
virtual void Unpack(const eastl::span<const std::byte> p_flatbuffer) = 0;
/**
* Pack the asset to a flatbuffer
*
* \return The packed asset
*/
[[nodiscard]]
virtual eastl::vector<std::byte> Pack() const = 0;
AssetBase(const AssetBase& p_asset) = delete;
AssetBase& operator=(const AssetBase& p_asset) = delete;
protected:
AssetBase() = default;
AssetBase(AssetBase&& p_asset) = default;
AssetBase& operator=(AssetBase&& p_asset) = default;
class HardReferenceVisitor: public flatbuffers::IterationVisitor
{
public:
void Field(size_t p_fieldIndex,
size_t p_setIndex,
const flatbuffers::ElementaryType p_type,
const bool p_isVector,
const flatbuffers::TypeTable* p_typeTable,
const char* p_name,
const std::uint8_t* p_val) override;
void Element(size_t p_index,
const flatbuffers::ElementaryType p_type,
const flatbuffers::TypeTable* p_typeTable,
const std::uint8_t* p_val) override;
/**
* Get the visited HardReference
*
* \return The visited HardReferences
*/
[[nodiscard]]
eastl::vector<UUID> GetUUIDs() const;
private:
/**
* Visit an element in the flatbuffer
*
* \param p_type The element type
* \param p_typeTable The element typetable
* \param p_val The element
*/
void Visit(const flatbuffers::ElementaryType p_type,
const flatbuffers::TypeTable* p_typeTable,
const std::uint8_t* p_val);
/**
* The HardReferences visited so far
*/
ankerl::unordered_dense::set<UUID> m_uuids;
};
};
} // namespace Bigfoot
#endif
@@ -6,7 +6,7 @@
*********************************************************************/
#ifndef BIGFOOT_ENGINE_ASSET_ASSETCONTAINER_HPP
#define BIGFOOT_ENGINE_ASSET_ASSETCONTAINER_HPP
#include <Engine/Asset/Asset.hpp>
#include <Engine/Asset/AssetBase.hpp>
#include <Engine/Asset/AssetConcepts.hpp>
#include <Engine/EngineAssertHandler.hpp>
@@ -27,11 +27,11 @@ class ContainerHandle
{
public:
/**
* Constructor
*
* \param p_assetContainer The originating assetcontainer
* \param p_uuid The UUID of tha asset
*/
* Constructor
*
* \param p_assetContainer The originating assetcontainer
* \param p_uuid The UUID of tha asset
*/
ContainerHandle(AssetContainerBase* p_assetContainer, const UUID p_uuid);
/*
@@ -200,8 +200,12 @@ class AssetContainerBase
[[nodiscard]]
bool IsMarkedForRemove(const UUID& p_uuid);
AssetContainerBase& operator=(const AssetContainerBase& p_container) = delete;
AssetContainerBase& operator=(AssetContainerBase&& p_container) = delete;
AssetContainerBase(const AssetContainerBase& p_container) = delete;
AssetContainerBase(AssetContainerBase&& p_container) = delete;
protected:
struct Entry
{
@@ -223,8 +227,6 @@ class AssetContainerBase
AssetContainerBase() = default;
AssetContainerBase(AssetContainerBase&& p_container) = delete;
/*
* Finds an entry matching the Asset
*
@@ -352,7 +354,6 @@ class AssetContainer: public AssetContainerBase
m_assets.Remove(p_key);
}
private:
/*
* The assets
*/
@@ -91,14 +91,16 @@ class AssetLibrary
bool IsLoaded(const UUID& p_uuid) const;
/**
* Loop through the AssetContainers to remove the pending assets marked for removal
*
*/
* Loop through the AssetContainers to remove the pending assets marked for removal
*
*/
void ProcessPendingRemovals();
AssetLibrary& operator=(const AssetLibrary& p_library) = default;
AssetLibrary& operator=(AssetLibrary&& p_library) = delete;
~AssetLibrary() = default;
private:
// All the asset containers
ankerl::unordered_dense::map<AssetTypeID, AssetContainerBase*> m_assetContainers;
@@ -15,13 +15,10 @@ using AssetTypeID = std::uint64_t;
/****************************************************************************************/
namespace Flat
{
namespace Bigfoot
namespace Flat::Bigfoot
{
struct AssetTypeID;
}
} // namespace Flat
} // namespace Flat::Bigfoot
/****************************************************************************************/
@@ -94,7 +94,9 @@ class ReferenceBase
return m_uuid == p_reference.m_uuid;
}
protected:
private:
friend DERIVED;
ReferenceBase() = default;
ReferenceBase(const UUID& p_uuid):
@@ -116,7 +118,6 @@ class ReferenceBase
{
}
private:
/**
* Get the associated handle container for the asset
* Register the reference inside the handle
@@ -152,7 +153,6 @@ class ReferenceBase
}
}
private:
/**
* The UUID
*/
@@ -15,8 +15,11 @@
#include <EASTL/optional.h>
#include <EASTL/span.h>
#include <EASTL/string_view.h>
#include <sqlite3.h>
#include <span>
namespace Bigfoot
{
#ifdef BIGFOOT_TOOLMODE
@@ -57,7 +60,7 @@ class BigFile: public DataAccessor
*/
void Clear();
~BigFile();
~BigFile() override;
/**
* Get an Asset flatbuffer
@@ -325,6 +328,13 @@ class BigFile: public DataAccessor
*/
operator eastl::span<const std::byte>() const;
/*
* Get value as a blob
*
* \return The value
*/
operator std::span<const std::byte>() const;
private:
/*
* The statement
@@ -359,14 +369,14 @@ class BigFile: public DataAccessor
/*
* The statement
*/
sqlite3_stmt* m_statement;
sqlite3_stmt* m_statement = nullptr;
};
private:
/**
* The BigFile DB
*/
sqlite3* m_db;
sqlite3* m_db = nullptr;
};
#endif
} // namespace Bigfoot
@@ -10,7 +10,7 @@
#include <Utils/Assert/AssertHandler.hpp>
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
namespace Bigfoot
{
@@ -15,7 +15,7 @@ namespace Bigfoot
/*
* Logger
*/
inline Log::LoggerInfo ENGINE_LOGGER {"ENGINE_LOGGER", Flat::LogLevel::Trace};
inline Log::LoggerInfo ENGINE_LOGGER { .m_name = "ENGINE_LOGGER", .m_level = Flat::LogLevel::Trace};
} // namespace Bigfoot
#endif
#endif
@@ -95,7 +95,7 @@ class SasquatchWriter
SasquatchWriter& operator=(SasquatchWriter&& p_writer) = delete;
private:
static constexpr std::uint64_t PREFETCH_BYTES = 4 * 1024 * 1024;
static constexpr std::uint64_t PREFETCH_BYTES = 4ULL * 1024 * 1024;
/**
* The number of assets expected
@@ -105,7 +105,12 @@ class SasquatchWriter
/**
* How far into m_file has already been prefetched
*/
std::size_t m_prefetchedUpTo;
std::size_t m_prefetchedUpTo = 0;
/**
* Current write position in the data region
*/
std::size_t m_currentDataOffset;
/**
* The Sasquatch file being written, mapped at its final size
@@ -140,6 +145,7 @@ class Sasquatch: public DataAccessor
*
* \return The header
*/
[[nodiscard]]
const SasquatchHeader& GetHeader() const;
/**
@@ -28,7 +28,7 @@ void LoadAsset(const UUID& p_uuid);
*/
void LoadAssets(const eastl::span<const UUID> p_uuids);
#if defined BIGFOOT_TOOLMODE
#ifdef BIGFOOT_TOOLMODE
/**
* Save an Asset
* Fails without saving if a cyclic dependency is detected starting from this asset
+19 -24
View File
@@ -19,9 +19,9 @@ SasquatchWriter::SasquatchWriter(const File& p_file,
const std::size_t p_totalFlatbufferBytes,
const std::size_t p_totalHardReferencesBytes):
m_assetCount(p_assetCount),
m_prefetchedUpTo(0),
m_currentDataOffset(sizeof(SasquatchHeader) + (m_assetCount * sizeof(SasquatchEntry))),
m_file(p_file,
sizeof(SasquatchHeader) + m_assetCount * sizeof(SasquatchEntry) + p_totalFlatbufferBytes +
sizeof(SasquatchHeader) + (m_assetCount * sizeof(SasquatchEntry)) + p_totalFlatbufferBytes +
p_totalHardReferencesBytes)
{
m_entries.reserve(m_assetCount);
@@ -63,21 +63,15 @@ void SasquatchWriter::WriteAsset(const UUID& p_uuid,
"SasquatchWriter can only hold {} assets",
m_assetCount);
const std::size_t offset = std::accumulate(m_entries.begin(),
m_entries.end(),
sizeof(SasquatchHeader) + m_assetCount * sizeof(SasquatchEntry),
[](const std::size_t p_value, const SasquatchEntry& p_entry)
{
return p_value + p_entry.m_assetSize + p_entry.m_hardReferencesSize;
});
const std::size_t offset = m_currentDataOffset;
const eastl::span<std::byte> data = m_file.GetData();
ASSERT(EngineAssertHandler,
offset + p_flatbuffer.size() + p_hardReferences.size() * UUID::UUID_BYTE_SIZE <= data.size(),
offset + p_flatbuffer.size() + (p_hardReferences.size() * UUID::UUID_BYTE_SIZE) <= data.size(),
"SasquatchWriter can only write {} bytes",
data.size());
const std::size_t writeEnd = offset + p_flatbuffer.size() + p_hardReferences.size() * UUID::UUID_BYTE_SIZE;
const std::size_t writeEnd = offset + p_flatbuffer.size() + (p_hardReferences.size() * UUID::UUID_BYTE_SIZE);
if (writeEnd > m_prefetchedUpTo)
{
const std::size_t prefetchEnd = std::min(writeEnd + PREFETCH_BYTES, data.size());
@@ -97,11 +91,12 @@ void SasquatchWriter::WriteAsset(const UUID& p_uuid,
for (std::uint32_t i = 0; i < p_hardReferences.size(); ++i)
{
const std::span<const std::byte, UUID::UUID_BYTE_SIZE> rawUUID = p_hardReferences[i].ToBytes();
std::memcpy(data.data() + entry.m_hardReferencesOffset + i * UUID::UUID_BYTE_SIZE,
std::memcpy(data.data() + entry.m_hardReferencesOffset + (static_cast<std::size_t>(i) * UUID::UUID_BYTE_SIZE),
rawUUID.data(),
UUID::UUID_BYTE_SIZE);
}
m_currentDataOffset += entry.m_assetSize + entry.m_hardReferencesSize;
m_entries.push_back(entry);
}
@@ -133,11 +128,11 @@ Sasquatch::Sasquatch(const File& p_file):
SasquatchHeader::VERSION);
CRITICAL_ASSERT(EngineAssertHandler,
data.size() >= sizeof(SasquatchHeader) + m_header.m_assetCount * sizeof(SasquatchEntry),
data.size() >= sizeof(SasquatchHeader) + (m_header.m_assetCount * sizeof(SasquatchEntry)),
"Sasquatch file {} index is truncated (got {} / expected at least {})",
p_file.GetPath(),
data.size(),
sizeof(SasquatchHeader) + m_header.m_assetCount * sizeof(SasquatchEntry));
sizeof(SasquatchHeader) + (m_header.m_assetCount * sizeof(SasquatchEntry)));
eastl::vector<SasquatchEntry> entries(m_header.m_assetCount);
if (!entries.empty())
@@ -172,15 +167,15 @@ const SasquatchHeader& Sasquatch::GetHeader() const
eastl::vector<std::byte> Sasquatch::GetAssetFlatbuffer(const UUID& p_uuid) const
{
const auto it = m_entries.find(p_uuid);
if (it == m_entries.end())
const auto entryIt = m_entries.find(p_uuid);
if (entryIt == m_entries.end())
{
return {};
}
const eastl::span<const std::byte> data = m_file.GetData();
const eastl::span<const std::byte> bytes {data.data() + it->second.m_assetOffset,
static_cast<std::size_t>(it->second.m_assetSize)};
const eastl::span<const std::byte> bytes {data.data() + entryIt->second.m_assetOffset,
static_cast<std::size_t>(entryIt->second.m_assetSize)};
return eastl::vector<std::byte> {bytes.begin(), bytes.end()};
}
@@ -205,15 +200,15 @@ eastl::vector<UUID> Sasquatch::GetAssetHardReferences(const UUID& p_uuid) const
{
eastl::vector<UUID> hardReferences;
const auto it = m_entries.find(p_uuid);
if (it == m_entries.end())
const auto entryIt = m_entries.find(p_uuid);
if (entryIt == m_entries.end())
{
return hardReferences;
}
const eastl::span<const std::byte> data = m_file.GetData();
const eastl::span<const std::byte> bytes {data.data() + it->second.m_hardReferencesOffset,
static_cast<std::size_t>(it->second.m_hardReferencesSize)};
const eastl::span<const std::byte> bytes {data.data() + entryIt->second.m_hardReferencesOffset,
static_cast<std::size_t>(entryIt->second.m_hardReferencesSize)};
const std::size_t hardReferenceCount = bytes.size() / UUID::UUID_BYTE_SIZE;
hardReferences.reserve(hardReferenceCount);
@@ -221,7 +216,7 @@ eastl::vector<UUID> Sasquatch::GetAssetHardReferences(const UUID& p_uuid) const
for (std::size_t i = 0; i < hardReferenceCount; ++i)
{
std::array<std::byte, UUID::UUID_BYTE_SIZE> rawUUID;
std::memcpy(rawUUID.data(), bytes.data() + i * UUID::UUID_BYTE_SIZE, UUID::UUID_BYTE_SIZE);
std::memcpy(rawUUID.data(), bytes.data() + (i * UUID::UUID_BYTE_SIZE), UUID::UUID_BYTE_SIZE);
hardReferences.emplace_back(rawUUID);
}
@@ -265,7 +260,7 @@ void Sasquatch::SaveAssetFlatbuffers([[maybe_unused]] const eastl::span<const UU
bool Sasquatch::Has(const UUID& p_uuid) const
{
return m_entries.find(p_uuid) != m_entries.end();
return m_entries.contains(p_uuid);
}
#endif
} // namespace Bigfoot
@@ -95,7 +95,8 @@ void LoadAssets(const eastl::span<const UUID> p_uuids)
}
#ifdef BIGFOOT_NOT_OPTIMIZED
flatbuffers::Verifier verifier {std::bit_cast<std::uint8_t*>(flatbuffer.data()), flatbuffer.size()};
flatbuffers::Verifier verifier {reinterpret_cast<const std::uint8_t*>(flatbuffer.data()),
flatbuffer.size()};
const bool assetVerified = ::Flat::Bigfoot::VerifyAssetBuffer(verifier);
CRITICAL_ASSERT(EngineAssertHandler, assetVerified, "Given asset could not be verified!");
#endif
@@ -104,6 +105,10 @@ void LoadAssets(const eastl::span<const UUID> p_uuids)
AssetContainerBase* container = g_activeAssetLibrary->GetAssetContainer(
flatbuffers::UnPack(*asset->header()->type_id()));
CRITICAL_ASSERT(EngineAssertHandler,
container != nullptr,
"No AssetContainer registered for asset {}",
wave[i]);
std::ignore = container->Insert(flatbuffer);
}
}
@@ -113,52 +118,12 @@ void LoadAssets(const eastl::span<const UUID> p_uuids)
void LoadAsset(const UUID& p_uuid)
{
ankerl::unordered_dense::set<UUID> discovered;
const ankerl::unordered_dense::map<UUID, eastl::vector<UUID>> graph = BuildDependencyGraph(
eastl::span<const UUID> {&p_uuid, 1},
discovered);
// Assets that are part of a cyclic HardReference dependency are left out of waves and simply never loaded.
eastl::vector<eastl::vector<UUID>> waves;
eastl::vector<UUID> cyclicUuids;
std::ignore = LayeredTopologicalSort(graph, discovered, waves, cyclicUuids);
BIGFOOT_LOG_ERROR_IF(!cyclicUuids.empty(),
ENGINE_LOGGER,
"Cyclic HardReference dependency detected while loading asset {}, involved UUIDs: {}",
p_uuid,
cyclicUuids);
// Waves are loaded one after another since a wave's assets may HardReference the previous wave's; within a
// wave, every asset is independent of the others, so this is where loading could later be parallelized.
for (const eastl::vector<UUID>& wave: waves)
{
for (const UUID& uuid: wave)
{
const eastl::vector<std::byte> flatbuffer = g_dataAccessor->GetAssetFlatbuffer(uuid);
if (flatbuffer.empty())
{
BIGFOOT_LOG_ERROR(ENGINE_LOGGER, "Asset {} could not be found while loading, skipping it", uuid);
continue;
}
#ifdef BIGFOOT_NOT_OPTIMIZED
flatbuffers::Verifier verifier {std::bit_cast<std::uint8_t*>(flatbuffer.data()), flatbuffer.size()};
const bool assetVerified = ::Flat::Bigfoot::VerifyAssetBuffer(verifier);
CRITICAL_ASSERT(EngineAssertHandler, assetVerified, "Given asset could not be verified!");
#endif
const ::Flat::Bigfoot::Asset* asset = flatbuffers::GetRoot<::Flat::Bigfoot::Asset>(flatbuffer.data());
AssetContainerBase* container = g_activeAssetLibrary->GetAssetContainer(
flatbuffers::UnPack(*asset->header()->type_id()));
std::ignore = container->Insert(flatbuffer);
}
}
LoadAssets(eastl::span<const UUID> {&p_uuid, 1});
}
/****************************************************************************************/
#if defined BIGFOOT_TOOLMODE
#ifdef BIGFOOT_TOOLMODE
/*
* Finds the cyclic dependencies that may exist in Assets
*
@@ -223,6 +188,7 @@ eastl::vector<UUID> FindCyclicDependencies(const eastl::span<const UUID> p_uuids
bool SaveAsset(const UUID& p_uuid)
{
AssetContainerBase* container = g_activeAssetLibrary->GetAssetContainer(p_uuid);
CRITICAL_ASSERT(EngineAssertHandler, container != nullptr, "No AssetContainer registered for asset {}", p_uuid);
const AssetBase* asset = container->AcquireContainerHandle(p_uuid)->GetAsset();
const eastl::vector<std::byte> flatbuffer = asset->Pack();
@@ -257,6 +223,7 @@ bool SaveAssets(const eastl::span<const UUID> p_uuids)
for (const UUID& uuid: p_uuids)
{
AssetContainerBase* container = g_activeAssetLibrary->GetAssetContainer(uuid);
CRITICAL_ASSERT(EngineAssertHandler, container != nullptr, "No AssetContainer registered for asset {}", uuid);
const AssetBase* asset = container->AcquireContainerHandle(uuid)->GetAsset();
const eastl::vector<std::byte> flatbuffer = asset->Pack();
+4 -5
View File
@@ -8,7 +8,6 @@
#include <System/SystemAssertHandler.hpp>
#include <bit>
#include <fstream>
#include <string>
@@ -83,7 +82,7 @@ eastl::vector<std::byte> File::Read(const std::size_t p_offset, const std::size_
eastl::vector<std::byte> data;
data.resize(p_size);
file.read(std::bit_cast<char*>(data.data()), static_cast<std::streamsize>(data.size()));
file.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(data.size()));
return data;
}
@@ -100,7 +99,7 @@ void File::Write(const eastl::span<const std::byte> p_data, const std::size_t p_
CRITICAL_ASSERT(SystemAssertHandler, file.is_open(), "Failed to open file {} for writing", path);
file.seekp(static_cast<std::streamoff>(p_offset), std::ios::beg);
file.write(std::bit_cast<const char*>(p_data.data()), static_cast<std::streamsize>(p_data.size()));
file.write(reinterpret_cast<const char*>(p_data.data()), static_cast<std::streamsize>(p_data.size()));
}
/****************************************************************************************/
@@ -112,8 +111,8 @@ void File::Delete() const
/****************************************************************************************/
File::File(const std::filesystem::path& p_path):
m_path(p_path),
File::File(std::filesystem::path p_path):
m_path(std::move(p_path)),
m_pathString(m_path.string().c_str())
{
}
@@ -10,7 +10,7 @@
#include <string>
#if defined BIGFOOT_WINDOWS
#ifdef BIGFOOT_WINDOWS
#include <Windows.h>
#elif defined BIGFOOT_LINUX
#include <fcntl.h>
@@ -26,7 +26,7 @@ MemoryMappedFile::MemoryMappedFile(const File& p_file)
const File absoluteFile = p_file.ToAbsolute();
const eastl::string_view path = absoluteFile.GetPath();
#if defined BIGFOOT_WINDOWS
#ifdef BIGFOOT_WINDOWS
m_fileHandle = CreateFileA(path.data(),
GENERIC_READ,
FILE_SHARE_READ,
@@ -78,7 +78,7 @@ MemoryMappedFile::MemoryMappedFile(const File& p_file)
MemoryMappedFile::~MemoryMappedFile()
{
#if defined BIGFOOT_WINDOWS
#ifdef BIGFOOT_WINDOWS
if (m_data != nullptr)
{
[[maybe_unused]]
@@ -133,7 +133,7 @@ WritableMemoryMappedFile::WritableMemoryMappedFile(const File& p_file, const std
const File absoluteFile = p_file.ToAbsolute();
const eastl::string_view path = absoluteFile.GetPath();
#if defined BIGFOOT_WINDOWS
#ifdef BIGFOOT_WINDOWS
m_fileHandle =
CreateFileA(path.data(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
CRITICAL_ASSERT(SystemAssertHandler, m_fileHandle != INVALID_HANDLE_VALUE, "Failed to create file {}", path);
@@ -169,7 +169,7 @@ WritableMemoryMappedFile::WritableMemoryMappedFile(const File& p_file, const std
WritableMemoryMappedFile::~WritableMemoryMappedFile()
{
#if defined BIGFOOT_WINDOWS
#ifdef BIGFOOT_WINDOWS
if (m_data != nullptr)
{
[[maybe_unused]]
@@ -220,7 +220,7 @@ eastl::span<std::byte> WritableMemoryMappedFile::GetData() const
void WritableMemoryMappedFile::Prefetch(const std::size_t p_offset, const std::size_t p_size) const
{
#if defined BIGFOOT_WINDOWS
#ifdef BIGFOOT_WINDOWS
WIN32_MEMORY_RANGE_ENTRY range {.VirtualAddress = m_data + p_offset, .NumberOfBytes = p_size};
[[maybe_unused]]
const BOOL prefetched = PrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0);
@@ -112,7 +112,7 @@ class File
*
* \param p_path The path
*/
File(const std::filesystem::path& p_path);
File(std::filesystem::path p_path);
/**
* The path
@@ -47,7 +47,7 @@ class MemoryMappedFile
MemoryMappedFile& operator=(MemoryMappedFile&& p_file) = delete;
private:
#if defined BIGFOOT_WINDOWS
#ifdef BIGFOOT_WINDOWS
/**
* Handle to the file
*/
@@ -118,7 +118,7 @@ class WritableMemoryMappedFile
WritableMemoryMappedFile& operator=(WritableMemoryMappedFile&& p_file) = delete;
private:
#if defined BIGFOOT_WINDOWS
#ifdef BIGFOOT_WINDOWS
/**
* Handle to the file
*/
@@ -10,7 +10,7 @@
#include <Utils/Assert/AssertHandler.hpp>
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
namespace Bigfoot
{
@@ -15,7 +15,7 @@ namespace Bigfoot
/*
* Logger
*/
inline Log::LoggerInfo SYSTEM_LOGGER {"SYSTEM_LOGGER", Flat::LogLevel::Trace};
inline Log::LoggerInfo SYSTEM_LOGGER { .m_name = "SYSTEM_LOGGER", .m_level = Flat::LogLevel::Trace};
} // namespace Bigfoot
#endif
#endif
@@ -65,13 +65,10 @@ class Time
/****************************************************************************************/
namespace Flat
{
namespace Bigfoot
namespace Flat::Bigfoot
{
struct Time;
}
} // namespace Flat
} // namespace Flat::Bigfoot
/****************************************************************************************/
@@ -6,6 +6,7 @@
*********************************************************************/
#ifndef BIGFOOT_SYSTEM_UUID_UUID_HPP
#define BIGFOOT_SYSTEM_UUID_UUID_HPP
#include <EASTL/string.h>
#include <ankerl/unordered_dense.h>
#include <fmt/format.h>
#include <uuid.h>
@@ -52,7 +53,7 @@ class UUID
* \return A string representing the UUID
*/
[[nodiscard]]
std::string ToString() const;
eastl::string ToString() const;
operator bool() const;
@@ -120,33 +121,33 @@ struct std::hash<Bigfoot::UUID>
template<>
struct fmt::formatter<Bigfoot::UUID>
{
constexpr auto parse(format_parse_context& ctx)
static constexpr auto parse(format_parse_context& ctx)
{
return ctx.begin();
}
auto format(const Bigfoot::UUID& p_uuid, format_context& ctx) const
static auto format(const Bigfoot::UUID& p_uuid, format_context& ctx)
{
return fmt::format_to(ctx.out(), "{}", p_uuid.ToString());
return fmt::format_to(ctx.out(), "{}", p_uuid.ToString().c_str());
}
};
/****************************************************************************************/
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
#include <quill/DeferredFormatCodec.h>
template<>
struct fmtquill::formatter<Bigfoot::UUID>
{
constexpr auto parse(format_parse_context& ctx)
static constexpr auto parse(format_parse_context& ctx)
{
return ctx.begin();
}
auto format(const Bigfoot::UUID& p_uuid, format_context& ctx) const
static auto format(const Bigfoot::UUID& p_uuid, format_context& ctx)
{
return fmtquill::format_to(ctx.out(), "{}", p_uuid.ToString());
return fmtquill::format_to(ctx.out(), "{}", p_uuid.ToString().c_str());
}
};
@@ -158,13 +159,10 @@ struct quill::Codec<Bigfoot::UUID>: quill::DeferredFormatCodec<Bigfoot::UUID>
/****************************************************************************************/
namespace Flat
{
namespace Bigfoot
namespace Flat::Bigfoot
{
struct UUID;
}
} // namespace Flat
} // namespace Flat::Bigfoot
/****************************************************************************************/
+2 -1
View File
@@ -57,7 +57,8 @@ Time::Time(const std::uint64_t p_epoch):
std::uint32_t Time::GetYear() const
{
return m_timeInfo.tm_year + 1900;
constexpr std::uint32_t TM_YEAR_EPOCH = 1900;
return m_timeInfo.tm_year + TM_YEAR_EPOCH;
}
/****************************************************************************************/
+4 -3
View File
@@ -35,7 +35,7 @@ UUID::UUID(const std::string_view p_string):
UUID::UUID(const std::span<const std::byte, UUID_BYTE_SIZE> p_raw)
{
const std::span<std::uint8_t, UUID_BYTE_SIZE> raw {
const_cast<std::uint8_t*>(std::bit_cast<const std::uint8_t*>(p_raw.data())),
const_cast<std::uint8_t*>(reinterpret_cast<const std::uint8_t*>(p_raw.data())),
UUID_BYTE_SIZE};
m_uuid = uuids::uuid {raw};
@@ -50,9 +50,10 @@ std::span<const std::byte, UUID::UUID_BYTE_SIZE> UUID::ToBytes() const
/****************************************************************************************/
std::string UUID::ToString() const
eastl::string UUID::ToString() const
{
return uuids::to_string(m_uuid);
const std::string uuid = uuids::to_string(m_uuid);
return eastl::string {uuid.data(), uuid.size()};
}
/****************************************************************************************/
@@ -25,20 +25,21 @@ int main(int argc, char** argv)
std::string bigFilePath;
std::string outputPath;
auto cli = lyra::help(showHelp) |
lyra::opt(bigFilePath, "bigfile")["-b"]["--bigfile"]("The BigFile to bake (must exist)").required() |
lyra::opt(outputPath, "output")["-o"]["--output"]("The Sasquatch file to write").required();
const auto& cli = lyra::help(showHelp) |
lyra::opt(bigFilePath, "bigfile")["-b"]["--bigfile"]("The BigFile to bake (must exist)")
.required() |
lyra::opt(outputPath, "output")["-o"]["--output"]("The Sasquatch file to write").required();
const lyra::parse_result result = cli.parse({argc, argv});
if (!result)
{
std::cerr << result.message() << "\n\n" << cli << std::endl;
std::cerr << result.message() << "\n\n" << cli << '\n';
return 1;
}
if (showHelp)
{
std::cout << cli << std::endl;
std::cout << cli << '\n';
return 0;
}
@@ -10,7 +10,7 @@
#include <SasquatchBaker/SasquatchBakerLogger_generated.hpp>
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
namespace Bigfoot
{
@@ -15,7 +15,7 @@ namespace Bigfoot
/*
* Logger
*/
inline Log::LoggerInfo SASQUATCHBAKER_LOGGER {"SASQUATCHBAKER_LOGGER", Flat::LogLevel::Trace};
inline Log::LoggerInfo SASQUATCHBAKER_LOGGER { .m_name = "SASQUATCHBAKER_LOGGER", .m_level = Flat::LogLevel::Trace};
} // namespace Bigfoot
#endif
#endif
@@ -47,7 +47,7 @@ void Bake(const BigFile& p_bigFile, const File& p_outputFile)
BigFile::Request request {p_bigFile, "SELECT UUID FROM Asset;"};
while (request.Step())
{
const eastl::span<const std::byte> rawUUID = request.Get(0);
const std::span<const std::byte> rawUUID = request.Get(0);
ASSERT(SasquatchBakerAssertHandler,
rawUUID.size() == UUID::UUID_BYTE_SIZE,
@@ -67,11 +67,11 @@ bool LayeredTopologicalSort(const ankerl::unordered_dense::map<NODE_TYPE, eastl:
std::uint32_t degree = 0;
for (const NODE_TYPE& edge: p_graph.at(indexToNode[index]))
{
const auto it = nodeToIndex.find(edge);
if (it != nodeToIndex.end())
const auto nodeIt = nodeToIndex.find(edge);
if (nodeIt != nodeToIndex.end())
{
++degree;
++adjacencyOffsets[it->second + 1];
++adjacencyOffsets[nodeIt->second + 1];
}
}
@@ -93,10 +93,10 @@ bool LayeredTopologicalSort(const ankerl::unordered_dense::map<NODE_TYPE, eastl:
{
for (const NODE_TYPE& edge: p_graph.at(indexToNode[index]))
{
const auto it = nodeToIndex.find(edge);
if (it != nodeToIndex.end())
const auto nodeIt = nodeToIndex.find(edge);
if (nodeIt != nodeToIndex.end())
{
adjacency[cursor[it->second]++] = index;
adjacency[cursor[nodeIt->second]++] = index;
}
}
}
@@ -7,26 +7,23 @@
#ifndef BIGFOOT_UTILS_ASSERT_HPP
#define BIGFOOT_UTILS_ASSERT_HPP
#include <Utils/Log/LogMacros.hpp>
#include <Utils/TargetMacros.h>
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
#include <Utils/Format.hpp>
#include <EASTL/fixed_function.h>
#include <EASTL/string.h>
#include <cstdlib>
#include <source_location>
#include <string>
#if defined BIGFOOT_LINUX
#ifdef BIGFOOT_LINUX
#include <csignal>
#endif
#define BIGFOOT_FLUSH_LOG \
do \
{ \
if (Bigfoot::Singleton<Bigfoot::Log>::HasInstance()) \
{ \
Bigfoot::Singleton<Bigfoot::Log>::GetInstance().Flush(); \
} \
} while (false)
#if defined BIGFOOT_WINDOWS
#ifdef BIGFOOT_WINDOWS
#define BREAK \
do \
{ \
@@ -42,39 +39,68 @@
} while (false)
#endif
namespace Bigfoot
{
/**
* Assert then break
*
* \param p_condition The condition to check
* \param p_message A function that will return the formatting string describing the issue
* \param p_location The location the assert originates from
*/
template<typename HANDLER>
BIGFOOT_ALWAYS_INLINE void AssertCheck(const bool p_condition,
const eastl::fixed_function<32, eastl::string()>& p_messageFn,
const std::source_location p_location = std::source_location::current())
{
if (!p_condition) [[unlikely]]
{
HANDLER::Handle(p_location, p_messageFn());
BREAK;
}
}
/**
* Assert then break then kill
*
* \param p_condition The condition to check
* \param p_message A function that will return the formatting string describing the issue
* \param p_location The location the assert originates from
*/
template<typename HANDLER>
BIGFOOT_ALWAYS_INLINE void CriticalAssertCheck(const bool p_condition,
const eastl::fixed_function<32, eastl::string()>& p_messageFn,
const std::source_location p_location = std::source_location::current())
{
if (!p_condition) [[unlikely]]
{
HANDLER::Handle(p_location, p_messageFn());
BREAK;
std::abort();
}
}
} // namespace Bigfoot
#define ASSERT(HANDLER, p_assert, p_message, ...) \
do \
{ \
constexpr std::source_location location = std::source_location::current(); \
if (!(p_assert)) [[unlikely]] \
{ \
HANDLER::Handle(location, p_message __VA_OPT__(, ) __VA_ARGS__); \
BREAK; \
} \
} while (false)
::Bigfoot::AssertCheck<HANDLER>((p_assert), \
[&] \
{ \
return ::Bigfoot::Format(p_message __VA_OPT__(, ) __VA_ARGS__); \
})
#define SOFT_ASSERT(HANDLER, p_assert, p_message, ...) \
do \
{ \
constexpr std::source_location location = std::source_location::current(); \
if (!(p_assert)) [[unlikely]] \
{ \
HANDLER::Handle(location, p_message __VA_OPT__(, ) __VA_ARGS__); \
BREAK; \
} \
} while (false)
::Bigfoot::AssertCheck<HANDLER>((p_assert), \
[&] \
{ \
return ::Bigfoot::Format(p_message __VA_OPT__(, ) __VA_ARGS__); \
})
#define CRITICAL_ASSERT(HANDLER, p_assert, p_message, ...) \
do \
{ \
constexpr std::source_location location = std::source_location::current(); \
if (!(p_assert)) [[unlikely]] \
{ \
HANDLER::Handle(location, p_message __VA_OPT__(, ) __VA_ARGS__); \
BREAK; \
std::abort(); \
} \
} while (false)
::Bigfoot::CriticalAssertCheck<HANDLER>((p_assert), \
[&] \
{ \
return ::Bigfoot::Format(p_message __VA_OPT__(, ) __VA_ARGS__); \
})
#else
#define ASSERT(HANDLER, p_assert, p_message, ...)
@@ -9,9 +9,9 @@
#include <Utils/Assert/Assert.hpp>
#include <Utils/Log/Log.hpp>
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
#include <fmt/format.h>
#include <EASTL/string.h>
#include <source_location>
@@ -32,15 +32,13 @@ class AssertHandler
* Handle an assertion.
*
* \param p_location Location of the assertion.
* \param p_format Format string for the assertion message.
* \param p_args Arguments for the format string.
* \param p_message Message describing the assertion failure.
*/
template<typename... ARGS>
static void Handle(const std::source_location& p_location, fmt::format_string<ARGS...> p_format, ARGS&&... p_args)
static void Handle(const std::source_location& p_location, const eastl::string& p_message)
{
BIGFOOT_LOG_FATAL(LOGGER,
"Assert: {} (File:{}, Line:{}, Function:{}\n",
fmt::format(p_format, std::forward<ARGS>(p_args)...),
p_message,
p_location.file_name(),
p_location.line(),
p_location.function_name());
+9 -13
View File
@@ -6,37 +6,33 @@
*********************************************************************/
#ifndef BIGFOOT_UTILS_CASTER_HPP
#define BIGFOOT_UTILS_CASTER_HPP
#include <EASTL/type_traits.h>
#include <type_traits>
namespace Bigfoot
{
template<class TO,
class FROM,
eastl::enable_if_t<eastl::is_base_of_v<FROM, TO> || eastl::is_base_of_v<TO, FROM>, bool> = true>
template<class TO, class FROM>
requires(std::is_base_of_v<FROM, TO> || std::is_base_of_v<TO, FROM>)
constexpr TO* Cast(FROM* p_object)
{
return static_cast<TO*>(p_object);
}
template<class TO,
class FROM,
eastl::enable_if_t<eastl::is_base_of_v<FROM, TO> || eastl::is_base_of_v<TO, FROM>, bool> = true>
template<class TO, class FROM>
requires(std::is_base_of_v<FROM, TO> || std::is_base_of_v<TO, FROM>)
constexpr const TO* Cast(const FROM* p_object)
{
return static_cast<const TO*>(p_object);
}
template<class TO,
class FROM,
eastl::enable_if_t<eastl::is_base_of_v<FROM, TO> || eastl::is_base_of_v<TO, FROM>, bool> = true>
template<class TO, class FROM>
requires(std::is_base_of_v<FROM, TO> || std::is_base_of_v<TO, FROM>)
constexpr TO& Cast(FROM& p_object)
{
return static_cast<TO&>(p_object);
}
template<class TO,
class FROM,
eastl::enable_if_t<eastl::is_base_of_v<FROM, TO> || eastl::is_base_of_v<TO, FROM>, bool> = true>
template<class TO, class FROM>
requires(std::is_base_of_v<FROM, TO> || std::is_base_of_v<TO, FROM>)
constexpr const TO& Cast(const FROM& p_object)
{
return static_cast<const TO&>(p_object);
@@ -28,7 +28,7 @@ class SlotMapKey
private:
static constexpr std::uint32_t VERSION_BIT_COUNT = sizeof(VersionType) * std::numeric_limits<unsigned char>::digits;
static constexpr std::uint32_t INDEX_BIT_COUNT = sizeof(IndexType) * std::numeric_limits<unsigned char>::digits;
static_assert(VERSION_BIT_COUNT + INDEX_BIT_COUNT <= 64,
static_assert(VERSION_BIT_COUNT + INDEX_BIT_COUNT <= std::numeric_limits<std::uint64_t>::digits,
"We cant construct a 64 bit key from the given Version and Index types!");
static constexpr std::uint64_t INDEX_MASK = (static_cast<std::uint64_t>(1) << INDEX_BIT_COUNT) - 1;
@@ -115,10 +115,10 @@ class DenseSlotMap
public:
using SlotMapKey = SLOT_MAP_KEY_TYPE;
using iterator = typename eastl::vector<T>::iterator;
using const_iterator = typename eastl::vector<T>::const_iterator;
using reverse_iterator = typename eastl::vector<T>::reverse_iterator;
using const_reverse_iterator = typename eastl::vector<T>::const_reverse_iterator;
using iterator = eastl::vector<T>::iterator;
using const_iterator = eastl::vector<T>::const_iterator;
using reverse_iterator = eastl::vector<T>::reverse_iterator;
using const_reverse_iterator = eastl::vector<T>::const_reverse_iterator;
/**
* Check if the map has the key
@@ -402,7 +402,6 @@ class DenseSlotMap
m_freeListHead = p_key.GetIndex();
}
private:
/**
* The actual storage for our data
*/
@@ -431,12 +430,13 @@ class DenseSlotMap
template<class T, class SLOT_MAP_KEY_TYPE = SlotMapKey<>>
class StableSlotMap
{
private:
public:
static constexpr std::size_t PAGE_SIZE = 64;
private:
struct AlignedSlot
{
alignas(T) std::byte m_bytes[sizeof(T)];
alignas(T) eastl::array<std::byte, sizeof(T)> m_bytes;
};
struct Page
@@ -467,7 +467,8 @@ class StableSlotMap
T* Get(const std::size_t p_offset)
{
ASSERT(UtilsAssertHandler, m_occupied[p_offset], "Requesting a dead data!");
return std::launder(reinterpret_cast<T*>(m_data[p_offset].m_bytes));
void* const bytes = m_data[p_offset].m_bytes.data();
return std::launder(static_cast<T*>(bytes));
}
/**
@@ -479,7 +480,8 @@ class StableSlotMap
const T* Get(const std::size_t p_offset) const
{
ASSERT(UtilsAssertHandler, m_occupied[p_offset], "Requesting a dead data!");
return std::launder(reinterpret_cast<const T*>(m_data[p_offset].m_bytes));
const void* const bytes = m_data[p_offset].m_bytes.data();
return std::launder(static_cast<const T*>(bytes));
}
/**
@@ -527,7 +529,8 @@ class StableSlotMap
IteratorImpl() = default;
// Allows an iterator to be implicitly used as a const_iterator.
template<class OTHER_VALUE_TYPE, class = std::enable_if_t<std::is_same_v<VALUE_TYPE, const OTHER_VALUE_TYPE>>>
template<class OTHER_VALUE_TYPE>
requires std::is_same_v<VALUE_TYPE, const OTHER_VALUE_TYPE>
IteratorImpl(const IteratorImpl<OTHER_VALUE_TYPE>& p_other):
m_map(p_other.m_map),
m_pageIt(p_other.m_pageIt),
@@ -777,7 +780,7 @@ class StableSlotMap
Page* const page = GetPageAt(pageIndex);
const std::size_t offsetInPage = GetDataOffset(key);
new (page->m_data[offsetInPage].m_bytes) T(std::forward<ARGS>(p_args)...);
new (page->m_data[offsetInPage].m_bytes.data()) T(std::forward<ARGS>(p_args)...);
page->m_occupied.set(offsetInPage);
return key;
@@ -835,7 +838,7 @@ class StableSlotMap
{
std::destroy_at(page->Get(offset));
const std::size_t keyIndex = pageIndex * PAGE_SIZE + offset;
const std::size_t keyIndex = (pageIndex * PAGE_SIZE) + offset;
RecycleKey(SlotMapKey {m_keys[keyIndex].GetVersion(), static_cast<SlotMapKey::IndexType>(keyIndex)});
}
page->m_occupied.reset();
@@ -870,9 +873,9 @@ class StableSlotMap
[[nodiscard]]
iterator begin()
{
iterator it {this};
it.SeekFirstFrom(m_pages.begin());
return it;
iterator result {this};
result.SeekFirstFrom(m_pages.begin());
return result;
}
[[nodiscard]]
@@ -884,9 +887,9 @@ class StableSlotMap
[[nodiscard]]
const_iterator begin() const
{
const_iterator it {this};
it.SeekFirstFrom(m_pages.begin());
return it;
const_iterator result {this};
result.SeekFirstFrom(m_pages.begin());
return result;
}
[[nodiscard]]
@@ -1024,7 +1027,6 @@ class StableSlotMap
return m_pages[p_pageIndex].get();
}
private:
/**
* The pages
*/
@@ -0,0 +1,31 @@
/*********************************************************************
* \file Format.hpp
*
* \author Romain BOULLARD
* \date September 2026
*********************************************************************/
#ifndef BIGFOOT_UTILS_FORMAT_HPP
#define BIGFOOT_UTILS_FORMAT_HPP
#include <EASTL/string.h>
#include <fmt/format.h>
#include <iterator>
namespace Bigfoot
{
/**
* Format a string, like fmt::format, but returning an eastl::string instead of a std::string.
*
* \param p_format The format string
* \param p_args The arguments for the format string
* \return The formatted eastl::string
*/
template<typename... ARGS>
eastl::string Format(fmt::format_string<ARGS...> p_format, ARGS&&... p_args)
{
fmt::memory_buffer buffer;
fmt::format_to(std::back_inserter(buffer), p_format, std::forward<ARGS>(p_args)...);
return eastl::string {buffer.data(), buffer.size()};
}
} // namespace Bigfoot
#endif
@@ -8,7 +8,7 @@
#define BIGFOOT_UTILS_LOG_EASTLFORMATTERS_HPP
#include <Utils/TargetMacros.h>
#if defined(BIGFOOT_NOT_OPTIMIZED)
#ifdef BIGFOOT_NOT_OPTIMIZED
#include <quill/core/Codec.h>
#endif
@@ -24,27 +24,27 @@
template<>
struct fmt::formatter<eastl::string>
{
constexpr auto parse(format_parse_context& ctx)
static constexpr auto parse(format_parse_context& ctx)
{
return ctx.begin();
}
auto format(const eastl::string& p_string, format_context& ctx) const
static auto format(const eastl::string& p_string, format_context& ctx)
{
return fmt::format_to(ctx.out(), "{}", p_string.c_str());
}
};
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
template<>
struct fmtquill::formatter<eastl::string>
{
constexpr auto parse(format_parse_context& ctx)
static constexpr auto parse(format_parse_context& ctx)
{
return ctx.begin();
}
auto format(const eastl::string& p_string, format_context& ctx) const
static auto format(const eastl::string& p_string, format_context& ctx)
{
return fmtquill::format_to(ctx.out(), "{}", p_string.c_str());
}
@@ -56,27 +56,27 @@ struct fmtquill::formatter<eastl::string>
template<>
struct fmt::formatter<eastl::string_view>
{
constexpr auto parse(format_parse_context& ctx)
static constexpr auto parse(format_parse_context& ctx)
{
return ctx.begin();
}
auto format(const eastl::string_view& p_stringView, format_context& ctx) const
static auto format(const eastl::string_view& p_stringView, format_context& ctx)
{
return fmt::format_to(ctx.out(), "{}", p_stringView.data());
}
};
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
template<>
struct fmtquill::formatter<eastl::string_view>
{
constexpr auto parse(format_parse_context& ctx)
static constexpr auto parse(format_parse_context& ctx)
{
return ctx.begin();
}
auto format(const eastl::string_view& p_stringView, format_context& ctx) const
static auto format(const eastl::string_view& p_stringView, format_context& ctx)
{
return fmtquill::format_to(ctx.out(), "{}", p_stringView.data());
}
@@ -141,7 +141,7 @@ struct fmt::formatter<eastl::vector<T>>
}
};
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
#include <quill/DeferredFormatCodec.h>
template<class T>
@@ -8,7 +8,7 @@
#define BIGFOOT_UTILS_LOG_LOG_HPP
#include <Utils/Log/EASTLFormatters.hpp>
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
#include <Utils/Log/Log_generated.hpp>
#include <EASTL/array.h>
@@ -23,7 +23,7 @@
#include <quill/Logger.h>
#include <quill/sinks/ConsoleSink.h>
#include <quill/sinks/FileSink.h>
#if defined BIGFOOT_WINDOWS
#ifdef BIGFOOT_WINDOWS
#pragma warning(default: 4702)
#endif
@@ -9,7 +9,16 @@
#include <Utils/Log/Log.hpp>
#include <Utils/Singleton.hpp>
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
#define BIGFOOT_FLUSH_LOG \
do \
{ \
if (Bigfoot::Singleton<Bigfoot::Log>::HasInstance()) \
{ \
Bigfoot::Singleton<Bigfoot::Log>::GetInstance().Flush(); \
} \
} while (false)
#define BIGFOOT_LOG_DEBUG(loggerName, fmt, ...) \
do \
{ \
@@ -102,7 +111,7 @@
#define BIGFOOT_LOG_FATAL(loggerName, fmt, ...)
#endif
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
#define BIGFOOT_LOG_DEBUG_IF(condition, loggerName, fmt, ...) \
do \
{ \
@@ -15,7 +15,7 @@ namespace Bigfoot
/*
* Logger
*/
inline Log::LoggerInfo @LOGGER_NAME@ {"@LOGGER_NAME@", Flat::LogLevel::Trace};
inline Log::LoggerInfo @LOGGER_NAME@ { .m_name = "@LOGGER_NAME@", .m_level = Flat::LogLevel::Trace};
} // namespace Bigfoot
#endif
#endif
@@ -33,6 +33,7 @@ class TaggedType
return m_value;
}
[[nodiscard]]
constexpr TYPE Get() const
{
return m_value;
@@ -7,33 +7,39 @@
#ifndef BIGFOOT_UTILS_TARGETMACROS_H
#define BIGFOOT_UTILS_TARGETMACROS_H
#if defined BIGFOOT_WINDOWS
#ifdef BIGFOOT_WINDOWS
#define BIGFOOT_WINDOWS_OR_LINUX(p_windows, p_linux) p_windows
#endif
#if defined BIGFOOT_LINUX
#ifdef BIGFOOT_LINUX
#define BIGFOOT_WINDOWS_OR_LINUX(p_windows, p_linux) p_linux
#endif
#if defined BIGFOOT_OPTIMIZED
#ifdef BIGFOOT_WINDOWS
#define BIGFOOT_ALWAYS_INLINE [[msvc::forceinline]]
#elif defined BIGFOOT_LINUX
#define BIGFOOT_ALWAYS_INLINE [[gnu::always_inline]] inline
#endif
#ifdef BIGFOOT_OPTIMIZED
#define BIGFOOT_OPTIMIZED_ONLY(...) __VA_ARGS__
#define BIGFOOT_NOT_OPTIMIZED_ONLY(...)
#define BIGFOOT_OPTIMIZED_OR_NOT(p_optimized, p_notOptimized) p_optimized
#endif
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
#define BIGFOOT_OPTIMIZED_ONLY(...)
#define BIGFOOT_NOT_OPTIMIZED_ONLY(...) __VA_ARGS__
#define BIGFOOT_OPTIMIZED_OR_NOT(p_optimized, p_notOptimized) p_notOptimized
#endif
#if defined BIGFOOT_TOOLMODE
#ifdef BIGFOOT_TOOLMODE
#define BIGFOOT_TOOLMODE_ONLY(...) __VA_ARGS__
#define BIGFOOT_GAME_ONLY(...)
#define BIGFOOT_GAME_OR_TOOLMODE(p_game, p_toolmode) p_toolmode
#endif
#if defined BIGFOOT_GAME
#ifdef BIGFOOT_GAME
#define BIGFOOT_TOOLMODE_ONLY(...)
#define BIGFOOT_GAME_ONLY(...) __VA_ARGS__
#define BIGFOOT_GAME_OR_TOOLMODE(p_game, p_toolmode) p_game
@@ -9,7 +9,7 @@
#include <Utils/Assert/AssertHandler.hpp>
#include <Utils/UtilsLogger_generated.hpp>
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
namespace Bigfoot
{
@@ -15,7 +15,7 @@ namespace Bigfoot
/*
* Logger
*/
inline Log::LoggerInfo UTILS_LOGGER {"UTILS_LOGGER", Flat::LogLevel::Trace};
inline Log::LoggerInfo UTILS_LOGGER { .m_name = "UTILS_LOGGER", .m_level = Flat::LogLevel::Trace};
} // namespace Bigfoot
#endif
#endif
@@ -7,17 +7,22 @@
#ifndef BIGFOOT_UTILS_VERSION_HPP
#define BIGFOOT_UTILS_VERSION_HPP
#include <Utils/Caster.hpp>
#include <Utils/Format.hpp>
#include <Utils/TargetMacros.h>
#include <EASTL/string.h>
#include <fmt/format.h>
#include <cstdint>
#include <string>
namespace Bigfoot
{
class Version
{
private:
static constexpr std::uint32_t MAJOR_SHIFT = 16;
static constexpr std::uint32_t MINOR_SHIFT = 8;
public:
Version() = default;
@@ -39,7 +44,7 @@ class Version
* \param p_patch Patch
*/
constexpr Version(const std::uint8_t p_major, const std::uint8_t p_minor, const std::uint8_t p_patch):
m_combined((p_major << 16) | (p_minor << 8) | p_patch)
m_combined((p_major << MAJOR_SHIFT) | (p_minor << MINOR_SHIFT) | p_patch)
{
}
@@ -99,7 +104,7 @@ class Version
* \return The string
*/
[[nodiscard]]
std::string ToString() const;
eastl::string ToString() const;
[[nodiscard]]
constexpr auto operator<=>(const Version& p_version) const = default;
@@ -126,7 +131,7 @@ struct fmt::formatter<Bigfoot::Version>
template<typename FormatContext>
auto format(const Bigfoot::Version& p_version, FormatContext& p_context) const
{
return fmt::format_to(p_context.out(), "{}", p_version.ToString());
return fmt::format_to(p_context.out(), "{}", p_version.ToString().c_str());
}
};
#endif
+1 -1
View File
@@ -6,7 +6,7 @@
*********************************************************************/
#include <Utils/Log/Log.hpp>
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
namespace Bigfoot
{
+2
View File
@@ -4,6 +4,7 @@
* \author Romain BOULLARD
* \date October 2025
*********************************************************************/
// NOLINTBEGIN
#include <Utils/Profiler.hpp>
#if defined BIGFOOT_WINDOWS
@@ -96,3 +97,4 @@
#pragma clang diagnostic pop
#endif
#endif
// NOLINTEND
+2 -2
View File
@@ -8,8 +8,8 @@
namespace Bigfoot
{
std::string Version::ToString() const
eastl::string Version::ToString() const
{
return fmt::format("{}.{}.{}", GetMajor(), GetMinor(), GetPatch());
return Format("{}.{}.{}", GetMajor(), GetMinor(), GetPatch());
}
} // namespace Bigfoot
+5
View File
@@ -0,0 +1,5 @@
InheritParentConfig: true
Checks: >
-cppcoreguidelines-non-private-member-variables-in-classes,
-cppcoreguidelines-avoid-magic-numbers,
-readability-magic-numbers
+54
View File
@@ -20,6 +20,10 @@ class AssetFixture: public ::testing::Test
protected:
void SetUp() override
{
SetActiveAssetLibrary(&m_library);
std::ignore = m_library.Insert(&m_containerA);
std::ignore = m_library.Insert(&m_containerB);
const UUID uuidA = m_assetA.GetHeader().uuid;
const UUID uuidB = m_assetB.GetHeader().uuid;
@@ -35,6 +39,15 @@ class AssetFixture: public ::testing::Test
m_assetC.GetAsset().asset_b_refs.push_back(SoftReference<AssetB> {uuidB});
}
void TearDown() override
{
SetActiveAssetLibrary(&g_assetLibrary);
}
AssetLibrary m_library;
AssetContainer<AssetA> m_containerA;
AssetContainer<AssetB> m_containerB;
AssetA m_assetA;
AssetB m_assetB;
AssetC m_assetC;
@@ -117,4 +130,45 @@ TEST_F(AssetFixture, GetHardReferences_ShouldReturnTheHardReferencesOfTheAsset)
EXPECT_THAT(hardReferences, ::testing::UnorderedElementsAre(m_assetA.GetHeader().uuid, m_assetB.GetHeader().uuid));
}
/****************************************************************************************/
TEST_F(AssetFixture, CreateAsset_ShouldReturnTheCreatedAsset)
{
EXPECT_NE(CreateAsset<AssetA>(), nullptr);
}
/****************************************************************************************/
TEST_F(AssetFixture, CreateAsset_ShouldCreateUniqueAssets)
{
const AssetA* first = CreateAsset<AssetA>();
const AssetA* second = CreateAsset<AssetA>();
EXPECT_NE(first->GetHeader().uuid, second->GetHeader().uuid);
}
/****************************************************************************************/
TEST_F(AssetFixture, CreateAsset_ShouldReturnTheSameAssetAsItsContainerHandle)
{
const AssetA* asset = CreateAsset<AssetA>();
const ContainerHandle* handle = m_containerA.AcquireContainerHandle(asset->GetHeader().uuid);
EXPECT_EQ(handle->GetAsset(), asset);
}
/****************************************************************************************/
TEST_F(AssetFixture, CreateAsset_ShouldInsertTheAssetIntoItsCorrespondingContainer)
{
const AssetA* assetA = CreateAsset<AssetA>();
const AssetB* assetB = CreateAsset<AssetB>();
EXPECT_TRUE(m_containerA.Has(assetA->GetHeader().uuid));
EXPECT_FALSE(m_containerB.Has(assetA->GetHeader().uuid));
EXPECT_TRUE(m_containerB.Has(assetB->GetHeader().uuid));
EXPECT_FALSE(m_containerA.Has(assetB->GetHeader().uuid));
}
} // namespace Bigfoot
+15 -1
View File
@@ -24,7 +24,7 @@ class ContainerHandleFixture: public ::testing::Test
AssetContainer<AssetA> m_containerA;
UUID m_uuid;
ContainerHandle* m_handle;
ContainerHandle* m_handle = nullptr;
};
/****************************************************************************************/
@@ -168,6 +168,20 @@ TEST_F(AssetContainerFixture, Insert_ShouldReturnAHandleWithTheInsertedAsset)
/****************************************************************************************/
TEST_F(AssetContainerFixture, Insert_ShouldReuseTheExistingHandleWhenInsertingAnAssetWithAnAlreadyExistingUUID)
{
ContainerHandle* const firstHandle = m_containerA.Insert();
const AssetBase* const firstAsset = firstHandle->GetAsset();
const eastl::vector<std::byte> packed = firstAsset->Pack();
ContainerHandle* const secondHandle = m_containerA.Insert(packed);
EXPECT_EQ(secondHandle, firstHandle);
EXPECT_EQ(secondHandle->GetAsset(), firstAsset);
}
/****************************************************************************************/
TEST_F(AssetContainerFixture, Remove_ShouldRemoveTheAsset)
{
const ContainerHandle* handle = m_containerA.Insert();
@@ -170,6 +170,76 @@ TEST_F(AssetLibraryFixture, ProcessPendingRemovals_ShouldNotRemoveAssetsThatAreN
/****************************************************************************************/
TEST_F(AssetLibraryFixture, ProcessPendingRemovals_ShouldCascadeThroughHardReferencedAssetsOneLevelPerCall)
{
const ScopedActiveAssetLibrary activeAssetLibraryScoped {&m_library};
std::ignore = m_library.Insert(&m_containerA);
std::ignore = m_library.Insert(&m_containerB);
std::ignore = m_library.Insert(&m_containerC);
UUID leafUUID;
UUID middleUUID;
UUID rootUUID;
{
// leaf
AssetA* leaf = CreateAsset<AssetA>();
leafUUID = leaf->GetHeader().uuid;
// middle --> leaf
AssetB* middle = CreateAsset<AssetB>();
middle->GetAsset().ref_a = HardReference<AssetA> {leafUUID};
middleUUID = middle->GetHeader().uuid;
// root
// / \
// v v
// middle --> leaf
AssetC* root = CreateAsset<AssetC>();
root->GetAsset().asset_b_ref = HardReference<AssetB> {middleUUID};
root->GetAsset().inner_table->asset_a_ref = HardReference<AssetA> {leafUUID};
rootUUID = root->GetHeader().uuid;
const HardReference<AssetC> rootRef {rootUUID};
const HardReference<AssetB> middleRef {middleUUID};
const HardReference<AssetA> leafRef {leafUUID};
ASSERT_NE(rootRef.Get(), nullptr);
ASSERT_NE(middleRef.Get(), nullptr);
ASSERT_NE(leafRef.Get(), nullptr);
}
// Releasing the outer HardReferences only drops root's count to zero: middle and leaf are
// still kept alive by root's own internal HardReferences to them.
EXPECT_TRUE(m_containerC.IsMarkedForRemove(rootUUID));
EXPECT_FALSE(m_containerB.IsMarkedForRemove(middleUUID));
EXPECT_FALSE(m_containerA.IsMarkedForRemove(leafUUID));
EXPECT_TRUE(m_library.IsLoaded(rootUUID));
EXPECT_TRUE(m_library.IsLoaded(middleUUID));
EXPECT_TRUE(m_library.IsLoaded(leafUUID));
// 1st pass: removing root destroys its HardReference to middle, dropping middle's count to
// zero; leaf is still held alive by middle's own HardReference to it.
m_library.ProcessPendingRemovals();
EXPECT_FALSE(m_library.IsLoaded(rootUUID));
EXPECT_TRUE(m_containerB.IsMarkedForRemove(middleUUID));
EXPECT_TRUE(m_library.IsLoaded(middleUUID));
EXPECT_TRUE(m_library.IsLoaded(leafUUID));
// 2nd pass: removing middle destroys its HardReference to leaf, dropping leaf's count to zero.
m_library.ProcessPendingRemovals();
EXPECT_FALSE(m_library.IsLoaded(middleUUID));
EXPECT_TRUE(m_containerA.IsMarkedForRemove(leafUUID));
EXPECT_TRUE(m_library.IsLoaded(leafUUID));
// 3rd pass: nothing references leaf anymore, it finally gets removed.
m_library.ProcessPendingRemovals();
EXPECT_FALSE(m_library.IsLoaded(leafUUID));
}
/****************************************************************************************/
TEST_F(AssetLibraryFixture, SetActiveAssetLibrary_ShouldSetTheActiveAssetLibraryToTheGivenLibrary)
{
SetActiveAssetLibrary(&m_library);
+5 -5
View File
@@ -66,7 +66,7 @@ class ReferenceTypeNameGenerator
{
public:
template<typename T>
static std::string GetName(int)
static std::string GetName([[maybe_unused]] int p_index)
{
if constexpr (std::is_same_v<T, HardReference<AssetA>>)
{
@@ -96,7 +96,7 @@ TYPED_TEST(ReferenceFixture, GetUUID_ShouldReturnTheUUID)
TYPED_TEST(ReferenceFixture, Get_ShouldReturnTheAsset)
{
const AssetA* inserted = static_cast<const AssetA*>(this->m_containerA.Insert()->GetAsset());
const AssetA* inserted = CreateAsset<AssetA>();
const UUID uuid = inserted->GetHeader().uuid;
TypeParam ref {uuid};
@@ -120,7 +120,7 @@ TYPED_TEST(ReferenceFixture, Get_ShouldReturnNullptrIfTheAssetDoesNotExist)
TYPED_TEST(ReferenceFixture, Get_ShouldReturnNullptrAfterTheAssetIsRemovedFromTheContainer)
{
const AssetA* inserted = static_cast<const AssetA*>(this->m_containerA.Insert()->GetAsset());
const AssetA* inserted = CreateAsset<AssetA>();
const UUID uuid = inserted->GetHeader().uuid;
TypeParam ref {uuid};
@@ -157,7 +157,7 @@ TYPED_TEST(ReferenceFixture, ShouldTouchTheRefCountOfTheHandle)
TYPED_TEST(ReferenceFixture, CopyConstructor_ShouldIncrementTheRefCountAndCopyTheState)
{
const AssetA* inserted = static_cast<const AssetA*>(this->m_containerA.Insert()->GetAsset());
const AssetA* inserted = CreateAsset<AssetA>();
const UUID uuid = inserted->GetHeader().uuid;
const ContainerHandle* handle = this->m_containerA.AcquireContainerHandle(uuid);
@@ -175,7 +175,7 @@ TYPED_TEST(ReferenceFixture, CopyConstructor_ShouldIncrementTheRefCountAndCopyTh
TYPED_TEST(ReferenceFixture, MoveConstructor_ShouldTransferTheStateWithoutChangingTheRefCount)
{
const AssetA* inserted = static_cast<const AssetA*>(this->m_containerA.Insert()->GetAsset());
const AssetA* inserted = CreateAsset<AssetA>();
const UUID uuid = inserted->GetHeader().uuid;
const ContainerHandle* handle = this->m_containerA.AcquireContainerHandle(uuid);
@@ -26,7 +26,7 @@ class DataAccessorFixture: public ::testing::Test
}
DataAccessorMock m_accessor;
DataAccessor* m_original;
DataAccessor* m_original = nullptr;
};
/****************************************************************************************/
@@ -13,6 +13,8 @@ int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
GTEST_FLAG_SET(death_test_style, "threadsafe");
BIGFOOT_NOT_OPTIMIZED_ONLY(::Bigfoot::Singleton<::Bigfoot::Log>::Lifetime m_lifetime);
return RUN_ALL_TESTS();
@@ -9,7 +9,7 @@
#include <Engine/Asset/AssetLibrary.hpp>
#include <Engine/DataAccessor/DataAccessor.hpp>
#if defined BIGFOOT_TOOLMODE
#ifdef BIGFOOT_TOOLMODE
#include <Engine/BigFile/BigFile.hpp>
#include <EngineTests/BigFileInfo_generated.hpp>
@@ -91,7 +91,13 @@ class SerializationManagerFixture: public ::testing::Test
multiRootB.GetAsset().ref_a = HardReference<AssetA> {m_sharedChildUUID};
m_multiRootBUUID = multiRootB.GetHeader().uuid;
Populate({&leaf, &middle, &root, &cycleX, &cycleY, &sharedChild, &multiRootA, &multiRootB});
// missingRef --> unsavedUUID (never persisted to the data accessor)
AssetB missingRef;
missingRef.SetName("missingRef");
missingRef.GetAsset().ref_a = HardReference<AssetA> {m_unsavedUUID};
m_missingRefUUID = missingRef.GetHeader().uuid;
Populate({&leaf, &middle, &root, &cycleX, &cycleY, &sharedChild, &multiRootA, &multiRootB, &missingRef});
m_leafFlatbuffer = leaf.Pack();
m_middleFlatbuffer = middle.Pack();
@@ -99,6 +105,7 @@ class SerializationManagerFixture: public ::testing::Test
m_sharedChildFlatbuffer = sharedChild.Pack();
m_multiRootAFlatbuffer = multiRootA.Pack();
m_multiRootBFlatbuffer = multiRootB.Pack();
m_missingRefFlatbuffer = missingRef.Pack();
}
void TearDown() override
@@ -114,7 +121,7 @@ class SerializationManagerFixture: public ::testing::Test
*/
void Populate(const eastl::vector<AssetBase*>& p_assets)
{
#if defined BIGFOOT_TOOLMODE
#ifdef BIGFOOT_TOOLMODE
m_bigFile.emplace(File {BIGFILE_ENGINETESTS_LOCATION});
m_bigFile->Clear();
@@ -200,7 +207,12 @@ class SerializationManagerFixture: public ::testing::Test
UUID m_multiRootBUUID;
eastl::vector<std::byte> m_multiRootBFlatbuffer;
#if defined BIGFOOT_TOOLMODE
// HardReferences an asset that is never saved to the data accessor
const UUID m_unsavedUUID;
UUID m_missingRefUUID;
eastl::vector<std::byte> m_missingRefFlatbuffer;
#ifdef BIGFOOT_TOOLMODE
eastl::optional<BigFile> m_bigFile;
#elif defined BIGFOOT_GAME
eastl::optional<Sasquatch> m_sasquatch;
@@ -263,7 +275,7 @@ TEST_F(SerializationManagerFixture, LoadAsset_ShouldSkipAssetsThatAreCaughtInACy
TEST_F(SerializationManagerFixture, LoadAsset_ShouldNotReloadAnAssetThatIsAlreadyLoaded)
{
AssetA* alreadyLoaded = static_cast<AssetA*>(m_containerA.Insert()->GetAsset());
AssetA* alreadyLoaded = CreateAsset<AssetA>();
alreadyLoaded->SetName("in-memory");
const UUID uuid = alreadyLoaded->GetHeader().uuid;
@@ -278,6 +290,37 @@ TEST_F(SerializationManagerFixture, LoadAsset_ShouldNotReloadAnAssetThatIsAlread
/****************************************************************************************/
TEST_F(SerializationManagerFixture, LoadAssets_ShouldNotFailWhenTheSameRootIsPassedTwice)
{
const HardReference<AssetA> leafRef {m_leafUUID};
ASSERT_EQ(leafRef.Get(), nullptr);
const eastl::array<UUID, 2> roots {m_leafUUID, m_leafUUID};
SerializationManager::LoadAssets(roots);
ASSERT_NE(leafRef.Get(), nullptr);
EXPECT_EQ(leafRef.Get()->Pack(), m_leafFlatbuffer);
}
/****************************************************************************************/
TEST_F(SerializationManagerFixture, LoadAsset_ShouldSkipHardReferencesThatCouldNotBeFound)
{
const HardReference<AssetB> missingRefRef {m_missingRefUUID};
const HardReference<AssetA> unsavedRef {m_unsavedUUID};
ASSERT_EQ(missingRefRef.Get(), nullptr);
ASSERT_EQ(unsavedRef.Get(), nullptr);
SerializationManager::LoadAsset(m_missingRefUUID);
ASSERT_NE(missingRefRef.Get(), nullptr);
EXPECT_EQ(missingRefRef.Get()->Pack(), m_missingRefFlatbuffer);
EXPECT_EQ(unsavedRef.Get(), nullptr);
}
/****************************************************************************************/
TEST_F(SerializationManagerFixture, LoadAssets_ShouldLoadEveryRootAndMergeSharedHardReferences)
{
const HardReference<AssetA> sharedChildRef {m_sharedChildUUID};
@@ -305,7 +348,7 @@ TEST_F(SerializationManagerFixture, LoadAssets_ShouldLoadEveryRootAndMergeShared
#ifdef BIGFOOT_TOOLMODE
TEST_F(SerializationManagerFixture, SaveAsset_ShouldSaveTheAsset)
{
AssetB* asset = static_cast<AssetB*>(m_containerB.Insert()->GetAsset());
AssetB* asset = CreateAsset<AssetB>();
const UUID referencedUUID;
asset->GetAsset().ref_a = HardReference<AssetA> {referencedUUID};
@@ -323,7 +366,7 @@ TEST_F(SerializationManagerFixture, SaveAsset_ShouldSaveTheAsset)
TEST_F(SerializationManagerFixture, SaveAsset_ShouldFailAndNotSaveIfAnAssetHardReferencesItself)
{
AssetB* asset = static_cast<AssetB*>(m_containerB.Insert()->GetAsset());
AssetB* asset = CreateAsset<AssetB>();
const UUID uuid = asset->GetHeader().uuid;
asset->GetAsset().ref_a = HardReference<AssetA> {uuid};
@@ -338,8 +381,8 @@ TEST_F(SerializationManagerFixture, SaveAsset_ShouldFailAndNotSaveIfAnAssetHardR
TEST_F(SerializationManagerFixture, SaveAssets_ShouldFailAndNotSaveIfTwoAssetsInTheSameSaveHardReferenceEachOther)
{
AssetB* assetX = static_cast<AssetB*>(m_containerB.Insert()->GetAsset());
AssetB* assetY = static_cast<AssetB*>(m_containerB.Insert()->GetAsset());
AssetB* assetX = CreateAsset<AssetB>();
AssetB* assetY = CreateAsset<AssetB>();
const UUID uuidX = assetX->GetHeader().uuid;
const UUID uuidY = assetY->GetHeader().uuid;
@@ -361,7 +404,7 @@ TEST_F(SerializationManagerFixture, SaveAssets_ShouldFailAndNotSaveIfTwoAssetsIn
TEST_F(SerializationManagerFixture, SaveAssets_ShouldFailAndNotSaveIfAnAlreadySavedHardReferencePointsBackToIt)
{
AssetB* asset = static_cast<AssetB*>(m_containerB.Insert()->GetAsset());
AssetB* asset = CreateAsset<AssetB>();
const UUID uuid = asset->GetHeader().uuid;
const UUID referencedUUID;
asset->GetAsset().ref_a = HardReference<AssetA> {referencedUUID};
@@ -383,8 +426,8 @@ TEST_F(SerializationManagerFixture, SaveAssets_ShouldFailAndNotSaveIfAnAlreadySa
TEST_F(SerializationManagerFixture, SaveAssets_ShouldSaveEveryAsset)
{
const AssetA* assetX = static_cast<const AssetA*>(m_containerA.Insert()->GetAsset());
const AssetA* assetY = static_cast<const AssetA*>(m_containerA.Insert()->GetAsset());
const AssetA* assetX = CreateAsset<AssetA>();
const AssetA* assetY = CreateAsset<AssetA>();
const UUID uuidX = assetX->GetHeader().uuid;
const UUID uuidY = assetY->GetHeader().uuid;
+7 -7
View File
@@ -103,7 +103,7 @@ TEST_F(FileFixture, GetSize_ShouldReturnZeroForAnEmptyFile)
TEST_F(FileFixture, GetSize_ShouldReturnTheFileSize)
{
constexpr eastl::string_view content = "Hello, Sasquatch!";
m_writeScratchFile.Write({std::bit_cast<const std::byte*>(content.data()), content.size()}, 0);
m_writeScratchFile.Write({reinterpret_cast<const std::byte*>(content.data()), content.size()}, 0);
EXPECT_EQ(m_writeScratchFile.GetSize(), content.size());
}
@@ -113,7 +113,7 @@ TEST_F(FileFixture, GetSize_ShouldReturnTheFileSize)
TEST_F(FileFixture, Read_ShouldReturnTheRequestedBytesAtTheGivenOffset)
{
constexpr eastl::string_view content = "Hello, Sasquatch!";
m_writeScratchFile.Write({std::bit_cast<const std::byte*>(content.data()), content.size()}, 0);
m_writeScratchFile.Write({reinterpret_cast<const std::byte*>(content.data()), content.size()}, 0);
const eastl::vector<std::byte> data = m_writeScratchFile.Read(7, 10);
ASSERT_EQ(data.size(), 10);
@@ -125,7 +125,7 @@ TEST_F(FileFixture, Read_ShouldReturnTheRequestedBytesAtTheGivenOffset)
TEST_F(FileFixture, Write_ShouldCreateTheFileWithTheGivenContent)
{
constexpr eastl::string_view content = "Hello, Sasquatch!";
m_writeScratchFile.Write({std::bit_cast<const std::byte*>(content.data()), content.size()}, 0);
m_writeScratchFile.Write({reinterpret_cast<const std::byte*>(content.data()), content.size()}, 0);
const eastl::vector<std::byte> data = m_writeScratchFile.Read(0, m_writeScratchFile.GetSize());
ASSERT_EQ(data.size(), content.size());
@@ -137,10 +137,10 @@ TEST_F(FileFixture, Write_ShouldCreateTheFileWithTheGivenContent)
TEST_F(FileFixture, Write_ShouldNotTouchContentOutsideTheWrittenRange)
{
constexpr eastl::string_view initial = "Hello, Sasquatch!";
m_writeScratchFile.Write({std::bit_cast<const std::byte*>(initial.data()), initial.size()}, 0);
m_writeScratchFile.Write({reinterpret_cast<const std::byte*>(initial.data()), initial.size()}, 0);
constexpr eastl::string_view patch = "BIGFOOT";
m_writeScratchFile.Write({std::bit_cast<const std::byte*>(patch.data()), patch.size()}, 7);
m_writeScratchFile.Write({reinterpret_cast<const std::byte*>(patch.data()), patch.size()}, 7);
const eastl::vector<std::byte> data = m_writeScratchFile.Read(0, m_writeScratchFile.GetSize());
ASSERT_EQ(data.size(), initial.size());
@@ -165,11 +165,11 @@ TEST_F(FileFixture, Write_ShouldRoundTripArbitraryData)
static_assert(std::is_trivially_copyable_v<Payload>);
constexpr Payload payload {.m_intValue = 42, .m_doubleValue = 3.14, .m_tag = {'B', 'I', 'G', 'F'}};
m_writeScratchFile.Write({std::bit_cast<const std::byte*>(&payload), sizeof(payload)}, 0);
m_writeScratchFile.Write({reinterpret_cast<const std::byte*>(&payload), sizeof(payload)}, 0);
const eastl::vector<std::byte> data = m_writeScratchFile.Read(0, m_writeScratchFile.GetSize());
ASSERT_EQ(data.size(), sizeof(Payload));
EXPECT_EQ(*std::bit_cast<const Payload*>(data.data()), payload);
EXPECT_EQ(*reinterpret_cast<const Payload*>(data.data()), payload);
}
/****************************************************************************************/
@@ -13,6 +13,8 @@ int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
GTEST_FLAG_SET(death_test_style, "threadsafe");
BIGFOOT_NOT_OPTIMIZED_ONLY(::Bigfoot::Singleton<::Bigfoot::Log>::Lifetime m_lifetime);
return RUN_ALL_TESTS();
+11
View File
@@ -16,10 +16,21 @@ class TimeFixture: public ::testing::Test
{
public:
Time m_time {1'767'643'746'680'609};
Time m_earlierTime {1'767'643'746'680'608};
};
/****************************************************************************************/
TEST_F(TimeFixture, ComparisonOperators_ShouldOrderTimesByEpoch)
{
EXPECT_LT(m_earlierTime, m_time);
EXPECT_LE(m_earlierTime, m_time);
EXPECT_GT(m_time, m_earlierTime);
EXPECT_GE(m_time, m_earlierTime);
}
/****************************************************************************************/
TEST_F(TimeFixture, GetYear_ShouldReturnTheYear)
{
EXPECT_EQ(m_time.GetYear(), 2026);
+13 -4
View File
@@ -8,6 +8,8 @@
#include <System/UUID/UUID_generated.hpp>
#include <Utils/Format.hpp>
#include <ankerl/unordered_dense.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
@@ -171,12 +173,19 @@ TEST_F(UUIDFixture, GeneratingFiveMillionUniqueID)
/****************************************************************************************/
TEST_F(UUIDFixture, LessThanOperator_ShouldOrderTwoDifferentIDsConsistently)
{
EXPECT_LT(UUID::NULL_UUID, m_b);
}
/****************************************************************************************/
TEST_F(UUIDFixture, ToBytes_ShouldGiveBackTheRawDataOfTheID)
{
std::span<const std::byte, UUID::UUID_BYTE_SIZE> d = m_d.ToBytes();
std::span<const std::byte, UUID::UUID_BYTE_SIZE> idBytes = m_d.ToBytes();
std::span<const std::byte, UUID::UUID_BYTE_SIZE> raw = m_raw;
EXPECT_THAT(d, ::testing::ElementsAreArray(raw));
EXPECT_THAT(idBytes, ::testing::ElementsAreArray(raw));
}
/****************************************************************************************/
@@ -203,7 +212,7 @@ TEST_F(UUIDFixture, UnPack_ShouldGiveBackTheOriginalUUID)
TEST_F(UUIDFixture, FormatsUUID)
{
EXPECT_EQ(fmt::format("{}", m_b), m_b.ToString());
EXPECT_EQ(fmt::format("{}", UUID::NULL_UUID), "00000000-0000-0000-0000-000000000000");
EXPECT_STREQ(Format("{}", m_b).c_str(), m_b.ToString().c_str());
EXPECT_STREQ(Format("{}", UUID::NULL_UUID).c_str(), "00000000-0000-0000-0000-000000000000");
}
} // namespace Bigfoot
@@ -13,6 +13,8 @@ int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
GTEST_FLAG_SET(death_test_style, "threadsafe");
BIGFOOT_NOT_OPTIMIZED_ONLY(::Bigfoot::Singleton<::Bigfoot::Log>::Lifetime m_lifetime);
return RUN_ALL_TESTS();
+33
View File
@@ -0,0 +1,33 @@
/*********************************************************************
* \file Assert.cpp
*
* \author Romain BOULLARD
* \date September 2026
*********************************************************************/
#include <Utils/Assert/AssertHandler.hpp>
#include <UtilsTests/UtilsTestsLogger_generated.hpp>
#ifdef BIGFOOT_NOT_OPTIMIZED
#include <gtest/gtest.h>
namespace Bigfoot
{
using TestAssertHandler = AssertHandler<UTILSTESTS_LOGGER>;
/****************************************************************************************/
TEST(AssertDeathTest, Assert_ShouldTerminateTheProcessWhenTheConditionIsFalse)
{
EXPECT_DEATH({ ASSERT(TestAssertHandler, false, "Something went wrong: {}", 42); }, "");
}
/****************************************************************************************/
TEST(AssertDeathTest, CriticalAssert_ShouldTerminateTheProcessWhenTheConditionIsFalse)
{
EXPECT_DEATH({ CRITICAL_ASSERT(TestAssertHandler, false, "Something critical went wrong: {}", 42); }, "");
}
} // namespace Bigfoot
#endif
@@ -0,0 +1,62 @@
/*********************************************************************
* \file AssertHandler.cpp
*
* \author Romain BOULLARD
* \date September 2026
*********************************************************************/
#include <Utils/Assert/AssertHandler.hpp>
#include <Utils/Format.hpp>
#include <Utils/Singleton.hpp>
#include <UtilsTests/UtilsTestsLogger_generated.hpp>
#ifdef BIGFOOT_NOT_OPTIMIZED
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <fstream>
#include <source_location>
#include <sstream>
#include <string>
namespace Bigfoot
{
class AssertHandlerFixture: public ::testing::Test
{
protected:
static std::string ReadFileSinkContent()
{
Singleton<Log>::GetInstance().Flush();
std::ifstream file {std::string {Log::FILE_SINK_PATH.data()}};
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
};
/****************************************************************************************/
TEST_F(AssertHandlerFixture, Handle_ShouldLogAFatalMessageContainingTheGivenMessage)
{
constexpr std::source_location location = std::source_location::current();
AssertHandler<UTILSTESTS_LOGGER>::Handle(location, Format("Something went wrong: {}", 42));
EXPECT_THAT(ReadFileSinkContent(), ::testing::HasSubstr("Something went wrong: 42"));
}
/****************************************************************************************/
TEST_F(AssertHandlerFixture, Handle_ShouldLogAFatalMessageContainingTheSourceLocation)
{
constexpr std::source_location location = std::source_location::current();
AssertHandler<UTILSTESTS_LOGGER>::Handle(location, "Doesn't matter");
const std::string content = ReadFileSinkContent();
EXPECT_THAT(content, ::testing::HasSubstr(location.file_name()));
EXPECT_THAT(content, ::testing::HasSubstr(location.function_name()));
}
} // namespace Bigfoot
#endif
File diff suppressed because it is too large Load Diff
+48
View File
@@ -0,0 +1,48 @@
/*********************************************************************
* \file Format.cpp
*
* \author Romain BOULLARD
* \date September 2026
*********************************************************************/
#include <Utils/Format.hpp>
#include <EASTL/string.h>
#include <gtest/gtest.h>
namespace Bigfoot
{
TEST(Format, ShouldReturnAnEastlString)
{
const eastl::string result = Format("Hello");
EXPECT_STREQ(result.c_str(), "Hello");
}
/****************************************************************************************/
TEST(Format, ShouldFormatASingleArgument)
{
EXPECT_STREQ(Format("Value: {}", 42).c_str(), "Value: 42");
}
/****************************************************************************************/
TEST(Format, ShouldFormatMultipleArguments)
{
EXPECT_STREQ(Format("{} + {} = {}", 1, 2, 3).c_str(), "1 + 2 = 3");
}
/****************************************************************************************/
TEST(Format, ShouldReturnAnEmptyStringForAnEmptyFormat)
{
EXPECT_STREQ(Format("").c_str(), "");
}
/****************************************************************************************/
TEST(Format, ShouldFormatAStringLongerThanTheSmallStringOptimizationBuffer)
{
const eastl::string expected(256, 'a');
EXPECT_STREQ(Format("{}", expected.c_str()).c_str(), expected.c_str());
}
} // namespace Bigfoot
@@ -15,7 +15,7 @@ namespace Bigfoot
/*
* Logger
*/
inline Log::LoggerInfo UTILSTESTS_LOGGER {"UTILSTESTS_LOGGER", Flat::LogLevel::Trace};
inline Log::LoggerInfo UTILSTESTS_LOGGER { .m_name = "UTILSTESTS_LOGGER", .m_level = Flat::LogLevel::Trace};
} // namespace Bigfoot
#endif
#endif
+7 -6
View File
@@ -20,6 +20,7 @@
#include <fstream>
#include <sstream>
#include <string>
namespace Bigfoot
{
@@ -84,18 +85,18 @@ TEST_F(EASTLFormattersFixture, FormatsNestedVectors)
/****************************************************************************************/
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
class EASTLFormattersLogFixture: public ::testing::Test
{
protected:
eastl::string ReadFileSinkContent()
static std::string ReadFileSinkContent()
{
Singleton<Log>::GetInstance().Flush();
std::ifstream file {std::string {Log::FILE_SINK_PATH.data()}};
std::stringstream buffer;
buffer << file.rdbuf();
return eastl::string {buffer.str().c_str()};
return buffer.str();
}
};
@@ -105,7 +106,7 @@ TEST_F(EASTLFormattersLogFixture, LogsEastlStringArgument)
{
const eastl::string value = "Hello EASTL string";
BIGFOOT_LOG_INFO(UTILSTESTS_LOGGER, "{}", value);
EXPECT_THAT(std::string {ReadFileSinkContent().c_str()}, ::testing::HasSubstr("Hello EASTL string"));
EXPECT_THAT(ReadFileSinkContent(), ::testing::HasSubstr("Hello EASTL string"));
}
/****************************************************************************************/
@@ -114,7 +115,7 @@ TEST_F(EASTLFormattersLogFixture, LogsEmptyVectorArgument)
{
const eastl::vector<int> value;
BIGFOOT_LOG_INFO(UTILSTESTS_LOGGER, "{}", value);
EXPECT_THAT(std::string {ReadFileSinkContent().c_str()}, ::testing::HasSubstr("[]"));
EXPECT_THAT(ReadFileSinkContent(), ::testing::HasSubstr("[]"));
}
/****************************************************************************************/
@@ -123,7 +124,7 @@ TEST_F(EASTLFormattersLogFixture, LogsVectorArgumentWithCommaSeparators)
{
const eastl::vector<eastl::string> value {"a", "b", "c"};
BIGFOOT_LOG_INFO(UTILSTESTS_LOGGER, "{}", value);
EXPECT_THAT(std::string {ReadFileSinkContent().c_str()}, ::testing::HasSubstr("[a, b, c]"));
EXPECT_THAT(ReadFileSinkContent(), ::testing::HasSubstr("[a, b, c]"));
}
#endif
} // namespace Bigfoot
+12 -3
View File
@@ -10,7 +10,7 @@
#include <UtilsTests/UtilsTestsLogger_generated.hpp>
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
#include <gtest/gtest.h>
@@ -88,8 +88,17 @@ TEST_F(LogFixture, ChangeLoggerLogLevel_ShouldChangeTheLoggerLogLevel)
const quill::Logger* logger = Singleton<Log>::GetInstance().RegisterLogger(UTILSTESTS_LOGGER);
Singleton<Log>::GetInstance().ChangeLoggerLogLevel(UTILSTESTS_LOGGER, Flat::LogLevel::Critical);
EXPECT_EQ(QuillLogLevelToLogLevel(logger->get_log_level()), Flat::LogLevel::Critical);
for (const Flat::LogLevel level: {Flat::LogLevel::Debug,
Flat::LogLevel::Trace,
Flat::LogLevel::Info,
Flat::LogLevel::Warn,
Flat::LogLevel::Error,
Flat::LogLevel::Critical})
{
Singleton<Log>::GetInstance().ChangeLoggerLogLevel(UTILSTESTS_LOGGER, level);
EXPECT_EQ(QuillLogLevelToLogLevel(logger->get_log_level()), level);
}
Singleton<Log>::GetInstance().ChangeLoggerLogLevel(UTILSTESTS_LOGGER, previous);
EXPECT_EQ(QuillLogLevelToLogLevel(logger->get_log_level()), previous);
}
+10 -10
View File
@@ -10,28 +10,28 @@
#include <UtilsTests/UtilsTestsLogger_generated.hpp>
#if defined BIGFOOT_NOT_OPTIMIZED
#ifdef BIGFOOT_NOT_OPTIMIZED
#include <EASTL/string.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <fstream>
#include <sstream>
#include <string>
namespace Bigfoot
{
class LogMacrosFixture: public ::testing::Test
{
protected:
eastl::string ReadFileSinkContent()
static std::string ReadFileSinkContent()
{
Singleton<Log>::GetInstance().Flush();
std::ifstream file {std::string {Log::FILE_SINK_PATH.data()}};
std::stringstream buffer;
buffer << file.rdbuf();
return eastl::string {buffer.str().c_str()};
return buffer.str();
}
};
@@ -40,7 +40,7 @@ class LogMacrosFixture: public ::testing::Test
TEST_F(LogMacrosFixture, LogDebug)
{
BIGFOOT_LOG_DEBUG(UTILSTESTS_LOGGER, "Hello Debug");
EXPECT_THAT(std::string {ReadFileSinkContent().c_str()}, ::testing::HasSubstr("Hello Debug"));
EXPECT_THAT(ReadFileSinkContent(), ::testing::HasSubstr("Hello Debug"));
}
/****************************************************************************************/
@@ -48,7 +48,7 @@ TEST_F(LogMacrosFixture, LogDebug)
TEST_F(LogMacrosFixture, LogTrace)
{
BIGFOOT_LOG_TRACE(UTILSTESTS_LOGGER, "Hello Trace");
EXPECT_THAT(std::string {ReadFileSinkContent().c_str()}, ::testing::HasSubstr("Hello Trace"));
EXPECT_THAT(ReadFileSinkContent(), ::testing::HasSubstr("Hello Trace"));
}
/****************************************************************************************/
@@ -56,7 +56,7 @@ TEST_F(LogMacrosFixture, LogTrace)
TEST_F(LogMacrosFixture, LogInfo)
{
BIGFOOT_LOG_INFO(UTILSTESTS_LOGGER, "Hello Info");
EXPECT_THAT(std::string {ReadFileSinkContent().c_str()}, ::testing::HasSubstr("Hello Info"));
EXPECT_THAT(ReadFileSinkContent(), ::testing::HasSubstr("Hello Info"));
}
/****************************************************************************************/
@@ -64,7 +64,7 @@ TEST_F(LogMacrosFixture, LogInfo)
TEST_F(LogMacrosFixture, LogWarn)
{
BIGFOOT_LOG_WARN(UTILSTESTS_LOGGER, "Hello Warn");
EXPECT_THAT(std::string {ReadFileSinkContent().c_str()}, ::testing::HasSubstr("Hello Warn"));
EXPECT_THAT(ReadFileSinkContent(), ::testing::HasSubstr("Hello Warn"));
}
/****************************************************************************************/
@@ -72,7 +72,7 @@ TEST_F(LogMacrosFixture, LogWarn)
TEST_F(LogMacrosFixture, LogError)
{
BIGFOOT_LOG_ERROR(UTILSTESTS_LOGGER, "Hello Error");
EXPECT_THAT(std::string {ReadFileSinkContent().c_str()}, ::testing::HasSubstr("Hello Error"));
EXPECT_THAT(ReadFileSinkContent(), ::testing::HasSubstr("Hello Error"));
}
/****************************************************************************************/
@@ -80,7 +80,7 @@ TEST_F(LogMacrosFixture, LogError)
TEST_F(LogMacrosFixture, LogFatal)
{
BIGFOOT_LOG_FATAL(UTILSTESTS_LOGGER, "Hello Fatal");
EXPECT_THAT(std::string {ReadFileSinkContent().c_str()}, ::testing::HasSubstr("Hello Fatal"));
EXPECT_THAT(ReadFileSinkContent(), ::testing::HasSubstr("Hello Fatal"));
}
} // namespace Bigfoot
#endif
+2
View File
@@ -13,6 +13,8 @@ int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
GTEST_FLAG_SET(death_test_style, "threadsafe");
BIGFOOT_NOT_OPTIMIZED_ONLY(::Bigfoot::Singleton<::Bigfoot::Log>::Lifetime m_lifetime);
return RUN_ALL_TESTS();
+4 -2
View File
@@ -6,6 +6,8 @@
*********************************************************************/
#include <Utils/Version.hpp>
#include <Utils/Format.hpp>
#include <gtest/gtest.h>
namespace Bigfoot
@@ -75,7 +77,7 @@ TEST_F(VersionFixture, Comparisons)
TEST_F(VersionFixture, FormatsVersion)
{
EXPECT_EQ(fmt::format("{}", m_detailed), "1.2.3");
EXPECT_EQ(fmt::format("{}", m_combined), "1.2.3");
EXPECT_STREQ(Format("{}", m_detailed).c_str(), "1.2.3");
EXPECT_STREQ(Format("{}", m_combined).c_str(), "1.2.3");
}
} // namespace Bigfoot
+2 -2
View File
@@ -3,11 +3,11 @@ add_library(BigfootCompileAndLinkFlags INTERFACE)
target_compile_options(BigfootCompileAndLinkFlags INTERFACE
$<$<CXX_COMPILER_ID:MSVC>:/W4 /WX>
$<$<CXX_COMPILER_ID:Clang,GNU>:-Wall -Wextra -Wpedantic -Werror>
$<$<AND:$<BOOL:${COVERAGE}>,$<CXX_COMPILER_ID:Clang>>:-fprofile-instr-generate -fcoverage-mapping>
$<$<AND:$<BOOL:${COVERAGE}>,$<CXX_COMPILER_ID:Clang>>:-fprofile-instr-generate -fcoverage-mapping -fprofile-continuous>
)
target_link_options(BigfootCompileAndLinkFlags INTERFACE
$<$<AND:$<BOOL:${COVERAGE}>,$<CXX_COMPILER_ID:Clang>>:-fprofile-instr-generate>
$<$<AND:$<BOOL:${COVERAGE}>,$<CXX_COMPILER_ID:Clang>>:-fprofile-instr-generate -fprofile-continuous>
)
target_compile_definitions(BigfootCompileAndLinkFlags INTERFACE
+4 -1
View File
@@ -10,7 +10,10 @@ else()
set(BIGFOOT_PROJECT_NAME BigfootGame)
endif()
project(${BIGFOOT_PROJECT_NAME} VERSION 0.1.0
file(READ ${CMAKE_SOURCE_DIR}/VERSION BIGFOOT_VERSION)
string(STRIP "${BIGFOOT_VERSION}" BIGFOOT_VERSION)
project(${BIGFOOT_PROJECT_NAME} VERSION ${BIGFOOT_VERSION}
DESCRIPTION "The Bigfoot engine"
LANGUAGES CXX)
+1
View File
@@ -0,0 +1 @@
0.1.0
+4 -2
View File
@@ -1,6 +1,6 @@
from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout
from conan.tools.files import copy
from conan.tools.files import copy, load
import os
required_conan_version = ">=1.33.0"
@@ -11,7 +11,9 @@ class Bigfoot(ConanFile):
description = "Bigfoot is a 3D game engine written in C++"
topics = ("game engine", "3d")
license = "MIT"
version = "0.1.0"
def set_version(self):
self.version = load(self, "VERSION").strip()
# Binary configuration
settings = "os", "compiler", "build_type", "arch"
+2 -4
View File
@@ -1,7 +1,3 @@
sonar.projectKey=Bigfoot
sonar.projectVersion=0.1.0
sonar.sourceEncoding=UTF-8
sonar.sources=Bigfoot/Sources
@@ -10,5 +6,7 @@ sonar.tests=Bigfoot/Tests
sonar.cxx.file.suffixes=.hpp,.cpp,.h
sonar.cxx.clangtidy.reportPaths=tidy_result.txt
sonar.cxx.infer.reportPaths=infer-out/report.json
sonar.cxx.cobertura.reportPaths=coverage.xml
sonar.coverage.exclusions=**/*_generated.hpp
sonar.cxx.jsonCompilationDatabase.analyzeOnlyContainedFiles=True