mirror of
https://github.com/orange-cpp/omath.git
synced 2026-04-18 20:43:27 +00:00
Compare commits
99 Commits
feature/vm
...
37ea091282
| Author | SHA1 | Date | |
|---|---|---|---|
| 37ea091282 | |||
| 29a2743728 | |||
| 1117eb37f1 | |||
| b6b0d4db13 | |||
| 2e8a74aaaf | |||
| d8632dc74c | |||
| fd531c930c | |||
| a91673216d | |||
| 6487554844 | |||
| 1744172694 | |||
| 114b2a6e58 | |||
| d90a85d8b6 | |||
| e0a7179812 | |||
| a99dd24d6b | |||
| d62dec9a8f | |||
| 1a176d8f09 | |||
| 8e6ed19abf | |||
| 311ab45722 | |||
| 130277c1ae | |||
| 4f1c42d6f6 | |||
| ccea4a0f0d | |||
| 3fb98397e4 | |||
| 56256c40fb | |||
| 46c94ae541 | |||
| a45f095b9c | |||
| e849d23c47 | |||
| adad66599a | |||
| 69bdfc3307 | |||
| 55304c5df1 | |||
| 19d796cd4e | |||
| d31ea6ed4d | |||
| 977d772687 | |||
| 746f1b84a8 | |||
| af399a14ed | |||
| 6fb420642b | |||
| 6a2b4b90b4 | |||
| 371d8154ee | |||
| d6a2165f83 | |||
| bb1b5ad14a | |||
| f188257e0f | |||
| 87966c82b9 | |||
| 9da19582b5 | |||
| 29f3e2565d | |||
| e083b15e0b | |||
| ed9da79d08 | |||
| 2002bcca83 | |||
| ffacba71e2 | |||
| 6081a9c426 | |||
| 8bbd504356 | |||
| 1d54039f57 | |||
| 93fc93d4f6 | |||
| b8a578774c | |||
| bfa6c77776 | |||
| 1341ef9925 | |||
| 3ccbb0b25b | |||
| 68993db48a | |||
| 337204b3bf | |||
| 1e601d2d8f | |||
| 2b4a75d011 | |||
| 99a30e8fdf | |||
| 0cdd1d021f | |||
| a79ac9743a | |||
| f26afb703b | |||
| f237ee5f6a | |||
| 9058ea9b39 | |||
| f707ac1adb | |||
| cbdabd3fc2 | |||
| 30e3feb4f8 | |||
| 0726fdef32 | |||
| 0ffe0c2bdc | |||
| e9600ad42b | |||
| 673835618c | |||
| afb2a13dd6 | |||
| 943472cf64 | |||
| 9752accb14 | |||
| 7373e6d3df | |||
| 68f4c8cc72 | |||
| 2dafc8a49d | |||
| 11fe49e801 | |||
| dee705a391 | |||
| bfe147ef80 | |||
| 2c70288a8f | |||
| 529322fe34 | |||
| 414b2af289 | |||
| a79ad6948c | |||
| ea2c7c3d7f | |||
| 91c2e0d74b | |||
| 52e9b906ff | |||
| cc6d625c2d | |||
| 5eaec70846 | |||
| 2063c4d33a | |||
| 60bf8ca30f | |||
| 6fca106edc | |||
| 78cb644920 | |||
| 646a920e4c | |||
| 52687a70c7 | |||
| a9eff7d320 | |||
| 211e4c3d9b | |||
| 74dc2234f7 |
@@ -12,6 +12,7 @@ AlignConsecutiveMacros: AcrossEmptyLinesAndComments
|
||||
AlignTrailingComments: false
|
||||
AllowShortBlocksOnASingleLine: Never
|
||||
AllowShortFunctionsOnASingleLine: None
|
||||
AllowShortLambdasOnASingleLine: None
|
||||
AllowShortIfStatementsOnASingleLine: false
|
||||
AllowShortLoopsOnASingleLine: false
|
||||
BreakTemplateDeclarations: Leave
|
||||
|
||||
20
.github/workflows/cmake-multi-platform.yml
vendored
20
.github/workflows/cmake-multi-platform.yml
vendored
@@ -107,7 +107,7 @@ jobs:
|
||||
-DOMATH_BUILD_TESTS=ON \
|
||||
-DOMATH_BUILD_BENCHMARK=OFF \
|
||||
-DOMATH_ENABLE_COVERAGE=${{ matrix.coverage == true && 'ON' || 'OFF' }} \
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;tests"
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;tests;lua"
|
||||
|
||||
- name: Build
|
||||
shell: bash
|
||||
@@ -193,7 +193,7 @@ jobs:
|
||||
-DOMATH_BUILD_TESTS=ON \
|
||||
-DOMATH_BUILD_BENCHMARK=OFF \
|
||||
-DOMATH_ENABLE_COVERAGE=OFF \
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;tests"
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;tests;lua"
|
||||
|
||||
- name: Build
|
||||
shell: bash
|
||||
@@ -234,7 +234,7 @@ jobs:
|
||||
-DOMATH_ENABLE_COVERAGE=ON \
|
||||
-DOMATH_THREAT_WARNING_AS_ERROR=OFF \
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;tests"
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;tests;lua"
|
||||
cmake --build cmake-build/build/${{ matrix.preset }} --config Debug --target unit_tests omath
|
||||
|
||||
- name: Run Tests (Generates .profraw)
|
||||
@@ -373,7 +373,7 @@ jobs:
|
||||
-DOMATH_BUILD_TESTS=ON \
|
||||
-DOMATH_BUILD_BENCHMARK=OFF \
|
||||
-DOMATH_ENABLE_COVERAGE=${{ matrix.coverage == true && 'ON' || 'OFF' }} \
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;tests"
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;tests;lua"
|
||||
|
||||
- name: Build
|
||||
shell: bash
|
||||
@@ -450,7 +450,7 @@ jobs:
|
||||
-DVCPKG_INSTALL_OPTIONS="--allow-unsupported" \
|
||||
-DOMATH_BUILD_TESTS=ON \
|
||||
-DOMATH_BUILD_BENCHMARK=OFF \
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;tests"
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;tests;lua"
|
||||
|
||||
- name: Build
|
||||
shell: bash
|
||||
@@ -509,7 +509,7 @@ jobs:
|
||||
cmake --preset ${{ matrix.preset }} \
|
||||
-DOMATH_BUILD_TESTS=ON \
|
||||
-DOMATH_BUILD_BENCHMARK=OFF \
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;tests" \
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;tests;lua" \
|
||||
-DVCPKG_INSTALL_OPTIONS="--allow-unsupported"
|
||||
cmake --build cmake-build/build/${{ matrix.preset }} --target unit_tests omath
|
||||
./out/Release/unit_tests
|
||||
@@ -581,7 +581,7 @@ jobs:
|
||||
-DVCPKG_INSTALL_OPTIONS="--allow-unsupported" \
|
||||
-DOMATH_BUILD_TESTS=ON \
|
||||
-DOMATH_BUILD_BENCHMARK=OFF \
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;tests"
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;tests;lua"
|
||||
|
||||
- name: Build
|
||||
shell: bash
|
||||
@@ -650,7 +650,7 @@ jobs:
|
||||
-DVCPKG_INSTALL_OPTIONS="--allow-unsupported" \
|
||||
-DOMATH_BUILD_TESTS=ON \
|
||||
-DOMATH_BUILD_BENCHMARK=OFF \
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;tests"
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;tests;lua"
|
||||
|
||||
- name: Build
|
||||
shell: bash
|
||||
@@ -735,7 +735,7 @@ jobs:
|
||||
-DVCPKG_INSTALL_OPTIONS="--allow-unsupported" \
|
||||
-DOMATH_BUILD_TESTS=ON \
|
||||
-DOMATH_BUILD_BENCHMARK=OFF \
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;tests"
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;tests;lua"
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
@@ -800,7 +800,7 @@ jobs:
|
||||
-DOMATH_BUILD_TESTS=ON \
|
||||
-DOMATH_BUILD_BENCHMARK=ON \
|
||||
-DOMATH_ENABLE_VALGRIND=ON \
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;tests;benchmark"
|
||||
-DVCPKG_MANIFEST_FEATURES="imgui;avx2;lua;tests;benchmark"
|
||||
|
||||
- name: Build All Targets
|
||||
shell: bash
|
||||
|
||||
5
.luarc.json
Normal file
5
.luarc.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"diagnostics.globals": [
|
||||
"omath"
|
||||
]
|
||||
}
|
||||
@@ -31,6 +31,9 @@ option(OMATH_SUPRESS_SAFETY_CHECKS
|
||||
option(OMATH_ENABLE_COVERAGE "Enable coverage" OFF)
|
||||
option(OMATH_ENABLE_FORCE_INLINE
|
||||
"Will for compiler to make some functions to be force inlined no matter what" ON)
|
||||
|
||||
option(OMATH_ENABLE_LUA
|
||||
"omath bindings for lua" OFF)
|
||||
if(VCPKG_MANIFEST_FEATURES)
|
||||
foreach(omath_feature IN LISTS VCPKG_MANIFEST_FEATURES)
|
||||
if(omath_feature STREQUAL "imgui")
|
||||
@@ -43,6 +46,8 @@ if(VCPKG_MANIFEST_FEATURES)
|
||||
set(OMATH_BUILD_BENCHMARK ON)
|
||||
elseif(omath_feature STREQUAL "examples")
|
||||
set(OMATH_BUILD_EXAMPLES ON)
|
||||
elseif(omath_feature STREQUAL "lua")
|
||||
set(OMATH_ENABLE_LUA ON)
|
||||
endif()
|
||||
|
||||
endforeach()
|
||||
@@ -72,6 +77,7 @@ if(${PROJECT_IS_TOP_LEVEL})
|
||||
message(STATUS "[${PROJECT_NAME}]: Building using vcpkg ${OMATH_BUILD_VIA_VCPKG}")
|
||||
message(STATUS "[${PROJECT_NAME}]: Coverage feature status ${OMATH_ENABLE_COVERAGE}")
|
||||
message(STATUS "[${PROJECT_NAME}]: Valgrind feature status ${OMATH_ENABLE_VALGRIND}")
|
||||
message(STATUS "[${PROJECT_NAME}]: Lua feature status ${OMATH_ENABLE_LUA}")
|
||||
endif()
|
||||
|
||||
file(GLOB_RECURSE OMATH_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/source/*.cpp")
|
||||
@@ -83,6 +89,17 @@ else()
|
||||
add_library(${PROJECT_NAME} STATIC ${OMATH_SOURCES} ${OMATH_HEADERS})
|
||||
endif()
|
||||
|
||||
if (OMATH_ENABLE_LUA)
|
||||
target_compile_definitions(${PROJECT_NAME} PUBLIC OMATH_ENABLE_LUA)
|
||||
|
||||
find_package(Lua REQUIRED)
|
||||
target_include_directories(${PROJECT_NAME} PRIVATE ${LUA_INCLUDE_DIR})
|
||||
target_link_libraries(${PROJECT_NAME} PRIVATE ${LUA_LIBRARIES})
|
||||
|
||||
find_path(SOL2_INCLUDE_DIRS "sol/abort.hpp")
|
||||
target_include_directories(${PROJECT_NAME} PRIVATE ${SOL2_INCLUDE_DIRS})
|
||||
endif ()
|
||||
|
||||
add_library(${PROJECT_NAME}::${PROJECT_NAME} ALIAS ${PROJECT_NAME})
|
||||
|
||||
target_compile_definitions(${PROJECT_NAME} PUBLIC OMATH_VERSION="${PROJECT_VERSION}")
|
||||
@@ -174,6 +191,12 @@ elseif(OMATH_THREAT_WARNING_AS_ERROR)
|
||||
target_compile_options(${PROJECT_NAME} PRIVATE -Wall -Wextra -Wpedantic -Werror)
|
||||
endif()
|
||||
|
||||
if (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
|
||||
target_compile_options(${PROJECT_NAME} PRIVATE /bigobj)
|
||||
endif()
|
||||
if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_HOST_SYSTEM_NAME EQUAL "Windows")
|
||||
target_compile_options(${PROJECT_NAME} PRIVATE -mbig-obj)
|
||||
endif()
|
||||
# Windows SDK redefine min/max via preprocessor and break std::min and std::max
|
||||
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
|
||||
target_compile_definitions(${PROJECT_NAME} INTERFACE NOMINMAX)
|
||||
|
||||
@@ -145,7 +145,7 @@
|
||||
"hidden": true,
|
||||
"inherits": ["linux-base", "vcpkg-base"],
|
||||
"cacheVariables": {
|
||||
"VCPKG_MANIFEST_FEATURES": "tests;imgui;avx2"
|
||||
"VCPKG_MANIFEST_FEATURES": "tests;imgui;avx2;lua"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -235,7 +235,7 @@
|
||||
"hidden": true,
|
||||
"inherits": ["darwin-base", "vcpkg-base"],
|
||||
"cacheVariables": {
|
||||
"VCPKG_MANIFEST_FEATURES": "tests;imgui;avx2;examples"
|
||||
"VCPKG_MANIFEST_FEATURES": "tests;imgui;avx2;examples;lua"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -5,6 +5,7 @@ Thanks to everyone who made this possible, including:
|
||||
- Saikari aka luadebug for VCPKG port and awesome new initial logo design.
|
||||
- AmbushedRaccoon for telegram post about omath to boost repository activity.
|
||||
- Billy O'Neal aka BillyONeal for fixing compilation issues due to C math library compatibility.
|
||||
- Alex2772 for reference of AUI declarative interface design for omath::hud
|
||||
|
||||
And a big hand to everyone else who has contributed over the past!
|
||||
|
||||
|
||||
@@ -9,11 +9,12 @@
|
||||
[](https://www.codefactor.io/repository/github/orange-cpp/omath)
|
||||

|
||||
[](https://repology.org/project/orange-math/versions)
|
||||

|
||||

|
||||
[](https://discord.gg/eDgdaWbqwZ)
|
||||
[](https://t.me/orangennotes)
|
||||
|
||||
OMath is a 100% independent, constexpr template blazingly fast math library that doesn't have legacy C++ code.
|
||||
OMath is a 100% independent, constexpr template blazingly fast math/physics/games/mods/cheats development framework that doesn't have legacy C++ code.
|
||||
|
||||
It provides the latest features, is highly customizable, has all for cheat development, DirectX/OpenGL/Vulkan support, premade support for different game engines, much more constexpr stuff than in other libraries and more...
|
||||
<br>
|
||||
@@ -83,6 +84,8 @@ if (auto screen = camera.world_to_screen(world_position)) {
|
||||
- **Engine support**: Supports coordinate systems of **Source, Unity, Unreal, Frostbite, IWEngine, CryEngine and canonical OpenGL**.
|
||||
- **Cross platform**: Supports Windows, MacOS and Linux.
|
||||
- **Algorithms**: Has ability to scan for byte pattern with wildcards in ELF/Mach-O/PE files/modules, binary slices, works even with Wine apps.
|
||||
- **Scripting**: Supports to make scripts in Lua out of box.
|
||||
- **Handy**: Allow to design wall hacks in modern jetpack compose like way.
|
||||
- **Battle tested**: It's already used by some big players on the market like wraith.su and bluedream.ltd
|
||||
<div align = center>
|
||||
|
||||
|
||||
161
benchmark/benchmark_collision.cpp
Normal file
161
benchmark/benchmark_collision.cpp
Normal file
@@ -0,0 +1,161 @@
|
||||
//
|
||||
// Created by Vlad on 3/2/2026.
|
||||
//
|
||||
#include <benchmark/benchmark.h>
|
||||
#include <memory_resource>
|
||||
#include <omath/collision/epa_algorithm.hpp>
|
||||
#include <omath/collision/gjk_algorithm.hpp>
|
||||
#include <omath/engines/source_engine/collider.hpp>
|
||||
#include <omath/engines/source_engine/mesh.hpp>
|
||||
|
||||
using Mesh = omath::source_engine::Mesh;
|
||||
using Collider = omath::source_engine::MeshCollider;
|
||||
using Gjk = omath::collision::GjkAlgorithm<Collider>;
|
||||
using Epa = omath::collision::Epa<Collider>;
|
||||
|
||||
namespace
|
||||
{
|
||||
// Unit cube with half-extent 1 — 8 vertices in [-1,1]^3.
|
||||
const std::vector<omath::primitives::Vertex<>> k_cube_vbo = {
|
||||
{ { -1.f, -1.f, -1.f }, {}, {} },
|
||||
{ { -1.f, -1.f, 1.f }, {}, {} },
|
||||
{ { -1.f, 1.f, -1.f }, {}, {} },
|
||||
{ { -1.f, 1.f, 1.f }, {}, {} },
|
||||
{ { 1.f, 1.f, 1.f }, {}, {} },
|
||||
{ { 1.f, 1.f, -1.f }, {}, {} },
|
||||
{ { 1.f, -1.f, 1.f }, {}, {} },
|
||||
{ { 1.f, -1.f, -1.f }, {}, {} },
|
||||
};
|
||||
const std::vector<omath::Vector3<std::uint32_t>> k_empty_vao{};
|
||||
} // namespace
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// GJK benchmarks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Separated cubes — origin distance 2.1, no overlap.
|
||||
// Exercises the early-exit path and the centroid-based initial direction.
|
||||
static void BM_Gjk_Separated(benchmark::State& state)
|
||||
{
|
||||
const Collider a{Mesh{k_cube_vbo, k_empty_vao}};
|
||||
|
||||
Mesh mesh_b{k_cube_vbo, k_empty_vao};
|
||||
mesh_b.set_origin({0.f, 2.1f, 0.f});
|
||||
const Collider b{mesh_b};
|
||||
|
||||
for ([[maybe_unused]] auto _ : state)
|
||||
benchmark::DoNotOptimize(Gjk::is_collide(a, b));
|
||||
}
|
||||
|
||||
// Overlapping cubes — B offset by 0.5 along X, ~1.5 units penetration depth.
|
||||
static void BM_Gjk_Overlapping(benchmark::State& state)
|
||||
{
|
||||
const Collider a{Mesh{k_cube_vbo, k_empty_vao}};
|
||||
|
||||
Mesh mesh_b{k_cube_vbo, k_empty_vao};
|
||||
mesh_b.set_origin({0.5f, 0.f, 0.f});
|
||||
const Collider b{mesh_b};
|
||||
|
||||
for ([[maybe_unused]] auto _ : state)
|
||||
benchmark::DoNotOptimize(Gjk::is_collide(a, b));
|
||||
}
|
||||
|
||||
// Identical cubes at the same origin — deep overlap / worst case for GJK.
|
||||
static void BM_Gjk_SameOrigin(benchmark::State& state)
|
||||
{
|
||||
const Collider a{Mesh{k_cube_vbo, k_empty_vao}};
|
||||
const Collider b{Mesh{k_cube_vbo, k_empty_vao}};
|
||||
|
||||
for ([[maybe_unused]] auto _ : state)
|
||||
benchmark::DoNotOptimize(Gjk::is_collide(a, b));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// EPA benchmarks
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// EPA with a pre-allocated monotonic buffer (reset each iteration).
|
||||
// Isolates algorithmic cost from allocator overhead.
|
||||
static void BM_Epa_MonotonicBuffer(benchmark::State& state)
|
||||
{
|
||||
const Collider a{Mesh{k_cube_vbo, k_empty_vao}};
|
||||
|
||||
Mesh mesh_b{k_cube_vbo, k_empty_vao};
|
||||
mesh_b.set_origin({0.5f, 0.f, 0.f});
|
||||
const Collider b{mesh_b};
|
||||
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(a, b);
|
||||
if (!hit)
|
||||
return; // shouldn't happen, but guard for safety
|
||||
|
||||
constexpr Epa::Params params{.max_iterations = 64, .tolerance = 1e-4f};
|
||||
|
||||
// Pre-allocate a 32 KiB stack buffer — enough for typical polytope growth.
|
||||
constexpr std::size_t k_buf_size = 32768;
|
||||
alignas(std::max_align_t) char buf[k_buf_size];
|
||||
std::pmr::monotonic_buffer_resource mr{buf, k_buf_size, std::pmr::null_memory_resource()};
|
||||
|
||||
for ([[maybe_unused]] auto _ : state)
|
||||
{
|
||||
mr.release(); // reset the buffer without touching the upstream resource
|
||||
benchmark::DoNotOptimize(Epa::solve(a, b, simplex, params, mr));
|
||||
}
|
||||
}
|
||||
|
||||
// EPA with the default (malloc-backed) memory resource.
|
||||
// Shows total cost including allocator pressure.
|
||||
static void BM_Epa_DefaultResource(benchmark::State& state)
|
||||
{
|
||||
const Collider a{Mesh{k_cube_vbo, k_empty_vao}};
|
||||
|
||||
Mesh mesh_b{k_cube_vbo, k_empty_vao};
|
||||
mesh_b.set_origin({0.5f, 0.f, 0.f});
|
||||
const Collider b{mesh_b};
|
||||
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(a, b);
|
||||
if (!hit)
|
||||
return;
|
||||
|
||||
constexpr Epa::Params params{.max_iterations = 64, .tolerance = 1e-4f};
|
||||
|
||||
for ([[maybe_unused]] auto _ : state)
|
||||
benchmark::DoNotOptimize(Epa::solve(a, b, simplex, params));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Combined GJK + EPA pipeline
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Full collision pipeline: GJK detects contact, EPA resolves penetration.
|
||||
// This is the hot path in a physics engine tick.
|
||||
static void BM_GjkEpa_Pipeline(benchmark::State& state)
|
||||
{
|
||||
const Collider a{Mesh{k_cube_vbo, k_empty_vao}};
|
||||
|
||||
Mesh mesh_b{k_cube_vbo, k_empty_vao};
|
||||
mesh_b.set_origin({0.5f, 0.f, 0.f});
|
||||
const Collider b{mesh_b};
|
||||
|
||||
constexpr Epa::Params params{.max_iterations = 64, .tolerance = 1e-4f};
|
||||
|
||||
constexpr std::size_t k_buf_size = 32768;
|
||||
alignas(std::max_align_t) char buf[k_buf_size];
|
||||
std::pmr::monotonic_buffer_resource mr{buf, k_buf_size, std::pmr::null_memory_resource()};
|
||||
|
||||
for ([[maybe_unused]] auto _ : state)
|
||||
{
|
||||
mr.release();
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(a, b);
|
||||
if (hit)
|
||||
benchmark::DoNotOptimize(Epa::solve(a, b, simplex, params, mr));
|
||||
}
|
||||
}
|
||||
|
||||
BENCHMARK(BM_Gjk_Separated)->Iterations(100'000);
|
||||
BENCHMARK(BM_Gjk_Overlapping)->Iterations(100'000);
|
||||
BENCHMARK(BM_Gjk_SameOrigin)->Iterations(100'000);
|
||||
|
||||
BENCHMARK(BM_Epa_MonotonicBuffer)->Iterations(100'000);
|
||||
BENCHMARK(BM_Epa_DefaultResource)->Iterations(100'000);
|
||||
|
||||
BENCHMARK(BM_GjkEpa_Pipeline)->Iterations(100'000);
|
||||
@@ -2,6 +2,7 @@ add_subdirectory(example_barycentric)
|
||||
add_subdirectory(example_glfw3)
|
||||
add_subdirectory(example_proj_mat_builder)
|
||||
add_subdirectory(example_signature_scan)
|
||||
add_subdirectory(example_hud)
|
||||
|
||||
if(OMATH_ENABLE_VALGRIND)
|
||||
omath_setup_valgrind(example_projection_matrix_builder)
|
||||
|
||||
16
examples/example_hud/CMakeLists.txt
Normal file
16
examples/example_hud/CMakeLists.txt
Normal file
@@ -0,0 +1,16 @@
|
||||
project(example_hud)
|
||||
|
||||
|
||||
add_executable(${PROJECT_NAME} main.cpp gui/main_window.cpp gui/main_window.hpp)
|
||||
|
||||
set_target_properties(
|
||||
${PROJECT_NAME}
|
||||
PROPERTIES CXX_STANDARD 23
|
||||
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}"
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}"
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/out/${CMAKE_BUILD_TYPE}")
|
||||
|
||||
find_package(OpenGL)
|
||||
find_package(GLEW REQUIRED)
|
||||
find_package(glfw3 CONFIG REQUIRED)
|
||||
target_link_libraries(${PROJECT_NAME} PRIVATE glfw imgui::imgui omath::omath OpenGL::GL)
|
||||
251
examples/example_hud/gui/main_window.cpp
Normal file
251
examples/example_hud/gui/main_window.cpp
Normal file
@@ -0,0 +1,251 @@
|
||||
//
|
||||
// Created by Orange on 11/11/2024.
|
||||
//
|
||||
#include "main_window.hpp"
|
||||
#include "omath/hud/renderer_realizations/imgui_renderer.hpp"
|
||||
#include <GLFW/glfw3.h>
|
||||
#include <imgui.h>
|
||||
#include <imgui_impl_glfw.h>
|
||||
#include <imgui_impl_opengl3.h>
|
||||
#include <omath/hud/entity_overlay.hpp>
|
||||
|
||||
namespace imgui_desktop::gui
|
||||
{
|
||||
bool MainWindow::m_canMoveWindow = false;
|
||||
|
||||
MainWindow::MainWindow(const std::string_view& caption, int width, int height)
|
||||
{
|
||||
if (!glfwInit())
|
||||
std::exit(EXIT_FAILURE);
|
||||
|
||||
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
|
||||
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
|
||||
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
|
||||
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
|
||||
glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, true);
|
||||
m_window = glfwCreateWindow(width, height, caption.data(), nullptr, nullptr);
|
||||
|
||||
glfwMakeContextCurrent(m_window);
|
||||
|
||||
ImGui::CreateContext();
|
||||
ImGui::StyleColorsDark();
|
||||
ImGui::GetStyle().Colors[ImGuiCol_WindowBg] = {0.05f, 0.05f, 0.05f, 0.92f};
|
||||
ImGui::GetStyle().AntiAliasedLines = false;
|
||||
ImGui::GetStyle().AntiAliasedFill = false;
|
||||
ImGui_ImplGlfw_InitForOpenGL(m_window, true);
|
||||
ImGui_ImplOpenGL3_Init("#version 150");
|
||||
}
|
||||
|
||||
void MainWindow::Run()
|
||||
{
|
||||
while (!glfwWindowShouldClose(m_window) && m_opened)
|
||||
{
|
||||
glfwPollEvents();
|
||||
ImGui_ImplOpenGL3_NewFrame();
|
||||
ImGui_ImplGlfw_NewFrame();
|
||||
ImGui::NewFrame();
|
||||
|
||||
const auto* vp = ImGui::GetMainViewport();
|
||||
ImGui::GetBackgroundDrawList()->AddRectFilled({}, vp->Size, ImColor(30, 30, 30, 220));
|
||||
|
||||
draw_controls();
|
||||
draw_overlay();
|
||||
|
||||
ImGui::Render();
|
||||
present();
|
||||
}
|
||||
glfwDestroyWindow(m_window);
|
||||
}
|
||||
|
||||
void MainWindow::draw_controls()
|
||||
{
|
||||
const auto* vp = ImGui::GetMainViewport();
|
||||
ImGui::SetNextWindowPos({0.f, 0.f});
|
||||
ImGui::SetNextWindowSize({280.f, vp->Size.y});
|
||||
ImGui::Begin("Controls", &m_opened,
|
||||
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse);
|
||||
ImGui::PushItemWidth(160.f);
|
||||
|
||||
if (ImGui::CollapsingHeader("Entity", ImGuiTreeNodeFlags_DefaultOpen))
|
||||
{
|
||||
ImGui::SliderFloat("X##ent", &m_entity_x, 100.f, vp->Size.x - 100.f);
|
||||
ImGui::SliderFloat("Top Y", &m_entity_top_y, 20.f, m_entity_bottom_y - 20.f);
|
||||
ImGui::SliderFloat("Bottom Y", &m_entity_bottom_y, m_entity_top_y + 20.f, vp->Size.y - 20.f);
|
||||
}
|
||||
|
||||
if (ImGui::CollapsingHeader("Box", ImGuiTreeNodeFlags_DefaultOpen))
|
||||
{
|
||||
ImGui::Checkbox("Box##chk", &m_show_box);
|
||||
ImGui::SameLine();
|
||||
ImGui::Checkbox("Cornered", &m_show_cornered_box);
|
||||
ImGui::SameLine();
|
||||
ImGui::Checkbox("Dashed", &m_show_dashed_box);
|
||||
ImGui::ColorEdit4("Color##box", reinterpret_cast<float*>(&m_box_color), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::ColorEdit4("Fill##box", reinterpret_cast<float*>(&m_box_fill), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::SliderFloat("Thickness", &m_box_thickness, 0.5f, 5.f);
|
||||
ImGui::SliderFloat("Corner ratio", &m_corner_ratio, 0.05f, 0.5f);
|
||||
ImGui::Separator();
|
||||
ImGui::ColorEdit4("Dash color", reinterpret_cast<float*>(&m_dash_color), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::SliderFloat("Dash length", &m_dash_len, 2.f, 30.f);
|
||||
ImGui::SliderFloat("Dash gap", &m_dash_gap, 1.f, 20.f);
|
||||
ImGui::SliderFloat("Dash thick", &m_dash_thickness, 0.5f, 5.f);
|
||||
}
|
||||
|
||||
if (ImGui::CollapsingHeader("Bars", ImGuiTreeNodeFlags_DefaultOpen))
|
||||
{
|
||||
ImGui::ColorEdit4("Color##bar", reinterpret_cast<float*>(&m_bar_color), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::ColorEdit4("BG##bar", reinterpret_cast<float*>(&m_bar_bg_color), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::ColorEdit4("Outline##bar", reinterpret_cast<float*>(&m_bar_outline_color),
|
||||
ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::SliderFloat("Width##bar", &m_bar_width, 1.f, 20.f);
|
||||
ImGui::SliderFloat("Value##bar", &m_bar_value, 0.f, 1.f);
|
||||
ImGui::SliderFloat("Offset##bar", &m_bar_offset, 1.f, 20.f);
|
||||
ImGui::Checkbox("Right##bar", &m_show_right_bar);
|
||||
ImGui::SameLine();
|
||||
ImGui::Checkbox("Left##bar", &m_show_left_bar);
|
||||
ImGui::Checkbox("Top##bar", &m_show_top_bar);
|
||||
ImGui::SameLine();
|
||||
ImGui::Checkbox("Bottom##bar", &m_show_bottom_bar);
|
||||
ImGui::Checkbox("Right dashed##bar", &m_show_right_dashed_bar);
|
||||
ImGui::SameLine();
|
||||
ImGui::Checkbox("Left dashed##bar", &m_show_left_dashed_bar);
|
||||
ImGui::Checkbox("Top dashed##bar", &m_show_top_dashed_bar);
|
||||
ImGui::SameLine();
|
||||
ImGui::Checkbox("Bot dashed##bar", &m_show_bottom_dashed_bar);
|
||||
ImGui::SliderFloat("Dash len##bar", &m_bar_dash_len, 2.f, 20.f);
|
||||
ImGui::SliderFloat("Dash gap##bar", &m_bar_dash_gap, 1.f, 15.f);
|
||||
}
|
||||
|
||||
if (ImGui::CollapsingHeader("Labels", ImGuiTreeNodeFlags_DefaultOpen))
|
||||
{
|
||||
ImGui::Checkbox("Outlined", &m_outlined);
|
||||
ImGui::SliderFloat("Offset##lbl", &m_label_offset, 0.f, 15.f);
|
||||
ImGui::Checkbox("Right##lbl", &m_show_right_labels);
|
||||
ImGui::SameLine();
|
||||
ImGui::Checkbox("Left##lbl", &m_show_left_labels);
|
||||
ImGui::Checkbox("Top##lbl", &m_show_top_labels);
|
||||
ImGui::SameLine();
|
||||
ImGui::Checkbox("Bottom##lbl", &m_show_bottom_labels);
|
||||
ImGui::Checkbox("Ctr top##lbl", &m_show_centered_top);
|
||||
ImGui::SameLine();
|
||||
ImGui::Checkbox("Ctr bot##lbl", &m_show_centered_bottom);
|
||||
}
|
||||
|
||||
if (ImGui::CollapsingHeader("Skeleton"))
|
||||
{
|
||||
ImGui::Checkbox("Show##skel", &m_show_skeleton);
|
||||
ImGui::ColorEdit4("Color##skel", reinterpret_cast<float*>(&m_skel_color), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::SliderFloat("Thick##skel", &m_skel_thickness, 0.5f, 5.f);
|
||||
}
|
||||
|
||||
if (ImGui::CollapsingHeader("Progress Ring"))
|
||||
{
|
||||
ImGui::Checkbox("Show##ring", &m_show_ring);
|
||||
ImGui::ColorEdit4("Color##ring", reinterpret_cast<float*>(&m_ring_color), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::ColorEdit4("BG##ring", reinterpret_cast<float*>(&m_ring_bg), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::SliderFloat("Radius##ring", &m_ring_radius, 4.f, 30.f);
|
||||
ImGui::SliderFloat("Value##ring", &m_ring_ratio, 0.f, 1.f);
|
||||
ImGui::SliderFloat("Thick##ring", &m_ring_thickness, 0.5f, 6.f);
|
||||
ImGui::SliderFloat("Offset##ring", &m_ring_offset, 0.f, 15.f);
|
||||
}
|
||||
|
||||
if (ImGui::CollapsingHeader("Scan Marker"))
|
||||
{
|
||||
ImGui::Checkbox("Show##scan", &m_show_scan);
|
||||
ImGui::ColorEdit4("Fill##scan", reinterpret_cast<float*>(&m_scan_color), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::ColorEdit4("Outline##scan", reinterpret_cast<float*>(&m_scan_outline), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::SliderFloat("Thick##scan", &m_scan_outline_thickness, 0.5f, 5.f);
|
||||
}
|
||||
|
||||
if (ImGui::CollapsingHeader("Aim Dot"))
|
||||
{
|
||||
ImGui::Checkbox("Show##aim", &m_show_aim);
|
||||
ImGui::ColorEdit4("Color##aim", reinterpret_cast<float*>(&m_aim_color), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::SliderFloat("Radius##aim", &m_aim_radius, 1.f, 10.f);
|
||||
}
|
||||
|
||||
if (ImGui::CollapsingHeader("Snap Line"))
|
||||
{
|
||||
ImGui::Checkbox("Show##snap", &m_show_snap);
|
||||
ImGui::ColorEdit4("Color##snap", reinterpret_cast<float*>(&m_snap_color), ImGuiColorEditFlags_NoInputs);
|
||||
ImGui::SliderFloat("Width##snap", &m_snap_width, 0.5f, 5.f);
|
||||
}
|
||||
|
||||
ImGui::PopItemWidth();
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
void MainWindow::draw_overlay()
|
||||
{
|
||||
using namespace omath::hud::widget;
|
||||
using omath::hud::when;
|
||||
const auto* vp = ImGui::GetMainViewport();
|
||||
const Bar bar{m_bar_color, m_bar_outline_color, m_bar_bg_color, m_bar_width, m_bar_value, m_bar_offset};
|
||||
const DashedBar dbar{m_bar_color, m_bar_outline_color, m_bar_bg_color, m_bar_width,
|
||||
m_bar_value, m_bar_dash_len, m_bar_dash_gap, m_bar_offset};
|
||||
|
||||
omath::hud::EntityOverlay({m_entity_x, m_entity_top_y}, {m_entity_x, m_entity_bottom_y},
|
||||
std::make_shared<omath::hud::ImguiHudRenderer>())
|
||||
.contents(
|
||||
// ── Boxes ────────────────────────────────────────────────────
|
||||
when(m_show_box, Box{m_box_color, m_box_fill, m_box_thickness}),
|
||||
when(m_show_cornered_box, CorneredBox{omath::Color::from_rgba(255, 0, 255, 255), m_box_fill,
|
||||
m_corner_ratio, m_box_thickness}),
|
||||
when(m_show_dashed_box, DashedBox{m_dash_color, m_dash_len, m_dash_gap, m_dash_thickness}),
|
||||
RightSide{
|
||||
when(m_show_right_bar, bar),
|
||||
when(m_show_right_dashed_bar, dbar),
|
||||
when(m_show_right_labels,
|
||||
Label{{0.f, 1.f, 0.f, 1.f}, m_label_offset, m_outlined, "Health: 100/100"}),
|
||||
when(m_show_right_labels,
|
||||
Label{{1.f, 0.f, 0.f, 1.f}, m_label_offset, m_outlined, "Shield: 125/125"}),
|
||||
when(m_show_right_labels,
|
||||
Label{{1.f, 0.f, 1.f, 1.f}, m_label_offset, m_outlined, "*LOCKED*"}),
|
||||
|
||||
SpaceVertical{10},
|
||||
when(m_show_ring, ProgressRing{m_ring_color, m_ring_bg, m_ring_radius, m_ring_ratio,
|
||||
m_ring_thickness, m_ring_offset}),
|
||||
},
|
||||
LeftSide{
|
||||
when(m_show_left_bar, bar),
|
||||
when(m_show_left_dashed_bar, dbar),
|
||||
when(m_show_left_labels, Label{omath::Color::from_rgba(255, 128, 0, 255),
|
||||
m_label_offset, m_outlined, "Armor: 75"}),
|
||||
when(m_show_left_labels, Label{omath::Color::from_rgba(0, 200, 255, 255),
|
||||
m_label_offset, m_outlined, "Level: 42"}),
|
||||
},
|
||||
TopSide{
|
||||
when(m_show_top_bar, bar),
|
||||
when(m_show_top_dashed_bar, dbar),
|
||||
when(m_show_centered_top, Centered{Label{omath::Color::from_rgba(0, 255, 255, 255),
|
||||
m_label_offset, m_outlined, "*VISIBLE*"}}),
|
||||
when(m_show_top_labels, Label{omath::Color::from_rgba(255, 255, 0, 255), m_label_offset,
|
||||
m_outlined, "*SCOPED*"}),
|
||||
when(m_show_top_labels, Label{omath::Color::from_rgba(255, 0, 0, 255), m_label_offset,
|
||||
m_outlined, "*BLEEDING*"}),
|
||||
},
|
||||
BottomSide{
|
||||
when(m_show_bottom_bar, bar),
|
||||
when(m_show_bottom_dashed_bar, dbar),
|
||||
when(m_show_centered_bottom, Centered{Label{omath::Color::from_rgba(255, 255, 255, 255),
|
||||
m_label_offset, m_outlined, "PlayerName"}}),
|
||||
when(m_show_bottom_labels, Label{omath::Color::from_rgba(200, 200, 0, 255),
|
||||
m_label_offset, m_outlined, "42m"}),
|
||||
},
|
||||
when(m_show_aim, AimDot{{m_entity_x, m_entity_top_y+40.f}, m_aim_color, m_aim_radius}),
|
||||
when(m_show_scan, ScanMarker{m_scan_color, m_scan_outline, m_scan_outline_thickness}),
|
||||
when(m_show_skeleton, Skeleton{m_skel_color, m_skel_thickness}),
|
||||
when(m_show_snap, SnapLine{{vp->Size.x / 2.f, vp->Size.y}, m_snap_color, m_snap_width}));
|
||||
}
|
||||
|
||||
void MainWindow::present()
|
||||
{
|
||||
int w, h;
|
||||
glfwGetFramebufferSize(m_window, &w, &h);
|
||||
glViewport(0, 0, w, h);
|
||||
glClearColor(0.f, 0.f, 0.f, 0.f);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
|
||||
glfwSwapBuffers(m_window);
|
||||
}
|
||||
} // namespace imgui_desktop::gui
|
||||
86
examples/example_hud/gui/main_window.hpp
Normal file
86
examples/example_hud/gui/main_window.hpp
Normal file
@@ -0,0 +1,86 @@
|
||||
//
|
||||
// Created by Orange on 11/11/2024.
|
||||
//
|
||||
#pragma once
|
||||
#include <omath/hud/entity_overlay.hpp>
|
||||
#include <omath/utility/color.hpp>
|
||||
#include <string_view>
|
||||
|
||||
struct GLFWwindow;
|
||||
|
||||
namespace imgui_desktop::gui
|
||||
{
|
||||
class MainWindow
|
||||
{
|
||||
public:
|
||||
MainWindow(const std::string_view& caption, int width, int height);
|
||||
void Run();
|
||||
|
||||
private:
|
||||
void draw_controls();
|
||||
void draw_overlay();
|
||||
void present();
|
||||
|
||||
GLFWwindow* m_window = nullptr;
|
||||
static bool m_canMoveWindow;
|
||||
bool m_opened = true;
|
||||
|
||||
// Entity
|
||||
float m_entity_x = 550.f, m_entity_top_y = 150.f, m_entity_bottom_y = 450.f;
|
||||
|
||||
// Box
|
||||
omath::Color m_box_color{1.f, 1.f, 1.f, 1.f};
|
||||
omath::Color m_box_fill{0.f, 0.f, 0.f, 0.f};
|
||||
float m_box_thickness = 1.f, m_corner_ratio = 0.2f;
|
||||
bool m_show_box = true, m_show_cornered_box = true, m_show_dashed_box = false;
|
||||
|
||||
// Dashed box
|
||||
omath::Color m_dash_color = omath::Color::from_rgba(255, 200, 0, 255);
|
||||
float m_dash_len = 8.f, m_dash_gap = 5.f, m_dash_thickness = 1.f;
|
||||
|
||||
// Bars
|
||||
omath::Color m_bar_color{0.f, 1.f, 0.f, 1.f};
|
||||
omath::Color m_bar_bg_color{0.f, 0.f, 0.f, 0.5f};
|
||||
omath::Color m_bar_outline_color{0.f, 0.f, 0.f, 1.f};
|
||||
float m_bar_width = 4.f, m_bar_value = 0.75f, m_bar_offset = 5.f;
|
||||
bool m_show_right_bar = true, m_show_left_bar = true;
|
||||
bool m_show_top_bar = true, m_show_bottom_bar = true;
|
||||
bool m_show_right_dashed_bar = false, m_show_left_dashed_bar = false;
|
||||
bool m_show_top_dashed_bar = false, m_show_bottom_dashed_bar = false;
|
||||
float m_bar_dash_len = 6.f, m_bar_dash_gap = 4.f;
|
||||
|
||||
// Labels
|
||||
float m_label_offset = 3.f;
|
||||
bool m_outlined = true;
|
||||
bool m_show_right_labels = true, m_show_left_labels = true;
|
||||
bool m_show_top_labels = true, m_show_bottom_labels = true;
|
||||
bool m_show_centered_top = true, m_show_centered_bottom = true;
|
||||
|
||||
// Skeleton
|
||||
omath::Color m_skel_color = omath::Color::from_rgba(255, 255, 255, 200);
|
||||
float m_skel_thickness = 1.f;
|
||||
bool m_show_skeleton = false;
|
||||
|
||||
// Progress ring
|
||||
omath::Color m_ring_color = omath::Color::from_rgba(0, 200, 255, 255);
|
||||
omath::Color m_ring_bg{0.3f, 0.3f, 0.3f, 0.5f};
|
||||
float m_ring_radius = 10.f, m_ring_ratio = 0.65f, m_ring_thickness = 2.5f, m_ring_offset = 5.f;
|
||||
bool m_show_ring = false;
|
||||
|
||||
// Scan marker
|
||||
omath::Color m_scan_color = omath::Color::from_rgba(255, 200, 0, 150);
|
||||
omath::Color m_scan_outline = omath::Color::from_rgba(255, 200, 0, 255);
|
||||
float m_scan_outline_thickness = 2.f;
|
||||
bool m_show_scan = false;
|
||||
|
||||
// Aim dot
|
||||
omath::Color m_aim_color = omath::Color::from_rgba(255, 0, 0, 255);
|
||||
float m_aim_radius = 3.f;
|
||||
bool m_show_aim = false;
|
||||
|
||||
// Snap line
|
||||
omath::Color m_snap_color = omath::Color::from_rgba(255, 50, 50, 255);
|
||||
float m_snap_width = 1.5f;
|
||||
bool m_show_snap = true;
|
||||
};
|
||||
} // namespace imgui_desktop::gui
|
||||
8
examples/example_hud/main.cpp
Normal file
8
examples/example_hud/main.cpp
Normal file
@@ -0,0 +1,8 @@
|
||||
//
|
||||
// Created by orange on 13.03.2026.
|
||||
//
|
||||
#include "gui/main_window.hpp"
|
||||
int main()
|
||||
{
|
||||
imgui_desktop::gui::MainWindow("omath::hud", 800, 600).Run();
|
||||
}
|
||||
@@ -8,6 +8,7 @@
|
||||
#include <memory>
|
||||
#include <memory_resource>
|
||||
#include <queue>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
@@ -56,83 +57,76 @@ namespace omath::collision
|
||||
const Simplex<VectorType>& simplex, const Params params = {},
|
||||
std::pmr::memory_resource& mem_resource = *std::pmr::get_default_resource())
|
||||
{
|
||||
// --- Build initial polytope from simplex (4 points) ---
|
||||
std::pmr::vector<VectorType> vertexes = build_initial_polytope_from_simplex(simplex, mem_resource);
|
||||
|
||||
// Initial tetra faces (windings corrected in make_face)
|
||||
std::pmr::vector<Face> faces = create_initial_tetra_faces(mem_resource, vertexes);
|
||||
|
||||
auto heap = rebuild_heap(faces, mem_resource);
|
||||
// Build initial min-heap by distance.
|
||||
Heap heap = rebuild_heap(faces, mem_resource);
|
||||
|
||||
Result out{};
|
||||
|
||||
// Hoisted outside the loop to reuse bucket allocation across iterations.
|
||||
// Initial bucket count 16 covers a typical horizon without rehashing.
|
||||
BoundaryMap boundary{16, &mem_resource};
|
||||
|
||||
for (int it = 0; it < params.max_iterations; ++it)
|
||||
{
|
||||
// If heap might be stale after face edits, rebuild lazily.
|
||||
if (heap.empty())
|
||||
break;
|
||||
// Rebuild when the "closest" face changed (simple cheap guard)
|
||||
// (We could keep face handles; this is fine for small Ns.)
|
||||
|
||||
if (const auto top = heap.top(); faces[top.idx].d != top.d)
|
||||
heap = rebuild_heap(faces, mem_resource);
|
||||
// Lazily discard stale (deleted or index-mismatched) heap entries.
|
||||
discard_stale_heap_entries(faces, heap);
|
||||
|
||||
if (heap.empty())
|
||||
break;
|
||||
|
||||
// FIXME: STORE REF VALUE, DO NOT USE
|
||||
// AFTER IF STATEMENT BLOCK
|
||||
const Face& face = faces[heap.top().idx];
|
||||
|
||||
// Get the furthest point in face normal direction
|
||||
const VectorType p = support_point(a, b, face.n);
|
||||
const auto p_dist = face.n.dot(p);
|
||||
|
||||
// Converged if we can’t push the face closer than tolerance
|
||||
// Converged: new support can't push the face closer than tolerance.
|
||||
if (p_dist - face.d <= params.tolerance)
|
||||
{
|
||||
out.normal = face.n;
|
||||
out.depth = face.d; // along unit normal
|
||||
out.depth = face.d;
|
||||
out.iterations = it + 1;
|
||||
out.num_vertices = static_cast<int>(vertexes.size());
|
||||
out.num_faces = static_cast<int>(faces.size());
|
||||
|
||||
out.penetration_vector = out.normal * out.depth;
|
||||
return out;
|
||||
}
|
||||
|
||||
// Add new vertex
|
||||
const int new_idx = static_cast<int>(vertexes.size());
|
||||
vertexes.emplace_back(p);
|
||||
|
||||
const auto [to_delete, boundary] = mark_visible_and_collect_horizon(faces, p);
|
||||
// Tombstone visible faces and collect the horizon boundary.
|
||||
// This avoids copying the faces array (O(n)) each iteration.
|
||||
tombstone_visible_faces(faces, boundary, p);
|
||||
|
||||
erase_marked(faces, to_delete);
|
||||
|
||||
// Stitch new faces around the horizon
|
||||
for (const auto& e : boundary)
|
||||
// Stitch new faces around the horizon and push them directly onto the
|
||||
// heap — no full O(n log n) rebuild needed.
|
||||
for (const auto& [key, e] : boundary)
|
||||
{
|
||||
const int fi = static_cast<int>(faces.size());
|
||||
faces.emplace_back(make_face(vertexes, e.a, e.b, new_idx));
|
||||
|
||||
// Rebuild heap after topology change
|
||||
heap = rebuild_heap(faces, mem_resource);
|
||||
heap.emplace(faces.back().d, fi);
|
||||
}
|
||||
|
||||
if (!std::isfinite(vertexes.back().dot(vertexes.back())))
|
||||
break; // safety
|
||||
|
||||
out.iterations = it + 1;
|
||||
}
|
||||
|
||||
if (faces.empty())
|
||||
// Find the best surviving (non-deleted) face.
|
||||
const Face* best = find_best_surviving_face(faces);
|
||||
|
||||
if (!best)
|
||||
return std::nullopt;
|
||||
|
||||
const auto best = *std::ranges::min_element(faces, [](const auto& first, const auto& second)
|
||||
{ return first.d < second.d; });
|
||||
out.normal = best.n;
|
||||
out.depth = best.d;
|
||||
out.normal = best->n;
|
||||
out.depth = best->d;
|
||||
out.num_vertices = static_cast<int>(vertexes.size());
|
||||
out.num_faces = static_cast<int>(faces.size());
|
||||
|
||||
out.penetration_vector = out.normal * out.depth;
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -141,7 +135,8 @@ namespace omath::collision
|
||||
{
|
||||
int i0, i1, i2;
|
||||
VectorType n; // unit outward normal
|
||||
FloatingType d; // n · v0 (>=0 ideally because origin is inside)
|
||||
FloatingType d; // n · v0 (>= 0 ideally because origin is inside)
|
||||
bool deleted{false}; // tombstone flag — avoids O(n) compaction per iteration
|
||||
};
|
||||
|
||||
struct Edge final
|
||||
@@ -154,6 +149,7 @@ namespace omath::collision
|
||||
FloatingType d;
|
||||
int idx;
|
||||
};
|
||||
|
||||
struct HeapCmp final
|
||||
{
|
||||
[[nodiscard]]
|
||||
@@ -165,35 +161,44 @@ namespace omath::collision
|
||||
|
||||
using Heap = std::priority_queue<HeapItem, std::pmr::vector<HeapItem>, HeapCmp>;
|
||||
|
||||
// Horizon boundary: maps packed(a,b) → Edge.
|
||||
// Opposite edges cancel in O(1) via hash lookup instead of O(h) linear scan.
|
||||
using BoundaryMap = std::pmr::unordered_map<std::int64_t, Edge>;
|
||||
|
||||
[[nodiscard]]
|
||||
static constexpr std::int64_t pack_edge(const int a, const int b) noexcept
|
||||
{
|
||||
return (static_cast<std::int64_t>(a) << 32) | static_cast<std::uint32_t>(b);
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
static Heap rebuild_heap(const std::pmr::vector<Face>& faces, auto& memory_resource)
|
||||
{
|
||||
std::pmr::vector<HeapItem> storage{&memory_resource};
|
||||
storage.reserve(faces.size()); // optional but recommended
|
||||
|
||||
storage.reserve(faces.size());
|
||||
Heap h{HeapCmp{}, std::move(storage)};
|
||||
|
||||
for (int i = 0; i < static_cast<int>(faces.size()); ++i)
|
||||
h.emplace(faces[i].d, i);
|
||||
|
||||
return h; // allocator is preserved
|
||||
if (!faces[i].deleted)
|
||||
h.emplace(faces[i].d, i);
|
||||
return h;
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
static bool visible_from(const Face& f, const VectorType& p)
|
||||
{
|
||||
// positive if p is in front of the face
|
||||
return f.n.dot(p) - f.d > static_cast<FloatingType>(1e-7);
|
||||
}
|
||||
|
||||
static void add_edge_boundary(std::pmr::vector<Edge>& boundary, int a, int b)
|
||||
static void add_edge_boundary(BoundaryMap& boundary, int a, int b)
|
||||
{
|
||||
// Keep edges that appear only once; erase if opposite already present
|
||||
auto itb = std::ranges::find_if(boundary, [&](const Edge& e) { return e.a == b && e.b == a; });
|
||||
if (itb != boundary.end())
|
||||
boundary.erase(itb); // internal edge cancels out
|
||||
// O(1) cancel: if the opposite edge (b→a) is already in the map it is an
|
||||
// internal edge shared by two visible faces and must be removed.
|
||||
// Otherwise this is a horizon edge and we insert it.
|
||||
const std::int64_t rev = pack_edge(b, a);
|
||||
if (const auto it = boundary.find(rev); it != boundary.end())
|
||||
boundary.erase(it);
|
||||
else
|
||||
boundary.emplace_back(a, b); // horizon edge (directed)
|
||||
boundary.emplace(pack_edge(a, b), Edge{a, b});
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
@@ -204,9 +209,7 @@ namespace omath::collision
|
||||
const VectorType& a2 = vertexes[i2];
|
||||
VectorType n = (a1 - a0).cross(a2 - a0);
|
||||
if (n.dot(n) <= static_cast<FloatingType>(1e-30))
|
||||
{
|
||||
n = any_perp_vec(a1 - a0); // degenerate guard
|
||||
}
|
||||
// Ensure normal points outward (away from origin): require n·a0 >= 0
|
||||
if (n.dot(a0) < static_cast<FloatingType>(0.0))
|
||||
{
|
||||
@@ -243,6 +246,7 @@ namespace omath::collision
|
||||
return d;
|
||||
return V{1, 0, 0};
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
static std::pmr::vector<Face> create_initial_tetra_faces(std::pmr::memory_resource& mem_resource,
|
||||
const std::pmr::vector<VectorType>& vertexes)
|
||||
@@ -262,48 +266,45 @@ namespace omath::collision
|
||||
{
|
||||
std::pmr::vector<VectorType> vertexes{&mem_resource};
|
||||
vertexes.reserve(simplex.size());
|
||||
|
||||
for (std::size_t i = 0; i < simplex.size(); ++i)
|
||||
vertexes.emplace_back(simplex[i]);
|
||||
|
||||
return vertexes;
|
||||
}
|
||||
static void erase_marked(std::pmr::vector<Face>& faces, const std::pmr::vector<bool>& to_delete)
|
||||
|
||||
static const Face* find_best_surviving_face(const std::pmr::vector<Face>& faces)
|
||||
{
|
||||
auto* mr = faces.get_allocator().resource(); // keep same resource
|
||||
std::pmr::vector<Face> kept{mr};
|
||||
kept.reserve(faces.size());
|
||||
|
||||
for (std::size_t i = 0; i < faces.size(); ++i)
|
||||
if (!to_delete[i])
|
||||
kept.emplace_back(faces[i]);
|
||||
|
||||
faces.swap(kept);
|
||||
const Face* best = nullptr;
|
||||
for (const auto& f : faces)
|
||||
if (!f.deleted && (best == nullptr || f.d < best->d))
|
||||
best = &f;
|
||||
return best;
|
||||
}
|
||||
struct Horizon
|
||||
static void tombstone_visible_faces(std::pmr::vector<Face>& faces, BoundaryMap& boundary,
|
||||
const VectorType& p)
|
||||
{
|
||||
std::pmr::vector<bool> to_delete;
|
||||
std::pmr::vector<Edge> boundary;
|
||||
};
|
||||
|
||||
static Horizon mark_visible_and_collect_horizon(const std::pmr::vector<Face>& faces, const VectorType& p)
|
||||
{
|
||||
auto* mr = faces.get_allocator().resource();
|
||||
|
||||
Horizon horizon{std::pmr::vector<bool>(faces.size(), false, mr), std::pmr::vector<Edge>(mr)};
|
||||
horizon.boundary.reserve(faces.size());
|
||||
|
||||
for (std::size_t i = 0; i < faces.size(); ++i)
|
||||
if (visible_from(faces[i], p))
|
||||
boundary.clear();
|
||||
for (auto& f : faces)
|
||||
{
|
||||
if (!f.deleted && visible_from(f, p))
|
||||
{
|
||||
const auto& rf = faces[i];
|
||||
horizon.to_delete[i] = true;
|
||||
add_edge_boundary(horizon.boundary, rf.i0, rf.i1);
|
||||
add_edge_boundary(horizon.boundary, rf.i1, rf.i2);
|
||||
add_edge_boundary(horizon.boundary, rf.i2, rf.i0);
|
||||
f.deleted = true;
|
||||
add_edge_boundary(boundary, f.i0, f.i1);
|
||||
add_edge_boundary(boundary, f.i1, f.i2);
|
||||
add_edge_boundary(boundary, f.i2, f.i0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return horizon;
|
||||
static void discard_stale_heap_entries(const std::pmr::vector<Face>& faces,
|
||||
std::priority_queue<HeapItem, std::pmr::vector<HeapItem>, HeapCmp>& heap)
|
||||
{
|
||||
while (!heap.empty())
|
||||
{
|
||||
const auto& top = heap.top();
|
||||
if (!faces[top.idx].deleted && faces[top.idx].d == top.d)
|
||||
break;
|
||||
heap.pop();
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace omath::collision
|
||||
|
||||
@@ -14,11 +14,15 @@ namespace omath::collision
|
||||
Simplex<VertexType> simplex; // valid only if hit == true and size==4
|
||||
};
|
||||
|
||||
struct GjkSettings final
|
||||
{
|
||||
float epsilon = 1e-6f;
|
||||
std::size_t max_iterations = 64;
|
||||
};
|
||||
template<class ColliderInterfaceType>
|
||||
class GjkAlgorithm final
|
||||
{
|
||||
using VectorType = ColliderInterfaceType::VectorType;
|
||||
|
||||
public:
|
||||
[[nodiscard]]
|
||||
static VectorType find_support_vertex(const ColliderInterfaceType& collider_a,
|
||||
@@ -36,20 +40,34 @@ namespace omath::collision
|
||||
|
||||
[[nodiscard]]
|
||||
static GjkHitInfo<VectorType> is_collide_with_simplex_info(const ColliderInterfaceType& collider_a,
|
||||
const ColliderInterfaceType& collider_b)
|
||||
const ColliderInterfaceType& collider_b,
|
||||
const GjkSettings& settings = {})
|
||||
{
|
||||
auto support = find_support_vertex(collider_a, collider_b, VectorType{1, 0, 0});
|
||||
// Use centroid difference as initial direction — greatly reduces iterations for separated shapes.
|
||||
VectorType initial_dir;
|
||||
if constexpr (requires { collider_b.get_origin() - collider_a.get_origin(); })
|
||||
{
|
||||
initial_dir = collider_b.get_origin() - collider_a.get_origin();
|
||||
if (initial_dir.dot(initial_dir) < settings.epsilon * settings.epsilon)
|
||||
initial_dir = VectorType{1, 0, 0};
|
||||
}
|
||||
else
|
||||
{
|
||||
initial_dir = VectorType{1, 0, 0};
|
||||
}
|
||||
|
||||
auto support = find_support_vertex(collider_a, collider_b, initial_dir);
|
||||
|
||||
Simplex<VectorType> simplex;
|
||||
simplex.push_front(support);
|
||||
|
||||
auto direction = -support;
|
||||
|
||||
while (true)
|
||||
for (std::size_t iteration = 0; iteration < settings.max_iterations; ++iteration)
|
||||
{
|
||||
support = find_support_vertex(collider_a, collider_b, direction);
|
||||
|
||||
if (support.dot(direction) <= 0.f)
|
||||
if (support.dot(direction) <= settings.epsilon)
|
||||
return {false, simplex};
|
||||
|
||||
simplex.push_front(support);
|
||||
@@ -57,6 +75,7 @@ namespace omath::collision
|
||||
if (simplex.handle(direction))
|
||||
return {true, simplex};
|
||||
}
|
||||
return {false, simplex};
|
||||
}
|
||||
};
|
||||
} // namespace omath::collision
|
||||
@@ -42,13 +42,40 @@ namespace omath::collision
|
||||
m_mesh.set_origin(new_origin);
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
const MeshType& get_mesh() const
|
||||
{
|
||||
return m_mesh;
|
||||
}
|
||||
[[nodiscard]]
|
||||
MeshType& get_mesh()
|
||||
{
|
||||
return m_mesh;
|
||||
}
|
||||
private:
|
||||
[[nodiscard]]
|
||||
const VertexType& find_furthest_vertex(const VectorType& direction) const
|
||||
{
|
||||
return *std::ranges::max_element(
|
||||
m_mesh.m_vertex_buffer, [&direction](const auto& first, const auto& second)
|
||||
{ return first.position.dot(direction) < second.position.dot(direction); });
|
||||
// The support query arrives in world space, but vertex positions are stored
|
||||
// in local space. We need argmax_v { world(v) · d }.
|
||||
//
|
||||
// world(v) = M·v (ignoring translation, which is constant across vertices)
|
||||
// world(v) · d = v · Mᵀ·d
|
||||
//
|
||||
// So we transform the direction to local space once — O(1) — then compare
|
||||
// raw local positions, which is far cheaper than calling
|
||||
// vertex_position_to_world_space (full 4×4 multiply) for every vertex.
|
||||
//
|
||||
// d_local = upper-left 3×3 of M, transposed, times d_world:
|
||||
// d_local[j] = sum_i M.at(i,j) * d[i] (i.e. column j of M dotted with d)
|
||||
const auto& m = m_mesh.get_to_world_matrix();
|
||||
const VectorType d_local = {
|
||||
m[0, 0] * direction.x + m[1, 0] * direction.y + m[2, 0] * direction.z,
|
||||
m[0, 1] * direction.x + m[1, 1] * direction.y + m[2, 1] * direction.z,
|
||||
m[0, 2] * direction.x + m[1, 2] * direction.y + m[2, 2] * direction.z,
|
||||
};
|
||||
return *std::ranges::max_element(m_mesh.m_vertex_buffer, [&d_local](const auto& first, const auto& second)
|
||||
{ return first.position.dot(d_local) < second.position.dot(d_local); });
|
||||
}
|
||||
MeshType m_mesh;
|
||||
};
|
||||
|
||||
23
include/omath/hud/canvas_box.hpp
Normal file
23
include/omath/hud/canvas_box.hpp
Normal file
@@ -0,0 +1,23 @@
|
||||
//
|
||||
// Created by orange on 13.03.2026.
|
||||
//
|
||||
#pragma once
|
||||
#include "omath/linear_algebra/vector2.hpp"
|
||||
#include <array>
|
||||
namespace omath::hud
|
||||
{
|
||||
class CanvasBox final
|
||||
{
|
||||
public:
|
||||
CanvasBox(Vector2<float> top, Vector2<float> bottom, float ratio = 4.f);
|
||||
|
||||
[[nodiscard]]
|
||||
std::array<Vector2<float>, 4> as_array() const;
|
||||
|
||||
Vector2<float> top_left_corner;
|
||||
Vector2<float> top_right_corner;
|
||||
|
||||
Vector2<float> bottom_left_corner;
|
||||
Vector2<float> bottom_right_corner;
|
||||
};
|
||||
} // namespace omath::hud
|
||||
201
include/omath/hud/entity_overlay.hpp
Normal file
201
include/omath/hud/entity_overlay.hpp
Normal file
@@ -0,0 +1,201 @@
|
||||
//
|
||||
// Created by orange on 13.03.2026.
|
||||
//
|
||||
#pragma once
|
||||
#include "canvas_box.hpp"
|
||||
#include "entity_overlay_widgets.hpp"
|
||||
#include "hud_renderer_interface.hpp"
|
||||
#include "omath/linear_algebra/vector2.hpp"
|
||||
#include "omath/utility/color.hpp"
|
||||
#include <memory>
|
||||
#include <string_view>
|
||||
|
||||
namespace omath::hud
|
||||
{
|
||||
class EntityOverlay final
|
||||
{
|
||||
public:
|
||||
EntityOverlay(const Vector2<float>& top, const Vector2<float>& bottom,
|
||||
const std::shared_ptr<HudRendererInterface>& renderer);
|
||||
|
||||
// ── Boxes ────────────────────────────────────────────────────────
|
||||
EntityOverlay& add_2d_box(const Color& box_color, const Color& fill_color = Color{0.f, 0.f, 0.f, 0.f},
|
||||
float thickness = 1.f);
|
||||
|
||||
EntityOverlay& add_cornered_2d_box(const Color& box_color, const Color& fill_color = Color{0.f, 0.f, 0.f, 0.f},
|
||||
float corner_ratio_len = 0.2f, float thickness = 1.f);
|
||||
|
||||
EntityOverlay& add_dashed_box(const Color& color, float dash_len = 8.f, float gap_len = 5.f,
|
||||
float thickness = 1.f);
|
||||
|
||||
// ── Bars ─────────────────────────────────────────────────────────
|
||||
EntityOverlay& add_right_bar(const Color& color, const Color& outline_color, const Color& bg_color, float width,
|
||||
float ratio, float offset = 5.f);
|
||||
|
||||
EntityOverlay& add_left_bar(const Color& color, const Color& outline_color, const Color& bg_color, float width,
|
||||
float ratio, float offset = 5.f);
|
||||
|
||||
EntityOverlay& add_top_bar(const Color& color, const Color& outline_color, const Color& bg_color, float height,
|
||||
float ratio, float offset = 5.f);
|
||||
|
||||
EntityOverlay& add_bottom_bar(const Color& color, const Color& outline_color, const Color& bg_color,
|
||||
float height, float ratio, float offset = 5.f);
|
||||
|
||||
EntityOverlay& add_right_dashed_bar(const Color& color, const Color& outline_color, const Color& bg_color,
|
||||
float width, float ratio, float dash_len, float gap_len,
|
||||
float offset = 5.f);
|
||||
|
||||
EntityOverlay& add_left_dashed_bar(const Color& color, const Color& outline_color, const Color& bg_color,
|
||||
float width, float ratio, float dash_len, float gap_len, float offset = 5.f);
|
||||
|
||||
EntityOverlay& add_top_dashed_bar(const Color& color, const Color& outline_color, const Color& bg_color,
|
||||
float height, float ratio, float dash_len, float gap_len, float offset = 5.f);
|
||||
|
||||
EntityOverlay& add_bottom_dashed_bar(const Color& color, const Color& outline_color, const Color& bg_color,
|
||||
float height, float ratio, float dash_len, float gap_len,
|
||||
float offset = 5.f);
|
||||
|
||||
// ── Labels ───────────────────────────────────────────────────────
|
||||
EntityOverlay& add_right_label(const Color& color, float offset, bool outlined, const std::string_view& text);
|
||||
|
||||
EntityOverlay& add_left_label(const Color& color, float offset, bool outlined, const std::string_view& text);
|
||||
|
||||
EntityOverlay& add_top_label(const Color& color, float offset, bool outlined, std::string_view text);
|
||||
|
||||
EntityOverlay& add_bottom_label(const Color& color, float offset, bool outlined, std::string_view text);
|
||||
|
||||
EntityOverlay& add_centered_top_label(const Color& color, float offset, bool outlined,
|
||||
const std::string_view& text);
|
||||
|
||||
EntityOverlay& add_centered_bottom_label(const Color& color, float offset, bool outlined,
|
||||
const std::string_view& text);
|
||||
|
||||
template<typename... Args>
|
||||
EntityOverlay& add_right_label(const Color& color, const float offset, const bool outlined, std::format_string<Args...> fmt,
|
||||
Args&&... args)
|
||||
{
|
||||
return add_right_label(color, offset, outlined,
|
||||
std::string_view{std::vformat(fmt.get(), std::make_format_args(args...))});
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
EntityOverlay& add_left_label(const Color& color, const float offset, const bool outlined, std::format_string<Args...> fmt,
|
||||
Args&&... args)
|
||||
{
|
||||
return add_left_label(color, offset, outlined,
|
||||
std::string_view{std::vformat(fmt.get(), std::make_format_args(args...))});
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
EntityOverlay& add_top_label(const Color& color, const float offset, const bool outlined, std::format_string<Args...> fmt,
|
||||
Args&&... args)
|
||||
{
|
||||
return add_top_label(color, offset, outlined,
|
||||
std::string_view{std::vformat(fmt.get(), std::make_format_args(args...))});
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
EntityOverlay& add_bottom_label(const Color& color, const float offset, const bool outlined,
|
||||
std::format_string<Args...> fmt, Args&&... args)
|
||||
{
|
||||
return add_bottom_label(color, offset, outlined,
|
||||
std::string_view{std::vformat(fmt.get(), std::make_format_args(args...))});
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
EntityOverlay& add_centered_top_label(const Color& color, const float offset, const bool outlined,
|
||||
std::format_string<Args...> fmt, Args&&... args)
|
||||
{
|
||||
return add_centered_top_label(color, offset, outlined,
|
||||
std::string_view{std::vformat(fmt.get(), std::make_format_args(args...))});
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
EntityOverlay& add_centered_bottom_label(const Color& color, const float offset, const bool outlined,
|
||||
std::format_string<Args...> fmt, Args&&... args)
|
||||
{
|
||||
return add_centered_bottom_label(color, offset, outlined,
|
||||
std::string_view{std::vformat(fmt.get(), std::make_format_args(args...))});
|
||||
}
|
||||
|
||||
// ── Spacers ─────────────────────────────────────────────────────
|
||||
EntityOverlay& add_right_space_vertical(float size);
|
||||
EntityOverlay& add_right_space_horizontal(float size);
|
||||
EntityOverlay& add_left_space_vertical(float size);
|
||||
EntityOverlay& add_left_space_horizontal(float size);
|
||||
EntityOverlay& add_top_space_vertical(float size);
|
||||
EntityOverlay& add_top_space_horizontal(float size);
|
||||
EntityOverlay& add_bottom_space_vertical(float size);
|
||||
EntityOverlay& add_bottom_space_horizontal(float size);
|
||||
|
||||
// ── Progress rings ──────────────────────────────────────────────
|
||||
EntityOverlay& add_right_progress_ring(const Color& color, const Color& bg, float radius, float ratio,
|
||||
float thickness = 2.f, float offset = 5.f, int segments = 0);
|
||||
EntityOverlay& add_left_progress_ring(const Color& color, const Color& bg, float radius, float ratio,
|
||||
float thickness = 2.f, float offset = 5.f, int segments = 0);
|
||||
EntityOverlay& add_top_progress_ring(const Color& color, const Color& bg, float radius, float ratio,
|
||||
float thickness = 2.f, float offset = 5.f, int segments = 0);
|
||||
EntityOverlay& add_bottom_progress_ring(const Color& color, const Color& bg, float radius, float ratio,
|
||||
float thickness = 2.f, float offset = 5.f, int segments = 0);
|
||||
|
||||
// ── Icons ────────────────────────────────────────────────────────
|
||||
EntityOverlay& add_right_icon(const std::any& texture_id, float width, float height,
|
||||
const Color& tint = Color{1.f, 1.f, 1.f, 1.f}, float offset = 5.f);
|
||||
EntityOverlay& add_left_icon(const std::any& texture_id, float width, float height,
|
||||
const Color& tint = Color{1.f, 1.f, 1.f, 1.f}, float offset = 5.f);
|
||||
EntityOverlay& add_top_icon(const std::any& texture_id, float width, float height,
|
||||
const Color& tint = Color{1.f, 1.f, 1.f, 1.f}, float offset = 5.f);
|
||||
EntityOverlay& add_bottom_icon(const std::any& texture_id, float width, float height,
|
||||
const Color& tint = Color{1.f, 1.f, 1.f, 1.f}, float offset = 5.f);
|
||||
|
||||
// ── Misc ─────────────────────────────────────────────────────────
|
||||
EntityOverlay& add_snap_line(const Vector2<float>& start_pos, const Color& color, float width);
|
||||
|
||||
EntityOverlay& add_skeleton(const Color& color, float thickness = 1.f);
|
||||
|
||||
// ── Declarative interface ─────────────────────────────────────────
|
||||
/// Pass any combination of widget:: descriptor structs (and std::optional<W>
|
||||
/// from when()) to render them all in declaration order.
|
||||
template<typename... Widgets>
|
||||
EntityOverlay& contents(Widgets&&... widgets)
|
||||
{
|
||||
(dispatch(std::forward<Widgets>(widgets)), ...);
|
||||
return *this;
|
||||
}
|
||||
|
||||
private:
|
||||
// optional<W> dispatch — enables when() conditional widgets
|
||||
template<typename W>
|
||||
void dispatch(const std::optional<W>& w)
|
||||
{
|
||||
if (w)
|
||||
dispatch(*w);
|
||||
}
|
||||
|
||||
void dispatch(const widget::Box& box);
|
||||
void dispatch(const widget::CorneredBox& cornered_box);
|
||||
void dispatch(const widget::DashedBox& dashed_box);
|
||||
void dispatch(const widget::RightSide& right_side);
|
||||
void dispatch(const widget::LeftSide& left_side);
|
||||
void dispatch(const widget::TopSide& top_side);
|
||||
void dispatch(const widget::BottomSide& bottom_side);
|
||||
void dispatch(const widget::Skeleton& skeleton);
|
||||
void dispatch(const widget::SnapLine& snap_line);
|
||||
void dispatch(const widget::ScanMarker& scan_marker);
|
||||
void dispatch(const widget::AimDot& aim_dot);
|
||||
void draw_progress_ring(const Vector2<float>& center, const widget::ProgressRing& ring);
|
||||
void draw_outlined_text(const Vector2<float>& position, const Color& color, const std::string_view& text);
|
||||
void draw_dashed_line(const Vector2<float>& from, const Vector2<float>& to, const Color& color, float dash_len,
|
||||
float gap_len, float thickness) const;
|
||||
void draw_dashed_fill(const Vector2<float>& origin, const Vector2<float>& step_dir,
|
||||
const Vector2<float>& perp_dir, float full_len, float filled_len, const Color& fill_color,
|
||||
const Color& split_color, float dash_len, float gap_len) const;
|
||||
|
||||
CanvasBox m_canvas;
|
||||
Vector2<float> m_text_cursor_right;
|
||||
Vector2<float> m_text_cursor_top;
|
||||
Vector2<float> m_text_cursor_bottom;
|
||||
Vector2<float> m_text_cursor_left;
|
||||
std::shared_ptr<HudRendererInterface> m_renderer;
|
||||
};
|
||||
} // namespace omath::hud
|
||||
219
include/omath/hud/entity_overlay_widgets.hpp
Normal file
219
include/omath/hud/entity_overlay_widgets.hpp
Normal file
@@ -0,0 +1,219 @@
|
||||
//
|
||||
// Created by orange on 15.03.2026.
|
||||
//
|
||||
#pragma once
|
||||
#include "omath/linear_algebra/vector2.hpp"
|
||||
#include "omath/utility/color.hpp"
|
||||
#include <any>
|
||||
#include <initializer_list>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
#include <variant>
|
||||
|
||||
namespace omath::hud::widget
|
||||
{
|
||||
// ── Overloaded helper for std::visit ──────────────────────────────────────
|
||||
template<typename... Ts>
|
||||
struct Overloaded : Ts...
|
||||
{
|
||||
using Ts::operator()...;
|
||||
};
|
||||
template<typename... Ts>
|
||||
Overloaded(Ts...) -> Overloaded<Ts...>;
|
||||
|
||||
// ── Standalone widgets ────────────────────────────────────────────────────
|
||||
struct Box
|
||||
{
|
||||
Color color;
|
||||
Color fill{0.f, 0.f, 0.f, 0.f};
|
||||
float thickness = 1.f;
|
||||
};
|
||||
|
||||
struct CorneredBox
|
||||
{
|
||||
Color color;
|
||||
Color fill{0.f, 0.f, 0.f, 0.f};
|
||||
float corner_ratio = 0.2f;
|
||||
float thickness = 1.f;
|
||||
};
|
||||
|
||||
struct DashedBox
|
||||
{
|
||||
Color color;
|
||||
float dash_len = 8.f;
|
||||
float gap_len = 5.f;
|
||||
float thickness = 1.f;
|
||||
};
|
||||
|
||||
struct Skeleton
|
||||
{
|
||||
Color color;
|
||||
float thickness = 1.f;
|
||||
};
|
||||
struct SnapLine
|
||||
{
|
||||
Vector2<float> start;
|
||||
Color color;
|
||||
float width;
|
||||
};
|
||||
|
||||
struct ScanMarker
|
||||
{
|
||||
Color color;
|
||||
Color outline{0.f, 0.f, 0.f, 0.f};
|
||||
float outline_thickness = 1.f;
|
||||
};
|
||||
|
||||
/// Dot at an absolute screen position.
|
||||
struct AimDot
|
||||
{
|
||||
Vector2<float> position;
|
||||
Color color;
|
||||
float radius = 3.f;
|
||||
};
|
||||
|
||||
// ── Side-agnostic widgets (used inside XxxSide containers) ────────────────
|
||||
|
||||
/// A filled bar. `size` is width for left/right sides, height for top/bottom.
|
||||
struct Bar
|
||||
{
|
||||
Color color;
|
||||
Color outline;
|
||||
Color bg;
|
||||
float size;
|
||||
float ratio;
|
||||
float offset = 5.f;
|
||||
};
|
||||
|
||||
/// A dashed bar. Same field semantics as Bar plus dash parameters.
|
||||
struct DashedBar
|
||||
{
|
||||
Color color;
|
||||
Color outline;
|
||||
Color bg;
|
||||
float size;
|
||||
float ratio;
|
||||
float dash_len;
|
||||
float gap_len;
|
||||
float offset = 5.f;
|
||||
};
|
||||
|
||||
struct Label
|
||||
{
|
||||
Color color;
|
||||
float offset;
|
||||
bool outlined;
|
||||
std::string_view text;
|
||||
};
|
||||
|
||||
/// Wraps a Label to request horizontal centering (only applied in TopSide / BottomSide).
|
||||
template<typename W>
|
||||
struct Centered
|
||||
{
|
||||
W child;
|
||||
};
|
||||
template<typename W>
|
||||
Centered(W) -> Centered<W>;
|
||||
|
||||
/// Empty vertical gap that advances the Y cursor without drawing.
|
||||
struct SpaceVertical
|
||||
{
|
||||
float size;
|
||||
};
|
||||
|
||||
/// Empty horizontal gap that advances the X cursor without drawing.
|
||||
struct SpaceHorizontal
|
||||
{
|
||||
float size;
|
||||
};
|
||||
|
||||
struct ProgressRing
|
||||
{
|
||||
Color color;
|
||||
Color bg{0.3f, 0.3f, 0.3f, 0.5f};
|
||||
float radius = 12.f;
|
||||
float ratio;
|
||||
float thickness = 2.f;
|
||||
float offset = 5.f;
|
||||
int segments = 32;
|
||||
};
|
||||
|
||||
struct Icon
|
||||
{
|
||||
std::any texture_id;
|
||||
float width;
|
||||
float height;
|
||||
Color tint{1.f, 1.f, 1.f, 1.f};
|
||||
float offset = 5.f;
|
||||
};
|
||||
|
||||
// ── Side widget variant ───────────────────────────────────────────────────
|
||||
struct None
|
||||
{
|
||||
}; ///< No-op placeholder — used by widget::when for disabled elements.
|
||||
using SideWidget =
|
||||
std::variant<None, Bar, DashedBar, Label, Centered<Label>, SpaceVertical, SpaceHorizontal, ProgressRing, Icon>;
|
||||
|
||||
// ── Side containers ───────────────────────────────────────────────────────
|
||||
// Storing std::initializer_list<SideWidget> is safe here: the backing array
|
||||
// is a const SideWidget[] on the caller's stack whose lifetime matches the
|
||||
// temporary side-container object, which is consumed within the same
|
||||
// full-expression by EntityOverlay::dispatch. No heap allocation occurs.
|
||||
|
||||
struct RightSide
|
||||
{
|
||||
std::initializer_list<SideWidget> children;
|
||||
RightSide(const std::initializer_list<SideWidget> c): children(c)
|
||||
{
|
||||
}
|
||||
};
|
||||
struct LeftSide
|
||||
{
|
||||
std::initializer_list<SideWidget> children;
|
||||
LeftSide(const std::initializer_list<SideWidget> c): children(c)
|
||||
{
|
||||
}
|
||||
};
|
||||
struct TopSide
|
||||
{
|
||||
std::initializer_list<SideWidget> children;
|
||||
TopSide(const std::initializer_list<SideWidget> c): children(c)
|
||||
{
|
||||
}
|
||||
};
|
||||
struct BottomSide
|
||||
{
|
||||
std::initializer_list<SideWidget> children;
|
||||
BottomSide(const std::initializer_list<SideWidget> c): children(c)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace omath::hud::widget
|
||||
|
||||
namespace omath::hud::widget
|
||||
{
|
||||
/// Inside XxxSide containers: returns the widget as a SideWidget when condition is true,
|
||||
/// or None{} otherwise. Preferred over hud::when for types inside the SideWidget variant.
|
||||
template<typename W>
|
||||
requires std::constructible_from<SideWidget, W>
|
||||
SideWidget when(const bool condition, W widget)
|
||||
{
|
||||
if (condition)
|
||||
return SideWidget{std::move(widget)};
|
||||
return None{};
|
||||
}
|
||||
} // namespace omath::hud::widget
|
||||
|
||||
namespace omath::hud
|
||||
{
|
||||
/// Top-level: returns an engaged optional<W> when condition is true, std::nullopt otherwise.
|
||||
/// Designed for use with EntityOverlay::contents() for top-level widget types.
|
||||
template<typename W>
|
||||
std::optional<W> when(const bool condition, W widget)
|
||||
{
|
||||
if (condition)
|
||||
return std::move(widget);
|
||||
return std::nullopt;
|
||||
}
|
||||
} // namespace omath::hud
|
||||
47
include/omath/hud/hud_renderer_interface.hpp
Normal file
47
include/omath/hud/hud_renderer_interface.hpp
Normal file
@@ -0,0 +1,47 @@
|
||||
//
|
||||
// Created by orange on 13.03.2026.
|
||||
//
|
||||
#pragma once
|
||||
#include "omath/linear_algebra/vector2.hpp"
|
||||
#include "omath/utility/color.hpp"
|
||||
#include <any>
|
||||
#include <span>
|
||||
|
||||
namespace omath::hud
|
||||
{
|
||||
class HudRendererInterface
|
||||
{
|
||||
public:
|
||||
virtual ~HudRendererInterface() = default;
|
||||
virtual void add_line(const Vector2<float>& line_start, const Vector2<float>& line_end, const Color& color,
|
||||
float thickness) = 0;
|
||||
|
||||
virtual void add_polyline(const std::span<const Vector2<float>>& vertexes, const Color& color,
|
||||
float thickness) = 0;
|
||||
|
||||
virtual void add_filled_polyline(const std::span<const Vector2<float>>& vertexes, const Color& color) = 0;
|
||||
|
||||
virtual void add_rectangle(const Vector2<float>& min, const Vector2<float>& max, const Color& color) = 0;
|
||||
|
||||
virtual void add_filled_rectangle(const Vector2<float>& min, const Vector2<float>& max, const Color& color) = 0;
|
||||
|
||||
virtual void add_circle(const Vector2<float>& center, float radius, const Color& color, float thickness,
|
||||
int segments = 0) = 0;
|
||||
|
||||
virtual void add_filled_circle(const Vector2<float>& center, float radius, const Color& color,
|
||||
int segments = 0) = 0;
|
||||
|
||||
/// Draw an arc (partial circle outline). Angles in radians, 0 = right (+X), counter-clockwise.
|
||||
virtual void add_arc(const Vector2<float>& center, float radius, float a_min, float a_max, const Color& color,
|
||||
float thickness, int segments = 0) = 0;
|
||||
|
||||
/// Draw a textured quad. texture_id is renderer-specific (e.g. ImTextureID for ImGui).
|
||||
virtual void add_image(const std::any& texture_id, const Vector2<float>& min, const Vector2<float>& max,
|
||||
const Color& tint = Color{1.f, 1.f, 1.f, 1.f}) = 0;
|
||||
|
||||
virtual void add_text(const Vector2<float>& position, const Color& color, const std::string_view& text) = 0;
|
||||
|
||||
[[nodiscard]]
|
||||
virtual Vector2<float> calc_text_size(const std::string_view& text) = 0;
|
||||
};
|
||||
} // namespace omath::hud
|
||||
33
include/omath/hud/renderer_realizations/imgui_renderer.hpp
Normal file
33
include/omath/hud/renderer_realizations/imgui_renderer.hpp
Normal file
@@ -0,0 +1,33 @@
|
||||
//
|
||||
// Created by orange on 13.03.2026.
|
||||
//
|
||||
#pragma once
|
||||
#include <omath/hud/hud_renderer_interface.hpp>
|
||||
|
||||
#ifdef OMATH_IMGUI_INTEGRATION
|
||||
namespace omath::hud
|
||||
{
|
||||
class ImguiHudRenderer final : public HudRendererInterface
|
||||
{
|
||||
public:
|
||||
~ImguiHudRenderer() override;
|
||||
void add_line(const Vector2<float>& line_start, const Vector2<float>& line_end, const Color& color,
|
||||
float thickness) override;
|
||||
void add_polyline(const std::span<const Vector2<float>>& vertexes, const Color& color, float thickness) override;
|
||||
void add_filled_polyline(const std::span<const Vector2<float>>& vertexes, const Color& color) override;
|
||||
void add_rectangle(const Vector2<float>& min, const Vector2<float>& max, const Color& color) override;
|
||||
void add_filled_rectangle(const Vector2<float>& min, const Vector2<float>& max, const Color& color) override;
|
||||
void add_circle(const Vector2<float>& center, float radius, const Color& color, float thickness,
|
||||
int segments = 0) override;
|
||||
void add_filled_circle(const Vector2<float>& center, float radius, const Color& color,
|
||||
int segments = 0) override;
|
||||
void add_arc(const Vector2<float>& center, float radius, float a_min, float a_max, const Color& color,
|
||||
float thickness, int segments = 0) override;
|
||||
void add_image(const std::any& texture_id, const Vector2<float>& min, const Vector2<float>& max,
|
||||
const Color& tint = Color{1.f, 1.f, 1.f, 1.f}) override;
|
||||
void add_text(const Vector2<float>& position, const Color& color, const std::string_view& text) override;
|
||||
[[nodiscard]]
|
||||
virtual Vector2<float> calc_text_size(const std::string_view& text) override;
|
||||
};
|
||||
} // namespace omath::hud
|
||||
#endif // OMATH_IMGUI_INTEGRATION
|
||||
219
include/omath/linear_algebra/quaternion.hpp
Normal file
219
include/omath/linear_algebra/quaternion.hpp
Normal file
@@ -0,0 +1,219 @@
|
||||
//
|
||||
// Created by vlad on 3/1/2026.
|
||||
//
|
||||
#pragma once
|
||||
|
||||
#include "omath/linear_algebra/mat.hpp"
|
||||
#include "omath/linear_algebra/vector3.hpp"
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <format>
|
||||
|
||||
namespace omath
|
||||
{
|
||||
template<class Type>
|
||||
requires std::is_arithmetic_v<Type>
|
||||
class Quaternion
|
||||
{
|
||||
public:
|
||||
using ContainedType = Type;
|
||||
|
||||
Type x = static_cast<Type>(0);
|
||||
Type y = static_cast<Type>(0);
|
||||
Type z = static_cast<Type>(0);
|
||||
Type w = static_cast<Type>(1); // identity quaternion
|
||||
|
||||
constexpr Quaternion() noexcept = default;
|
||||
|
||||
constexpr Quaternion(const Type& x, const Type& y, const Type& z, const Type& w) noexcept
|
||||
: x(x), y(y), z(z), w(w)
|
||||
{
|
||||
}
|
||||
|
||||
// Factory: build from a normalized axis and an angle in radians
|
||||
[[nodiscard]]
|
||||
static Quaternion from_axis_angle(const Vector3<Type>& axis, const Type& angle_rad) noexcept
|
||||
{
|
||||
const Type half = angle_rad / static_cast<Type>(2);
|
||||
const Type s = std::sin(half);
|
||||
return {axis.x * s, axis.y * s, axis.z * s, std::cos(half)};
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool operator==(const Quaternion& other) const noexcept
|
||||
{
|
||||
return x == other.x && y == other.y && z == other.z && w == other.w;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool operator!=(const Quaternion& other) const noexcept
|
||||
{
|
||||
return !(*this == other);
|
||||
}
|
||||
|
||||
// Hamilton product: this * other
|
||||
[[nodiscard]] constexpr Quaternion operator*(const Quaternion& other) const noexcept
|
||||
{
|
||||
return {
|
||||
w * other.x + x * other.w + y * other.z - z * other.y,
|
||||
w * other.y - x * other.z + y * other.w + z * other.x,
|
||||
w * other.z + x * other.y - y * other.x + z * other.w,
|
||||
w * other.w - x * other.x - y * other.y - z * other.z,
|
||||
};
|
||||
}
|
||||
|
||||
constexpr Quaternion& operator*=(const Quaternion& other) noexcept
|
||||
{
|
||||
return *this = *this * other;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Quaternion operator*(const Type& scalar) const noexcept
|
||||
{
|
||||
return {x * scalar, y * scalar, z * scalar, w * scalar};
|
||||
}
|
||||
|
||||
constexpr Quaternion& operator*=(const Type& scalar) noexcept
|
||||
{
|
||||
x *= scalar;
|
||||
y *= scalar;
|
||||
z *= scalar;
|
||||
w *= scalar;
|
||||
return *this;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Quaternion operator+(const Quaternion& other) const noexcept
|
||||
{
|
||||
return {x + other.x, y + other.y, z + other.z, w + other.w};
|
||||
}
|
||||
|
||||
constexpr Quaternion& operator+=(const Quaternion& other) noexcept
|
||||
{
|
||||
x += other.x;
|
||||
y += other.y;
|
||||
z += other.z;
|
||||
w += other.w;
|
||||
return *this;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Quaternion operator-() const noexcept
|
||||
{
|
||||
return {-x, -y, -z, -w};
|
||||
}
|
||||
|
||||
// Conjugate: negates the vector part (x, y, z)
|
||||
[[nodiscard]] constexpr Quaternion conjugate() const noexcept
|
||||
{
|
||||
return {-x, -y, -z, w};
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Type dot(const Quaternion& other) const noexcept
|
||||
{
|
||||
return x * other.x + y * other.y + z * other.z + w * other.w;
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Type length_sqr() const noexcept
|
||||
{
|
||||
return x * x + y * y + z * z + w * w;
|
||||
}
|
||||
|
||||
#ifndef _MSC_VER
|
||||
[[nodiscard]] constexpr Type length() const noexcept
|
||||
{
|
||||
return std::sqrt(length_sqr());
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr Quaternion normalized() const noexcept
|
||||
{
|
||||
const Type len = length();
|
||||
return len != static_cast<Type>(0) ? *this * (static_cast<Type>(1) / len) : *this;
|
||||
}
|
||||
#else
|
||||
[[nodiscard]] Type length() const noexcept
|
||||
{
|
||||
return std::sqrt(length_sqr());
|
||||
}
|
||||
|
||||
[[nodiscard]] Quaternion normalized() const noexcept
|
||||
{
|
||||
const Type len = length();
|
||||
return len != static_cast<Type>(0) ? *this * (static_cast<Type>(1) / len) : *this;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Inverse: q* / |q|^2 (for unit quaternions inverse == conjugate)
|
||||
[[nodiscard]] constexpr Quaternion inverse() const noexcept
|
||||
{
|
||||
return conjugate() * (static_cast<Type>(1) / length_sqr());
|
||||
}
|
||||
|
||||
// Rotate a 3D vector: v' = q * pure(v) * q^-1
|
||||
// Computed via Rodrigues' formula to avoid full quaternion product overhead
|
||||
[[nodiscard]] constexpr Vector3<Type> rotate(const Vector3<Type>& v) const noexcept
|
||||
{
|
||||
const Vector3<Type> q_vec{x, y, z};
|
||||
const Vector3<Type> cross = q_vec.cross(v);
|
||||
return v + cross * (static_cast<Type>(2) * w) + q_vec.cross(cross) * static_cast<Type>(2);
|
||||
}
|
||||
|
||||
// 3x3 rotation matrix from this (unit) quaternion
|
||||
[[nodiscard]] constexpr Mat<3, 3, Type> to_rotation_matrix3() const noexcept
|
||||
{
|
||||
const Type xx = x * x, yy = y * y, zz = z * z;
|
||||
const Type xy = x * y, xz = x * z, yz = y * z;
|
||||
const Type wx = w * x, wy = w * y, wz = w * z;
|
||||
const Type one = static_cast<Type>(1);
|
||||
const Type two = static_cast<Type>(2);
|
||||
|
||||
return {
|
||||
{one - two * (yy + zz), two * (xy - wz), two * (xz + wy) },
|
||||
{two * (xy + wz), one - two * (xx + zz), two * (yz - wx) },
|
||||
{two * (xz - wy), two * (yz + wx), one - two * (xx + yy)},
|
||||
};
|
||||
}
|
||||
|
||||
// 4x4 rotation matrix (with homogeneous row/column)
|
||||
[[nodiscard]] constexpr Mat<4, 4, Type> to_rotation_matrix4() const noexcept
|
||||
{
|
||||
const Type xx = x * x, yy = y * y, zz = z * z;
|
||||
const Type xy = x * y, xz = x * z, yz = y * z;
|
||||
const Type wx = w * x, wy = w * y, wz = w * z;
|
||||
const Type one = static_cast<Type>(1);
|
||||
const Type two = static_cast<Type>(2);
|
||||
const Type zero = static_cast<Type>(0);
|
||||
|
||||
return {
|
||||
{one - two * (yy + zz), two * (xy - wz), two * (xz + wy), zero},
|
||||
{two * (xy + wz), one - two * (xx + zz), two * (yz - wx), zero},
|
||||
{two * (xz - wy), two * (yz + wx), one - two * (xx + yy), zero},
|
||||
{zero, zero, zero, one },
|
||||
};
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr std::array<Type, 4> as_array() const noexcept
|
||||
{
|
||||
return {x, y, z, w};
|
||||
}
|
||||
};
|
||||
} // namespace omath
|
||||
|
||||
template<class Type>
|
||||
struct std::formatter<omath::Quaternion<Type>> // NOLINT(*-dcl58-cpp)
|
||||
{
|
||||
[[nodiscard]]
|
||||
static constexpr auto parse(std::format_parse_context& ctx)
|
||||
{
|
||||
return ctx.begin();
|
||||
}
|
||||
|
||||
template<class FormatContext>
|
||||
[[nodiscard]]
|
||||
static auto format(const omath::Quaternion<Type>& q, FormatContext& ctx)
|
||||
{
|
||||
if constexpr (std::is_same_v<typename FormatContext::char_type, char>)
|
||||
return std::format_to(ctx.out(), "[{}, {}, {}, {}]", q.x, q.y, q.z, q.w);
|
||||
|
||||
if constexpr (std::is_same_v<typename FormatContext::char_type, wchar_t>)
|
||||
return std::format_to(ctx.out(), L"[{}, {}, {}, {}]", q.x, q.y, q.z, q.w);
|
||||
|
||||
if constexpr (std::is_same_v<typename FormatContext::char_type, char8_t>)
|
||||
return std::format_to(ctx.out(), u8"[{}, {}, {}, {}]", q.x, q.y, q.z, q.w);
|
||||
}
|
||||
};
|
||||
25
include/omath/lua/lua.hpp
Normal file
25
include/omath/lua/lua.hpp
Normal file
@@ -0,0 +1,25 @@
|
||||
//
|
||||
// Created by orange on 07.03.2026.
|
||||
//
|
||||
#pragma once
|
||||
#ifdef OMATH_ENABLE_LUA
|
||||
#include <sol/forward.hpp>
|
||||
namespace omath::lua
|
||||
{
|
||||
class LuaInterpreter final
|
||||
{
|
||||
public:
|
||||
static void register_lib(lua_State* lua_state);
|
||||
|
||||
private:
|
||||
static void register_vec2(sol::table& omath_table);
|
||||
static void register_vec3(sol::table& omath_table);
|
||||
static void register_vec4(sol::table& omath_table);
|
||||
static void register_color(sol::table& omath_table);
|
||||
static void register_triangle(sol::table& omath_table);
|
||||
static void register_shared_types(sol::table& omath_table);
|
||||
static void register_engines(sol::table& omath_table);
|
||||
static void register_pattern_scan(sol::table& omath_table);
|
||||
};
|
||||
}
|
||||
#endif
|
||||
@@ -17,6 +17,9 @@
|
||||
// Matrix classes
|
||||
#include "omath/linear_algebra/mat.hpp"
|
||||
|
||||
// Quaternion
|
||||
#include "omath/linear_algebra/quaternion.hpp"
|
||||
|
||||
// Color functionality
|
||||
#include "omath/utility/color.hpp"
|
||||
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
|
||||
#include "omath/linear_algebra/vector3.hpp"
|
||||
#include <expected>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace omath::pathfinding
|
||||
@@ -28,10 +30,20 @@ namespace omath::pathfinding
|
||||
[[nodiscard]]
|
||||
bool empty() const;
|
||||
|
||||
[[nodiscard]] std::vector<uint8_t> serialize() const noexcept;
|
||||
// Events -- per-vertex optional tag (e.g. "jump", "teleport")
|
||||
void set_event(const Vector3<float>& vertex, const std::string_view& event_id);
|
||||
void clear_event(const Vector3<float>& vertex);
|
||||
|
||||
void deserialize(const std::vector<uint8_t>& raw) noexcept;
|
||||
[[nodiscard]]
|
||||
std::optional<std::string> get_event(const Vector3<float>& vertex) const noexcept;
|
||||
|
||||
[[nodiscard]] std::string serialize() const noexcept;
|
||||
|
||||
void deserialize(const std::string& raw);
|
||||
|
||||
std::unordered_map<Vector3<float>, std::vector<Vector3<float>>> m_vertex_map;
|
||||
|
||||
private:
|
||||
std::unordered_map<Vector3<float>, std::string> m_vertex_events;
|
||||
};
|
||||
} // namespace omath::pathfinding
|
||||
|
||||
@@ -16,19 +16,28 @@ namespace omath
|
||||
float value{};
|
||||
};
|
||||
|
||||
class Color final : public Vector4<float>
|
||||
class Color final
|
||||
{
|
||||
Vector4<float> m_value;
|
||||
public:
|
||||
constexpr Color(const float r, const float g, const float b, const float a) noexcept: Vector4(r, g, b, a)
|
||||
constexpr const Vector4<float>& value() const
|
||||
{
|
||||
clamp(0.f, 1.f);
|
||||
return m_value;
|
||||
}
|
||||
constexpr Color(const float r, const float g, const float b, const float a) noexcept: m_value(r, g, b, a)
|
||||
{
|
||||
m_value.clamp(0.f, 1.f);
|
||||
}
|
||||
|
||||
constexpr explicit Color(const Vector4<float>& value) : m_value(value)
|
||||
{
|
||||
m_value.clamp(0.f, 1.f);
|
||||
}
|
||||
constexpr explicit Color() noexcept = default;
|
||||
[[nodiscard]]
|
||||
constexpr static Color from_rgba(const uint8_t r, const uint8_t g, const uint8_t b, const uint8_t a) noexcept
|
||||
{
|
||||
return Color{Vector4(r, g, b, a) / 255.f};
|
||||
return Color(Vector4<float>(r, g, b, a) / 255.f);
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
@@ -82,9 +91,9 @@ namespace omath
|
||||
{
|
||||
Hsv hsv_data;
|
||||
|
||||
const float& red = x;
|
||||
const float& green = y;
|
||||
const float& blue = z;
|
||||
const float& red = m_value.x;
|
||||
const float& green = m_value.y;
|
||||
const float& blue = m_value.z;
|
||||
|
||||
const float max = std::max({red, green, blue});
|
||||
const float min = std::min({red, green, blue});
|
||||
@@ -109,11 +118,6 @@ namespace omath
|
||||
|
||||
return hsv_data;
|
||||
}
|
||||
|
||||
constexpr explicit Color(const Vector4& vec) noexcept: Vector4(vec)
|
||||
{
|
||||
clamp(0.f, 1.f);
|
||||
}
|
||||
constexpr void set_hue(const float hue) noexcept
|
||||
{
|
||||
auto hsv = to_hsv();
|
||||
@@ -141,7 +145,7 @@ namespace omath
|
||||
constexpr Color blend(const Color& other, float ratio) const noexcept
|
||||
{
|
||||
ratio = std::clamp(ratio, 0.f, 1.f);
|
||||
return Color(*this * (1.f - ratio) + other * ratio);
|
||||
return Color(this->m_value * (1.f - ratio) + other.m_value * ratio);
|
||||
}
|
||||
|
||||
[[nodiscard]] static constexpr Color red()
|
||||
@@ -160,16 +164,26 @@ namespace omath
|
||||
[[nodiscard]]
|
||||
ImColor to_im_color() const noexcept
|
||||
{
|
||||
return {to_im_vec4()};
|
||||
return {m_value.to_im_vec4()};
|
||||
}
|
||||
#endif
|
||||
[[nodiscard]] std::string to_string() const noexcept
|
||||
{
|
||||
return std::format("[r:{}, g:{}, b:{}, a:{}]",
|
||||
static_cast<int>(x * 255.f),
|
||||
static_cast<int>(y * 255.f),
|
||||
static_cast<int>(z * 255.f),
|
||||
static_cast<int>(w * 255.f));
|
||||
static_cast<int>(m_value.x * 255.f),
|
||||
static_cast<int>(m_value.y * 255.f),
|
||||
static_cast<int>(m_value.z * 255.f),
|
||||
static_cast<int>(m_value.w * 255.f));
|
||||
}
|
||||
[[nodiscard]] std::string to_rgbf_string() const noexcept
|
||||
{
|
||||
return std::format("[r:{}, g:{}, b:{}, a:{}]",
|
||||
m_value.x, m_value.y, m_value.z, m_value.w);
|
||||
}
|
||||
[[nodiscard]] std::string to_hsv_string() const noexcept
|
||||
{
|
||||
const auto [hue, saturation, value] = to_hsv();
|
||||
return std::format("[h:{}, s:{}, v:{}]", hue, saturation, value);
|
||||
}
|
||||
[[nodiscard]] std::wstring to_wstring() const noexcept
|
||||
{
|
||||
@@ -188,23 +202,55 @@ namespace omath
|
||||
template<>
|
||||
struct std::formatter<omath::Color> // NOLINT(*-dcl58-cpp)
|
||||
{
|
||||
[[nodiscard]]
|
||||
static constexpr auto parse(const std::format_parse_context& ctx)
|
||||
enum class ColorFormat { rgb, rgbf, hsv };
|
||||
ColorFormat color_format = ColorFormat::rgb;
|
||||
|
||||
constexpr auto parse(std::format_parse_context& ctx)
|
||||
{
|
||||
return ctx.begin();
|
||||
const auto it = ctx.begin();
|
||||
const auto end = ctx.end();
|
||||
|
||||
if (it == end || *it == '}')
|
||||
return it;
|
||||
|
||||
const std::string_view spec(it, end);
|
||||
|
||||
if (spec.starts_with("rgbf"))
|
||||
{
|
||||
color_format = ColorFormat::rgbf;
|
||||
return it + 4;
|
||||
}
|
||||
if (spec.starts_with("rgb"))
|
||||
{
|
||||
color_format = ColorFormat::rgb;
|
||||
return it + 3;
|
||||
}
|
||||
if (spec.starts_with("hsv"))
|
||||
{
|
||||
color_format = ColorFormat::hsv;
|
||||
return it + 3;
|
||||
}
|
||||
|
||||
throw std::format_error("Invalid format specifier for omath::Color. Use rgb, rgbf, or hsv.");
|
||||
}
|
||||
|
||||
template<class FormatContext>
|
||||
[[nodiscard]]
|
||||
static auto format(const omath::Color& col, FormatContext& ctx)
|
||||
auto format(const omath::Color& col, FormatContext& ctx) const
|
||||
{
|
||||
if constexpr (std::is_same_v<typename FormatContext::char_type, char>)
|
||||
return std::format_to(ctx.out(), "{}", col.to_string());
|
||||
if constexpr (std::is_same_v<typename FormatContext::char_type, wchar_t>)
|
||||
return std::format_to(ctx.out(), L"{}", col.to_wstring());
|
||||
std::string str;
|
||||
switch (color_format)
|
||||
{
|
||||
case ColorFormat::rgb: str = col.to_string(); break;
|
||||
case ColorFormat::rgbf: str = col.to_rgbf_string(); break;
|
||||
case ColorFormat::hsv: str = col.to_hsv_string(); break;
|
||||
}
|
||||
|
||||
if constexpr (std::is_same_v<typename FormatContext::char_type, char>)
|
||||
return std::format_to(ctx.out(), "{}", str);
|
||||
if constexpr (std::is_same_v<typename FormatContext::char_type, wchar_t>)
|
||||
return std::format_to(ctx.out(), L"{}", std::wstring(str.cbegin(), str.cend()));
|
||||
if constexpr (std::is_same_v<typename FormatContext::char_type, char8_t>)
|
||||
return std::format_to(ctx.out(), u8"{}", col.to_u8string());
|
||||
return std::format_to(ctx.out(), u8"{}", std::u8string(str.cbegin(), str.cend()));
|
||||
|
||||
std::unreachable();
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
#include "section_scan_result.hpp"
|
||||
namespace omath
|
||||
@@ -21,5 +22,10 @@ namespace omath
|
||||
static std::optional<SectionScanResult>
|
||||
scan_for_pattern_in_file(const std::filesystem::path& path_to_file, const std::string_view& pattern,
|
||||
const std::string_view& target_section_name = ".text");
|
||||
|
||||
[[nodiscard]]
|
||||
static std::optional<SectionScanResult>
|
||||
scan_for_pattern_in_memory_file(std::span<const std::byte> file_data, const std::string_view& pattern,
|
||||
const std::string_view& target_section_name = ".text");
|
||||
};
|
||||
} // namespace omath
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
#include "section_scan_result.hpp"
|
||||
namespace omath
|
||||
@@ -21,5 +22,10 @@ namespace omath
|
||||
static std::optional<SectionScanResult>
|
||||
scan_for_pattern_in_file(const std::filesystem::path& path_to_file, const std::string_view& pattern,
|
||||
const std::string_view& target_section_name = "__text");
|
||||
|
||||
[[nodiscard]]
|
||||
static std::optional<SectionScanResult>
|
||||
scan_for_pattern_in_memory_file(std::span<const std::byte> file_data, const std::string_view& pattern,
|
||||
const std::string_view& target_section_name = "__text");
|
||||
};
|
||||
} // namespace omath
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
#include "section_scan_result.hpp"
|
||||
namespace omath
|
||||
@@ -23,5 +24,10 @@ namespace omath
|
||||
static std::optional<SectionScanResult>
|
||||
scan_for_pattern_in_file(const std::filesystem::path& path_to_file, const std::string_view& pattern,
|
||||
const std::string_view& target_section_name = ".text");
|
||||
|
||||
[[nodiscard]]
|
||||
static std::optional<SectionScanResult>
|
||||
scan_for_pattern_in_memory_file(std::span<const std::byte> file_data, const std::string_view& pattern,
|
||||
const std::string_view& target_section_name = ".text");
|
||||
};
|
||||
} // namespace omath
|
||||
27
source/hud/canvas_box.cpp
Normal file
27
source/hud/canvas_box.cpp
Normal file
@@ -0,0 +1,27 @@
|
||||
//
|
||||
// Created by orange on 13.03.2026.
|
||||
//
|
||||
//
|
||||
// Created by Vlad on 6/17/2025.
|
||||
//
|
||||
#include "omath/hud/canvas_box.hpp"
|
||||
|
||||
namespace omath::hud
|
||||
{
|
||||
|
||||
CanvasBox::CanvasBox(const Vector2<float> top, Vector2<float> bottom, const float ratio)
|
||||
{
|
||||
bottom.x = top.x;
|
||||
const auto height = std::abs(top.y - bottom.y);
|
||||
|
||||
top_left_corner = top - Vector2<float>{height / ratio, 0};
|
||||
top_right_corner = top + Vector2<float>{height / ratio, 0};
|
||||
|
||||
bottom_left_corner = bottom - Vector2<float>{height / ratio, 0};
|
||||
bottom_right_corner = bottom + Vector2<float>{height / ratio, 0};
|
||||
}
|
||||
std::array<Vector2<float>, 4> CanvasBox::as_array() const
|
||||
{
|
||||
return {top_left_corner, top_right_corner, bottom_right_corner, bottom_left_corner};
|
||||
}
|
||||
} // namespace ohud
|
||||
845
source/hud/entity_overlay.cpp
Normal file
845
source/hud/entity_overlay.cpp
Normal file
@@ -0,0 +1,845 @@
|
||||
//
|
||||
// Created by orange on 13.03.2026.
|
||||
//
|
||||
#include "omath/hud/entity_overlay.hpp"
|
||||
|
||||
namespace omath::hud
|
||||
{
|
||||
EntityOverlay& EntityOverlay::add_2d_box(const Color& box_color, const Color& fill_color, const float thickness)
|
||||
{
|
||||
const auto points = m_canvas.as_array();
|
||||
|
||||
m_renderer->add_polyline({points.data(), points.size()}, box_color, thickness);
|
||||
|
||||
if (fill_color.value().w > 0.f)
|
||||
m_renderer->add_filled_polyline({points.data(), points.size()}, fill_color);
|
||||
|
||||
return *this;
|
||||
}
|
||||
EntityOverlay& EntityOverlay::add_cornered_2d_box(const Color& box_color, const Color& fill_color,
|
||||
const float corner_ratio_len, const float thickness)
|
||||
{
|
||||
const auto corner_line_length =
|
||||
std::abs((m_canvas.top_left_corner - m_canvas.top_right_corner).x * corner_ratio_len);
|
||||
|
||||
if (fill_color.value().w > 0.f)
|
||||
add_2d_box(fill_color, fill_color);
|
||||
// Left Side
|
||||
m_renderer->add_line(m_canvas.top_left_corner,
|
||||
m_canvas.top_left_corner + Vector2<float>{corner_line_length, 0.f}, box_color, thickness);
|
||||
|
||||
m_renderer->add_line(m_canvas.top_left_corner,
|
||||
m_canvas.top_left_corner + Vector2<float>{0.f, corner_line_length}, box_color, thickness);
|
||||
|
||||
m_renderer->add_line(m_canvas.bottom_left_corner,
|
||||
m_canvas.bottom_left_corner - Vector2<float>{0.f, corner_line_length}, box_color,
|
||||
thickness);
|
||||
|
||||
m_renderer->add_line(m_canvas.bottom_left_corner,
|
||||
m_canvas.bottom_left_corner + Vector2<float>{corner_line_length, 0.f}, box_color,
|
||||
thickness);
|
||||
// Right Side
|
||||
m_renderer->add_line(m_canvas.top_right_corner,
|
||||
m_canvas.top_right_corner - Vector2<float>{corner_line_length, 0.f}, box_color, thickness);
|
||||
|
||||
m_renderer->add_line(m_canvas.top_right_corner,
|
||||
m_canvas.top_right_corner + Vector2<float>{0.f, corner_line_length}, box_color, thickness);
|
||||
|
||||
m_renderer->add_line(m_canvas.bottom_right_corner,
|
||||
m_canvas.bottom_right_corner - Vector2<float>{0.f, corner_line_length}, box_color,
|
||||
thickness);
|
||||
|
||||
m_renderer->add_line(m_canvas.bottom_right_corner,
|
||||
m_canvas.bottom_right_corner - Vector2<float>{corner_line_length, 0.f}, box_color,
|
||||
thickness);
|
||||
|
||||
return *this;
|
||||
}
|
||||
EntityOverlay& EntityOverlay::add_right_bar(const Color& color, const Color& outline_color, const Color& bg_color,
|
||||
const float width, float ratio, const float offset)
|
||||
{
|
||||
ratio = std::clamp(ratio, 0.f, 1.f);
|
||||
const auto max_bar_height = std::abs(m_canvas.top_right_corner.y - m_canvas.bottom_right_corner.y);
|
||||
|
||||
const auto bar_start = Vector2<float>{m_text_cursor_right.x + offset, m_canvas.bottom_right_corner.y};
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>(width, -max_bar_height), bg_color);
|
||||
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>(width, -max_bar_height * ratio), color);
|
||||
m_renderer->add_rectangle(bar_start - Vector2<float>(1.f, 0.f),
|
||||
bar_start + Vector2<float>(width, -max_bar_height), outline_color);
|
||||
|
||||
m_text_cursor_right.x += offset + width;
|
||||
|
||||
return *this;
|
||||
}
|
||||
EntityOverlay& EntityOverlay::add_left_bar(const Color& color, const Color& outline_color, const Color& bg_color,
|
||||
const float width, float ratio, const float offset)
|
||||
{
|
||||
ratio = std::clamp(ratio, 0.f, 1.f);
|
||||
const auto max_bar_height = std::abs(m_canvas.top_left_corner.y - m_canvas.bottom_right_corner.y);
|
||||
|
||||
const auto bar_start = Vector2<float>{m_text_cursor_left.x - (offset + width), m_canvas.bottom_left_corner.y};
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>(width, -max_bar_height), bg_color);
|
||||
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>(width, -max_bar_height * ratio), color);
|
||||
m_renderer->add_rectangle(bar_start - Vector2<float>(1.f, 0.f),
|
||||
bar_start + Vector2<float>(width, -max_bar_height), outline_color);
|
||||
|
||||
m_text_cursor_left.x -= offset + width;
|
||||
|
||||
return *this;
|
||||
}
|
||||
EntityOverlay& EntityOverlay::add_right_label(const Color& color, const float offset, const bool outlined,
|
||||
const std::string_view& text)
|
||||
{
|
||||
if (outlined)
|
||||
draw_outlined_text(m_text_cursor_right + Vector2<float>{offset, 0.f}, color, text);
|
||||
else
|
||||
m_renderer->add_text(m_text_cursor_right + Vector2<float>{offset, 0.f}, color, text.data());
|
||||
|
||||
m_text_cursor_right.y += m_renderer->calc_text_size(text.data()).y;
|
||||
|
||||
return *this;
|
||||
}
|
||||
EntityOverlay& EntityOverlay::add_top_label(const Color& color, const float offset, const bool outlined,
|
||||
const std::string_view text)
|
||||
{
|
||||
m_text_cursor_top.y -= m_renderer->calc_text_size(text.data()).y;
|
||||
|
||||
if (outlined)
|
||||
draw_outlined_text(m_text_cursor_top + Vector2<float>{0.f, -offset}, color, text);
|
||||
else
|
||||
m_renderer->add_text(m_text_cursor_top + Vector2<float>{0.f, -offset}, color, text.data());
|
||||
|
||||
return *this;
|
||||
}
|
||||
EntityOverlay& EntityOverlay::add_top_bar(const Color& color, const Color& outline_color, const Color& bg_color,
|
||||
const float height, float ratio, const float offset)
|
||||
{
|
||||
ratio = std::clamp(ratio, 0.f, 1.f);
|
||||
const auto max_bar_width = std::abs(m_canvas.top_left_corner.x - m_canvas.bottom_right_corner.x);
|
||||
|
||||
const auto bar_start = Vector2<float>{m_canvas.top_left_corner.x, m_text_cursor_top.y - offset};
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>(max_bar_width, -height), bg_color);
|
||||
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>(max_bar_width * ratio, -height), color);
|
||||
m_renderer->add_rectangle(bar_start, bar_start + Vector2<float>(max_bar_width, -height), outline_color);
|
||||
|
||||
m_text_cursor_top.y -= offset + height;
|
||||
|
||||
return *this;
|
||||
}
|
||||
EntityOverlay& EntityOverlay::add_snap_line(const Vector2<float>& start_pos, const Color& color, const float width)
|
||||
{
|
||||
const Vector2<float> line_end =
|
||||
m_canvas.bottom_left_corner
|
||||
+ Vector2<float>{m_canvas.bottom_right_corner.x - m_canvas.bottom_left_corner.x, 0.f} / 2;
|
||||
m_renderer->add_line(start_pos, line_end, color, width);
|
||||
|
||||
return *this;
|
||||
}
|
||||
void EntityOverlay::draw_dashed_fill(const Vector2<float>& origin, const Vector2<float>& step_dir,
|
||||
const Vector2<float>& perp_dir, const float full_len, const float filled_len,
|
||||
const Color& fill_color, const Color& split_color, const float dash_len,
|
||||
const float gap_len) const
|
||||
{
|
||||
if (full_len <= 0.f)
|
||||
return;
|
||||
|
||||
const float step = dash_len + gap_len;
|
||||
const float n = std::floor((full_len + gap_len) / step);
|
||||
if (n < 1.f)
|
||||
return;
|
||||
|
||||
const float used = n * dash_len + (n - 1.f) * gap_len;
|
||||
const float offset = (full_len - used) / 2.f;
|
||||
|
||||
const auto fill_rect = [&](const Vector2<float>& a, const Vector2<float>& b, const Color& c)
|
||||
{
|
||||
m_renderer->add_filled_rectangle({std::min(a.x, b.x), std::min(a.y, b.y)},
|
||||
{std::max(a.x, b.x), std::max(a.y, b.y)}, c);
|
||||
};
|
||||
|
||||
// Draw split lines (gaps) across the full bar first
|
||||
// Leading gap
|
||||
if (offset > 0.f)
|
||||
fill_rect(origin, origin + step_dir * offset + perp_dir, split_color);
|
||||
|
||||
for (float i = 0.f; i < n; ++i)
|
||||
{
|
||||
const float dash_start = offset + i * step;
|
||||
const float dash_end = dash_start + dash_len;
|
||||
const float gap_start = dash_end;
|
||||
const float gap_end = dash_start + step;
|
||||
|
||||
// Fill dash only up to filled_len
|
||||
if (dash_start < filled_len)
|
||||
{
|
||||
const auto a = origin + step_dir * dash_start;
|
||||
const auto b = a + step_dir * std::min(dash_len, filled_len - dash_start) + perp_dir;
|
||||
fill_rect(a, b, fill_color);
|
||||
}
|
||||
|
||||
// Split line (gap) — always drawn across full bar
|
||||
if (i < n - 1.f && gap_start < full_len)
|
||||
{
|
||||
const auto a = origin + step_dir * gap_start;
|
||||
const auto b = origin + step_dir * std::min(gap_end, full_len) + perp_dir;
|
||||
fill_rect(a, b, split_color);
|
||||
}
|
||||
}
|
||||
|
||||
// Trailing gap
|
||||
const float trail_start = offset + n * dash_len + (n - 1.f) * gap_len;
|
||||
if (trail_start < full_len)
|
||||
fill_rect(origin + step_dir * trail_start, origin + step_dir * full_len + perp_dir, split_color);
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_right_dashed_bar(const Color& color, const Color& outline_color,
|
||||
const Color& bg_color, const float width, float ratio,
|
||||
const float dash_len, const float gap_len, const float offset)
|
||||
{
|
||||
ratio = std::clamp(ratio, 0.f, 1.f);
|
||||
const float height = std::abs(m_canvas.top_right_corner.y - m_canvas.bottom_right_corner.y);
|
||||
const auto bar_start = Vector2<float>{m_text_cursor_right.x + offset, m_canvas.bottom_right_corner.y};
|
||||
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>{width, -height}, bg_color);
|
||||
draw_dashed_fill(bar_start, {0.f, -1.f}, {width, 0.f}, height, height * ratio, color, outline_color, dash_len,
|
||||
gap_len);
|
||||
m_renderer->add_rectangle(bar_start - Vector2<float>{1.f, 0.f}, bar_start + Vector2<float>{width, -height},
|
||||
outline_color);
|
||||
m_text_cursor_right.x += offset + width;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_left_dashed_bar(const Color& color, const Color& outline_color,
|
||||
const Color& bg_color, const float width, float ratio,
|
||||
const float dash_len, const float gap_len, const float offset)
|
||||
{
|
||||
ratio = std::clamp(ratio, 0.f, 1.f);
|
||||
const float height = std::abs(m_canvas.top_left_corner.y - m_canvas.bottom_left_corner.y);
|
||||
const auto bar_start = Vector2<float>{m_text_cursor_left.x - (offset + width), m_canvas.bottom_left_corner.y};
|
||||
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>{width, -height}, bg_color);
|
||||
draw_dashed_fill(bar_start, {0.f, -1.f}, {width, 0.f}, height, height * ratio, color, outline_color, dash_len,
|
||||
gap_len);
|
||||
m_renderer->add_rectangle(bar_start - Vector2<float>{1.f, 0.f}, bar_start + Vector2<float>{width, -height},
|
||||
outline_color);
|
||||
m_text_cursor_left.x -= offset + width;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_top_dashed_bar(const Color& color, const Color& outline_color,
|
||||
const Color& bg_color, const float height, float ratio,
|
||||
const float dash_len, const float gap_len, const float offset)
|
||||
{
|
||||
ratio = std::clamp(ratio, 0.f, 1.f);
|
||||
const float bar_w = std::abs(m_canvas.top_left_corner.x - m_canvas.top_right_corner.x);
|
||||
const auto bar_start = Vector2<float>{m_canvas.top_left_corner.x, m_text_cursor_top.y - offset};
|
||||
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>{bar_w, -height}, bg_color);
|
||||
draw_dashed_fill(bar_start, {1.f, 0.f}, {0.f, -height}, bar_w, bar_w * ratio, color, outline_color, dash_len,
|
||||
gap_len);
|
||||
m_renderer->add_rectangle(bar_start, bar_start + Vector2<float>{bar_w, -height}, outline_color);
|
||||
m_text_cursor_top.y -= offset + height;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_bottom_dashed_bar(const Color& color, const Color& outline_color,
|
||||
const Color& bg_color, const float height, float ratio,
|
||||
const float dash_len, const float gap_len, const float offset)
|
||||
{
|
||||
ratio = std::clamp(ratio, 0.f, 1.f);
|
||||
const float bar_w = std::abs(m_canvas.bottom_left_corner.x - m_canvas.bottom_right_corner.x);
|
||||
const auto bar_start = Vector2<float>{m_canvas.bottom_left_corner.x, m_text_cursor_bottom.y + offset};
|
||||
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>{bar_w, height}, bg_color);
|
||||
draw_dashed_fill(bar_start, {1.f, 0.f}, {0.f, height}, bar_w, bar_w * ratio, color, outline_color, dash_len,
|
||||
gap_len);
|
||||
m_renderer->add_rectangle(bar_start, bar_start + Vector2<float>{bar_w, height}, outline_color);
|
||||
m_text_cursor_bottom.y += offset + height;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_skeleton(const Color& color, const float thickness)
|
||||
{
|
||||
// Maps normalized (rx in [0,1], ry in [0,1]) to canvas screen position
|
||||
const auto joint = [&](const float rx, const float ry) -> Vector2<float>
|
||||
{
|
||||
const auto top = m_canvas.top_left_corner + (m_canvas.top_right_corner - m_canvas.top_left_corner) * rx;
|
||||
const auto bot =
|
||||
m_canvas.bottom_left_corner + (m_canvas.bottom_right_corner - m_canvas.bottom_left_corner) * rx;
|
||||
return top + (bot - top) * ry;
|
||||
};
|
||||
|
||||
using B = std::pair<std::pair<float, float>, std::pair<float, float>>;
|
||||
static constexpr std::array<B, 15> k_bones{{
|
||||
// Spine
|
||||
{{0.50f, 0.13f}, {0.50f, 0.22f}}, // head → neck
|
||||
{{0.50f, 0.22f}, {0.50f, 0.38f}}, // neck → chest
|
||||
{{0.50f, 0.38f}, {0.50f, 0.55f}}, // chest → pelvis
|
||||
// Left arm
|
||||
{{0.50f, 0.22f}, {0.25f, 0.25f}}, // neck → L shoulder
|
||||
{{0.25f, 0.25f}, {0.13f, 0.42f}}, // L shoulder → L elbow
|
||||
{{0.13f, 0.42f}, {0.08f, 0.56f}}, // L elbow → L hand
|
||||
// Right arm
|
||||
{{0.50f, 0.22f}, {0.75f, 0.25f}}, // neck → R shoulder
|
||||
{{0.75f, 0.25f}, {0.87f, 0.42f}}, // R shoulder → R elbow
|
||||
{{0.87f, 0.42f}, {0.92f, 0.56f}}, // R elbow → R hand
|
||||
// Left leg
|
||||
{{0.50f, 0.55f}, {0.36f, 0.58f}}, // pelvis → L hip
|
||||
{{0.36f, 0.58f}, {0.32f, 0.77f}}, // L hip → L knee
|
||||
{{0.32f, 0.77f}, {0.27f, 0.97f}}, // L knee → L foot
|
||||
// Right leg
|
||||
{{0.50f, 0.55f}, {0.64f, 0.58f}}, // pelvis → R hip
|
||||
{{0.64f, 0.58f}, {0.68f, 0.77f}}, // R hip → R knee
|
||||
{{0.68f, 0.77f}, {0.73f, 0.97f}}, // R knee → R foot
|
||||
}};
|
||||
|
||||
for (const auto& [a, b] : k_bones)
|
||||
m_renderer->add_line(joint(a.first, a.second), joint(b.first, b.second), color, thickness);
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
void EntityOverlay::draw_dashed_line(const Vector2<float>& from, const Vector2<float>& to, const Color& color,
|
||||
const float dash_len, const float gap_len, const float thickness) const
|
||||
{
|
||||
const auto total = (to - from).length();
|
||||
if (total <= 0.f)
|
||||
return;
|
||||
|
||||
const auto dir = (to - from).normalized();
|
||||
const float step = dash_len + gap_len;
|
||||
|
||||
const float n_dashes = std::floor((total + gap_len) / step);
|
||||
if (n_dashes < 1.f)
|
||||
return;
|
||||
|
||||
const float used = n_dashes * dash_len + (n_dashes - 1.f) * gap_len;
|
||||
const float offset = (total - used) / 2.f;
|
||||
|
||||
for (float i = 0.f; i < n_dashes; ++i)
|
||||
{
|
||||
const float pos = offset + i * step;
|
||||
const auto dash_start = from + dir * pos;
|
||||
const auto dash_end = from + dir * std::min(pos + dash_len, total);
|
||||
m_renderer->add_line(dash_start, dash_end, color, thickness);
|
||||
}
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_dashed_box(const Color& color, const float dash_len, const float gap_len,
|
||||
const float thickness)
|
||||
{
|
||||
const float min_edge = std::min((m_canvas.top_right_corner - m_canvas.top_left_corner).length(),
|
||||
(m_canvas.bottom_right_corner - m_canvas.top_right_corner).length());
|
||||
const float corner_len = std::min(dash_len, min_edge / 2.f);
|
||||
|
||||
const auto draw_edge = [&](const Vector2<float>& from, const Vector2<float>& to)
|
||||
{
|
||||
const auto dir = (to - from).normalized();
|
||||
|
||||
m_renderer->add_line(from, from + dir * corner_len, color, thickness);
|
||||
draw_dashed_line(from + dir * corner_len, to - dir * corner_len, color, dash_len, gap_len, thickness);
|
||||
m_renderer->add_line(to - dir * corner_len, to, color, thickness);
|
||||
};
|
||||
|
||||
draw_edge(m_canvas.top_left_corner, m_canvas.top_right_corner);
|
||||
draw_edge(m_canvas.top_right_corner, m_canvas.bottom_right_corner);
|
||||
draw_edge(m_canvas.bottom_right_corner, m_canvas.bottom_left_corner);
|
||||
draw_edge(m_canvas.bottom_left_corner, m_canvas.top_left_corner);
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
void EntityOverlay::draw_outlined_text(const Vector2<float>& position, const Color& color,
|
||||
const std::string_view& text)
|
||||
{
|
||||
static constexpr std::array outline_offsets = {
|
||||
Vector2<float>{-1, -1}, Vector2<float>{-1, 0}, Vector2<float>{-1, 1}, Vector2<float>{0, -1},
|
||||
Vector2<float>{0, 1}, Vector2<float>{1, -1}, Vector2<float>{1, 0}, Vector2<float>{1, 1}};
|
||||
|
||||
for (const auto& outline_offset : outline_offsets)
|
||||
m_renderer->add_text(position + outline_offset, Color{0.f, 0.f, 0.f, 1.f}, text.data());
|
||||
m_renderer->add_text(position, color, text.data());
|
||||
}
|
||||
EntityOverlay& EntityOverlay::add_bottom_bar(const Color& color, const Color& outline_color, const Color& bg_color,
|
||||
const float height, float ratio, const float offset)
|
||||
{
|
||||
ratio = std::clamp(ratio, 0.f, 1.f);
|
||||
const auto max_bar_width = std::abs(m_canvas.bottom_right_corner.x - m_canvas.bottom_left_corner.x);
|
||||
|
||||
const auto bar_start = Vector2<float>{m_canvas.bottom_left_corner.x, m_text_cursor_bottom.y + offset};
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>(max_bar_width, height), bg_color);
|
||||
m_renderer->add_filled_rectangle(bar_start, bar_start + Vector2<float>(max_bar_width * ratio, height), color);
|
||||
m_renderer->add_rectangle(bar_start, bar_start + Vector2<float>(max_bar_width, height), outline_color);
|
||||
|
||||
m_text_cursor_bottom.y += offset + height;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_bottom_label(const Color& color, const float offset, const bool outlined,
|
||||
const std::string_view text)
|
||||
{
|
||||
const auto text_size = m_renderer->calc_text_size(text);
|
||||
|
||||
if (outlined)
|
||||
draw_outlined_text(m_text_cursor_bottom + Vector2<float>{0.f, offset}, color, text);
|
||||
else
|
||||
m_renderer->add_text(m_text_cursor_bottom + Vector2<float>{0.f, offset}, color, text);
|
||||
|
||||
m_text_cursor_bottom.y += text_size.y;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_left_label(const Color& color, const float offset, const bool outlined,
|
||||
const std::string_view& text)
|
||||
{
|
||||
const auto text_size = m_renderer->calc_text_size(text);
|
||||
const auto pos = m_text_cursor_left + Vector2<float>{-(offset + text_size.x), 0.f};
|
||||
|
||||
if (outlined)
|
||||
draw_outlined_text(pos, color, text);
|
||||
else
|
||||
m_renderer->add_text(pos, color, text);
|
||||
|
||||
m_text_cursor_left.y += text_size.y;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_centered_bottom_label(const Color& color, const float offset, const bool outlined,
|
||||
const std::string_view& text)
|
||||
{
|
||||
const auto text_size = m_renderer->calc_text_size(text);
|
||||
const auto box_center_x =
|
||||
m_canvas.bottom_left_corner.x + (m_canvas.bottom_right_corner.x - m_canvas.bottom_left_corner.x) / 2.f;
|
||||
const auto pos = Vector2<float>{box_center_x - text_size.x / 2.f, m_text_cursor_bottom.y + offset};
|
||||
|
||||
if (outlined)
|
||||
draw_outlined_text(pos, color, text);
|
||||
else
|
||||
m_renderer->add_text(pos, color, text);
|
||||
|
||||
m_text_cursor_bottom.y += text_size.y;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_centered_top_label(const Color& color, const float offset, const bool outlined,
|
||||
const std::string_view& text)
|
||||
{
|
||||
const auto text_size = m_renderer->calc_text_size(text);
|
||||
const auto box_center_x =
|
||||
m_canvas.top_left_corner.x + (m_canvas.top_right_corner.x - m_canvas.top_left_corner.x) / 2.f;
|
||||
|
||||
m_text_cursor_top.y -= text_size.y;
|
||||
const auto pos = Vector2<float>{box_center_x - text_size.x / 2.f, m_text_cursor_top.y - offset};
|
||||
|
||||
if (outlined)
|
||||
draw_outlined_text(pos, color, text);
|
||||
else
|
||||
m_renderer->add_text(pos, color, text);
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay::EntityOverlay(const Vector2<float>& top, const Vector2<float>& bottom,
|
||||
const std::shared_ptr<HudRendererInterface>& renderer)
|
||||
: m_canvas(top, bottom), m_text_cursor_right(m_canvas.top_right_corner),
|
||||
m_text_cursor_top(m_canvas.top_left_corner), m_text_cursor_bottom(m_canvas.bottom_left_corner),
|
||||
m_text_cursor_left(m_canvas.top_left_corner), m_renderer(renderer)
|
||||
{
|
||||
}
|
||||
// ── Spacers ─────────────────────────────────────────────────────────────────
|
||||
EntityOverlay& EntityOverlay::add_right_space_vertical(const float size)
|
||||
{
|
||||
m_text_cursor_right.y += size;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_right_space_horizontal(const float size)
|
||||
{
|
||||
m_text_cursor_right.x += size;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_left_space_vertical(const float size)
|
||||
{
|
||||
m_text_cursor_left.y += size;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_left_space_horizontal(const float size)
|
||||
{
|
||||
m_text_cursor_left.x -= size;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_top_space_vertical(const float size)
|
||||
{
|
||||
m_text_cursor_top.y -= size;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_top_space_horizontal(const float size)
|
||||
{
|
||||
m_text_cursor_top.x += size;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_bottom_space_vertical(const float size)
|
||||
{
|
||||
m_text_cursor_bottom.y += size;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_bottom_space_horizontal(const float size)
|
||||
{
|
||||
m_text_cursor_bottom.x += size;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// ── Progress rings ──────────────────────────────────────────────────────────
|
||||
EntityOverlay& EntityOverlay::add_right_progress_ring(const Color& color, const Color& bg, const float radius,
|
||||
const float ratio, const float thickness, const float offset,
|
||||
const int segments)
|
||||
{
|
||||
const auto cx = m_text_cursor_right.x + offset + radius;
|
||||
const auto cy = m_text_cursor_right.y + radius;
|
||||
draw_progress_ring({cx, cy}, widget::ProgressRing{color, bg, radius, ratio, thickness, offset, segments});
|
||||
m_text_cursor_right.y += radius * 2.f;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_left_progress_ring(const Color& color, const Color& bg, const float radius,
|
||||
const float ratio, const float thickness, const float offset,
|
||||
const int segments)
|
||||
{
|
||||
const auto cx = m_text_cursor_left.x - offset - radius;
|
||||
const auto cy = m_text_cursor_left.y + radius;
|
||||
draw_progress_ring({cx, cy}, widget::ProgressRing{color, bg, radius, ratio, thickness, offset, segments});
|
||||
m_text_cursor_left.y += radius * 2.f;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_top_progress_ring(const Color& color, const Color& bg, const float radius,
|
||||
const float ratio, const float thickness, const float offset,
|
||||
const int segments)
|
||||
{
|
||||
m_text_cursor_top.y -= radius * 2.f;
|
||||
const auto cx = m_text_cursor_top.x + radius;
|
||||
const auto cy = m_text_cursor_top.y - offset + radius;
|
||||
draw_progress_ring({cx, cy}, widget::ProgressRing{color, bg, radius, ratio, thickness, offset, segments});
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_bottom_progress_ring(const Color& color, const Color& bg, const float radius,
|
||||
const float ratio, const float thickness, const float offset,
|
||||
const int segments)
|
||||
{
|
||||
const auto cx = m_text_cursor_bottom.x + radius;
|
||||
const auto cy = m_text_cursor_bottom.y + offset + radius;
|
||||
draw_progress_ring({cx, cy}, widget::ProgressRing{color, bg, radius, ratio, thickness, offset, segments});
|
||||
m_text_cursor_bottom.y += radius * 2.f;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// ── Icons ────────────────────────────────────────────────────────────────────
|
||||
EntityOverlay& EntityOverlay::add_right_icon(const std::any& texture_id, const float width, const float height,
|
||||
const Color& tint, const float offset)
|
||||
{
|
||||
const auto pos = m_text_cursor_right + Vector2<float>{offset, 0.f};
|
||||
m_renderer->add_image(texture_id, pos, pos + Vector2<float>{width, height}, tint);
|
||||
m_text_cursor_right.y += height;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_left_icon(const std::any& texture_id, const float width, const float height,
|
||||
const Color& tint, const float offset)
|
||||
{
|
||||
const auto pos = m_text_cursor_left + Vector2<float>{-(offset + width), 0.f};
|
||||
m_renderer->add_image(texture_id, pos, pos + Vector2<float>{width, height}, tint);
|
||||
m_text_cursor_left.y += height;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_top_icon(const std::any& texture_id, const float width, const float height,
|
||||
const Color& tint, const float offset)
|
||||
{
|
||||
m_text_cursor_top.y -= height;
|
||||
const auto pos = m_text_cursor_top + Vector2<float>{0.f, -offset};
|
||||
m_renderer->add_image(texture_id, pos, pos + Vector2<float>{width, height}, tint);
|
||||
return *this;
|
||||
}
|
||||
|
||||
EntityOverlay& EntityOverlay::add_bottom_icon(const std::any& texture_id, const float width, const float height,
|
||||
const Color& tint, const float offset)
|
||||
{
|
||||
const auto pos = m_text_cursor_bottom + Vector2<float>{0.f, offset};
|
||||
m_renderer->add_image(texture_id, pos, pos + Vector2<float>{width, height}, tint);
|
||||
m_text_cursor_bottom.y += height;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// ── widget dispatch ───────────────────────────────────────────────────────
|
||||
void EntityOverlay::dispatch(const widget::Box& box)
|
||||
{
|
||||
add_2d_box(box.color, box.fill, box.thickness);
|
||||
}
|
||||
|
||||
void EntityOverlay::dispatch(const widget::CorneredBox& cornered_box)
|
||||
{
|
||||
add_cornered_2d_box(cornered_box.color, cornered_box.fill, cornered_box.corner_ratio, cornered_box.thickness);
|
||||
}
|
||||
|
||||
void EntityOverlay::dispatch(const widget::DashedBox& dashed_box)
|
||||
{
|
||||
add_dashed_box(dashed_box.color, dashed_box.dash_len, dashed_box.gap_len, dashed_box.thickness);
|
||||
}
|
||||
|
||||
void EntityOverlay::dispatch(const widget::Skeleton& skeleton)
|
||||
{
|
||||
add_skeleton(skeleton.color, skeleton.thickness);
|
||||
}
|
||||
|
||||
void EntityOverlay::dispatch(const widget::SnapLine& snap_line)
|
||||
{
|
||||
add_snap_line(snap_line.start, snap_line.color, snap_line.width);
|
||||
}
|
||||
|
||||
void EntityOverlay::dispatch(const widget::ScanMarker& scan_marker)
|
||||
{
|
||||
const auto box_width = std::abs(m_canvas.top_right_corner.x - m_canvas.top_left_corner.x);
|
||||
const auto box_height = std::abs(m_canvas.bottom_left_corner.y - m_canvas.top_left_corner.y);
|
||||
|
||||
const auto center_x = (m_canvas.top_left_corner.x + m_canvas.top_right_corner.x) / 2.f;
|
||||
const auto center_y = m_canvas.top_left_corner.y + box_height * 0.44f;
|
||||
|
||||
const auto side = std::min(box_width, box_height) * 0.5f;
|
||||
const auto h = side * std::sqrt(3.f) / 2.f;
|
||||
|
||||
const std::array<Vector2<float>, 3> tri = {
|
||||
Vector2<float>{center_x, center_y - h * 2.f / 3.f},
|
||||
Vector2<float>{center_x - side / 2.f, center_y + h / 3.f},
|
||||
Vector2<float>{center_x + side / 2.f, center_y + h / 3.f},
|
||||
};
|
||||
|
||||
m_renderer->add_filled_polyline({tri.data(), tri.size()}, scan_marker.color);
|
||||
|
||||
if (scan_marker.outline.value().w > 0.f)
|
||||
m_renderer->add_polyline({tri.data(), tri.size()}, scan_marker.outline, scan_marker.outline_thickness);
|
||||
}
|
||||
|
||||
void EntityOverlay::dispatch(const widget::AimDot& aim_dot)
|
||||
{
|
||||
m_renderer->add_filled_circle(aim_dot.position, aim_dot.radius, aim_dot.color);
|
||||
}
|
||||
|
||||
void EntityOverlay::draw_progress_ring(const Vector2<float>& center, const widget::ProgressRing& ring)
|
||||
{
|
||||
constexpr auto pi = std::numbers::pi_v<float>;
|
||||
const float ratio = std::clamp(ring.ratio, 0.f, 1.f);
|
||||
|
||||
m_renderer->add_circle(center, ring.radius, ring.bg, ring.thickness, ring.segments);
|
||||
|
||||
if (ratio > 0.f)
|
||||
{
|
||||
const float a_min = -pi / 2.f;
|
||||
const float a_max = a_min + ratio * 2.f * pi;
|
||||
m_renderer->add_arc(center, ring.radius, a_min, a_max, ring.color, ring.thickness, ring.segments);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Side container dispatch ───────────────────────────────────────────────
|
||||
void EntityOverlay::dispatch(const widget::RightSide& right_side)
|
||||
{
|
||||
for (const auto& child : right_side.children)
|
||||
std::visit(
|
||||
widget::Overloaded{
|
||||
[](const widget::None&)
|
||||
{
|
||||
},
|
||||
[this](const widget::Bar& w)
|
||||
{
|
||||
add_right_bar(w.color, w.outline, w.bg, w.size, w.ratio, w.offset);
|
||||
},
|
||||
[this](const widget::DashedBar& w)
|
||||
{
|
||||
add_right_dashed_bar(w.color, w.outline, w.bg, w.size, w.ratio, w.dash_len, w.gap_len,
|
||||
w.offset);
|
||||
},
|
||||
[this](const widget::Label& w)
|
||||
{
|
||||
add_right_label(w.color, w.offset, w.outlined, w.text);
|
||||
},
|
||||
[this](const widget::Centered<widget::Label>& w)
|
||||
{
|
||||
add_right_label(w.child.color, w.child.offset, w.child.outlined, w.child.text);
|
||||
},
|
||||
[this](const widget::SpaceVertical& w)
|
||||
{
|
||||
add_right_space_vertical(w.size);
|
||||
},
|
||||
[this](const widget::SpaceHorizontal& w)
|
||||
{
|
||||
add_right_space_horizontal(w.size);
|
||||
},
|
||||
[this](const widget::ProgressRing& w)
|
||||
{
|
||||
add_right_progress_ring(w.color, w.bg, w.radius, w.ratio, w.thickness, w.offset,
|
||||
w.segments);
|
||||
},
|
||||
[this](const widget::Icon& w)
|
||||
{
|
||||
add_right_icon(w.texture_id, w.width, w.height, w.tint, w.offset);
|
||||
},
|
||||
},
|
||||
child);
|
||||
}
|
||||
|
||||
void EntityOverlay::dispatch(const widget::LeftSide& left_side)
|
||||
{
|
||||
for (const auto& child : left_side.children)
|
||||
std::visit(
|
||||
widget::Overloaded{
|
||||
[](const widget::None&)
|
||||
{
|
||||
},
|
||||
[this](const widget::Bar& w)
|
||||
{
|
||||
add_left_bar(w.color, w.outline, w.bg, w.size, w.ratio, w.offset);
|
||||
},
|
||||
[this](const widget::DashedBar& w)
|
||||
{
|
||||
add_left_dashed_bar(w.color, w.outline, w.bg, w.size, w.ratio, w.dash_len, w.gap_len,
|
||||
w.offset);
|
||||
},
|
||||
[this](const widget::Label& w)
|
||||
{
|
||||
add_left_label(w.color, w.offset, w.outlined, w.text);
|
||||
},
|
||||
[this](const widget::Centered<widget::Label>& w)
|
||||
{
|
||||
add_left_label(w.child.color, w.child.offset, w.child.outlined, w.child.text);
|
||||
},
|
||||
[this](const widget::SpaceVertical& w)
|
||||
{
|
||||
add_left_space_vertical(w.size);
|
||||
},
|
||||
[this](const widget::SpaceHorizontal& w)
|
||||
{
|
||||
add_left_space_horizontal(w.size);
|
||||
},
|
||||
[this](const widget::ProgressRing& w)
|
||||
{
|
||||
add_left_progress_ring(w.color, w.bg, w.radius, w.ratio, w.thickness, w.offset,
|
||||
w.segments);
|
||||
},
|
||||
[this](const widget::Icon& w)
|
||||
{
|
||||
add_left_icon(w.texture_id, w.width, w.height, w.tint, w.offset);
|
||||
},
|
||||
},
|
||||
child);
|
||||
}
|
||||
|
||||
void EntityOverlay::dispatch(const widget::TopSide& top_side)
|
||||
{
|
||||
for (const auto& child : top_side.children)
|
||||
std::visit(
|
||||
widget::Overloaded{
|
||||
[](const widget::None&)
|
||||
{
|
||||
},
|
||||
[this](const widget::Bar& w)
|
||||
{
|
||||
add_top_bar(w.color, w.outline, w.bg, w.size, w.ratio, w.offset);
|
||||
},
|
||||
[this](const widget::DashedBar& w)
|
||||
{
|
||||
add_top_dashed_bar(w.color, w.outline, w.bg, w.size, w.ratio, w.dash_len, w.gap_len,
|
||||
w.offset);
|
||||
},
|
||||
[this](const widget::Label& w)
|
||||
{
|
||||
add_top_label(w.color, w.offset, w.outlined, w.text);
|
||||
},
|
||||
[this](const widget::Centered<widget::Label>& w)
|
||||
{
|
||||
add_centered_top_label(w.child.color, w.child.offset, w.child.outlined, w.child.text);
|
||||
},
|
||||
[this](const widget::SpaceVertical& w)
|
||||
{
|
||||
add_top_space_vertical(w.size);
|
||||
},
|
||||
[this](const widget::SpaceHorizontal& w)
|
||||
{
|
||||
add_top_space_horizontal(w.size);
|
||||
},
|
||||
[this](const widget::ProgressRing& w)
|
||||
{
|
||||
add_top_progress_ring(w.color, w.bg, w.radius, w.ratio, w.thickness, w.offset,
|
||||
w.segments);
|
||||
},
|
||||
[this](const widget::Icon& w)
|
||||
{
|
||||
add_top_icon(w.texture_id, w.width, w.height, w.tint, w.offset);
|
||||
},
|
||||
},
|
||||
child);
|
||||
}
|
||||
void EntityOverlay::dispatch(const widget::BottomSide& bottom_side)
|
||||
{
|
||||
for (const auto& child : bottom_side.children)
|
||||
std::visit(
|
||||
widget::Overloaded{
|
||||
[](const widget::None&)
|
||||
{
|
||||
},
|
||||
[this](const widget::Bar& w)
|
||||
{
|
||||
add_bottom_bar(w.color, w.outline, w.bg, w.size, w.ratio, w.offset);
|
||||
},
|
||||
[this](const widget::DashedBar& w)
|
||||
{
|
||||
add_bottom_dashed_bar(w.color, w.outline, w.bg, w.size, w.ratio, w.dash_len, w.gap_len,
|
||||
w.offset);
|
||||
},
|
||||
[this](const widget::Label& w)
|
||||
{
|
||||
add_bottom_label(w.color, w.offset, w.outlined, w.text);
|
||||
},
|
||||
[this](const widget::Centered<widget::Label>& w)
|
||||
{
|
||||
add_centered_bottom_label(w.child.color, w.child.offset, w.child.outlined,
|
||||
w.child.text);
|
||||
},
|
||||
[this](const widget::SpaceVertical& w)
|
||||
{
|
||||
add_bottom_space_vertical(w.size);
|
||||
},
|
||||
[this](const widget::SpaceHorizontal& w)
|
||||
{
|
||||
add_bottom_space_horizontal(w.size);
|
||||
},
|
||||
[this](const widget::ProgressRing& w)
|
||||
{
|
||||
add_bottom_progress_ring(w.color, w.bg, w.radius, w.ratio, w.thickness, w.offset,
|
||||
w.segments);
|
||||
},
|
||||
[this](const widget::Icon& w)
|
||||
{
|
||||
add_bottom_icon(w.texture_id, w.width, w.height, w.tint, w.offset);
|
||||
},
|
||||
},
|
||||
child);
|
||||
}
|
||||
|
||||
} // namespace omath::hud
|
||||
82
source/hud/renderer_realizations/imgui_renderer.cpp
Normal file
82
source/hud/renderer_realizations/imgui_renderer.cpp
Normal file
@@ -0,0 +1,82 @@
|
||||
//
|
||||
// Created by orange on 13.03.2026.
|
||||
//
|
||||
#include "omath/hud/renderer_realizations/imgui_renderer.hpp"
|
||||
|
||||
#ifdef OMATH_IMGUI_INTEGRATION
|
||||
#include <imgui.h>
|
||||
|
||||
namespace omath::hud
|
||||
{
|
||||
ImguiHudRenderer::~ImguiHudRenderer() = default;
|
||||
|
||||
void ImguiHudRenderer::add_line(const Vector2<float>& line_start, const Vector2<float>& line_end,
|
||||
const Color& color, const float thickness)
|
||||
{
|
||||
ImGui::GetBackgroundDrawList()->AddLine(line_start.to_im_vec2(), line_end.to_im_vec2(), color.to_im_color(),
|
||||
thickness);
|
||||
}
|
||||
|
||||
void ImguiHudRenderer::add_polyline(const std::span<const Vector2<float>>& vertexes, const Color& color,
|
||||
const float thickness)
|
||||
{
|
||||
ImGui::GetBackgroundDrawList()->AddPolyline(reinterpret_cast<const ImVec2*>(vertexes.data()),
|
||||
static_cast<int>(vertexes.size()), color.to_im_color(),
|
||||
ImDrawFlags_Closed, thickness);
|
||||
}
|
||||
|
||||
void ImguiHudRenderer::add_filled_polyline(const std::span<const Vector2<float>>& vertexes, const Color& color)
|
||||
{
|
||||
ImGui::GetBackgroundDrawList()->AddConvexPolyFilled(reinterpret_cast<const ImVec2*>(vertexes.data()),
|
||||
static_cast<int>(vertexes.size()), color.to_im_color());
|
||||
}
|
||||
|
||||
void ImguiHudRenderer::add_rectangle(const Vector2<float>& min, const Vector2<float>& max, const Color& color)
|
||||
{
|
||||
ImGui::GetBackgroundDrawList()->AddRect(min.to_im_vec2(), max.to_im_vec2(), color.to_im_color());
|
||||
}
|
||||
|
||||
void ImguiHudRenderer::add_filled_rectangle(const Vector2<float>& min, const Vector2<float>& max,
|
||||
const Color& color)
|
||||
{
|
||||
ImGui::GetBackgroundDrawList()->AddRectFilled(min.to_im_vec2(), max.to_im_vec2(), color.to_im_color());
|
||||
}
|
||||
|
||||
void ImguiHudRenderer::add_circle(const Vector2<float>& center, const float radius, const Color& color,
|
||||
const float thickness, const int segments)
|
||||
{
|
||||
ImGui::GetBackgroundDrawList()->AddCircle(center.to_im_vec2(), radius, color.to_im_color(), segments, thickness);
|
||||
}
|
||||
|
||||
void ImguiHudRenderer::add_filled_circle(const Vector2<float>& center, const float radius, const Color& color,
|
||||
const int segments)
|
||||
{
|
||||
ImGui::GetBackgroundDrawList()->AddCircleFilled(center.to_im_vec2(), radius, color.to_im_color(), segments);
|
||||
}
|
||||
|
||||
void ImguiHudRenderer::add_arc(const Vector2<float>& center, const float radius, const float a_min, const float a_max,
|
||||
const Color& color, const float thickness, const int segments)
|
||||
{
|
||||
ImGui::GetBackgroundDrawList()->PathArcTo(center.to_im_vec2(), radius, a_min, a_max, segments);
|
||||
ImGui::GetBackgroundDrawList()->PathStroke(color.to_im_color(), ImDrawFlags_None, thickness);
|
||||
}
|
||||
|
||||
void ImguiHudRenderer::add_image(const std::any& texture_id, const Vector2<float>& min, const Vector2<float>& max,
|
||||
const Color& tint)
|
||||
{
|
||||
ImGui::GetBackgroundDrawList()->AddImage(std::any_cast<ImTextureID>(texture_id), min.to_im_vec2(),
|
||||
max.to_im_vec2(), {0, 0}, {1, 1}, tint.to_im_color());
|
||||
}
|
||||
|
||||
void ImguiHudRenderer::add_text(const Vector2<float>& position, const Color& color, const std::string_view& text)
|
||||
{
|
||||
ImGui::GetBackgroundDrawList()->AddText(position.to_im_vec2(), color.to_im_color(), text.data(),
|
||||
text.data() + text.size());
|
||||
}
|
||||
[[nodiscard]]
|
||||
Vector2<float> ImguiHudRenderer::calc_text_size(const std::string_view& text)
|
||||
{
|
||||
return Vector2<float>::from_im_vec2(ImGui::CalcTextSize(text.data()));
|
||||
}
|
||||
} // namespace omath::hud
|
||||
#endif // OMATH_IMGUI_INTEGRATION
|
||||
27
source/lua/lua.cpp
Normal file
27
source/lua/lua.cpp
Normal file
@@ -0,0 +1,27 @@
|
||||
//
|
||||
// Created by orange on 07.03.2026.
|
||||
//
|
||||
#ifdef OMATH_ENABLE_LUA
|
||||
#include "lua.hpp"
|
||||
#include <sol/sol.hpp>
|
||||
#include "omath/lua/lua.hpp"
|
||||
|
||||
namespace omath::lua
|
||||
{
|
||||
void LuaInterpreter::register_lib(lua_State* lua_state)
|
||||
{
|
||||
sol::state_view lua(lua_state);
|
||||
|
||||
auto omath_table = lua["omath"].get_or_create<sol::table>();
|
||||
|
||||
register_vec2(omath_table);
|
||||
register_vec3(omath_table);
|
||||
register_vec4(omath_table);
|
||||
register_color(omath_table);
|
||||
register_triangle(omath_table);
|
||||
register_shared_types(omath_table);
|
||||
register_engines(omath_table);
|
||||
register_pattern_scan(omath_table);
|
||||
}
|
||||
} // namespace omath::lua
|
||||
#endif
|
||||
46
source/lua/lua_color.cpp
Normal file
46
source/lua/lua_color.cpp
Normal file
@@ -0,0 +1,46 @@
|
||||
//
|
||||
// Created by orange on 07.03.2026.
|
||||
//
|
||||
#ifdef OMATH_ENABLE_LUA
|
||||
#include "omath/lua/lua.hpp"
|
||||
#include <sol/sol.hpp>
|
||||
#include <omath/utility/color.hpp>
|
||||
|
||||
namespace omath::lua
|
||||
{
|
||||
void LuaInterpreter::register_color(sol::table& omath_table)
|
||||
{
|
||||
omath_table.new_usertype<omath::Color>(
|
||||
"Color",
|
||||
sol::factories([](float r, float g, float b, float a) { return omath::Color(r, g, b, a); },
|
||||
[]() { return omath::Color(); }),
|
||||
|
||||
"from_rgba", [](uint8_t r, uint8_t g, uint8_t b, uint8_t a)
|
||||
{ return omath::Color::from_rgba(r, g, b, a); }, "from_hsv",
|
||||
sol::overload([](float h, float s, float v) { return omath::Color::from_hsv(h, s, v); },
|
||||
[](const omath::Hsv& hsv) { return omath::Color::from_hsv(hsv); }),
|
||||
"red", []() { return omath::Color::red(); }, "green", []() { return omath::Color::green(); }, "blue",
|
||||
[]() { return omath::Color::blue(); },
|
||||
|
||||
"r", sol::property([](const omath::Color& c) { return c.value().x; }), "g",
|
||||
sol::property([](const omath::Color& c) { return c.value().y; }), "b",
|
||||
sol::property([](const omath::Color& c) { return c.value().z; }), "a",
|
||||
sol::property([](const omath::Color& c) { return c.value().w; }),
|
||||
|
||||
"to_hsv", &omath::Color::to_hsv, "set_hue", &omath::Color::set_hue, "set_saturation",
|
||||
&omath::Color::set_saturation, "set_value", &omath::Color::set_value, "blend", &omath::Color::blend,
|
||||
|
||||
sol::meta_function::to_string, &omath::Color::to_string);
|
||||
|
||||
omath_table.new_usertype<omath::Hsv>(
|
||||
"Hsv", sol::constructors<omath::Hsv()>(), "hue",
|
||||
sol::property([](const omath::Hsv& h) { return h.hue; }, [](omath::Hsv& h, float val) { h.hue = val; }),
|
||||
"saturation",
|
||||
sol::property([](const omath::Hsv& h) { return h.saturation; },
|
||||
[](omath::Hsv& h, float val) { h.saturation = val; }),
|
||||
"value",
|
||||
sol::property([](const omath::Hsv& h) { return h.value; },
|
||||
[](omath::Hsv& h, float val) { h.value = val; }));
|
||||
}
|
||||
} // namespace omath::lua::detail
|
||||
#endif
|
||||
227
source/lua/lua_engines.cpp
Normal file
227
source/lua/lua_engines.cpp
Normal file
@@ -0,0 +1,227 @@
|
||||
//
|
||||
// Created by orange on 07.03.2026.
|
||||
//
|
||||
#ifdef OMATH_ENABLE_LUA
|
||||
#include "omath/lua/lua.hpp"
|
||||
#include <omath/engines/cry_engine/camera.hpp>
|
||||
#include <omath/engines/frostbite_engine/camera.hpp>
|
||||
#include <omath/engines/iw_engine/camera.hpp>
|
||||
#include <omath/engines/opengl_engine/camera.hpp>
|
||||
#include <omath/engines/source_engine/camera.hpp>
|
||||
#include <omath/engines/unity_engine/camera.hpp>
|
||||
#include <omath/engines/unreal_engine/camera.hpp>
|
||||
#include <sol/sol.hpp>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
// ---- Canonical shared C++ type aliases ----------------------------------
|
||||
// Each unique template instantiation must be registered exactly once.
|
||||
|
||||
using PitchAngle90 = omath::Angle<float, -90.f, 90.f, omath::AngleFlags::Clamped>;
|
||||
using PitchAngle89 = omath::Angle<float, -89.f, 89.f, omath::AngleFlags::Clamped>;
|
||||
using SharedYawRoll = omath::Angle<float, -180.f, 180.f, omath::AngleFlags::Normalized>;
|
||||
using SharedFoV = omath::Angle<float, 0.f, 180.f, omath::AngleFlags::Clamped>;
|
||||
using ViewAngles90 = omath::ViewAngles<PitchAngle90, SharedYawRoll, SharedYawRoll>;
|
||||
using ViewAngles89 = omath::ViewAngles<PitchAngle89, SharedYawRoll, SharedYawRoll>;
|
||||
|
||||
std::string projection_error_to_string(omath::projection::Error e)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case omath::projection::Error::WORLD_POSITION_IS_OUT_OF_SCREEN_BOUNDS:
|
||||
return "world position is out of screen bounds";
|
||||
case omath::projection::Error::INV_VIEW_PROJ_MAT_DET_EQ_ZERO:
|
||||
return "inverse view-projection matrix determinant is zero";
|
||||
}
|
||||
return "unknown error";
|
||||
}
|
||||
|
||||
template<class AngleType>
|
||||
void register_angle(sol::table& table, const char* name)
|
||||
{
|
||||
table.new_usertype<AngleType>(
|
||||
name, sol::no_constructor, "from_degrees", &AngleType::from_degrees, "from_radians",
|
||||
&AngleType::from_radians, "as_degrees", &AngleType::as_degrees, "as_radians", &AngleType::as_radians,
|
||||
"sin", &AngleType::sin, "cos", &AngleType::cos, "tan", &AngleType::tan, "cot", &AngleType::cot,
|
||||
sol::meta_function::addition, [](const AngleType& a, const AngleType& b)
|
||||
{ return AngleType::from_degrees(a.as_degrees() + b.as_degrees()); }, sol::meta_function::subtraction,
|
||||
[](const AngleType& a, const AngleType& b)
|
||||
{ return AngleType::from_degrees(a.as_degrees() - b.as_degrees()); }, sol::meta_function::unary_minus,
|
||||
[](const AngleType& a) { return AngleType::from_degrees(-a.as_degrees()); },
|
||||
sol::meta_function::equal_to, [](const AngleType& a, const AngleType& b) { return a == b; },
|
||||
sol::meta_function::to_string, [](const AngleType& a) { return std::format("{}deg", a.as_degrees()); });
|
||||
}
|
||||
|
||||
// Set aliases in an engine subtable pointing to the already-registered shared types
|
||||
template<class PitchAngleType, class ViewAnglesType>
|
||||
void set_engine_aliases(sol::table& engine_table, sol::table& types)
|
||||
{
|
||||
if constexpr (std::is_same_v<PitchAngleType, PitchAngle90>)
|
||||
engine_table["PitchAngle"] = types["PitchAngle90"];
|
||||
else
|
||||
engine_table["PitchAngle"] = types["PitchAngle89"];
|
||||
|
||||
engine_table["YawAngle"] = types["YawRoll"];
|
||||
engine_table["RollAngle"] = types["YawRoll"];
|
||||
engine_table["FieldOfView"] = types["FieldOfView"];
|
||||
engine_table["ViewPort"] = types["ViewPort"];
|
||||
|
||||
if constexpr (std::is_same_v<ViewAnglesType, ViewAngles90>)
|
||||
engine_table["ViewAngles"] = types["ViewAngles90"];
|
||||
else
|
||||
engine_table["ViewAngles"] = types["ViewAngles89"];
|
||||
}
|
||||
|
||||
// Register an engine: alias shared types, register unique Camera
|
||||
template<class EngineTraits>
|
||||
void register_engine(sol::table& omath_table, const char* subtable_name)
|
||||
{
|
||||
using PitchAngle = typename EngineTraits::PitchAngle;
|
||||
using ViewAngles = typename EngineTraits::ViewAngles;
|
||||
using Camera = typename EngineTraits::Camera;
|
||||
|
||||
auto engine_table = omath_table[subtable_name].get_or_create<sol::table>();
|
||||
auto types = omath_table["_types"].get<sol::table>();
|
||||
|
||||
set_engine_aliases<PitchAngle, ViewAngles>(engine_table, types);
|
||||
|
||||
engine_table.new_usertype<Camera>(
|
||||
"Camera",
|
||||
sol::constructors<Camera(const omath::Vector3<float>&, const ViewAngles&,
|
||||
const omath::projection::ViewPort&, const omath::projection::FieldOfView&,
|
||||
float, float)>(),
|
||||
"look_at", &Camera::look_at, "get_forward", &Camera::get_forward, "get_right", &Camera::get_right,
|
||||
"get_up", &Camera::get_up, "get_origin", &Camera::get_origin, "get_view_angles",
|
||||
&Camera::get_view_angles, "get_near_plane", &Camera::get_near_plane, "get_far_plane",
|
||||
&Camera::get_far_plane, "get_field_of_view", &Camera::get_field_of_view, "set_origin",
|
||||
&Camera::set_origin, "set_view_angles", &Camera::set_view_angles, "set_view_port",
|
||||
&Camera::set_view_port, "set_field_of_view", &Camera::set_field_of_view, "set_near_plane",
|
||||
&Camera::set_near_plane, "set_far_plane", &Camera::set_far_plane,
|
||||
|
||||
"world_to_screen",
|
||||
[](const Camera& cam, const omath::Vector3<float>& pos)
|
||||
-> std::tuple<sol::optional<omath::Vector3<float>>, sol::optional<std::string>>
|
||||
{
|
||||
auto result = cam.world_to_screen(pos);
|
||||
if (result)
|
||||
return {*result, sol::nullopt};
|
||||
return {sol::nullopt, projection_error_to_string(result.error())};
|
||||
},
|
||||
|
||||
"screen_to_world",
|
||||
[](const Camera& cam, const omath::Vector3<float>& pos)
|
||||
-> std::tuple<sol::optional<omath::Vector3<float>>, sol::optional<std::string>>
|
||||
{
|
||||
auto result = cam.screen_to_world(pos);
|
||||
if (result)
|
||||
return {*result, sol::nullopt};
|
||||
return {sol::nullopt, projection_error_to_string(result.error())};
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Engine trait structs -----------------------------------------------
|
||||
|
||||
struct OpenGLEngineTraits
|
||||
{
|
||||
using PitchAngle = omath::opengl_engine::PitchAngle;
|
||||
using ViewAngles = omath::opengl_engine::ViewAngles;
|
||||
using Camera = omath::opengl_engine::Camera;
|
||||
};
|
||||
struct FrostbiteEngineTraits
|
||||
{
|
||||
using PitchAngle = omath::frostbite_engine::PitchAngle;
|
||||
using ViewAngles = omath::frostbite_engine::ViewAngles;
|
||||
using Camera = omath::frostbite_engine::Camera;
|
||||
};
|
||||
struct IWEngineTraits
|
||||
{
|
||||
using PitchAngle = omath::iw_engine::PitchAngle;
|
||||
using ViewAngles = omath::iw_engine::ViewAngles;
|
||||
using Camera = omath::iw_engine::Camera;
|
||||
};
|
||||
struct SourceEngineTraits
|
||||
{
|
||||
using PitchAngle = omath::source_engine::PitchAngle;
|
||||
using ViewAngles = omath::source_engine::ViewAngles;
|
||||
using Camera = omath::source_engine::Camera;
|
||||
};
|
||||
struct UnityEngineTraits
|
||||
{
|
||||
using PitchAngle = omath::unity_engine::PitchAngle;
|
||||
using ViewAngles = omath::unity_engine::ViewAngles;
|
||||
using Camera = omath::unity_engine::Camera;
|
||||
};
|
||||
struct UnrealEngineTraits
|
||||
{
|
||||
using PitchAngle = omath::unreal_engine::PitchAngle;
|
||||
using ViewAngles = omath::unreal_engine::ViewAngles;
|
||||
using Camera = omath::unreal_engine::Camera;
|
||||
};
|
||||
struct CryEngineTraits
|
||||
{
|
||||
using PitchAngle = omath::cry_engine::PitchAngle;
|
||||
using ViewAngles = omath::cry_engine::ViewAngles;
|
||||
using Camera = omath::cry_engine::Camera;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
namespace omath::lua
|
||||
{
|
||||
void LuaInterpreter::register_shared_types(sol::table& omath_table)
|
||||
{
|
||||
auto t = omath_table["_types"].get_or_create<sol::table>();
|
||||
|
||||
register_angle<PitchAngle90>(t, "PitchAngle90");
|
||||
register_angle<PitchAngle89>(t, "PitchAngle89");
|
||||
register_angle<SharedYawRoll>(t, "YawRoll");
|
||||
register_angle<SharedFoV>(t, "FieldOfView");
|
||||
|
||||
t.new_usertype<omath::projection::ViewPort>(
|
||||
"ViewPort", sol::factories([](float w, float h) { return omath::projection::ViewPort{w, h}; }), "width",
|
||||
sol::property([](const omath::projection::ViewPort& vp) { return vp.m_width; },
|
||||
[](omath::projection::ViewPort& vp, float val) { vp.m_width = val; }),
|
||||
"height",
|
||||
sol::property([](const omath::projection::ViewPort& vp) { return vp.m_height; },
|
||||
[](omath::projection::ViewPort& vp, float val) { vp.m_height = val; }),
|
||||
"aspect_ratio", &omath::projection::ViewPort::aspect_ratio);
|
||||
|
||||
t.new_usertype<ViewAngles90>(
|
||||
"ViewAngles90",
|
||||
sol::factories([](PitchAngle90 p, SharedYawRoll y, SharedYawRoll r) { return ViewAngles90{p, y, r}; }),
|
||||
"pitch",
|
||||
sol::property([](const ViewAngles90& va) { return va.pitch; },
|
||||
[](ViewAngles90& va, const PitchAngle90& val) { va.pitch = val; }),
|
||||
"yaw",
|
||||
sol::property([](const ViewAngles90& va) { return va.yaw; },
|
||||
[](ViewAngles90& va, const SharedYawRoll& val) { va.yaw = val; }),
|
||||
"roll",
|
||||
sol::property([](const ViewAngles90& va) { return va.roll; },
|
||||
[](ViewAngles90& va, const SharedYawRoll& val) { va.roll = val; }));
|
||||
|
||||
t.new_usertype<ViewAngles89>(
|
||||
"ViewAngles89",
|
||||
sol::factories([](PitchAngle89 p, SharedYawRoll y, SharedYawRoll r) { return ViewAngles89{p, y, r}; }),
|
||||
"pitch",
|
||||
sol::property([](const ViewAngles89& va) { return va.pitch; },
|
||||
[](ViewAngles89& va, const PitchAngle89& val) { va.pitch = val; }),
|
||||
"yaw",
|
||||
sol::property([](const ViewAngles89& va) { return va.yaw; },
|
||||
[](ViewAngles89& va, const SharedYawRoll& val) { va.yaw = val; }),
|
||||
"roll",
|
||||
sol::property([](const ViewAngles89& va) { return va.roll; },
|
||||
[](ViewAngles89& va, const SharedYawRoll& val) { va.roll = val; }));
|
||||
}
|
||||
|
||||
void LuaInterpreter::register_engines(sol::table& omath_table)
|
||||
{
|
||||
register_engine<OpenGLEngineTraits>(omath_table, "opengl");
|
||||
register_engine<FrostbiteEngineTraits>(omath_table, "frostbite");
|
||||
register_engine<IWEngineTraits>(omath_table, "iw");
|
||||
register_engine<SourceEngineTraits>(omath_table, "source");
|
||||
register_engine<UnityEngineTraits>(omath_table, "unity");
|
||||
register_engine<UnrealEngineTraits>(omath_table, "unreal");
|
||||
register_engine<CryEngineTraits>(omath_table, "cry");
|
||||
}
|
||||
} // namespace omath::lua::detail
|
||||
#endif
|
||||
104
source/lua/lua_pattern_scan.cpp
Normal file
104
source/lua/lua_pattern_scan.cpp
Normal file
@@ -0,0 +1,104 @@
|
||||
//
|
||||
// Created by orange on 10.03.2026.
|
||||
//
|
||||
#ifdef OMATH_ENABLE_LUA
|
||||
#include "omath/lua/lua.hpp"
|
||||
#include <format>
|
||||
#include <omath/utility/elf_pattern_scan.hpp>
|
||||
#include <omath/utility/macho_pattern_scan.hpp>
|
||||
#include <omath/utility/pattern_scan.hpp>
|
||||
#include <omath/utility/pe_pattern_scan.hpp>
|
||||
#include <omath/utility/section_scan_result.hpp>
|
||||
#include <sol/sol.hpp>
|
||||
|
||||
namespace omath::lua
|
||||
{
|
||||
void LuaInterpreter::register_pattern_scan(sol::table& omath_table)
|
||||
{
|
||||
omath_table.new_usertype<SectionScanResult>(
|
||||
"SectionScanResult", sol::no_constructor,
|
||||
"virtual_base_addr",
|
||||
sol::property([](const SectionScanResult& r) { return r.virtual_base_addr; }),
|
||||
"raw_base_addr",
|
||||
sol::property([](const SectionScanResult& r) { return r.raw_base_addr; }),
|
||||
"target_offset",
|
||||
sol::property([](const SectionScanResult& r) { return r.target_offset; }),
|
||||
sol::meta_function::to_string,
|
||||
[](const SectionScanResult& r)
|
||||
{
|
||||
return std::format("SectionScanResult(vbase=0x{:X}, raw_base=0x{:X}, offset={})",
|
||||
r.virtual_base_addr, r.raw_base_addr, r.target_offset);
|
||||
});
|
||||
|
||||
// Generic scanner: accepts a Lua string as a byte buffer
|
||||
auto ps_table = omath_table["PatternScanner"].get_or_create<sol::table>();
|
||||
ps_table["scan"] = [](const std::string& data, const std::string& pattern) -> sol::optional<std::ptrdiff_t>
|
||||
{
|
||||
const auto* begin = reinterpret_cast<const std::byte*>(data.data());
|
||||
const auto* end = begin + data.size();
|
||||
const auto* result = PatternScanner::scan_for_pattern(begin, end, pattern);
|
||||
if (result == end)
|
||||
return sol::nullopt;
|
||||
return std::distance(begin, result);
|
||||
};
|
||||
|
||||
auto pe_table = omath_table["PePatternScanner"].get_or_create<sol::table>();
|
||||
pe_table["scan_in_module"] = [](std::uintptr_t base_addr, const std::string& pattern,
|
||||
sol::optional<std::string> section) -> sol::optional<std::uintptr_t>
|
||||
{
|
||||
auto result = PePatternScanner::scan_for_pattern_in_loaded_module(reinterpret_cast<const void*>(base_addr),
|
||||
pattern, section.value_or(".text"));
|
||||
if (!result)
|
||||
return sol::nullopt;
|
||||
return *result;
|
||||
};
|
||||
pe_table["scan_in_file"] = [](const std::string& path, const std::string& pattern,
|
||||
sol::optional<std::string> section) -> sol::optional<SectionScanResult>
|
||||
{
|
||||
auto result = PePatternScanner::scan_for_pattern_in_file(std::filesystem::path(path), pattern,
|
||||
section.value_or(".text"));
|
||||
if (!result)
|
||||
return sol::nullopt;
|
||||
return *result;
|
||||
};
|
||||
auto elf_table = omath_table["ElfPatternScanner"].get_or_create<sol::table>();
|
||||
elf_table["scan_in_module"] = [](std::uintptr_t base_addr, const std::string& pattern,
|
||||
sol::optional<std::string> section) -> sol::optional<std::uintptr_t>
|
||||
{
|
||||
auto result = ElfPatternScanner::scan_for_pattern_in_loaded_module(reinterpret_cast<const void*>(base_addr),
|
||||
pattern, section.value_or(".text"));
|
||||
if (!result)
|
||||
return sol::nullopt;
|
||||
return *result;
|
||||
};
|
||||
elf_table["scan_in_file"] = [](const std::string& path, const std::string& pattern,
|
||||
sol::optional<std::string> section) -> sol::optional<SectionScanResult>
|
||||
{
|
||||
auto result = ElfPatternScanner::scan_for_pattern_in_file(std::filesystem::path(path), pattern,
|
||||
section.value_or(".text"));
|
||||
if (!result)
|
||||
return sol::nullopt;
|
||||
return *result;
|
||||
};
|
||||
auto macho_table = omath_table["MachOPatternScanner"].get_or_create<sol::table>();
|
||||
macho_table["scan_in_module"] = [](std::uintptr_t base_addr, const std::string& pattern,
|
||||
sol::optional<std::string> section) -> sol::optional<std::uintptr_t>
|
||||
{
|
||||
auto result = MachOPatternScanner::scan_for_pattern_in_loaded_module(
|
||||
reinterpret_cast<const void*>(base_addr), pattern, section.value_or("__text"));
|
||||
if (!result)
|
||||
return sol::nullopt;
|
||||
return *result;
|
||||
};
|
||||
macho_table["scan_in_file"] = [](const std::string& path, const std::string& pattern,
|
||||
sol::optional<std::string> section) -> sol::optional<SectionScanResult>
|
||||
{
|
||||
auto result = MachOPatternScanner::scan_for_pattern_in_file(std::filesystem::path(path), pattern,
|
||||
section.value_or("__text"));
|
||||
if (!result)
|
||||
return sol::nullopt;
|
||||
return *result;
|
||||
};
|
||||
}
|
||||
} // namespace omath::lua
|
||||
#endif
|
||||
48
source/lua/lua_triangle.cpp
Normal file
48
source/lua/lua_triangle.cpp
Normal file
@@ -0,0 +1,48 @@
|
||||
//
|
||||
// Created by orange on 10.03.2026.
|
||||
//
|
||||
#ifdef OMATH_ENABLE_LUA
|
||||
#include "omath/lua/lua.hpp"
|
||||
#include <sol/sol.hpp>
|
||||
#include <omath/linear_algebra/triangle.hpp>
|
||||
|
||||
namespace omath::lua
|
||||
{
|
||||
void LuaInterpreter::register_triangle(sol::table& omath_table)
|
||||
{
|
||||
using Vec3f = omath::Vector3<float>;
|
||||
using Tri3f = omath::Triangle<Vec3f>;
|
||||
|
||||
omath_table.new_usertype<Tri3f>(
|
||||
"Triangle", sol::constructors<Tri3f(), Tri3f(const Vec3f&, const Vec3f&, const Vec3f&)>(),
|
||||
|
||||
"vertex1",
|
||||
sol::property([](const Tri3f& t) { return t.m_vertex1; },
|
||||
[](Tri3f& t, const Vec3f& v) { t.m_vertex1 = v; }),
|
||||
"vertex2",
|
||||
sol::property([](const Tri3f& t) { return t.m_vertex2; },
|
||||
[](Tri3f& t, const Vec3f& v) { t.m_vertex2 = v; }),
|
||||
"vertex3",
|
||||
sol::property([](const Tri3f& t) { return t.m_vertex3; },
|
||||
[](Tri3f& t, const Vec3f& v) { t.m_vertex3 = v; }),
|
||||
|
||||
"calculate_normal", &Tri3f::calculate_normal,
|
||||
"side_a_length", &Tri3f::side_a_length,
|
||||
"side_b_length", &Tri3f::side_b_length,
|
||||
"side_a_vector", &Tri3f::side_a_vector,
|
||||
"side_b_vector", &Tri3f::side_b_vector,
|
||||
"hypot", &Tri3f::hypot,
|
||||
"is_rectangular", &Tri3f::is_rectangular,
|
||||
"mid_point", &Tri3f::mid_point,
|
||||
|
||||
sol::meta_function::to_string,
|
||||
[](const Tri3f& t)
|
||||
{
|
||||
return std::format("Triangle(({}, {}, {}), ({}, {}, {}), ({}, {}, {}))",
|
||||
t.m_vertex1.x, t.m_vertex1.y, t.m_vertex1.z,
|
||||
t.m_vertex2.x, t.m_vertex2.y, t.m_vertex2.z,
|
||||
t.m_vertex3.x, t.m_vertex3.y, t.m_vertex3.z);
|
||||
});
|
||||
}
|
||||
} // namespace omath::lua
|
||||
#endif
|
||||
54
source/lua/lua_vec2.cpp
Normal file
54
source/lua/lua_vec2.cpp
Normal file
@@ -0,0 +1,54 @@
|
||||
//
|
||||
// Created by orange on 07.03.2026.
|
||||
//
|
||||
#ifdef OMATH_ENABLE_LUA
|
||||
#include "omath/lua/lua.hpp"
|
||||
#include <omath/linear_algebra/vector2.hpp>
|
||||
#include <sol/sol.hpp>
|
||||
|
||||
namespace omath::lua
|
||||
{
|
||||
void LuaInterpreter::register_vec2(sol::table& omath_table)
|
||||
{
|
||||
using Vec2f = omath::Vector2<float>;
|
||||
|
||||
omath_table.new_usertype<Vec2f>(
|
||||
"Vec2", sol::constructors<Vec2f(), Vec2f(float, float)>(),
|
||||
|
||||
"x", sol::property([](const Vec2f& v) { return v.x; }, [](Vec2f& v, const float val) { v.x = val; }),
|
||||
"y", sol::property([](const Vec2f& v) { return v.y; }, [](Vec2f& v, const float val) { v.y = val; }),
|
||||
|
||||
sol::meta_function::addition, sol::resolve<Vec2f(const Vec2f&) const>(&Vec2f::operator+),
|
||||
sol::meta_function::subtraction, sol::resolve<Vec2f(const Vec2f&) const>(&Vec2f::operator-),
|
||||
sol::meta_function::unary_minus, sol::resolve<Vec2f() const>(&Vec2f::operator-),
|
||||
sol::meta_function::equal_to, &Vec2f::operator==,
|
||||
sol::meta_function::less_than, sol::resolve<bool(const Vec2f&) const>(&Vec2f::operator<),
|
||||
sol::meta_function::less_than_or_equal_to, sol::resolve<bool(const Vec2f&) const>(&Vec2f::operator<=),
|
||||
sol::meta_function::to_string,
|
||||
[](const Vec2f& v) { return std::format("Vec2({}, {})", v.x, v.y); },
|
||||
|
||||
sol::meta_function::multiplication,
|
||||
sol::overload(sol::resolve<Vec2f(const float&) const>(&Vec2f::operator*),
|
||||
[](const float s, const Vec2f& v) { return v * s; }),
|
||||
|
||||
sol::meta_function::division,
|
||||
sol::resolve<Vec2f(const float&) const>(&Vec2f::operator/),
|
||||
|
||||
"length", &Vec2f::length,
|
||||
"length_sqr", &Vec2f::length_sqr,
|
||||
"normalized", &Vec2f::normalized,
|
||||
"dot", &Vec2f::dot,
|
||||
"distance_to", &Vec2f::distance_to,
|
||||
"distance_to_sqr", &Vec2f::distance_to_sqr,
|
||||
"sum", &Vec2f::sum,
|
||||
|
||||
"abs",
|
||||
[](const Vec2f& v)
|
||||
{
|
||||
Vec2f copy = v;
|
||||
copy.abs();
|
||||
return copy;
|
||||
});
|
||||
}
|
||||
} // namespace omath::lua::detail
|
||||
#endif
|
||||
81
source/lua/lua_vec3.cpp
Normal file
81
source/lua/lua_vec3.cpp
Normal file
@@ -0,0 +1,81 @@
|
||||
//
|
||||
// Created by orange on 07.03.2026.
|
||||
//
|
||||
#ifdef OMATH_ENABLE_LUA
|
||||
#include "omath/lua/lua.hpp"
|
||||
#include <sol/sol.hpp>
|
||||
#include <omath/linear_algebra/vector3.hpp>
|
||||
|
||||
namespace omath::lua
|
||||
{
|
||||
void LuaInterpreter::register_vec3(sol::table& omath_table)
|
||||
{
|
||||
using Vec3f = omath::Vector3<float>;
|
||||
|
||||
omath_table.new_usertype<Vec3f>(
|
||||
"Vec3", sol::constructors<Vec3f(), Vec3f(float, float, float)>(),
|
||||
|
||||
"x", sol::property([](const Vec3f& v) { return v.x; }, [](Vec3f& v, float val) { v.x = val; }),
|
||||
"y", sol::property([](const Vec3f& v) { return v.y; }, [](Vec3f& v, float val) { v.y = val; }),
|
||||
"z", sol::property([](const Vec3f& v) { return v.z; }, [](Vec3f& v, float val) { v.z = val; }),
|
||||
|
||||
sol::meta_function::addition, sol::resolve<Vec3f(const Vec3f&) const>(&Vec3f::operator+),
|
||||
sol::meta_function::subtraction, sol::resolve<Vec3f(const Vec3f&) const>(&Vec3f::operator-),
|
||||
sol::meta_function::unary_minus, sol::resolve<Vec3f() const>(&Vec3f::operator-),
|
||||
sol::meta_function::equal_to, &Vec3f::operator==, sol::meta_function::less_than,
|
||||
sol::resolve<bool(const Vec3f&) const>(&Vec3f::operator<), sol::meta_function::less_than_or_equal_to,
|
||||
sol::resolve<bool(const Vec3f&) const>(&Vec3f::operator<=), sol::meta_function::to_string,
|
||||
[](const Vec3f& v) { return std::format("Vec3({}, {}, {})", v.x, v.y, v.z); },
|
||||
|
||||
sol::meta_function::multiplication,
|
||||
sol::overload(sol::resolve<Vec3f(const float&) const>(&Vec3f::operator*),
|
||||
sol::resolve<Vec3f(const Vec3f&) const>(&Vec3f::operator*),
|
||||
[](const float s, const Vec3f& v) { return v * s; }),
|
||||
|
||||
sol::meta_function::division,
|
||||
sol::overload(sol::resolve<Vec3f(const float&) const>(&Vec3f::operator/),
|
||||
sol::resolve<Vec3f(const Vec3f&) const>(&Vec3f::operator/)),
|
||||
|
||||
"length", &Vec3f::length, "length_2d", &Vec3f::length_2d, "length_sqr", &Vec3f::length_sqr,
|
||||
"normalized", &Vec3f::normalized, "dot", &Vec3f::dot, "cross", &Vec3f::cross, "distance_to",
|
||||
&Vec3f::distance_to, "distance_to_sqr", &Vec3f::distance_to_sqr, "sum",
|
||||
sol::resolve<float() const>(&Vec3f::sum), "sum_2d", &Vec3f::sum_2d, "point_to_same_direction",
|
||||
&Vec3f::point_to_same_direction, "as_array", &Vec3f::as_array,
|
||||
|
||||
"abs",
|
||||
[](const Vec3f& v)
|
||||
{
|
||||
Vec3f copy = v;
|
||||
copy.abs();
|
||||
return copy;
|
||||
},
|
||||
|
||||
"angle_between",
|
||||
[](const Vec3f& self,
|
||||
const Vec3f& other) -> std::tuple<sol::optional<float>, sol::optional<std::string>>
|
||||
{
|
||||
auto result = self.angle_between(other);
|
||||
if (result)
|
||||
return std::make_tuple(sol::optional<float>(result->as_degrees()),
|
||||
sol::optional<std::string>(sol::nullopt));
|
||||
return std::make_tuple(sol::optional<float>(sol::nullopt),
|
||||
sol::optional<std::string>("impossible angle (zero-length vector)"));
|
||||
},
|
||||
|
||||
"is_perpendicular",
|
||||
[](const Vec3f& self, const Vec3f& other, sol::optional<float> eps)
|
||||
{ return self.is_perpendicular(other, eps.value_or(0.0001f)); },
|
||||
|
||||
"as_table",
|
||||
[](const Vec3f& v, sol::this_state s) -> sol::table
|
||||
{
|
||||
sol::state_view lua(s);
|
||||
sol::table t = lua.create_table();
|
||||
t["x"] = v.x;
|
||||
t["y"] = v.y;
|
||||
t["z"] = v.z;
|
||||
return t;
|
||||
});
|
||||
}
|
||||
} // namespace omath::lua::detail
|
||||
#endif
|
||||
62
source/lua/lua_vec4.cpp
Normal file
62
source/lua/lua_vec4.cpp
Normal file
@@ -0,0 +1,62 @@
|
||||
//
|
||||
// Created by orange on 07.03.2026.
|
||||
//
|
||||
#ifdef OMATH_ENABLE_LUA
|
||||
#include "omath/lua/lua.hpp"
|
||||
#include <sol/sol.hpp>
|
||||
#include <omath/linear_algebra/vector4.hpp>
|
||||
|
||||
namespace omath::lua
|
||||
{
|
||||
void LuaInterpreter::register_vec4(sol::table& omath_table)
|
||||
{
|
||||
using Vec4f = omath::Vector4<float>;
|
||||
|
||||
omath_table.new_usertype<Vec4f>(
|
||||
"Vec4", sol::constructors<Vec4f(), Vec4f(float, float, float, float)>(),
|
||||
|
||||
"x", sol::property([](const Vec4f& v) { return v.x; }, [](Vec4f& v, float val) { v.x = val; }),
|
||||
"y", sol::property([](const Vec4f& v) { return v.y; }, [](Vec4f& v, float val) { v.y = val; }),
|
||||
"z", sol::property([](const Vec4f& v) { return v.z; }, [](Vec4f& v, float val) { v.z = val; }),
|
||||
"w", sol::property([](const Vec4f& v) { return v.w; }, [](Vec4f& v, float val) { v.w = val; }),
|
||||
|
||||
sol::meta_function::addition, sol::resolve<Vec4f(const Vec4f&) const>(&Vec4f::operator+),
|
||||
sol::meta_function::subtraction, sol::resolve<Vec4f(const Vec4f&) const>(&Vec4f::operator-),
|
||||
sol::meta_function::unary_minus, sol::resolve<Vec4f() const>(&Vec4f::operator-),
|
||||
sol::meta_function::equal_to, &Vec4f::operator==,
|
||||
sol::meta_function::less_than, sol::resolve<bool(const Vec4f&) const>(&Vec4f::operator<),
|
||||
sol::meta_function::less_than_or_equal_to, sol::resolve<bool(const Vec4f&) const>(&Vec4f::operator<=),
|
||||
sol::meta_function::to_string,
|
||||
[](const Vec4f& v) { return std::format("Vec4({}, {}, {}, {})", v.x, v.y, v.z, v.w); },
|
||||
|
||||
sol::meta_function::multiplication,
|
||||
sol::overload(sol::resolve<Vec4f(const float&) const>(&Vec4f::operator*),
|
||||
sol::resolve<Vec4f(const Vec4f&) const>(&Vec4f::operator*),
|
||||
[](const float s, const Vec4f& v) { return v * s; }),
|
||||
|
||||
sol::meta_function::division,
|
||||
sol::overload(sol::resolve<Vec4f(const float&) const>(&Vec4f::operator/),
|
||||
sol::resolve<Vec4f(const Vec4f&) const>(&Vec4f::operator/)),
|
||||
|
||||
"length", &Vec4f::length,
|
||||
"length_sqr", &Vec4f::length_sqr,
|
||||
"dot", &Vec4f::dot,
|
||||
"sum", &Vec4f::sum,
|
||||
|
||||
"abs",
|
||||
[](const Vec4f& v)
|
||||
{
|
||||
Vec4f copy = v;
|
||||
copy.abs();
|
||||
return copy;
|
||||
},
|
||||
|
||||
"clamp",
|
||||
[](Vec4f& v, float mn, float mx)
|
||||
{
|
||||
v.clamp(mn, mx);
|
||||
return v;
|
||||
});
|
||||
}
|
||||
} // namespace omath::lua::detail
|
||||
#endif
|
||||
@@ -3,9 +3,9 @@
|
||||
//
|
||||
#include "omath/pathfinding/navigation_mesh.hpp"
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace omath::pathfinding
|
||||
{
|
||||
std::expected<Vector3<float>, std::string>
|
||||
@@ -30,77 +30,72 @@ namespace omath::pathfinding
|
||||
return m_vertex_map.empty();
|
||||
}
|
||||
|
||||
std::vector<uint8_t> NavigationMesh::serialize() const noexcept
|
||||
void NavigationMesh::set_event(const Vector3<float>& vertex, const std::string_view& event_id)
|
||||
{
|
||||
std::vector<std::uint8_t> raw;
|
||||
if (!m_vertex_map.contains(vertex))
|
||||
throw std::invalid_argument(std::format("Vertex '{}' not found", vertex));
|
||||
|
||||
// Pre-calculate total size for better performance
|
||||
std::size_t total_size = 0;
|
||||
for (const auto& [vertex, neighbors] : m_vertex_map)
|
||||
{
|
||||
total_size += sizeof(vertex) + sizeof(std::uint16_t) + sizeof(Vector3<float>) * neighbors.size();
|
||||
}
|
||||
raw.reserve(total_size);
|
||||
|
||||
auto dump_to_vector = [&raw]<typename T>(const T& t)
|
||||
{
|
||||
const auto* byte_ptr = reinterpret_cast<const std::uint8_t*>(&t);
|
||||
raw.insert(raw.end(), byte_ptr, byte_ptr + sizeof(T));
|
||||
};
|
||||
|
||||
for (const auto& [vertex, neighbors] : m_vertex_map)
|
||||
{
|
||||
// Clamp neighbors count to fit in uint16_t (prevents silent data corruption)
|
||||
// NOTE: If neighbors.size() > 65535, only the first 65535 neighbors will be serialized.
|
||||
// This is a limitation of the current serialization format using uint16_t for count.
|
||||
const auto clamped_count =
|
||||
std::min<std::size_t>(neighbors.size(), std::numeric_limits<std::uint16_t>::max());
|
||||
const auto neighbors_count = static_cast<std::uint16_t>(clamped_count);
|
||||
|
||||
dump_to_vector(vertex);
|
||||
dump_to_vector(neighbors_count);
|
||||
|
||||
// Only serialize up to the clamped count
|
||||
for (std::size_t i = 0; i < clamped_count; ++i)
|
||||
dump_to_vector(neighbors[i]);
|
||||
}
|
||||
return raw;
|
||||
m_vertex_events[vertex] = event_id;
|
||||
}
|
||||
|
||||
void NavigationMesh::deserialize(const std::vector<uint8_t>& raw) noexcept
|
||||
void NavigationMesh::clear_event(const Vector3<float>& vertex)
|
||||
{
|
||||
auto load_from_vector = [](const std::vector<uint8_t>& vec, std::size_t& offset, auto& value)
|
||||
m_vertex_events.erase(vertex);
|
||||
}
|
||||
|
||||
std::optional<std::string> NavigationMesh::get_event(const Vector3<float>& vertex) const noexcept
|
||||
{
|
||||
const auto it = m_vertex_events.find(vertex);
|
||||
if (it == m_vertex_events.end())
|
||||
return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
|
||||
// Serialization format per vertex line:
|
||||
// x y z neighbor_count event_id
|
||||
// where event_id is "-" when no event is set.
|
||||
// Neighbor lines follow: nx ny nz
|
||||
|
||||
std::string NavigationMesh::serialize() const noexcept
|
||||
{
|
||||
std::ostringstream oss;
|
||||
for (const auto& [vertex, neighbors] : m_vertex_map)
|
||||
{
|
||||
if (offset + sizeof(value) > vec.size())
|
||||
throw std::runtime_error("Deserialize: Invalid input data size.");
|
||||
const auto event_it = m_vertex_events.find(vertex);
|
||||
const std::string& event = (event_it != m_vertex_events.end()) ? event_it->second : "-";
|
||||
|
||||
std::copy_n(vec.data() + offset, sizeof(value), reinterpret_cast<uint8_t*>(&value));
|
||||
offset += sizeof(value);
|
||||
};
|
||||
oss << vertex.x << ' ' << vertex.y << ' ' << vertex.z << ' ' << neighbors.size() << ' ' << event << '\n';
|
||||
|
||||
for (const auto& n : neighbors)
|
||||
oss << n.x << ' ' << n.y << ' ' << n.z << '\n';
|
||||
}
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
void NavigationMesh::deserialize(const std::string& raw)
|
||||
{
|
||||
m_vertex_map.clear();
|
||||
m_vertex_events.clear();
|
||||
std::istringstream iss(raw);
|
||||
|
||||
std::size_t offset = 0;
|
||||
|
||||
while (offset < raw.size())
|
||||
Vector3<float> vertex;
|
||||
std::size_t neighbors_count;
|
||||
std::string event;
|
||||
while (iss >> vertex.x >> vertex.y >> vertex.z >> neighbors_count >> event)
|
||||
{
|
||||
Vector3<float> vertex;
|
||||
load_from_vector(raw, offset, vertex);
|
||||
|
||||
std::uint16_t neighbors_count;
|
||||
load_from_vector(raw, offset, neighbors_count);
|
||||
|
||||
std::vector<Vector3<float>> neighbors;
|
||||
neighbors.reserve(neighbors_count);
|
||||
|
||||
for (std::size_t i = 0; i < neighbors_count; ++i)
|
||||
{
|
||||
Vector3<float> neighbor;
|
||||
load_from_vector(raw, offset, neighbor);
|
||||
neighbors.push_back(neighbor);
|
||||
Vector3<float> n;
|
||||
if (!(iss >> n.x >> n.y >> n.z))
|
||||
throw std::runtime_error("Deserialize: Unexpected end of data.");
|
||||
neighbors.push_back(n);
|
||||
}
|
||||
|
||||
m_vertex_map.emplace(vertex, std::move(neighbors));
|
||||
|
||||
if (event != "-")
|
||||
m_vertex_events.emplace(vertex, std::move(event));
|
||||
}
|
||||
}
|
||||
} // namespace omath::pathfinding
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <array>
|
||||
#include <fstream>
|
||||
#include <omath/utility/elf_pattern_scan.hpp>
|
||||
#include <span>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
@@ -140,6 +141,87 @@ namespace
|
||||
std::uintptr_t raw_base_addr{};
|
||||
std::vector<std::byte> data;
|
||||
};
|
||||
template<FileArch arch>
|
||||
std::optional<ExtractedSection> get_elf_section_from_memory_impl(const std::span<const std::byte> data,
|
||||
const std::string_view& section_name)
|
||||
{
|
||||
using FH = typename ElfHeaders<arch>::FileHeader;
|
||||
using SH = typename ElfHeaders<arch>::SectionHeader;
|
||||
|
||||
if (data.size() < sizeof(FH))
|
||||
return std::nullopt;
|
||||
|
||||
const auto* file_header = reinterpret_cast<const FH*>(data.data());
|
||||
|
||||
const auto shoff = static_cast<std::size_t>(file_header->e_shoff);
|
||||
const auto shnum = static_cast<std::size_t>(file_header->e_shnum);
|
||||
const auto shstrndx = static_cast<std::size_t>(file_header->e_shstrndx);
|
||||
|
||||
const auto shstrtab_hdr_off = shoff + shstrndx * sizeof(SH);
|
||||
if (shstrtab_hdr_off + sizeof(SH) > data.size())
|
||||
return std::nullopt;
|
||||
|
||||
const auto* shstrtab_hdr = reinterpret_cast<const SH*>(data.data() + shstrtab_hdr_off);
|
||||
const auto shstrtab_off = static_cast<std::size_t>(shstrtab_hdr->sh_offset);
|
||||
const auto shstrtab_size = static_cast<std::size_t>(shstrtab_hdr->sh_size);
|
||||
|
||||
if (shstrtab_off + shstrtab_size > data.size())
|
||||
return std::nullopt;
|
||||
|
||||
const auto* shstrtab = reinterpret_cast<const char*>(data.data() + shstrtab_off);
|
||||
|
||||
for (std::size_t i = 0; i < shnum; ++i)
|
||||
{
|
||||
const auto sect_hdr_off = shoff + i * sizeof(SH);
|
||||
if (sect_hdr_off + sizeof(SH) > data.size())
|
||||
continue;
|
||||
|
||||
const auto* section = reinterpret_cast<const SH*>(data.data() + sect_hdr_off);
|
||||
|
||||
if (std::cmp_greater_equal(section->sh_name, shstrtab_size))
|
||||
continue;
|
||||
|
||||
if (std::string_view{shstrtab + section->sh_name} != section_name)
|
||||
continue;
|
||||
|
||||
const auto raw_off = static_cast<std::size_t>(section->sh_offset);
|
||||
const auto sec_size = static_cast<std::size_t>(section->sh_size);
|
||||
|
||||
if (raw_off + sec_size > data.size())
|
||||
return std::nullopt;
|
||||
|
||||
ExtractedSection out;
|
||||
out.virtual_base_addr = static_cast<std::uintptr_t>(section->sh_addr);
|
||||
out.raw_base_addr = raw_off;
|
||||
out.data.assign(data.data() + raw_off, data.data() + raw_off + sec_size);
|
||||
return out;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<ExtractedSection> get_elf_section_by_name_from_memory(const std::span<const std::byte> data,
|
||||
const std::string_view& section_name)
|
||||
{
|
||||
constexpr std::string_view valid_elf_signature = "\x7F"
|
||||
"ELF";
|
||||
if (data.size() < ei_nident)
|
||||
return std::nullopt;
|
||||
|
||||
if (std::string_view{reinterpret_cast<const char*>(data.data()), valid_elf_signature.size()}
|
||||
!= valid_elf_signature)
|
||||
return std::nullopt;
|
||||
|
||||
const auto class_byte = static_cast<uint8_t>(data[ei_class]);
|
||||
|
||||
if (class_byte == elfclass64)
|
||||
return get_elf_section_from_memory_impl<FileArch::x64>(data, section_name);
|
||||
|
||||
if (class_byte == elfclass32)
|
||||
return get_elf_section_from_memory_impl<FileArch::x32>(data, section_name);
|
||||
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[maybe_unused]]
|
||||
std::optional<ExtractedSection> get_elf_section_by_name(const std::filesystem::path& path,
|
||||
const std::string_view& section_name)
|
||||
@@ -322,4 +404,27 @@ namespace omath
|
||||
.raw_base_addr = pe_section->raw_base_addr,
|
||||
.target_offset = offset};
|
||||
}
|
||||
|
||||
std::optional<SectionScanResult>
|
||||
ElfPatternScanner::scan_for_pattern_in_memory_file(const std::span<const std::byte> file_data,
|
||||
const std::string_view& pattern,
|
||||
const std::string_view& target_section_name)
|
||||
{
|
||||
const auto section = get_elf_section_by_name_from_memory(file_data, target_section_name);
|
||||
|
||||
if (!section.has_value()) [[unlikely]]
|
||||
return std::nullopt;
|
||||
|
||||
const auto scan_result =
|
||||
PatternScanner::scan_for_pattern(section->data.cbegin(), section->data.cend(), pattern);
|
||||
|
||||
if (scan_result == section->data.cend())
|
||||
return std::nullopt;
|
||||
|
||||
const auto offset = std::distance(section->data.begin(), scan_result);
|
||||
|
||||
return SectionScanResult{.virtual_base_addr = section->virtual_base_addr,
|
||||
.raw_base_addr = section->raw_base_addr,
|
||||
.target_offset = offset};
|
||||
}
|
||||
} // namespace omath
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "omath/utility/pattern_scan.hpp"
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <span>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
@@ -231,6 +232,96 @@ namespace
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
template<typename HeaderType, typename SegmentType, typename SectionType, std::uint32_t segment_cmd>
|
||||
std::optional<ExtractedSection> extract_section_from_memory_impl(const std::span<const std::byte> data,
|
||||
const std::string_view& section_name)
|
||||
{
|
||||
if (data.size() < sizeof(HeaderType))
|
||||
return std::nullopt;
|
||||
|
||||
const auto* header = reinterpret_cast<const HeaderType*>(data.data());
|
||||
|
||||
std::size_t cmd_offset = sizeof(HeaderType);
|
||||
|
||||
for (std::uint32_t i = 0; i < header->ncmds; ++i)
|
||||
{
|
||||
if (cmd_offset + sizeof(LoadCommand) > data.size())
|
||||
return std::nullopt;
|
||||
|
||||
const auto* lc = reinterpret_cast<const LoadCommand*>(data.data() + cmd_offset);
|
||||
|
||||
if (lc->cmd != segment_cmd)
|
||||
{
|
||||
cmd_offset += lc->cmdsize;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (cmd_offset + sizeof(SegmentType) > data.size())
|
||||
return std::nullopt;
|
||||
|
||||
const auto* segment = reinterpret_cast<const SegmentType*>(data.data() + cmd_offset);
|
||||
|
||||
if (!segment->nsects)
|
||||
{
|
||||
cmd_offset += lc->cmdsize;
|
||||
continue;
|
||||
}
|
||||
|
||||
std::size_t sect_offset = cmd_offset + sizeof(SegmentType);
|
||||
|
||||
for (std::uint32_t j = 0; j < segment->nsects; ++j)
|
||||
{
|
||||
if (sect_offset + sizeof(SectionType) > data.size())
|
||||
return std::nullopt;
|
||||
|
||||
const auto* section = reinterpret_cast<const SectionType*>(data.data() + sect_offset);
|
||||
|
||||
if (get_section_name(section->sectname) != section_name)
|
||||
{
|
||||
sect_offset += sizeof(SectionType);
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto raw_off = static_cast<std::size_t>(section->offset);
|
||||
const auto sec_size = static_cast<std::size_t>(section->size);
|
||||
|
||||
if (raw_off + sec_size > data.size())
|
||||
return std::nullopt;
|
||||
|
||||
ExtractedSection out;
|
||||
out.virtual_base_addr = static_cast<std::uintptr_t>(section->addr);
|
||||
out.raw_base_addr = raw_off;
|
||||
out.data.assign(data.data() + raw_off, data.data() + raw_off + sec_size);
|
||||
return out;
|
||||
}
|
||||
|
||||
cmd_offset += lc->cmdsize;
|
||||
}
|
||||
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
std::optional<ExtractedSection> get_macho_section_by_name_from_memory(const std::span<const std::byte> data,
|
||||
const std::string_view& section_name)
|
||||
{
|
||||
if (data.size() < sizeof(std::uint32_t))
|
||||
return std::nullopt;
|
||||
|
||||
std::uint32_t magic{};
|
||||
std::memcpy(&magic, data.data(), sizeof(magic));
|
||||
|
||||
if (magic == mh_magic_64 || magic == mh_cigam_64)
|
||||
return extract_section_from_memory_impl<MachHeader64, SegmentCommand64, Section64, lc_segment_64>(
|
||||
data, section_name);
|
||||
|
||||
if (magic == mh_magic_32 || magic == mh_cigam_32)
|
||||
return extract_section_from_memory_impl<MachHeader32, SegmentCommand32, Section32, lc_segment>(data,
|
||||
section_name);
|
||||
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
std::optional<ExtractedSection> get_macho_section_by_name(const std::filesystem::path& path,
|
||||
const std::string_view& section_name)
|
||||
@@ -346,4 +437,27 @@ namespace omath
|
||||
.raw_base_addr = macho_section->raw_base_addr,
|
||||
.target_offset = offset};
|
||||
}
|
||||
|
||||
std::optional<SectionScanResult>
|
||||
MachOPatternScanner::scan_for_pattern_in_memory_file(const std::span<const std::byte> file_data,
|
||||
const std::string_view& pattern,
|
||||
const std::string_view& target_section_name)
|
||||
{
|
||||
const auto section = get_macho_section_by_name_from_memory(file_data, target_section_name);
|
||||
|
||||
if (!section.has_value()) [[unlikely]]
|
||||
return std::nullopt;
|
||||
|
||||
const auto scan_result =
|
||||
PatternScanner::scan_for_pattern(section->data.cbegin(), section->data.cend(), pattern);
|
||||
|
||||
if (scan_result == section->data.cend())
|
||||
return std::nullopt;
|
||||
|
||||
const auto offset = std::distance(section->data.begin(), scan_result);
|
||||
|
||||
return SectionScanResult{.virtual_base_addr = section->virtual_base_addr,
|
||||
.raw_base_addr = section->raw_base_addr,
|
||||
.target_offset = offset};
|
||||
}
|
||||
} // namespace omath
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <span>
|
||||
#include <stdexcept>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
// Internal PE shit defines
|
||||
// Big thx for linuxpe sources as ref
|
||||
@@ -244,6 +245,78 @@ namespace
|
||||
std::vector<std::byte> data;
|
||||
};
|
||||
|
||||
[[nodiscard]]
|
||||
std::optional<ExtractedSection> extract_section_from_pe_memory(const std::span<const std::byte> data,
|
||||
const std::string_view& section_name)
|
||||
{
|
||||
if (data.size() < sizeof(DosHeader))
|
||||
return std::nullopt;
|
||||
|
||||
const auto* dos_header = reinterpret_cast<const DosHeader*>(data.data());
|
||||
|
||||
if (invalid_dos_header_file(*dos_header))
|
||||
return std::nullopt;
|
||||
|
||||
const auto nt_off = static_cast<std::size_t>(dos_header->e_lfanew);
|
||||
|
||||
if (nt_off + sizeof(ImageNtHeaders<NtArchitecture::x32_bit>) > data.size())
|
||||
return std::nullopt;
|
||||
|
||||
const auto* x86_hdrs =
|
||||
reinterpret_cast<const ImageNtHeaders<NtArchitecture::x32_bit>*>(data.data() + nt_off);
|
||||
|
||||
NtHeaderVariant nt_headers;
|
||||
if (x86_hdrs->optional_header.magic == opt_hdr32_magic)
|
||||
nt_headers = *x86_hdrs;
|
||||
else if (x86_hdrs->optional_header.magic == opt_hdr64_magic)
|
||||
{
|
||||
if (nt_off + sizeof(ImageNtHeaders<NtArchitecture::x64_bit>) > data.size())
|
||||
return std::nullopt;
|
||||
nt_headers = *reinterpret_cast<const ImageNtHeaders<NtArchitecture::x64_bit>*>(data.data() + nt_off);
|
||||
}
|
||||
else
|
||||
return std::nullopt;
|
||||
|
||||
if (invalid_nt_header_file(nt_headers))
|
||||
return std::nullopt;
|
||||
|
||||
return std::visit(
|
||||
[&data, §ion_name, nt_off](const auto& concrete_headers) -> std::optional<ExtractedSection>
|
||||
{
|
||||
constexpr std::size_t sig_size = sizeof(concrete_headers.signature);
|
||||
const auto section_table_off = nt_off + sig_size + sizeof(FileHeader)
|
||||
+ concrete_headers.file_header.size_optional_header;
|
||||
|
||||
for (std::size_t i = 0; i < concrete_headers.file_header.num_sections; ++i)
|
||||
{
|
||||
const auto sh_off = section_table_off + i * sizeof(SectionHeader);
|
||||
if (sh_off + sizeof(SectionHeader) > data.size())
|
||||
return std::nullopt;
|
||||
|
||||
const auto* section = reinterpret_cast<const SectionHeader*>(data.data() + sh_off);
|
||||
|
||||
if (std::string_view(section->name) != section_name)
|
||||
continue;
|
||||
|
||||
const auto raw_off = static_cast<std::size_t>(section->ptr_raw_data);
|
||||
const auto raw_size = static_cast<std::size_t>(section->size_raw_data);
|
||||
|
||||
if (raw_off + raw_size > data.size())
|
||||
return std::nullopt;
|
||||
|
||||
std::vector<std::byte> section_data(data.data() + raw_off, data.data() + raw_off + raw_size);
|
||||
|
||||
return ExtractedSection{
|
||||
.virtual_base_addr = static_cast<std::uintptr_t>(
|
||||
section->virtual_address + concrete_headers.optional_header.image_base),
|
||||
.raw_base_addr = raw_off,
|
||||
.data = std::move(section_data)};
|
||||
}
|
||||
return std::nullopt;
|
||||
},
|
||||
nt_headers);
|
||||
}
|
||||
|
||||
[[nodiscard]]
|
||||
std::optional<ExtractedSection> extract_section_from_pe_file(const std::filesystem::path& path_to_file,
|
||||
const std::string_view& section_name)
|
||||
@@ -383,4 +456,27 @@ namespace omath
|
||||
.raw_base_addr = pe_section->raw_base_addr,
|
||||
.target_offset = offset};
|
||||
}
|
||||
|
||||
std::optional<SectionScanResult>
|
||||
PePatternScanner::scan_for_pattern_in_memory_file(const std::span<const std::byte> file_data,
|
||||
const std::string_view& pattern,
|
||||
const std::string_view& target_section_name)
|
||||
{
|
||||
const auto pe_section = extract_section_from_pe_memory(file_data, target_section_name);
|
||||
|
||||
if (!pe_section.has_value()) [[unlikely]]
|
||||
return std::nullopt;
|
||||
|
||||
const auto scan_result =
|
||||
PatternScanner::scan_for_pattern(pe_section->data.cbegin(), pe_section->data.cend(), pattern);
|
||||
|
||||
if (scan_result == pe_section->data.cend())
|
||||
return std::nullopt;
|
||||
|
||||
const auto offset = std::distance(pe_section->data.begin(), scan_result);
|
||||
|
||||
return SectionScanResult{.virtual_base_addr = pe_section->virtual_base_addr,
|
||||
.raw_base_addr = pe_section->raw_base_addr,
|
||||
.target_offset = offset};
|
||||
}
|
||||
} // namespace omath
|
||||
@@ -4,8 +4,8 @@ project(unit_tests)
|
||||
|
||||
include(GoogleTest)
|
||||
|
||||
file(GLOB_RECURSE UNIT_TESTS_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp")
|
||||
add_executable(${PROJECT_NAME} ${UNIT_TESTS_SOURCES})
|
||||
file(GLOB_RECURSE UNIT_TESTS_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/general/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/engines/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/*.hpp")
|
||||
add_executable(${PROJECT_NAME} ${UNIT_TESTS_SOURCES} main.cpp)
|
||||
|
||||
set_target_properties(
|
||||
${PROJECT_NAME}
|
||||
@@ -22,6 +22,16 @@ else() # GTest is being linked as vcpkg package
|
||||
target_link_libraries(${PROJECT_NAME} PRIVATE GTest::gtest GTest::gtest_main omath::omath)
|
||||
endif()
|
||||
|
||||
if (OMATH_ENABLE_LUA)
|
||||
file(GLOB_RECURSE UNIT_TESTS_SOURCES_LUA CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/lua/*.cpp")
|
||||
target_compile_definitions(${PROJECT_NAME} PRIVATE LUA_SCRIPTS_DIR="${CMAKE_CURRENT_SOURCE_DIR}/lua")
|
||||
target_sources(${PROJECT_NAME} PRIVATE ${UNIT_TESTS_SOURCES_LUA})
|
||||
if (EMSCRIPTEN)
|
||||
target_link_options(${PROJECT_NAME} PRIVATE
|
||||
"SHELL:--embed-file ${CMAKE_CURRENT_SOURCE_DIR}/lua@${CMAKE_CURRENT_SOURCE_DIR}/lua")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(OMATH_ENABLE_COVERAGE)
|
||||
include(${CMAKE_SOURCE_DIR}/cmake/Coverage.cmake)
|
||||
omath_setup_coverage(${PROJECT_NAME})
|
||||
@@ -36,3 +46,4 @@ endif()
|
||||
if(NOT (ANDROID OR IOS OR EMSCRIPTEN))
|
||||
gtest_discover_tests(${PROJECT_NAME})
|
||||
endif()
|
||||
|
||||
|
||||
192
tests/general/mem_fd_helper.hpp
Normal file
192
tests/general/mem_fd_helper.hpp
Normal file
@@ -0,0 +1,192 @@
|
||||
#pragma once
|
||||
// Cross-platform helper for creating binary test "files" without writing to disk where possible.
|
||||
//
|
||||
// Strategy:
|
||||
// - Linux (non-Android, or Android API >= 30): memfd_create → /proc/self/fd/<N> (no disk I/O)
|
||||
// - All other platforms: anonymous temp file via std::tmpfile(), accessed via /proc/self/fd/<N>
|
||||
// on Linux, or a named temp file (cleaned up on destruction) elsewhere.
|
||||
//
|
||||
// Usage:
|
||||
// auto f = MemFdFile::create(myVector);
|
||||
// ASSERT_TRUE(f.valid());
|
||||
// scanner.scan_for_pattern_in_file(f.path(), ...);
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#if defined(__linux__)
|
||||
# include <unistd.h>
|
||||
# include <fcntl.h>
|
||||
# if defined(__ANDROID__)
|
||||
# if __ANDROID_API__ >= 30
|
||||
# include <sys/mman.h>
|
||||
# define OMATH_TEST_USE_MEMFD 1
|
||||
# endif
|
||||
// Android < 30: fall through to tmpfile() path below
|
||||
# else
|
||||
// Desktop Linux: memfd_create available since glibc 2.27 / kernel 3.17
|
||||
# include <sys/mman.h>
|
||||
# define OMATH_TEST_USE_MEMFD 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
class MemFdFile
|
||||
{
|
||||
public:
|
||||
MemFdFile() = default;
|
||||
|
||||
~MemFdFile()
|
||||
{
|
||||
#if defined(OMATH_TEST_USE_MEMFD)
|
||||
if (m_fd >= 0)
|
||||
::close(m_fd);
|
||||
#else
|
||||
if (!m_temp_path.empty())
|
||||
std::filesystem::remove(m_temp_path);
|
||||
#endif
|
||||
}
|
||||
|
||||
MemFdFile(const MemFdFile&) = delete;
|
||||
MemFdFile& operator=(const MemFdFile&) = delete;
|
||||
|
||||
MemFdFile(MemFdFile&& o) noexcept
|
||||
: m_path(std::move(o.m_path))
|
||||
#if defined(OMATH_TEST_USE_MEMFD)
|
||||
, m_fd(o.m_fd)
|
||||
#else
|
||||
, m_temp_path(std::move(o.m_temp_path))
|
||||
#endif
|
||||
{
|
||||
#if defined(OMATH_TEST_USE_MEMFD)
|
||||
o.m_fd = -1;
|
||||
#else
|
||||
o.m_temp_path.clear();
|
||||
#endif
|
||||
}
|
||||
|
||||
[[nodiscard]] bool valid() const { return !m_path.empty(); }
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& path() const { return m_path; }
|
||||
|
||||
static MemFdFile create(const std::vector<std::uint8_t>& data)
|
||||
{
|
||||
return create(data.data(), data.size());
|
||||
}
|
||||
|
||||
static MemFdFile create(const std::uint8_t* data, std::size_t size)
|
||||
{
|
||||
MemFdFile f;
|
||||
|
||||
#if defined(OMATH_TEST_USE_MEMFD)
|
||||
f.m_fd = static_cast<int>(::memfd_create("test_bin", 0));
|
||||
if (f.m_fd < 0)
|
||||
return f;
|
||||
|
||||
if (!write_all(f.m_fd, data, size))
|
||||
{
|
||||
::close(f.m_fd);
|
||||
f.m_fd = -1;
|
||||
return f;
|
||||
}
|
||||
f.m_path = "/proc/self/fd/" + std::to_string(f.m_fd);
|
||||
|
||||
#else
|
||||
// Portable fallback: write to a uniquely-named temp file and delete on destruction
|
||||
const auto tmp_dir = std::filesystem::temp_directory_path();
|
||||
std::mt19937_64 rng(std::random_device{}());
|
||||
const auto unique_name = "omath_test_" + std::to_string(rng()) + ".bin";
|
||||
f.m_temp_path = (tmp_dir / unique_name).string();
|
||||
f.m_path = f.m_temp_path;
|
||||
|
||||
std::ofstream out(f.m_temp_path, std::ios::binary | std::ios::trunc);
|
||||
if (!out.is_open())
|
||||
{
|
||||
f.m_temp_path.clear();
|
||||
f.m_path.clear();
|
||||
return f;
|
||||
}
|
||||
out.write(reinterpret_cast<const char*>(data), static_cast<std::streamsize>(size));
|
||||
if (!out)
|
||||
{
|
||||
out.close();
|
||||
std::filesystem::remove(f.m_temp_path);
|
||||
f.m_temp_path.clear();
|
||||
f.m_path.clear();
|
||||
}
|
||||
#endif
|
||||
return f;
|
||||
}
|
||||
|
||||
private:
|
||||
std::filesystem::path m_path;
|
||||
|
||||
#if defined(OMATH_TEST_USE_MEMFD)
|
||||
int m_fd = -1;
|
||||
|
||||
static bool write_all(int fd, const std::uint8_t* data, std::size_t size)
|
||||
{
|
||||
std::size_t written = 0;
|
||||
while (written < size)
|
||||
{
|
||||
const auto n = ::write(fd, data + written, size - written);
|
||||
if (n <= 0)
|
||||
return false;
|
||||
written += static_cast<std::size_t>(n);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
#else
|
||||
std::string m_temp_path;
|
||||
#endif
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Build a minimal PE binary in-memory with a single .text section.
|
||||
// Layout (all offsets compile-time):
|
||||
// 0x00: DOS header (64 B) 0x40: pad 0x80: NT sig 0x84: FileHeader (20 B)
|
||||
// 0x98: OptionalHeader (0xF0 B) 0x188: SectionHeader (44 B) 0x1B4: section data
|
||||
// ---------------------------------------------------------------------------
|
||||
inline std::vector<std::uint8_t> build_minimal_pe(const std::vector<std::uint8_t>& section_bytes)
|
||||
{
|
||||
constexpr std::uint32_t e_lfanew = 0x80u;
|
||||
constexpr std::uint16_t size_opt = 0xF0u;
|
||||
constexpr std::size_t nt_off = e_lfanew;
|
||||
constexpr std::size_t fh_off = nt_off + 4;
|
||||
constexpr std::size_t oh_off = fh_off + 20;
|
||||
constexpr std::size_t sh_off = oh_off + size_opt;
|
||||
constexpr std::size_t data_off = sh_off + 44;
|
||||
|
||||
std::vector<std::uint8_t> buf(data_off + section_bytes.size(), 0u);
|
||||
|
||||
buf[0] = 'M'; buf[1] = 'Z';
|
||||
std::memcpy(buf.data() + 0x3Cu, &e_lfanew, 4);
|
||||
|
||||
buf[nt_off] = 'P'; buf[nt_off + 1] = 'E';
|
||||
|
||||
const std::uint16_t machine = 0x8664u, num_sections = 1u;
|
||||
std::memcpy(buf.data() + fh_off, &machine, 2);
|
||||
std::memcpy(buf.data() + fh_off + 2, &num_sections, 2);
|
||||
std::memcpy(buf.data() + fh_off + 16, &size_opt, 2);
|
||||
|
||||
const std::uint16_t magic = 0x20Bu;
|
||||
std::memcpy(buf.data() + oh_off, &magic, 2);
|
||||
|
||||
const char name[8] = {'.','t','e','x','t',0,0,0};
|
||||
std::memcpy(buf.data() + sh_off, name, 8);
|
||||
|
||||
const auto vsize = static_cast<std::uint32_t>(section_bytes.size());
|
||||
const std::uint32_t vaddr = 0x1000u;
|
||||
const auto ptr_raw = static_cast<std::uint32_t>(data_off);
|
||||
std::memcpy(buf.data() + sh_off + 8, &vsize, 4);
|
||||
std::memcpy(buf.data() + sh_off + 12, &vaddr, 4);
|
||||
std::memcpy(buf.data() + sh_off + 16, &vsize, 4);
|
||||
std::memcpy(buf.data() + sh_off + 20, &ptr_raw, 4);
|
||||
|
||||
std::memcpy(buf.data() + data_off, section_bytes.data(), section_bytes.size());
|
||||
return buf;
|
||||
}
|
||||
@@ -8,6 +8,29 @@
|
||||
using namespace omath;
|
||||
using namespace omath::pathfinding;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static NavigationMesh make_linear_chain(int length)
|
||||
{
|
||||
// 0 -> 1 -> 2 -> ... -> length-1 (directed)
|
||||
NavigationMesh nav;
|
||||
for (int i = 0; i < length; ++i)
|
||||
{
|
||||
const Vector3<float> v{static_cast<float>(i), 0.f, 0.f};
|
||||
if (i + 1 < length)
|
||||
nav.m_vertex_map[v] = {Vector3<float>{static_cast<float>(i + 1), 0.f, 0.f}};
|
||||
else
|
||||
nav.m_vertex_map[v] = {};
|
||||
}
|
||||
return nav;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Basic reachability
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AStarExtra, TrivialNeighbor)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
@@ -78,7 +101,7 @@ TEST(AStarExtra, LongerPathAvoidsBlock)
|
||||
constexpr Vector3<float> goal = idx(2, 1);
|
||||
const auto path = Astar::find_path(start, goal, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.front(), goal); // Astar convention: single-element or endpoint present
|
||||
EXPECT_EQ(path.front(), goal);
|
||||
}
|
||||
|
||||
TEST(AstarTests, TrivialDirectNeighborPath)
|
||||
@@ -91,9 +114,6 @@ TEST(AstarTests, TrivialDirectNeighborPath)
|
||||
nav.m_vertex_map.emplace(v2, std::vector<Vector3<float>>{v1});
|
||||
|
||||
const auto path = Astar::find_path(v1, v2, nav);
|
||||
// Current A* implementation returns the end vertex as the reconstructed
|
||||
// path (single-element) in the simple neighbor scenario. Assert that the
|
||||
// endpoint is present and reachable.
|
||||
ASSERT_EQ(path.size(), 1u);
|
||||
EXPECT_EQ(path.front(), v2);
|
||||
}
|
||||
@@ -133,4 +153,155 @@ TEST(unit_test_a_star, finding_right_path)
|
||||
mesh.m_vertex_map[{0.f, 2.f, 0.f}] = {{0.f, 3.f, 0.f}};
|
||||
mesh.m_vertex_map[{0.f, 3.f, 0.f}] = {};
|
||||
std::ignore = omath::pathfinding::Astar::find_path({}, {0.f, 3.f, 0.f}, mesh);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Directed edges
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AstarTests, DirectedEdge_ForwardPathExists)
|
||||
{
|
||||
// A -> B only; path from A to B should succeed
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> a{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> b{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[a] = {b};
|
||||
nav.m_vertex_map[b] = {}; // no edge back
|
||||
|
||||
const auto path = Astar::find_path(a, b, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), b);
|
||||
}
|
||||
|
||||
TEST(AstarTests, DirectedEdge_ReversePathMissing)
|
||||
{
|
||||
// A -> B only; path from B to A should fail
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> a{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> b{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[a] = {b};
|
||||
nav.m_vertex_map[b] = {};
|
||||
|
||||
const auto path = Astar::find_path(b, a, nav);
|
||||
EXPECT_TRUE(path.empty());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Vertex snapping
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AstarTests, OffMeshStart_SnapsToNearestVertex)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> v1{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> v2{10.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[v1] = {v2};
|
||||
nav.m_vertex_map[v2] = {v1};
|
||||
|
||||
// Start is slightly off v1 but closer to it than to v2
|
||||
constexpr Vector3<float> off_start{0.1f, 0.f, 0.f};
|
||||
const auto path = Astar::find_path(off_start, v2, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), v2);
|
||||
}
|
||||
|
||||
TEST(AstarTests, OffMeshEnd_SnapsToNearestVertex)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> v1{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> v2{10.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[v1] = {v2};
|
||||
nav.m_vertex_map[v2] = {v1};
|
||||
|
||||
// Goal is slightly off v2 but closer to it than to v1
|
||||
constexpr Vector3<float> off_goal{9.9f, 0.f, 0.f};
|
||||
const auto path = Astar::find_path(v1, off_goal, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), v2);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Cycle handling
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AstarTests, CyclicGraph_FindsPathWithoutLooping)
|
||||
{
|
||||
// Triangle: A <-> B <-> C <-> A
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> a{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> b{1.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> c{0.5f, 1.f, 0.f};
|
||||
nav.m_vertex_map[a] = {b, c};
|
||||
nav.m_vertex_map[b] = {a, c};
|
||||
nav.m_vertex_map[c] = {a, b};
|
||||
|
||||
const auto path = Astar::find_path(a, c, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), c);
|
||||
}
|
||||
|
||||
TEST(AstarTests, SelfLoopVertex_DoesNotBreakSearch)
|
||||
{
|
||||
// Vertex with itself as a neighbor
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> a{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> b{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[a] = {a, b}; // self-loop on a
|
||||
nav.m_vertex_map[b] = {a};
|
||||
|
||||
const auto path = Astar::find_path(a, b, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), b);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Longer chains
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AstarTests, LinearChain_ReachesEnd)
|
||||
{
|
||||
constexpr int kLength = 10;
|
||||
const NavigationMesh nav = make_linear_chain(kLength);
|
||||
|
||||
const Vector3<float> start{0.f, 0.f, 0.f};
|
||||
const Vector3<float> goal{static_cast<float>(kLength - 1), 0.f, 0.f};
|
||||
|
||||
const auto path = Astar::find_path(start, goal, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), goal);
|
||||
}
|
||||
|
||||
TEST(AstarTests, LinearChain_MidpointReachable)
|
||||
{
|
||||
constexpr int kLength = 6;
|
||||
const NavigationMesh nav = make_linear_chain(kLength);
|
||||
|
||||
const Vector3<float> start{0.f, 0.f, 0.f};
|
||||
const Vector3<float> mid{3.f, 0.f, 0.f};
|
||||
|
||||
const auto path = Astar::find_path(start, mid, nav);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), mid);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Serialize -> pathfind integration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(AstarTests, PathfindAfterSerializeDeserialize)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
constexpr Vector3<float> a{0.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> b{1.f, 0.f, 0.f};
|
||||
constexpr Vector3<float> c{2.f, 0.f, 0.f};
|
||||
nav.m_vertex_map[a] = {b};
|
||||
nav.m_vertex_map[b] = {a, c};
|
||||
nav.m_vertex_map[c] = {b};
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
const auto path = Astar::find_path(a, c, nav2);
|
||||
ASSERT_FALSE(path.empty());
|
||||
EXPECT_EQ(path.back(), c);
|
||||
}
|
||||
|
||||
@@ -26,38 +26,38 @@ protected:
|
||||
TEST_F(UnitTestColorGrouped, Constructor_Float)
|
||||
{
|
||||
constexpr Color color(0.5f, 0.5f, 0.5f, 1.0f);
|
||||
EXPECT_FLOAT_EQ(color.x, 0.5f);
|
||||
EXPECT_FLOAT_EQ(color.y, 0.5f);
|
||||
EXPECT_FLOAT_EQ(color.z, 0.5f);
|
||||
EXPECT_FLOAT_EQ(color.w, 1.0f);
|
||||
EXPECT_FLOAT_EQ(color.value().x, 0.5f);
|
||||
EXPECT_FLOAT_EQ(color.value().y, 0.5f);
|
||||
EXPECT_FLOAT_EQ(color.value().z, 0.5f);
|
||||
EXPECT_FLOAT_EQ(color.value().w, 1.0f);
|
||||
}
|
||||
|
||||
TEST_F(UnitTestColorGrouped, Constructor_Vector4)
|
||||
{
|
||||
constexpr omath::Vector4 vec(0.2f, 0.4f, 0.6f, 0.8f);
|
||||
constexpr Color color(vec);
|
||||
EXPECT_FLOAT_EQ(color.x, 0.2f);
|
||||
EXPECT_FLOAT_EQ(color.y, 0.4f);
|
||||
EXPECT_FLOAT_EQ(color.z, 0.6f);
|
||||
EXPECT_FLOAT_EQ(color.w, 0.8f);
|
||||
EXPECT_FLOAT_EQ(color.value().x, 0.2f);
|
||||
EXPECT_FLOAT_EQ(color.value().y, 0.4f);
|
||||
EXPECT_FLOAT_EQ(color.value().z, 0.6f);
|
||||
EXPECT_FLOAT_EQ(color.value().w, 0.8f);
|
||||
}
|
||||
|
||||
TEST_F(UnitTestColorGrouped, FromRGBA)
|
||||
{
|
||||
constexpr Color color = Color::from_rgba(128, 64, 32, 255);
|
||||
EXPECT_FLOAT_EQ(color.x, 128.0f / 255.0f);
|
||||
EXPECT_FLOAT_EQ(color.y, 64.0f / 255.0f);
|
||||
EXPECT_FLOAT_EQ(color.z, 32.0f / 255.0f);
|
||||
EXPECT_FLOAT_EQ(color.w, 1.0f);
|
||||
EXPECT_FLOAT_EQ(color.value().x, 128.0f / 255.0f);
|
||||
EXPECT_FLOAT_EQ(color.value().y, 64.0f / 255.0f);
|
||||
EXPECT_FLOAT_EQ(color.value().z, 32.0f / 255.0f);
|
||||
EXPECT_FLOAT_EQ(color.value().w, 1.0f);
|
||||
}
|
||||
|
||||
TEST_F(UnitTestColorGrouped, FromHSV)
|
||||
{
|
||||
constexpr Color color = Color::from_hsv(0.0f, 1.0f, 1.0f); // Red in HSV
|
||||
EXPECT_FLOAT_EQ(color.x, 1.0f);
|
||||
EXPECT_FLOAT_EQ(color.y, 0.0f);
|
||||
EXPECT_FLOAT_EQ(color.z, 0.0f);
|
||||
EXPECT_FLOAT_EQ(color.w, 1.0f);
|
||||
EXPECT_FLOAT_EQ(color.value().x, 1.0f);
|
||||
EXPECT_FLOAT_EQ(color.value().y, 0.0f);
|
||||
EXPECT_FLOAT_EQ(color.value().z, 0.0f);
|
||||
EXPECT_FLOAT_EQ(color.value().w, 1.0f);
|
||||
}
|
||||
|
||||
TEST_F(UnitTestColorGrouped, ToHSV)
|
||||
@@ -71,10 +71,10 @@ TEST_F(UnitTestColorGrouped, ToHSV)
|
||||
TEST_F(UnitTestColorGrouped, Blend)
|
||||
{
|
||||
const Color blended = color1.blend(color2, 0.5f);
|
||||
EXPECT_FLOAT_EQ(blended.x, 0.5f);
|
||||
EXPECT_FLOAT_EQ(blended.y, 0.5f);
|
||||
EXPECT_FLOAT_EQ(blended.z, 0.0f);
|
||||
EXPECT_FLOAT_EQ(blended.w, 1.0f);
|
||||
EXPECT_FLOAT_EQ(blended.value().x, 0.5f);
|
||||
EXPECT_FLOAT_EQ(blended.value().y, 0.5f);
|
||||
EXPECT_FLOAT_EQ(blended.value().z, 0.0f);
|
||||
EXPECT_FLOAT_EQ(blended.value().w, 1.0f);
|
||||
}
|
||||
|
||||
TEST_F(UnitTestColorGrouped, PredefinedColors)
|
||||
@@ -83,20 +83,20 @@ TEST_F(UnitTestColorGrouped, PredefinedColors)
|
||||
constexpr Color green = Color::green();
|
||||
constexpr Color blue = Color::blue();
|
||||
|
||||
EXPECT_FLOAT_EQ(red.x, 1.0f);
|
||||
EXPECT_FLOAT_EQ(red.y, 0.0f);
|
||||
EXPECT_FLOAT_EQ(red.z, 0.0f);
|
||||
EXPECT_FLOAT_EQ(red.w, 1.0f);
|
||||
EXPECT_FLOAT_EQ(red.value().x, 1.0f);
|
||||
EXPECT_FLOAT_EQ(red.value().y, 0.0f);
|
||||
EXPECT_FLOAT_EQ(red.value().z, 0.0f);
|
||||
EXPECT_FLOAT_EQ(red.value().w, 1.0f);
|
||||
|
||||
EXPECT_FLOAT_EQ(green.x, 0.0f);
|
||||
EXPECT_FLOAT_EQ(green.y, 1.0f);
|
||||
EXPECT_FLOAT_EQ(green.z, 0.0f);
|
||||
EXPECT_FLOAT_EQ(green.w, 1.0f);
|
||||
EXPECT_FLOAT_EQ(green.value().x, 0.0f);
|
||||
EXPECT_FLOAT_EQ(green.value().y, 1.0f);
|
||||
EXPECT_FLOAT_EQ(green.value().z, 0.0f);
|
||||
EXPECT_FLOAT_EQ(green.value().w, 1.0f);
|
||||
|
||||
EXPECT_FLOAT_EQ(blue.x, 0.0f);
|
||||
EXPECT_FLOAT_EQ(blue.y, 0.0f);
|
||||
EXPECT_FLOAT_EQ(blue.z, 1.0f);
|
||||
EXPECT_FLOAT_EQ(blue.w, 1.0f);
|
||||
EXPECT_FLOAT_EQ(blue.value().x, 0.0f);
|
||||
EXPECT_FLOAT_EQ(blue.value().y, 0.0f);
|
||||
EXPECT_FLOAT_EQ(blue.value().z, 1.0f);
|
||||
EXPECT_FLOAT_EQ(blue.value().w, 1.0f);
|
||||
}
|
||||
|
||||
TEST_F(UnitTestColorGrouped, BlendVector3)
|
||||
@@ -104,9 +104,9 @@ TEST_F(UnitTestColorGrouped, BlendVector3)
|
||||
constexpr Color v1(1.0f, 0.0f, 0.0f, 1.f); // Red
|
||||
constexpr Color v2(0.0f, 1.0f, 0.0f, 1.f); // Green
|
||||
constexpr Color blended = v1.blend(v2, 0.5f);
|
||||
EXPECT_FLOAT_EQ(blended.x, 0.5f);
|
||||
EXPECT_FLOAT_EQ(blended.y, 0.5f);
|
||||
EXPECT_FLOAT_EQ(blended.z, 0.0f);
|
||||
EXPECT_FLOAT_EQ(blended.value().x, 0.5f);
|
||||
EXPECT_FLOAT_EQ(blended.value().y, 0.5f);
|
||||
EXPECT_FLOAT_EQ(blended.value().z, 0.0f);
|
||||
}
|
||||
|
||||
// From unit_test_color_extra.cpp
|
||||
@@ -148,37 +148,37 @@ TEST(UnitTestColorGrouped_Extra, BlendEdgeCases)
|
||||
constexpr Color a = Color::red();
|
||||
constexpr Color b = Color::blue();
|
||||
constexpr auto r0 = a.blend(b, 0.f);
|
||||
EXPECT_FLOAT_EQ(r0.x, a.x);
|
||||
EXPECT_FLOAT_EQ(r0.value().x, a.value().x);
|
||||
constexpr auto r1 = a.blend(b, 1.f);
|
||||
EXPECT_FLOAT_EQ(r1.x, b.x);
|
||||
EXPECT_FLOAT_EQ(r1.value().x, b.value().x);
|
||||
}
|
||||
|
||||
// From unit_test_color_more.cpp
|
||||
TEST(UnitTestColorGrouped_More, DefaultCtorIsZero)
|
||||
{
|
||||
constexpr Color c;
|
||||
EXPECT_FLOAT_EQ(c.x, 0.0f);
|
||||
EXPECT_FLOAT_EQ(c.y, 0.0f);
|
||||
EXPECT_FLOAT_EQ(c.z, 0.0f);
|
||||
EXPECT_FLOAT_EQ(c.w, 0.0f);
|
||||
EXPECT_FLOAT_EQ(c.value().x, 0.0f);
|
||||
EXPECT_FLOAT_EQ(c.value().y, 0.0f);
|
||||
EXPECT_FLOAT_EQ(c.value().z, 0.0f);
|
||||
EXPECT_FLOAT_EQ(c.value().w, 0.0f);
|
||||
}
|
||||
|
||||
TEST(UnitTestColorGrouped_More, FloatCtorAndClampForRGB)
|
||||
{
|
||||
constexpr Color c(1.2f, -0.5f, 0.5f, 2.0f);
|
||||
EXPECT_FLOAT_EQ(c.x, 1.0f);
|
||||
EXPECT_FLOAT_EQ(c.y, 0.0f);
|
||||
EXPECT_FLOAT_EQ(c.z, 0.5f);
|
||||
EXPECT_FLOAT_EQ(c.w, 2.0f);
|
||||
EXPECT_FLOAT_EQ(c.value().x, 1.0f);
|
||||
EXPECT_FLOAT_EQ(c.value().y, 0.0f);
|
||||
EXPECT_FLOAT_EQ(c.value().z, 0.5f);
|
||||
EXPECT_FLOAT_EQ(c.value().w, 2.0f);
|
||||
}
|
||||
|
||||
TEST(UnitTestColorGrouped_More, FromRgbaProducesScaledComponents)
|
||||
{
|
||||
constexpr Color c = Color::from_rgba(25u, 128u, 230u, 64u);
|
||||
EXPECT_NEAR(c.x, 25.0f/255.0f, 1e-6f);
|
||||
EXPECT_NEAR(c.y, 128.0f/255.0f, 1e-6f);
|
||||
EXPECT_NEAR(c.z, 230.0f/255.0f, 1e-6f);
|
||||
EXPECT_NEAR(c.w, 64.0f/255.0f, 1e-6f);
|
||||
EXPECT_NEAR(c.value().x, 25.0f/255.0f, 1e-6f);
|
||||
EXPECT_NEAR(c.value().y, 128.0f/255.0f, 1e-6f);
|
||||
EXPECT_NEAR(c.value().z, 230.0f/255.0f, 1e-6f);
|
||||
EXPECT_NEAR(c.value().w, 64.0f/255.0f, 1e-6f);
|
||||
}
|
||||
|
||||
TEST(UnitTestColorGrouped_More, BlendProducesIntermediate)
|
||||
@@ -186,10 +186,10 @@ TEST(UnitTestColorGrouped_More, BlendProducesIntermediate)
|
||||
constexpr Color c0(0.0f, 0.0f, 0.0f, 1.0f);
|
||||
constexpr Color c1(1.0f, 1.0f, 1.0f, 0.0f);
|
||||
constexpr Color mid = c0.blend(c1, 0.5f);
|
||||
EXPECT_FLOAT_EQ(mid.x, 0.5f);
|
||||
EXPECT_FLOAT_EQ(mid.y, 0.5f);
|
||||
EXPECT_FLOAT_EQ(mid.z, 0.5f);
|
||||
EXPECT_FLOAT_EQ(mid.w, 0.5f);
|
||||
EXPECT_FLOAT_EQ(mid.value().x, 0.5f);
|
||||
EXPECT_FLOAT_EQ(mid.value().y, 0.5f);
|
||||
EXPECT_FLOAT_EQ(mid.value().z, 0.5f);
|
||||
EXPECT_FLOAT_EQ(mid.value().w, 0.5f);
|
||||
}
|
||||
|
||||
TEST(UnitTestColorGrouped_More, HsvRoundTrip)
|
||||
@@ -197,9 +197,9 @@ TEST(UnitTestColorGrouped_More, HsvRoundTrip)
|
||||
constexpr Color red = Color::red();
|
||||
const auto hsv = red.to_hsv();
|
||||
const Color back = Color::from_hsv(hsv);
|
||||
EXPECT_NEAR(back.x, 1.0f, 1e-6f);
|
||||
EXPECT_NEAR(back.y, 0.0f, 1e-6f);
|
||||
EXPECT_NEAR(back.z, 0.0f, 1e-6f);
|
||||
EXPECT_NEAR(back.value().x, 1.0f, 1e-6f);
|
||||
EXPECT_NEAR(back.value().y, 0.0f, 1e-6f);
|
||||
EXPECT_NEAR(back.value().z, 0.0f, 1e-6f);
|
||||
}
|
||||
|
||||
TEST(UnitTestColorGrouped_More, ToStringContainsComponents)
|
||||
@@ -230,18 +230,18 @@ TEST(UnitTestColorGrouped_More2, FromHsvCases)
|
||||
auto check_hue = [&](float h) {
|
||||
SCOPED_TRACE(::testing::Message() << "h=" << h);
|
||||
Color c = Color::from_hsv(h, 1.f, 1.f);
|
||||
EXPECT_TRUE(std::isfinite(c.x));
|
||||
EXPECT_TRUE(std::isfinite(c.y));
|
||||
EXPECT_TRUE(std::isfinite(c.z));
|
||||
EXPECT_GE(c.x, -eps);
|
||||
EXPECT_LE(c.x, 1.f + eps);
|
||||
EXPECT_GE(c.y, -eps);
|
||||
EXPECT_LE(c.y, 1.f + eps);
|
||||
EXPECT_GE(c.z, -eps);
|
||||
EXPECT_LE(c.z, 1.f + eps);
|
||||
EXPECT_TRUE(std::isfinite(c.value().x));
|
||||
EXPECT_TRUE(std::isfinite(c.value().y));
|
||||
EXPECT_TRUE(std::isfinite(c.value().z));
|
||||
EXPECT_GE(c.value().x, -eps);
|
||||
EXPECT_LE(c.value().x, 1.f + eps);
|
||||
EXPECT_GE(c.value().y, -eps);
|
||||
EXPECT_LE(c.value().y, 1.f + eps);
|
||||
EXPECT_GE(c.value().z, -eps);
|
||||
EXPECT_LE(c.value().z, 1.f + eps);
|
||||
|
||||
float mx = std::max({c.x, c.y, c.z});
|
||||
float mn = std::min({c.x, c.y, c.z});
|
||||
float mx = std::max({c.value().x, c.value().y, c.value().z});
|
||||
float mn = std::min({c.value().x, c.value().y, c.value().z});
|
||||
EXPECT_GE(mx, 0.999f);
|
||||
EXPECT_LE(mn, 1e-3f + 1e-4f);
|
||||
};
|
||||
@@ -261,13 +261,13 @@ TEST(UnitTestColorGrouped_More2, ToHsvAndSetters)
|
||||
EXPECT_NEAR(hsv.value, 0.6f, 1e-6f);
|
||||
|
||||
c.set_hue(0.0f);
|
||||
EXPECT_TRUE(std::isfinite(c.x));
|
||||
EXPECT_TRUE(std::isfinite(c.value().x));
|
||||
|
||||
c.set_saturation(0.0f);
|
||||
EXPECT_TRUE(std::isfinite(c.y));
|
||||
EXPECT_TRUE(std::isfinite(c.value().y));
|
||||
|
||||
c.set_value(0.5f);
|
||||
EXPECT_TRUE(std::isfinite(c.z));
|
||||
EXPECT_TRUE(std::isfinite(c.value().z));
|
||||
}
|
||||
|
||||
TEST(UnitTestColorGrouped_More2, BlendAndStaticColors)
|
||||
@@ -275,14 +275,14 @@ TEST(UnitTestColorGrouped_More2, BlendAndStaticColors)
|
||||
constexpr Color a = Color::red();
|
||||
constexpr Color b = Color::blue();
|
||||
constexpr auto mid = a.blend(b, 0.5f);
|
||||
EXPECT_GT(mid.x, 0.f);
|
||||
EXPECT_GT(mid.z, 0.f);
|
||||
EXPECT_GT(mid.value().x, 0.f);
|
||||
EXPECT_GT(mid.value().z, 0.f);
|
||||
|
||||
constexpr auto all_a = a.blend(b, -1.f);
|
||||
EXPECT_NEAR(all_a.x, a.x, 1e-6f);
|
||||
EXPECT_NEAR(all_a.value().x, a.value().x, 1e-6f);
|
||||
|
||||
constexpr auto all_b = a.blend(b, 2.f);
|
||||
EXPECT_NEAR(all_b.z, b.z, 1e-6f);
|
||||
EXPECT_NEAR(all_b.value().z, b.value().z, 1e-6f);
|
||||
}
|
||||
|
||||
TEST(UnitTestColorGrouped_More2, FormatterUsesToString)
|
||||
@@ -291,3 +291,35 @@ TEST(UnitTestColorGrouped_More2, FormatterUsesToString)
|
||||
const auto formatted = std::format("{}", c);
|
||||
EXPECT_NE(formatted.find("r:10"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(UnitTestColorGrouped_More2, FormatterRgb)
|
||||
{
|
||||
constexpr Color c = Color::from_rgba(255, 128, 0, 64);
|
||||
const auto s = std::format("{:rgb}", c);
|
||||
EXPECT_NE(s.find("r:255"), std::string::npos);
|
||||
EXPECT_NE(s.find("g:128"), std::string::npos);
|
||||
EXPECT_NE(s.find("b:0"), std::string::npos);
|
||||
EXPECT_NE(s.find("a:64"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(UnitTestColorGrouped_More2, FormatterRgbf)
|
||||
{
|
||||
constexpr Color c(0.5f, 0.25f, 1.0f, 0.75f);
|
||||
const auto s = std::format("{:rgbf}", c);
|
||||
EXPECT_NE(s.find("r:"), std::string::npos);
|
||||
EXPECT_NE(s.find("g:"), std::string::npos);
|
||||
EXPECT_NE(s.find("b:"), std::string::npos);
|
||||
EXPECT_NE(s.find("a:"), std::string::npos);
|
||||
// Values should be in [0,1] float range, not 0-255
|
||||
EXPECT_EQ(s.find("r:127"), std::string::npos);
|
||||
EXPECT_EQ(s.find("r:255"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(UnitTestColorGrouped_More2, FormatterHsv)
|
||||
{
|
||||
const Color c = Color::red();
|
||||
const auto s = std::format("{:hsv}", c);
|
||||
EXPECT_NE(s.find("h:"), std::string::npos);
|
||||
EXPECT_NE(s.find("s:"), std::string::npos);
|
||||
EXPECT_NE(s.find("v:"), std::string::npos);
|
||||
}
|
||||
|
||||
@@ -1,17 +1,214 @@
|
||||
//
|
||||
// Created by Vladislav on 30.12.2025.
|
||||
//
|
||||
// /Users/vladislav/Downloads/valencia
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/utility/elf_pattern_scan.hpp>
|
||||
#include <print>
|
||||
TEST(unit_test_elf_pattern_scan_file, ScanMissingPattern)
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
using namespace omath;
|
||||
|
||||
// ---- helpers ---------------------------------------------------------------
|
||||
|
||||
// Minimal ELF64 file with a single .text section containing known bytes.
|
||||
// Layout:
|
||||
// 0x000 : ELF64 file header (64 bytes)
|
||||
// 0x040 : section data (padded to 0x20 bytes)
|
||||
// 0x060 : section name table ".text\0" + "\0" (empty name for SHN_UNDEF)
|
||||
// 0x080 : section header table (3 entries × 64 bytes = 0xC0)
|
||||
static std::vector<std::byte> make_elf64_with_text_section(const std::vector<std::uint8_t>& code_bytes)
|
||||
{
|
||||
//FIXME: Implement normal tests :)
|
||||
//constexpr std::string_view path = "/Users/vladislav/Downloads/crackme";
|
||||
// Fixed layout constants
|
||||
constexpr std::size_t text_off = 0x40;
|
||||
constexpr std::size_t text_size = 0x20; // always 32 bytes (code padded with zeros)
|
||||
constexpr std::size_t shstrtab_off = text_off + text_size;
|
||||
// ".text\0" = 6 chars, prepend \0 for SHN_UNDEF → "\0.text\0"
|
||||
constexpr std::size_t shstrtab_size = 8; // "\0.text\0\0"
|
||||
constexpr std::size_t shdr_table_off = shstrtab_off + shstrtab_size;
|
||||
constexpr std::size_t shdr_size = 64; // sizeof(Elf64_Shdr)
|
||||
constexpr std::size_t num_sections = 3; // null + .text + .shstrtab
|
||||
constexpr std::size_t total_size = shdr_table_off + num_sections * shdr_size;
|
||||
|
||||
//const auto res = omath::ElfPatternScanner::scan_for_pattern_in_file(path, "F3 0F 1E FA 55 48 89 E5 B8 00 00 00 00", ".text");
|
||||
//EXPECT_TRUE(res.has_value());
|
||||
std::vector<std::byte> buf(total_size, std::byte{0});
|
||||
|
||||
//std::println("In virtual mem: 0x{:x}", res->virtual_base_addr+res->target_offset);
|
||||
auto w8 = [&](std::size_t off, std::uint8_t v) { buf[off] = std::byte{v}; };
|
||||
auto w16 = [&](std::size_t off, std::uint16_t v)
|
||||
{ std::memcpy(buf.data() + off, &v, 2); };
|
||||
auto w32 = [&](std::size_t off, std::uint32_t v)
|
||||
{ std::memcpy(buf.data() + off, &v, 4); };
|
||||
auto w64 = [&](std::size_t off, std::uint64_t v)
|
||||
{ std::memcpy(buf.data() + off, &v, 8); };
|
||||
|
||||
// --- ELF64 file header ---
|
||||
// e_ident
|
||||
buf[0] = std::byte{0x7F};
|
||||
buf[1] = std::byte{'E'};
|
||||
buf[2] = std::byte{'L'};
|
||||
buf[3] = std::byte{'F'};
|
||||
w8(4, 2); // ELFCLASS64
|
||||
w8(5, 1); // ELFDATA2LSB
|
||||
w8(6, 1); // EV_CURRENT
|
||||
// rest of e_ident is 0
|
||||
w16(16, 2); // e_type = ET_EXEC
|
||||
w16(18, 62); // e_machine = EM_X86_64
|
||||
w32(20, 1); // e_version
|
||||
w64(24, 0); // e_entry
|
||||
w64(32, 0); // e_phoff
|
||||
w64(40, static_cast<std::uint64_t>(shdr_table_off)); // e_shoff
|
||||
w32(48, 0); // e_flags
|
||||
w16(52, 64); // e_ehsize
|
||||
w16(54, 56); // e_phentsize
|
||||
w16(56, 0); // e_phnum
|
||||
w16(58, static_cast<std::uint16_t>(shdr_size)); // e_shentsize
|
||||
w16(60, static_cast<std::uint16_t>(num_sections)); // e_shnum
|
||||
w16(62, 2); // e_shstrndx = 2 (.shstrtab is section index 2)
|
||||
|
||||
// --- section data (.text) ---
|
||||
const std::size_t copy_len = std::min(code_bytes.size(), text_size);
|
||||
for (std::size_t i = 0; i < copy_len; ++i)
|
||||
buf[text_off + i] = std::byte{code_bytes[i]};
|
||||
|
||||
// --- .shstrtab data: "\0.text\0\0" ---
|
||||
// index 0 → "" (SHN_UNDEF name)
|
||||
// index 1 → ".text"
|
||||
// index 7 → ".shstrtab" (we cheat and use index 1 for .shstrtab too, fine for test)
|
||||
buf[shstrtab_off + 0] = std::byte{0};
|
||||
buf[shstrtab_off + 1] = std::byte{'.'};
|
||||
buf[shstrtab_off + 2] = std::byte{'t'};
|
||||
buf[shstrtab_off + 3] = std::byte{'e'};
|
||||
buf[shstrtab_off + 4] = std::byte{'x'};
|
||||
buf[shstrtab_off + 5] = std::byte{'t'};
|
||||
buf[shstrtab_off + 6] = std::byte{0};
|
||||
buf[shstrtab_off + 7] = std::byte{0};
|
||||
|
||||
// --- section headers ---
|
||||
// Elf64_Shdr fields (all offsets relative to start of a section header):
|
||||
// 0 sh_name (4)
|
||||
// 4 sh_type (4)
|
||||
// 8 sh_flags (8)
|
||||
// 16 sh_addr (8)
|
||||
// 24 sh_offset (8)
|
||||
// 32 sh_size (8)
|
||||
// 40 sh_link (4)
|
||||
// 44 sh_info (4)
|
||||
// 48 sh_addralign(8)
|
||||
// 56 sh_entsize (8)
|
||||
|
||||
// Section 0: null
|
||||
// (all zeros – already zeroed)
|
||||
|
||||
// Section 1: .text
|
||||
{
|
||||
const std::size_t base = shdr_table_off + 1 * shdr_size;
|
||||
w32(base + 0, 1); // sh_name → index 1 in shstrtab → ".text"
|
||||
w32(base + 4, 1); // sh_type = SHT_PROGBITS
|
||||
w64(base + 8, 6); // sh_flags = SHF_ALLOC|SHF_EXECINSTR
|
||||
w64(base + 16, static_cast<std::uint64_t>(text_off)); // sh_addr (same as offset in test)
|
||||
w64(base + 24, static_cast<std::uint64_t>(text_off)); // sh_offset
|
||||
w64(base + 32, static_cast<std::uint64_t>(text_size)); // sh_size
|
||||
w64(base + 48, 16); // sh_addralign
|
||||
}
|
||||
|
||||
// Section 2: .shstrtab
|
||||
{
|
||||
const std::size_t base = shdr_table_off + 2 * shdr_size;
|
||||
w32(base + 0, 0); // sh_name → index 0 → "" (good enough for scanner)
|
||||
w32(base + 4, 3); // sh_type = SHT_STRTAB
|
||||
w64(base + 24, static_cast<std::uint64_t>(shstrtab_off)); // sh_offset
|
||||
w64(base + 32, static_cast<std::uint64_t>(shstrtab_size)); // sh_size
|
||||
}
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
// ---- tests -----------------------------------------------------------------
|
||||
|
||||
TEST(unit_test_elf_pattern_scan_memory, finds_pattern)
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0x55, 0x48, 0x89, 0xE5, 0xC3};
|
||||
const auto buf = make_elf64_with_text_section(code);
|
||||
const auto span = std::span<const std::byte>{buf};
|
||||
|
||||
const auto result = ElfPatternScanner::scan_for_pattern_in_memory_file(span, "55 48 89 E5", ".text");
|
||||
|
||||
ASSERT_TRUE(result.has_value());
|
||||
EXPECT_EQ(result->target_offset, 0);
|
||||
}
|
||||
|
||||
TEST(unit_test_elf_pattern_scan_memory, finds_pattern_with_wildcard)
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0xDE, 0xAD, 0xBE, 0xEF, 0x00};
|
||||
const auto buf = make_elf64_with_text_section(code);
|
||||
|
||||
const auto result =
|
||||
ElfPatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf}, "DE ?? BE EF", ".text");
|
||||
|
||||
ASSERT_TRUE(result.has_value());
|
||||
EXPECT_EQ(result->target_offset, 0);
|
||||
}
|
||||
|
||||
TEST(unit_test_elf_pattern_scan_memory, pattern_not_found_returns_nullopt)
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0x01, 0x02, 0x03, 0x04};
|
||||
const auto buf = make_elf64_with_text_section(code);
|
||||
|
||||
const auto result =
|
||||
ElfPatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf}, "AA BB CC", ".text");
|
||||
|
||||
EXPECT_FALSE(result.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_elf_pattern_scan_memory, invalid_data_returns_nullopt)
|
||||
{
|
||||
const std::vector<std::byte> garbage(64, std::byte{0xFF});
|
||||
const auto result =
|
||||
ElfPatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{garbage}, "FF FF", ".text");
|
||||
|
||||
EXPECT_FALSE(result.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_elf_pattern_scan_memory, empty_data_returns_nullopt)
|
||||
{
|
||||
const auto result = ElfPatternScanner::scan_for_pattern_in_memory_file({}, "FF", ".text");
|
||||
EXPECT_FALSE(result.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_elf_pattern_scan_memory, missing_section_returns_nullopt)
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0x90, 0x90};
|
||||
const auto buf = make_elf64_with_text_section(code);
|
||||
|
||||
const auto result = ElfPatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf},
|
||||
"90 90", ".nonexistent");
|
||||
|
||||
EXPECT_FALSE(result.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_elf_pattern_scan_memory, matches_file_scan)
|
||||
{
|
||||
// Write our synthetic ELF to a temp file and verify memory scan == file scan
|
||||
const std::vector<std::uint8_t> code = {0x48, 0x89, 0xE5, 0xDE, 0xAD, 0xBE, 0xEF, 0x00};
|
||||
const auto buf = make_elf64_with_text_section(code);
|
||||
|
||||
const auto tmp_path = std::filesystem::temp_directory_path() / "omath_elf_test.elf";
|
||||
{
|
||||
std::ofstream out(tmp_path, std::ios::binary);
|
||||
out.write(reinterpret_cast<const char*>(buf.data()), static_cast<std::streamsize>(buf.size()));
|
||||
}
|
||||
|
||||
const auto file_result = ElfPatternScanner::scan_for_pattern_in_file(tmp_path, "48 89 E5 DE AD", ".text");
|
||||
const auto mem_result =
|
||||
ElfPatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf}, "48 89 E5 DE AD", ".text");
|
||||
|
||||
std::filesystem::remove(tmp_path);
|
||||
|
||||
ASSERT_TRUE(file_result.has_value());
|
||||
ASSERT_TRUE(mem_result.has_value());
|
||||
EXPECT_EQ(file_result->virtual_base_addr, mem_result->virtual_base_addr);
|
||||
EXPECT_EQ(file_result->raw_base_addr, mem_result->raw_base_addr);
|
||||
EXPECT_EQ(file_result->target_offset, mem_result->target_offset);
|
||||
}
|
||||
|
||||
471
tests/general/unit_test_epa_comprehensive.cpp
Normal file
471
tests/general/unit_test_epa_comprehensive.cpp
Normal file
@@ -0,0 +1,471 @@
|
||||
//
|
||||
// Comprehensive EPA tests.
|
||||
// Covers: all 3 axis directions, multiple depth levels, penetration-vector
|
||||
// round-trips, depth monotonicity, symmetry, asymmetric sizes, memory
|
||||
// resource variants, tolerance sensitivity, and iteration bookkeeping.
|
||||
//
|
||||
#include <cmath>
|
||||
#include <gtest/gtest.h>
|
||||
#include <memory_resource>
|
||||
#include <omath/collision/epa_algorithm.hpp>
|
||||
#include <omath/collision/gjk_algorithm.hpp>
|
||||
#include <omath/engines/source_engine/collider.hpp>
|
||||
#include <omath/engines/source_engine/mesh.hpp>
|
||||
|
||||
using Mesh = omath::source_engine::Mesh;
|
||||
using Collider = omath::source_engine::MeshCollider;
|
||||
using Gjk = omath::collision::GjkAlgorithm<Collider>;
|
||||
using Epa = omath::collision::Epa<Collider>;
|
||||
using Vec3 = omath::Vector3<float>;
|
||||
|
||||
namespace
|
||||
{
|
||||
const std::vector<omath::primitives::Vertex<>> k_cube_vbo = {
|
||||
{ { -1.f, -1.f, -1.f }, {}, {} },
|
||||
{ { -1.f, -1.f, 1.f }, {}, {} },
|
||||
{ { -1.f, 1.f, -1.f }, {}, {} },
|
||||
{ { -1.f, 1.f, 1.f }, {}, {} },
|
||||
{ { 1.f, 1.f, 1.f }, {}, {} },
|
||||
{ { 1.f, 1.f, -1.f }, {}, {} },
|
||||
{ { 1.f, -1.f, 1.f }, {}, {} },
|
||||
{ { 1.f, -1.f, -1.f }, {}, {} },
|
||||
};
|
||||
const std::vector<omath::Vector3<std::uint32_t>> k_empty_ebo{};
|
||||
|
||||
constexpr Epa::Params k_default_params{ .max_iterations = 64, .tolerance = 1e-4f };
|
||||
|
||||
Collider make_cube(const Vec3& origin = {}, const Vec3& scale = { 1, 1, 1 })
|
||||
{
|
||||
Mesh m{ k_cube_vbo, k_empty_ebo, scale };
|
||||
m.set_origin(origin);
|
||||
return Collider{ m };
|
||||
}
|
||||
|
||||
// Run GJK then EPA; asserts GJK hit and EPA converged.
|
||||
Epa::Result solve(const Collider& a, const Collider& b,
|
||||
const Epa::Params& params = k_default_params)
|
||||
{
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(a, b);
|
||||
EXPECT_TRUE(hit) << "GJK must detect collision before EPA can run";
|
||||
auto result = Epa::solve(a, b, simplex, params);
|
||||
EXPECT_TRUE(result.has_value()) << "EPA must converge";
|
||||
return *result;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Normal direction per axis
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// For two unit cubes (half-extent 1) with B offset by d along an axis:
|
||||
// depth = 2 - d (distance from origin to nearest face of Minkowski diff)
|
||||
// normal component along that axis ≈ ±1
|
||||
|
||||
TEST(EpaComprehensive, NormalAlongX_Positive)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0.5f, 0, 0 }));
|
||||
EXPECT_NEAR(std::abs(r.normal.x), 1.f, 1e-3f);
|
||||
EXPECT_NEAR(r.normal.y, 0.f, 1e-3f);
|
||||
EXPECT_NEAR(r.normal.z, 0.f, 1e-3f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, NormalAlongX_Negative)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ -0.5f, 0, 0 }));
|
||||
EXPECT_NEAR(std::abs(r.normal.x), 1.f, 1e-3f);
|
||||
EXPECT_NEAR(r.normal.y, 0.f, 1e-3f);
|
||||
EXPECT_NEAR(r.normal.z, 0.f, 1e-3f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, NormalAlongY_Positive)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0, 0.5f, 0 }));
|
||||
EXPECT_NEAR(r.normal.x, 0.f, 1e-3f);
|
||||
EXPECT_NEAR(std::abs(r.normal.y), 1.f, 1e-3f);
|
||||
EXPECT_NEAR(r.normal.z, 0.f, 1e-3f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, NormalAlongY_Negative)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0, -0.5f, 0 }));
|
||||
EXPECT_NEAR(r.normal.x, 0.f, 1e-3f);
|
||||
EXPECT_NEAR(std::abs(r.normal.y), 1.f, 1e-3f);
|
||||
EXPECT_NEAR(r.normal.z, 0.f, 1e-3f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, NormalAlongZ_Positive)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0, 0, 0.5f }));
|
||||
EXPECT_NEAR(r.normal.x, 0.f, 1e-3f);
|
||||
EXPECT_NEAR(r.normal.y, 0.f, 1e-3f);
|
||||
EXPECT_NEAR(std::abs(r.normal.z), 1.f, 1e-3f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, NormalAlongZ_Negative)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0, 0, -0.5f }));
|
||||
EXPECT_NEAR(r.normal.x, 0.f, 1e-3f);
|
||||
EXPECT_NEAR(r.normal.y, 0.f, 1e-3f);
|
||||
EXPECT_NEAR(std::abs(r.normal.z), 1.f, 1e-3f);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Depth correctness (depth = 2 - offset for unit cubes)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(EpaComprehensive, Depth_ShallowOverlap)
|
||||
{
|
||||
// offset 1.9 → depth 0.1
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 1.9f, 0, 0 }));
|
||||
EXPECT_NEAR(r.depth, 0.1f, 1e-2f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, Depth_QuarterOverlap)
|
||||
{
|
||||
// offset 1.5 → depth 0.5
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 1.5f, 0, 0 }));
|
||||
EXPECT_NEAR(r.depth, 0.5f, 1e-2f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, Depth_HalfOverlap)
|
||||
{
|
||||
// offset 1.0 → depth 1.0
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 1.0f, 0, 0 }));
|
||||
EXPECT_NEAR(r.depth, 1.0f, 1e-2f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, Depth_ThreeQuarterOverlap)
|
||||
{
|
||||
// offset 0.5 → depth 1.5
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0.5f, 0, 0 }));
|
||||
EXPECT_NEAR(r.depth, 1.5f, 1e-2f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, Depth_AlongY_HalfOverlap)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0, 1.0f, 0 }));
|
||||
EXPECT_NEAR(r.depth, 1.0f, 1e-2f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, Depth_AlongZ_HalfOverlap)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0, 0, 1.0f }));
|
||||
EXPECT_NEAR(r.depth, 1.0f, 1e-2f);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Depth monotonicity — deeper overlap → larger depth
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(EpaComprehensive, DepthMonotonic_AlongX)
|
||||
{
|
||||
const float d1 = solve(make_cube({ 0, 0, 0 }), make_cube({ 1.9f, 0, 0 })).depth; // ~0.1
|
||||
const float d2 = solve(make_cube({ 0, 0, 0 }), make_cube({ 1.5f, 0, 0 })).depth; // ~0.5
|
||||
const float d3 = solve(make_cube({ 0, 0, 0 }), make_cube({ 1.0f, 0, 0 })).depth; // ~1.0
|
||||
const float d4 = solve(make_cube({ 0, 0, 0 }), make_cube({ 0.5f, 0, 0 })).depth; // ~1.5
|
||||
|
||||
EXPECT_LT(d1, d2);
|
||||
EXPECT_LT(d2, d3);
|
||||
EXPECT_LT(d3, d4);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Normal is a unit vector
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(EpaComprehensive, NormalIsUnit_AlongX)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0.5f, 0, 0 }));
|
||||
EXPECT_NEAR(r.normal.dot(r.normal), 1.f, 1e-5f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, NormalIsUnit_AlongY)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0, 1.2f, 0 }));
|
||||
EXPECT_NEAR(r.normal.dot(r.normal), 1.f, 1e-5f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, NormalIsUnit_AlongZ)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0, 0, 0.8f }));
|
||||
EXPECT_NEAR(r.normal.dot(r.normal), 1.f, 1e-5f);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Penetration vector = normal * depth
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(EpaComprehensive, PenetrationVectorLength_EqualsDepth)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0.5f, 0, 0 }));
|
||||
const float pen_len = std::sqrt(r.penetration_vector.dot(r.penetration_vector));
|
||||
EXPECT_NEAR(pen_len, r.depth, 1e-5f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, PenetrationVectorDirection_ParallelToNormal)
|
||||
{
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }), make_cube({ 0, 1.0f, 0 }));
|
||||
// penetration_vector = normal * depth → cross product must be ~zero
|
||||
const auto cross = r.penetration_vector.cross(r.normal);
|
||||
EXPECT_NEAR(cross.dot(cross), 0.f, 1e-8f);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Round-trip: applying penetration_vector separates the shapes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(EpaComprehensive, RoundTrip_AlongX)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
Mesh mesh_b{ k_cube_vbo, k_empty_ebo };
|
||||
mesh_b.set_origin({ 0.5f, 0, 0 });
|
||||
const auto b = Collider{ mesh_b };
|
||||
|
||||
const auto r = solve(a, b);
|
||||
constexpr float margin = 1.f + 1e-3f;
|
||||
|
||||
// Move B along the penetration vector; it should separate from A
|
||||
Mesh mesh_sep{ k_cube_vbo, k_empty_ebo };
|
||||
mesh_sep.set_origin(mesh_b.get_origin() + r.penetration_vector * margin);
|
||||
EXPECT_FALSE(Gjk::is_collide(a, Collider{ mesh_sep })) << "Applying pen vector must separate";
|
||||
|
||||
// Moving the wrong way must still collide
|
||||
Mesh mesh_wrong{ k_cube_vbo, k_empty_ebo };
|
||||
mesh_wrong.set_origin(mesh_b.get_origin() - r.penetration_vector * margin);
|
||||
EXPECT_TRUE(Gjk::is_collide(a, Collider{ mesh_wrong })) << "Opposite direction must still collide";
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, RoundTrip_AlongY)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
Mesh mesh_b{ k_cube_vbo, k_empty_ebo };
|
||||
mesh_b.set_origin({ 0, 0.8f, 0 });
|
||||
const auto b = Collider{ mesh_b };
|
||||
|
||||
const auto r = solve(a, b);
|
||||
constexpr float margin = 1.f + 1e-3f;
|
||||
|
||||
Mesh mesh_sep{ k_cube_vbo, k_empty_ebo };
|
||||
mesh_sep.set_origin(mesh_b.get_origin() + r.penetration_vector * margin);
|
||||
EXPECT_FALSE(Gjk::is_collide(a, Collider{ mesh_sep }));
|
||||
|
||||
Mesh mesh_wrong{ k_cube_vbo, k_empty_ebo };
|
||||
mesh_wrong.set_origin(mesh_b.get_origin() - r.penetration_vector * margin);
|
||||
EXPECT_TRUE(Gjk::is_collide(a, Collider{ mesh_wrong }));
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, RoundTrip_AlongZ)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
Mesh mesh_b{ k_cube_vbo, k_empty_ebo };
|
||||
mesh_b.set_origin({ 0, 0, 1.2f });
|
||||
const auto b = Collider{ mesh_b };
|
||||
|
||||
const auto r = solve(a, b);
|
||||
constexpr float margin = 1.f + 1e-3f;
|
||||
|
||||
Mesh mesh_sep{ k_cube_vbo, k_empty_ebo };
|
||||
mesh_sep.set_origin(mesh_b.get_origin() + r.penetration_vector * margin);
|
||||
EXPECT_FALSE(Gjk::is_collide(a, Collider{ mesh_sep }));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Symmetry — swapping A and B preserves depth
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(EpaComprehensive, Symmetry_DepthIsIndependentOfOrder)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 0.5f, 0, 0 });
|
||||
|
||||
const float depth_ab = solve(a, b).depth;
|
||||
const float depth_ba = solve(b, a).depth;
|
||||
|
||||
EXPECT_NEAR(depth_ab, depth_ba, 1e-2f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, Symmetry_NormalsAreOpposite)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 0.5f, 0, 0 });
|
||||
|
||||
const Vec3 n_ab = solve(a, b).normal;
|
||||
const Vec3 n_ba = solve(b, a).normal;
|
||||
|
||||
// The normals should be anti-parallel: n_ab · n_ba ≈ -1
|
||||
EXPECT_NEAR(n_ab.dot(n_ba), -1.f, 1e-3f);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Asymmetric sizes
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(EpaComprehensive, LargeVsSmall_DepthCorrect)
|
||||
{
|
||||
// Big (half-ext 2) at origin, small (half-ext 0.5) at (2.0, 0, 0)
|
||||
// Minkowski diff closest face in X at distance 0.5
|
||||
const auto r = solve(make_cube({ 0, 0, 0 }, { 2, 2, 2 }), make_cube({ 2.0f, 0, 0 }, { 0.5f, 0.5f, 0.5f }));
|
||||
EXPECT_NEAR(r.depth, 0.5f, 1e-2f);
|
||||
EXPECT_NEAR(std::abs(r.normal.x), 1.f, 1e-3f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, LargeVsSmall_RoundTrip)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 }, { 2, 2, 2 });
|
||||
|
||||
Mesh mesh_b{ k_cube_vbo, k_empty_ebo, { 0.5f, 0.5f, 0.5f } };
|
||||
mesh_b.set_origin({ 2.0f, 0, 0 });
|
||||
const auto b = Collider{ mesh_b };
|
||||
|
||||
const auto r = solve(a, b);
|
||||
constexpr float margin = 1.f + 1e-3f;
|
||||
|
||||
Mesh mesh_sep{ k_cube_vbo, k_empty_ebo, { 0.5f, 0.5f, 0.5f } };
|
||||
mesh_sep.set_origin(mesh_b.get_origin() + r.penetration_vector * margin);
|
||||
EXPECT_FALSE(Gjk::is_collide(a, Collider{ mesh_sep }));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Memory resource variants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(EpaComprehensive, MonotonicBuffer_ConvergesCorrectly)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 0.5f, 0, 0 });
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(a, b);
|
||||
ASSERT_TRUE(hit);
|
||||
|
||||
constexpr std::size_t k_buf = 32768;
|
||||
alignas(std::max_align_t) char buf[k_buf];
|
||||
std::pmr::monotonic_buffer_resource mr{ buf, k_buf, std::pmr::null_memory_resource() };
|
||||
|
||||
const auto r = Epa::solve(a, b, simplex, k_default_params, mr);
|
||||
ASSERT_TRUE(r.has_value());
|
||||
EXPECT_NEAR(r->depth, 1.5f, 1e-2f);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, MonotonicBuffer_MultipleReleaseCycles)
|
||||
{
|
||||
// Verify mr.release() correctly resets the buffer across multiple calls
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 0.5f, 0, 0 });
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(a, b);
|
||||
ASSERT_TRUE(hit);
|
||||
|
||||
constexpr std::size_t k_buf = 32768;
|
||||
alignas(std::max_align_t) char buf[k_buf];
|
||||
std::pmr::monotonic_buffer_resource mr{ buf, k_buf, std::pmr::null_memory_resource() };
|
||||
|
||||
float first_depth = 0.f;
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
mr.release();
|
||||
const auto r = Epa::solve(a, b, simplex, k_default_params, mr);
|
||||
ASSERT_TRUE(r.has_value()) << "solve must converge on iteration " << i;
|
||||
if (i == 0)
|
||||
first_depth = r->depth;
|
||||
else
|
||||
EXPECT_NEAR(r->depth, first_depth, 1e-6f) << "depth must be deterministic";
|
||||
}
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, DefaultResource_ConvergesCorrectly)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 1.0f, 0, 0 });
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(a, b);
|
||||
ASSERT_TRUE(hit);
|
||||
|
||||
const auto r = Epa::solve(a, b, simplex);
|
||||
ASSERT_TRUE(r.has_value());
|
||||
EXPECT_NEAR(r->depth, 1.0f, 1e-2f);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tolerance sensitivity
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(EpaComprehensive, TighterTolerance_MoreAccurateDepth)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 1.0f, 0, 0 });
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(a, b);
|
||||
ASSERT_TRUE(hit);
|
||||
|
||||
const Epa::Params loose{ .max_iterations = 64, .tolerance = 1e-2f };
|
||||
const Epa::Params tight{ .max_iterations = 64, .tolerance = 1e-5f };
|
||||
|
||||
const auto r_loose = Epa::solve(a, b, simplex, loose);
|
||||
const auto r_tight = Epa::solve(a, b, simplex, tight);
|
||||
ASSERT_TRUE(r_loose.has_value());
|
||||
ASSERT_TRUE(r_tight.has_value());
|
||||
|
||||
// Tighter tolerance must yield a result at least as accurate
|
||||
EXPECT_LE(std::abs(r_tight->depth - 1.0f), std::abs(r_loose->depth - 1.0f) + 1e-4f);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bookkeeping fields
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(EpaComprehensive, Bookkeeping_IterationsInBounds)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 0.5f, 0, 0 });
|
||||
const auto r = solve(a, b);
|
||||
|
||||
EXPECT_GT(r.iterations, 0);
|
||||
EXPECT_LE(r.iterations, k_default_params.max_iterations);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, Bookkeeping_FacesAndVerticesGrow)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 0.5f, 0, 0 });
|
||||
const auto r = solve(a, b);
|
||||
|
||||
// Started with a tetrahedron (4 faces, 4 vertices); EPA must have expanded it
|
||||
EXPECT_GE(r.num_faces, 4);
|
||||
EXPECT_GE(r.num_vertices, 4);
|
||||
}
|
||||
|
||||
TEST(EpaComprehensive, Bookkeeping_MaxIterationsRespected)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 0.5f, 0, 0 });
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(a, b);
|
||||
ASSERT_TRUE(hit);
|
||||
|
||||
constexpr Epa::Params tight{ .max_iterations = 3, .tolerance = 1e-10f };
|
||||
const auto r = Epa::solve(a, b, simplex, tight);
|
||||
|
||||
// Must return something (fallback best-face path) and respect the cap
|
||||
if (r.has_value())
|
||||
EXPECT_LE(r->iterations, tight.max_iterations);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Determinism
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(EpaComprehensive, Deterministic_SameResultOnRepeatedCalls)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 0.7f, 0, 0 });
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(a, b);
|
||||
ASSERT_TRUE(hit);
|
||||
|
||||
const auto first = Epa::solve(a, b, simplex);
|
||||
ASSERT_TRUE(first.has_value());
|
||||
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
const auto r = Epa::solve(a, b, simplex);
|
||||
ASSERT_TRUE(r.has_value());
|
||||
EXPECT_NEAR(r->depth, first->depth, 1e-6f);
|
||||
EXPECT_NEAR(r->normal.x, first->normal.x, 1e-6f);
|
||||
EXPECT_NEAR(r->normal.y, first->normal.y, 1e-6f);
|
||||
EXPECT_NEAR(r->normal.z, first->normal.z, 1e-6f);
|
||||
}
|
||||
}
|
||||
277
tests/general/unit_test_gjk_comprehensive.cpp
Normal file
277
tests/general/unit_test_gjk_comprehensive.cpp
Normal file
@@ -0,0 +1,277 @@
|
||||
//
|
||||
// Comprehensive GJK tests.
|
||||
// Covers: all 6 axis directions, diagonal cases, boundary touching,
|
||||
// asymmetric sizes, nesting, symmetry, simplex info, far separation.
|
||||
//
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/collision/gjk_algorithm.hpp>
|
||||
#include <omath/engines/source_engine/collider.hpp>
|
||||
#include <omath/engines/source_engine/mesh.hpp>
|
||||
|
||||
using Mesh = omath::source_engine::Mesh;
|
||||
using Collider = omath::source_engine::MeshCollider;
|
||||
using Gjk = omath::collision::GjkAlgorithm<Collider>;
|
||||
using Vec3 = omath::Vector3<float>;
|
||||
|
||||
namespace
|
||||
{
|
||||
// Unit cube [-1, 1]^3 in local space.
|
||||
const std::vector<omath::primitives::Vertex<>> k_cube_vbo = {
|
||||
{ { -1.f, -1.f, -1.f }, {}, {} },
|
||||
{ { -1.f, -1.f, 1.f }, {}, {} },
|
||||
{ { -1.f, 1.f, -1.f }, {}, {} },
|
||||
{ { -1.f, 1.f, 1.f }, {}, {} },
|
||||
{ { 1.f, 1.f, 1.f }, {}, {} },
|
||||
{ { 1.f, 1.f, -1.f }, {}, {} },
|
||||
{ { 1.f, -1.f, 1.f }, {}, {} },
|
||||
{ { 1.f, -1.f, -1.f }, {}, {} },
|
||||
};
|
||||
const std::vector<omath::Vector3<std::uint32_t>> k_empty_ebo{};
|
||||
|
||||
Collider make_cube(const Vec3& origin = {}, const Vec3& scale = { 1, 1, 1 })
|
||||
{
|
||||
Mesh m{ k_cube_vbo, k_empty_ebo, scale };
|
||||
m.set_origin(origin);
|
||||
return Collider{ m };
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Separation — expect false
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(GjkComprehensive, Separated_AlongPosX)
|
||||
{
|
||||
// A extends to x=1, B starts at x=1.1 → clear gap
|
||||
EXPECT_FALSE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 2.1f, 0, 0 })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Separated_AlongNegX)
|
||||
{
|
||||
// B to the left of A
|
||||
EXPECT_FALSE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ -2.1f, 0, 0 })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Separated_AlongPosY)
|
||||
{
|
||||
EXPECT_FALSE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 0, 2.1f, 0 })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Separated_AlongNegY)
|
||||
{
|
||||
EXPECT_FALSE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 0, -2.1f, 0 })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Separated_AlongPosZ)
|
||||
{
|
||||
EXPECT_FALSE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 0, 0, 2.1f })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Separated_AlongNegZ)
|
||||
{
|
||||
EXPECT_FALSE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 0, 0, -2.1f })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Separated_AlongDiagonal)
|
||||
{
|
||||
// All components exceed 2.0 — no overlap on any axis
|
||||
EXPECT_FALSE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 2.1f, 2.1f, 2.1f })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Separated_LargeDistance)
|
||||
{
|
||||
EXPECT_FALSE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 100.f, 0, 0 })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Separated_AsymmetricSizes)
|
||||
{
|
||||
// Big (scale 2, half-ext 2), small (scale 0.5, half-ext 0.5) at 2.6 → gap of 0.1
|
||||
EXPECT_FALSE(Gjk::is_collide(make_cube({ 0, 0, 0 }, { 2, 2, 2 }), make_cube({ 2.6f, 0, 0 }, { 0.5f, 0.5f, 0.5f })));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Overlap — expect true
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(GjkComprehensive, Overlapping_AlongPosX)
|
||||
{
|
||||
// B offset 1.5 → overlap depth 0.5 in X
|
||||
EXPECT_TRUE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 1.5f, 0, 0 })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Overlapping_AlongNegX)
|
||||
{
|
||||
EXPECT_TRUE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ -1.5f, 0, 0 })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Overlapping_AlongPosZ)
|
||||
{
|
||||
EXPECT_TRUE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 0, 0, 1.5f })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Overlapping_AlongNegZ)
|
||||
{
|
||||
EXPECT_TRUE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 0, 0, -1.5f })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Overlapping_AlongDiagonalXY)
|
||||
{
|
||||
// Minkowski sum extends ±2 on each axis; offset (1,1,0) is inside
|
||||
EXPECT_TRUE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 1.f, 1.f, 0.f })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Overlapping_AlongDiagonalXYZ)
|
||||
{
|
||||
// All three axes overlap: (1,1,1) is inside the Minkowski sum
|
||||
EXPECT_TRUE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 1.f, 1.f, 1.f })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, FullyNested_SmallInsideBig)
|
||||
{
|
||||
// Small cube (half-ext 0.5) fully inside big cube (half-ext 2)
|
||||
EXPECT_TRUE(Gjk::is_collide(make_cube({ 0, 0, 0 }, { 2, 2, 2 }), make_cube({ 0, 0, 0 }, { 0.5f, 0.5f, 0.5f })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, FullyNested_OffCenter)
|
||||
{
|
||||
// Small at (0.5, 0, 0) still fully inside big (half-ext 2)
|
||||
EXPECT_TRUE(Gjk::is_collide(make_cube({ 0, 0, 0 }, { 2, 2, 2 }), make_cube({ 0.5f, 0, 0 }, { 0.5f, 0.5f, 0.5f })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Overlapping_AsymmetricSizes)
|
||||
{
|
||||
// Big (scale 2, half-ext 2) and small (scale 0.5, half-ext 0.5) at 2.0 → overlap 0.5 in X
|
||||
EXPECT_TRUE(Gjk::is_collide(make_cube({ 0, 0, 0 }, { 2, 2, 2 }), make_cube({ 2.0f, 0, 0 }, { 0.5f, 0.5f, 0.5f })));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Boundary cases
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(GjkComprehensive, BoundaryCase_JustColliding)
|
||||
{
|
||||
// B at 1.999 — 0.001 overlap in X
|
||||
EXPECT_TRUE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 1.999f, 0, 0 })));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, BoundaryCase_JustSeparated)
|
||||
{
|
||||
// B at 2.001 — 0.001 gap in X
|
||||
EXPECT_FALSE(Gjk::is_collide(make_cube({ 0, 0, 0 }), make_cube({ 2.001f, 0, 0 })));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Symmetry
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(GjkComprehensive, Symmetry_WhenColliding)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 1.5f, 0, 0 });
|
||||
EXPECT_EQ(Gjk::is_collide(a, b), Gjk::is_collide(b, a));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Symmetry_WhenSeparated)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 2.1f, 0.5f, 0 });
|
||||
EXPECT_EQ(Gjk::is_collide(a, b), Gjk::is_collide(b, a));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, Symmetry_DiagonalSeparation)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 1.5f, 1.5f, 1.5f });
|
||||
EXPECT_EQ(Gjk::is_collide(a, b), Gjk::is_collide(b, a));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Simplex info
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(GjkComprehensive, SimplexInfo_HitProducesSimplex4)
|
||||
{
|
||||
// On collision the simplex must be a full tetrahedron (4 points)
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(make_cube({ 0, 0, 0 }), make_cube({ 0.5f, 0, 0 }));
|
||||
EXPECT_TRUE(hit);
|
||||
EXPECT_EQ(simplex.size(), 4u);
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, SimplexInfo_MissProducesLessThan4)
|
||||
{
|
||||
// On non-collision the simplex can never be a full tetrahedron
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(make_cube({ 0, 0, 0 }), make_cube({ 2.1f, 0, 0 }));
|
||||
EXPECT_FALSE(hit);
|
||||
EXPECT_LT(simplex.size(), 4u);
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, SimplexInfo_HitAlongY)
|
||||
{
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(make_cube({ 0, 0, 0 }), make_cube({ 0, 1.5f, 0 }));
|
||||
EXPECT_TRUE(hit);
|
||||
EXPECT_EQ(simplex.size(), 4u);
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, SimplexInfo_HitAlongZ)
|
||||
{
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(make_cube({ 0, 0, 0 }), make_cube({ 0, 0, 1.5f }));
|
||||
EXPECT_TRUE(hit);
|
||||
EXPECT_EQ(simplex.size(), 4u);
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, SimplexInfo_MissAlongDiagonal)
|
||||
{
|
||||
const auto [hit, simplex] = Gjk::is_collide_with_simplex_info(make_cube({ 0, 0, 0 }), make_cube({ 2.1f, 2.1f, 2.1f }));
|
||||
EXPECT_FALSE(hit);
|
||||
EXPECT_LT(simplex.size(), 4u);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Non-trivial geometry — tetrahedron shaped colliders
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(GjkComprehensive, TetrahedronShapes_Overlapping)
|
||||
{
|
||||
// A rough tetrahedron mesh; two of them close enough to overlap
|
||||
const std::vector<omath::primitives::Vertex<>> tet_vbo = {
|
||||
{ { 0.f, 1.f, 0.f }, {}, {} },
|
||||
{ { -1.f, -1.f, 1.f }, {}, {} },
|
||||
{ { 1.f, -1.f, 1.f }, {}, {} },
|
||||
{ { 0.f, -1.f, -1.f }, {}, {} },
|
||||
};
|
||||
|
||||
Mesh m_a{ tet_vbo, k_empty_ebo };
|
||||
Mesh m_b{ tet_vbo, k_empty_ebo };
|
||||
m_b.set_origin({ 0.5f, 0.f, 0.f });
|
||||
|
||||
EXPECT_TRUE(Gjk::is_collide(Collider{ m_a }, Collider{ m_b }));
|
||||
}
|
||||
|
||||
TEST(GjkComprehensive, TetrahedronShapes_Separated)
|
||||
{
|
||||
const std::vector<omath::primitives::Vertex<>> tet_vbo = {
|
||||
{ { 0.f, 1.f, 0.f }, {}, {} },
|
||||
{ { -1.f, -1.f, 1.f }, {}, {} },
|
||||
{ { 1.f, -1.f, 1.f }, {}, {} },
|
||||
{ { 0.f, -1.f, -1.f }, {}, {} },
|
||||
};
|
||||
|
||||
Mesh m_a{ tet_vbo, k_empty_ebo };
|
||||
Mesh m_b{ tet_vbo, k_empty_ebo };
|
||||
m_b.set_origin({ 3.f, 0.f, 0.f });
|
||||
|
||||
EXPECT_FALSE(Gjk::is_collide(Collider{ m_a }, Collider{ m_b }));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Determinism
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(GjkComprehensive, Deterministic_SameResultOnRepeatedCalls)
|
||||
{
|
||||
const auto a = make_cube({ 0, 0, 0 });
|
||||
const auto b = make_cube({ 1.2f, 0.3f, 0.1f });
|
||||
const bool first = Gjk::is_collide(a, b);
|
||||
for (int i = 0; i < 10; ++i)
|
||||
EXPECT_EQ(Gjk::is_collide(a, b), first);
|
||||
}
|
||||
145
tests/general/unit_test_macho_memory_file_scan.cpp
Normal file
145
tests/general/unit_test_macho_memory_file_scan.cpp
Normal file
@@ -0,0 +1,145 @@
|
||||
// Tests for MachOPatternScanner::scan_for_pattern_in_memory_file
|
||||
#include <cstring>
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/utility/macho_pattern_scan.hpp>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
using namespace omath;
|
||||
|
||||
// Build a minimal Mach-O 64-bit file in memory with a single __text section.
|
||||
// Layout:
|
||||
// 0x000 : MachHeader64 (32 bytes)
|
||||
// 0x020 : SegmentCommand64 (72 bytes)
|
||||
// 0x068 : Section64 (80 bytes) ← follows segment command inline
|
||||
// 0x0B8 : section raw data (padded to 0x20 bytes)
|
||||
static std::vector<std::byte> make_macho64_with_text_section(const std::vector<std::uint8_t>& code_bytes)
|
||||
{
|
||||
constexpr std::uint32_t mh_magic_64 = 0xFEEDFACF;
|
||||
constexpr std::uint32_t lc_segment_64 = 0x19;
|
||||
|
||||
// MachHeader64 layout (32 bytes):
|
||||
// 0 magic, 4 cputype, 8 cpusubtype, 12 filetype, 16 ncmds, 20 sizeofcmds, 24 flags, 28 reserved
|
||||
constexpr std::size_t hdr_size = 32;
|
||||
|
||||
// SegmentCommand64 layout (72 bytes):
|
||||
// 0 cmd, 4 cmdsize, 8 segname[16], 24 vmaddr, 32 vmsize, 40 fileoff, 48 filesize,
|
||||
// 56 maxprot, 60 initprot, 64 nsects, 68 flags
|
||||
constexpr std::size_t seg_size = 72;
|
||||
|
||||
// Section64 layout (80 bytes):
|
||||
// 0 sectname[16], 16 segname[16], 32 addr, 40 size, 48 offset, 52 align,
|
||||
// 56 reloff, 60 nreloc, 64 flags, 68 reserved1, 72 reserved2, 76 reserved3
|
||||
constexpr std::size_t sect_hdr_size = 80;
|
||||
|
||||
constexpr std::size_t text_raw_off = hdr_size + seg_size + sect_hdr_size; // 0xB8
|
||||
constexpr std::size_t text_raw_size = 0x20;
|
||||
constexpr std::size_t total_size = text_raw_off + text_raw_size;
|
||||
constexpr std::uint64_t text_vmaddr = 0x1000ULL;
|
||||
|
||||
constexpr std::uint32_t cmd_size =
|
||||
static_cast<std::uint32_t>(seg_size + sect_hdr_size); // segment + 1 section
|
||||
|
||||
std::vector<std::byte> buf(total_size, std::byte{0});
|
||||
|
||||
auto w32 = [&](std::size_t off, std::uint32_t v) { std::memcpy(buf.data() + off, &v, 4); };
|
||||
auto w64 = [&](std::size_t off, std::uint64_t v) { std::memcpy(buf.data() + off, &v, 8); };
|
||||
|
||||
// MachHeader64
|
||||
w32(0, mh_magic_64);
|
||||
w32(4, 0x0100000C); // cputype = CPU_TYPE_ARM64 (doesn't matter for scan)
|
||||
w32(12, 2); // filetype = MH_EXECUTE
|
||||
w32(16, 1); // ncmds = 1
|
||||
w32(20, cmd_size); // sizeofcmds
|
||||
|
||||
// SegmentCommand64 at 0x20
|
||||
constexpr std::size_t seg_off = hdr_size;
|
||||
w32(seg_off + 0, lc_segment_64);
|
||||
w32(seg_off + 4, cmd_size);
|
||||
std::memcpy(buf.data() + seg_off + 8, "__TEXT", 6); // segname
|
||||
w64(seg_off + 24, text_vmaddr); // vmaddr
|
||||
w64(seg_off + 32, text_raw_size); // vmsize
|
||||
w64(seg_off + 40, text_raw_off); // fileoff
|
||||
w64(seg_off + 48, text_raw_size); // filesize
|
||||
w32(seg_off + 64, 1); // nsects
|
||||
|
||||
// Section64 at 0x68
|
||||
constexpr std::size_t sect_off = seg_off + seg_size;
|
||||
std::memcpy(buf.data() + sect_off + 0, "__text", 6); // sectname
|
||||
std::memcpy(buf.data() + sect_off + 16, "__TEXT", 6); // segname
|
||||
w64(sect_off + 32, text_vmaddr); // addr
|
||||
w64(sect_off + 40, text_raw_size); // size
|
||||
w32(sect_off + 48, static_cast<std::uint32_t>(text_raw_off)); // offset (file offset)
|
||||
|
||||
// Section data
|
||||
const std::size_t copy_len = std::min(code_bytes.size(), text_raw_size);
|
||||
for (std::size_t i = 0; i < copy_len; ++i)
|
||||
buf[text_raw_off + i] = std::byte{code_bytes[i]};
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
// ---- tests -----------------------------------------------------------------
|
||||
|
||||
TEST(unit_test_macho_memory_file_scan, finds_pattern)
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0x55, 0x48, 0x89, 0xE5, 0xC3};
|
||||
const auto buf = make_macho64_with_text_section(code);
|
||||
|
||||
const auto result =
|
||||
MachOPatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf}, "55 48 89 E5");
|
||||
|
||||
ASSERT_TRUE(result.has_value());
|
||||
EXPECT_EQ(result->target_offset, 0);
|
||||
}
|
||||
|
||||
TEST(unit_test_macho_memory_file_scan, finds_pattern_with_wildcard)
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0xDE, 0xAD, 0xBE, 0xEF};
|
||||
const auto buf = make_macho64_with_text_section(code);
|
||||
|
||||
const auto result =
|
||||
MachOPatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf}, "DE ?? BE EF");
|
||||
|
||||
ASSERT_TRUE(result.has_value());
|
||||
EXPECT_EQ(result->target_offset, 0);
|
||||
}
|
||||
|
||||
TEST(unit_test_macho_memory_file_scan, pattern_not_found_returns_nullopt)
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0x01, 0x02, 0x03};
|
||||
const auto buf = make_macho64_with_text_section(code);
|
||||
|
||||
const auto result =
|
||||
MachOPatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf}, "AA BB CC");
|
||||
|
||||
EXPECT_FALSE(result.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_macho_memory_file_scan, invalid_data_returns_nullopt)
|
||||
{
|
||||
const std::vector<std::byte> garbage(64, std::byte{0xFF});
|
||||
const auto result =
|
||||
MachOPatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{garbage}, "FF FF");
|
||||
EXPECT_FALSE(result.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_macho_memory_file_scan, empty_data_returns_nullopt)
|
||||
{
|
||||
const auto result = MachOPatternScanner::scan_for_pattern_in_memory_file({}, "FF");
|
||||
EXPECT_FALSE(result.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_macho_memory_file_scan, raw_addr_and_virtual_addr_correct)
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0xCA, 0xFE, 0xBA, 0xBE};
|
||||
const auto buf = make_macho64_with_text_section(code);
|
||||
|
||||
constexpr std::size_t expected_raw_off = 32 + 72 + 80; // hdr + seg + sect_hdr
|
||||
const auto result =
|
||||
MachOPatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf}, "CA FE BA BE");
|
||||
|
||||
ASSERT_TRUE(result.has_value());
|
||||
EXPECT_EQ(result->raw_base_addr, expected_raw_off);
|
||||
EXPECT_EQ(result->virtual_base_addr, 0x1000u);
|
||||
}
|
||||
@@ -6,8 +6,8 @@
|
||||
#include <omath/utility/macho_pattern_scan.hpp>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
#include "mem_fd_helper.hpp"
|
||||
|
||||
using namespace omath;
|
||||
|
||||
@@ -16,11 +16,12 @@ namespace
|
||||
// Mach-O magic numbers
|
||||
constexpr std::uint32_t mh_magic_64 = 0xFEEDFACF;
|
||||
constexpr std::uint32_t mh_magic_32 = 0xFEEDFACE;
|
||||
constexpr std::uint32_t lc_segment = 0x1;
|
||||
constexpr std::uint32_t lc_segment = 0x1;
|
||||
constexpr std::uint32_t lc_segment_64 = 0x19;
|
||||
|
||||
constexpr std::string_view segment_name = "__TEXT";
|
||||
constexpr std::string_view section_name = "__text";
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct MachHeader64
|
||||
{
|
||||
@@ -107,249 +108,174 @@ namespace
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
// Helper function to create a minimal 64-bit Mach-O file with a __text section
|
||||
bool write_minimal_macho64_file(const std::string& path, const std::vector<std::uint8_t>& section_bytes)
|
||||
// Build a minimal 64-bit Mach-O binary in-memory with a __text section
|
||||
std::vector<std::uint8_t> build_minimal_macho64(const std::vector<std::uint8_t>& section_bytes)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open())
|
||||
return false;
|
||||
constexpr std::size_t load_cmd_size = sizeof(SegmentCommand64) + sizeof(Section64);
|
||||
const std::size_t section_offset = sizeof(MachHeader64) + load_cmd_size;
|
||||
|
||||
// Calculate sizes
|
||||
constexpr std::size_t header_size = sizeof(MachHeader64);
|
||||
constexpr std::size_t segment_size = sizeof(SegmentCommand64);
|
||||
constexpr std::size_t section_size = sizeof(Section64);
|
||||
constexpr std::size_t load_cmd_size = segment_size + section_size;
|
||||
// Section data will start after headers
|
||||
const std::size_t section_offset = header_size + load_cmd_size;
|
||||
std::vector<std::uint8_t> buf(section_offset + section_bytes.size(), 0u);
|
||||
|
||||
// Create Mach-O header
|
||||
MachHeader64 header{};
|
||||
header.magic = mh_magic_64;
|
||||
header.cputype = 0x01000007; // CPU_TYPE_X86_64
|
||||
header.cpusubtype = 0x3; // CPU_SUBTYPE_X86_64_ALL
|
||||
header.filetype = 0x2; // MH_EXECUTE
|
||||
header.ncmds = 1;
|
||||
header.sizeofcmds = static_cast<std::uint32_t>(load_cmd_size);
|
||||
header.flags = 0;
|
||||
header.reserved = 0;
|
||||
auto* header = reinterpret_cast<MachHeader64*>(buf.data());
|
||||
header->magic = mh_magic_64;
|
||||
header->cputype = 0x01000007; // CPU_TYPE_X86_64
|
||||
header->cpusubtype = 0x3;
|
||||
header->filetype = 0x2; // MH_EXECUTE
|
||||
header->ncmds = 1;
|
||||
header->sizeofcmds = static_cast<std::uint32_t>(load_cmd_size);
|
||||
|
||||
f.write(reinterpret_cast<const char*>(&header), sizeof(header));
|
||||
auto* segment = reinterpret_cast<SegmentCommand64*>(buf.data() + sizeof(MachHeader64));
|
||||
segment->cmd = lc_segment_64;
|
||||
segment->cmdsize = static_cast<std::uint32_t>(load_cmd_size);
|
||||
std::ranges::copy(segment_name, segment->segname);
|
||||
segment->vmaddr = 0x100000000;
|
||||
segment->vmsize = section_bytes.size();
|
||||
segment->fileoff = section_offset;
|
||||
segment->filesize = section_bytes.size();
|
||||
segment->maxprot = 7;
|
||||
segment->initprot = 5;
|
||||
segment->nsects = 1;
|
||||
|
||||
// Create segment command
|
||||
SegmentCommand64 segment{};
|
||||
segment.cmd = lc_segment_64;
|
||||
segment.cmdsize = static_cast<std::uint32_t>(load_cmd_size);
|
||||
std::ranges::copy(segment_name, segment.segname);
|
||||
segment.vmaddr = 0x100000000;
|
||||
segment.vmsize = section_bytes.size();
|
||||
segment.fileoff = section_offset;
|
||||
segment.filesize = section_bytes.size();
|
||||
segment.maxprot = 7; // VM_PROT_ALL
|
||||
segment.initprot = 5; // VM_PROT_READ | VM_PROT_EXECUTE
|
||||
segment.nsects = 1;
|
||||
segment.flags = 0;
|
||||
auto* section = reinterpret_cast<Section64*>(buf.data() + sizeof(MachHeader64) + sizeof(SegmentCommand64));
|
||||
std::ranges::copy(section_name, section->sectname);
|
||||
std::ranges::copy(segment_name, section->segname);
|
||||
section->addr = 0x100000000;
|
||||
section->size = section_bytes.size();
|
||||
section->offset = static_cast<std::uint32_t>(section_offset);
|
||||
|
||||
f.write(reinterpret_cast<const char*>(&segment), sizeof(segment));
|
||||
|
||||
// Create section
|
||||
Section64 section{};
|
||||
std::ranges::copy(section_name, section.sectname);
|
||||
std::ranges::copy(segment_name, segment.segname);
|
||||
section.addr = 0x100000000;
|
||||
section.size = section_bytes.size();
|
||||
section.offset = static_cast<std::uint32_t>(section_offset);
|
||||
section.align = 0;
|
||||
section.reloff = 0;
|
||||
section.nreloc = 0;
|
||||
section.flags = 0;
|
||||
section.reserved1 = 0;
|
||||
section.reserved2 = 0;
|
||||
section.reserved3 = 0;
|
||||
|
||||
f.write(reinterpret_cast<const char*>(§ion), sizeof(section));
|
||||
|
||||
// Write section data
|
||||
f.write(reinterpret_cast<const char*>(section_bytes.data()), static_cast<std::streamsize>(section_bytes.size()));
|
||||
|
||||
f.close();
|
||||
return true;
|
||||
std::memcpy(buf.data() + section_offset, section_bytes.data(), section_bytes.size());
|
||||
return buf;
|
||||
}
|
||||
|
||||
// Helper function to create a minimal 32-bit Mach-O file with a __text section
|
||||
bool write_minimal_macho32_file(const std::string& path, const std::vector<std::uint8_t>& section_bytes)
|
||||
// Build a minimal 32-bit Mach-O binary in-memory with a __text section
|
||||
std::vector<std::uint8_t> build_minimal_macho32(const std::vector<std::uint8_t>& section_bytes)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open())
|
||||
return false;
|
||||
constexpr std::size_t load_cmd_size = sizeof(SegmentCommand32) + sizeof(Section32);
|
||||
constexpr std::size_t section_offset = sizeof(MachHeader32) + load_cmd_size;
|
||||
|
||||
// Calculate sizes
|
||||
constexpr std::size_t header_size = sizeof(MachHeader32);
|
||||
constexpr std::size_t segment_size = sizeof(SegmentCommand32);
|
||||
constexpr std::size_t section_size = sizeof(Section32);
|
||||
constexpr std::size_t load_cmd_size = segment_size + section_size;
|
||||
std::vector<std::uint8_t> buf(section_offset + section_bytes.size(), 0u);
|
||||
|
||||
// Section data will start after headers
|
||||
constexpr std::size_t section_offset = header_size + load_cmd_size;
|
||||
auto* header = reinterpret_cast<MachHeader32*>(buf.data());
|
||||
header->magic = mh_magic_32;
|
||||
header->cputype = 0x7;
|
||||
header->cpusubtype = 0x3;
|
||||
header->filetype = 0x2;
|
||||
header->ncmds = 1;
|
||||
header->sizeofcmds = static_cast<std::uint32_t>(load_cmd_size);
|
||||
|
||||
// Create Mach-O header
|
||||
MachHeader32 header{};
|
||||
header.magic = mh_magic_32;
|
||||
header.cputype = 0x7; // CPU_TYPE_X86
|
||||
header.cpusubtype = 0x3; // CPU_SUBTYPE_X86_ALL
|
||||
header.filetype = 0x2; // MH_EXECUTE
|
||||
header.ncmds = 1;
|
||||
header.sizeofcmds = static_cast<std::uint32_t>(load_cmd_size);
|
||||
header.flags = 0;
|
||||
auto* segment = reinterpret_cast<SegmentCommand32*>(buf.data() + sizeof(MachHeader32));
|
||||
segment->cmd = lc_segment;
|
||||
segment->cmdsize = static_cast<std::uint32_t>(load_cmd_size);
|
||||
std::ranges::copy(segment_name, segment->segname);
|
||||
segment->vmaddr = 0x1000;
|
||||
segment->vmsize = static_cast<std::uint32_t>(section_bytes.size());
|
||||
segment->fileoff = static_cast<std::uint32_t>(section_offset);
|
||||
segment->filesize = static_cast<std::uint32_t>(section_bytes.size());
|
||||
segment->maxprot = 7;
|
||||
segment->initprot = 5;
|
||||
segment->nsects = 1;
|
||||
|
||||
f.write(reinterpret_cast<const char*>(&header), sizeof(header));
|
||||
auto* section = reinterpret_cast<Section32*>(buf.data() + sizeof(MachHeader32) + sizeof(SegmentCommand32));
|
||||
std::ranges::copy(section_name, section->sectname);
|
||||
std::ranges::copy(segment_name, section->segname);
|
||||
section->addr = 0x1000;
|
||||
section->size = static_cast<std::uint32_t>(section_bytes.size());
|
||||
section->offset = static_cast<std::uint32_t>(section_offset);
|
||||
|
||||
// Create segment command
|
||||
SegmentCommand32 segment{};
|
||||
segment.cmd = lc_segment;
|
||||
segment.cmdsize = static_cast<std::uint32_t>(load_cmd_size);
|
||||
std::ranges::copy(segment_name, segment.segname);
|
||||
segment.vmaddr = 0x1000;
|
||||
segment.vmsize = static_cast<std::uint32_t>(section_bytes.size());
|
||||
segment.fileoff = static_cast<std::uint32_t>(section_offset);
|
||||
segment.filesize = static_cast<std::uint32_t>(section_bytes.size());
|
||||
segment.maxprot = 7; // VM_PROT_ALL
|
||||
segment.initprot = 5; // VM_PROT_READ | VM_PROT_EXECUTE
|
||||
segment.nsects = 1;
|
||||
segment.flags = 0;
|
||||
|
||||
f.write(reinterpret_cast<const char*>(&segment), sizeof(segment));
|
||||
|
||||
// Create section
|
||||
Section32 section{};
|
||||
std::ranges::copy(section_name, section.sectname);
|
||||
std::ranges::copy(segment_name, segment.segname);
|
||||
section.addr = 0x1000;
|
||||
section.size = static_cast<std::uint32_t>(section_bytes.size());
|
||||
section.offset = static_cast<std::uint32_t>(section_offset);
|
||||
section.align = 0;
|
||||
section.reloff = 0;
|
||||
section.nreloc = 0;
|
||||
section.flags = 0;
|
||||
section.reserved1 = 0;
|
||||
section.reserved2 = 0;
|
||||
|
||||
f.write(reinterpret_cast<const char*>(§ion), sizeof(section));
|
||||
|
||||
// Write section data
|
||||
f.write(reinterpret_cast<const char*>(section_bytes.data()), static_cast<std::streamsize>(section_bytes.size()));
|
||||
|
||||
f.close();
|
||||
return true;
|
||||
std::memcpy(buf.data() + section_offset, section_bytes.data(), section_bytes.size());
|
||||
return buf;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// Test scanning for a pattern that exists in a 64-bit Mach-O file
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanFindsPattern64)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_macho64.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x48, 0x89, 0xE5, 0x90, 0x90}; // push rbp; mov rbp, rsp; nop; nop
|
||||
ASSERT_TRUE(write_minimal_macho64_file(path.data(), bytes));
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x48, 0x89, 0xE5, 0x90, 0x90};
|
||||
const auto f = MemFdFile::create(build_minimal_macho64(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 48 89 E5", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 48 89 E5", "__text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
if (res.has_value())
|
||||
{
|
||||
EXPECT_EQ(res->target_offset, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Test scanning for a pattern that exists in a 32-bit Mach-O file
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanFindsPattern32)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_macho32.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x89, 0xE5, 0x90, 0x90}; // push ebp; mov ebp, esp; nop; nop
|
||||
ASSERT_TRUE(write_minimal_macho32_file(path.data(), bytes));
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x89, 0xE5, 0x90, 0x90};
|
||||
const auto f = MemFdFile::create(build_minimal_macho32(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 89 E5", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 89 E5", "__text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
if (res.has_value())
|
||||
{
|
||||
EXPECT_EQ(res->target_offset, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Test scanning for a pattern that does not exist
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanMissingPattern)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_macho_missing.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x00, 0x01, 0x02, 0x03};
|
||||
ASSERT_TRUE(write_minimal_macho64_file(path.data(), bytes));
|
||||
const auto f = MemFdFile::create(build_minimal_macho64(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "FF EE DD", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "FF EE DD", "__text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning for a pattern at a non-zero offset
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanPatternAtOffset)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_macho_offset.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x90, 0x90, 0x90, 0x55, 0x48, 0x89, 0xE5}; // nops then pattern
|
||||
ASSERT_TRUE(write_minimal_macho64_file(path.data(), bytes));
|
||||
const std::vector<std::uint8_t> bytes = {0x90, 0x90, 0x90, 0x55, 0x48, 0x89, 0xE5};
|
||||
const auto f = MemFdFile::create(build_minimal_macho64(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 48 89 E5", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 48 89 E5", "__text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
if (res.has_value())
|
||||
{
|
||||
EXPECT_EQ(res->target_offset, 3);
|
||||
}
|
||||
}
|
||||
|
||||
// Test scanning with wildcards
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanWithWildcard)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_macho_wildcard.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x48, 0x89, 0xE5, 0x90};
|
||||
ASSERT_TRUE(write_minimal_macho64_file(path.data(), bytes));
|
||||
const auto f = MemFdFile::create(build_minimal_macho64(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 ? 89 E5", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 ? 89 E5", "__text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning a non-existent file
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanNonExistentFile)
|
||||
{
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file("/non/existent/file.bin", "55 48", "__text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning an invalid (non-Mach-O) file
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanInvalidFile)
|
||||
{
|
||||
constexpr std::string_view path = "./test_invalid_macho.bin";
|
||||
std::ofstream f(path.data(), std::ios::binary);
|
||||
const std::vector<std::uint8_t> garbage = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
|
||||
f.write(reinterpret_cast<const char*>(garbage.data()), static_cast<std::streamsize>(garbage.size()));
|
||||
f.close();
|
||||
const auto f = MemFdFile::create(garbage);
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 48", "__text");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 48", "__text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning for a non-existent section
|
||||
TEST(unit_test_macho_pattern_scan_file, ScanNonExistentSection)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_macho_nosect.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x48, 0x89, 0xE5};
|
||||
ASSERT_TRUE(write_minimal_macho64_file(path.data(), bytes));
|
||||
const auto f = MemFdFile::create(build_minimal_macho64(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(path, "55 48", "__nonexistent");
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_file(f.path(), "55 48", "__nonexistent");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning with null module base address
|
||||
TEST(unit_test_macho_pattern_scan_loaded, ScanNullModule)
|
||||
{
|
||||
const auto res = MachOPatternScanner::scan_for_pattern_in_loaded_module(nullptr, "55 48", "__text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
// Test scanning in loaded module with invalid magic
|
||||
TEST(unit_test_macho_pattern_scan_loaded, ScanInvalidMagic)
|
||||
{
|
||||
std::vector<std::uint8_t> invalid_data(256, 0x00);
|
||||
|
||||
@@ -7,19 +7,18 @@ using namespace omath::pathfinding;
|
||||
TEST(NavigationMeshTests, SerializeDeserializeRoundTrip)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
Vector3<float> a{0.f,0.f,0.f};
|
||||
Vector3<float> b{1.f,0.f,0.f};
|
||||
Vector3<float> c{0.f,1.f,0.f};
|
||||
Vector3<float> a{0.f, 0.f, 0.f};
|
||||
Vector3<float> b{1.f, 0.f, 0.f};
|
||||
Vector3<float> c{0.f, 1.f, 0.f};
|
||||
|
||||
nav.m_vertex_map.emplace(a, std::vector<Vector3<float>>{b,c});
|
||||
nav.m_vertex_map.emplace(a, std::vector<Vector3<float>>{b, c});
|
||||
nav.m_vertex_map.emplace(b, std::vector<Vector3<float>>{a});
|
||||
nav.m_vertex_map.emplace(c, std::vector<Vector3<float>>{a});
|
||||
|
||||
auto data = nav.serialize();
|
||||
std::string data = nav.serialize();
|
||||
NavigationMesh nav2;
|
||||
EXPECT_NO_THROW(nav2.deserialize(data));
|
||||
|
||||
// verify neighbors preserved
|
||||
EXPECT_EQ(nav2.m_vertex_map.size(), nav.m_vertex_map.size());
|
||||
EXPECT_EQ(nav2.get_neighbors(a).size(), 2u);
|
||||
}
|
||||
@@ -27,7 +26,223 @@ TEST(NavigationMeshTests, SerializeDeserializeRoundTrip)
|
||||
TEST(NavigationMeshTests, GetClosestVertexWhenEmpty)
|
||||
{
|
||||
const NavigationMesh nav;
|
||||
constexpr Vector3<float> p{5.f,5.f,5.f};
|
||||
constexpr Vector3<float> p{5.f, 5.f, 5.f};
|
||||
const auto res = nav.get_closest_vertex(p);
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, SerializeEmptyMesh)
|
||||
{
|
||||
const NavigationMesh nav;
|
||||
const std::string data = nav.serialize();
|
||||
EXPECT_TRUE(data.empty());
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, DeserializeEmptyString)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
EXPECT_NO_THROW(nav.deserialize(""));
|
||||
EXPECT_TRUE(nav.empty());
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, SerializeProducesHumanReadableText)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
nav.m_vertex_map.emplace(Vector3<float>{1.f, 2.f, 3.f}, std::vector<Vector3<float>>{{4.f, 5.f, 6.f}});
|
||||
|
||||
const std::string data = nav.serialize();
|
||||
|
||||
// Must contain the vertex and neighbor coords as plain text
|
||||
EXPECT_NE(data.find("1"), std::string::npos);
|
||||
EXPECT_NE(data.find("2"), std::string::npos);
|
||||
EXPECT_NE(data.find("3"), std::string::npos);
|
||||
EXPECT_NE(data.find("4"), std::string::npos);
|
||||
EXPECT_NE(data.find("5"), std::string::npos);
|
||||
EXPECT_NE(data.find("6"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, DeserializeRestoresNeighborValues)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{1.f, 2.f, 3.f};
|
||||
const Vector3<float> n1{4.f, 5.f, 6.f};
|
||||
const Vector3<float> n2{7.f, 8.f, 9.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{n1, n2});
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
ASSERT_EQ(nav2.m_vertex_map.count(v), 1u);
|
||||
const auto& neighbors = nav2.get_neighbors(v);
|
||||
ASSERT_EQ(neighbors.size(), 2u);
|
||||
EXPECT_EQ(neighbors[0], n1);
|
||||
EXPECT_EQ(neighbors[1], n2);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, DeserializeOverwritesPreviousData)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
|
||||
// Load a different mesh into the same object
|
||||
NavigationMesh other;
|
||||
const Vector3<float> a{10.f, 20.f, 30.f};
|
||||
other.m_vertex_map.emplace(a, std::vector<Vector3<float>>{});
|
||||
|
||||
nav.deserialize(other.serialize());
|
||||
|
||||
EXPECT_EQ(nav.m_vertex_map.size(), 1u);
|
||||
EXPECT_EQ(nav.m_vertex_map.count(v), 0u);
|
||||
EXPECT_EQ(nav.m_vertex_map.count(a), 1u);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, RoundTripNegativeAndFractionalCoords)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{-1.5f, 0.25f, -3.75f};
|
||||
const Vector3<float> n{100.f, -200.f, 0.001f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{n});
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
ASSERT_EQ(nav2.m_vertex_map.count(v), 1u);
|
||||
const auto& neighbors = nav2.get_neighbors(v);
|
||||
ASSERT_EQ(neighbors.size(), 1u);
|
||||
EXPECT_NEAR(neighbors[0].x, n.x, 1e-3f);
|
||||
EXPECT_NEAR(neighbors[0].y, n.y, 1e-3f);
|
||||
EXPECT_NEAR(neighbors[0].z, n.z, 1e-3f);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, GetClosestVertexReturnsNearest)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> a{0.f, 0.f, 0.f};
|
||||
const Vector3<float> b{10.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(a, std::vector<Vector3<float>>{});
|
||||
nav.m_vertex_map.emplace(b, std::vector<Vector3<float>>{});
|
||||
|
||||
const auto res = nav.get_closest_vertex({1.f, 0.f, 0.f});
|
||||
ASSERT_TRUE(res.has_value());
|
||||
EXPECT_EQ(res.value(), a);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, VertexWithNoNeighborsRoundTrip)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{5.f, 5.f, 5.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
ASSERT_EQ(nav2.m_vertex_map.count(v), 1u);
|
||||
EXPECT_TRUE(nav2.get_neighbors(v).empty());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Vertex events
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
TEST(NavigationMeshTests, SetEventOnNonExistentVertexThrows)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{99.f, 99.f, 99.f};
|
||||
EXPECT_THROW(nav.set_event(v, "jump"), std::invalid_argument);
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, EventNotSetByDefault)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{0.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
|
||||
EXPECT_FALSE(nav.get_event(v).has_value());
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, SetAndGetEvent)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
nav.set_event(v, "jump");
|
||||
|
||||
const auto event = nav.get_event(v);
|
||||
ASSERT_TRUE(event.has_value());
|
||||
EXPECT_EQ(event.value(), "jump");
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, OverwriteEvent)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
nav.set_event(v, "jump");
|
||||
nav.set_event(v, "teleport");
|
||||
|
||||
EXPECT_EQ(nav.get_event(v).value(), "teleport");
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, ClearEvent)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
nav.set_event(v, "jump");
|
||||
nav.clear_event(v);
|
||||
|
||||
EXPECT_FALSE(nav.get_event(v).has_value());
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, EventRoundTripSerialization)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> a{0.f, 0.f, 0.f};
|
||||
const Vector3<float> b{1.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(a, std::vector<Vector3<float>>{b});
|
||||
nav.m_vertex_map.emplace(b, std::vector<Vector3<float>>{});
|
||||
nav.set_event(b, "jump");
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
ASSERT_FALSE(nav2.get_event(a).has_value());
|
||||
ASSERT_TRUE(nav2.get_event(b).has_value());
|
||||
EXPECT_EQ(nav2.get_event(b).value(), "jump");
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, MultipleEventsRoundTrip)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> a{0.f, 0.f, 0.f};
|
||||
const Vector3<float> b{1.f, 0.f, 0.f};
|
||||
const Vector3<float> c{2.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(a, std::vector<Vector3<float>>{});
|
||||
nav.m_vertex_map.emplace(b, std::vector<Vector3<float>>{});
|
||||
nav.m_vertex_map.emplace(c, std::vector<Vector3<float>>{});
|
||||
nav.set_event(a, "spawn");
|
||||
nav.set_event(c, "teleport");
|
||||
|
||||
NavigationMesh nav2;
|
||||
nav2.deserialize(nav.serialize());
|
||||
|
||||
EXPECT_EQ(nav2.get_event(a).value(), "spawn");
|
||||
EXPECT_FALSE(nav2.get_event(b).has_value());
|
||||
EXPECT_EQ(nav2.get_event(c).value(), "teleport");
|
||||
}
|
||||
|
||||
TEST(NavigationMeshTests, DeserializeClearsOldEvents)
|
||||
{
|
||||
NavigationMesh nav;
|
||||
const Vector3<float> v{0.f, 0.f, 0.f};
|
||||
nav.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
nav.set_event(v, "jump");
|
||||
|
||||
// Deserialize a mesh that has no events
|
||||
NavigationMesh empty_events;
|
||||
empty_events.m_vertex_map.emplace(v, std::vector<Vector3<float>>{});
|
||||
|
||||
nav.deserialize(empty_events.serialize());
|
||||
EXPECT_FALSE(nav.get_event(v).has_value());
|
||||
}
|
||||
|
||||
128
tests/general/unit_test_pe_memory_file_scan.cpp
Normal file
128
tests/general/unit_test_pe_memory_file_scan.cpp
Normal file
@@ -0,0 +1,128 @@
|
||||
// Tests for PePatternScanner::scan_for_pattern_in_memory_file
|
||||
#include <cstring>
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/utility/pe_pattern_scan.hpp>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
using namespace omath;
|
||||
|
||||
// Reuse the fake-module builder from unit_test_pe_pattern_scan_loaded.cpp but
|
||||
// lay out the buffer as a raw PE *file* (ptr_raw_data != virtual_address).
|
||||
static std::vector<std::byte> make_fake_pe_file(std::uint32_t virtual_address, std::uint32_t ptr_raw_data,
|
||||
std::uint32_t section_size,
|
||||
const std::vector<std::uint8_t>& code_bytes)
|
||||
{
|
||||
constexpr std::uint32_t e_lfanew = 0x80;
|
||||
constexpr std::uint32_t nt_sig = 0x4550;
|
||||
constexpr std::uint16_t opt_magic = 0x020B; // PE32+
|
||||
constexpr std::uint16_t num_sections = 1;
|
||||
constexpr std::uint16_t opt_hdr_size = 0xF0;
|
||||
constexpr std::uint32_t section_table_off = e_lfanew + 4 + 20 + opt_hdr_size;
|
||||
constexpr std::uint32_t section_header_size = 40;
|
||||
|
||||
const std::uint32_t total_size = ptr_raw_data + section_size + 0x100;
|
||||
std::vector<std::byte> buf(total_size, std::byte{0});
|
||||
|
||||
auto w16 = [&](std::size_t off, std::uint16_t v) { std::memcpy(buf.data() + off, &v, 2); };
|
||||
auto w32 = [&](std::size_t off, std::uint32_t v) { std::memcpy(buf.data() + off, &v, 4); };
|
||||
auto w64 = [&](std::size_t off, std::uint64_t v) { std::memcpy(buf.data() + off, &v, 8); };
|
||||
|
||||
// DOS header
|
||||
w16(0x00, 0x5A4D);
|
||||
w32(0x3C, e_lfanew);
|
||||
|
||||
// NT signature
|
||||
w32(e_lfanew, nt_sig);
|
||||
|
||||
// FileHeader
|
||||
const std::size_t fh_off = e_lfanew + 4;
|
||||
w16(fh_off + 2, num_sections);
|
||||
w16(fh_off + 16, opt_hdr_size);
|
||||
|
||||
// OptionalHeader PE32+
|
||||
const std::size_t opt_off = fh_off + 20;
|
||||
w16(opt_off + 0, opt_magic);
|
||||
w64(opt_off + 24, 0ULL); // ImageBase = 0 to keep virtual_base_addr in 32-bit range
|
||||
|
||||
// Section header (.text)
|
||||
const std::size_t sh_off = section_table_off;
|
||||
std::memcpy(buf.data() + sh_off, ".text", 5);
|
||||
w32(sh_off + 8, section_size); // VirtualSize
|
||||
w32(sh_off + 12, virtual_address); // VirtualAddress
|
||||
w32(sh_off + 16, section_size); // SizeOfRawData
|
||||
w32(sh_off + 20, ptr_raw_data); // PointerToRawData
|
||||
|
||||
// Place code at raw file offset
|
||||
const std::size_t copy_len = std::min(code_bytes.size(), static_cast<std::size_t>(section_size));
|
||||
for (std::size_t i = 0; i < copy_len; ++i)
|
||||
buf[ptr_raw_data + i] = std::byte{code_bytes[i]};
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
// ---- tests -----------------------------------------------------------------
|
||||
|
||||
TEST(unit_test_pe_memory_file_scan, finds_pattern)
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0x90, 0x01, 0x02, 0x03, 0x04};
|
||||
const auto buf = make_fake_pe_file(0x1000, 0x400, static_cast<std::uint32_t>(code.size()), code);
|
||||
|
||||
const auto result = PePatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf}, "90 01 02");
|
||||
|
||||
ASSERT_TRUE(result.has_value());
|
||||
EXPECT_EQ(result->target_offset, 0);
|
||||
EXPECT_EQ(result->raw_base_addr, 0x400u);
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_memory_file_scan, finds_pattern_with_wildcard)
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0xDE, 0xAD, 0xBE, 0xEF};
|
||||
const auto buf = make_fake_pe_file(0x2000, 0x600, static_cast<std::uint32_t>(code.size()), code);
|
||||
|
||||
const auto result =
|
||||
PePatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf}, "DE ?? BE EF");
|
||||
|
||||
ASSERT_TRUE(result.has_value());
|
||||
EXPECT_EQ(result->target_offset, 0);
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_memory_file_scan, pattern_not_found_returns_nullopt)
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0x01, 0x02, 0x03};
|
||||
const auto buf = make_fake_pe_file(0x1000, 0x400, static_cast<std::uint32_t>(code.size()), code);
|
||||
|
||||
const auto result =
|
||||
PePatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf}, "AA BB CC");
|
||||
|
||||
EXPECT_FALSE(result.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_memory_file_scan, invalid_data_returns_nullopt)
|
||||
{
|
||||
const std::vector<std::byte> garbage(128, std::byte{0xFF});
|
||||
const auto result = PePatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{garbage}, "FF FF");
|
||||
EXPECT_FALSE(result.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_memory_file_scan, empty_data_returns_nullopt)
|
||||
{
|
||||
const auto result = PePatternScanner::scan_for_pattern_in_memory_file({}, "FF");
|
||||
EXPECT_FALSE(result.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_memory_file_scan, raw_addr_differs_from_virtual_address)
|
||||
{
|
||||
// ptr_raw_data = 0x600, virtual_address = 0x3000 — different intentionally
|
||||
const std::vector<std::uint8_t> code = {0xCA, 0xFE, 0xBA, 0xBE};
|
||||
const auto buf = make_fake_pe_file(0x3000, 0x600, static_cast<std::uint32_t>(code.size()), code);
|
||||
|
||||
const auto result =
|
||||
PePatternScanner::scan_for_pattern_in_memory_file(std::span<const std::byte>{buf}, "CA FE BA BE");
|
||||
|
||||
ASSERT_TRUE(result.has_value());
|
||||
// raw_base_addr should be ptr_raw_data, not virtual_address
|
||||
EXPECT_EQ(result->raw_base_addr, 0x600u);
|
||||
// virtual_base_addr = virtual_address + image_base (image_base = 0)
|
||||
EXPECT_EQ(result->virtual_base_addr, 0x3000u);
|
||||
}
|
||||
@@ -1,114 +1,28 @@
|
||||
// Unit test for PePatternScanner::scan_for_pattern_in_file using a synthetic PE-like file
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/utility/pe_pattern_scan.hpp>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include "mem_fd_helper.hpp"
|
||||
|
||||
using namespace omath;
|
||||
|
||||
// Helper: write a trivial PE-like file with DOS header and a single section named .text
|
||||
static bool write_minimal_pe_file(const std::string& path, const std::vector<std::uint8_t>& section_bytes)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open()) return false;
|
||||
|
||||
// Write DOS header (e_magic = 0x5A4D, e_lfanew at offset 0x3C)
|
||||
std::vector<std::uint8_t> dos(64, 0);
|
||||
dos[0] = 'M'; dos[1] = 'Z';
|
||||
// e_lfanew -> place NT headers right after DOS (offset 0x80)
|
||||
std::uint32_t e_lfanew = 0x80;
|
||||
std::memcpy(dos.data() + 0x3C, &e_lfanew, sizeof(e_lfanew));
|
||||
f.write(reinterpret_cast<const char*>(dos.data()), dos.size());
|
||||
|
||||
// Pad up to e_lfanew
|
||||
if (f.tellp() < static_cast<std::streampos>(e_lfanew))
|
||||
{
|
||||
std::vector<char> pad(e_lfanew - static_cast<std::uint32_t>(f.tellp()), 0);
|
||||
f.write(pad.data(), pad.size());
|
||||
}
|
||||
|
||||
// NT headers signature 'PE\0\0'
|
||||
f.put('P'); f.put('E'); f.put('\0'); f.put('\0');
|
||||
|
||||
// FileHeader: machine, num_sections
|
||||
std::uint16_t machine = 0x8664; // x64
|
||||
std::uint16_t num_sections = 1;
|
||||
std::uint32_t dummy32 = 0;
|
||||
std::uint32_t dummy32b = 0;
|
||||
std::uint16_t size_optional = 0xF0; // reasonable
|
||||
std::uint16_t characteristics = 0;
|
||||
f.write(reinterpret_cast<const char*>(&machine), sizeof(machine));
|
||||
f.write(reinterpret_cast<const char*>(&num_sections), sizeof(num_sections));
|
||||
f.write(reinterpret_cast<const char*>(&dummy32), sizeof(dummy32));
|
||||
f.write(reinterpret_cast<const char*>(&dummy32b), sizeof(dummy32b));
|
||||
std::uint32_t num_symbols = 0;
|
||||
f.write(reinterpret_cast<const char*>(&num_symbols), sizeof(num_symbols));
|
||||
f.write(reinterpret_cast<const char*>(&size_optional), sizeof(size_optional));
|
||||
f.write(reinterpret_cast<const char*>(&characteristics), sizeof(characteristics));
|
||||
|
||||
// OptionalHeader (x64) minimal: magic 0x20b, image_base, size_of_code, size_of_headers
|
||||
std::uint16_t magic = 0x20b;
|
||||
f.write(reinterpret_cast<const char*>(&magic), sizeof(magic));
|
||||
// filler for rest of optional header up to size_optional
|
||||
std::vector<std::uint8_t> opt(size_optional - sizeof(magic), 0);
|
||||
// set size_code near end
|
||||
// we'll set image_base and size_code fields in reasonable positions for extractor
|
||||
// For simplicity, leave zeros; extractor primarily uses optional_header.image_base and size_code later,
|
||||
// but we will craft a SectionHeader that points to raw data we append below.
|
||||
f.write(reinterpret_cast<const char*>(opt.data()), opt.size());
|
||||
|
||||
// Section header (name 8 bytes, then remaining 36 bytes)
|
||||
char name[8] = {'.','t','e','x','t',0,0,0};
|
||||
f.write(name, 8);
|
||||
|
||||
// Write placeholder bytes for the rest of the section header and remember its start
|
||||
constexpr std::uint32_t section_header_rest = 36u;
|
||||
const std::streampos header_rest_pos = f.tellp();
|
||||
std::vector<char> placeholder(section_header_rest, 0);
|
||||
f.write(placeholder.data(), placeholder.size());
|
||||
|
||||
// Now write section raw data and remember its file offset
|
||||
const std::streampos data_pos = f.tellp();
|
||||
f.write(reinterpret_cast<const char*>(section_bytes.data()), static_cast<std::streamsize>(section_bytes.size()));
|
||||
|
||||
// Patch section header fields: virtual_size, virtual_address, size_raw_data, ptr_raw_data
|
||||
const std::uint32_t virtual_size = static_cast<std::uint32_t>(section_bytes.size());
|
||||
constexpr std::uint32_t virtual_address = 0x1000u;
|
||||
const std::uint32_t size_raw_data = static_cast<std::uint32_t>(section_bytes.size());
|
||||
const std::uint32_t ptr_raw_data = static_cast<std::uint32_t>(data_pos);
|
||||
|
||||
// Seek back to the header_rest_pos and write fields in order
|
||||
f.seekp(header_rest_pos, std::ios::beg);
|
||||
f.write(reinterpret_cast<const char*>(&virtual_size), sizeof(virtual_size));
|
||||
f.write(reinterpret_cast<const char*>(&virtual_address), sizeof(virtual_address));
|
||||
f.write(reinterpret_cast<const char*>(&size_raw_data), sizeof(size_raw_data));
|
||||
f.write(reinterpret_cast<const char*>(&ptr_raw_data), sizeof(ptr_raw_data));
|
||||
|
||||
// Seek back to end for consistency
|
||||
f.seekp(0, std::ios::end);
|
||||
|
||||
f.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_file, ScanFindsPattern)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_pe.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x8B, 0xEC, 0x90, 0x90}; // pattern at offset 0
|
||||
ASSERT_TRUE(write_minimal_pe_file(path.data(), bytes));
|
||||
const std::vector<std::uint8_t> bytes = {0x55, 0x8B, 0xEC, 0x90, 0x90};
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "55 8B EC", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "55 8B EC", ".text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_file, ScanMissingPattern)
|
||||
{
|
||||
constexpr std::string_view path = "./test_minimal_pe_2.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x00, 0x01, 0x02, 0x03};
|
||||
ASSERT_TRUE(write_minimal_pe_file(path.data(), bytes));
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "FF EE DD", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "FF EE DD", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
@@ -1,120 +1,89 @@
|
||||
// Additional tests for PePatternScanner to exercise edge cases and loaded-module scanning
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/utility/pe_pattern_scan.hpp>
|
||||
#include <vector>
|
||||
#include "mem_fd_helper.hpp"
|
||||
|
||||
using namespace omath;
|
||||
|
||||
static bool write_bytes(const std::string& path, const std::vector<std::uint8_t>& data)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open())
|
||||
return false;
|
||||
f.write(reinterpret_cast<const char*>(data.data()), data.size());
|
||||
return true;
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more, InvalidDosHeader)
|
||||
{
|
||||
constexpr std::string_view path = "./test_bad_dos.bin";
|
||||
std::vector<std::uint8_t> data(128, 0);
|
||||
// write wrong magic
|
||||
data[0] = 'N';
|
||||
data[1] = 'Z';
|
||||
ASSERT_TRUE(write_bytes(path.data(), data));
|
||||
const auto f = MemFdFile::create(data);
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "55 8B EC", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "55 8B EC", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more, InvalidNtSignature)
|
||||
{
|
||||
constexpr std::string_view path = "./test_bad_nt.bin";
|
||||
std::vector<std::uint8_t> data(256, 0);
|
||||
// valid DOS header
|
||||
data[0] = 'M';
|
||||
data[1] = 'Z';
|
||||
// point e_lfanew to 0x80
|
||||
constexpr std::uint32_t e_lfanew = 0x80;
|
||||
std::memcpy(data.data() + 0x3C, &e_lfanew, sizeof(e_lfanew));
|
||||
// write garbage at e_lfanew (not 'PE\0\0')
|
||||
data[e_lfanew + 0] = 'X';
|
||||
data[e_lfanew + 1] = 'Y';
|
||||
data[e_lfanew + 2] = 'Z';
|
||||
data[e_lfanew + 3] = 'W';
|
||||
ASSERT_TRUE(write_bytes(path.data(), data));
|
||||
const auto f = MemFdFile::create(data);
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "55 8B EC", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "55 8B EC", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more, SectionNotFound)
|
||||
{
|
||||
// reuse minimal writer but with section named .data and search .text
|
||||
constexpr std::string_view path = "./test_section_not_found.bin";
|
||||
std::ofstream f(path.data(), std::ios::binary);
|
||||
ASSERT_TRUE(f.is_open());
|
||||
// DOS
|
||||
std::vector<std::uint8_t> dos(64, 0);
|
||||
dos[0] = 'M';
|
||||
dos[1] = 'Z';
|
||||
std::uint32_t e_lfanew = 0x80;
|
||||
std::memcpy(dos.data() + 0x3C, &e_lfanew, sizeof(e_lfanew));
|
||||
f.write(reinterpret_cast<char*>(dos.data()), dos.size());
|
||||
// pad
|
||||
std::vector<char> pad(e_lfanew - static_cast<std::uint32_t>(f.tellp()), 0);
|
||||
f.write(pad.data(), pad.size());
|
||||
// NT sig
|
||||
f.put('P');
|
||||
f.put('E');
|
||||
f.put('\0');
|
||||
f.put('\0');
|
||||
// FileHeader minimal
|
||||
std::uint16_t machine = 0x8664;
|
||||
std::uint16_t num_sections = 1;
|
||||
std::uint32_t z = 0;
|
||||
std::uint32_t z2 = 0;
|
||||
std::uint32_t numsym = 0;
|
||||
std::uint16_t size_opt = 0xF0;
|
||||
std::uint16_t ch = 0;
|
||||
f.write(reinterpret_cast<char*>(&machine), sizeof(machine));
|
||||
f.write(reinterpret_cast<char*>(&num_sections), sizeof(num_sections));
|
||||
f.write(reinterpret_cast<char*>(&z), sizeof(z));
|
||||
f.write(reinterpret_cast<char*>(&z2), sizeof(z2));
|
||||
f.write(reinterpret_cast<char*>(&numsym), sizeof(numsym));
|
||||
f.write(reinterpret_cast<char*>(&size_opt), sizeof(size_opt));
|
||||
f.write(reinterpret_cast<char*>(&ch), sizeof(ch));
|
||||
// Optional header magic
|
||||
std::uint16_t magic = 0x20b;
|
||||
f.write(reinterpret_cast<char*>(&magic), sizeof(magic));
|
||||
std::vector<std::uint8_t> opt(size_opt - sizeof(magic), 0);
|
||||
f.write(reinterpret_cast<char*>(opt.data()), opt.size());
|
||||
// Section header named .data
|
||||
char name[8] = {'.', 'd', 'a', 't', 'a', 0, 0, 0};
|
||||
f.write(name, 8);
|
||||
std::uint32_t vs = 4, va = 0x1000, srd = 4, prd = 0x200;
|
||||
f.write(reinterpret_cast<char*>(&vs), 4);
|
||||
f.write(reinterpret_cast<char*>(&va), 4);
|
||||
f.write(reinterpret_cast<char*>(&srd), 4);
|
||||
f.write(reinterpret_cast<char*>(&prd), 4);
|
||||
std::vector<char> rest(16, 0);
|
||||
f.write(rest.data(), rest.size());
|
||||
// section bytes
|
||||
std::vector<std::uint8_t> sec = {0x00, 0x01, 0x02, 0x03};
|
||||
f.write(reinterpret_cast<char*>(sec.data()), sec.size());
|
||||
f.close();
|
||||
// Minimal PE with a .data section; scanning for .text should fail
|
||||
constexpr std::uint32_t e_lfanew = 0x80u;
|
||||
constexpr std::uint16_t size_opt = 0xF0u;
|
||||
constexpr std::size_t nt_off = e_lfanew;
|
||||
constexpr std::size_t fh_off = nt_off + 4;
|
||||
constexpr std::size_t oh_off = fh_off + 20;
|
||||
constexpr std::size_t sh_off = oh_off + size_opt;
|
||||
constexpr std::size_t data_off = sh_off + 44;
|
||||
|
||||
auto res = PePatternScanner::scan_for_pattern_in_file(path, "00 01", ".text");
|
||||
const std::vector<std::uint8_t> sec_data = {0x00, 0x01, 0x02, 0x03};
|
||||
std::vector<std::uint8_t> buf(data_off + sec_data.size(), 0u);
|
||||
|
||||
buf[0] = 'M'; buf[1] = 'Z';
|
||||
std::memcpy(buf.data() + 0x3C, &e_lfanew, 4);
|
||||
buf[nt_off] = 'P'; buf[nt_off + 1] = 'E';
|
||||
|
||||
const std::uint16_t machine = 0x8664u, num_sections = 1u;
|
||||
std::memcpy(buf.data() + fh_off, &machine, 2);
|
||||
std::memcpy(buf.data() + fh_off + 2, &num_sections, 2);
|
||||
std::memcpy(buf.data() + fh_off + 16, &size_opt, 2);
|
||||
|
||||
const std::uint16_t magic = 0x20Bu;
|
||||
std::memcpy(buf.data() + oh_off, &magic, 2);
|
||||
|
||||
const char name[8] = {'.','d','a','t','a',0,0,0};
|
||||
std::memcpy(buf.data() + sh_off, name, 8);
|
||||
|
||||
const std::uint32_t vs = 4u, va = 0x1000u, srd = 4u, prd = static_cast<std::uint32_t>(data_off);
|
||||
std::memcpy(buf.data() + sh_off + 8, &vs, 4);
|
||||
std::memcpy(buf.data() + sh_off + 12, &va, 4);
|
||||
std::memcpy(buf.data() + sh_off + 16, &srd, 4);
|
||||
std::memcpy(buf.data() + sh_off + 20, &prd, 4);
|
||||
std::memcpy(buf.data() + data_off, sec_data.data(), sec_data.size());
|
||||
|
||||
const auto f = MemFdFile::create(buf);
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "00 01", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more, LoadedModuleScanFinds)
|
||||
{
|
||||
// Create an in-memory buffer that mimics loaded module layout
|
||||
// Define local header structs matching those in source
|
||||
struct DosHeader
|
||||
{
|
||||
std::uint16_t e_magic;
|
||||
@@ -158,9 +127,9 @@ TEST(unit_test_pe_pattern_scan_more, LoadedModuleScanFinds)
|
||||
std::uint32_t base_of_code;
|
||||
std::uint64_t image_base;
|
||||
std::uint32_t section_alignment;
|
||||
std::uint32_t file_alignment; /* rest omitted */
|
||||
std::uint32_t file_alignment;
|
||||
std::uint32_t size_image;
|
||||
std::uint32_t size_headers; /* keep space */
|
||||
std::uint32_t size_headers;
|
||||
std::uint8_t pad[200];
|
||||
};
|
||||
struct SectionHeader
|
||||
@@ -188,44 +157,38 @@ TEST(unit_test_pe_pattern_scan_more, LoadedModuleScanFinds)
|
||||
};
|
||||
|
||||
const std::vector<std::uint8_t> pattern_bytes = {0xDE, 0xAD, 0xBE, 0xEF, 0x90};
|
||||
constexpr std::uint32_t base_of_code = 0x200; // will place bytes at offset 0x200
|
||||
constexpr std::uint32_t base_of_code = 0x200;
|
||||
const std::uint32_t size_code = static_cast<std::uint32_t>(pattern_bytes.size());
|
||||
|
||||
const std::uint32_t bufsize = 0x400 + size_code;
|
||||
std::vector<std::uint8_t> buf(bufsize, 0);
|
||||
|
||||
// DOS header
|
||||
const auto dos = reinterpret_cast<DosHeader*>(buf.data());
|
||||
dos->e_magic = 0x5A4D;
|
||||
dos->e_magic = 0x5A4D;
|
||||
dos->e_lfanew = 0x80;
|
||||
|
||||
// NT headers
|
||||
const auto nt = reinterpret_cast<ImageNtHeadersX64*>(buf.data() + dos->e_lfanew);
|
||||
nt->signature = 0x4550; // 'PE\0\0'
|
||||
nt->file_header.machine = 0x8664;
|
||||
nt->file_header.num_sections = 1;
|
||||
nt->file_header.size_optional_header = static_cast<std::uint16_t>(sizeof(OptionalHeaderX64));
|
||||
nt->signature = 0x4550;
|
||||
nt->file_header.machine = 0x8664;
|
||||
nt->file_header.num_sections = 1;
|
||||
nt->file_header.size_optional_header = static_cast<std::uint16_t>(sizeof(OptionalHeaderX64));
|
||||
nt->optional_header.magic = 0x020B;
|
||||
nt->optional_header.base_of_code = base_of_code;
|
||||
nt->optional_header.size_code = size_code;
|
||||
|
||||
nt->optional_header.magic = 0x020B; // x64
|
||||
nt->optional_header.base_of_code = base_of_code;
|
||||
nt->optional_header.size_code = size_code;
|
||||
|
||||
// Compute section table offset: e_lfanew + 4 (sig) + FileHeader + OptionalHeader
|
||||
const std::size_t section_table_off =
|
||||
static_cast<std::size_t>(dos->e_lfanew) + 4 + sizeof(FileHeader) + sizeof(OptionalHeaderX64);
|
||||
nt->optional_header.size_headers = static_cast<std::uint32_t>(section_table_off + sizeof(SectionHeader));
|
||||
|
||||
// Section header (.text)
|
||||
const auto sect = reinterpret_cast<SectionHeader*>(buf.data() + section_table_off);
|
||||
std::memset(sect, 0, sizeof(SectionHeader));
|
||||
std::memcpy(sect->name, ".text", 5);
|
||||
sect->virtual_size = size_code;
|
||||
sect->virtual_size = size_code;
|
||||
sect->virtual_address = base_of_code;
|
||||
sect->size_raw_data = size_code;
|
||||
sect->ptr_raw_data = base_of_code;
|
||||
sect->characteristics = 0x60000020; // code | execute | read
|
||||
sect->size_raw_data = size_code;
|
||||
sect->ptr_raw_data = base_of_code;
|
||||
sect->characteristics = 0x60000020;
|
||||
|
||||
// place code at base_of_code
|
||||
std::memcpy(buf.data() + base_of_code, pattern_bytes.data(), pattern_bytes.size());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_loaded_module(buf.data(), "DE AD BE EF", ".text");
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <omath/utility/pe_pattern_scan.hpp>
|
||||
#include <vector>
|
||||
#include "mem_fd_helper.hpp"
|
||||
|
||||
using namespace omath;
|
||||
|
||||
@@ -19,95 +20,6 @@ struct TestFileHeader
|
||||
std::uint16_t characteristics;
|
||||
};
|
||||
|
||||
static bool write_bytes(const std::string& path, const std::vector<std::uint8_t>& data)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open())
|
||||
return false;
|
||||
f.write(reinterpret_cast<const char*>(data.data()), data.size());
|
||||
return true;
|
||||
}
|
||||
|
||||
// Helper: write a trivial PE-like file with DOS header and a single section named .text
|
||||
static bool write_minimal_pe_file(const std::string& path, const std::vector<std::uint8_t>& section_bytes)
|
||||
{
|
||||
std::ofstream f(path, std::ios::binary);
|
||||
if (!f.is_open())
|
||||
return false;
|
||||
|
||||
// Write DOS header (e_magic = 0x5A4D, e_lfanew at offset 0x3C)
|
||||
std::vector<std::uint8_t> dos(64, 0);
|
||||
dos[0] = 'M';
|
||||
dos[1] = 'Z';
|
||||
std::uint32_t e_lfanew = 0x80;
|
||||
std::memcpy(dos.data() + 0x3C, &e_lfanew, sizeof(e_lfanew));
|
||||
f.write(reinterpret_cast<const char*>(dos.data()), dos.size());
|
||||
|
||||
// Pad up to e_lfanew
|
||||
if (f.tellp() < static_cast<std::streampos>(e_lfanew))
|
||||
{
|
||||
std::vector<char> pad(e_lfanew - static_cast<std::uint32_t>(f.tellp()), 0);
|
||||
f.write(pad.data(), pad.size());
|
||||
}
|
||||
|
||||
// NT headers signature 'PE\0\0'
|
||||
f.put('P');
|
||||
f.put('E');
|
||||
f.put('\0');
|
||||
f.put('\0');
|
||||
|
||||
// FileHeader minimal
|
||||
std::uint16_t machine = 0x8664; // x64
|
||||
std::uint16_t num_sections = 1;
|
||||
std::uint32_t dummy32 = 0;
|
||||
std::uint32_t dummy32b = 0;
|
||||
std::uint16_t size_optional = 0xF0;
|
||||
std::uint16_t characteristics = 0;
|
||||
f.write(reinterpret_cast<const char*>(&machine), sizeof(machine));
|
||||
f.write(reinterpret_cast<const char*>(&num_sections), sizeof(num_sections));
|
||||
f.write(reinterpret_cast<const char*>(&dummy32), sizeof(dummy32));
|
||||
f.write(reinterpret_cast<const char*>(&dummy32b), sizeof(dummy32b));
|
||||
std::uint32_t num_symbols = 0;
|
||||
f.write(reinterpret_cast<const char*>(&num_symbols), sizeof(num_symbols));
|
||||
f.write(reinterpret_cast<const char*>(&size_optional), sizeof(size_optional));
|
||||
f.write(reinterpret_cast<const char*>(&characteristics), sizeof(characteristics));
|
||||
|
||||
// OptionalHeader minimal filler
|
||||
std::uint16_t magic = 0x20b;
|
||||
f.write(reinterpret_cast<const char*>(&magic), sizeof(magic));
|
||||
std::vector<std::uint8_t> opt(size_optional - sizeof(magic), 0);
|
||||
f.write(reinterpret_cast<const char*>(opt.data()), opt.size());
|
||||
|
||||
// Section header (name 8 bytes, then remaining 36 bytes)
|
||||
char name[8] = {'.', 't', 'e', 'x', 't', 0, 0, 0};
|
||||
f.write(name, 8);
|
||||
|
||||
constexpr std::uint32_t section_header_rest = 36u;
|
||||
const std::streampos header_rest_pos = f.tellp();
|
||||
std::vector<char> placeholder(section_header_rest, 0);
|
||||
f.write(placeholder.data(), placeholder.size());
|
||||
|
||||
// Now write section raw data and remember its file offset
|
||||
const std::streampos data_pos = f.tellp();
|
||||
f.write(reinterpret_cast<const char*>(section_bytes.data()), static_cast<std::streamsize>(section_bytes.size()));
|
||||
|
||||
// Patch section header fields
|
||||
const std::uint32_t virtual_size = static_cast<std::uint32_t>(section_bytes.size());
|
||||
constexpr std::uint32_t virtual_address = 0x1000u;
|
||||
const std::uint32_t size_raw_data = static_cast<std::uint32_t>(section_bytes.size());
|
||||
const std::uint32_t ptr_raw_data = static_cast<std::uint32_t>(data_pos);
|
||||
|
||||
f.seekp(header_rest_pos, std::ios::beg);
|
||||
f.write(reinterpret_cast<const char*>(&virtual_size), sizeof(virtual_size));
|
||||
f.write(reinterpret_cast<const char*>(&virtual_address), sizeof(virtual_address));
|
||||
f.write(reinterpret_cast<const char*>(&size_raw_data), sizeof(size_raw_data));
|
||||
f.write(reinterpret_cast<const char*>(&ptr_raw_data), sizeof(ptr_raw_data));
|
||||
f.seekp(0, std::ios::end);
|
||||
|
||||
f.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more2, LoadedModuleNullBaseReturnsNull)
|
||||
{
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_loaded_module(nullptr, "DE AD");
|
||||
@@ -116,7 +28,6 @@ TEST(unit_test_pe_pattern_scan_more2, LoadedModuleNullBaseReturnsNull)
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more2, LoadedModuleInvalidOptionalHeaderReturnsNull)
|
||||
{
|
||||
// Construct in-memory buffer with DOS header but invalid optional header magic
|
||||
std::vector<std::uint8_t> buf(0x200, 0);
|
||||
struct DosHeader
|
||||
{
|
||||
@@ -128,19 +39,11 @@ TEST(unit_test_pe_pattern_scan_more2, LoadedModuleInvalidOptionalHeaderReturnsNu
|
||||
dos->e_magic = 0x5A4D;
|
||||
dos->e_lfanew = 0x80;
|
||||
|
||||
// Place an NT header with wrong optional magic at e_lfanew
|
||||
const auto nt_ptr = buf.data() + dos->e_lfanew;
|
||||
// write signature
|
||||
nt_ptr[0] = 'P';
|
||||
nt_ptr[1] = 'E';
|
||||
nt_ptr[2] = 0;
|
||||
nt_ptr[3] = 0;
|
||||
// craft FileHeader with size_optional_header large enough
|
||||
nt_ptr[0] = 'P'; nt_ptr[1] = 'E'; nt_ptr[2] = 0; nt_ptr[3] = 0;
|
||||
|
||||
constexpr std::uint16_t size_opt = 0xE0;
|
||||
// file header starts at offset 4
|
||||
std::memcpy(nt_ptr + 4 + 12, &size_opt,
|
||||
sizeof(size_opt)); // size_optional_header located after 12 bytes into FileHeader
|
||||
// write optional header magic to be invalid value
|
||||
std::memcpy(nt_ptr + 4 + 12, &size_opt, sizeof(size_opt));
|
||||
constexpr std::uint16_t bad_magic = 0x9999;
|
||||
std::memcpy(nt_ptr + 4 + sizeof(std::uint32_t) + sizeof(std::uint16_t) + sizeof(std::uint16_t), &bad_magic,
|
||||
sizeof(bad_magic));
|
||||
@@ -151,13 +54,11 @@ TEST(unit_test_pe_pattern_scan_more2, LoadedModuleInvalidOptionalHeaderReturnsNu
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more2, FileX86OptionalHeaderScanFindsPattern)
|
||||
{
|
||||
constexpr std::string_view path = "./test_pe_x86.bin";
|
||||
const std::vector<std::uint8_t> pattern = {0xDE, 0xAD, 0xBE, 0xEF};
|
||||
const auto f = MemFdFile::create(build_minimal_pe(pattern));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
// Use helper from this file to write a consistent minimal PE file with .text section
|
||||
ASSERT_TRUE(write_minimal_pe_file(path.data(), pattern));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "DE AD BE EF", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "DE AD BE EF", ".text");
|
||||
ASSERT_TRUE(res.has_value());
|
||||
EXPECT_GE(res->virtual_base_addr, 0u);
|
||||
EXPECT_GE(res->raw_base_addr, 0u);
|
||||
@@ -166,97 +67,73 @@ TEST(unit_test_pe_pattern_scan_more2, FileX86OptionalHeaderScanFindsPattern)
|
||||
|
||||
TEST(unit_test_pe_pattern_scan_more2, FilePatternNotFoundReturnsNull)
|
||||
{
|
||||
const std::string path = "./test_pe_no_pattern.bin";
|
||||
std::vector<std::uint8_t> data(512, 0);
|
||||
// minimal DOS/NT headers to make extract_section fail earlier or return empty data
|
||||
data[0] = 'M';
|
||||
data[1] = 'Z';
|
||||
data[0] = 'M'; data[1] = 'Z';
|
||||
constexpr std::uint32_t e_lfanew = 0x80;
|
||||
std::memcpy(data.data() + 0x3C, &e_lfanew, sizeof(e_lfanew));
|
||||
// NT signature
|
||||
data[e_lfanew + 0] = 'P';
|
||||
data[e_lfanew + 1] = 'E';
|
||||
data[e_lfanew + 2] = 0;
|
||||
data[e_lfanew + 3] = 0;
|
||||
// FileHeader: one section, size_optional_header set low
|
||||
data[e_lfanew + 0] = 'P'; data[e_lfanew + 1] = 'E';
|
||||
|
||||
constexpr std::uint16_t num_sections = 1;
|
||||
constexpr std::uint16_t size_optional_header = 0xE0;
|
||||
std::memcpy(data.data() + e_lfanew + 6, &num_sections, sizeof(num_sections));
|
||||
std::memcpy(data.data() + e_lfanew + 4 + 12, &size_optional_header, sizeof(size_optional_header));
|
||||
// Optional header magic x64
|
||||
|
||||
constexpr std::uint16_t magic = 0x020B;
|
||||
std::memcpy(data.data() + e_lfanew + 4 + sizeof(TestFileHeader), &magic, sizeof(magic));
|
||||
// Section header .text with small data that does not contain the pattern
|
||||
|
||||
constexpr std::size_t offset_to_segment_table = e_lfanew + 4 + sizeof(TestFileHeader) + size_optional_header;
|
||||
constexpr char name[8] = {'.', 't', 'e', 'x', 't', 0, 0, 0};
|
||||
std::memcpy(data.data() + offset_to_segment_table, name, 8);
|
||||
std::uint32_t vs = 4, va = 0x1000, srd = 4, prd = 0x200;
|
||||
std::memcpy(data.data() + offset_to_segment_table + 8, &vs, 4);
|
||||
std::memcpy(data.data() + offset_to_segment_table + 12, &va, 4);
|
||||
std::memcpy(data.data() + offset_to_segment_table + 8, &vs, 4);
|
||||
std::memcpy(data.data() + offset_to_segment_table + 12, &va, 4);
|
||||
std::memcpy(data.data() + offset_to_segment_table + 16, &srd, 4);
|
||||
std::memcpy(data.data() + offset_to_segment_table + 20, &prd, 4);
|
||||
// write file
|
||||
ASSERT_TRUE(write_bytes(path, data));
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "AA BB CC", ".text");
|
||||
const auto f = MemFdFile::create(data);
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "AA BB CC", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
// Extra tests for pe_pattern_scan edge cases (on-disk API)
|
||||
|
||||
TEST(PePatternScanMore2, PatternAtStartFound)
|
||||
{
|
||||
const std::string path = "./test_pe_more_start.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x90, 0x01, 0x02, 0x03, 0x04};
|
||||
ASSERT_TRUE(write_minimal_pe_file(path, bytes));
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "90 01 02", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "90 01 02", ".text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(PePatternScanMore2, PatternAtEndFound)
|
||||
{
|
||||
const std::string path = "./test_pe_more_end.bin";
|
||||
std::vector<std::uint8_t> bytes = {0x00, 0x11, 0x22, 0x33, 0x44};
|
||||
ASSERT_TRUE(write_minimal_pe_file(path, bytes));
|
||||
const std::vector<std::uint8_t> bytes = {0x00, 0x11, 0x22, 0x33, 0x44};
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "22 33 44", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "22 33 44", ".text");
|
||||
if (!res.has_value())
|
||||
{
|
||||
// Try to locate the section header and print the raw section bytes the scanner would read
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
ASSERT_TRUE(in.is_open());
|
||||
// search for ".text" name
|
||||
in.seekg(0, std::ios::beg);
|
||||
std::vector<char> filebuf((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
const auto it = std::search(filebuf.begin(), filebuf.end(), std::begin(".text"), std::end(".text") - 1);
|
||||
if (it != filebuf.end())
|
||||
// Debug: inspect section header via the memfd path
|
||||
std::ifstream in(f.path(), std::ios::binary);
|
||||
if (in.is_open())
|
||||
{
|
||||
const size_t pos = std::distance(filebuf.begin(), it);
|
||||
// after name, next fields: virtual_size (4), virtual_address(4), size_raw_data(4), ptr_raw_data(4)
|
||||
const size_t meta_off = pos + 8;
|
||||
uint32_t virtual_size{};
|
||||
uint32_t virtual_address{};
|
||||
uint32_t size_raw_data{};
|
||||
uint32_t ptr_raw_data{};
|
||||
std::memcpy(&virtual_size, filebuf.data() + meta_off, sizeof(virtual_size));
|
||||
std::memcpy(&virtual_address, filebuf.data() + meta_off + 4, sizeof(virtual_address));
|
||||
std::memcpy(&size_raw_data, filebuf.data() + meta_off + 8, sizeof(size_raw_data));
|
||||
std::memcpy(&ptr_raw_data, filebuf.data() + meta_off + 12, sizeof(ptr_raw_data));
|
||||
|
||||
std::cerr << "Parsed section header: virtual_size=" << virtual_size << " virtual_address=0x" << std::hex
|
||||
<< virtual_address << std::dec << " size_raw_data=" << size_raw_data
|
||||
<< " ptr_raw_data=" << ptr_raw_data << "\n";
|
||||
|
||||
if (ptr_raw_data + size_raw_data <= filebuf.size())
|
||||
std::vector<char> filebuf((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||
const auto it = std::search(filebuf.begin(), filebuf.end(), std::begin(".text"), std::end(".text") - 1);
|
||||
if (it != filebuf.end())
|
||||
{
|
||||
std::cerr << "Extracted section bytes:\n";
|
||||
for (size_t i = 0; i < size_raw_data; i += 16)
|
||||
{
|
||||
std::fprintf(stderr, "%04zx: ", i);
|
||||
for (size_t j = 0; j < 16 && i + j < size_raw_data; ++j)
|
||||
std::fprintf(stderr, "%02x ", static_cast<uint8_t>(filebuf[ptr_raw_data + i + j]));
|
||||
std::fprintf(stderr, "\n");
|
||||
}
|
||||
const std::size_t pos = std::distance(filebuf.begin(), it);
|
||||
const std::size_t meta_off = pos + 8;
|
||||
std::uint32_t virtual_size{}, virtual_address{}, size_raw_data{}, ptr_raw_data{};
|
||||
std::memcpy(&virtual_size, filebuf.data() + meta_off, sizeof(virtual_size));
|
||||
std::memcpy(&virtual_address, filebuf.data() + meta_off + 4, sizeof(virtual_address));
|
||||
std::memcpy(&size_raw_data, filebuf.data() + meta_off + 8, sizeof(size_raw_data));
|
||||
std::memcpy(&ptr_raw_data, filebuf.data() + meta_off + 12, sizeof(ptr_raw_data));
|
||||
std::cerr << "Parsed section header: virtual_size=" << virtual_size << " virtual_address=0x"
|
||||
<< std::hex << virtual_address << std::dec << " size_raw_data=" << size_raw_data
|
||||
<< " ptr_raw_data=" << ptr_raw_data << "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -265,30 +142,30 @@ TEST(PePatternScanMore2, PatternAtEndFound)
|
||||
|
||||
TEST(PePatternScanMore2, WildcardMatches)
|
||||
{
|
||||
const std::string path = "./test_pe_more_wild.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0xDE, 0xAD, 0xBE, 0xEF};
|
||||
ASSERT_TRUE(write_minimal_pe_file(path, bytes));
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "DE ?? BE", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "DE ?? BE", ".text");
|
||||
EXPECT_TRUE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(PePatternScanMore2, PatternLongerThanBuffer)
|
||||
{
|
||||
const std::string path = "./test_pe_more_small.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0xAA, 0xBB};
|
||||
ASSERT_TRUE(write_minimal_pe_file(path, bytes));
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "AA BB CC", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "AA BB CC", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
TEST(PePatternScanMore2, InvalidPatternParse)
|
||||
{
|
||||
const std::string path = "./test_pe_more_invalid.bin";
|
||||
const std::vector<std::uint8_t> bytes = {0x01, 0x02, 0x03};
|
||||
ASSERT_TRUE(write_minimal_pe_file(path, bytes));
|
||||
const auto f = MemFdFile::create(build_minimal_pe(bytes));
|
||||
ASSERT_TRUE(f.valid());
|
||||
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(path, "01 GG 03", ".text");
|
||||
const auto res = PePatternScanner::scan_for_pattern_in_file(f.path(), "01 GG 03", ".text");
|
||||
EXPECT_FALSE(res.has_value());
|
||||
}
|
||||
|
||||
402
tests/general/unit_test_quaternion.cpp
Normal file
402
tests/general/unit_test_quaternion.cpp
Normal file
@@ -0,0 +1,402 @@
|
||||
//
|
||||
// Created by vlad on 3/1/2026.
|
||||
//
|
||||
#include <omath/linear_algebra/quaternion.hpp>
|
||||
#include <cmath>
|
||||
#include <gtest/gtest.h>
|
||||
#include <numbers>
|
||||
|
||||
using namespace omath;
|
||||
|
||||
static constexpr float kEps = 1e-5f;
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
static void expect_quat_near(const Quaternion<float>& a, const Quaternion<float>& b, float eps = kEps)
|
||||
{
|
||||
EXPECT_NEAR(a.x, b.x, eps);
|
||||
EXPECT_NEAR(a.y, b.y, eps);
|
||||
EXPECT_NEAR(a.z, b.z, eps);
|
||||
EXPECT_NEAR(a.w, b.w, eps);
|
||||
}
|
||||
|
||||
static void expect_vec3_near(const Vector3<float>& a, const Vector3<float>& b, float eps = kEps)
|
||||
{
|
||||
EXPECT_NEAR(a.x, b.x, eps);
|
||||
EXPECT_NEAR(a.y, b.y, eps);
|
||||
EXPECT_NEAR(a.z, b.z, eps);
|
||||
}
|
||||
|
||||
// ── Constructors ─────────────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, DefaultConstructorIsIdentity)
|
||||
{
|
||||
constexpr Quaternion<float> q;
|
||||
EXPECT_FLOAT_EQ(q.x, 0.f);
|
||||
EXPECT_FLOAT_EQ(q.y, 0.f);
|
||||
EXPECT_FLOAT_EQ(q.z, 0.f);
|
||||
EXPECT_FLOAT_EQ(q.w, 1.f);
|
||||
}
|
||||
|
||||
TEST(Quaternion, ValueConstructor)
|
||||
{
|
||||
constexpr Quaternion<float> q{1.f, 2.f, 3.f, 4.f};
|
||||
EXPECT_FLOAT_EQ(q.x, 1.f);
|
||||
EXPECT_FLOAT_EQ(q.y, 2.f);
|
||||
EXPECT_FLOAT_EQ(q.z, 3.f);
|
||||
EXPECT_FLOAT_EQ(q.w, 4.f);
|
||||
}
|
||||
|
||||
TEST(Quaternion, DoubleInstantiation)
|
||||
{
|
||||
constexpr Quaternion<double> q{0.0, 0.0, 0.0, 1.0};
|
||||
EXPECT_DOUBLE_EQ(q.w, 1.0);
|
||||
}
|
||||
|
||||
// ── Equality ─────────────────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, EqualityOperators)
|
||||
{
|
||||
constexpr Quaternion<float> a{1.f, 2.f, 3.f, 4.f};
|
||||
constexpr Quaternion<float> b{1.f, 2.f, 3.f, 4.f};
|
||||
constexpr Quaternion<float> c{1.f, 2.f, 3.f, 5.f};
|
||||
|
||||
EXPECT_TRUE(a == b);
|
||||
EXPECT_FALSE(a == c);
|
||||
EXPECT_FALSE(a != b);
|
||||
EXPECT_TRUE(a != c);
|
||||
}
|
||||
|
||||
// ── Arithmetic ───────────────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, ScalarMultiply)
|
||||
{
|
||||
constexpr Quaternion<float> q{1.f, 2.f, 3.f, 4.f};
|
||||
constexpr auto r = q * 2.f;
|
||||
EXPECT_FLOAT_EQ(r.x, 2.f);
|
||||
EXPECT_FLOAT_EQ(r.y, 4.f);
|
||||
EXPECT_FLOAT_EQ(r.z, 6.f);
|
||||
EXPECT_FLOAT_EQ(r.w, 8.f);
|
||||
}
|
||||
|
||||
TEST(Quaternion, ScalarMultiplyAssign)
|
||||
{
|
||||
Quaternion<float> q{1.f, 2.f, 3.f, 4.f};
|
||||
q *= 3.f;
|
||||
EXPECT_FLOAT_EQ(q.x, 3.f);
|
||||
EXPECT_FLOAT_EQ(q.y, 6.f);
|
||||
EXPECT_FLOAT_EQ(q.z, 9.f);
|
||||
EXPECT_FLOAT_EQ(q.w, 12.f);
|
||||
}
|
||||
|
||||
TEST(Quaternion, Addition)
|
||||
{
|
||||
constexpr Quaternion<float> a{1.f, 2.f, 3.f, 4.f};
|
||||
constexpr Quaternion<float> b{4.f, 3.f, 2.f, 1.f};
|
||||
constexpr auto r = a + b;
|
||||
EXPECT_FLOAT_EQ(r.x, 5.f);
|
||||
EXPECT_FLOAT_EQ(r.y, 5.f);
|
||||
EXPECT_FLOAT_EQ(r.z, 5.f);
|
||||
EXPECT_FLOAT_EQ(r.w, 5.f);
|
||||
}
|
||||
|
||||
TEST(Quaternion, AdditionAssign)
|
||||
{
|
||||
Quaternion<float> a{1.f, 0.f, 0.f, 0.f};
|
||||
const Quaternion<float> b{0.f, 1.f, 0.f, 0.f};
|
||||
a += b;
|
||||
EXPECT_FLOAT_EQ(a.x, 1.f);
|
||||
EXPECT_FLOAT_EQ(a.y, 1.f);
|
||||
}
|
||||
|
||||
TEST(Quaternion, UnaryNegation)
|
||||
{
|
||||
constexpr Quaternion<float> q{1.f, -2.f, 3.f, -4.f};
|
||||
constexpr auto r = -q;
|
||||
EXPECT_FLOAT_EQ(r.x, -1.f);
|
||||
EXPECT_FLOAT_EQ(r.y, 2.f);
|
||||
EXPECT_FLOAT_EQ(r.z, -3.f);
|
||||
EXPECT_FLOAT_EQ(r.w, 4.f);
|
||||
}
|
||||
|
||||
// ── Hamilton product ──────────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, MultiplyByIdentityIsNoop)
|
||||
{
|
||||
constexpr Quaternion<float> identity;
|
||||
constexpr Quaternion<float> q{0.5f, 0.5f, 0.5f, 0.5f};
|
||||
expect_quat_near(q * identity, q);
|
||||
expect_quat_near(identity * q, q);
|
||||
}
|
||||
|
||||
TEST(Quaternion, MultiplyAssign)
|
||||
{
|
||||
constexpr Quaternion<float> identity;
|
||||
Quaternion<float> q{0.5f, 0.5f, 0.5f, 0.5f};
|
||||
q *= identity;
|
||||
expect_quat_near(q, {0.5f, 0.5f, 0.5f, 0.5f});
|
||||
}
|
||||
|
||||
TEST(Quaternion, MultiplyKnownResult)
|
||||
{
|
||||
// i * j = k → (1,0,0,0) * (0,1,0,0) = (0,0,1,0)
|
||||
constexpr Quaternion<float> i{1.f, 0.f, 0.f, 0.f};
|
||||
constexpr Quaternion<float> j{0.f, 1.f, 0.f, 0.f};
|
||||
constexpr auto k = i * j;
|
||||
EXPECT_FLOAT_EQ(k.x, 0.f);
|
||||
EXPECT_FLOAT_EQ(k.y, 0.f);
|
||||
EXPECT_FLOAT_EQ(k.z, 1.f);
|
||||
EXPECT_FLOAT_EQ(k.w, 0.f);
|
||||
}
|
||||
|
||||
TEST(Quaternion, MultiplyByInverseGivesIdentity)
|
||||
{
|
||||
const Quaternion<float> q = Quaternion<float>::from_axis_angle({0.f, 0.f, 1.f},
|
||||
std::numbers::pi_v<float> / 3.f);
|
||||
const auto result = q * q.inverse();
|
||||
expect_quat_near(result, Quaternion<float>{});
|
||||
}
|
||||
|
||||
// ── Conjugate ────────────────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, Conjugate)
|
||||
{
|
||||
constexpr Quaternion<float> q{1.f, 2.f, 3.f, 4.f};
|
||||
constexpr auto c = q.conjugate();
|
||||
EXPECT_FLOAT_EQ(c.x, -1.f);
|
||||
EXPECT_FLOAT_EQ(c.y, -2.f);
|
||||
EXPECT_FLOAT_EQ(c.z, -3.f);
|
||||
EXPECT_FLOAT_EQ(c.w, 4.f);
|
||||
}
|
||||
|
||||
TEST(Quaternion, ConjugateOfIdentityIsIdentity)
|
||||
{
|
||||
constexpr Quaternion<float> id;
|
||||
constexpr auto c = id.conjugate();
|
||||
EXPECT_FLOAT_EQ(c.x, 0.f);
|
||||
EXPECT_FLOAT_EQ(c.y, 0.f);
|
||||
EXPECT_FLOAT_EQ(c.z, 0.f);
|
||||
EXPECT_FLOAT_EQ(c.w, 1.f);
|
||||
}
|
||||
|
||||
// ── Dot / length ─────────────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, Dot)
|
||||
{
|
||||
constexpr Quaternion<float> a{1.f, 0.f, 0.f, 0.f};
|
||||
constexpr Quaternion<float> b{0.f, 1.f, 0.f, 0.f};
|
||||
EXPECT_FLOAT_EQ(a.dot(b), 0.f);
|
||||
EXPECT_FLOAT_EQ(a.dot(a), 1.f);
|
||||
}
|
||||
|
||||
TEST(Quaternion, LengthSqrIdentity)
|
||||
{
|
||||
constexpr Quaternion<float> id;
|
||||
EXPECT_FLOAT_EQ(id.length_sqr(), 1.f);
|
||||
}
|
||||
|
||||
TEST(Quaternion, LengthSqrGeneral)
|
||||
{
|
||||
constexpr Quaternion<float> q{1.f, 2.f, 3.f, 4.f};
|
||||
EXPECT_FLOAT_EQ(q.length_sqr(), 30.f);
|
||||
}
|
||||
|
||||
TEST(Quaternion, LengthIdentity)
|
||||
{
|
||||
const Quaternion<float> id;
|
||||
EXPECT_NEAR(id.length(), 1.f, kEps);
|
||||
}
|
||||
|
||||
TEST(Quaternion, Normalized)
|
||||
{
|
||||
const Quaternion<float> q{1.f, 1.f, 1.f, 1.f};
|
||||
const auto n = q.normalized();
|
||||
EXPECT_NEAR(n.length(), 1.f, kEps);
|
||||
EXPECT_NEAR(n.x, 0.5f, kEps);
|
||||
EXPECT_NEAR(n.y, 0.5f, kEps);
|
||||
EXPECT_NEAR(n.z, 0.5f, kEps);
|
||||
EXPECT_NEAR(n.w, 0.5f, kEps);
|
||||
}
|
||||
|
||||
TEST(Quaternion, NormalizedOfZeroLengthReturnsSelf)
|
||||
{
|
||||
// length_sqr = 0 would be UB, but zero-vector part + zero w is degenerate;
|
||||
// we just verify the guard branch (divides by zero) doesn't crash by
|
||||
// keeping length > 0 via the default constructor path.
|
||||
const Quaternion<float> unit;
|
||||
const auto n = unit.normalized();
|
||||
expect_quat_near(n, unit);
|
||||
}
|
||||
|
||||
// ── Inverse ───────────────────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, InverseOfUnitIsConjugate)
|
||||
{
|
||||
const Quaternion<float> q = Quaternion<float>::from_axis_angle({1.f, 0.f, 0.f},
|
||||
std::numbers::pi_v<float> / 4.f);
|
||||
const auto inv = q.inverse();
|
||||
const auto conj = q.conjugate();
|
||||
expect_quat_near(inv, conj);
|
||||
}
|
||||
|
||||
// ── from_axis_angle ──────────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, FromAxisAngleZeroAngleIsIdentity)
|
||||
{
|
||||
const auto q = Quaternion<float>::from_axis_angle({1.f, 0.f, 0.f}, 0.f);
|
||||
EXPECT_NEAR(q.x, 0.f, kEps);
|
||||
EXPECT_NEAR(q.y, 0.f, kEps);
|
||||
EXPECT_NEAR(q.z, 0.f, kEps);
|
||||
EXPECT_NEAR(q.w, 1.f, kEps);
|
||||
}
|
||||
|
||||
TEST(Quaternion, FromAxisAngle90DegZ)
|
||||
{
|
||||
const float half_pi = std::numbers::pi_v<float> / 2.f;
|
||||
const auto q = Quaternion<float>::from_axis_angle({0.f, 0.f, 1.f}, half_pi);
|
||||
const float s = std::sin(half_pi / 2.f);
|
||||
const float c = std::cos(half_pi / 2.f);
|
||||
EXPECT_NEAR(q.x, 0.f, kEps);
|
||||
EXPECT_NEAR(q.y, 0.f, kEps);
|
||||
EXPECT_NEAR(q.z, s, kEps);
|
||||
EXPECT_NEAR(q.w, c, kEps);
|
||||
}
|
||||
|
||||
// ── rotate ───────────────────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, RotateByIdentityIsNoop)
|
||||
{
|
||||
constexpr Quaternion<float> id;
|
||||
constexpr Vector3<float> v{1.f, 2.f, 3.f};
|
||||
const auto r = id.rotate(v);
|
||||
expect_vec3_near(r, v);
|
||||
}
|
||||
|
||||
TEST(Quaternion, Rotate90DegAroundZ)
|
||||
{
|
||||
// Rotating (1,0,0) by 90° around Z should give (0,1,0)
|
||||
const auto q = Quaternion<float>::from_axis_angle({0.f, 0.f, 1.f}, std::numbers::pi_v<float> / 2.f);
|
||||
const auto r = q.rotate({1.f, 0.f, 0.f});
|
||||
expect_vec3_near(r, {0.f, 1.f, 0.f});
|
||||
}
|
||||
|
||||
TEST(Quaternion, Rotate180DegAroundY)
|
||||
{
|
||||
// Rotating (1,0,0) by 180° around Y should give (-1,0,0)
|
||||
const auto q = Quaternion<float>::from_axis_angle({0.f, 1.f, 0.f}, std::numbers::pi_v<float>);
|
||||
const auto r = q.rotate({1.f, 0.f, 0.f});
|
||||
expect_vec3_near(r, {-1.f, 0.f, 0.f});
|
||||
}
|
||||
|
||||
TEST(Quaternion, Rotate90DegAroundX)
|
||||
{
|
||||
// Rotating (0,1,0) by 90° around X should give (0,0,1)
|
||||
const auto q = Quaternion<float>::from_axis_angle({1.f, 0.f, 0.f}, std::numbers::pi_v<float> / 2.f);
|
||||
const auto r = q.rotate({0.f, 1.f, 0.f});
|
||||
expect_vec3_near(r, {0.f, 0.f, 1.f});
|
||||
}
|
||||
|
||||
// ── to_rotation_matrix3 ───────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, RotationMatrix3FromIdentityIsIdentityMatrix)
|
||||
{
|
||||
constexpr Quaternion<float> id;
|
||||
constexpr auto m = id.to_rotation_matrix3();
|
||||
for (size_t i = 0; i < 3; ++i)
|
||||
for (size_t j = 0; j < 3; ++j)
|
||||
EXPECT_NEAR(m.at(i, j), i == j ? 1.f : 0.f, kEps);
|
||||
}
|
||||
|
||||
TEST(Quaternion, RotationMatrix3From90DegZ)
|
||||
{
|
||||
// Expected: | 0 -1 0 |
|
||||
// | 1 0 0 |
|
||||
// | 0 0 1 |
|
||||
const auto q = Quaternion<float>::from_axis_angle({0.f, 0.f, 1.f}, std::numbers::pi_v<float> / 2.f);
|
||||
const auto m = q.to_rotation_matrix3();
|
||||
EXPECT_NEAR(m.at(0, 0), 0.f, kEps);
|
||||
EXPECT_NEAR(m.at(0, 1), -1.f, kEps);
|
||||
EXPECT_NEAR(m.at(0, 2), 0.f, kEps);
|
||||
EXPECT_NEAR(m.at(1, 0), 1.f, kEps);
|
||||
EXPECT_NEAR(m.at(1, 1), 0.f, kEps);
|
||||
EXPECT_NEAR(m.at(1, 2), 0.f, kEps);
|
||||
EXPECT_NEAR(m.at(2, 0), 0.f, kEps);
|
||||
EXPECT_NEAR(m.at(2, 1), 0.f, kEps);
|
||||
EXPECT_NEAR(m.at(2, 2), 1.f, kEps);
|
||||
}
|
||||
|
||||
TEST(Quaternion, RotationMatrix3ConsistentWithRotate)
|
||||
{
|
||||
// Matrix-vector multiply must agree with the rotate() method
|
||||
const auto q = Quaternion<float>::from_axis_angle({1.f, 1.f, 0.f}, std::numbers::pi_v<float> / 3.f);
|
||||
const Vector3<float> v{2.f, -1.f, 0.5f};
|
||||
|
||||
const auto rotated = q.rotate(v);
|
||||
const auto m = q.to_rotation_matrix3();
|
||||
|
||||
// manual mat-vec multiply (row-major)
|
||||
const float rx = m.at(0, 0) * v.x + m.at(0, 1) * v.y + m.at(0, 2) * v.z;
|
||||
const float ry = m.at(1, 0) * v.x + m.at(1, 1) * v.y + m.at(1, 2) * v.z;
|
||||
const float rz = m.at(2, 0) * v.x + m.at(2, 1) * v.y + m.at(2, 2) * v.z;
|
||||
|
||||
EXPECT_NEAR(rotated.x, rx, kEps);
|
||||
EXPECT_NEAR(rotated.y, ry, kEps);
|
||||
EXPECT_NEAR(rotated.z, rz, kEps);
|
||||
}
|
||||
|
||||
// ── to_rotation_matrix4 ───────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, RotationMatrix4FromIdentityIsIdentityMatrix)
|
||||
{
|
||||
constexpr Quaternion<float> id;
|
||||
constexpr auto m = id.to_rotation_matrix4();
|
||||
for (size_t i = 0; i < 4; ++i)
|
||||
for (size_t j = 0; j < 4; ++j)
|
||||
EXPECT_NEAR(m.at(i, j), i == j ? 1.f : 0.f, kEps);
|
||||
}
|
||||
|
||||
TEST(Quaternion, RotationMatrix4HomogeneousRowAndColumn)
|
||||
{
|
||||
const auto q = Quaternion<float>::from_axis_angle({1.f, 0.f, 0.f}, std::numbers::pi_v<float> / 5.f);
|
||||
const auto m = q.to_rotation_matrix4();
|
||||
|
||||
// Last row and last column must be (0,0,0,1)
|
||||
for (size_t i = 0; i < 3; ++i)
|
||||
{
|
||||
EXPECT_NEAR(m.at(3, i), 0.f, kEps);
|
||||
EXPECT_NEAR(m.at(i, 3), 0.f, kEps);
|
||||
}
|
||||
EXPECT_NEAR(m.at(3, 3), 1.f, kEps);
|
||||
}
|
||||
|
||||
TEST(Quaternion, RotationMatrix4Upper3x3MatchesMatrix3)
|
||||
{
|
||||
const auto q = Quaternion<float>::from_axis_angle({0.f, 1.f, 0.f}, std::numbers::pi_v<float> / 7.f);
|
||||
const auto m3 = q.to_rotation_matrix3();
|
||||
const auto m4 = q.to_rotation_matrix4();
|
||||
|
||||
for (size_t i = 0; i < 3; ++i)
|
||||
for (size_t j = 0; j < 3; ++j)
|
||||
EXPECT_NEAR(m4.at(i, j), m3.at(i, j), kEps);
|
||||
}
|
||||
|
||||
// ── as_array ──────────────────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, AsArray)
|
||||
{
|
||||
constexpr Quaternion<float> q{1.f, 2.f, 3.f, 4.f};
|
||||
constexpr auto arr = q.as_array();
|
||||
EXPECT_FLOAT_EQ(arr[0], 1.f);
|
||||
EXPECT_FLOAT_EQ(arr[1], 2.f);
|
||||
EXPECT_FLOAT_EQ(arr[2], 3.f);
|
||||
EXPECT_FLOAT_EQ(arr[3], 4.f);
|
||||
}
|
||||
|
||||
// ── std::formatter ────────────────────────────────────────────────────────────
|
||||
|
||||
TEST(Quaternion, Formatter)
|
||||
{
|
||||
const Quaternion<float> q{1.f, 2.f, 3.f, 4.f};
|
||||
const auto s = std::format("{}", q);
|
||||
EXPECT_EQ(s, "[1, 2, 3, 4]");
|
||||
}
|
||||
96
tests/lua/color_tests.lua
Normal file
96
tests/lua/color_tests.lua
Normal file
@@ -0,0 +1,96 @@
|
||||
local function approx(a, b, eps) return math.abs(a - b) < (eps or 1e-4) end
|
||||
|
||||
function Color_Constructor_float()
|
||||
local c = omath.Color.new(1, 0.5, 0.25, 1)
|
||||
assert(approx(c.r, 1) and approx(c.g, 0.5) and approx(c.b, 0.25) and approx(c.a, 1))
|
||||
end
|
||||
|
||||
function Color_Constructor_default()
|
||||
local c = omath.Color.new()
|
||||
assert(c ~= nil)
|
||||
end
|
||||
|
||||
function Color_Constructor_clamping()
|
||||
local c = omath.Color.new(2, -1, 0.5, 1)
|
||||
assert(approx(c.r, 1) and approx(c.g, 0) and approx(c.b, 0.5))
|
||||
end
|
||||
|
||||
function Color_from_rgba()
|
||||
local c = omath.Color.from_rgba(255, 128, 0, 255)
|
||||
assert(approx(c.r, 1) and approx(c.g, 128/255) and approx(c.b, 0) and approx(c.a, 1))
|
||||
end
|
||||
|
||||
function Color_from_hsv_components()
|
||||
local c = omath.Color.from_hsv(0, 1, 1)
|
||||
assert(approx(c.r, 1) and approx(c.g, 0) and approx(c.b, 0))
|
||||
end
|
||||
|
||||
function Color_from_hsv_struct()
|
||||
local hsv = omath.Hsv.new()
|
||||
hsv.hue = 0
|
||||
hsv.saturation = 1
|
||||
hsv.value = 1
|
||||
local c = omath.Color.from_hsv(hsv)
|
||||
assert(approx(c.r, 1) and approx(c.g, 0) and approx(c.b, 0))
|
||||
end
|
||||
|
||||
function Color_red()
|
||||
local c = omath.Color.red()
|
||||
assert(approx(c.r, 1) and approx(c.g, 0) and approx(c.b, 0) and approx(c.a, 1))
|
||||
end
|
||||
|
||||
function Color_green()
|
||||
local c = omath.Color.green()
|
||||
assert(approx(c.r, 0) and approx(c.g, 1) and approx(c.b, 0) and approx(c.a, 1))
|
||||
end
|
||||
|
||||
function Color_blue()
|
||||
local c = omath.Color.blue()
|
||||
assert(approx(c.r, 0) and approx(c.g, 0) and approx(c.b, 1) and approx(c.a, 1))
|
||||
end
|
||||
|
||||
function Color_to_hsv()
|
||||
local hsv = omath.Color.red():to_hsv()
|
||||
assert(approx(hsv.hue, 0) and approx(hsv.saturation, 1) and approx(hsv.value, 1))
|
||||
end
|
||||
|
||||
function Color_set_hue()
|
||||
local c = omath.Color.red()
|
||||
c:set_hue(1/3)
|
||||
assert(approx(c.g, 1, 1e-3))
|
||||
end
|
||||
|
||||
function Color_set_saturation()
|
||||
local c = omath.Color.red()
|
||||
c:set_saturation(0)
|
||||
assert(approx(c.r, c.g) and approx(c.g, c.b))
|
||||
end
|
||||
|
||||
function Color_set_value()
|
||||
local c = omath.Color.red()
|
||||
c:set_value(0)
|
||||
assert(approx(c.r, 0) and approx(c.g, 0) and approx(c.b, 0))
|
||||
end
|
||||
|
||||
function Color_blend()
|
||||
local c = omath.Color.red():blend(omath.Color.blue(), 0.5)
|
||||
assert(approx(c.r, 0.5) and approx(c.b, 0.5))
|
||||
end
|
||||
|
||||
function Color_blend_clamped_ratio()
|
||||
local c = omath.Color.red():blend(omath.Color.blue(), 2.0)
|
||||
assert(approx(c.r, 0) and approx(c.b, 1))
|
||||
end
|
||||
|
||||
function Color_to_string()
|
||||
local s = tostring(omath.Color.red())
|
||||
assert(s == "[r:255, g:0, b:0, a:255]")
|
||||
end
|
||||
|
||||
function Hsv_fields()
|
||||
local hsv = omath.Hsv.new()
|
||||
hsv.hue = 0.5
|
||||
hsv.saturation = 0.8
|
||||
hsv.value = 0.9
|
||||
assert(approx(hsv.hue, 0.5) and approx(hsv.saturation, 0.8) and approx(hsv.value, 0.9))
|
||||
end
|
||||
66
tests/lua/pe_scanner_tests.lua
Normal file
66
tests/lua/pe_scanner_tests.lua
Normal file
@@ -0,0 +1,66 @@
|
||||
-- PatternScanner tests: generic scan over a Lua string buffer
|
||||
|
||||
function PatternScanner_FindsExactPattern()
|
||||
local buf = "\x90\x01\x02\x03\x04"
|
||||
local offset = omath.PatternScanner.scan(buf, "90 01 02")
|
||||
assert(offset ~= nil, "expected pattern to be found")
|
||||
assert(offset == 0, "expected offset 0, got " .. tostring(offset))
|
||||
end
|
||||
|
||||
function PatternScanner_FindsPatternAtNonZeroOffset()
|
||||
local buf = "\x00\x00\xAB\xCD\xEF"
|
||||
local offset = omath.PatternScanner.scan(buf, "AB CD EF")
|
||||
assert(offset ~= nil, "expected pattern to be found")
|
||||
assert(offset == 2, "expected offset 2, got " .. tostring(offset))
|
||||
end
|
||||
|
||||
function PatternScanner_WildcardMatches()
|
||||
local buf = "\xDE\xAD\xBE\xEF"
|
||||
local offset = omath.PatternScanner.scan(buf, "DE ?? BE")
|
||||
assert(offset ~= nil, "expected wildcard match")
|
||||
assert(offset == 0)
|
||||
end
|
||||
|
||||
function PatternScanner_ReturnsNilWhenNotFound()
|
||||
local buf = "\x01\x02\x03"
|
||||
local offset = omath.PatternScanner.scan(buf, "AA BB CC")
|
||||
assert(offset == nil, "expected nil for not-found pattern")
|
||||
end
|
||||
|
||||
function PatternScanner_ReturnsNilForEmptyBuffer()
|
||||
local offset = omath.PatternScanner.scan("", "90 01")
|
||||
assert(offset == nil)
|
||||
end
|
||||
|
||||
-- PePatternScanner tests: scan_in_module uses FAKE_MODULE_BASE injected from C++
|
||||
-- The fake module contains {0x90, 0x01, 0x02, 0x03, 0x04} placed at raw offset 0x200
|
||||
|
||||
function PeScanner_FindsExactPattern()
|
||||
local addr = omath.PePatternScanner.scan_in_module(FAKE_MODULE_BASE, "90 01 02")
|
||||
assert(addr ~= nil, "expected pattern to be found in module")
|
||||
local offset = addr - FAKE_MODULE_BASE
|
||||
assert(offset == 0x200, string.format("expected offset 0x200, got 0x%X", offset))
|
||||
end
|
||||
|
||||
function PeScanner_WildcardMatches()
|
||||
local addr = omath.PePatternScanner.scan_in_module(FAKE_MODULE_BASE, "90 ?? 02")
|
||||
assert(addr ~= nil, "expected wildcard match in module")
|
||||
local offset = addr - FAKE_MODULE_BASE
|
||||
assert(offset == 0x200, string.format("expected offset 0x200, got 0x%X", offset))
|
||||
end
|
||||
|
||||
function PeScanner_ReturnsNilWhenNotFound()
|
||||
local addr = omath.PePatternScanner.scan_in_module(FAKE_MODULE_BASE, "AA BB CC DD")
|
||||
assert(addr == nil, "expected nil for not-found pattern")
|
||||
end
|
||||
|
||||
function PeScanner_CustomSectionFallsBackToNil()
|
||||
-- Request a section that doesn't exist in our fake module
|
||||
local addr = omath.PePatternScanner.scan_in_module(FAKE_MODULE_BASE, "90 01 02", ".rdata")
|
||||
assert(addr == nil, "expected nil for wrong section name")
|
||||
end
|
||||
|
||||
-- SectionScanResult: verify the type is registered and tostring works on a C++-returned value
|
||||
function SectionScanResult_TypeIsRegistered()
|
||||
assert(omath.SectionScanResult ~= nil, "SectionScanResult type should be registered")
|
||||
end
|
||||
197
tests/lua/source_engine_tests.lua
Normal file
197
tests/lua/source_engine_tests.lua
Normal file
@@ -0,0 +1,197 @@
|
||||
local function approx(a, b, eps) return math.abs(a - b) < (eps or 1e-4) end
|
||||
|
||||
local function make_camera()
|
||||
local pos = omath.Vec3.new(0, 0, 0)
|
||||
local pitch = omath.source.PitchAngle.from_degrees(0)
|
||||
local yaw = omath.source.YawAngle.from_degrees(0)
|
||||
local roll = omath.source.RollAngle.from_degrees(0)
|
||||
local angles = omath.source.ViewAngles.new(pitch, yaw, roll)
|
||||
local vp = omath.opengl.ViewPort.new(1920, 1080)
|
||||
local fov = omath.source.FieldOfView.from_degrees(90)
|
||||
return omath.source.Camera.new(pos, angles, vp, fov, 0.1, 1000)
|
||||
end
|
||||
|
||||
-- PitchAngle
|
||||
function Source_PitchAngle_from_degrees()
|
||||
assert(omath.source.PitchAngle.from_degrees(45):as_degrees() == 45)
|
||||
end
|
||||
|
||||
function Source_PitchAngle_clamping_max()
|
||||
assert(omath.source.PitchAngle.from_degrees(100):as_degrees() == 89)
|
||||
end
|
||||
|
||||
function Source_PitchAngle_clamping_min()
|
||||
assert(omath.source.PitchAngle.from_degrees(-100):as_degrees() == -89)
|
||||
end
|
||||
|
||||
function Source_PitchAngle_from_radians()
|
||||
assert(approx(omath.source.PitchAngle.from_radians(math.pi / 4):as_degrees(), 45))
|
||||
end
|
||||
|
||||
function Source_PitchAngle_as_radians()
|
||||
assert(approx(omath.source.PitchAngle.from_degrees(0):as_radians(), 0))
|
||||
end
|
||||
|
||||
function Source_PitchAngle_sin()
|
||||
assert(approx(omath.source.PitchAngle.from_degrees(30):sin(), 0.5))
|
||||
end
|
||||
|
||||
function Source_PitchAngle_cos()
|
||||
assert(approx(omath.source.PitchAngle.from_degrees(60):cos(), 0.5))
|
||||
end
|
||||
|
||||
function Source_PitchAngle_tan()
|
||||
assert(approx(omath.source.PitchAngle.from_degrees(45):tan(), 1.0))
|
||||
end
|
||||
|
||||
function Source_PitchAngle_addition()
|
||||
local c = omath.source.PitchAngle.from_degrees(20) + omath.source.PitchAngle.from_degrees(15)
|
||||
assert(c:as_degrees() == 35)
|
||||
end
|
||||
|
||||
function Source_PitchAngle_addition_clamped()
|
||||
local c = omath.source.PitchAngle.from_degrees(80) + omath.source.PitchAngle.from_degrees(20)
|
||||
assert(c:as_degrees() == 89)
|
||||
end
|
||||
|
||||
function Source_PitchAngle_subtraction()
|
||||
local c = omath.source.PitchAngle.from_degrees(50) - omath.source.PitchAngle.from_degrees(20)
|
||||
assert(c:as_degrees() == 30)
|
||||
end
|
||||
|
||||
function Source_PitchAngle_unary_minus()
|
||||
assert((-omath.source.PitchAngle.from_degrees(45)):as_degrees() == -45)
|
||||
end
|
||||
|
||||
function Source_PitchAngle_equal_to()
|
||||
local a = omath.source.PitchAngle.from_degrees(45)
|
||||
assert(a == omath.source.PitchAngle.from_degrees(45))
|
||||
assert(not (a == omath.source.PitchAngle.from_degrees(30)))
|
||||
end
|
||||
|
||||
function Source_PitchAngle_to_string()
|
||||
assert(tostring(omath.source.PitchAngle.from_degrees(45)) == "45deg")
|
||||
end
|
||||
|
||||
-- YawAngle
|
||||
function Source_YawAngle_from_degrees()
|
||||
assert(omath.source.YawAngle.from_degrees(90):as_degrees() == 90)
|
||||
end
|
||||
|
||||
function Source_YawAngle_normalization()
|
||||
assert(approx(omath.source.YawAngle.from_degrees(200):as_degrees(), -160))
|
||||
end
|
||||
|
||||
-- RollAngle
|
||||
function Source_RollAngle_from_degrees()
|
||||
assert(omath.source.RollAngle.from_degrees(45):as_degrees() == 45)
|
||||
end
|
||||
|
||||
-- FieldOfView
|
||||
function Source_FieldOfView_from_degrees()
|
||||
assert(omath.source.FieldOfView.from_degrees(90):as_degrees() == 90)
|
||||
end
|
||||
|
||||
function Source_FieldOfView_clamping()
|
||||
assert(omath.source.FieldOfView.from_degrees(200):as_degrees() == 180)
|
||||
end
|
||||
|
||||
-- ViewAngles
|
||||
function Source_ViewAngles_new()
|
||||
local angles = omath.source.ViewAngles.new(
|
||||
omath.source.PitchAngle.from_degrees(30),
|
||||
omath.source.YawAngle.from_degrees(90),
|
||||
omath.source.RollAngle.from_degrees(0))
|
||||
assert(angles.pitch:as_degrees() == 30)
|
||||
assert(angles.yaw:as_degrees() == 90)
|
||||
assert(angles.roll:as_degrees() == 0)
|
||||
end
|
||||
|
||||
function Source_ViewAngles_field_mutation()
|
||||
local angles = omath.source.ViewAngles.new(
|
||||
omath.source.PitchAngle.from_degrees(0),
|
||||
omath.source.YawAngle.from_degrees(0),
|
||||
omath.source.RollAngle.from_degrees(0))
|
||||
angles.pitch = omath.source.PitchAngle.from_degrees(45)
|
||||
assert(angles.pitch:as_degrees() == 45)
|
||||
end
|
||||
|
||||
-- Camera
|
||||
function Source_Camera_constructor()
|
||||
assert(make_camera() ~= nil)
|
||||
end
|
||||
|
||||
function Source_Camera_get_set_origin()
|
||||
local cam = make_camera()
|
||||
cam:set_origin(omath.Vec3.new(1, 2, 3))
|
||||
local o = cam:get_origin()
|
||||
assert(approx(o.x, 1) and approx(o.y, 2) and approx(o.z, 3))
|
||||
end
|
||||
|
||||
function Source_Camera_get_set_near_plane()
|
||||
local cam = make_camera()
|
||||
cam:set_near_plane(0.5)
|
||||
assert(approx(cam:get_near_plane(), 0.5))
|
||||
end
|
||||
|
||||
function Source_Camera_get_set_far_plane()
|
||||
local cam = make_camera()
|
||||
cam:set_far_plane(500)
|
||||
assert(approx(cam:get_far_plane(), 500))
|
||||
end
|
||||
|
||||
function Source_Camera_get_set_fov()
|
||||
local cam = make_camera()
|
||||
cam:set_field_of_view(omath.source.FieldOfView.from_degrees(60))
|
||||
assert(approx(cam:get_field_of_view():as_degrees(), 60))
|
||||
end
|
||||
|
||||
function Source_Camera_get_set_view_angles()
|
||||
local cam = make_camera()
|
||||
cam:set_view_angles(omath.source.ViewAngles.new(
|
||||
omath.source.PitchAngle.from_degrees(30),
|
||||
omath.source.YawAngle.from_degrees(90),
|
||||
omath.source.RollAngle.from_degrees(0)))
|
||||
assert(approx(cam:get_view_angles().pitch:as_degrees(), 30))
|
||||
assert(approx(cam:get_view_angles().yaw:as_degrees(), 90))
|
||||
end
|
||||
|
||||
function Source_Camera_look_at()
|
||||
local cam = make_camera()
|
||||
cam:look_at(omath.Vec3.new(10, 0, 0))
|
||||
assert(cam:get_view_angles() ~= nil)
|
||||
end
|
||||
|
||||
function Source_Camera_get_forward()
|
||||
local fwd = make_camera():get_forward()
|
||||
assert(approx(fwd:length(), 1.0))
|
||||
end
|
||||
|
||||
function Source_Camera_get_right()
|
||||
assert(approx(make_camera():get_right():length(), 1.0))
|
||||
end
|
||||
|
||||
function Source_Camera_get_up()
|
||||
assert(approx(make_camera():get_up():length(), 1.0))
|
||||
end
|
||||
|
||||
function Source_Camera_world_to_screen_success()
|
||||
local cam = make_camera()
|
||||
cam:look_at(omath.Vec3.new(1, 0, 0))
|
||||
local screen, err = cam:world_to_screen(omath.Vec3.new(5, 0, 0))
|
||||
assert(screen ~= nil, "expected screen pos, got: " .. tostring(err))
|
||||
end
|
||||
|
||||
function Source_Camera_world_to_screen_error()
|
||||
local cam = make_camera()
|
||||
cam:look_at(omath.Vec3.new(1, 0, 0))
|
||||
local screen, err = cam:world_to_screen(omath.Vec3.new(-100, 0, 0))
|
||||
assert(screen == nil and err ~= nil)
|
||||
end
|
||||
|
||||
function Source_Camera_screen_to_world()
|
||||
local cam = make_camera()
|
||||
cam:look_at(omath.Vec3.new(1, 0, 0))
|
||||
local world, err = cam:screen_to_world(omath.Vec3.new(960, 540, 1))
|
||||
assert(world ~= nil, "expected world pos, got: " .. tostring(err))
|
||||
end
|
||||
82
tests/lua/triangle_tests.lua
Normal file
82
tests/lua/triangle_tests.lua
Normal file
@@ -0,0 +1,82 @@
|
||||
local function approx(a, b, eps) return math.abs(a - b) < (eps or 1e-5) end
|
||||
|
||||
function Triangle_Constructor_default()
|
||||
local t = omath.Triangle.new()
|
||||
assert(t.vertex1.x == 0 and t.vertex1.y == 0 and t.vertex1.z == 0)
|
||||
assert(t.vertex2.x == 0 and t.vertex2.y == 0 and t.vertex2.z == 0)
|
||||
assert(t.vertex3.x == 0 and t.vertex3.y == 0 and t.vertex3.z == 0)
|
||||
end
|
||||
|
||||
function Triangle_Constructor_vertices()
|
||||
local v1 = omath.Vec3.new(1, 0, 0)
|
||||
local v2 = omath.Vec3.new(0, 1, 0)
|
||||
local v3 = omath.Vec3.new(0, 0, 1)
|
||||
local t = omath.Triangle.new(v1, v2, v3)
|
||||
assert(t.vertex1.x == 1 and t.vertex1.y == 0 and t.vertex1.z == 0)
|
||||
assert(t.vertex2.x == 0 and t.vertex2.y == 1 and t.vertex2.z == 0)
|
||||
assert(t.vertex3.x == 0 and t.vertex3.y == 0 and t.vertex3.z == 1)
|
||||
end
|
||||
|
||||
function Triangle_Vertex_mutation()
|
||||
local t = omath.Triangle.new()
|
||||
t.vertex1 = omath.Vec3.new(5, 6, 7)
|
||||
assert(t.vertex1.x == 5 and t.vertex1.y == 6 and t.vertex1.z == 7)
|
||||
end
|
||||
|
||||
-- Right triangle: v1=(0,3,0), v2=(0,0,0), v3=(4,0,0) — sides 3, 4, hypot 5
|
||||
function Triangle_SideALength()
|
||||
local t = omath.Triangle.new(omath.Vec3.new(0, 3, 0), omath.Vec3.new(0, 0, 0), omath.Vec3.new(4, 0, 0))
|
||||
assert(approx(t:side_a_length(), 3.0))
|
||||
end
|
||||
|
||||
function Triangle_SideBLength()
|
||||
local t = omath.Triangle.new(omath.Vec3.new(0, 3, 0), omath.Vec3.new(0, 0, 0), omath.Vec3.new(4, 0, 0))
|
||||
assert(approx(t:side_b_length(), 4.0))
|
||||
end
|
||||
|
||||
function Triangle_Hypot()
|
||||
local t = omath.Triangle.new(omath.Vec3.new(0, 3, 0), omath.Vec3.new(0, 0, 0), omath.Vec3.new(4, 0, 0))
|
||||
assert(approx(t:hypot(), 5.0))
|
||||
end
|
||||
|
||||
function Triangle_SideAVector()
|
||||
local t = omath.Triangle.new(omath.Vec3.new(0, 3, 0), omath.Vec3.new(0, 0, 0), omath.Vec3.new(4, 0, 0))
|
||||
local a = t:side_a_vector()
|
||||
assert(approx(a.x, 0) and approx(a.y, 3) and approx(a.z, 0))
|
||||
end
|
||||
|
||||
function Triangle_SideBVector()
|
||||
local t = omath.Triangle.new(omath.Vec3.new(0, 3, 0), omath.Vec3.new(0, 0, 0), omath.Vec3.new(4, 0, 0))
|
||||
local b = t:side_b_vector()
|
||||
assert(approx(b.x, 4) and approx(b.y, 0) and approx(b.z, 0))
|
||||
end
|
||||
|
||||
function Triangle_IsRectangular_true()
|
||||
local t = omath.Triangle.new(omath.Vec3.new(0, 3, 0), omath.Vec3.new(0, 0, 0), omath.Vec3.new(4, 0, 0))
|
||||
assert(t:is_rectangular() == true)
|
||||
end
|
||||
|
||||
function Triangle_IsRectangular_false()
|
||||
-- equilateral-ish triangle, not rectangular
|
||||
local t = omath.Triangle.new(omath.Vec3.new(0, 1, 0), omath.Vec3.new(-1, 0, 0), omath.Vec3.new(1, 0, 0))
|
||||
assert(t:is_rectangular() == false)
|
||||
end
|
||||
|
||||
function Triangle_MidPoint()
|
||||
local t = omath.Triangle.new(omath.Vec3.new(3, 0, 0), omath.Vec3.new(0, 3, 0), omath.Vec3.new(0, 0, 3))
|
||||
local m = t:mid_point()
|
||||
assert(approx(m.x, 1.0) and approx(m.y, 1.0) and approx(m.z, 1.0))
|
||||
end
|
||||
|
||||
function Triangle_CalculateNormal()
|
||||
-- flat triangle in XY plane — normal should be (0, 0, 1)
|
||||
local t = omath.Triangle.new(omath.Vec3.new(0, 1, 0), omath.Vec3.new(0, 0, 0), omath.Vec3.new(1, 0, 0))
|
||||
local n = t:calculate_normal()
|
||||
assert(approx(n.x, 0) and approx(n.y, 0) and approx(n.z, 1))
|
||||
end
|
||||
|
||||
function Triangle_ToString()
|
||||
local t = omath.Triangle.new(omath.Vec3.new(1, 0, 0), omath.Vec3.new(0, 1, 0), omath.Vec3.new(0, 0, 1))
|
||||
local s = tostring(t)
|
||||
assert(s == "Triangle((1, 0, 0), (0, 1, 0), (0, 0, 1))")
|
||||
end
|
||||
51
tests/lua/unit_test_lua_color.cpp
Normal file
51
tests/lua/unit_test_lua_color.cpp
Normal file
@@ -0,0 +1,51 @@
|
||||
//
|
||||
// Created by orange on 08.03.2026.
|
||||
//
|
||||
#include <gtest/gtest.h>
|
||||
#include <lua.hpp>
|
||||
#include <omath/lua/lua.hpp>
|
||||
|
||||
class LuaColor : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
lua_State* L = nullptr;
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
L = luaL_newstate();
|
||||
luaL_openlibs(L);
|
||||
omath::lua::LuaInterpreter::register_lib(L);
|
||||
if (luaL_dofile(L, LUA_SCRIPTS_DIR "/color_tests.lua") != LUA_OK)
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
}
|
||||
|
||||
void TearDown() override { lua_close(L); }
|
||||
|
||||
void check(const char* func_name)
|
||||
{
|
||||
lua_getglobal(L, func_name);
|
||||
if (lua_pcall(L, 0, 0, 0) != LUA_OK)
|
||||
{
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(LuaColor, Constructor_float) { check("Color_Constructor_float"); }
|
||||
TEST_F(LuaColor, Constructor_default) { check("Color_Constructor_default"); }
|
||||
TEST_F(LuaColor, Constructor_clamping) { check("Color_Constructor_clamping"); }
|
||||
TEST_F(LuaColor, from_rgba) { check("Color_from_rgba"); }
|
||||
TEST_F(LuaColor, from_hsv_components) { check("Color_from_hsv_components"); }
|
||||
TEST_F(LuaColor, from_hsv_struct) { check("Color_from_hsv_struct"); }
|
||||
TEST_F(LuaColor, red) { check("Color_red"); }
|
||||
TEST_F(LuaColor, green) { check("Color_green"); }
|
||||
TEST_F(LuaColor, blue) { check("Color_blue"); }
|
||||
TEST_F(LuaColor, to_hsv) { check("Color_to_hsv"); }
|
||||
TEST_F(LuaColor, set_hue) { check("Color_set_hue"); }
|
||||
TEST_F(LuaColor, set_saturation) { check("Color_set_saturation"); }
|
||||
TEST_F(LuaColor, set_value) { check("Color_set_value"); }
|
||||
TEST_F(LuaColor, blend) { check("Color_blend"); }
|
||||
TEST_F(LuaColor, blend_clamped_ratio) { check("Color_blend_clamped_ratio"); }
|
||||
TEST_F(LuaColor, to_string) { check("Color_to_string"); }
|
||||
TEST_F(LuaColor, Hsv_fields) { check("Hsv_fields"); }
|
||||
113
tests/lua/unit_test_lua_pe_scanner.cpp
Normal file
113
tests/lua/unit_test_lua_pe_scanner.cpp
Normal file
@@ -0,0 +1,113 @@
|
||||
//
|
||||
// Created by orange on 10.03.2026.
|
||||
//
|
||||
#include <gtest/gtest.h>
|
||||
#include <lua.hpp>
|
||||
#include <omath/lua/lua.hpp>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
std::vector<std::uint8_t> make_fake_pe_module(std::uint32_t base_of_code, std::uint32_t size_code,
|
||||
const std::vector<std::uint8_t>& code_bytes)
|
||||
{
|
||||
constexpr std::uint32_t e_lfanew = 0x80;
|
||||
constexpr std::uint32_t nt_sig = 0x4550;
|
||||
constexpr std::uint16_t opt_magic = 0x020B; // PE32+
|
||||
constexpr std::uint16_t num_sections = 1;
|
||||
constexpr std::uint16_t opt_hdr_size = 0xF0;
|
||||
constexpr std::uint32_t section_table_off = e_lfanew + 4 + 20 + opt_hdr_size;
|
||||
constexpr std::uint32_t section_hdr_size = 40;
|
||||
constexpr std::uint32_t text_chars = 0x60000020;
|
||||
|
||||
const std::uint32_t headers_end = section_table_off + section_hdr_size;
|
||||
const std::uint32_t code_end = base_of_code + size_code;
|
||||
const std::uint32_t total_size = std::max(headers_end, code_end) + 0x100;
|
||||
std::vector<std::uint8_t> buf(total_size, 0);
|
||||
|
||||
auto w16 = [&](std::size_t off, std::uint16_t v) { std::memcpy(buf.data() + off, &v, 2); };
|
||||
auto w32 = [&](std::size_t off, std::uint32_t v) { std::memcpy(buf.data() + off, &v, 4); };
|
||||
auto w64 = [&](std::size_t off, std::uint64_t v) { std::memcpy(buf.data() + off, &v, 8); };
|
||||
|
||||
w16(0x00, 0x5A4D);
|
||||
w32(0x3C, e_lfanew);
|
||||
w32(e_lfanew, nt_sig);
|
||||
|
||||
const std::size_t fh = e_lfanew + 4;
|
||||
w16(fh + 2, num_sections);
|
||||
w16(fh + 16, opt_hdr_size);
|
||||
|
||||
const std::size_t opt = fh + 20;
|
||||
w16(opt + 0, opt_magic);
|
||||
w32(opt + 4, size_code);
|
||||
w32(opt + 20, base_of_code);
|
||||
w64(opt + 24, 0);
|
||||
w32(opt + 32, 0x1000);
|
||||
w32(opt + 36, 0x200);
|
||||
w32(opt + 56, code_end);
|
||||
w32(opt + 60, headers_end);
|
||||
w32(opt + 108, 0);
|
||||
|
||||
const std::size_t sh = section_table_off;
|
||||
std::memcpy(buf.data() + sh, ".text", 5);
|
||||
w32(sh + 8, size_code);
|
||||
w32(sh + 12, base_of_code);
|
||||
w32(sh + 16, size_code);
|
||||
w32(sh + 20, base_of_code);
|
||||
w32(sh + 36, text_chars);
|
||||
|
||||
if (base_of_code + code_bytes.size() <= buf.size())
|
||||
std::memcpy(buf.data() + base_of_code, code_bytes.data(), code_bytes.size());
|
||||
|
||||
return buf;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class LuaPeScanner : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
lua_State* L = nullptr;
|
||||
std::vector<std::uint8_t> m_fake_module;
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
const std::vector<std::uint8_t> code = {0x90, 0x01, 0x02, 0x03, 0x04};
|
||||
m_fake_module = make_fake_pe_module(0x200, static_cast<std::uint32_t>(code.size()), code);
|
||||
|
||||
L = luaL_newstate();
|
||||
luaL_openlibs(L);
|
||||
omath::lua::LuaInterpreter::register_lib(L);
|
||||
|
||||
lua_pushinteger(L, static_cast<lua_Integer>(
|
||||
reinterpret_cast<std::uintptr_t>(m_fake_module.data())));
|
||||
lua_setglobal(L, "FAKE_MODULE_BASE");
|
||||
|
||||
if (luaL_dofile(L, LUA_SCRIPTS_DIR "/pe_scanner_tests.lua") != LUA_OK)
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
}
|
||||
|
||||
void TearDown() override { lua_close(L); }
|
||||
|
||||
void check(const char* func_name)
|
||||
{
|
||||
lua_getglobal(L, func_name);
|
||||
if (lua_pcall(L, 0, 0, 0) != LUA_OK)
|
||||
{
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(LuaPeScanner, PatternScanner_FindsExactPattern) { check("PatternScanner_FindsExactPattern"); }
|
||||
TEST_F(LuaPeScanner, PatternScanner_FindsPatternAtOffset) { check("PatternScanner_FindsPatternAtNonZeroOffset"); }
|
||||
TEST_F(LuaPeScanner, PatternScanner_WildcardMatches) { check("PatternScanner_WildcardMatches"); }
|
||||
TEST_F(LuaPeScanner, PatternScanner_ReturnsNilWhenNotFound) { check("PatternScanner_ReturnsNilWhenNotFound"); }
|
||||
TEST_F(LuaPeScanner, PatternScanner_ReturnsNilForEmptyBuffer){ check("PatternScanner_ReturnsNilForEmptyBuffer"); }
|
||||
TEST_F(LuaPeScanner, PeScanner_FindsExactPattern) { check("PeScanner_FindsExactPattern"); }
|
||||
TEST_F(LuaPeScanner, PeScanner_WildcardMatches) { check("PeScanner_WildcardMatches"); }
|
||||
TEST_F(LuaPeScanner, PeScanner_ReturnsNilWhenNotFound) { check("PeScanner_ReturnsNilWhenNotFound"); }
|
||||
TEST_F(LuaPeScanner, PeScanner_CustomSectionFallsBackToNil) { check("PeScanner_CustomSectionFallsBackToNil"); }
|
||||
TEST_F(LuaPeScanner, SectionScanResult_TypeIsRegistered) { check("SectionScanResult_TypeIsRegistered"); }
|
||||
79
tests/lua/unit_test_lua_source_engine.cpp
Normal file
79
tests/lua/unit_test_lua_source_engine.cpp
Normal file
@@ -0,0 +1,79 @@
|
||||
//
|
||||
// Created by orange on 07.03.2026.
|
||||
//
|
||||
#include <gtest/gtest.h>
|
||||
#include <lua.hpp>
|
||||
#include <omath/lua/lua.hpp>
|
||||
|
||||
class LuaSourceEngine : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
lua_State* L = nullptr;
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
L = luaL_newstate();
|
||||
luaL_openlibs(L);
|
||||
omath::lua::LuaInterpreter::register_lib(L);
|
||||
if (luaL_dofile(L, LUA_SCRIPTS_DIR "/source_engine_tests.lua") != LUA_OK)
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
}
|
||||
|
||||
void TearDown() override { lua_close(L); }
|
||||
|
||||
void check(const char* func_name)
|
||||
{
|
||||
lua_getglobal(L, func_name);
|
||||
if (lua_pcall(L, 0, 0, 0) != LUA_OK)
|
||||
{
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// PitchAngle
|
||||
TEST_F(LuaSourceEngine, PitchAngle_from_degrees) { check("Source_PitchAngle_from_degrees"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_clamping_max) { check("Source_PitchAngle_clamping_max"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_clamping_min) { check("Source_PitchAngle_clamping_min"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_from_radians) { check("Source_PitchAngle_from_radians"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_as_radians) { check("Source_PitchAngle_as_radians"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_sin) { check("Source_PitchAngle_sin"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_cos) { check("Source_PitchAngle_cos"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_tan) { check("Source_PitchAngle_tan"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_addition) { check("Source_PitchAngle_addition"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_addition_clamped) { check("Source_PitchAngle_addition_clamped"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_subtraction) { check("Source_PitchAngle_subtraction"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_unary_minus) { check("Source_PitchAngle_unary_minus"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_equal_to) { check("Source_PitchAngle_equal_to"); }
|
||||
TEST_F(LuaSourceEngine, PitchAngle_to_string) { check("Source_PitchAngle_to_string"); }
|
||||
|
||||
// YawAngle
|
||||
TEST_F(LuaSourceEngine, YawAngle_from_degrees) { check("Source_YawAngle_from_degrees"); }
|
||||
TEST_F(LuaSourceEngine, YawAngle_normalization) { check("Source_YawAngle_normalization"); }
|
||||
|
||||
// RollAngle
|
||||
TEST_F(LuaSourceEngine, RollAngle_from_degrees) { check("Source_RollAngle_from_degrees"); }
|
||||
|
||||
// FieldOfView
|
||||
TEST_F(LuaSourceEngine, FieldOfView_from_degrees) { check("Source_FieldOfView_from_degrees"); }
|
||||
TEST_F(LuaSourceEngine, FieldOfView_clamping) { check("Source_FieldOfView_clamping"); }
|
||||
|
||||
// ViewAngles
|
||||
TEST_F(LuaSourceEngine, ViewAngles_new) { check("Source_ViewAngles_new"); }
|
||||
TEST_F(LuaSourceEngine, ViewAngles_field_mutation) { check("Source_ViewAngles_field_mutation"); }
|
||||
|
||||
// Camera
|
||||
TEST_F(LuaSourceEngine, Camera_constructor) { check("Source_Camera_constructor"); }
|
||||
TEST_F(LuaSourceEngine, Camera_get_set_origin) { check("Source_Camera_get_set_origin"); }
|
||||
TEST_F(LuaSourceEngine, Camera_get_set_near_plane) { check("Source_Camera_get_set_near_plane"); }
|
||||
TEST_F(LuaSourceEngine, Camera_get_set_far_plane) { check("Source_Camera_get_set_far_plane"); }
|
||||
TEST_F(LuaSourceEngine, Camera_get_set_fov) { check("Source_Camera_get_set_fov"); }
|
||||
TEST_F(LuaSourceEngine, Camera_get_set_view_angles) { check("Source_Camera_get_set_view_angles"); }
|
||||
TEST_F(LuaSourceEngine, Camera_look_at) { check("Source_Camera_look_at"); }
|
||||
TEST_F(LuaSourceEngine, Camera_get_forward) { check("Source_Camera_get_forward"); }
|
||||
TEST_F(LuaSourceEngine, Camera_get_right) { check("Source_Camera_get_right"); }
|
||||
TEST_F(LuaSourceEngine, Camera_get_up) { check("Source_Camera_get_up"); }
|
||||
TEST_F(LuaSourceEngine, Camera_world_to_screen_success) { check("Source_Camera_world_to_screen_success"); }
|
||||
TEST_F(LuaSourceEngine, Camera_world_to_screen_error) { check("Source_Camera_world_to_screen_error"); }
|
||||
TEST_F(LuaSourceEngine, Camera_screen_to_world) { check("Source_Camera_screen_to_world"); }
|
||||
47
tests/lua/unit_test_lua_triangle.cpp
Normal file
47
tests/lua/unit_test_lua_triangle.cpp
Normal file
@@ -0,0 +1,47 @@
|
||||
//
|
||||
// Created by orange on 10.03.2026.
|
||||
//
|
||||
#include <gtest/gtest.h>
|
||||
#include <lua.hpp>
|
||||
#include <omath/lua/lua.hpp>
|
||||
|
||||
class LuaTriangle : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
lua_State* L = nullptr;
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
L = luaL_newstate();
|
||||
luaL_openlibs(L);
|
||||
omath::lua::LuaInterpreter::register_lib(L);
|
||||
if (luaL_dofile(L, LUA_SCRIPTS_DIR "/triangle_tests.lua") != LUA_OK)
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
}
|
||||
|
||||
void TearDown() override { lua_close(L); }
|
||||
|
||||
void check(const char* func_name)
|
||||
{
|
||||
lua_getglobal(L, func_name);
|
||||
if (lua_pcall(L, 0, 0, 0) != LUA_OK)
|
||||
{
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(LuaTriangle, Constructor_default) { check("Triangle_Constructor_default"); }
|
||||
TEST_F(LuaTriangle, Constructor_vertices) { check("Triangle_Constructor_vertices"); }
|
||||
TEST_F(LuaTriangle, Vertex_mutation) { check("Triangle_Vertex_mutation"); }
|
||||
TEST_F(LuaTriangle, SideALength) { check("Triangle_SideALength"); }
|
||||
TEST_F(LuaTriangle, SideBLength) { check("Triangle_SideBLength"); }
|
||||
TEST_F(LuaTriangle, Hypot) { check("Triangle_Hypot"); }
|
||||
TEST_F(LuaTriangle, SideAVector) { check("Triangle_SideAVector"); }
|
||||
TEST_F(LuaTriangle, SideBVector) { check("Triangle_SideBVector"); }
|
||||
TEST_F(LuaTriangle, IsRectangular_true) { check("Triangle_IsRectangular_true"); }
|
||||
TEST_F(LuaTriangle, IsRectangular_false) { check("Triangle_IsRectangular_false"); }
|
||||
TEST_F(LuaTriangle, MidPoint) { check("Triangle_MidPoint"); }
|
||||
TEST_F(LuaTriangle, CalculateNormal) { check("Triangle_CalculateNormal"); }
|
||||
TEST_F(LuaTriangle, ToString) { check("Triangle_ToString"); }
|
||||
56
tests/lua/unit_test_lua_vector2.cpp
Normal file
56
tests/lua/unit_test_lua_vector2.cpp
Normal file
@@ -0,0 +1,56 @@
|
||||
//
|
||||
// Created by orange on 07.03.2026.
|
||||
//
|
||||
#include <gtest/gtest.h>
|
||||
#include <lua.hpp>
|
||||
#include <omath/lua/lua.hpp>
|
||||
|
||||
class LuaVec2 : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
lua_State* L = nullptr;
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
L = luaL_newstate();
|
||||
luaL_openlibs(L);
|
||||
omath::lua::LuaInterpreter::register_lib(L);
|
||||
if (luaL_dofile(L, LUA_SCRIPTS_DIR "/vec2_tests.lua") != LUA_OK)
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
}
|
||||
|
||||
void TearDown() override { lua_close(L); }
|
||||
|
||||
void check(const char* func_name)
|
||||
{
|
||||
lua_getglobal(L, func_name);
|
||||
if (lua_pcall(L, 0, 0, 0) != LUA_OK)
|
||||
{
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(LuaVec2, Constructor_default) { check("Vec2_Constructor_default"); }
|
||||
TEST_F(LuaVec2, Constructor_xy) { check("Vec2_Constructor_xy"); }
|
||||
TEST_F(LuaVec2, Field_mutation) { check("Vec2_Field_mutation"); }
|
||||
TEST_F(LuaVec2, Addition) { check("Vec2_Addition"); }
|
||||
TEST_F(LuaVec2, Subtraction) { check("Vec2_Subtraction"); }
|
||||
TEST_F(LuaVec2, UnaryMinus) { check("Vec2_UnaryMinus"); }
|
||||
TEST_F(LuaVec2, Multiplication_scalar) { check("Vec2_Multiplication_scalar"); }
|
||||
TEST_F(LuaVec2, Multiplication_scalar_reversed) { check("Vec2_Multiplication_scalar_reversed"); }
|
||||
TEST_F(LuaVec2, Division_scalar) { check("Vec2_Division_scalar"); }
|
||||
TEST_F(LuaVec2, EqualTo_true) { check("Vec2_EqualTo_true"); }
|
||||
TEST_F(LuaVec2, EqualTo_false) { check("Vec2_EqualTo_false"); }
|
||||
TEST_F(LuaVec2, LessThan) { check("Vec2_LessThan"); }
|
||||
TEST_F(LuaVec2, LessThanOrEqual) { check("Vec2_LessThanOrEqual"); }
|
||||
TEST_F(LuaVec2, ToString) { check("Vec2_ToString"); }
|
||||
TEST_F(LuaVec2, Length) { check("Vec2_Length"); }
|
||||
TEST_F(LuaVec2, LengthSqr) { check("Vec2_LengthSqr"); }
|
||||
TEST_F(LuaVec2, Normalized) { check("Vec2_Normalized"); }
|
||||
TEST_F(LuaVec2, Dot) { check("Vec2_Dot"); }
|
||||
TEST_F(LuaVec2, DistanceTo) { check("Vec2_DistanceTo"); }
|
||||
TEST_F(LuaVec2, DistanceToSqr) { check("Vec2_DistanceToSqr"); }
|
||||
TEST_F(LuaVec2, Sum) { check("Vec2_Sum"); }
|
||||
TEST_F(LuaVec2, Abs) { check("Vec2_Abs"); }
|
||||
69
tests/lua/unit_test_lua_vector3.cpp
Normal file
69
tests/lua/unit_test_lua_vector3.cpp
Normal file
@@ -0,0 +1,69 @@
|
||||
//
|
||||
// Created by orange on 07.03.2026.
|
||||
//
|
||||
#include <gtest/gtest.h>
|
||||
#include <lua.hpp>
|
||||
#include <omath/lua/lua.hpp>
|
||||
|
||||
class LuaVec3 : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
lua_State* L = nullptr;
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
L = luaL_newstate();
|
||||
luaL_openlibs(L);
|
||||
omath::lua::LuaInterpreter::register_lib(L);
|
||||
if (luaL_dofile(L, LUA_SCRIPTS_DIR "/vec3_tests.lua") != LUA_OK)
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
}
|
||||
|
||||
void TearDown() override { lua_close(L); }
|
||||
|
||||
void check(const char* func_name)
|
||||
{
|
||||
lua_getglobal(L, func_name);
|
||||
if (lua_pcall(L, 0, 0, 0) != LUA_OK)
|
||||
{
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(LuaVec3, Constructor_default) { check("Vec3_Constructor_default"); }
|
||||
TEST_F(LuaVec3, Constructor_xyz) { check("Vec3_Constructor_xyz"); }
|
||||
TEST_F(LuaVec3, Field_mutation) { check("Vec3_Field_mutation"); }
|
||||
TEST_F(LuaVec3, Addition) { check("Vec3_Addition"); }
|
||||
TEST_F(LuaVec3, Subtraction) { check("Vec3_Subtraction"); }
|
||||
TEST_F(LuaVec3, UnaryMinus) { check("Vec3_UnaryMinus"); }
|
||||
TEST_F(LuaVec3, Multiplication_scalar) { check("Vec3_Multiplication_scalar"); }
|
||||
TEST_F(LuaVec3, Multiplication_scalar_reversed) { check("Vec3_Multiplication_scalar_reversed"); }
|
||||
TEST_F(LuaVec3, Multiplication_vec) { check("Vec3_Multiplication_vec"); }
|
||||
TEST_F(LuaVec3, Division_scalar) { check("Vec3_Division_scalar"); }
|
||||
TEST_F(LuaVec3, Division_vec) { check("Vec3_Division_vec"); }
|
||||
TEST_F(LuaVec3, EqualTo_true) { check("Vec3_EqualTo_true"); }
|
||||
TEST_F(LuaVec3, EqualTo_false) { check("Vec3_EqualTo_false"); }
|
||||
TEST_F(LuaVec3, LessThan) { check("Vec3_LessThan"); }
|
||||
TEST_F(LuaVec3, LessThanOrEqual) { check("Vec3_LessThanOrEqual"); }
|
||||
TEST_F(LuaVec3, ToString) { check("Vec3_ToString"); }
|
||||
TEST_F(LuaVec3, Length) { check("Vec3_Length"); }
|
||||
TEST_F(LuaVec3, Length2d) { check("Vec3_Length2d"); }
|
||||
TEST_F(LuaVec3, LengthSqr) { check("Vec3_LengthSqr"); }
|
||||
TEST_F(LuaVec3, Normalized) { check("Vec3_Normalized"); }
|
||||
TEST_F(LuaVec3, Dot_perpendicular) { check("Vec3_Dot_perpendicular"); }
|
||||
TEST_F(LuaVec3, Dot_parallel) { check("Vec3_Dot_parallel"); }
|
||||
TEST_F(LuaVec3, Cross) { check("Vec3_Cross"); }
|
||||
TEST_F(LuaVec3, DistanceTo) { check("Vec3_DistanceTo"); }
|
||||
TEST_F(LuaVec3, DistanceToSqr) { check("Vec3_DistanceToSqr"); }
|
||||
TEST_F(LuaVec3, Sum) { check("Vec3_Sum"); }
|
||||
TEST_F(LuaVec3, Sum2d) { check("Vec3_Sum2d"); }
|
||||
TEST_F(LuaVec3, Abs) { check("Vec3_Abs"); }
|
||||
TEST_F(LuaVec3, PointToSameDirection_true) { check("Vec3_PointToSameDirection_true"); }
|
||||
TEST_F(LuaVec3, PointToSameDirection_false) { check("Vec3_PointToSameDirection_false"); }
|
||||
TEST_F(LuaVec3, IsPerpendicular_true) { check("Vec3_IsPerpendicular_true"); }
|
||||
TEST_F(LuaVec3, IsPerpendicular_false) { check("Vec3_IsPerpendicular_false"); }
|
||||
TEST_F(LuaVec3, AngleBetween_90deg) { check("Vec3_AngleBetween_90deg"); }
|
||||
TEST_F(LuaVec3, AngleBetween_zero_vector_error) { check("Vec3_AngleBetween_zero_vector_error"); }
|
||||
TEST_F(LuaVec3, AsTable) { check("Vec3_AsTable"); }
|
||||
57
tests/lua/unit_test_lua_vector4.cpp
Normal file
57
tests/lua/unit_test_lua_vector4.cpp
Normal file
@@ -0,0 +1,57 @@
|
||||
//
|
||||
// Created by orange on 07.03.2026.
|
||||
//
|
||||
#include <gtest/gtest.h>
|
||||
#include <lua.hpp>
|
||||
#include <omath/lua/lua.hpp>
|
||||
|
||||
class LuaVec4 : public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
lua_State* L = nullptr;
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
L = luaL_newstate();
|
||||
luaL_openlibs(L);
|
||||
omath::lua::LuaInterpreter::register_lib(L);
|
||||
if (luaL_dofile(L, LUA_SCRIPTS_DIR "/vec4_tests.lua") != LUA_OK)
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
}
|
||||
|
||||
void TearDown() override { lua_close(L); }
|
||||
|
||||
void check(const char* func_name)
|
||||
{
|
||||
lua_getglobal(L, func_name);
|
||||
if (lua_pcall(L, 0, 0, 0) != LUA_OK)
|
||||
{
|
||||
FAIL() << lua_tostring(L, -1);
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(LuaVec4, Constructor_default) { check("Vec4_Constructor_default"); }
|
||||
TEST_F(LuaVec4, Constructor_xyzw) { check("Vec4_Constructor_xyzw"); }
|
||||
TEST_F(LuaVec4, Field_mutation) { check("Vec4_Field_mutation"); }
|
||||
TEST_F(LuaVec4, Addition) { check("Vec4_Addition"); }
|
||||
TEST_F(LuaVec4, Subtraction) { check("Vec4_Subtraction"); }
|
||||
TEST_F(LuaVec4, UnaryMinus) { check("Vec4_UnaryMinus"); }
|
||||
TEST_F(LuaVec4, Multiplication_scalar) { check("Vec4_Multiplication_scalar"); }
|
||||
TEST_F(LuaVec4, Multiplication_scalar_reversed) { check("Vec4_Multiplication_scalar_reversed"); }
|
||||
TEST_F(LuaVec4, Multiplication_vec) { check("Vec4_Multiplication_vec"); }
|
||||
TEST_F(LuaVec4, Division_scalar) { check("Vec4_Division_scalar"); }
|
||||
TEST_F(LuaVec4, Division_vec) { check("Vec4_Division_vec"); }
|
||||
TEST_F(LuaVec4, EqualTo_true) { check("Vec4_EqualTo_true"); }
|
||||
TEST_F(LuaVec4, EqualTo_false) { check("Vec4_EqualTo_false"); }
|
||||
TEST_F(LuaVec4, LessThan) { check("Vec4_LessThan"); }
|
||||
TEST_F(LuaVec4, LessThanOrEqual) { check("Vec4_LessThanOrEqual"); }
|
||||
TEST_F(LuaVec4, ToString) { check("Vec4_ToString"); }
|
||||
TEST_F(LuaVec4, Length) { check("Vec4_Length"); }
|
||||
TEST_F(LuaVec4, LengthSqr) { check("Vec4_LengthSqr"); }
|
||||
TEST_F(LuaVec4, Dot) { check("Vec4_Dot"); }
|
||||
TEST_F(LuaVec4, Dot_perpendicular) { check("Vec4_Dot_perpendicular"); }
|
||||
TEST_F(LuaVec4, Sum) { check("Vec4_Sum"); }
|
||||
TEST_F(LuaVec4, Abs) { check("Vec4_Abs"); }
|
||||
TEST_F(LuaVec4, Clamp) { check("Vec4_Clamp"); }
|
||||
102
tests/lua/vec2_tests.lua
Normal file
102
tests/lua/vec2_tests.lua
Normal file
@@ -0,0 +1,102 @@
|
||||
local function approx(a, b) return math.abs(a - b) < 1e-5 end
|
||||
|
||||
function Vec2_Constructor_default()
|
||||
local v = omath.Vec2.new()
|
||||
assert(v.x == 0 and v.y == 0)
|
||||
end
|
||||
|
||||
function Vec2_Constructor_xy()
|
||||
local v = omath.Vec2.new(3, 4)
|
||||
assert(v.x == 3 and v.y == 4)
|
||||
end
|
||||
|
||||
function Vec2_Field_mutation()
|
||||
local v = omath.Vec2.new(1, 2)
|
||||
v.x = 9; v.y = 8
|
||||
assert(v.x == 9 and v.y == 8)
|
||||
end
|
||||
|
||||
function Vec2_Addition()
|
||||
local c = omath.Vec2.new(1, 2) + omath.Vec2.new(3, 4)
|
||||
assert(c.x == 4 and c.y == 6)
|
||||
end
|
||||
|
||||
function Vec2_Subtraction()
|
||||
local c = omath.Vec2.new(5, 7) - omath.Vec2.new(2, 3)
|
||||
assert(c.x == 3 and c.y == 4)
|
||||
end
|
||||
|
||||
function Vec2_UnaryMinus()
|
||||
local b = -omath.Vec2.new(1, 2)
|
||||
assert(b.x == -1 and b.y == -2)
|
||||
end
|
||||
|
||||
function Vec2_Multiplication_scalar()
|
||||
local b = omath.Vec2.new(2, 3) * 2.0
|
||||
assert(b.x == 4 and b.y == 6)
|
||||
end
|
||||
|
||||
function Vec2_Multiplication_scalar_reversed()
|
||||
local b = 2.0 * omath.Vec2.new(2, 3)
|
||||
assert(b.x == 4 and b.y == 6)
|
||||
end
|
||||
|
||||
function Vec2_Division_scalar()
|
||||
local b = omath.Vec2.new(4, 6) / 2.0
|
||||
assert(b.x == 2 and b.y == 3)
|
||||
end
|
||||
|
||||
function Vec2_EqualTo_true()
|
||||
assert(omath.Vec2.new(1, 2) == omath.Vec2.new(1, 2))
|
||||
end
|
||||
|
||||
function Vec2_EqualTo_false()
|
||||
assert(not (omath.Vec2.new(1, 2) == omath.Vec2.new(9, 9)))
|
||||
end
|
||||
|
||||
function Vec2_LessThan()
|
||||
assert(omath.Vec2.new(1, 0) < omath.Vec2.new(3, 4))
|
||||
end
|
||||
|
||||
function Vec2_LessThanOrEqual()
|
||||
-- (3,4) and (4,3) both have length 5
|
||||
assert(omath.Vec2.new(3, 4) <= omath.Vec2.new(4, 3))
|
||||
end
|
||||
|
||||
function Vec2_ToString()
|
||||
assert(tostring(omath.Vec2.new(1, 2)) == "Vec2(1, 2)")
|
||||
end
|
||||
|
||||
function Vec2_Length()
|
||||
assert(approx(omath.Vec2.new(3, 4):length(), 5.0))
|
||||
end
|
||||
|
||||
function Vec2_LengthSqr()
|
||||
assert(omath.Vec2.new(3, 4):length_sqr() == 25.0)
|
||||
end
|
||||
|
||||
function Vec2_Normalized()
|
||||
local n = omath.Vec2.new(3, 4):normalized()
|
||||
assert(approx(n.x, 0.6) and approx(n.y, 0.8))
|
||||
end
|
||||
|
||||
function Vec2_Dot()
|
||||
assert(omath.Vec2.new(1, 2):dot(omath.Vec2.new(3, 4)) == 11.0)
|
||||
end
|
||||
|
||||
function Vec2_DistanceTo()
|
||||
assert(approx(omath.Vec2.new(0, 0):distance_to(omath.Vec2.new(3, 4)), 5.0))
|
||||
end
|
||||
|
||||
function Vec2_DistanceToSqr()
|
||||
assert(omath.Vec2.new(0, 0):distance_to_sqr(omath.Vec2.new(3, 4)) == 25.0)
|
||||
end
|
||||
|
||||
function Vec2_Sum()
|
||||
assert(omath.Vec2.new(3, 4):sum() == 7.0)
|
||||
end
|
||||
|
||||
function Vec2_Abs()
|
||||
local a = omath.Vec2.new(-3, -4):abs()
|
||||
assert(a.x == 3 and a.y == 4)
|
||||
end
|
||||
163
tests/lua/vec3_tests.lua
Normal file
163
tests/lua/vec3_tests.lua
Normal file
@@ -0,0 +1,163 @@
|
||||
local function approx(a, b, eps) return math.abs(a - b) < (eps or 1e-5) end
|
||||
|
||||
function Vec3_Constructor_default()
|
||||
local v = omath.Vec3.new()
|
||||
assert(v.x == 0 and v.y == 0 and v.z == 0)
|
||||
end
|
||||
|
||||
function Vec3_Constructor_xyz()
|
||||
local v = omath.Vec3.new(1, 2, 3)
|
||||
assert(v.x == 1 and v.y == 2 and v.z == 3)
|
||||
end
|
||||
|
||||
function Vec3_Field_mutation()
|
||||
local v = omath.Vec3.new(1, 2, 3)
|
||||
v.x = 9; v.y = 8; v.z = 7
|
||||
assert(v.x == 9 and v.y == 8 and v.z == 7)
|
||||
end
|
||||
|
||||
function Vec3_Addition()
|
||||
local c = omath.Vec3.new(1, 2, 3) + omath.Vec3.new(4, 5, 6)
|
||||
assert(c.x == 5 and c.y == 7 and c.z == 9)
|
||||
end
|
||||
|
||||
function Vec3_Subtraction()
|
||||
local c = omath.Vec3.new(4, 5, 6) - omath.Vec3.new(1, 2, 3)
|
||||
assert(c.x == 3 and c.y == 3 and c.z == 3)
|
||||
end
|
||||
|
||||
function Vec3_UnaryMinus()
|
||||
local b = -omath.Vec3.new(1, 2, 3)
|
||||
assert(b.x == -1 and b.y == -2 and b.z == -3)
|
||||
end
|
||||
|
||||
function Vec3_Multiplication_scalar()
|
||||
local b = omath.Vec3.new(1, 2, 3) * 2.0
|
||||
assert(b.x == 2 and b.y == 4 and b.z == 6)
|
||||
end
|
||||
|
||||
function Vec3_Multiplication_scalar_reversed()
|
||||
local b = 2.0 * omath.Vec3.new(1, 2, 3)
|
||||
assert(b.x == 2 and b.y == 4 and b.z == 6)
|
||||
end
|
||||
|
||||
function Vec3_Multiplication_vec()
|
||||
local c = omath.Vec3.new(2, 3, 4) * omath.Vec3.new(2, 2, 2)
|
||||
assert(c.x == 4 and c.y == 6 and c.z == 8)
|
||||
end
|
||||
|
||||
function Vec3_Division_scalar()
|
||||
local b = omath.Vec3.new(2, 4, 6) / 2.0
|
||||
assert(b.x == 1 and b.y == 2 and b.z == 3)
|
||||
end
|
||||
|
||||
function Vec3_Division_vec()
|
||||
local c = omath.Vec3.new(4, 6, 8) / omath.Vec3.new(2, 2, 2)
|
||||
assert(c.x == 2 and c.y == 3 and c.z == 4)
|
||||
end
|
||||
|
||||
function Vec3_EqualTo_true()
|
||||
assert(omath.Vec3.new(1, 2, 3) == omath.Vec3.new(1, 2, 3))
|
||||
end
|
||||
|
||||
function Vec3_EqualTo_false()
|
||||
assert(not (omath.Vec3.new(1, 2, 3) == omath.Vec3.new(9, 9, 9)))
|
||||
end
|
||||
|
||||
function Vec3_LessThan()
|
||||
assert(omath.Vec3.new(1, 0, 0) < omath.Vec3.new(3, 4, 0))
|
||||
end
|
||||
|
||||
function Vec3_LessThanOrEqual()
|
||||
-- (0,3,4) and (0,4,3) both have length 5
|
||||
assert(omath.Vec3.new(0, 3, 4) <= omath.Vec3.new(0, 4, 3))
|
||||
end
|
||||
|
||||
function Vec3_ToString()
|
||||
assert(tostring(omath.Vec3.new(1, 2, 3)) == "Vec3(1, 2, 3)")
|
||||
end
|
||||
|
||||
function Vec3_Length()
|
||||
assert(approx(omath.Vec3.new(1, 2, 2):length(), 3.0))
|
||||
end
|
||||
|
||||
function Vec3_Length2d()
|
||||
assert(approx(omath.Vec3.new(3, 4, 99):length_2d(), 5.0))
|
||||
end
|
||||
|
||||
function Vec3_LengthSqr()
|
||||
assert(omath.Vec3.new(1, 2, 2):length_sqr() == 9.0)
|
||||
end
|
||||
|
||||
function Vec3_Normalized()
|
||||
local n = omath.Vec3.new(3, 0, 0):normalized()
|
||||
assert(approx(n.x, 1.0) and approx(n.y, 0.0) and approx(n.z, 0.0))
|
||||
end
|
||||
|
||||
function Vec3_Dot_perpendicular()
|
||||
assert(omath.Vec3.new(1, 0, 0):dot(omath.Vec3.new(0, 1, 0)) == 0.0)
|
||||
end
|
||||
|
||||
function Vec3_Dot_parallel()
|
||||
local a = omath.Vec3.new(1, 2, 3)
|
||||
assert(a:dot(a) == 14.0)
|
||||
end
|
||||
|
||||
function Vec3_Cross()
|
||||
local c = omath.Vec3.new(1, 0, 0):cross(omath.Vec3.new(0, 1, 0))
|
||||
assert(approx(c.x, 0) and approx(c.y, 0) and approx(c.z, 1))
|
||||
end
|
||||
|
||||
function Vec3_DistanceTo()
|
||||
assert(approx(omath.Vec3.new(0, 0, 0):distance_to(omath.Vec3.new(1, 2, 2)), 3.0))
|
||||
end
|
||||
|
||||
function Vec3_DistanceToSqr()
|
||||
assert(omath.Vec3.new(0, 0, 0):distance_to_sqr(omath.Vec3.new(1, 2, 2)) == 9.0)
|
||||
end
|
||||
|
||||
function Vec3_Sum()
|
||||
assert(omath.Vec3.new(1, 2, 3):sum() == 6.0)
|
||||
end
|
||||
|
||||
function Vec3_Sum2d()
|
||||
assert(omath.Vec3.new(1, 2, 3):sum_2d() == 3.0)
|
||||
end
|
||||
|
||||
function Vec3_Abs()
|
||||
local a = omath.Vec3.new(-1, -2, -3):abs()
|
||||
assert(a.x == 1 and a.y == 2 and a.z == 3)
|
||||
end
|
||||
|
||||
function Vec3_PointToSameDirection_true()
|
||||
assert(omath.Vec3.new(1, 1, 0):point_to_same_direction(omath.Vec3.new(2, 2, 0)) == true)
|
||||
end
|
||||
|
||||
function Vec3_PointToSameDirection_false()
|
||||
assert(omath.Vec3.new(1, 0, 0):point_to_same_direction(omath.Vec3.new(-1, 0, 0)) == false)
|
||||
end
|
||||
|
||||
function Vec3_IsPerpendicular_true()
|
||||
assert(omath.Vec3.new(1, 0, 0):is_perpendicular(omath.Vec3.new(0, 1, 0)) == true)
|
||||
end
|
||||
|
||||
function Vec3_IsPerpendicular_false()
|
||||
local a = omath.Vec3.new(1, 0, 0)
|
||||
assert(a:is_perpendicular(a) == false)
|
||||
end
|
||||
|
||||
function Vec3_AngleBetween_90deg()
|
||||
local angle, err = omath.Vec3.new(1, 0, 0):angle_between(omath.Vec3.new(0, 1, 0))
|
||||
assert(angle ~= nil, err)
|
||||
assert(math.abs(angle - 90.0) < 1e-3)
|
||||
end
|
||||
|
||||
function Vec3_AngleBetween_zero_vector_error()
|
||||
local angle, err = omath.Vec3.new(0, 0, 0):angle_between(omath.Vec3.new(1, 0, 0))
|
||||
assert(angle == nil and err ~= nil)
|
||||
end
|
||||
|
||||
function Vec3_AsTable()
|
||||
local t = omath.Vec3.new(1, 2, 3):as_table()
|
||||
assert(t.x == 1 and t.y == 2 and t.z == 3)
|
||||
end
|
||||
110
tests/lua/vec4_tests.lua
Normal file
110
tests/lua/vec4_tests.lua
Normal file
@@ -0,0 +1,110 @@
|
||||
local function approx(a, b) return math.abs(a - b) < 1e-5 end
|
||||
|
||||
function Vec4_Constructor_default()
|
||||
local v = omath.Vec4.new()
|
||||
assert(v.x == 0 and v.y == 0 and v.z == 0 and v.w == 0)
|
||||
end
|
||||
|
||||
function Vec4_Constructor_xyzw()
|
||||
local v = omath.Vec4.new(1, 2, 3, 4)
|
||||
assert(v.x == 1 and v.y == 2 and v.z == 3 and v.w == 4)
|
||||
end
|
||||
|
||||
function Vec4_Field_mutation()
|
||||
local v = omath.Vec4.new(1, 2, 3, 4)
|
||||
v.w = 99
|
||||
assert(v.w == 99)
|
||||
end
|
||||
|
||||
function Vec4_Addition()
|
||||
local c = omath.Vec4.new(1, 2, 3, 4) + omath.Vec4.new(4, 3, 2, 1)
|
||||
assert(c.x == 5 and c.y == 5 and c.z == 5 and c.w == 5)
|
||||
end
|
||||
|
||||
function Vec4_Subtraction()
|
||||
local c = omath.Vec4.new(5, 5, 5, 5) - omath.Vec4.new(1, 2, 3, 4)
|
||||
assert(c.x == 4 and c.y == 3 and c.z == 2 and c.w == 1)
|
||||
end
|
||||
|
||||
function Vec4_UnaryMinus()
|
||||
local b = -omath.Vec4.new(1, 2, 3, 4)
|
||||
assert(b.x == -1 and b.y == -2 and b.z == -3 and b.w == -4)
|
||||
end
|
||||
|
||||
function Vec4_Multiplication_scalar()
|
||||
local b = omath.Vec4.new(1, 2, 3, 4) * 2.0
|
||||
assert(b.x == 2 and b.y == 4 and b.z == 6 and b.w == 8)
|
||||
end
|
||||
|
||||
function Vec4_Multiplication_scalar_reversed()
|
||||
local b = 2.0 * omath.Vec4.new(1, 2, 3, 4)
|
||||
assert(b.x == 2 and b.y == 4 and b.z == 6 and b.w == 8)
|
||||
end
|
||||
|
||||
function Vec4_Multiplication_vec()
|
||||
local c = omath.Vec4.new(2, 3, 4, 5) * omath.Vec4.new(2, 2, 2, 2)
|
||||
assert(c.x == 4 and c.y == 6 and c.z == 8 and c.w == 10)
|
||||
end
|
||||
|
||||
function Vec4_Division_scalar()
|
||||
local b = omath.Vec4.new(2, 4, 6, 8) / 2.0
|
||||
assert(b.x == 1 and b.y == 2 and b.z == 3 and b.w == 4)
|
||||
end
|
||||
|
||||
function Vec4_Division_vec()
|
||||
local c = omath.Vec4.new(4, 6, 8, 10) / omath.Vec4.new(2, 2, 2, 2)
|
||||
assert(c.x == 2 and c.y == 3 and c.z == 4 and c.w == 5)
|
||||
end
|
||||
|
||||
function Vec4_EqualTo_true()
|
||||
assert(omath.Vec4.new(1, 2, 3, 4) == omath.Vec4.new(1, 2, 3, 4))
|
||||
end
|
||||
|
||||
function Vec4_EqualTo_false()
|
||||
assert(not (omath.Vec4.new(1, 2, 3, 4) == omath.Vec4.new(9, 9, 9, 9)))
|
||||
end
|
||||
|
||||
function Vec4_LessThan()
|
||||
assert(omath.Vec4.new(1, 0, 0, 0) < omath.Vec4.new(0, 0, 3, 4))
|
||||
end
|
||||
|
||||
function Vec4_LessThanOrEqual()
|
||||
-- (0,0,3,4) and (0,0,4,3) both have length 5
|
||||
assert(omath.Vec4.new(0, 0, 3, 4) <= omath.Vec4.new(0, 0, 4, 3))
|
||||
end
|
||||
|
||||
function Vec4_ToString()
|
||||
assert(tostring(omath.Vec4.new(1, 2, 3, 4)) == "Vec4(1, 2, 3, 4)")
|
||||
end
|
||||
|
||||
function Vec4_Length()
|
||||
assert(approx(omath.Vec4.new(0, 0, 3, 4):length(), 5.0))
|
||||
end
|
||||
|
||||
function Vec4_LengthSqr()
|
||||
assert(omath.Vec4.new(0, 0, 3, 4):length_sqr() == 25.0)
|
||||
end
|
||||
|
||||
function Vec4_Dot()
|
||||
local a = omath.Vec4.new(1, 2, 3, 4)
|
||||
assert(a:dot(a) == 30.0)
|
||||
end
|
||||
|
||||
function Vec4_Dot_perpendicular()
|
||||
assert(omath.Vec4.new(1, 0, 0, 0):dot(omath.Vec4.new(0, 1, 0, 0)) == 0.0)
|
||||
end
|
||||
|
||||
function Vec4_Sum()
|
||||
assert(omath.Vec4.new(1, 2, 3, 4):sum() == 10.0)
|
||||
end
|
||||
|
||||
function Vec4_Abs()
|
||||
local a = omath.Vec4.new(-1, -2, -3, -4):abs()
|
||||
assert(a.x == 1 and a.y == 2 and a.z == 3 and a.w == 4)
|
||||
end
|
||||
|
||||
function Vec4_Clamp()
|
||||
local v = omath.Vec4.new(5, -3, 10, 99)
|
||||
v:clamp(0, 7)
|
||||
assert(v.x == 5 and v.y == 0 and v.z == 7)
|
||||
end
|
||||
29
tests/lua/vector2_test.lua
Normal file
29
tests/lua/vector2_test.lua
Normal file
@@ -0,0 +1,29 @@
|
||||
local a = omath.Vec2.new(1, 2)
|
||||
local b = omath.Vec2.new(10, 20)
|
||||
|
||||
-- Operators
|
||||
local c = a + b
|
||||
local d = a - b
|
||||
local e = a * 2.0
|
||||
local f = -a
|
||||
print("a + b = " .. tostring(c))
|
||||
print("a - b = " .. tostring(d))
|
||||
print("a * 2 = " .. tostring(e))
|
||||
print("-a = " .. tostring(f))
|
||||
print("a == Vec2(1,2): " .. tostring(a == omath.Vec2.new(1, 2)))
|
||||
print("a < b: " .. tostring(a < b))
|
||||
|
||||
-- Field access + mutation
|
||||
print("c.x = " .. c.x .. ", c.y = " .. c.y)
|
||||
c.x = 99
|
||||
print("c.x after mutation = " .. c.x)
|
||||
|
||||
-- Methods
|
||||
print("a:length() = " .. a:length())
|
||||
print("a:length_sqr() = " .. a:length_sqr())
|
||||
print("a:normalized() = " .. tostring(a:normalized()))
|
||||
print("a:dot(b) = " .. a:dot(b))
|
||||
print("a:distance_to(b) = " .. a:distance_to(b))
|
||||
print("a:distance_to_sqr(b) = " .. a:distance_to_sqr(b))
|
||||
print("a:sum() = " .. a:sum())
|
||||
print("a:abs() = " .. tostring(a:abs()))
|
||||
55
tests/lua/vector3_test.lua
Normal file
55
tests/lua/vector3_test.lua
Normal file
@@ -0,0 +1,55 @@
|
||||
local a = omath.Vec3.new(1, 0, 0)
|
||||
local b = omath.Vec3.new(0, 1, 0)
|
||||
|
||||
-- Operators
|
||||
local c = a + b
|
||||
local d = a - b
|
||||
local e = a * 2.0
|
||||
local f = -a
|
||||
print("a + b = " .. tostring(c))
|
||||
print("a - b = " .. tostring(d))
|
||||
print("a * 2 = " .. tostring(e))
|
||||
print("-a = " .. tostring(f))
|
||||
print("a == Vec3(1,2,3): " .. tostring(a == omath.Vec3.new(1, 2, 3)))
|
||||
print("a < b: " .. tostring(a < b))
|
||||
|
||||
-- Field access + mutation
|
||||
print("c.x = " .. c.x .. ", c.y = " .. c.y .. ", c.z = " .. c.z)
|
||||
c.x = 99
|
||||
print("c.x after mutation = " .. c.x)
|
||||
|
||||
-- Methods
|
||||
print("a:length() = " .. a:length())
|
||||
print("a:length_2d() = " .. a:length_2d())
|
||||
print("a:length_sqr() = " .. a:length_sqr())
|
||||
print("a:normalized() = " .. tostring(a:normalized()))
|
||||
print("a:dot(b) = " .. a:dot(b))
|
||||
print("a:cross(b) = " .. tostring(a:cross(b)))
|
||||
print("a:distance_to(b) = " .. a:distance_to(b))
|
||||
print("a:distance_to_sqr(b) = " .. a:distance_to_sqr(b))
|
||||
print("a:abs() = " .. tostring(a:abs()))
|
||||
print("a:sum() = " .. a:sum())
|
||||
print("a:sum_2d() = " .. a:sum_2d())
|
||||
print("a:point_to_same_direction(b) = " .. tostring(a:point_to_same_direction(b)))
|
||||
print("a:is_perpendicular(b) = " .. tostring(a:is_perpendicular(b)))
|
||||
|
||||
-- angle_between
|
||||
local angle, err = a:angle_between(b)
|
||||
if angle then
|
||||
print("angle_between = " .. angle .. " degrees")
|
||||
else
|
||||
print("angle_between error: " .. err)
|
||||
end
|
||||
|
||||
-- Zero vector edge case
|
||||
local zero = omath.Vec3.new(0, 0, 0)
|
||||
local ang2, err2 = zero:angle_between(a)
|
||||
if ang2 then
|
||||
print("zero angle = " .. ang2)
|
||||
else
|
||||
print("zero angle error: " .. err2)
|
||||
end
|
||||
|
||||
-- as_table
|
||||
local t = a:as_table()
|
||||
print("as_table: x=" .. t.x .. " y=" .. t.y .. " z=" .. t.z)
|
||||
31
tests/lua/vector4_test.lua
Normal file
31
tests/lua/vector4_test.lua
Normal file
@@ -0,0 +1,31 @@
|
||||
local a = omath.Vec4.new(1, 2, 3, 4)
|
||||
local b = omath.Vec4.new(10, 20, 30, 40)
|
||||
|
||||
-- Operators
|
||||
local c = a + b
|
||||
local d = a - b
|
||||
local e = a * 2.0
|
||||
local f = -a
|
||||
print("a + b = " .. tostring(c))
|
||||
print("a - b = " .. tostring(d))
|
||||
print("a * 2 = " .. tostring(e))
|
||||
print("-a = " .. tostring(f))
|
||||
print("a == Vec4(1,2,3,4): " .. tostring(a == omath.Vec4.new(1, 2, 3, 4)))
|
||||
print("a < b: " .. tostring(a < b))
|
||||
|
||||
-- Field access + mutation
|
||||
print("c.x=" .. c.x .. " c.y=" .. c.y .. " c.z=" .. c.z .. " c.w=" .. c.w)
|
||||
c.w = 99
|
||||
print("c.w after mutation = " .. c.w)
|
||||
|
||||
-- Methods
|
||||
print("a:length() = " .. a:length())
|
||||
print("a:length_sqr() = " .. a:length_sqr())
|
||||
print("a:dot(b) = " .. a:dot(b))
|
||||
print("a:sum() = " .. a:sum())
|
||||
print("a:abs() = " .. tostring(a:abs()))
|
||||
|
||||
-- clamp
|
||||
local clamped = omath.Vec4.new(5, -3, 10, 1)
|
||||
clamped:clamp(0, 7)
|
||||
print("clamp([5,-3,10,1], 0, 7).x=" .. clamped.x .. " .y=" .. clamped.y .. " .z=" .. clamped.z)
|
||||
17
vcpkg.json
17
vcpkg.json
@@ -17,7 +17,7 @@
|
||||
],
|
||||
"features": {
|
||||
"avx2": {
|
||||
"description": "Omath will use AVX2 to boost performance",
|
||||
"description": "omath will use AVX2 to boost performance",
|
||||
"supports": "!arm"
|
||||
},
|
||||
"benchmark": {
|
||||
@@ -31,11 +31,15 @@
|
||||
"dependencies": [
|
||||
"glfw3",
|
||||
"glew",
|
||||
"opengl"
|
||||
"opengl",
|
||||
{
|
||||
"name": "imgui",
|
||||
"features": ["glfw-binding", "opengl3-binding"]
|
||||
}
|
||||
]
|
||||
},
|
||||
"imgui": {
|
||||
"description": "Omath will define method to convert omath types to imgui types",
|
||||
"description": "omath will define method to convert omath types to imgui types",
|
||||
"dependencies": [
|
||||
"imgui"
|
||||
]
|
||||
@@ -45,6 +49,13 @@
|
||||
"dependencies": [
|
||||
"gtest"
|
||||
]
|
||||
},
|
||||
"lua": {
|
||||
"description": "lua support for omath",
|
||||
"dependencies": [
|
||||
"lua",
|
||||
"sol2"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user