#pragma once #include #include #include namespace easy2d { class SpatialHash : public ISpatialIndex { public: using CellKey = std::pair; struct CellKeyHash { size_t operator()(const CellKey& key) const { return std::hash()(key.first) ^ (std::hash()(key.second) << 1); } }; explicit SpatialHash(float cellSize = 64.0f); ~SpatialHash() override = default; void insert(Node* node, const Rect& bounds) override; void remove(Node* node) override; void update(Node* node, const Rect& newBounds) override; std::vector query(const Rect& area) const override; std::vector query(const Vec2& point) const override; std::vector> queryCollisions() const override; void clear() override; size_t size() const override; bool empty() const override; void rebuild() override; void setCellSize(float cellSize); float getCellSize() const { return cellSize_; } private: CellKey getCellKey(float x, float y) const; void getCellsForRect(const Rect& rect, std::vector& cells) const; void insertIntoCells(Node* node, const Rect& bounds); void removeFromCells(Node* node, const Rect& bounds); float cellSize_; std::unordered_map, CellKeyHash> grid_; std::unordered_map objectBounds_; size_t objectCount_ = 0; }; }