You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.8 KiB
67 lines
1.8 KiB
2 weeks ago
|
#include "spatialmap.hpp"
|
||
3 months ago
|
#include <fmt/core.h>
|
||
|
|
||
|
using namespace fmt;
|
||
3 months ago
|
|
||
|
using DinkyECS::Entity;
|
||
|
|
||
2 weeks ago
|
void SpatialMap::insert(Point pos, Entity ent) {
|
||
3 months ago
|
table[pos] = ent;
|
||
|
}
|
||
|
|
||
2 weeks ago
|
void SpatialMap::remove(Point pos) {
|
||
3 months ago
|
table.erase(pos);
|
||
|
}
|
||
|
|
||
2 weeks ago
|
void SpatialMap::move(Point from, Point to, Entity ent) {
|
||
3 months ago
|
remove(from);
|
||
|
insert(to, ent);
|
||
|
}
|
||
|
|
||
2 weeks ago
|
bool SpatialMap::occupied(Point at) const {
|
||
3 months ago
|
return table.contains(at);
|
||
3 months ago
|
}
|
||
|
|
||
2 weeks ago
|
Entity SpatialMap::get(Point at) const {
|
||
2 months ago
|
return table.at(at);
|
||
|
}
|
||
|
|
||
3 months ago
|
/*
|
||
|
* Avoid doing work by using the dy,dx and confirming that
|
||
|
* at.x or at.y is > 0. If either is 0 then there can't be
|
||
|
* a neighbor since that's out of bounds.
|
||
|
*/
|
||
3 months ago
|
inline void find_neighbor(const PointEntityMap &table, EntityList &result, Point at, int dy, int dx) {
|
||
3 months ago
|
// don't bother checking for cells out of bounds
|
||
|
if((dx < 0 && at.x <= 0) || (dy < 0 && at.y <= 0)) {
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
Point cell = {at.x + dx, at.y + dy};
|
||
|
|
||
|
auto it = table.find(cell);
|
||
3 months ago
|
if (it != table.end()) {
|
||
|
result.insert(result.end(), it->second);
|
||
|
}
|
||
|
}
|
||
|
|
||
2 weeks ago
|
FoundEntities SpatialMap::neighbors(Point cell, bool diag) const {
|
||
3 months ago
|
EntityList result;
|
||
3 months ago
|
|
||
3 months ago
|
// just unroll the loop since we only check four directions
|
||
|
// this also solves the problem that it was detecting that the cell was automatically included as a "neighbor" but it's not
|
||
3 months ago
|
find_neighbor(table, result, cell, 0, 1); // north
|
||
|
find_neighbor(table, result, cell, 0, -1); // south
|
||
|
find_neighbor(table, result, cell, 1, 0); // east
|
||
|
find_neighbor(table, result, cell, -1, 0); // west
|
||
3 months ago
|
|
||
|
if(diag) {
|
||
3 months ago
|
find_neighbor(table, result, cell, 1, -1); // south east
|
||
|
find_neighbor(table, result, cell, -1, -1); // south west
|
||
|
find_neighbor(table, result, cell, 1, 1); // north east
|
||
|
find_neighbor(table, result, cell, -1, 1); // north west
|
||
3 months ago
|
}
|
||
|
|
||
3 months ago
|
return {!result.empty(), result};
|
||
3 months ago
|
}
|