use double precision for positions of entities and players

Transform::pos, Hitbox::position and Player::position were floats. At
65k blocks the float step is 8 mm, at 1M it is 6-12 cm, at 30M it is
2 m. The physics moves a body by 3 cm or less per substep and pushes it
out of a wall by 10 cm or less: steps got rounded to the grid (the body
changed its speed, then stopped), the AABB of a body was off by a float
step and gave false collisions with the blocks around.

Positions of bodies, entity transforms, players, spawn points and the
skeleton position interpolation are worldvec3 now. Collisions are still
calculated in floats, but in the coordinates relative to the block the
body is in: the solver takes the origin, block lookups and hitboxes of
other bodies are shifted by it, the result is added back in doubles.
So the precision of the physics is the same anywhere in the world.

A calculated sensor is stored relative to the position of its entity.
Entities::getAllInside takes the corners in doubles,
Entities::hasBlockingInside takes the origin of the AABB.

The save format does not change: positions are written as numbers
(float64) as before, saves are compatible in both directions. Lua
functions keep their signatures, they only stop rounding to float.
This commit is contained in:
ostermine 2026-11-12 01:10:30 +03:00
parent ad69663b2e
commit cb39ed464a
33 changed files with 224 additions and 157 deletions

View file

@ -160,22 +160,26 @@ static glm::mat4 build_matrix(
void SkeletonConfig::update( void SkeletonConfig::update(
Skeleton& skeleton, Skeleton& skeleton,
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const worldvec3& position,
const glm::vec3& scale, const glm::vec3& scale,
const glm::ivec3& origin const glm::ivec3& origin
) const { ) const {
glm::vec3 pos = position; worldvec3 pos = position;
const auto& interpolation = skeleton.interpolation; const auto& interpolation = skeleton.interpolation;
if (interpolation.isEnabled() && interpolation.isRefreshed()) { if (interpolation.isEnabled() && interpolation.isRefreshed()) {
pos = interpolation.getCurrent(); pos = interpolation.getCurrent();
} }
pos = util::to_local(pos, origin);
glm::mat3 rot = rotation; glm::mat3 rot = rotation;
const auto& rotationInterpolation = skeleton.rotationInterpolation; const auto& rotationInterpolation = skeleton.rotationInterpolation;
if (rotationInterpolation.isEnabled() && rotationInterpolation.isRefreshed()) { if (rotationInterpolation.isEnabled() && rotationInterpolation.isRefreshed()) {
rot = glm::mat3_cast(rotationInterpolation.getCurrent()); rot = glm::mat3_cast(rotationInterpolation.getCurrent());
} }
update(0, skeleton, root.get(), build_matrix(rot, pos, scale)); update(
0,
skeleton,
root.get(),
build_matrix(rot, util::to_local(pos, origin), scale)
);
} }
static float max_component(const glm::vec3& v) { static float max_component(const glm::vec3& v) {
@ -254,7 +258,7 @@ void SkeletonConfig::render(
Skeleton& skeleton, Skeleton& skeleton,
ModelLightingMode lightingMode, ModelLightingMode lightingMode,
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const worldvec3& position,
const glm::vec3& scale, const glm::vec3& scale,
const glm::ivec3& origin, const glm::ivec3& origin,
bool translucent bool translucent
@ -282,7 +286,7 @@ void SkeletonConfig::updateBounds(
const Assets& assets, const Assets& assets,
Skeleton& skeleton, Skeleton& skeleton,
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const worldvec3& position,
const glm::vec3& scale, const glm::vec3& scale,
const glm::ivec3& origin const glm::ivec3& origin
) const { ) const {

View file

@ -104,7 +104,7 @@ namespace rigging {
glm::vec4 tint {1.0f, 1.0f, 1.0f, 1.0f}; glm::vec4 tint {1.0f, 1.0f, 1.0f, 1.0f};
std::vector<glm::vec4> boneTints; std::vector<glm::vec4> boneTints;
util::VecInterpolation<3, float> interpolation {false}; util::VecInterpolation<3, double> interpolation {false};
util::RotationInterpolation rotationInterpolation {false}; util::RotationInterpolation rotationInterpolation {false};
Skeleton(std::shared_ptr<const SkeletonConfig> config); Skeleton(std::shared_ptr<const SkeletonConfig> config);
@ -151,7 +151,7 @@ namespace rigging {
void update( void update(
Skeleton& skeleton, Skeleton& skeleton,
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const worldvec3& position,
const glm::vec3& scale, const glm::vec3& scale,
const glm::ivec3& origin const glm::ivec3& origin
) const; ) const;
@ -162,7 +162,7 @@ namespace rigging {
Skeleton& skeleton, Skeleton& skeleton,
ModelLightingMode lightingMode, ModelLightingMode lightingMode,
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const worldvec3& position,
const glm::vec3& scale, const glm::vec3& scale,
const glm::ivec3& origin, const glm::ivec3& origin,
bool translucent = false bool translucent = false
@ -172,7 +172,7 @@ namespace rigging {
const Assets& assets, const Assets& assets,
Skeleton& skeleton, Skeleton& skeleton,
const glm::mat3& rotation, const glm::mat3& rotation,
const glm::vec3& position, const worldvec3& position,
const glm::vec3& scale, const glm::vec3& scale,
const glm::ivec3& origin const glm::ivec3& origin
) const; ) const;

View file

@ -34,8 +34,8 @@ namespace dv {
return values; return values;
} }
template <int n> template <int n, typename T>
void get_vec(const dv::value& list, glm::vec<n, float>& vec) { void get_vec(const dv::value& list, glm::vec<n, T>& vec) {
for (size_t i = 0; i < n; i++) { for (size_t i = 0; i < n; i++) {
vec[i] = list[i].asNumber(); vec[i] = list[i].asNumber();
} }

View file

@ -292,7 +292,7 @@ std::shared_ptr<UINode> create_debug_panel(
if (allowDebugCheats) { if (allowDebugCheats) {
box->setTextConsumer([&player, ax](const std::wstring& text) { box->setTextConsumer([&player, ax](const std::wstring& text) {
try { try {
glm::vec3 position = player.getPosition(); worldvec3 position = player.getPosition();
position[ax] = std::stoi(text); position[ax] = std::stoi(text);
player.teleport(position); player.teleport(position);
} catch (std::exception& _) { } catch (std::exception& _) {

View file

@ -147,7 +147,11 @@ void EntitiesRenderer::renderDebug(
for (auto& sensor : rigidbody.sensors) { for (auto& sensor : rigidbody.sensors) {
if (sensor.type != SensorType::AABB) continue; if (sensor.type != SensorType::AABB) continue;
batch.box( batch.box(
util::to_local(sensor.calculated.aabb.center(), origin), util::to_local(
sensor.position +
worldvec3(sensor.calculated.aabb.center()),
origin
),
sensor.calculated.aabb.size(), sensor.calculated.aabb.size(),
glm::vec4(1.0f, 1.0f, 0.0f, 1.0f) glm::vec4(1.0f, 1.0f, 0.0f, 1.0f)
); );

View file

@ -59,7 +59,7 @@ LevelController::LevelController(
confirmed++; confirmed++;
continue; continue;
} }
glm::vec3 position = player->getPosition(); const auto& position = player->getPosition();
player->chunks->configure( player->chunks->configure(
std::floor(position.x), std::floor(position.z), 1 std::floor(position.x), std::floor(position.z), 1
); );
@ -82,7 +82,7 @@ void LevelController::update(float delta, bool pause) {
continue; continue;
} }
player->rotationInterpolation.updateTimer(delta); player->rotationInterpolation.updateTimer(delta);
glm::vec3 position = player->getPosition(); const auto& position = player->getPosition();
player->chunks->configure( player->chunks->configure(
glm::floor(position.x), glm::floor(position.x),
glm::floor(position.z), glm::floor(position.z),

View file

@ -54,7 +54,7 @@ CameraControl::CameraControl(
} }
void CameraControl::refreshPosition() { void CameraControl::refreshPosition() {
camera->position = player.getPosition() + offset; camera->position = player.getPosition() + worldvec3(offset);
} }
void CameraControl::refreshRotation() { void CameraControl::refreshRotation() {
@ -461,8 +461,7 @@ void PlayerController::processRightClick(
if (def.obstacle) { if (def.obstacle) {
const auto& hitboxes = def.getHitboxes(state); const auto& hitboxes = def.getHitboxes(state);
for (const AABB& blockAABB : hitboxes) { for (const AABB& blockAABB : hitboxes) {
if (level.entities->hasBlockingInside(blockAABB.translated(coord) if (level.entities->hasBlockingInside(coord, blockAABB)) {
)) {
return; return;
} }
} }

View file

@ -2,7 +2,7 @@
#include "maths/util.hpp" #include "maths/util.hpp"
static void check_valid(const glm::vec3& vec) { static void check_valid(const worldvec3& vec) {
if (util::is_nan_or_inf(vec)) { if (util::is_nan_or_inf(vec)) {
throw std::invalid_argument( throw std::invalid_argument(
"invalid vector: " + std::to_string(vec.x) + ", " + "invalid vector: " + std::to_string(vec.x) + ", " +
@ -21,14 +21,14 @@ static void check_valid(const glm::mat3& vec) {
static int l_get_pos(lua::State* L) { static int l_get_pos(lua::State* L) {
if (auto entity = get_entity(L, 1)) { if (auto entity = get_entity(L, 1)) {
return lua::pushvec3(L, entity->getTransform().pos); return lua::pushvec(L, entity->getTransform().pos);
} }
return 0; return 0;
} }
static int l_set_pos(lua::State* L) { static int l_set_pos(lua::State* L) {
if (auto entity = get_entity(L, 1)) { if (auto entity = get_entity(L, 1)) {
auto vec = lua::tovec3(L, 2); auto vec = lua::tovec<3, double>(L, 2);
check_valid(vec); check_valid(vec);
entity->getTransform().setPos(vec); entity->getTransform().setPos(vec);
entity->getRigidbody().hitbox.setPos(vec); entity->getRigidbody().hitbox.setPos(vec);

View file

@ -72,7 +72,7 @@ static int l_spawn(lua::State* L) {
auto level = controller->getLevel(); auto level = controller->getLevel();
auto defname = lua::require_string(L, 1); auto defname = lua::require_string(L, 1);
auto& def = content->entities.require(defname); auto& def = content->entities.require(defname);
auto pos = lua::tovec3(L, 2); auto pos = lua::tovec<3, double>(L, 2);
dv::value args = nullptr; dv::value args = nullptr;
if (lua::gettop(L) > 2) { if (lua::gettop(L) > 2) {
args = lua::tovalue(L, 3); args = lua::tovalue(L, 3);
@ -133,9 +133,9 @@ static int l_set_skeleton(lua::State* L) {
} }
static int l_get_all_in_box(lua::State* L) { static int l_get_all_in_box(lua::State* L) {
auto pos = lua::tovec<3>(L, 1); auto pos = lua::tovec<3, double>(L, 1);
auto size = lua::tovec<3>(L, 2); auto size = lua::tovec<3, double>(L, 2);
auto found = level->entities->getAllInside(AABB(pos, pos + size)); auto found = level->entities->getAllInside(pos, pos + size);
lua::createtable(L, found.size(), 0); lua::createtable(L, found.size(), 0);
for (size_t i = 0; i < found.size(); i++) { for (size_t i = 0; i < found.size(); i++) {
lua::pushinteger(L, found[i]->getUID()); lua::pushinteger(L, found[i]->getUID());
@ -145,7 +145,7 @@ static int l_get_all_in_box(lua::State* L) {
} }
static int l_get_all_in_radius(lua::State* L) { static int l_get_all_in_radius(lua::State* L) {
auto pos = lua::tovec<3>(L, 1); auto pos = lua::tovec<3, double>(L, 1);
auto radius = lua::tonumber(L, 2); auto radius = lua::tonumber(L, 2);
auto found = level->entities->getAllInRadius(pos, radius); auto found = level->entities->getAllInRadius(pos, radius);
lua::createtable(L, found.size(), 0); lua::createtable(L, found.size(), 0);

View file

@ -47,7 +47,7 @@ static int l_set_pos(lua::State* L) {
auto x = lua::tonumber(L, 2); auto x = lua::tonumber(L, 2);
auto y = lua::tonumber(L, 3); auto y = lua::tonumber(L, 3);
auto z = lua::tonumber(L, 4); auto z = lua::tonumber(L, 4);
player->teleport(glm::vec3(x, y, z)); player->teleport(worldvec3(x, y, z));
return 0; return 0;
} }
@ -256,7 +256,7 @@ static int l_set_spawnpoint(lua::State* L) {
auto x = lua::tonumber(L, 2); auto x = lua::tonumber(L, 2);
auto y = lua::tonumber(L, 3); auto y = lua::tonumber(L, 3);
auto z = lua::tonumber(L, 4); auto z = lua::tonumber(L, 4);
player->setSpawnPoint(glm::vec3(x, y, z)); player->setSpawnPoint(worldvec3(x, y, z));
} }
return 0; return 0;
} }
@ -359,7 +359,7 @@ static int l_set_suspended(lua::State* L) {
static int l_get_all_in_radius(lua::State* L) { static int l_get_all_in_radius(lua::State* L) {
auto& level = require_level(); auto& level = require_level();
auto center = lua::tovec3(L, 1); auto center = lua::tovec<3, double>(L, 1);
auto radius = static_cast<float>(lua::tonumber(L, 2)); auto radius = static_cast<float>(lua::tonumber(L, 2));
auto players = level.players->getAllInRadius(center, radius); auto players = level.players->getAllInRadius(center, radius);
@ -383,7 +383,7 @@ static int l_get_all(lua::State* L) {
static int l_get_nearest(lua::State* L) { static int l_get_nearest(lua::State* L) {
auto& level = require_level(); auto& level = require_level();
auto position = lua::tovec3(L, 1); auto position = lua::tovec<3, double>(L, 1);
if (auto player = level.players->getNearest(position)) { if (auto player = level.players->getNearest(position)) {
lua::pushinteger(L, player->getId()); lua::pushinteger(L, player->getId());
return 1; return 1;

View file

@ -100,8 +100,8 @@ namespace lua {
return 1; return 1;
} }
template <int n> template <int n, typename T = float>
inline int pushvec_stack(lua::State* L, const glm::vec<n, float>& vec) { inline int pushvec_stack(lua::State* L, const glm::vec<n, T>& vec) {
for (int i = 0; i < n; i++) { for (int i = 0; i < n; i++) {
pushnumber(L, vec[i]); pushnumber(L, vec[i]);
} }

View file

@ -43,7 +43,7 @@ Entity* Entities::get(entityid_t id) {
entityid_t Entities::spawn( entityid_t Entities::spawn(
const EntityDef& def, const EntityDef& def,
glm::vec3 position, worldvec3 position,
dv::value args, dv::value args,
dv::value saved, dv::value saved,
entityid_t uid entityid_t uid
@ -272,17 +272,22 @@ void Entities::updateSensors(
sensor.nextEntered.clear(); sensor.nextEntered.clear();
switch (sensor.type) { switch (sensor.type) {
case SensorType::AABB: case SensorType::AABB: {
glm::mat4 matrix = tsf.combined;
matrix[3] = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
sensor.calculated.aabb = sensor.params.aabb; sensor.calculated.aabb = sensor.params.aabb;
sensor.calculated.aabb.transform(tsf.combined); sensor.calculated.aabb.transform(matrix);
sensor.position = tsf.displayPos;
break; break;
}
case SensorType::RADIUS: case SensorType::RADIUS:
sensor.calculated.radial = glm::vec4( sensor.calculated.radial = glm::vec4(
body.hitbox.position.x, 0.0f,
body.hitbox.position.y, 0.0f,
body.hitbox.position.z, 0.0f,
sensor.params.radial.w * sensor.params.radial.w sensor.params.radial.w * sensor.params.radial.w
); );
sensor.position = body.hitbox.position;
break; break;
} }
sensors.push_back(&sensor); sensors.push_back(&sensor);
@ -409,10 +414,10 @@ void Entities::update(float delta) {
} }
} }
bool Entities::hasBlockingInside(AABB aabb) { bool Entities::hasBlockingInside(const worldvec3& origin, AABB aabb) {
constexpr float eps = 0.05f; constexpr float eps = 0.05f;
for (const auto& [uid, entity] : entities) { for (const auto& [uid, entity] : entities) {
AABB bodyAABB(entity->getRigidbody().hitbox.getAABB()); AABB bodyAABB(entity->getRigidbody().hitbox.getAABB(origin));
bodyAABB.scale(glm::vec3(1.0f - eps)); bodyAABB.scale(glm::vec3(1.0f - eps));
if (entity->getID().def.blocking && aabb.intersects(bodyAABB)) { if (entity->getID().def.blocking && aabb.intersects(bodyAABB)) {
return true; return true;
@ -421,17 +426,24 @@ bool Entities::hasBlockingInside(AABB aabb) {
return false; return false;
} }
std::vector<Entity*> Entities::getAllInside(AABB aabb) { std::vector<Entity*> Entities::getAllInside(
const worldvec3& a, const worldvec3& b
) {
const worldvec3 min = glm::min(a, b);
const worldvec3 max = glm::max(a, b);
std::vector<Entity*> collected; std::vector<Entity*> collected;
for (const auto& [uid, entity] : entities) { for (const auto& [uid, entity] : entities) {
if (!entity->getID().destroyFlag && aabb.contains(entity->getTransform().pos)) { const auto& pos = entity->getTransform().pos;
if (!entity->getID().destroyFlag &&
glm::all(glm::greaterThanEqual(pos, min)) &&
glm::all(glm::lessThan(pos, max))) {
collected.push_back(entity.get()); collected.push_back(entity.get());
} }
} }
return collected; return collected;
} }
std::vector<Entity*> Entities::getAllInRadius(glm::vec3 center, float radius) { std::vector<Entity*> Entities::getAllInRadius(worldvec3 center, float radius) {
std::vector<Entity*> collected; std::vector<Entity*> collected;
for (const auto& [uid, entity] : entities) { for (const auto& [uid, entity] : entities) {
if (glm::distance2(entity->getTransform().pos, center) <= radius * radius) { if (glm::distance2(entity->getTransform().pos, center) <= radius * radius) {

View file

@ -52,7 +52,7 @@ public:
entityid_t spawn( entityid_t spawn(
const EntityDef& def, const EntityDef& def,
glm::vec3 position, worldvec3 position,
dv::value args = nullptr, dv::value args = nullptr,
dv::value saved = nullptr, dv::value saved = nullptr,
entityid_t uid = 0 entityid_t uid = 0
@ -94,9 +94,9 @@ public:
void loadEntity(const dv::value& map); void loadEntity(const dv::value& map);
void loadEntity(const dv::value& map, Entity& entity); void loadEntity(const dv::value& map, Entity& entity);
void onSave(const Entity& entity); void onSave(const Entity& entity);
bool hasBlockingInside(AABB aabb); bool hasBlockingInside(const worldvec3& origin, AABB aabb);
std::vector<Entity*> getAllInside(AABB aabb); std::vector<Entity*> getAllInside(const worldvec3& a, const worldvec3& b);
std::vector<Entity*> getAllInRadius(glm::vec3 center, float radius); std::vector<Entity*> getAllInRadius(worldvec3 center, float radius);
void despawn(entityid_t id); void despawn(entityid_t id);
void despawn(const std::vector<Entity*>& entities); void despawn(const std::vector<Entity*>& entities);
dv::value serialize(const std::vector<Entity*>& entities); dv::value serialize(const std::vector<Entity*>& entities);

View file

@ -26,13 +26,13 @@ Entity::Entity(
Entity::~Entity() = default; Entity::~Entity() = default;
void Entity::setInterpolatedPosition(const glm::vec3& position) { void Entity::setInterpolatedPosition(const worldvec3& position) {
if (skeleton) { if (skeleton) {
skeleton->interpolation.refresh(position); skeleton->interpolation.refresh(position);
} }
} }
glm::vec3 Entity::getInterpolatedPosition() const { worldvec3 Entity::getInterpolatedPosition() const {
if (skeleton) { if (skeleton) {
const auto& interpolation = skeleton->interpolation; const auto& interpolation = skeleton->interpolation;
if (interpolation.isEnabled() && interpolation.isRefreshed()) { if (interpolation.isEnabled() && interpolation.isRefreshed()) {

View file

@ -104,9 +104,9 @@ public:
void setPlayer(int64_t player); void setPlayer(int64_t player);
void setInterpolatedPosition(const glm::vec3& position); void setInterpolatedPosition(const worldvec3& position);
glm::vec3 getInterpolatedPosition() const; worldvec3 getInterpolatedPosition() const;
void setInterpolatedRotation(const glm::quat& rotation); void setInterpolatedRotation(const glm::quat& rotation);

View file

@ -31,7 +31,7 @@ Player::Player(
Level& level, Level& level,
int64_t id, int64_t id,
const std::wstring& name, const std::wstring& name,
glm::vec3 position, worldvec3 position,
float speed, float speed,
std::shared_ptr<Inventory> inv, std::shared_ptr<Inventory> inv,
entityid_t eid entityid_t eid
@ -121,7 +121,7 @@ void Player::postUpdate() {
} }
} }
void Player::teleport(glm::vec3 position) { void Player::teleport(worldvec3 position) {
this->position = position; this->position = position;
if (auto entity = level.entities->get(eid)) { if (auto entity = level.entities->get(eid)) {
@ -138,7 +138,7 @@ void Player::attemptToChooseSpawnpoint() {
int minHeight = generatorDef.playerMinSpawnHeight; int minHeight = generatorDef.playerMinSpawnHeight;
int maxHeight = generatorDef.playerMaxSpawnHeight; int maxHeight = generatorDef.playerMaxSpawnHeight;
glm::vec3 newpos {0.0f, random.randFloat() * (maxHeight - minHeight + 1) + minHeight, 0.0f}; worldvec3 newpos {0.0f, random.randFloat() * (maxHeight - minHeight + 1) + minHeight, 0.0f};
double angle = random.randDouble() * glm::two_pi<double>(); double angle = random.randDouble() * glm::two_pi<double>();
double radius = glm::sqrt(random.randDouble()); double radius = glm::sqrt(random.randDouble());
newpos.x += glm::cos(angle) * generatorDef.playerSpawnRadius * radius; newpos.x += glm::cos(angle) * generatorDef.playerSpawnRadius * radius;
@ -154,7 +154,7 @@ void Player::attemptToChooseSpawnpoint() {
headvox == nullptr || headvox->id != 0) { headvox == nullptr || headvox->id != 0) {
return; return;
} }
spawnpoint = newpos + glm::vec3(0.5f, 0.0f, 0.5f); spawnpoint = newpos + worldvec3(0.5, 0.0, 0.5);
teleport(spawnpoint); teleport(spawnpoint);
} }
@ -259,11 +259,11 @@ const std::shared_ptr<Inventory>& Player::getInventory() const {
return inventory; return inventory;
} }
void Player::setSpawnPoint(glm::vec3 spawnpoint) { void Player::setSpawnPoint(worldvec3 spawnpoint) {
this->spawnpoint = spawnpoint; this->spawnpoint = spawnpoint;
} }
glm::vec3 Player::getSpawnPoint() const { worldvec3 Player::getSpawnPoint() const {
return spawnpoint; return spawnpoint;
} }
@ -324,7 +324,7 @@ void Player::deserialize(const dv::value& src) {
dv::get_vec(rotarr, rotation); dv::get_vec(rotarr, rotation);
const auto& sparr = src["spawnpoint"]; const auto& sparr = src["spawnpoint"];
setSpawnPoint(glm::vec3( setSpawnPoint(worldvec3(
sparr[0].asNumber(), sparr[1].asNumber(), sparr[2].asNumber())); sparr[0].asNumber(), sparr[1].asNumber(), sparr[2].asNumber()));
src.at("interaction-distance").get(interactionDistance); src.at("interaction-distance").get(interactionDistance);

View file

@ -50,8 +50,8 @@ class Player : public Serializable {
int chosenSlot; int chosenSlot;
int hotbarSize; int hotbarSize;
glm::vec3 position; worldvec3 position;
glm::vec3 spawnpoint {std::nanf(""), std::nanf(""), std::nanf("")}; worldvec3 spawnpoint {std::nanf(""), std::nanf(""), std::nanf("")};
std::shared_ptr<Inventory> inventory; std::shared_ptr<Inventory> inventory;
bool suspended = false; bool suspended = false;
bool flight = false; bool flight = false;
@ -81,14 +81,14 @@ public:
Level& level, Level& level,
int64_t id, int64_t id,
const std::wstring& name, const std::wstring& name,
glm::vec3 position, worldvec3 position,
float speed, float speed,
std::shared_ptr<Inventory> inv, std::shared_ptr<Inventory> inv,
entityid_t eid entityid_t eid
); );
~Player(); ~Player();
void teleport(glm::vec3 position); void teleport(worldvec3 position);
void updateEntity(); void updateEntity();
void updateSelectedEntity(); void updateSelectedEntity();
void postUpdate(); void postUpdate();
@ -134,7 +134,7 @@ public:
const std::shared_ptr<Inventory>& getInventory() const; const std::shared_ptr<Inventory>& getInventory() const;
const glm::vec3& getPosition() const { const worldvec3& getPosition() const {
return position; return position;
} }
@ -142,8 +142,8 @@ public:
Hitbox* getHitbox() const; Hitbox* getHitbox() const;
void setSpawnPoint(glm::vec3 point); void setSpawnPoint(worldvec3 point);
glm::vec3 getSpawnPoint() const; worldvec3 getSpawnPoint() const;
glm::vec3 getRotation(bool interpolated=false) const; glm::vec3 getRotation(bool interpolated=false) const;
void setRotation(const glm::vec3& rotation); void setRotation(const glm::vec3& rotation);

View file

@ -25,7 +25,7 @@ Player* Players::get(int64_t id) const {
} }
std::vector<Player*> Players::getAllInRadius( std::vector<Player*> Players::getAllInRadius(
const glm::vec3& center, float radius const worldvec3& center, float radius
) const { ) const {
std::vector<Player*> foundPlayers; std::vector<Player*> foundPlayers;
@ -48,9 +48,9 @@ std::vector<Player*> Players::getAll() const {
return allPlayers; return allPlayers;
} }
Player* Players::getNearest(const glm::vec3& position) const { Player* Players::getNearest(const worldvec3& position) const {
Player* nearest = nullptr; Player* nearest = nullptr;
float nearestDist2 = std::numeric_limits<float>::max(); double nearestDist2 = std::numeric_limits<double>::max();
for (const auto& pair : players) { for (const auto& pair : players) {
auto player = pair.second.get(); auto player = pair.second.get();
if (player->isSuspended()) { if (player->isSuspended()) {

View file

@ -36,9 +36,11 @@ public:
void remove(int64_t id); void remove(int64_t id);
std::vector<Player*> getAllInRadius(const glm::vec3& center, float radius) const; std::vector<Player*> getAllInRadius(
const worldvec3& center, float radius
) const;
std::vector<Player*> getAll() const; std::vector<Player*> getAll() const;
Player* getNearest(const glm::vec3& position) const; Player* getNearest(const worldvec3& position) const;
dv::value serialize() const override; dv::value serialize() const override;

View file

@ -11,7 +11,7 @@ static debug::Logger logger("entity-transform");
void Transform::refresh() { void Transform::refresh() {
combined = glm::mat4(1.0f); combined = glm::mat4(1.0f);
combined = glm::translate(combined, pos); combined = glm::translate(combined, glm::vec3(pos));
combined = combined * glm::mat4(rot); combined = combined * glm::mat4(rot);
combined = glm::scale(combined, size); combined = glm::scale(combined, size);
displayPos = pos; displayPos = pos;
@ -37,7 +37,7 @@ void Transform::deserialize(const dv::value& root) {
dv::get_mat(root, "rot", rot); dv::get_mat(root, "rot", rot);
} }
bool Transform::checkValue(const glm::vec3& vector, std::string_view name) { bool Transform::checkValue(const worldvec3& vector, std::string_view name) {
if (util::is_nan_or_inf(vector)) { if (util::is_nan_or_inf(vector)) {
auto message = "invalid vector attempted set to " + std::string(name) + auto message = "invalid vector attempted set to " + std::string(name) +
" : " + std::to_string(vector.x) + ", " + " : " + std::to_string(vector.x) + ", " +

View file

@ -2,6 +2,8 @@
#define GLM_ENABLE_EXPERIMENTAL #define GLM_ENABLE_EXPERIMENTAL
#include "typedefs.hpp"
#include <stdexcept> #include <stdexcept>
#include <glm/vec3.hpp> #include <glm/vec3.hpp>
#include <glm/mat4x4.hpp> #include <glm/mat4x4.hpp>
@ -10,13 +12,13 @@
struct Transform { struct Transform {
static inline constexpr float EPSILON = 1e-7f; static inline constexpr float EPSILON = 1e-7f;
glm::vec3 pos; worldvec3 pos;
glm::vec3 size; glm::vec3 size;
glm::mat3 rot; glm::mat3 rot;
glm::mat4 combined; glm::mat4 combined;
bool dirty = true; bool dirty = true;
glm::vec3 displayPos {}; worldvec3 displayPos {};
glm::vec3 displaySize {}; glm::vec3 displaySize {};
dv::value serialize() const; dv::value serialize() const;
@ -33,7 +35,7 @@ struct Transform {
} }
inline void setSize(const glm::vec3& v) { inline void setSize(const glm::vec3& v) {
if (!checkValue(v, "size")) { if (!checkValue(worldvec3(v), "size")) {
return; return;
} }
if (glm::distance2(displaySize, v) >= EPSILON) { if (glm::distance2(displaySize, v) >= EPSILON) {
@ -42,7 +44,7 @@ struct Transform {
size = v; size = v;
} }
inline void setPos(const glm::vec3& v) { inline void setPos(const worldvec3& v) {
if (!checkValue(v, "position")) { if (!checkValue(v, "position")) {
return; return;
} }
@ -52,6 +54,6 @@ struct Transform {
pos = v; pos = v;
} }
static bool checkValue(const glm::vec3& v, std::string_view name); static bool checkValue(const worldvec3& v, std::string_view name);
static bool checkValue(const glm::mat3& v, std::string_view name); static bool checkValue(const glm::mat3& v, std::string_view name);
}; };

View file

@ -29,10 +29,10 @@ private:
glm::vec3 gravity; glm::vec3 gravity;
SpatialGrid grid; SpatialGrid grid;
std::vector<std::vector<Hitbox*>> nearbySolids; std::vector<std::vector<Hitbox*>> nearbySolids;
std::vector<glm::vec3> nearbyOrigins; std::vector<worldvec3> nearbyOrigins;
std::vector<float> nearbyBudgets; std::vector<float> nearbyBudgets;
std::vector<glm::vec3> nearbyReaches; std::vector<glm::vec3> nearbyReaches;
std::vector<glm::vec3> solidOrigins; std::vector<worldvec3> solidOrigins;
std::vector<float> solidBudgets; std::vector<float> solidBudgets;
std::vector<uint> candidates; std::vector<uint> candidates;
std::vector<size_t> solidStamps; std::vector<size_t> solidStamps;

View file

@ -1,7 +1,7 @@
#include "Hitbox.hpp" #include "Hitbox.hpp"
Hitbox::Hitbox( Hitbox::Hitbox(
entityid_t entity, BodyType type, glm::vec3 position, glm::vec3 halfsize entityid_t entity, BodyType type, worldvec3 position, glm::vec3 halfsize
) )
: entity(entity), : entity(entity),
type(type), type(type),

View file

@ -19,7 +19,7 @@ enum class SensorType {
union SensorParams { union SensorParams {
AABB aabb; AABB aabb;
glm::vec4 radial; // x,y,z calculated entity coords + w - radius glm::vec4 radial; // w - radius
constexpr SensorParams() : aabb() { constexpr SensorParams() : aabb() {
} }
@ -38,6 +38,7 @@ struct Sensor {
std::set<entityid_t> nextEntered; std::set<entityid_t> nextEntered;
sensorcallback enterCallback; sensorcallback enterCallback;
sensorcallback exitCallback; sensorcallback exitCallback;
worldvec3 position {};
}; };
enum class BodyType { enum class BodyType {
@ -53,7 +54,7 @@ VC_ENUM_END
struct Hitbox { struct Hitbox {
entityid_t entity; entityid_t entity;
BodyType type; BodyType type;
glm::vec3 position; worldvec3 position;
glm::vec3 halfsize; glm::vec3 halfsize;
glm::vec3 velocity; glm::vec3 velocity;
glm::vec3 scale {1.0f, 1.0f, 1.0f}; glm::vec3 scale {1.0f, 1.0f, 1.0f};
@ -70,7 +71,7 @@ struct Hitbox {
std::string groundMaterial; std::string groundMaterial;
glm::vec3 groundVelocity {}; glm::vec3 groundVelocity {};
glm::vec3 prevPosition {}; worldvec3 prevPosition {};
glm::vec3 prevVelocity {}; glm::vec3 prevVelocity {};
bool prevGrounded = false; bool prevGrounded = false;
float substepTime = 0.0f; float substepTime = 0.0f;
@ -80,18 +81,19 @@ struct Hitbox {
static inline constexpr float TELEPORT_THRESOLD_SQR = 0.5f; static inline constexpr float TELEPORT_THRESOLD_SQR = 0.5f;
Hitbox( Hitbox(
entityid_t entity, BodyType type, glm::vec3 position, glm::vec3 halfsize entityid_t entity, BodyType type, worldvec3 position, glm::vec3 halfsize
); );
AABB getAABB() const { AABB getAABB(const worldvec3& origin) const {
return AABB(position - halfsize, position + halfsize); glm::vec3 pos(position - origin);
return AABB(pos - halfsize, pos + halfsize);
} }
glm::vec3 getHalfSize() const { glm::vec3 getHalfSize() const {
return halfsize * scale; return halfsize * scale;
} }
void setPos(const glm::vec3& vec) { void setPos(const worldvec3& vec) {
position = vec; position = vec;
if (glm::distance2(position, prevPosition) >= TELEPORT_THRESOLD_SQR) { if (glm::distance2(position, prevPosition) >= TELEPORT_THRESOLD_SQR) {
prevPosition = vec; prevPosition = vec;

View file

@ -2,9 +2,9 @@
#include <algorithm> #include <algorithm>
inline constexpr float GRID_CELL_SIZE = 4.0f; inline constexpr double GRID_CELL_SIZE = 4.0;
inline constexpr float GRID_PADDING = 0.01f; inline constexpr double GRID_PADDING = 0.01;
inline constexpr float GRID_MAX_COORD = 1e9f; inline constexpr double GRID_MAX_COORD = 1e9;
inline constexpr int GRID_MAX_CELLS = 64; inline constexpr int GRID_MAX_CELLS = 64;
void SpatialGrid::clear() { void SpatialGrid::clear() {
@ -13,7 +13,7 @@ void SpatialGrid::clear() {
} }
void SpatialGrid::insert( void SpatialGrid::insert(
uint id, const glm::vec3& center, const glm::vec3& extents uint id, const worldvec3& center, const glm::vec3& extents
) { ) {
glm::ivec2 min, max; glm::ivec2 min, max;
if (!calcRange(center, extents, min, max)) { if (!calcRange(center, extents, min, max)) {
@ -37,20 +37,20 @@ uint64_t SpatialGrid::calcKey(int x, int z) {
} }
bool SpatialGrid::calcRange( bool SpatialGrid::calcRange(
const glm::vec3& center, const worldvec3& center,
const glm::vec3& extents, const glm::vec3& extents,
glm::ivec2& min, glm::ivec2& min,
glm::ivec2& max glm::ivec2& max
) { ) {
glm::vec2 c(center.x, center.z); glm::dvec2 c(center.x, center.z);
glm::vec2 e = glm::vec2(extents.x, extents.z) + GRID_PADDING; glm::dvec2 e = glm::dvec2(extents.x, extents.z) + GRID_PADDING;
glm::vec2 a = glm::floor((c - e) / GRID_CELL_SIZE); glm::dvec2 a = glm::floor((c - e) / GRID_CELL_SIZE);
glm::vec2 b = glm::floor((c + e) / GRID_CELL_SIZE); glm::dvec2 b = glm::floor((c + e) / GRID_CELL_SIZE);
if (!(glm::abs(a.x) < GRID_MAX_COORD && glm::abs(a.y) < GRID_MAX_COORD && if (!(glm::abs(a.x) < GRID_MAX_COORD && glm::abs(a.y) < GRID_MAX_COORD &&
glm::abs(b.x) < GRID_MAX_COORD && glm::abs(b.y) < GRID_MAX_COORD)) { glm::abs(b.x) < GRID_MAX_COORD && glm::abs(b.y) < GRID_MAX_COORD)) {
return false; return false;
} }
if ((b.x - a.x + 1.0f) * (b.y - a.y + 1.0f) > GRID_MAX_CELLS) { if ((b.x - a.x + 1.0) * (b.y - a.y + 1.0) > GRID_MAX_CELLS) {
return false; return false;
} }
min = glm::ivec2(a); min = glm::ivec2(a);

View file

@ -10,13 +10,13 @@ class SpatialGrid {
public: public:
void clear(); void clear();
void insert(uint id, const glm::vec3& center, const glm::vec3& extents); void insert(uint id, const worldvec3& center, const glm::vec3& extents);
void build(); void build();
template <typename Func> template <typename Func>
bool query( bool query(
const glm::vec3& center, const glm::vec3& extents, const Func& func const worldvec3& center, const glm::vec3& extents, const Func& func
) const { ) const {
glm::ivec2 min, max; glm::ivec2 min, max;
if (!calcRange(center, extents, min, max)) { if (!calcRange(center, extents, min, max)) {
@ -46,7 +46,7 @@ private:
static uint64_t calcKey(int x, int z); static uint64_t calcKey(int x, int z);
static bool calcRange( static bool calcRange(
const glm::vec3& center, const worldvec3& center,
const glm::vec3& extents, const glm::vec3& extents,
glm::ivec2& min, glm::ivec2& min,
glm::ivec2& max glm::ivec2& max

View file

@ -2,6 +2,7 @@
#include "scheduling.hpp" #include "scheduling.hpp"
#include "maths/aabb.hpp" #include "maths/aabb.hpp"
#include "maths/util.hpp"
#include "voxels/GlobalChunks.hpp" #include "voxels/GlobalChunks.hpp"
#define GLM_ENABLE_EXPERIMENTAL #define GLM_ENABLE_EXPERIMENTAL
@ -28,6 +29,7 @@ static glm::vec3 calc_collsion_velocity_result(
static float calc_step_height( static float calc_step_height(
const GlobalChunks& chunks, const GlobalChunks& chunks,
const glm::vec3& pos, const glm::vec3& pos,
const glm::ivec3& origin,
const glm::vec3& half, const glm::vec3& half,
float stepHeight float stepHeight
) { ) {
@ -41,7 +43,9 @@ static float calc_step_height(
float x = (pos.x - half.x) + ix; float x = (pos.x - half.x) + ix;
for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) {
float z = (pos.z - half.z) + iz; float z = (pos.z - half.z) + iz;
if (chunks.isObstacleAt(x, pos.y + half.y + stepHeight, z, aabb)) { if (chunks.isObstacleAt(
origin, x, pos.y + half.y + stepHeight, z, aabb
)) {
return 0.0f; return 0.0f;
} }
} }
@ -54,18 +58,20 @@ static float calc_step_height(
template <int nx, int ny, int nz, int sign> template <int nx, int ny, int nz, int sign>
static void calc_collision( static void calc_collision(
Hitbox& hitbox, Hitbox& hitbox,
glm::vec3& pos,
const glm::ivec3& origin,
const GlobalChunks& chunks, const GlobalChunks& chunks,
const std::vector<Hitbox*>& solidHitboxes, const std::vector<Hitbox*>& solidHitboxes,
const glm::vec3& half, const glm::vec3& half,
float stepHeight, float stepHeight,
uint wakeSubstep uint wakeSubstep
) { ) {
auto& pos = hitbox.position;
auto& vel = hitbox.velocity; auto& vel = hitbox.velocity;
glm::vec3 offset(0.0f, stepHeight + E, 0.0f); glm::vec3 offset(0.0f, stepHeight + E, 0.0f);
for (auto box : solidHitboxes) { for (auto box : solidHitboxes) {
if (glm::distance2(box->position, pos) < E) { glm::vec3 boxpos = util::to_local(box->position, origin);
if (glm::distance2(boxpos, pos) < E) {
continue; continue;
} }
auto boxhalf = box->getHalfSize(); auto boxhalf = box->getHalfSize();
@ -77,12 +83,13 @@ static void calc_collision(
aabb = aabb + offset; aabb = aabb + offset;
aabb.b.y -= stepHeight + E * 2; aabb.b.y -= stepHeight + E * 2;
if ((box->position[nx] - pos[nx]) * sign <= 0.0f || !box->getAABB().intersects(aabb)) { if ((boxpos[nx] - pos[nx]) * sign <= 0.0f ||
!box->getAABB(origin).intersects(aabb)) {
continue; continue;
} }
float newnegx = box->position[nx] - boxhalf[nx] - half[nx]; float newnegx = boxpos[nx] - boxhalf[nx] - half[nx];
float newposx = box->position[nx] + boxhalf[nx] + half[nx]; float newposx = boxpos[nx] + boxhalf[nx] + half[nx];
float newx; float newx;
if ((glm::abs(newnegx - pos[nx]) - glm::abs(newposx - pos[nx]))*sign < 0.0f) { if ((glm::abs(newnegx - pos[nx]) - glm::abs(newposx - pos[nx]))*sign < 0.0f) {
newx = sign > 0 ? newnegx : newposx; newx = sign > 0 ? newnegx : newposx;
@ -116,7 +123,9 @@ static void calc_collision(
aabb = aabb + offset; aabb = aabb + offset;
aabb.b.y -= stepHeight + E * 2; aabb.b.y -= stepHeight + E * 2;
if (const auto obstacle = chunks.isObstacleAt(coord.x, coord.y, coord.z, aabb)) { if (const auto obstacle = chunks.isObstacleAt(
origin, coord.x, coord.y, coord.z, aabb
)) {
float newx = std::floor(coord[nx]) - half[nx] * sign + float newx = std::floor(coord[nx]) - half[nx] * sign +
(sign > 0 ? obstacle->min() : obstacle->max())[nx]; (sign > 0 ? obstacle->min() : obstacle->max())[nx];
if ((pos[nx] - newx) * sign > 0.0f && glm::abs(pos[nx] - newx) < MAX_FIX) { if ((pos[nx] - newx) * sign > 0.0f && glm::abs(pos[nx] - newx) < MAX_FIX) {
@ -130,15 +139,19 @@ static void calc_collision(
} }
static bool calc_collision_neg_y( static bool calc_collision_neg_y(
Hitbox& hitbox, const glm::vec3& half, const CollisionContext& ctx Hitbox& hitbox,
glm::vec3& pos,
const glm::ivec3& origin,
const glm::vec3& half,
const CollisionContext& ctx
) { ) {
const auto& chunks = ctx.chunks; const auto& chunks = ctx.chunks;
const auto& solids = ctx.solids; const auto& solids = ctx.solids;
auto& pos = hitbox.position;
auto& vel = hitbox.velocity; auto& vel = hitbox.velocity;
for (auto box : solids) { for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) { glm::vec3 boxpos = util::to_local(box->position, origin);
if (glm::distance2(boxpos, pos) < E) {
continue; continue;
} }
auto aabb = AABB(pos - half, pos + half); auto aabb = AABB(pos - half, pos + half);
@ -148,8 +161,8 @@ static bool calc_collision_neg_y(
aabb.scale(scale); aabb.scale(scale);
auto boxhalf = box->getHalfSize(); auto boxhalf = box->getHalfSize();
if (box->position.y < pos.y && box->getAABB().intersects(aabb)) { if (boxpos.y < pos.y && box->getAABB(origin).intersects(aabb)) {
float newy = box->position.y + boxhalf.y + half.y; float newy = boxpos.y + boxhalf.y + half.y;
if (pos.y < newy && glm::abs(pos.y - newy) < boxhalf.y) { if (pos.y < newy && glm::abs(pos.y - newy) < boxhalf.y) {
pos.y = newy; pos.y = newy;
} }
@ -158,7 +171,8 @@ static bool calc_collision_neg_y(
auto velB = calc_collsion_velocity_result(*box, hitbox); auto velB = calc_collsion_velocity_result(*box, hitbox);
float boxdt = box->substepTime > 0.0f ? box->substepTime : ctx.dt; float boxdt = box->substepTime > 0.0f ? box->substepTime : ctx.dt;
hitbox.groundVelocity = (box->position - box->prevPosition) / boxdt; hitbox.groundVelocity =
glm::vec3(box->position - box->prevPosition) / boxdt;
if (vel.y < hitbox.groundVelocity.y) { if (vel.y < hitbox.groundVelocity.y) {
vel.y = velA.y; vel.y = velA.y;
push_body(*box, 1, velB.y, ctx.wakeSubstep); push_body(*box, 1, velB.y, ctx.wakeSubstep);
@ -185,8 +199,9 @@ static bool calc_collision_neg_y(
scale.z = 1.0f - E * 4.0f; scale.z = 1.0f - E * 4.0f;
aabb.scale(scale); aabb.scale(scale);
if (const auto obstacle = if (const auto obstacle = chunks.isObstacleAt(
chunks.isObstacleAt(coord.x, coord.y, coord.z, aabb)) { origin, coord.x, coord.y, coord.z, aabb
)) {
float newy = std::floor(coord.y) + half.y + obstacle->max().y; float newy = std::floor(coord.y) + half.y + obstacle->max().y;
if (newy >= pos.y) { if (newy >= pos.y) {
@ -203,6 +218,8 @@ static bool calc_collision_neg_y(
static void calc_collisions( static void calc_collisions(
Hitbox& hitbox, Hitbox& hitbox,
glm::vec3& pos,
const glm::ivec3& origin,
const glm::vec3& half, const glm::vec3& half,
float stepHeight, float stepHeight,
const CollisionContext& ctx const CollisionContext& ctx
@ -210,32 +227,31 @@ static void calc_collisions(
const auto& chunks = ctx.chunks; const auto& chunks = ctx.chunks;
const auto& solids = ctx.solids; const auto& solids = ctx.solids;
uint wakeSubstep = ctx.wakeSubstep; uint wakeSubstep = ctx.wakeSubstep;
auto& pos = hitbox.position;
auto& vel = hitbox.velocity; auto& vel = hitbox.velocity;
stepHeight = calc_step_height(chunks, pos, half, stepHeight); stepHeight = calc_step_height(chunks, pos, origin, half, stepHeight);
auto prevPos = pos; auto prevPos = pos;
calc_collision<0, 1, 2, -1>( calc_collision<0, 1, 2, -1>(
hitbox, chunks, solids, half, stepHeight, wakeSubstep hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep
); );
calc_collision<0, 1, 2, 1>( calc_collision<0, 1, 2, 1>(
hitbox, chunks, solids, half, stepHeight, wakeSubstep hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep
); );
float xpos = pos.x; float xpos = pos.x;
pos.x = prevPos.x; pos.x = prevPos.x;
calc_collision<2, 1, 0, -1>( calc_collision<2, 1, 0, -1>(
hitbox, chunks, solids, half, stepHeight, wakeSubstep hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep
); );
calc_collision<2, 1, 0, 1>( calc_collision<2, 1, 0, 1>(
hitbox, chunks, solids, half, stepHeight, wakeSubstep hitbox, pos, origin, chunks, solids, half, stepHeight, wakeSubstep
); );
pos.x = xpos; pos.x = xpos;
if (calc_collision_neg_y(hitbox, half, ctx)) { if (calc_collision_neg_y(hitbox, pos, origin, half, ctx)) {
hitbox.grounded = true; hitbox.grounded = true;
} }
@ -249,7 +265,7 @@ static void calc_collisions(
for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) {
float z = (pos.z - half.z + E) + iz; float z = (pos.z - half.z + E) + iz;
float y = (pos.y + half.y + E) - E; float y = (pos.y + half.y + E) - E;
if (auto aabb = chunks.isObstacleAt(x, y, z, boxAABB)) { if (auto aabb = chunks.isObstacleAt(origin, x, y, z, boxAABB)) {
float bottom = std::floor(y) + aabb->min().y; float bottom = std::floor(y) + aabb->min().y;
float newy = bottom - half.y - E; float newy = bottom - half.y - E;
if (pos.y >= newy && pos.y - half.y < bottom) { if (pos.y >= newy && pos.y - half.y < bottom) {
@ -261,12 +277,13 @@ static void calc_collisions(
} }
} }
for (auto box : solids) { for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) { glm::vec3 boxpos = util::to_local(box->position, origin);
if (glm::distance2(boxpos, pos) < E) {
continue; continue;
} }
auto boxhalf = box->getHalfSize(); auto boxhalf = box->getHalfSize();
if (box->position.y > pos.y && box->getAABB().intersects(boxAABB)) { if (boxpos.y > pos.y && box->getAABB(origin).intersects(boxAABB)) {
float newy = box->position.y - boxhalf.y - half.y; float newy = boxpos.y - boxhalf.y - half.y;
if (pos.y > newy && glm::abs(pos.y - newy) < 0.5f) { if (pos.y > newy && glm::abs(pos.y - newy) < 0.5f) {
pos.y = newy; pos.y = newy;
} }
@ -290,7 +307,7 @@ static void calc_collisions(
for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) {
float z = (pos.z - half.z) + iz; float z = (pos.z - half.z) + iz;
float y = (pos.y - half.y + E) + E; float y = (pos.y - half.y + E) + E;
if (auto aabb = chunks.isObstacleAt(x, y, z, boxAABB)) { if (auto aabb = chunks.isObstacleAt(origin, x, y, z, boxAABB)) {
if (vel.y < 0.0f) { if (vel.y < 0.0f) {
vel.y = 0.0f; vel.y = 0.0f;
} }
@ -303,13 +320,14 @@ static void calc_collisions(
} }
} }
for (auto box : solids) { for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) { glm::vec3 boxpos = util::to_local(box->position, origin);
if (glm::distance2(boxpos, pos) < E) {
continue; continue;
} }
auto boxhalf = box->getHalfSize(); auto boxhalf = box->getHalfSize();
if (box->getAABB().intersects(boxAABB)) { if (box->getAABB(origin).intersects(boxAABB)) {
vel.y = 0.0f; vel.y = 0.0f;
float newy = box->position.y + boxhalf.y + half.y; float newy = boxpos.y + boxhalf.y + half.y;
if (std::abs(newy - pos.y) <= stepHeight + E * 4) { if (std::abs(newy - pos.y) <= stepHeight + E * 4) {
pos.y = newy; pos.y = newy;
} }
@ -318,12 +336,16 @@ static void calc_collisions(
} }
} }
void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) { static void calc_local_substep(
Hitbox& hitbox,
glm::vec3& pos,
const glm::ivec3& origin,
const CollisionContext& ctx
) {
const auto& chunks = ctx.chunks; const auto& chunks = ctx.chunks;
const auto& solids = ctx.solids; const auto& solids = ctx.solids;
const auto& gravity = ctx.gravity; const auto& gravity = ctx.gravity;
float dt = ctx.dt; float dt = ctx.dt;
auto& pos = hitbox.position;
auto& vel = hitbox.velocity; auto& vel = hitbox.velocity;
auto initpos = pos; auto initpos = pos;
@ -333,6 +355,8 @@ void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) {
if (hitbox.type == BodyType::DYNAMIC) { if (hitbox.type == BodyType::DYNAMIC) {
calc_collisions( calc_collisions(
hitbox, hitbox,
pos,
origin,
half, half,
(hitbox.prevGrounded && gravityScale > 0.0f) ? hitbox.stepHeight (hitbox.prevGrounded && gravityScale > 0.0f) ? hitbox.stepHeight
: 0.0f, : 0.0f,
@ -361,17 +385,18 @@ void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) {
float x = (pos.x - half.x + E) + ix; float x = (pos.x - half.x + E) + ix;
for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++){ for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++){
float z = (pos.z - half.z + E) + iz; float z = (pos.z - half.z + E) + iz;
if (chunks.isObstacleAt(x, y, z, boxAABB)){ if (chunks.isObstacleAt(origin, x, y, z, boxAABB)) {
hitbox.grounded = true; hitbox.grounded = true;
break; break;
} }
} }
} }
for (auto box : solids) { for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) { glm::vec3 boxpos = util::to_local(box->position, origin);
if (glm::distance2(boxpos, pos) < E) {
continue; continue;
} }
if (box->position.y < pos.y && box->getAABB().intersects(boxAABB)) { if (boxpos.y < pos.y && box->getAABB(origin).intersects(boxAABB)) {
hitbox.grounded = true; hitbox.grounded = true;
break; break;
} }
@ -383,3 +408,10 @@ void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) {
} }
hitbox.grounded = true; hitbox.grounded = true;
} }
void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) {
const glm::ivec3 origin = glm::floor(hitbox.position);
glm::vec3 pos = util::to_local(hitbox.position, origin);
calc_local_substep(hitbox, pos, origin, ctx);
hitbox.position = worldvec3(origin) + worldvec3(pos);
}

View file

@ -13,8 +13,9 @@ namespace physics {
) { ) {
float n = static_cast<float>(substeps); float n = static_cast<float>(substeps);
auto accel = gravity * box.gravityScale; auto accel = gravity * box.gravityScale;
box.position += box.velocity * (dt * n) + box.position += worldvec3(
accel * (dt * dt * n * (n + 2.0f) * 0.5f); box.velocity * (dt * n) + accel * (dt * dt * n * (n + 2.0f) * 0.5f)
);
box.velocity += accel * (dt * n); box.velocity += accel * (dt * n);
} }

View file

@ -3,8 +3,6 @@
void physics::update_sensors( void physics::update_sensors(
Hitbox& hitbox, const std::vector<Sensor*>& sensors Hitbox& hitbox, const std::vector<Sensor*>& sensors
) { ) {
auto aabb = hitbox.getAABB();
for (size_t i = 0; i < sensors.size(); i++) { for (size_t i = 0; i < sensors.size(); i++) {
auto& sensor = *sensors[i]; auto& sensor = *sensors[i];
if (sensor.entity == hitbox.entity) { if (sensor.entity == hitbox.entity) {
@ -13,12 +11,12 @@ void physics::update_sensors(
bool triggered = false; bool triggered = false;
switch (sensor.type) { switch (sensor.type) {
case SensorType::AABB: case SensorType::AABB:
triggered = aabb.intersects(sensor.calculated.aabb); triggered = hitbox.getAABB(sensor.position)
.intersects(sensor.calculated.aabb);
break; break;
case SensorType::RADIUS: case SensorType::RADIUS:
triggered = glm::distance2( triggered = glm::distance2(hitbox.position, sensor.position) <
hitbox.position, glm::vec3(sensor.calculated.radial)) sensor.calculated.radial.w;
< sensor.calculated.radial.w;
break; break;
} }
if (!triggered) { if (!triggered) {

View file

@ -191,7 +191,7 @@ void GlobalChunks::save(Chunk* chunk) {
return; return;
} }
AABB aabb = chunk->getAABB(); AABB aabb = chunk->getAABB();
auto entities = level.entities->getAllInside(aabb); auto entities = level.entities->getAllInside(aabb.a, aabb.b);
auto root = dv::object(); auto root = dv::object();
root["data"] = level.entities->serialize(entities); root["data"] = level.entities->serialize(entities);
if (!entities.empty()) { if (!entities.empty()) {
@ -214,6 +214,8 @@ void GlobalChunks::putChunk(std::shared_ptr<Chunk> chunk) {
chunksMap[keyfrom(chunk->x, chunk->z)] = std::move(chunk); chunksMap[keyfrom(chunk->x, chunk->z)] = std::move(chunk);
} }
std::optional<AABB> GlobalChunks::isObstacleAt(float x, float y, float z, const AABB& aabb) const { std::optional<AABB> GlobalChunks::isObstacleAt(
return blocks_agent::is_obstacle_at(*this, x, y, z, aabb); const glm::ivec3& origin, float x, float y, float z, const AABB& aabb
) const {
return blocks_agent::is_obstacle_at(*this, origin, x, y, z, aabb);
} }

View file

@ -58,7 +58,9 @@ public:
void putChunk(std::shared_ptr<Chunk> chunk); void putChunk(std::shared_ptr<Chunk> chunk);
std::optional<AABB> isObstacleAt(float x, float y, float z, const AABB& aabb) const; std::optional<AABB> isObstacleAt(
const glm::ivec3& origin, float x, float y, float z, const AABB& aabb
) const;
inline Chunk* getChunk(int cx, int cz) const { inline Chunk* getChunk(int cx, int cz) const {
const auto& found = chunksMap.find(keyfrom(cx, cz)); const auto& found = chunksMap.find(keyfrom(cx, cz));

View file

@ -488,14 +488,20 @@ void get_voxels(
template <class Storage> template <class Storage>
inline std::optional<AABB> is_obstacle_at( inline std::optional<AABB> is_obstacle_at(
const Storage& chunks, float x, float y, float z, const AABB& aabb const Storage& chunks,
const glm::ivec3& origin,
float x,
float y,
float z,
const AABB& aabb
) { ) {
int ix = std::floor(x); int ix = std::floor(x);
int iy = std::floor(y); int iy = std::floor(y);
int iz = std::floor(z); int iz = std::floor(z);
voxel* v = get(chunks, ix, iy, iz); glm::ivec3 point = origin + glm::ivec3(ix, iy, iz);
voxel* v = get(chunks, point.x, point.y, point.z);
if (v == nullptr) { if (v == nullptr) {
if (iy >= CHUNK_H) { if (point.y >= CHUNK_H) {
return std::nullopt; return std::nullopt;
} else { } else {
return AABB(); return AABB();
@ -508,10 +514,9 @@ inline std::optional<AABB> is_obstacle_at(
glm::ivec3 offset {}; glm::ivec3 offset {};
blockstate state = v->state; blockstate state = v->state;
if (state.segment) { if (state.segment) {
glm::ivec3 point(ix, iy, iz); auto blockOrigin = seek_origin(chunks, point, def, state);
auto origin = seek_origin(chunks, point, def, state); offset = blockOrigin - point;
offset = origin - point; state = hitbox_state(chunks, blockOrigin, state);
state = hitbox_state(chunks, origin, state);
} }
const auto& boxes = def.getHitboxes(state); const auto& boxes = def.getHitboxes(state);
@ -525,7 +530,9 @@ inline std::optional<AABB> is_obstacle_at(
template <class Storage> template <class Storage>
inline std::optional<AABB> is_obstacle_at(const Storage& chunks, float x, float y, float z) { inline std::optional<AABB> is_obstacle_at(const Storage& chunks, float x, float y, float z) {
return is_obstacle_at(chunks, x, y, z, AABB({x, y, z}, {x + 1, y + 1, z + 1})); return is_obstacle_at(
chunks, {}, x, y, z, AABB({x, y, z}, {x + 1, y + 1, z + 1})
);
} }
/// @brief Check block grounding /// @brief Check block grounding

View file

@ -64,7 +64,7 @@ Level::Level(
chunks->setOnUnload([this](Chunk& chunk) { chunks->setOnUnload([this](Chunk& chunk) {
events->trigger(LevelEventType::CHUNK_UNLOAD, &chunk); events->trigger(LevelEventType::CHUNK_UNLOAD, &chunk);
AABB aabb = chunk.getAABB(); AABB aabb = chunk.getAABB();
entities->despawn(entities->getAllInside(aabb)); entities->despawn(entities->getAllInside(aabb.a, aabb.b));
}); });
inventories = std::make_unique<Inventories>(*this); inventories = std::make_unique<Inventories>(*this);
} }