From 98baa1326460f275dead577b9ed18eba092a9385 Mon Sep 17 00:00:00 2001 From: "Zed A. Shaw" Date: Tue, 22 Oct 2024 01:52:15 -0400 Subject: [PATCH] Tried out Google's AI response to the question of a C++ spatial hash and it kind of came close. This took some massaging but it could work. --- meson.build | 5 +++ scratchpad/collider.cpp | 70 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 scratchpad/collider.cpp diff --git a/meson.build b/meson.build index 89fb5aa..8e616fd 100644 --- a/meson.build +++ b/meson.build @@ -38,4 +38,9 @@ myecstest = executable('myecstest', [ ], dependencies: dependencies) +collider = executable('collider', [ + './scratchpad/collider.cpp' + ], + dependencies: dependencies) + test('tests', runtests) diff --git a/scratchpad/collider.cpp b/scratchpad/collider.cpp new file mode 100644 index 0000000..bd0d4f4 --- /dev/null +++ b/scratchpad/collider.cpp @@ -0,0 +1,70 @@ +#include +#include +#include + +struct Point { + int x, y; + + bool operator==(const Point& other) const { + return other.x == x && other.y == y; + } +}; + +struct Object { + Point position; + // Add other object data as needed +}; + +struct PointHash { + size_t operator()(const Point& p) const { + return std::hash()(p.x) ^ std::hash()(p.y); + } +}; + +class SpatialHashTable { +public: + SpatialHashTable() {} + + void insert(Object* obj) { + table[obj->position].push_back(obj); + } + + std::vector getNearbyObjects(Point position) { + std::vector result; + Point cell = position; + + // Check the current cell and its 8 neighbors + for (int x = cell.x - 1; x <= cell.x + 1; x++) { + for (int y = cell.y - 1; y <= cell.y + 1; y++) { + Point neighborCell = {x, y}; + auto it = table.find(neighborCell); + if (it != table.end()) { + result.insert(result.end(), it->second.begin(), it->second.end()); + } + } + } + + return result; + } + +private: + std::unordered_map, PointHash> table; +}; + +int main() { + SpatialHashTable hashTable; + Object obj1 = {{5, 5}}; + Object obj2 = {{15, 15}}; + Object bomb = {{25, 25}}; + + hashTable.insert(&obj1); + hashTable.insert(&obj2); + hashTable.insert(&bomb); + + std::vector nearby = hashTable.getNearbyObjects({24, 24}); + for (Object* obj : nearby) { + std::cout << obj->position.x << ", " << obj->position.y << std::endl; + } + + return 0; +}