This commit is contained in:
Andrew Oster 2026-11-12 10:34:21 +03:00 • committed by GitHub
commit ebb181c60d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
85 changed files with 833 additions and 445 deletions

94
dev/tests/far_coords.lua Normal file
View file

@ -0,0 +1,94 @@
local util = require "core:tests_util"
util.create_demo_world("core:default")
app.set_setting("chunks.load-distance", 3)
app.set_setting("chunks.load-speed", 1)
local pid = player.create("Xerxes")
local function is_loaded(x, z)
return block.get(math.floor(x), 0, math.floor(z)) ~= -1
end
local function wait_chunk(x, z)
player.set_spawnpoint(pid, x, 100, z)
player.set_pos(pid, x, 100, z)
app.sleep_until(function () return is_loaded(x, z) end)
end
local function spawn_drop(x, y, z)
return entities.spawn("base:drop", {x, y, z}, {base__drop={
id=item.index("base:stone.item"),
count=1
}})
end
local function move_body(coord)
local x, z = coord + 8.5, -coord - 8.5
wait_chunk(x - 5, z)
local entity = spawn_drop(x, 50.5, z)
for _ = 1, 20 do
entity.rigidbody:set_vel({3, 0, -2})
app.tick()
end
local pos = entity.transform:get_pos()
entity:despawn()
return {pos[1] - x, pos[2] - 50.5, pos[3] - z}
end
local moved = move_body(0)
debug.print(moved)
assert(moved[1] > 1.0, "body didn't move")
for _, coord in ipairs({1000000, 30000000}) do
local x, y, z = coord + 0.3, 100.6, -coord - 0.7
player.set_pos(pid, x, y, z)
util.check_vec3({x, y, z}, {player.get_pos(pid)}, "player.get_pos", 1e-6)
player.set_spawnpoint(pid, x, y, z)
util.check_vec3(
{x, y, z}, {player.get_spawnpoint(pid)}, "player.get_spawnpoint", 1e-6
)
wait_chunk(x, z)
local entity = spawn_drop(x, y, z)
util.check_vec3({x, y, z}, entity.transform:get_pos(), "spawn pos", 1e-6)
entity.transform:set_pos({x + 0.25, y, z - 0.25})
util.check_vec3(
{x + 0.25, y, z - 0.25}, entity.transform:get_pos(), "set_pos", 1e-6
)
entity:despawn()
local ray = world.raycast({
start = {x, 8, z},
dir = {0, -1, 0},
distance = 10,
})
assert(ray, "ray didn't hit")
util.check_vec3({x, 1, z}, ray.endpoint, "ray.endpoint")
util.check_vec3(
{math.floor(x), 0, math.floor(z)}, ray.iendpoint, "ray.iendpoint"
)
util.check_float(7, ray.length, "ray.length")
local far_moved = move_body(coord)
debug.print(far_moved)
util.check_vec3(moved, far_moved, "body displacement", 1e-3)
end
local x, z = 30000000.3, -30000000.7
player.set_spawnpoint(pid, x, 100.6, z)
player.set_pos(pid, x, 100.6, z)
app.close_world(true)
app.open_world("demo")
local px, _, pz = player.get_pos(pid)
util.check_float(x, px, "saved x", 1e-6)
util.check_float(z, pz, "saved z", 1e-6)
util.check_vec3(
{x, 100.6, z}, {player.get_spawnpoint(pid)}, "saved spawnpoint", 1e-6
)
app.close_world(false)
app.delete_world("demo")

View file

@ -55,3 +55,9 @@ for i = 0, 63 do
end end
gfx.posteffects.set_array(slot, "u_arrayName", Bytearray_as_string(buffer)) gfx.posteffects.set_array(slot, "u_arrayName", Bytearray_as_string(buffer))
``` ```
## Coordinates in shaders
World-space values available in shaders (`u_cameraPos`, `u_view`, `u_inverseView`, positions of vertices and models) are relative to the rendering origin, not to the world origin. The rendering origin is an integer point near the camera: its X and Z are multiples of 1024 blocks, Y is 0. This keeps `float` precise far from the world origin.
Directions, distances and positions relative to the camera do not depend on the rendering origin. Neither does an effect bound to the blocks grid or repeating with a period that divides 1024.

View file

@ -55,3 +55,9 @@ for i = 0, 63 do
end end
gfx.posteffects.set_array(slot, "u_имяМассива", Bytearray_as_string(buffer)) gfx.posteffects.set_array(slot, "u_имяМассива", Bytearray_as_string(buffer))
``` ```
## Координаты в шейдерах
Значения в мировом пространстве, доступные в шейдерах (`u_cameraPos`, `u_view`, `u_inverseView`, позиции вершин и моделей), заданы относительно начала координат рендера, а не начала координат мира. Начало координат рендера - целочисленная точка рядом с камерой: X и Z кратны 1024 блокам, Y равен 0. Так `float` сохраняет точность вдали от начала координат мира.
Направления, расстояния и позиции относительно камеры от начала координат рендера не зависят. Не зависит и эффект, привязанный к сетке блоков или повторяющийся с периодом, на который делится 1024.

View file

@ -11,14 +11,17 @@ layout (location = 3) in vec4 v_normal;
#include <sky> #include <sky>
uniform float u_dayTime; uniform float u_dayTime;
uniform vec2 u_waveOffset;
out vec4 a_torchLight; out vec4 a_torchLight;
void main() { void main() {
a_modelpos = u_model * vec4(v_position, 1.0f); a_modelpos = u_model * vec4(v_position, 1.0f);
a_modelpos.xz += u_waveOffset;
a_modelpos.x += sin(u_timer * 0.05 + a_modelpos.z * 0.002) * 1.5; a_modelpos.x += sin(u_timer * 0.05 + a_modelpos.z * 0.002) * 1.5;
a_modelpos.z += sin(u_timer * 0.2 + a_modelpos.x * 0.002) * 1.5; a_modelpos.z += sin(u_timer * 0.2 + a_modelpos.x * 0.002) * 1.5;
a_modelpos.y += sin(u_timer * 0.1 + (a_modelpos.x + a_modelpos.z) * 0.001) * 2.0; a_modelpos.y += sin(u_timer * 0.1 + (a_modelpos.x + a_modelpos.z) * 0.001) * 2.0;
a_modelpos.xz -= u_waveOffset;
vec3 pos3d = a_modelpos.xyz - u_cameraPos; vec3 pos3d = a_modelpos.xyz - u_cameraPos;

View file

@ -8,6 +8,7 @@
#include "data/dv_util.hpp" #include "data/dv_util.hpp"
#include "graphics/commons/Model.hpp" #include "graphics/commons/Model.hpp"
#include "graphics/render/ModelBatch.hpp" #include "graphics/render/ModelBatch.hpp"
#include "maths/util.hpp"
using namespace rigging; using namespace rigging;
@ -159,10 +160,11 @@ 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 { ) 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();
@ -172,7 +174,12 @@ void SkeletonConfig::update(
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) {
@ -251,20 +258,27 @@ 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,
bool translucent bool translucent
) const { ) const {
if (skeleton.config->root == nullptr) { if (skeleton.config->root == nullptr) {
return; return;
} }
update(skeleton, rotation, position, scale); update(skeleton, rotation, position, scale, origin);
if (!skeleton.visible) { if (!skeleton.visible) {
return; return;
} }
processModels( processModels(
assets, skeleton, position, scale, &batch, lightingMode, translucent assets,
skeleton,
util::to_local(position, origin),
scale,
&batch,
lightingMode,
translucent
); );
} }
@ -272,17 +286,18 @@ 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 { ) const {
if (skeleton.config->root == nullptr) { if (skeleton.config->root == nullptr) {
return; return;
} }
update(skeleton, rotation, position, scale); update(skeleton, rotation, position, scale, origin);
processModels( processModels(
assets, assets,
skeleton, skeleton,
position, util::to_local(position, origin),
scale, scale,
nullptr, nullptr,
ModelLightingMode::SOLID, ModelLightingMode::SOLID,

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,8 +151,9 @@ 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; ) const;
void render( void render(
@ -161,8 +162,9 @@ 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,
bool translucent = false bool translucent = false
) const; ) const;
@ -170,8 +172,9 @@ 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; ) const;
Skeleton instance() const { Skeleton instance() const {

View file

@ -342,6 +342,7 @@ void ALSpeaker::update(const Channel* channel) {
if (source == 0) return; if (source == 0) return;
float gain = this->volume * channel->getVolume(); float gain = this->volume * channel->getVolume();
AL_CHECK(alSourcef(source, AL_GAIN, gain)); AL_CHECK(alSourcef(source, AL_GAIN, gain));
refreshPosition();
if (!paused) { if (!paused) {
if (isPaused() && !channel->isPaused()) { if (isPaused() && !channel->isPaused()) {
@ -451,12 +452,18 @@ void ALSpeaker::setTime(duration_t time) {
AL_CHECK(alSourcef(source, AL_SEC_OFFSET, static_cast<float>(time))); AL_CHECK(alSourcef(source, AL_SEC_OFFSET, static_cast<float>(time)));
} }
void ALSpeaker::setPosition(glm::vec3 pos) { void ALSpeaker::refreshPosition() {
glm::vec3 pos(relative ? position : position - al->listenerPosition);
AL_CHECK(alSource3f(source, AL_POSITION, pos.x, pos.y, pos.z)); AL_CHECK(alSource3f(source, AL_POSITION, pos.x, pos.y, pos.z));
} }
glm::vec3 ALSpeaker::getPosition() const { void ALSpeaker::setPosition(worldvec3 pos) {
return AL::getSource3f(source, AL_POSITION); position = pos;
refreshPosition();
}
worldvec3 ALSpeaker::getPosition() const {
return position;
} }
void ALSpeaker::setVelocity(glm::vec3 vel) { void ALSpeaker::setVelocity(glm::vec3 vel) {
@ -468,9 +475,11 @@ glm::vec3 ALSpeaker::getVelocity() const {
} }
void ALSpeaker::setRelative(bool relative) { void ALSpeaker::setRelative(bool relative) {
this->relative = relative;
AL_CHECK( AL_CHECK(
alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE) alSourcei(source, AL_SOURCE_RELATIVE, relative ? AL_TRUE : AL_FALSE)
); );
refreshPosition();
} }
bool ALSpeaker::isRelative() const { bool ALSpeaker::isRelative() const {
@ -782,11 +791,12 @@ void ALAudio::freeBuffer(uint buffer) {
} }
void ALAudio::setListener( void ALAudio::setListener(
glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up worldvec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up
) { ) {
ALfloat listenerOri[] = {at.x, at.y, at.z, up.x, up.y, up.z}; ALfloat listenerOri[] = {at.x, at.y, at.z, up.x, up.y, up.z};
AL_CHECK(alListener3f(AL_POSITION, position.x, position.y, position.z)); listenerPosition = position;
AL_CHECK(alListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f));
AL_CHECK(alListener3f(AL_VELOCITY, velocity.x, velocity.y, velocity.z)); AL_CHECK(alListener3f(AL_VELOCITY, velocity.x, velocity.y, velocity.z));
AL_CHECK(alListenerfv(AL_ORIENTATION, listenerOri)); AL_CHECK(alListenerfv(AL_ORIENTATION, listenerOri));
AL_CHECK(alListenerf(AL_GAIN, get_channel(0)->getVolume())); AL_CHECK(alListenerf(AL_GAIN, get_channel(0)->getVolume()));

View file

@ -121,6 +121,10 @@ namespace audio {
int priority; int priority;
int channel; int channel;
float volume = 0.0f; float volume = 0.0f;
worldvec3 position {};
bool relative = false;
void refreshPosition();
public: public:
ALStream* stream = nullptr; ALStream* stream = nullptr;
bool manuallyStopped = true; bool manuallyStopped = true;
@ -153,8 +157,8 @@ namespace audio {
duration_t getDuration() const override; duration_t getDuration() const override;
void setTime(duration_t time) override; void setTime(duration_t time) override;
void setPosition(glm::vec3 pos) override; void setPosition(worldvec3 pos) override;
glm::vec3 getPosition() const override; worldvec3 getPosition() const override;
void setVelocity(glm::vec3 vel) override; void setVelocity(glm::vec3 vel) override;
glm::vec3 getVelocity() const override; glm::vec3 getVelocity() const override;
@ -188,6 +192,7 @@ namespace audio {
std::array<uint, 1> filters; std::array<uint, 1> filters;
bool useEffects; bool useEffects;
worldvec3 listenerPosition {};
ALAudio( ALAudio(
ALCdevice* device, ALCdevice* device,
@ -221,7 +226,7 @@ namespace audio {
std::vector<std::string> getInputDeviceNames() override; std::vector<std::string> getInputDeviceNames() override;
void setListener( void setListener(
glm::vec3 position, worldvec3 position,
glm::vec3 velocity, glm::vec3 velocity,
glm::vec3 lookAt, glm::vec3 lookAt,
glm::vec3 up glm::vec3 up

View file

@ -97,7 +97,7 @@ namespace audio {
} }
void setListener( void setListener(
glm::vec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up worldvec3 position, glm::vec3 velocity, glm::vec3 at, glm::vec3 up
) override { ) override {
} }

View file

@ -352,7 +352,7 @@ void audio::set_input_device(const std::string& deviceName) {
} }
void audio::set_listener( void audio::set_listener(
glm::vec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up worldvec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up
) { ) {
backend->setListener(position, velocity, lookAt, up); backend->setListener(position, velocity, lookAt, up);
} }
@ -380,7 +380,7 @@ void remove_lower_priority_speaker(int priority) {
speakerid_t audio::play( speakerid_t audio::play(
Sound* sound, Sound* sound,
glm::vec3 position, worldvec3 position,
bool relative, bool relative,
float volume, float volume,
float pitch, float pitch,
@ -419,7 +419,7 @@ speakerid_t audio::play(
speakerid_t audio::play( speakerid_t audio::play(
const std::shared_ptr<Stream>& stream, const std::shared_ptr<Stream>& stream,
glm::vec3 position, worldvec3 position,
bool relative, bool relative,
float volume, float volume,
float pitch, float pitch,
@ -451,7 +451,7 @@ speakerid_t audio::play(
speakerid_t audio::play_stream( speakerid_t audio::play_stream(
const io::path& file, const io::path& file,
glm::vec3 position, worldvec3 position,
bool relative, bool relative,
float volume, float volume,
float pitch, float pitch,

View file

@ -331,11 +331,11 @@ namespace audio {
/// @brief Set speaker 3D position in the world /// @brief Set speaker 3D position in the world
/// @param pos new position /// @param pos new position
virtual void setPosition(glm::vec3 pos) = 0; virtual void setPosition(worldvec3 pos) = 0;
/// @brief Get speaker 3D position in the world /// @brief Get speaker 3D position in the world
/// @return position /// @return position
virtual glm::vec3 getPosition() const = 0; virtual worldvec3 getPosition() const = 0;
/// @brief Set speaker movement velocity used for Doppler effect /// @brief Set speaker movement velocity used for Doppler effect
/// @param vel velocity vector /// @param vel velocity vector
@ -391,7 +391,7 @@ namespace audio {
uint bitsPerSample uint bitsPerSample
) = 0; ) = 0;
virtual void setListener( virtual void setListener(
glm::vec3 position, worldvec3 position,
glm::vec3 velocity, glm::vec3 velocity,
glm::vec3 lookAt, glm::vec3 lookAt,
glm::vec3 up glm::vec3 up
@ -482,7 +482,7 @@ namespace audio {
/// @param lookAt point the listener look at /// @param lookAt point the listener look at
/// @param up camera up vector /// @param up camera up vector
void set_listener( void set_listener(
glm::vec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up worldvec3 position, glm::vec3 velocity, glm::vec3 lookAt, glm::vec3 up
); );
/// @brief Play 3D sound in the world /// @brief Play 3D sound in the world
@ -498,7 +498,7 @@ namespace audio {
/// @return speaker id or 0 /// @return speaker id or 0
speakerid_t play( speakerid_t play(
Sound* sound, Sound* sound,
glm::vec3 position, worldvec3 position,
bool relative, bool relative,
float volume, float volume,
float pitch, float pitch,
@ -518,7 +518,7 @@ namespace audio {
/// @return speaker id or 0 /// @return speaker id or 0
speakerid_t play( speakerid_t play(
const std::shared_ptr<Stream>& stream, const std::shared_ptr<Stream>& stream,
glm::vec3 position, worldvec3 position,
bool relative, bool relative,
float volume, float volume,
float pitch, float pitch,
@ -537,7 +537,7 @@ namespace audio {
/// @return speaker id or 0 /// @return speaker id or 0
speakerid_t play_stream( speakerid_t play_stream(
const io::path& file, const io::path& file,
glm::vec3 position, worldvec3 position,
bool relative, bool relative,
float volume, float volume,
float pitch, float pitch,

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

@ -74,7 +74,7 @@ LevelFrontend::LevelFrontend(
} }
auto sound = assets.get<audio::Sound>(material->stepsSound); auto sound = assets.get<audio::Sound>(material->stepsSound);
glm::vec3 pos {}; worldvec3 pos {};
auto soundsCamera = currentPlayer.currentCamera.get(); auto soundsCamera = currentPlayer.currentCamera.get();
if (currentPlayer.isCurrentCameraBuiltin()) { if (currentPlayer.isCurrentCameraBuiltin()) {
soundsCamera = currentPlayer.fpCamera.get(); soundsCamera = currentPlayer.fpCamera.get();
@ -117,7 +117,7 @@ LevelFrontend::LevelFrontend(
} }
audio::play( audio::play(
sound, sound,
glm::vec3(pos.x, pos.y, pos.z) + 0.5f, worldvec3(pos.x, pos.y, pos.z) + 0.5,
false, false,
1.0f, 1.0f,
1.0f + (rand() % 6 - 3) * 0.05f, 1.0f + (rand() % 6 - 3) * 0.05f,

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

@ -109,7 +109,7 @@ void PostProcessing::configureEffect(
shader.uniform1i("u_noise", TARGET_SSAO); // used in SSAO pass shader.uniform1i("u_noise", TARGET_SSAO); // used in SSAO pass
shader.uniform1i("u_ssao", TARGET_SSAO); shader.uniform1i("u_ssao", TARGET_SSAO);
shader.uniform2i("u_screenSize", viewport / downsample); shader.uniform2i("u_screenSize", viewport / downsample);
shader.uniform3f("u_cameraPos", camera.position); shader.uniform3f("u_cameraPos", camera.getLocalPosition());
shader.uniform1f("u_timer", timer); shader.uniform1f("u_timer", timer);
shader.uniformMatrix("u_projection", camera.getProjection()); shader.uniformMatrix("u_projection", camera.getProjection());
const auto view = camera.getView(); const auto view = camera.getView();

View file

@ -95,7 +95,17 @@ void Shadows::setQuality(int quality) {
this->quality = quality; this->quality = quality;
} }
void Shadows::setup(Shader& shader, const Weather& weather) { static glm::mat4 calc_shadows_matrix(
const Camera& shadowCamera, const glm::ivec3& origin
) {
return glm::translate(
shadowCamera.getProjView(), glm::vec3(origin - shadowCamera.getOrigin())
);
}
void Shadows::setup(
Shader& shader, const Camera& camera, const Weather& weather
) {
if (!shadows) { if (!shadows) {
return; return;
} }
@ -106,8 +116,13 @@ void Shadows::setup(Shader& shader, const Weather& weather) {
glm::mod((worldInfo.daytime + 0.5f) * 2.0f, 1.0f) * 2.0f - 1.0f glm::mod((worldInfo.daytime + 0.5f) * 2.0f, 1.0f) * 2.0f - 1.0f
)); ));
shader.uniform1i("u_screen", 0); shader.uniform1i("u_screen", 0);
shader.uniformMatrix("u_shadowsMatrix[0]", shadowCamera.getProjView()); const glm::ivec3 origin = camera.getOrigin();
shader.uniformMatrix("u_shadowsMatrix[1]", wideShadowCamera.getProjView()); shader.uniformMatrix(
"u_shadowsMatrix[0]", calc_shadows_matrix(shadowCamera, origin)
);
shader.uniformMatrix(
"u_shadowsMatrix[1]", calc_shadows_matrix(wideShadowCamera, origin)
);
shader.uniform3f("u_sunDir", shadowCamera.front); shader.uniform3f("u_sunDir", shadowCamera.front);
shader.uniform1i("u_shadowsRes", shadowMap->getResolution()); shader.uniform1i("u_shadowsRes", shadowMap->getResolution());
shader.uniform1f("u_shadowsOpacity", shadowsOpacity); // TODO: make it configurable shader.uniform1f("u_shadowsOpacity", shadowsOpacity); // TODO: make it configurable
@ -165,10 +180,10 @@ void Shadows::generateShadowsMap(
float shadowMapScale = 0.32f / (1 << glm::max(0, quality)) * scale; float shadowMapScale = 0.32f / (1 << glm::max(0, quality)) * scale;
float shadowMapSize = resolution * shadowMapScale; float shadowMapSize = resolution * shadowMapScale;
glm::vec3 basePos = glm::floor(camera.position / 4.0f) * 4.0f; worldvec3 basePos = glm::floor(camera.position / 4.0) * 4.0;
glm::vec3 prevPos = shadowCamera.position; worldvec3 prevPos = shadowCamera.position;
shadowCamera = Camera( shadowCamera = Camera(
glm::distance2(prevPos, basePos) > 25.0f ? basePos : prevPos, glm::distance2(prevPos, basePos) > 25.0 ? basePos : prevPos,
shadowMapSize shadowMapSize
); );
shadowCamera.near = 0.1f; shadowCamera.near = 0.1f;
@ -191,13 +206,13 @@ void Shadows::generateShadowsMap(
glm::radians(0.0f) glm::radians(0.0f)
); );
shadowCamera.position -= shadowCamera.front * 500.0f; shadowCamera.position -= worldvec3(shadowCamera.front * 500.0f);
shadowCamera.position += shadowCamera.up * 0.0f; shadowCamera.position += worldvec3(shadowCamera.up * 0.0f);
shadowCamera.position += camera.front * 0.0f; shadowCamera.position += worldvec3(camera.front * 0.0f);
auto view = shadowCamera.getView(); auto view = shadowCamera.getView();
auto currentPos = shadowCamera.position; auto currentPos = shadowCamera.getLocalPosition();
auto topRight = shadowCamera.right + shadowCamera.up; auto topRight = shadowCamera.right + shadowCamera.up;
auto min = view * glm::vec4(currentPos - topRight * shadowMapSize * 0.5f, 1.0f); auto min = view * glm::vec4(currentPos - topRight * shadowMapSize * 0.5f, 1.0f);
auto max = view * glm::vec4(currentPos + topRight * shadowMapSize * 0.5f, 1.0f); auto max = view * glm::vec4(currentPos + topRight * shadowMapSize * 0.5f, 1.0f);

View file

@ -19,7 +19,7 @@ public:
Shadows(const Level& level); Shadows(const Level& level);
~Shadows(); ~Shadows();
void setup(Shader& shader, const Weather& weather); void setup(Shader& shader, const Camera& camera, const Weather& weather);
void setQuality(int quality); void setQuality(int quality);
void refresh( void refresh(
const Camera& camera, const Camera& camera,

View file

@ -10,6 +10,7 @@
#include "lighting/Lightmap.hpp" #include "lighting/Lightmap.hpp"
#include "voxels/Block.hpp" #include "voxels/Block.hpp"
#include "voxels/Chunks.hpp" #include "voxels/Chunks.hpp"
#include "window/Camera.hpp"
#include <algorithm> #include <algorithm>
@ -24,7 +25,9 @@ BlockWrapsRenderer::BlockWrapsRenderer(
BlockWrapsRenderer::~BlockWrapsRenderer() = default; BlockWrapsRenderer::~BlockWrapsRenderer() = default;
void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) { void BlockWrapsRenderer::draw(
BlockWrapper& wrapper, const Texture* texture, const glm::ivec3& origin
) {
if (wrapper.cullingBits == 0x0) { if (wrapper.cullingBits == 0x0) {
return; return;
} }
@ -60,7 +63,7 @@ void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) {
switch (wrapper.modelType) { switch (wrapper.modelType) {
case BlockModelType::BLOCK: case BlockModelType::BLOCK:
batch->cube( batch->cube(
glm::vec3(wrapper.position) + glm::vec3(0.5f), glm::vec3(wrapper.position - origin) + glm::vec3(0.5f),
glm::vec3(1.01f), glm::vec3(1.01f),
wrapper.uvRegions, wrapper.uvRegions,
light, light,
@ -73,7 +76,7 @@ void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) {
const auto& aabb = def.getHitboxes(vox->state).at(0); const auto& aabb = def.getHitboxes(vox->state).at(0);
const auto& size = aabb.size(); const auto& size = aabb.size();
batch->cube( batch->cube(
glm::vec3(wrapper.position) + aabb.center(), glm::vec3(wrapper.position - origin) + aabb.center(),
size * glm::vec3(1.01f), size * glm::vec3(1.01f),
wrapper.uvRegions, wrapper.uvRegions,
light, light,
@ -134,8 +137,9 @@ void BlockWrapsRenderer::refreshWrapper(BlockWrapper& wrapper) {
} }
} }
void BlockWrapsRenderer::draw(const DrawContext& pctx) { void BlockWrapsRenderer::draw(const DrawContext& pctx, const Camera& camera) {
auto ctx = pctx.sub(); auto ctx = pctx.sub();
const glm::ivec3 origin = camera.getOrigin();
auto& shader = assets.require<Shader>("entity"); auto& shader = assets.require<Shader>("entity");
shader.use(); shader.use();
@ -151,7 +155,7 @@ void BlockWrapsRenderer::draw(const DrawContext& pctx) {
} }
for (const auto& [texture, wrapper] : renderOrder) { for (const auto& [texture, wrapper] : renderOrder) {
batch->setTexture(texture); batch->setTexture(texture);
draw(*wrapper, texture); draw(*wrapper, texture, origin);
} }
batch->flush(); batch->flush();
} }

View file

@ -12,6 +12,7 @@
#include <map> #include <map>
class Assets; class Assets;
class Camera;
class Content; class Content;
class Chunks; class Chunks;
class Texture; class Texture;
@ -41,7 +42,9 @@ class BlockWrapsRenderer {
std::unordered_map<u64id_t, std::unique_ptr<BlockWrapper>> wrappers; std::unordered_map<u64id_t, std::unique_ptr<BlockWrapper>> wrappers;
u64id_t nextWrapper = 1; u64id_t nextWrapper = 1;
void draw(BlockWrapper& wrapper, const Texture* texture); void draw(
BlockWrapper& wrapper, const Texture* texture, const glm::ivec3& origin
);
void refreshWrapper(BlockWrapper& wrapper); void refreshWrapper(BlockWrapper& wrapper);
void clearOrder(const BlockWrapper* const wrapper); void clearOrder(const BlockWrapper* const wrapper);
@ -51,7 +54,7 @@ public:
); );
~BlockWrapsRenderer(); ~BlockWrapsRenderer();
void draw(const DrawContext& ctx); void draw(const DrawContext& ctx, const Camera& camera);
u64id_t add( u64id_t add(
const glm::ivec3& position, const glm::ivec3& position,

View file

@ -637,12 +637,7 @@ SortingMeshData BlocksRenderer::renderTranslucent(
continue; continue;
} }
SortingMeshEntry entry { SortingMeshEntry entry {
glm::vec3( glm::vec3(x, y, z), util::Buffer<ChunkVertex>(indexCount), 0};
x + chunk->x * CHUNK_W + 0.5f,
y + 0.5f,
z + chunk->z * CHUNK_D + 0.5f
),
util::Buffer<ChunkVertex>(indexCount), 0};
totalSize += entry.vertexData.size(); totalSize += entry.vertexData.size();
@ -660,10 +655,6 @@ SortingMeshData BlocksRenderer::renderTranslucent(
} else { } else {
aabb.addPoint(vertex.position); aabb.addPoint(vertex.position);
} }
vertex.position.x += chunk->x * CHUNK_W + 0.5f;
vertex.position.y += 0.5f;
vertex.position.z += chunk->z * CHUNK_D + 0.5f;
} }
sortingMesh.entries.push_back(std::move(entry)); sortingMesh.entries.push_back(std::move(entry));
vertexCount = 0; vertexCount = 0;

View file

@ -12,6 +12,7 @@
#include "window/Camera.hpp" #include "window/Camera.hpp"
#include "maths/FrustumCulling.hpp" #include "maths/FrustumCulling.hpp"
#include "maths/util.hpp" #include "maths/util.hpp"
#include "maths/voxmaths.hpp"
#include "util/listutil.hpp" #include "util/listutil.hpp"
#include "util/ObjectsPool.hpp" #include "util/ObjectsPool.hpp"
#include "util/timeutil.hpp" #include "util/timeutil.hpp"
@ -241,6 +242,9 @@ void ChunksRenderer::drawShadowsPass(
auto denseDistance = settings.graphics.denseRenderDistance.get(); auto denseDistance = settings.graphics.denseRenderDistance.get();
auto denseDistance2 = denseDistance * denseDistance; auto denseDistance2 = denseDistance * denseDistance;
const glm::ivec3 origin = camera.getOrigin();
const glm::vec3 playerPos = util::to_local(playerCamera.position, origin);
for (const auto& chunk : chunks.getChunks()) { for (const auto& chunk : chunks.getChunks()) {
if (chunk == nullptr) { if (chunk == nullptr) {
continue; continue;
@ -251,16 +255,12 @@ void ChunksRenderer::drawShadowsPass(
continue; continue;
} }
glm::vec3 coord( int x = pos.x * CHUNK_W - origin.x;
pos.x * CHUNK_W + 0.5f, 0.5f, pos.y * CHUNK_D + 0.5f int z = pos.y * CHUNK_D - origin.z;
); glm::vec3 coord(x + 0.5f, 0.5f, z + 0.5f);
glm::vec3 min(pos.x * CHUNK_W, chunk->bottom, pos.y * CHUNK_D); glm::vec3 min(x, chunk->bottom, z);
glm::vec3 max( glm::vec3 max(x + CHUNK_W, chunk->top, z + CHUNK_D);
pos.x * CHUNK_W + CHUNK_W,
chunk->top,
pos.y * CHUNK_D + CHUNK_D
);
if (!frustum.isBoxVisible(min, max)) { if (!frustum.isBoxVisible(min, max)) {
continue; continue;
@ -268,7 +268,7 @@ void ChunksRenderer::drawShadowsPass(
glm::mat4 model = glm::translate(glm::mat4(1.0f), coord); glm::mat4 model = glm::translate(glm::mat4(1.0f), coord);
shader.uniformMatrix("u_model", model); shader.uniformMatrix("u_model", model);
found->second.mesh->draw(GL_TRIANGLES, found->second.mesh->draw(GL_TRIANGLES,
glm::distance2(playerCamera.position * glm::vec3(1, 0, 1), glm::distance2(playerPos * glm::vec3(1, 0, 1),
(min + max) * 0.5f * glm::vec3(1, 0, 1)) < denseDistance2); (min + max) * 0.5f * glm::vec3(1, 0, 1)) < denseDistance2);
} }
} }
@ -292,8 +292,13 @@ void ChunksRenderer::drawChunks(
indices.push_back(ChunksSortEntry {i, 0}); indices.push_back(ChunksSortEntry {i, 0});
} }
} }
float px = camera.position.x / static_cast<float>(CHUNK_W) - 0.5f; const glm::ivec3 origin = camera.getOrigin();
float pz = camera.position.z / static_cast<float>(CHUNK_D) - 0.5f; const glm::vec3 cameraPos = camera.getLocalPosition();
chunksOffsetX -= floordiv<CHUNK_W>(origin.x);
chunksOffsetY -= floordiv<CHUNK_D>(origin.z);
float px = cameraPos.x / static_cast<float>(CHUNK_W) - 0.5f;
float pz = cameraPos.z / static_cast<float>(CHUNK_D) - 0.5f;
for (auto& index : indices) { for (auto& index : indices) {
float x = index.index % chunksWidth + chunksOffsetX - px; float x = index.index % chunksWidth + chunksOffsetX - px;
float z = index.index / chunksWidth + chunksOffsetY - pz; float z = index.index / chunksWidth + chunksOffsetY - pz;
@ -323,32 +328,28 @@ void ChunksRenderer::drawChunks(
if (mesh.mesh == nullptr) { if (mesh.mesh == nullptr) {
continue; continue;
} }
int x = chunk->x * CHUNK_W - origin.x;
int z = chunk->z * CHUNK_D - origin.z;
if (culling) { if (culling) {
const auto& meshAABB = mesh.meshAABB; const auto& meshAABB = mesh.meshAABB;
auto aabbMin = meshAABB.min(); auto aabbMin = meshAABB.min();
auto aabbMax = meshAABB.max(); auto aabbMax = meshAABB.max();
glm::vec3 min( glm::vec3 min(
chunk->x * CHUNK_W + std::min(0.0f, aabbMin.x), x + std::min(0.0f, aabbMin.x),
chunk->bottom, chunk->bottom,
chunk->z * CHUNK_D + std::min(0.0f, aabbMin.z) z + std::min(0.0f, aabbMin.z)
);
glm::vec3 max(
chunk->x * CHUNK_W + aabbMax.x,
chunk->top,
chunk->z * CHUNK_D + aabbMax.z
); );
glm::vec3 max(x + aabbMax.x, chunk->top, z + aabbMax.z);
if (!frustum.isBoxVisible(min, max)) { if (!frustum.isBoxVisible(min, max)) {
continue; continue;
} }
} }
glm::vec3 coord( glm::vec3 coord(x + 0.5f, 0.5f, z + 0.5f);
chunk->x * CHUNK_W + 0.5f, 0.5f, chunk->z * CHUNK_D + 0.5f
);
glm::mat4 model = glm::translate(glm::mat4(1.0f), coord); glm::mat4 model = glm::translate(glm::mat4(1.0f), coord);
shader.uniformMatrix("u_model", model); shader.uniformMatrix("u_model", model);
mesh.mesh->draw(GL_TRIANGLES, glm::distance2(camera.position * glm::vec3(1, 0, 1), mesh.mesh->draw(GL_TRIANGLES, glm::distance2(cameraPos * glm::vec3(1, 0, 1),
(coord + glm::vec3(CHUNK_W * 0.5f, 0.0f, CHUNK_D * 0.5f))) < denseDistance2); (coord + glm::vec3(CHUNK_W * 0.5f, 0.0f, CHUNK_D * 0.5f))) < denseDistance2);
visibleChunks++; visibleChunks++;
} }
@ -375,12 +376,12 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) {
bool culling = settings.graphics.frustumCulling.get(); bool culling = settings.graphics.frustumCulling.get();
const auto& chunks = this->chunks.getChunks(); const auto& chunks = this->chunks.getChunks();
const auto& cameraPos = camera.position; const glm::ivec3 origin = camera.getOrigin();
const glm::vec3 cameraPos = camera.getLocalPosition();
const auto& atlas = assets.require<Atlas>("blocks"); const auto& atlas = assets.require<Atlas>("blocks");
shader.use(); shader.use();
atlas.getTexture()->bind(); atlas.getTexture()->bind();
shader.uniformMatrix("u_model", glm::mat4(1.0f));
shader.uniform1i("u_alphaClip", false); shader.uniform1i("u_alphaClip", false);
for (const auto& index : indices) { for (const auto& index : indices) {
@ -393,16 +394,18 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) {
continue; continue;
} }
int x = chunk->x * CHUNK_W - origin.x;
int z = chunk->z * CHUNK_D - origin.z;
if (culling) { if (culling) {
glm::vec3 min(chunk->x * CHUNK_W, chunk->bottom, chunk->z * CHUNK_D); glm::vec3 min(x, chunk->bottom, z);
glm::vec3 max( glm::vec3 max(x + CHUNK_W, chunk->top, z + CHUNK_D);
chunk->x * CHUNK_W + CHUNK_W,
chunk->top,
chunk->z * CHUNK_D + CHUNK_D
);
if (!frustum.isBoxVisible(min, max)) continue; if (!frustum.isBoxVisible(min, max)) continue;
} }
glm::vec3 coord(x + 0.5f, 0.5f, z + 0.5f);
shader.uniformMatrix(
"u_model", glm::translate(glm::mat4(1.0f), coord)
);
auto& chunkEntries = found->second.sortingMeshData.entries; auto& chunkEntries = found->second.sortingMeshData.entries;
@ -418,7 +421,7 @@ void ChunksRenderer::drawSortedMeshes(const Camera& camera, Shader& shader) {
} }
for (auto& entry : chunkEntries) { for (auto& entry : chunkEntries) {
entry.distance = static_cast<long long>( entry.distance = static_cast<long long>(
glm::distance2(entry.position, cameraPos) glm::distance2(entry.position, cameraPos - coord)
); );
} }
if (found->second.sortedMesh == nullptr || if (found->second.sortedMesh == nullptr ||

View file

@ -25,6 +25,7 @@ static debug::Logger logger("clouds-render");
static inline constexpr int MAP_SIZE = 512; static inline constexpr int MAP_SIZE = 512;
static inline constexpr float CLOUD_VOXEL_SCALE = 8.0f; static inline constexpr float CLOUD_VOXEL_SCALE = 8.0f;
static inline constexpr float CLOUDS_SPEED = 4.0f; static inline constexpr float CLOUDS_SPEED = 4.0f;
static inline constexpr double CLOUDS_WAVE_PERIOD = glm::two_pi<double>() * 1e3;
class CloudsMap { class CloudsMap {
public: public:
@ -269,8 +270,15 @@ void CloudsRenderer::draw(
float scale = CLOUD_VOXEL_SCALE; float scale = CLOUD_VOXEL_SCALE;
int totalDiameter = layer.segmentSize * scale; int totalDiameter = layer.segmentSize * scale;
int gcellX = floordiv(camera.position.x, totalDiameter); const glm::ivec3 origin = camera.getOrigin();
int gcellZ = floordiv(camera.position.z, totalDiameter); const glm::vec3 cameraPos = camera.getLocalPosition();
int gcellX = floordiv(
origin.x + static_cast<int>(glm::floor(cameraPos.x)), totalDiameter
);
int gcellZ = floordiv(
origin.z + static_cast<int>(glm::floor(cameraPos.z)), totalDiameter
);
float speed = CLOUDS_SPEED; float speed = CLOUDS_SPEED;
float speedX = glm::sin(layerId * 0.3f + 0.4f) * speed / (layerId + 1); float speedX = glm::sin(layerId * 0.3f + 0.4f) * speed / (layerId + 1);
@ -283,10 +291,10 @@ void CloudsRenderer::draw(
int lcellX = gcellX - floordiv(glm::floor(timer * speedX), totalDiameter); int lcellX = gcellX - floordiv(glm::floor(timer * speedX), totalDiameter);
int lcellZ = gcellZ - floordiv(glm::floor(timer * speedZ), totalDiameter); int lcellZ = gcellZ - floordiv(glm::floor(timer * speedZ), totalDiameter);
glm::vec3 position( glm::vec3 position(
-128 * scale + (x + gcellX) * layer.segmentSize * scale + -128 * scale + ((x + gcellX) * totalDiameter - origin.x) +
glm::mod(timer * speedX, static_cast<float>(totalDiameter)), glm::mod(timer * speedX, static_cast<float>(totalDiameter)),
250 + layerId * 200, 250 + layerId * 200,
-128 * scale + (z + gcellZ) * layer.segmentSize * scale + -128 * scale + ((z + gcellZ) * totalDiameter - origin.z) +
glm::mod(timer * speedZ, static_cast<float>(totalDiameter)) glm::mod(timer * speedZ, static_cast<float>(totalDiameter))
); );
if (glm::distance2( if (glm::distance2(
@ -294,7 +302,7 @@ void CloudsRenderer::draw(
position.x + totalDiameter * 0.5f, position.x + totalDiameter * 0.5f,
position.z + totalDiameter * 0.5f position.z + totalDiameter * 0.5f
), ),
glm::vec2(camera.position.x, camera.position.z) glm::vec2(cameraPos.x, cameraPos.z)
) > 4e6) { ) > 4e6) {
continue; continue;
} }
@ -331,6 +339,13 @@ void CloudsRenderer::draw(
shader.uniform1f("u_fogFactor", fogFactor * 0.03f); shader.uniform1f("u_fogFactor", fogFactor * 0.03f);
shader.uniform1f("u_fogCurve", 0.4f); shader.uniform1f("u_fogCurve", 0.4f);
const glm::ivec3 origin = camera.getOrigin();
shader.uniform2f(
"u_waveOffset",
std::fmod(origin.x, CLOUDS_WAVE_PERIOD),
std::fmod(origin.z, CLOUDS_WAVE_PERIOD)
);
for (int i = 0; i < std::min<int>(quality, layers.size()); i++) { for (int i = 0; i < std::min<int>(quality, layers.size()); i++) {
draw(layers[i], frustum, shader, camera, timer, i); draw(layers[i], frustum, shader, camera, timer, i);
} }

View file

@ -11,15 +11,17 @@
bool DebugLinesRenderer::showPaths = false; bool DebugLinesRenderer::showPaths = false;
static void draw_route(LineBatch& batch, const voxels::Agent& agent) { static void draw_route(
LineBatch& batch, const voxels::Agent& agent, const glm::ivec3& origin
) {
const auto& route = agent.route; const auto& route = agent.route;
if (!route.found) return; if (!route.found) return;
batch.lineWidth(1.0f); batch.lineWidth(1.0f);
for (int i = 1; i < route.nodes.size(); i++) { for (int i = 1; i < route.nodes.size(); i++) {
const auto& a = glm::vec3(route.nodes.at(i - 1).pos); const auto& a = glm::vec3(route.nodes.at(i - 1).pos - origin);
const auto& b = glm::vec3(route.nodes.at(i).pos); const auto& b = glm::vec3(route.nodes.at(i).pos - origin);
glm::vec3 a_base = a + glm::vec3(0.5); glm::vec3 a_base = a + glm::vec3(0.5);
glm::vec3 b_base = b + glm::vec3(0.5); glm::vec3 b_base = b + glm::vec3(0.5);
@ -99,10 +101,12 @@ void DebugLinesRenderer::render(
Shader& linesShader, Shader& linesShader,
bool showChunkBorders bool showChunkBorders
) { ) {
const glm::ivec3 origin = camera.getOrigin();
// In-world lines // In-world lines
if (showPaths) { if (showPaths) {
for (const auto& [_, agent] : level.pathfinding->getAgents()) { for (const auto& [_, agent] : level.pathfinding->getAgents()) {
draw_route(linesBatch, agent); draw_route(linesBatch, agent, origin);
} }
} }
DrawContext ctx = pctx.sub(&linesBatch); DrawContext ctx = pctx.sub(&linesBatch);
@ -114,7 +118,7 @@ void DebugLinesRenderer::render(
if (showChunkBorders) { if (showChunkBorders) {
linesShader.uniformMatrix("u_projview", camera.getProjView()); linesShader.uniformMatrix("u_projview", camera.getProjView());
glm::vec3 coord = camera.position; worldvec3 coord = camera.position;
if (coord.x < 0) coord.x--; if (coord.x < 0) coord.x--;
if (coord.z < 0) coord.z--; if (coord.z < 0) coord.z--;
int cx = floordiv(static_cast<int>(coord.x), CHUNK_W); int cx = floordiv(static_cast<int>(coord.x), CHUNK_W);
@ -122,12 +126,12 @@ void DebugLinesRenderer::render(
drawBorders( drawBorders(
linesBatch, linesBatch,
cx * CHUNK_W, cx * CHUNK_W - origin.x,
0, 0,
cz * CHUNK_D, cz * CHUNK_D - origin.z,
(cx + 1) * CHUNK_W, (cx + 1) * CHUNK_W - origin.x,
CHUNK_H, CHUNK_H,
(cz + 1) * CHUNK_D (cz + 1) * CHUNK_D - origin.z
); );
} }

View file

@ -83,7 +83,7 @@ void Decorator::addParticles(const Block& def, const glm::ivec3& pos) {
); );
blockEmitters[pos] = renderer.particles->add(std::make_unique<Emitter>( blockEmitters[pos] = renderer.particles->add(std::make_unique<Emitter>(
level, level,
glm::vec3{pos.x + 0.5, pos.y + 0.5, pos.z + 0.5}, worldvec3 {pos.x + 0.5, pos.y + 0.5, pos.z + 0.5},
*def.particles, *def.particles,
treg.texture, treg.texture,
treg.region, treg.region,
@ -120,7 +120,7 @@ void Decorator::updateAcoustics(const Camera& camera) {
glm::vec3 dir = { r * std::cos(phi), r * std::sin(phi), z }; glm::vec3 dir = { r * std::cos(phi), r * std::sin(phi), z };
dir = glm::normalize(dir); dir = glm::normalize(dir);
glm::vec3 end; worldvec3 end;
glm::ivec3 norm; glm::ivec3 norm;
glm::ivec3 iend; glm::ivec3 iend;
blocks_agent::RaycastSettings raycast {}; blocks_agent::RaycastSettings raycast {};
@ -128,7 +128,7 @@ void Decorator::updateAcoustics(const Camera& camera) {
if (vox == nullptr) { if (vox == nullptr) {
continue; continue;
} }
auto distance = glm::distance(start, end); float distance = glm::distance(start, end);
if (distance >= length * 0.98f) { if (distance >= length * 0.98f) {
continue; continue;
} }
@ -205,7 +205,7 @@ void Decorator::updateRandom(
); );
renderer.particles->add(std::make_unique<Emitter>( renderer.particles->add(std::make_unique<Emitter>(
level, level,
glm::vec3 { worldvec3 {
pos.x + random.randFloat(), pos.x + random.randFloat(),
pos.y + 1.1, pos.y + 1.1,
pos.z + random.randFloat()}, pos.z + random.randFloat()},
@ -308,11 +308,11 @@ void Decorator::updateTextNotes() {
renderer.texts->remove(textsIter->second); renderer.texts->remove(textsIter->second);
textsIter = playerTexts.erase(textsIter); textsIter = playerTexts.erase(textsIter);
} else { } else {
glm::vec3 position = player->getPosition(); worldvec3 position = player->getPosition();
if (auto entity = level.entities->get(player->getEntity())) { if (auto entity = level.entities->get(player->getEntity())) {
position = entity->getInterpolatedPosition(); position = entity->getInterpolatedPosition();
} }
note->setPosition(position + glm::vec3(0, 1, 0)); note->setPosition(position + worldvec3(0, 1, 0));
if (note->getText() != player->getName()) { if (note->getText() != player->getName()) {
note->setText(player->getName()); note->setText(player->getName());
} }

View file

@ -14,7 +14,7 @@
Emitter::Emitter( Emitter::Emitter(
const Level& level, const Level& level,
std::variant<glm::vec3, entityid_t> origin, EmitterOrigin origin,
ParticlesPreset preset, ParticlesPreset preset,
const Texture* texture, const Texture* texture,
const UVRegion& region, const UVRegion& region,
@ -50,15 +50,15 @@ static inline glm::vec3 generate_coord(ParticleSpawnShape shape) {
void Emitter::update( void Emitter::update(
float delta, float delta,
const glm::vec3& cameraPosition, const worldvec3& cameraPosition,
std::vector<Particle>& particles std::vector<Particle>& particles
) { ) {
const float spawnInterval = preset.spawnInterval; const float spawnInterval = preset.spawnInterval;
if (count == 0 || (count == -1 && spawnInterval < FLT_EPSILON)) { if (count == 0 || (count == -1 && spawnInterval < FLT_EPSILON)) {
return; return;
} }
glm::vec3 position {}; worldvec3 position {};
if (auto staticPos = std::get_if<glm::vec3>(&origin)) { if (auto staticPos = std::get_if<worldvec3>(&origin)) {
position = *staticPos; position = *staticPos;
} else if (auto entityId = std::get_if<entityid_t>(&origin)) { } else if (auto entityId = std::get_if<entityid_t>(&origin)) {
if (auto entity = level.entities->get(*entityId)) { if (auto entity = level.entities->get(*entityId)) {
@ -105,7 +105,7 @@ void Emitter::update(
spawnOffset *= preset.spawnSpread; spawnOffset *= preset.spawnSpread;
spawnOffset += preset.spawnOffset; spawnOffset += preset.spawnOffset;
particle.position = position + spawnOffset; particle.position = position + worldvec3(spawnOffset);
particle.lifetime *= 1.0f - preset.lifetimeSpread * random.randFloat(); particle.lifetime *= 1.0f - preset.lifetimeSpread * random.randFloat();
particle.velocity += glm::ballRand(1.0f) * preset.explosion; particle.velocity += glm::ballRand(1.0f) * preset.explosion;
if (preset.randomSubUV < 1.0f) { if (preset.randomSubUV < 1.0f) {

View file

@ -20,7 +20,7 @@ struct Particle {
/// @brief Some random integer for visuals configuration. /// @brief Some random integer for visuals configuration.
int random; int random;
/// @brief Global position /// @brief Global position
glm::vec3 position; worldvec3 position;
/// @brief Linear velocity /// @brief Linear velocity
glm::vec3 velocity; glm::vec3 velocity;
/// @brief Remaining life time /// @brief Remaining life time
@ -35,7 +35,7 @@ struct Particle {
class Texture; class Texture;
using EmitterOrigin = std::variant<glm::vec3, entityid_t>; using EmitterOrigin = std::variant<worldvec3, entityid_t>;
class Emitter { class Emitter {
const Level& level; const Level& level;
@ -61,7 +61,7 @@ public:
Emitter( Emitter(
const Level& level, const Level& level,
std::variant<glm::vec3, entityid_t> origin, EmitterOrigin origin,
ParticlesPreset preset, ParticlesPreset preset,
const Texture* texture, const Texture* texture,
const UVRegion& region, const UVRegion& region,
@ -79,7 +79,7 @@ public:
/// @param particles destination particles vector /// @param particles destination particles vector
void update( void update(
float delta, float delta,
const glm::vec3& cameraPosition, const worldvec3& cameraPosition,
std::vector<Particle>& particles std::vector<Particle>& particles
); );

View file

@ -5,6 +5,7 @@
#include "graphics/core/DrawContext.hpp" #include "graphics/core/DrawContext.hpp"
#include "graphics/core/LineBatch.hpp" #include "graphics/core/LineBatch.hpp"
#include "maths/FrustumCulling.hpp" #include "maths/FrustumCulling.hpp"
#include "maths/util.hpp"
#include "objects/Entities.hpp" #include "objects/Entities.hpp"
#include "objects/Entity.hpp" #include "objects/Entity.hpp"
#include "objects/EntityDef.hpp" #include "objects/EntityDef.hpp"
@ -46,10 +47,12 @@ static bool check_frustum(
const Frustum& frustum, const Frustum& frustum,
const Transform& transform, const Transform& transform,
const Rigidbody& rigidbody, const Rigidbody& rigidbody,
const rigging::Skeleton& skeleton const rigging::Skeleton& skeleton,
const glm::ivec3& origin
) { ) {
glm::vec3 pos = util::to_local(transform.pos, origin);
glm::vec3 ext = calc_extent(transform, rigidbody, skeleton); glm::vec3 ext = calc_extent(transform, rigidbody, skeleton);
return frustum.isBoxVisible(transform.pos - ext, transform.pos + ext); return frustum.isBoxVisible(pos - ext, pos + ext);
} }
EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities) EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities)
@ -57,8 +60,12 @@ EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities)
} }
void EntitiesRenderer::render( void EntitiesRenderer::render(
ModelBatch& batch, const Frustum* frustum, entityid_t fpsEntity ModelBatch& batch,
const glm::ivec3& origin,
const Frustum* frustum,
entityid_t fpsEntity
) { ) {
batch.setLightsOffset(origin);
for (const auto& [uid, entity] : entities.getEntities()) { for (const auto& [uid, entity] : entities.getEntities()) {
if (!entity->getSkeleton() || uid == fpsEntity) { if (!entity->getSkeleton() || uid == fpsEntity) {
continue; continue;
@ -73,12 +80,17 @@ void EntitiesRenderer::render(
if (rigConfig == nullptr) { if (rigConfig == nullptr) {
continue; continue;
} }
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { if (frustum &&
!check_frustum(*frustum, transform, rigidbody, skeleton, origin)) {
if (!skeleton.boundsDirty || !skeleton.visible) { if (!skeleton.boundsDirty || !skeleton.visible) {
continue; continue;
} }
rigConfig->updateBounds(assets, skeleton, transform.rot, pos, size); rigConfig->updateBounds(
if (!check_frustum(*frustum, transform, rigidbody, skeleton)) { assets, skeleton, transform.rot, pos, size, origin
);
if (!check_frustum(
*frustum, transform, rigidbody, skeleton, origin
)) {
continue; continue;
} }
} }
@ -90,6 +102,7 @@ void EntitiesRenderer::render(
transform.rot, transform.rot,
pos, pos,
size, size,
origin,
def.translucent def.translucent
); );
} }
@ -97,6 +110,7 @@ void EntitiesRenderer::render(
void EntitiesRenderer::renderDebug( void EntitiesRenderer::renderDebug(
LineBatch& batch, LineBatch& batch,
const glm::ivec3& origin,
const Frustum* frustum, const Frustum* frustum,
const DrawContext& pctx, const DrawContext& pctx,
entityid_t fpsEntity entityid_t fpsEntity
@ -113,20 +127,31 @@ void EntitiesRenderer::renderDebug(
const auto& rigidbody = entity->getRigidbody(); const auto& rigidbody = entity->getRigidbody();
const auto& skeleton = *entity->getSkeleton(); const auto& skeleton = *entity->getSkeleton();
const auto& hitbox = rigidbody.hitbox; const auto& hitbox = rigidbody.hitbox;
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { if (frustum &&
!check_frustum(
*frustum, transform, rigidbody, skeleton, origin
)) {
continue; continue;
} }
batch.box( batch.box(
hitbox.position, hitbox.getHalfSize() * 2.0f, glm::vec4(1.0f) util::to_local(hitbox.position, origin),
hitbox.getHalfSize() * 2.0f,
glm::vec4(1.0f)
); );
glm::vec3 ext = calc_extent(transform, rigidbody, skeleton); glm::vec3 ext = calc_extent(transform, rigidbody, skeleton);
batch.box( batch.box(
transform.pos, ext * 2.0f, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f) util::to_local(transform.pos, origin),
ext * 2.0f,
glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)
); );
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(
sensor.calculated.aabb.center(), 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)
); );
@ -149,7 +174,10 @@ void EntitiesRenderer::renderDebug(
if (config == nullptr) { if (config == nullptr) {
continue; continue;
} }
if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { if (frustum &&
!check_frustum(
*frustum, transform, rigidbody, skeleton, origin
)) {
continue; continue;
} }
auto bone = config->getRoot(); auto bone = config->getRoot();
@ -159,7 +187,7 @@ void EntitiesRenderer::renderDebug(
} }
void EntitiesRenderer::updateCulling( void EntitiesRenderer::updateCulling(
const Frustum* frustum, entityid_t fpsEntity const glm::ivec3& origin, const Frustum* frustum, entityid_t fpsEntity
) { ) {
for (const auto& [uid, entity] : entities.getEntities()) { for (const auto& [uid, entity] : entities.getEntities()) {
if (!entity->getSkeleton()) { if (!entity->getSkeleton()) {
@ -171,7 +199,11 @@ void EntitiesRenderer::updateCulling(
continue; continue;
} }
skeleton.culled = !check_frustum( skeleton.culled = !check_frustum(
*frustum, entity->getTransform(), entity->getRigidbody(), skeleton *frustum,
entity->getTransform(),
entity->getRigidbody(),
skeleton,
origin
); );
} }
} }

View file

@ -2,6 +2,8 @@
#include "typedefs.hpp" #include "typedefs.hpp"
#include <glm/vec3.hpp>
class Assets; class Assets;
class DrawContext; class DrawContext;
class Entities; class Entities;
@ -16,15 +18,21 @@ public:
EntitiesRenderer(const Assets& assets, Entities& entities); EntitiesRenderer(const Assets& assets, Entities& entities);
void render( void render(
ModelBatch& batch, const Frustum* frustum, entityid_t fpsEntity ModelBatch& batch,
const glm::ivec3& origin,
const Frustum* frustum,
entityid_t fpsEntity
); );
void renderDebug( void renderDebug(
LineBatch& batch, LineBatch& batch,
const glm::ivec3& origin,
const Frustum* frustum, const Frustum* frustum,
const DrawContext& ctx, const DrawContext& ctx,
entityid_t fpsEntity entityid_t fpsEntity
); );
void updateCulling(const Frustum* frustum, entityid_t fpsEntity); void updateCulling(
const glm::ivec3& origin, const Frustum* frustum, entityid_t fpsEntity
);
}; };

View file

@ -33,7 +33,8 @@ void HandsRenderer::render(const Camera& camera) {
ModelLightingMode::SOLID, ModelLightingMode::SOLID,
glm::mat3(1.0f), glm::mat3(1.0f),
glm::vec3(), glm::vec3(),
glm::vec3(1.0f) glm::vec3(1.0f),
glm::ivec3()
); );
modelBatch.render(); modelBatch.render();

View file

@ -63,11 +63,11 @@ void MainBatch::prepare(int vertices) {
} }
glm::vec4 MainBatch::sampleLight( glm::vec4 MainBatch::sampleLight(
const glm::vec3 &pos, const Chunks &chunks, bool backlight const glm::dvec3 &pos, const Chunks &chunks, bool backlight
) { ) {
light_t light = chunks.getLight( light_t light = chunks.getLight(
std::floor(pos.x), std::floor(pos.x),
std::floor(std::min(CHUNK_H - 1.0f, pos.y)), std::floor(std::min(CHUNK_H - 1.0, pos.y)),
std::floor(pos.z)); std::floor(pos.z));
light_t minIntensity = backlight ? 1 : 0; light_t minIntensity = backlight ? 1 : 0;
return { return {

View file

@ -46,7 +46,7 @@ public:
void flush(); void flush();
static glm::vec4 sampleLight( static glm::vec4 sampleLight(
const glm::vec3& pos, const Chunks& chunks, bool backlight const glm::dvec3& pos, const Chunks& chunks, bool backlight
); );
inline void vertex( inline void vertex(

View file

@ -106,8 +106,8 @@ void ModelBatch::draw(
auto& queue = auto& queue =
translucent || tint.a < 1.0f ? translucentEntries : entries; translucent || tint.a < 1.0f ? translucentEntries : entries;
const auto& gpuModel = upload(model); const auto& gpuModel = upload(model);
glm::vec3 lightSamplePos = glm::dvec3 lightSamplePos =
glm::vec3(matrix[3]) + lightsOffset + lightSampleOffset; glm::dvec3(matrix[3]) + lightsOffset + glm::dvec3(lightSampleOffset);
for (size_t i = 0; i < model->meshes.size(); i++) { for (size_t i = 0; i < model->meshes.size(); i++) {
const auto& mesh = model->meshes[i]; const auto& mesh = model->meshes[i];
if (mesh.vertices.empty()) { if (mesh.vertices.empty()) {
@ -219,6 +219,6 @@ void ModelBatch::renderTranslucent(const glm::vec3& cameraPosition) {
finishFrame(); finishFrame();
} }
void ModelBatch::setLightsOffset(const glm::vec3& offset) { void ModelBatch::setLightsOffset(const glm::dvec3& offset) {
lightsOffset = offset; lightsOffset = offset;
} }

View file

@ -50,13 +50,13 @@ public:
void renderTranslucent(const glm::vec3& cameraPosition); void renderTranslucent(const glm::vec3& cameraPosition);
void setLightsOffset(const glm::vec3& offset); void setLightsOffset(const glm::dvec3& offset);
private: private:
const Assets& assets; const Assets& assets;
const Chunks& chunks; const Chunks& chunks;
const EngineSettings& settings; const EngineSettings& settings;
glm::vec3 lightsOffset {}; glm::dvec3 lightsOffset {};
struct Vertex { struct Vertex {
glm::vec3 coord; glm::vec3 coord;
@ -103,7 +103,7 @@ private:
struct DrawEntry { struct DrawEntry {
const Texture* texture; const Texture* texture;
const Mesh<Vertex>* mesh; const Mesh<Vertex>* mesh;
glm::vec3 lightSamplePos; glm::dvec3 lightSamplePos;
bool shading; bool shading;
Instance instance; Instance instance;
}; };

View file

@ -38,10 +38,10 @@ static inline void update_particle(
auto& angle = particle.angle; auto& angle = particle.angle;
vel += delta * preset.acceleration; vel += delta * preset.acceleration;
if (preset.collision && chunks.isObstacleAt(pos + vel * delta)) { if (preset.collision && chunks.isObstacleAt(pos + worldvec3(vel * delta))) {
vel *= 0.0f; vel *= 0.0f;
} }
pos += vel * delta; pos += worldvec3(vel * delta);
angle += particle.angularVelocity * delta; angle += particle.angularVelocity * delta;
particle.lifetime -= delta; particle.lifetime -= delta;
} }
@ -114,7 +114,8 @@ static inline glm::vec4 calc_lights(
light = glm::max( light = glm::max(
light, light,
MainBatch::sampleLight( MainBatch::sampleLight(
particle.position - size * glm::vec3(x, y, z), particle.position -
worldvec3(size * glm::vec3(x, y, z)),
chunks, chunks,
backlight backlight
) )
@ -154,7 +155,7 @@ void ParticlesRenderer::renderParticle(
camera.front * rotatedUp.z; camera.front * rotatedUp.z;
} }
batch->quad( batch->quad(
particle.position, util::to_local(particle.position, camera.getOrigin()),
localRight, localRight,
localUp, localUp,
-camera.front, -camera.front,

View file

@ -67,7 +67,7 @@ static constexpr float K = 21.41149;
static constexpr glm::ivec2 FACE_SIZE {1, 16}; static constexpr glm::ivec2 FACE_SIZE {1, 16};
static UVRegion calc_uv( static UVRegion calc_uv(
const glm::vec3& pos, const glm::ivec3& pos,
const glm::vec3& right, const glm::vec3& right,
float timer, float timer,
const WeatherPreset& weather const WeatherPreset& weather
@ -84,8 +84,10 @@ static UVRegion calc_uv(
} }
random.setSeed(uz); random.setSeed(uz);
float hspeed = (random.randFloat() * 2.0f - 1.0f) * weather.fall.hspeed; float hspeed = (random.randFloat() * 2.0f - 1.0f) * weather.fall.hspeed;
float u1 = ux * scale + timer * hspeed * -m; float u1 =
float v1 = timer * weather.fall.vspeed + pos.y * scale + uz * K; glm::fract(ux * static_cast<double>(scale)) + timer * hspeed * -m;
float v1 = timer * weather.fall.vspeed + pos.y * scale +
glm::fract(uz * static_cast<double>(K));
return {u1, v1, u1 + m * scale, v1 + FACE_SIZE.y * scale}; return {u1, v1, u1 + m * scale, v1 + FACE_SIZE.y * scale};
} }
@ -104,6 +106,8 @@ void PrecipitationRenderer::render(
int y = glm::floor(camera.position.y); int y = glm::floor(camera.position.y);
int z = glm::floor(camera.position.z); int z = glm::floor(camera.position.z);
const glm::ivec3 origin = camera.getOrigin();
util::CentredMatrix<int, (depth + 1) * 2> heights; util::CentredMatrix<int, (depth + 1) * 2> heights;
heights.setCenter(x, z); heights.setCenter(x, z);
for (int z = heights.beginY(); z < heights.endY(); z++) { for (int z = heights.beginY(); z < heights.endY(); z++) {
@ -135,17 +139,16 @@ void PrecipitationRenderer::render(
for (int lx = -radius; lx <= radius; lx++) { for (int lx = -radius; lx <= radius; lx++) {
for (int lz = depth; lz > 0; lz--) { for (int lz = depth; lz > 0; lz--) {
// Position calculations // Position calculations
glm::vec3 pos = face.right * static_cast<float>(lx) + glm::ivec3 pos =
face.front * static_cast<float>(lz); glm::ivec3(face.right) * lx + glm::ivec3(face.front) * lz;
pos += glm::vec3(x, 0, z); pos += glm::ivec3(x, 0, z);
pos.y = pos.y =
glm::max(y - FACE_SIZE.y / 2, heights.at(pos.x, pos.z)) + glm::max(y - FACE_SIZE.y / 2, heights.at(pos.x, pos.z)) +
FACE_SIZE.y / 2 + 1; FACE_SIZE.y / 2 + 1;
pos += glm::vec3(0.5f, 0.0f, 0.5f);
// Draw // Draw
batch->quad( batch->quad(
pos, glm::vec3(pos - origin) + glm::vec3(0.5f, 0.0f, 0.5f),
face.right, face.right,
{0, 1, 0}, {0, 1, 0},
glm::cross(glm::vec3(0, 1, 0), face.right), glm::cross(glm::vec3(0, 1, 0), face.right),

View file

@ -1,6 +1,6 @@
#include "TextNote.hpp" #include "TextNote.hpp"
TextNote::TextNote(std::wstring text, NotePreset preset, glm::vec3 position) TextNote::TextNote(std::wstring text, NotePreset preset, worldvec3 position)
: text(std::move(text)), : text(std::move(text)),
preset(std::move(preset)), preset(std::move(preset)),
position(std::move(position)) { position(std::move(position)) {
@ -30,11 +30,11 @@ void TextNote::updatePreset(const dv::value& data) {
preset.deserialize(data); preset.deserialize(data);
} }
void TextNote::setPosition(const glm::vec3& position) { void TextNote::setPosition(const worldvec3& position) {
this->position = position; this->position = position;
} }
const glm::vec3& TextNote::getPosition() const { const worldvec3& TextNote::getPosition() const {
return position; return position;
} }

View file

@ -7,13 +7,13 @@
class TextNote { class TextNote {
std::wstring text; std::wstring text;
NotePreset preset; NotePreset preset;
glm::vec3 position; worldvec3 position;
entityid_t entity = ENTITY_NONE; entityid_t entity = ENTITY_NONE;
glm::vec3 xAxis {1, 0, 0}; glm::vec3 xAxis {1, 0, 0};
glm::vec3 yAxis {0, 1, 0}; glm::vec3 yAxis {0, 1, 0};
public: public:
TextNote(std::wstring text, NotePreset preset, glm::vec3 position); TextNote(std::wstring text, NotePreset preset, worldvec3 position);
void setText(std::wstring_view text); void setText(std::wstring_view text);
void setEntity(entityid_t eid); void setEntity(entityid_t eid);
@ -25,8 +25,8 @@ public:
void updatePreset(const dv::value& data); void updatePreset(const dv::value& data);
void setPosition(const glm::vec3& position); void setPosition(const worldvec3& position);
const glm::vec3& getPosition() const; const worldvec3& getPosition() const;
const glm::vec3& getAxisX() const; const glm::vec3& getAxisX() const;
const glm::vec3& getAxisY() const; const glm::vec3& getAxisY() const;

View file

@ -35,16 +35,19 @@ void TextsRenderer::renderNote(
) { ) {
const auto& text = note.getText(); const auto& text = note.getText();
const auto& preset = note.getPreset(); const auto& preset = note.getPreset();
auto pos = note.getPosition(); auto worldPos = note.getPosition();
entityid_t eid = note.getEntity(); entityid_t eid = note.getEntity();
if (eid != ENTITY_NONE) { if (eid != ENTITY_NONE) {
if (auto entity = level.entities->get(eid)) { if (auto entity = level.entities->get(eid)) {
pos += entity->getTransform().displayPos; worldPos += entity->getTransform().displayPos;
} }
} }
if (util::distance2(pos, camera.position) > glm::vec3 pos = util::to_local(worldPos, camera.getOrigin());
const glm::vec3 cameraPos = camera.getLocalPosition();
if (util::distance2(pos, cameraPos) >
util::sqr(preset.renderDistance / camera.zoom)) { util::sqr(preset.renderDistance / camera.zoom)) {
return; return;
} }
@ -70,7 +73,7 @@ void TextsRenderer::renderNote(
int height = font.getLineHeight(); int height = font.getLineHeight();
if (preset.displayMode == NoteDisplayMode::Y_FREE_BILLBOARD || if (preset.displayMode == NoteDisplayMode::Y_FREE_BILLBOARD ||
preset.displayMode == NoteDisplayMode::XY_FREE_BILLBOARD) { preset.displayMode == NoteDisplayMode::XY_FREE_BILLBOARD) {
xvec = camera.position - pos; xvec = cameraPos - pos;
xvec.y = 0; xvec.y = 0;
std::swap(xvec.x, xvec.z); std::swap(xvec.x, xvec.z);
xvec.z *= -1; xvec.z *= -1;
@ -80,9 +83,7 @@ void TextsRenderer::renderNote(
} }
float scale = float scale =
(1.0f - preset.perspective) * (1.0f - preset.perspective) *
glm::pow( glm::pow(glm::distance(cameraPos, pos), 1.0f - preset.perspective);
glm::distance(camera.position, pos), 1.0f - preset.perspective
);
xvec *= 1.0f + scale; xvec *= 1.0f + scale;
yvec *= 1.0f + scale; yvec *= 1.0f + scale;
} }
@ -91,7 +92,7 @@ void TextsRenderer::renderNote(
float scale = 1.0f; float scale = 1.0f;
if (glm::abs(preset.perspective) > 0.0001f) { if (glm::abs(preset.perspective) > 0.0001f) {
float scale2 = float scale2 =
scale / (glm::distance(camera.position, pos) * camera.zoom * scale / (glm::distance(cameraPos, pos) * camera.zoom *
glm::sqrt(glm::tan(camera.getFov() * 0.5f))); glm::sqrt(glm::tan(camera.getFov() * 0.5f)));
scale = scale2 * preset.perspective + scale = scale2 * preset.perspective +
scale * (1.0f - preset.perspective); scale * (1.0f - preset.perspective);

View file

@ -42,6 +42,7 @@
#include "items/ItemStack.hpp" #include "items/ItemStack.hpp"
#include "logic/PlayerController.hpp" #include "logic/PlayerController.hpp"
#include "maths/FrustumCulling.hpp" #include "maths/FrustumCulling.hpp"
#include "maths/util.hpp"
#include "maths/voxmaths.hpp" #include "maths/voxmaths.hpp"
#include "objects/Entities.hpp" #include "objects/Entities.hpp"
#include "objects/Player.hpp" #include "objects/Player.hpp"
@ -213,7 +214,7 @@ static void setup_camera(Shader& shader, const Camera& camera) {
shader.uniformMatrix("u_model", glm::mat4(1.0f)); shader.uniformMatrix("u_model", glm::mat4(1.0f));
shader.uniformMatrix("u_proj", camera.getProjection()); shader.uniformMatrix("u_proj", camera.getProjection());
shader.uniformMatrix("u_view", camera.getView()); shader.uniformMatrix("u_view", camera.getView());
shader.uniform3f("u_cameraPos", camera.position); shader.uniform3f("u_cameraPos", camera.getLocalPosition());
} }
void WorldRenderer::setupWorldShader( void WorldRenderer::setupWorldShader(
@ -226,7 +227,7 @@ void WorldRenderer::setupWorldShader(
setup_camera(shader, camera); setup_camera(shader, camera);
setup_weather(shader, weather); setup_weather(shader, weather);
shadowMapping->setup(shader, weather); shadowMapping->setup(shader, camera, weather);
shader.uniform1f("u_timer", timer); shader.uniform1f("u_timer", timer);
shader.uniform1f("u_gamma", settings.graphics.gamma.get()); shader.uniform1f("u_gamma", settings.graphics.gamma.get());
@ -283,6 +284,7 @@ void WorldRenderer::renderOpaque(
setup_entity_pass(modelShader, {0.5f, true, false, false, 1.0f}); setup_entity_pass(modelShader, {0.5f, true, false, false, 1.0f});
entitiesRenderer->render( entitiesRenderer->render(
*modelBatch, *modelBatch,
camera.getOrigin(),
culling ? frustumCulling.get() : nullptr, culling ? frustumCulling.get() : nullptr,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() player.currentCamera.get() == player.fpCamera.get() ? player.getEntity()
: 0 : 0
@ -297,7 +299,7 @@ void WorldRenderer::renderOpaque(
setupWorldShader(mainShader, camera, settings, fogFactor); setupWorldShader(mainShader, camera, settings, fogFactor);
chunksRenderer->drawChunks(camera, mainShader); chunksRenderer->drawChunks(camera, mainShader);
blockWraps->draw(ctx); blockWraps->draw(ctx, camera);
if (level.environment.sky.clouds) { if (level.environment.sky.clouds) {
int cloudsQuality = settings.graphics.cloudsQuality.get(); int cloudsQuality = settings.graphics.cloudsQuality.get();
@ -315,13 +317,14 @@ void WorldRenderer::renderOpaque(
} }
} }
void WorldRenderer::renderBlockSelection() { void WorldRenderer::renderBlockSelection(const Camera& camera) {
const auto& selection = player.selection; const auto& selection = player.selection;
auto indices = level.content.getIndices(); auto indices = level.content.getIndices();
blockid_t id = selection.vox.id; blockid_t id = selection.vox.id;
auto& block = indices->blocks.require(id); auto& block = indices->blocks.require(id);
const glm::ivec3 origin = camera.getOrigin();
const glm::ivec3 pos = player.selection.position; const glm::ivec3 pos = player.selection.position;
const glm::vec3 point = selection.hitPosition; const glm::vec3 point = util::to_local(selection.hitPosition, origin);
const glm::vec3 norm = selection.normal; const glm::vec3 norm = selection.normal;
const auto& hitboxes = block.getHitboxes( const auto& hitboxes = block.getHitboxes(
@ -330,7 +333,7 @@ void WorldRenderer::renderBlockSelection() {
lineBatch->lineWidth(2.0f); lineBatch->lineWidth(2.0f);
for (auto& hitbox : hitboxes) { for (auto& hitbox : hitboxes) {
const glm::vec3 center = glm::vec3(pos) + hitbox.center(); const glm::vec3 center = glm::vec3(pos - origin) + hitbox.center();
const glm::vec3 size = hitbox.size(); const glm::vec3 size = hitbox.size();
lineBatch->box( lineBatch->box(
center, size + glm::vec3(0.01), glm::vec4(0.f, 0.f, 0.f, 1.0f) center, size + glm::vec3(0.01), glm::vec4(0.f, 0.f, 0.f, 1.0f)
@ -350,13 +353,16 @@ void WorldRenderer::renderInWorldLines(
linesShader.use(); linesShader.use();
linesShader.uniformMatrix("u_projview", camera.getProjView()); linesShader.uniformMatrix("u_projview", camera.getProjView());
if (player.selection.vox.id != BLOCK_VOID) { if (player.selection.vox.id != BLOCK_VOID) {
renderBlockSelection(); renderBlockSelection(camera);
} }
if (debug && showEntitiesDebug) { if (debug && showEntitiesDebug) {
auto ctx = pctx.sub(lineBatch.get()); auto ctx = pctx.sub(lineBatch.get());
bool culling = engine.getSettings().graphics.frustumCulling.get(); bool culling = engine.getSettings().graphics.frustumCulling.get();
entitiesRenderer->renderDebug( entitiesRenderer->renderDebug(
*lineBatch, culling ? frustumCulling.get() : nullptr, ctx, *lineBatch,
camera.getOrigin(),
culling ? frustumCulling.get() : nullptr,
ctx,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0 player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0
); );
} }
@ -368,6 +374,7 @@ void WorldRenderer::updateEntitiesCulling(const Camera& camera) {
frustumCulling->update(camera.getProjView()); frustumCulling->update(camera.getProjView());
} }
entitiesRenderer->updateCulling( entitiesRenderer->updateCulling(
camera.getOrigin(),
culling ? frustumCulling.get() : nullptr, culling ? frustumCulling.get() : nullptr,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() player.currentCamera.get() == player.fpCamera.get() ? player.getEntity()
: 0 : 0
@ -587,7 +594,7 @@ void WorldRenderer::renderTranslucency(
auto& shader = assets.require<Shader>("model"); auto& shader = assets.require<Shader>("model");
setupWorldShader(shader, camera, settings, fogFactor); setupWorldShader(shader, camera, settings, fogFactor);
setup_entity_pass(shader, {0.002f, false, true, true, 1.0f}); setup_entity_pass(shader, {0.002f, false, true, true, 1.0f});
modelBatch->renderTranslucent(camera.position); modelBatch->renderTranslucent(camera.getLocalPosition());
} }
{ {
auto lctx = ctx.sub(); auto lctx = ctx.sub();

View file

@ -91,7 +91,7 @@ private:
bool dirtySettings = true; bool dirtySettings = true;
/// @brief Render block selection lines /// @brief Render block selection lines
void renderBlockSelection(); void renderBlockSelection(const Camera& camera);
/// @brief Render lines (selection and debug) /// @brief Render lines (selection and debug)
/// @param camera active camera /// @param camera active camera

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() {
@ -200,7 +200,7 @@ void CameraControl::update(
refreshPosition(); refreshPosition();
auto castRay = [](Player& player, Camera& camera, const glm::vec3& front) auto castRay = [](Player& player, Camera& camera, const glm::vec3& front)
-> glm::vec3 { -> worldvec3 {
auto blockEnd = player.chunks->rayCastToObstacle(camera.position, front, 3.0f); auto blockEnd = player.chunks->rayCastToObstacle(camera.position, front, 3.0f);
Entities::RaycastSettings raycast {}; Entities::RaycastSettings raycast {};
@ -212,7 +212,7 @@ void CameraControl::update(
); );
if (entityRay.has_value() && if (entityRay.has_value() &&
entityRay->distance < glm::distance(camera.position, blockEnd)) { entityRay->distance < glm::distance(camera.position, blockEnd)) {
return (camera.position + front * entityRay->distance); return camera.position + worldvec3(front * entityRay->distance);
} else { } else {
return blockEnd; return blockEnd;
} }
@ -220,14 +220,14 @@ void CameraControl::update(
camera->updateVectors(); camera->updateVectors();
if (player.currentCamera == spCamera) { if (player.currentCamera == spCamera) {
spCamera->position = spCamera->position = castRay(player, *camera, camera->front) -
castRay(player, *camera, camera->front) - 0.4f * camera->front; worldvec3(0.4f * camera->front);
spCamera->dir = -camera->dir; spCamera->dir = -camera->dir;
spCamera->front = -camera->front; spCamera->front = -camera->front;
spCamera->right = -camera->right; spCamera->right = -camera->right;
} else if (player.currentCamera == tpCamera) { } else if (player.currentCamera == tpCamera) {
tpCamera->position = castRay(player, *camera, camera->front * -1.0f) + tpCamera->position = castRay(player, *camera, camera->front * -1.0f) +
0.4f * camera->front; worldvec3(0.4f * camera->front);
tpCamera->dir = camera->dir; tpCamera->dir = camera->dir;
tpCamera->front = camera->front; tpCamera->front = camera->front;
tpCamera->right = camera->right; tpCamera->right = camera->right;
@ -366,7 +366,7 @@ voxel* PlayerController::updateSelection(float maxDistance) {
auto camera = player.fpCamera.get(); auto camera = player.fpCamera.get();
auto& selection = player.selection; auto& selection = player.selection;
glm::vec3 end; worldvec3 end;
glm::ivec3 iend; glm::ivec3 iend;
glm::ivec3 norm; glm::ivec3 norm;
voxel* vox = chunks.rayCast( voxel* vox = chunks.rayCast(
@ -393,7 +393,7 @@ voxel* PlayerController::updateSelection(float maxDistance) {
)) { )) {
selection.entity = result->entity; selection.entity = result->entity;
selection.hitPosition = selection.hitPosition =
camera->position + camera->front * result->distance; camera->position + worldvec3(camera->front * result->distance);
selection.position = selection.hitPosition; selection.position = selection.hitPosition;
selection.actualPosition = selection.position; selection.actualPosition = selection.position;
selection.normal = result->normal; selection.normal = result->normal;
@ -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

@ -42,9 +42,7 @@ static audio::speakerid_t play_sound(
} }
return audio::play( return audio::play(
sound, sound,
glm::vec3( worldvec3(x, y, z),
static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)
),
relative, relative,
volume, volume,
pitch, pitch,
@ -75,11 +73,7 @@ static audio::speakerid_t play_stream(
if (stream) { if (stream) {
return audio::play( return audio::play(
audio::open_stream(std::move(stream), true), audio::open_stream(std::move(stream), true),
glm::vec3( worldvec3(x, y, z),
static_cast<float>(x),
static_cast<float>(y),
static_cast<float>(z)
),
relative, relative,
volume, volume,
pitch, pitch,
@ -96,15 +90,7 @@ static audio::speakerid_t play_stream(
file = paths.find(filename); file = paths.find(filename);
} }
return audio::play_stream( return audio::play_stream(
file, file, worldvec3(x, y, z), relative, volume, pitch, loop, channel
glm::vec3(
static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)
),
relative,
volume,
pitch,
loop,
channel
); );
} }
@ -277,9 +263,7 @@ static int l_audio_set_position(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);
speaker->setPosition(glm::vec3( speaker->setPosition(worldvec3(x, y, z));
static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)
));
} }
return 0; return 0;
} }

View file

@ -548,7 +548,7 @@ static int l_destruct(lua::State* L) {
static int l_raycast(lua::State* L) { static int l_raycast(lua::State* L) {
const auto& level = require_level(); const auto& level = require_level();
auto start = lua::tovec<3>(L, 1); auto start = lua::tovec<3, double>(L, 1);
auto dir = lua::tovec<3>(L, 2); auto dir = lua::tovec<3>(L, 2);
auto maxDistance = lua::tonumber(L, 3); auto maxDistance = lua::tonumber(L, 3);
@ -576,7 +576,7 @@ static int l_raycast(lua::State* L) {
if (luaStackSize >= 6) { if (luaStackSize >= 6) {
raycast.includeNonSelectable = lua::toboolean(L, 6); raycast.includeNonSelectable = lua::toboolean(L, 6);
} }
glm::vec3 end; worldvec3 end;
glm::ivec3 normal; glm::ivec3 normal;
glm::ivec3 iend; glm::ivec3 iend;
@ -589,7 +589,7 @@ static int l_raycast(lua::State* L) {
lua::createtable(L, 0, 5); lua::createtable(L, 0, 5);
} }
lua::pushvec3(L, end); lua::pushvec(L, end);
lua::setfield(L, "endpoint"); lua::setfield(L, "endpoint");
lua::pushvec3(L, normal); lua::pushvec3(L, normal);
@ -598,7 +598,7 @@ static int l_raycast(lua::State* L) {
lua::pushnumber(L, glm::distance(start, end)); lua::pushnumber(L, glm::distance(start, end));
lua::setfield(L, "length"); lua::setfield(L, "length");
lua::pushvec3(L, iend); lua::pushvec(L, iend);
lua::setfield(L, "iendpoint"); lua::setfield(L, "iendpoint");
lua::pushinteger(L, voxel->id); lua::pushinteger(L, voxel->id);

View file

@ -7,7 +7,7 @@
using namespace scripting; using namespace scripting;
static int l_wrap(lua::State* L) { static int l_wrap(lua::State* L) {
auto position = lua::tovec3(L, 1); auto position = lua::tovec<3, double>(L, 1);
std::string texture = lua::require_string(L, 2); std::string texture = lua::require_string(L, 2);
float emission = lua::isnumber(L, 3) ? lua::tonumber(L, 3) : 1.0f; float emission = lua::isnumber(L, 3) ? lua::tonumber(L, 3) : 1.0f;
glm::vec4 tint = glm::vec4 tint =
@ -31,7 +31,7 @@ static int l_unwrap(lua::State* L) {
static int l_set_pos(lua::State* L) { static int l_set_pos(lua::State* L) {
if (auto wrapper = renderer->blockWraps->get(lua::tointeger(L, 1))) { if (auto wrapper = renderer->blockWraps->get(lua::tointeger(L, 1))) {
wrapper->position = lua::tovec3(L, 2); wrapper->position = lua::tovec<3, double>(L, 2);
} }
return 0; return 0;
} }

View file

@ -47,11 +47,11 @@ static int l_name(lua::State* L) {
} }
static int getter_pos(lua::State* L, const Camera& camera) { static int getter_pos(lua::State* L, const Camera& camera) {
return lua::pushvec3(L, camera.position); return lua::pushvec(L, camera.position);
} }
static void setter_pos(lua::State* L, Camera& camera, int idx) { static void setter_pos(lua::State* L, Camera& camera, int idx) {
camera.position = lua::tovec<3>(L, idx); camera.position = lua::tovec<3, double>(L, idx);
} }
static int getter_rot(lua::State* L, const Camera& camera) { static int getter_rot(lua::State* L, const Camera& camera) {
@ -104,9 +104,11 @@ static int getter_up(lua::State* L, const Camera& camera) {
static int l_look_at(lua::State* L) { static int l_look_at(lua::State* L) {
size_t index = static_cast<size_t>(lua::tointeger(L, 1)); size_t index = static_cast<size_t>(lua::tointeger(L, 1));
auto& camera = *require_level().cameras.at(index); auto& camera = *require_level().cameras.at(index);
auto center = lua::tovec<3>(L, 2); auto center = lua::tovec<3, double>(L, 2);
auto matrix = glm::inverse( auto matrix = glm::inverse(
glm::lookAt(glm::vec3(), center - camera.position, glm::vec3(0, 1, 0)) glm::lookAt(
glm::vec3(), glm::vec3(center - camera.position), glm::vec3(0, 1, 0)
)
); );
if (lua::isnumber(L, 3)) { if (lua::isnumber(L, 3)) {
matrix = glm::mat4_cast(glm::slerp( matrix = glm::mat4_cast(glm::slerp(

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);
@ -160,9 +160,9 @@ static int l_push_ray(
lua::State* L, lua::State* L,
const std::optional<Entities::RaycastResult>& ray, const std::optional<Entities::RaycastResult>& ray,
blockid_t block, blockid_t block,
const glm::vec3& start, const worldvec3& start,
const glm::vec3& dir, const glm::vec3& dir,
const glm::vec3& end, const worldvec3& end,
const glm::ivec3& iend, const glm::ivec3& iend,
const glm::ivec3& normal const glm::ivec3& normal
) { ) {
@ -175,7 +175,7 @@ static int l_push_ray(
lua::createtable(L, 0, 6); lua::createtable(L, 0, 6);
} }
lua::pushvec3(L, ray ? (start + dir * ray->distance) : end); lua::pushvec(L, ray ? (start + worldvec3(dir * ray->distance)) : end);
lua::setfield(L, "endpoint"); lua::setfield(L, "endpoint");
lua::pushvec3(L, ray ? ray->normal : normal); lua::pushvec3(L, ray ? ray->normal : normal);
@ -184,7 +184,7 @@ static int l_push_ray(
lua::pushnumber(L, ray ? ray->distance : glm::distance(start, end)); lua::pushnumber(L, ray ? ray->distance : glm::distance(start, end));
lua::setfield(L, "length"); lua::setfield(L, "length");
lua::pushvec3(L, iend); lua::pushvec(L, iend);
lua::setfield(L, "iendpoint"); lua::setfield(L, "iendpoint");
lua::pushinteger(L, block); lua::pushinteger(L, block);
@ -202,14 +202,14 @@ static int l_push_ray(
static int l_raycast( static int l_raycast(
lua::State* L, lua::State* L,
const glm::vec3& start, const worldvec3& start,
const glm::vec3& dir, const glm::vec3& dir,
float maxDistance, float maxDistance,
const blocks_agent::RaycastSettings& voxelRaycast, const blocks_agent::RaycastSettings& voxelRaycast,
const Entities::RaycastSettings& entityRaycast, const Entities::RaycastSettings& entityRaycast,
bool entities bool entities
) { ) {
glm::vec3 end; worldvec3 end;
glm::ivec3 normal; glm::ivec3 normal;
glm::ivec3 iend; glm::ivec3 iend;
@ -276,7 +276,8 @@ static int l_world_raycast(lua::State* L) {
std::set<blockid_t> filteredBlocks {}; std::set<blockid_t> filteredBlocks {};
std::set<entitydefid_t> filteredEntities {}; std::set<entitydefid_t> filteredEntities {};
glm::vec3 start, dir; worldvec3 start;
glm::vec3 dir;
float maxDistance; float maxDistance;
bool entities = true; bool entities = true;
@ -285,7 +286,7 @@ static int l_world_raycast(lua::State* L) {
} }
lua::requirefield(L, "start", 1); lua::requirefield(L, "start", 1);
start = lua::tovec3(L, -1); start = lua::tovec<3, double>(L, -1);
lua::requirefield(L, "dir", 1); lua::requirefield(L, "dir", 1);
dir = lua::tovec3(L, -1); dir = lua::tovec3(L, -1);
@ -341,7 +342,7 @@ static int l_raycast(lua::State* L) {
std::set<blockid_t> filteredBlocks {}; std::set<blockid_t> filteredBlocks {};
const int luaStackSize = lua::gettop(L); const int luaStackSize = lua::gettop(L);
glm::vec3 start = lua::tovec<3>(L, 1); worldvec3 start = lua::tovec<3, double>(L, 1);
glm::vec3 dir = lua::tovec<3>(L, 2); glm::vec3 dir = lua::tovec<3>(L, 2);
float maxDistance = lua::tonumber(L, 3); float maxDistance = lua::tonumber(L, 3);

View file

@ -24,8 +24,8 @@ static int l_save_fragment(lua::State* L) {
} }
static int l_create_fragment(lua::State* L) { static int l_create_fragment(lua::State* L) {
auto pointA = lua::tovec<3>(L, 1); auto pointA = lua::tovec<3, double>(L, 1);
auto pointB = lua::tovec<3>(L, 2); auto pointB = lua::tovec<3, double>(L, 2);
bool crop = lua::toboolean(L, 3); bool crop = lua::toboolean(L, 3);
bool saveEntities = lua::toboolean(L, 4); bool saveEntities = lua::toboolean(L, 4);

View file

@ -9,7 +9,7 @@ using namespace scripting;
static int l_emit(lua::State* L) { static int l_emit(lua::State* L) {
EmitterOrigin origin; EmitterOrigin origin;
if (lua::istable(L, 1)) { if (lua::istable(L, 1)) {
origin = lua::tovec3(L, 1); origin = lua::tovec<3, double>(L, 1);
} else { } else {
origin = static_cast<entityid_t>(lua::tointeger(L, 1)); origin = static_cast<entityid_t>(lua::tointeger(L, 1));
} }
@ -47,8 +47,8 @@ static int l_get_origin(lua::State* L) {
u64id_t id = lua::touinteger(L, 1); u64id_t id = lua::touinteger(L, 1);
if (auto emitter = renderer->particles->getEmitter(id)) { if (auto emitter = renderer->particles->getEmitter(id)) {
const auto& origin = emitter->getOrigin(); const auto& origin = emitter->getOrigin();
if (auto pos = std::get_if<glm::vec3>(&origin)) { if (auto pos = std::get_if<worldvec3>(&origin)) {
return lua::pushvec3(L, *pos); return lua::pushvec(L, *pos);
} else if (auto entityid = std::get_if<entityid_t>(&origin)) { } else if (auto entityid = std::get_if<entityid_t>(&origin)) {
return lua::pushinteger(L, *entityid); return lua::pushinteger(L, *entityid);
} }
@ -60,7 +60,7 @@ static int l_set_origin(lua::State* L) {
u64id_t id = lua::touinteger(L, 1); u64id_t id = lua::touinteger(L, 1);
if (auto emitter = renderer->particles->getEmitter(id)) { if (auto emitter = renderer->particles->getEmitter(id)) {
if (lua::istable(L, 2)) { if (lua::istable(L, 2)) {
emitter->setOrigin(lua::tovec3(L, 2)); emitter->setOrigin(lua::tovec<3, double>(L, 2));
} else { } else {
emitter->setOrigin(static_cast<entityid_t>(lua::tointeger(L, 2))); emitter->setOrigin(static_cast<entityid_t>(lua::tointeger(L, 2)));
} }

View file

@ -36,7 +36,7 @@ static int l_is_enabled(lua::State* L) {
static int push_route(lua::State* L, const voxels::Route& route) { static int push_route(lua::State* L, const voxels::Route& route) {
lua::createtable(L, route.nodes.size(), 1); lua::createtable(L, route.nodes.size(), 1);
for (int i = 0; i < route.nodes.size(); i++) { for (int i = 0; i < route.nodes.size(); i++) {
lua::pushvec3(L, route.nodes[i].pos); lua::pushvec(L, route.nodes[i].pos);
lua::rawseti(L, i + 1); lua::rawseti(L, i + 1);
} }
lua::pushinteger(L, route.totalVisited); lua::pushinteger(L, route.totalVisited);
@ -46,8 +46,8 @@ static int push_route(lua::State* L, const voxels::Route& route) {
static int l_make_route(lua::State* L) { static int l_make_route(lua::State* L) {
if (auto agent = get_agent(L)) { if (auto agent = get_agent(L)) {
auto start = lua::tovec3(L, 2); auto start = lua::tovec<3, double>(L, 2);
auto target = lua::tovec3(L, 3); auto target = lua::tovec<3, double>(L, 3);
agent->state = {}; agent->state = {};
agent->start = glm::floor(start); agent->start = glm::floor(start);
agent->target = target; agent->target = target;
@ -62,8 +62,8 @@ static int l_make_route(lua::State* L) {
static int l_make_route_async(lua::State* L) { static int l_make_route_async(lua::State* L) {
if (auto agent = get_agent(L)) { if (auto agent = get_agent(L)) {
auto start = lua::tovec3(L, 2); auto start = lua::tovec<3, double>(L, 2);
auto target = lua::tovec3(L, 3); auto target = lua::tovec<3, double>(L, 3);
agent->state = {}; agent->state = {};
agent->start = glm::floor(start); agent->start = glm::floor(start);
agent->target = target; agent->target = target;

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

@ -6,7 +6,7 @@
using namespace scripting; using namespace scripting;
static int l_show(lua::State* L) { static int l_show(lua::State* L) {
auto position = lua::tovec3(L, 1); auto position = lua::tovec<3, double>(L, 1);
auto text = lua::require_wstring(L, 2); auto text = lua::require_wstring(L, 2);
auto preset = lua::tovalue(L, 3); auto preset = lua::tovalue(L, 3);
auto extension = lua::tovalue(L, 4); auto extension = lua::tovalue(L, 4);
@ -47,7 +47,7 @@ static int l_get_pos(lua::State* L) {
} }
static int l_set_pos(lua::State* L) { static int l_set_pos(lua::State* L) {
if (auto note = renderer->texts->get(lua::tointeger(L, 1))) { if (auto note = renderer->texts->get(lua::tointeger(L, 1))) {
note->setPosition(lua::tovec3(L, 2)); note->setPosition(lua::tovec<3, double>(L, 2));
} }
return 0; return 0;
} }

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

@ -1,5 +1,7 @@
#pragma once #pragma once
#include "typedefs.hpp"
#include <stdint.h> #include <stdint.h>
#include <ctime> #include <ctime>
@ -17,6 +19,10 @@ namespace util {
constexpr inline float EPSILON = 1e-6f; constexpr inline float EPSILON = 1e-6f;
inline glm::vec3 to_local(const worldvec3& pos, const glm::ivec3& origin) {
return glm::vec3(pos - worldvec3(origin));
}
class PseudoRandom { class PseudoRandom {
uint32_t seed; uint32_t seed;

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
@ -159,7 +159,7 @@ void Entities::loadEntity(const dv::value& map, Entity& entity) {
} }
std::optional<Entities::RaycastResult> Entities::rayCast( std::optional<Entities::RaycastResult> Entities::rayCast(
glm::vec3 start, worldvec3 start,
glm::vec3 dir, glm::vec3 dir,
float maxDistance, float maxDistance,
const RaycastSettings& settings const RaycastSettings& settings
@ -187,7 +187,11 @@ std::optional<Entities::RaycastResult> Entities::rayCast(
glm::ivec3 normal; glm::ivec3 normal;
double distance; double distance;
if (ray.intersectAABB( if (ray.intersectAABB(
glm::vec3(), hitbox.getAABB(), maxDistance, normal, distance hitbox.position,
AABB(-hitbox.halfsize, hitbox.halfsize),
maxDistance,
normal,
distance
) > RayRelation::None) { ) > RayRelation::None) {
foundUID = eid.uid; foundUID = eid.uid;
foundNormal = normal; foundNormal = normal;
@ -268,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);
@ -405,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;
@ -417,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
@ -84,7 +84,7 @@ public:
/// @param maxDistance Max ray length /// @param maxDistance Max ray length
/// @return An optional structure containing entity, normal and distance /// @return An optional structure containing entity, normal and distance
std::optional<RaycastResult> rayCast( std::optional<RaycastResult> rayCast(
glm::vec3 start, worldvec3 start,
glm::vec3 dir, glm::vec3 dir,
float maxDistance, float maxDistance,
const RaycastSettings& settings const RaycastSettings& settings
@ -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

@ -38,7 +38,7 @@ struct CursorSelection {
glm::ivec3 position {}; glm::ivec3 position {};
glm::ivec3 actualPosition {}; glm::ivec3 actualPosition {};
glm::ivec3 normal {}; glm::ivec3 normal {};
glm::vec3 hitPosition; worldvec3 hitPosition;
entityid_t entity = ENTITY_NONE; entityid_t entity = ENTITY_NONE;
}; };
@ -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

@ -2,6 +2,7 @@
#include <memory> #include <memory>
#include <cstdint> #include <cstdint>
#include <glm/fwd.hpp>
using scriptenv = std::shared_ptr<int>; using scriptenv = std::shared_ptr<int>;
@ -12,6 +13,9 @@ using integer_t = int64_t;
/// @brief dynamic floating-point type (64 bit floating point) /// @brief dynamic floating-point type (64 bit floating point)
using number_t = double; using number_t = double;
/// @brief position in the world (64 bit floating point components)
using worldvec3 = glm::dvec3;
using uint = unsigned int; using uint = unsigned int;
using u64id_t = uint64_t; using u64id_t = uint64_t;

View file

@ -52,7 +52,7 @@ voxel& Chunks::require(int32_t x, int32_t y, int32_t z) const {
return blocks_agent::require(*this, x, y, z); return blocks_agent::require(*this, x, y, z);
} }
const AABB* Chunks::isObstacleAt(float x, float y, float z) const { const AABB* Chunks::isObstacleAt(double x, double y, double z) const {
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);
@ -211,10 +211,10 @@ void Chunks::set(
} }
voxel* Chunks::rayCast( voxel* Chunks::rayCast(
const glm::vec3& start, const worldvec3& start,
const glm::vec3& dir, const glm::vec3& dir,
float maxDist, float maxDist,
glm::vec3& end, worldvec3& end,
glm::ivec3& norm, glm::ivec3& norm,
glm::ivec3& iend, glm::ivec3& iend,
const blocks_agent::RaycastSettings& settings const blocks_agent::RaycastSettings& settings
@ -224,12 +224,12 @@ voxel* Chunks::rayCast(
); );
} }
glm::vec3 Chunks::rayCastToObstacle( worldvec3 Chunks::rayCastToObstacle(
const glm::vec3& start, const glm::vec3& dir, float maxDist const worldvec3& start, const glm::vec3& dir, float maxDist
) const { ) const {
const float px = start.x; const double px = start.x;
const float py = start.y; const double py = start.y;
const float pz = start.z; const double pz = start.z;
float dx = dir.x; float dx = dir.x;
float dy = dir.y; float dy = dir.y;
@ -286,11 +286,11 @@ glm::vec3 Chunks::rayCastToObstacle(
norm, norm,
distance distance
) > RayRelation::None) { ) > RayRelation::None) {
return start + (dir * glm::vec3(distance)); return start + worldvec3(dir) * distance;
} }
} }
} else { } else {
return glm::vec3(px + t * dx, py + t * dy, pz + t * dz); return worldvec3(px + t * dx, py + t * dy, pz + t * dz);
} }
} }
} }
@ -316,7 +316,7 @@ glm::vec3 Chunks::rayCastToObstacle(
} }
} }
} }
return glm::vec3(px + maxDist * dx, py + maxDist * dy, pz + maxDist * dz); return worldvec3(px + maxDist * dx, py + maxDist * dy, pz + maxDist * dz);
} }
void Chunks::setCenter(int32_t x, int32_t z) { void Chunks::setCenter(int32_t x, int32_t z) {

View file

@ -110,22 +110,22 @@ public:
void setRotation(int32_t x, int32_t y, int32_t z, uint8_t rotation); void setRotation(int32_t x, int32_t y, int32_t z, uint8_t rotation);
voxel* rayCast( voxel* rayCast(
const glm::vec3& start, const worldvec3& start,
const glm::vec3& dir, const glm::vec3& dir,
float maxLength, float maxLength,
glm::vec3& end, worldvec3& end,
glm::ivec3& norm, glm::ivec3& norm,
glm::ivec3& iend, glm::ivec3& iend,
const blocks_agent::RaycastSettings& settings const blocks_agent::RaycastSettings& settings
) const; ) const;
glm::vec3 rayCastToObstacle( worldvec3 rayCastToObstacle(
const glm::vec3& start, const glm::vec3& dir, float maxDist const worldvec3& start, const glm::vec3& dir, float maxDist
) const; ) const;
const AABB* isObstacleAt(float x, float y, float z) const; const AABB* isObstacleAt(double x, double y, double z) const;
const AABB* isObstacleAt(const glm::vec3& pos) const { const AABB* isObstacleAt(const worldvec3& pos) const {
return isObstacleAt(pos.x, pos.y, pos.z); return isObstacleAt(pos.x, pos.y, pos.z);
} }

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

@ -217,18 +217,18 @@ bool blocks_agent::set(
template <class Storage> template <class Storage>
static inline voxel* raycast_blocks( static inline voxel* raycast_blocks(
const Storage& chunks, const Storage& chunks,
const glm::vec3& start, const worldvec3& start,
const glm::vec3& dir, const glm::vec3& dir,
float maxDist, float maxDist,
glm::vec3& end, worldvec3& end,
glm::ivec3& norm, glm::ivec3& norm,
glm::ivec3& iend, glm::ivec3& iend,
const RaycastSettings& settings const RaycastSettings& settings
) { ) {
const auto& blocks = chunks.getContentIndices().blocks; const auto& blocks = chunks.getContentIndices().blocks;
float px = start.x; double px = start.x;
float py = start.y; double py = start.y;
float pz = start.z; double pz = start.z;
float dx = dir.x; float dx = dir.x;
float dy = dir.y; float dy = dir.y;
@ -271,7 +271,7 @@ static inline voxel* raycast_blocks(
(def.selectable || includeNonSelectable) && (def.selectable || includeNonSelectable) &&
((filter == nullptr || filter->find(def.rt.id) == filter->end()) == ((filter == nullptr || filter->find(def.rt.id) == filter->end()) ==
settings.blocksFilterExcludeMode)) { settings.blocksFilterExcludeMode)) {
end = start + t * dir; end = start + worldvec3(t * dir);
iend = {ix, iy, iz}; iend = {ix, iy, iz};
if (!def.rt.solid) { if (!def.rt.solid) {
@ -301,7 +301,7 @@ static inline voxel* raycast_blocks(
hit = true; hit = true;
distance = boxDistance; distance = boxDistance;
norm = boxNorm; norm = boxNorm;
end = start + (dir * glm::vec3(distance)); end = start + worldvec3(dir) * distance;
} }
} }
@ -342,17 +342,17 @@ static inline voxel* raycast_blocks(
} }
} }
iend = {ix, iy, iz}; iend = {ix, iy, iz};
end = start + t * dir; end = start + worldvec3(t * dir);
norm = {0, 0, 0}; norm = {0, 0, 0};
return nullptr; return nullptr;
} }
voxel* blocks_agent::raycast( voxel* blocks_agent::raycast(
const Chunks& chunks, const Chunks& chunks,
const glm::vec3& start, const worldvec3& start,
const glm::vec3& dir, const glm::vec3& dir,
float maxDist, float maxDist,
glm::vec3& end, worldvec3& end,
glm::ivec3& norm, glm::ivec3& norm,
glm::ivec3& iend, glm::ivec3& iend,
const RaycastSettings& settings const RaycastSettings& settings
@ -362,10 +362,10 @@ voxel* blocks_agent::raycast(
voxel* blocks_agent::raycast( voxel* blocks_agent::raycast(
const GlobalChunks& chunks, const GlobalChunks& chunks,
const glm::vec3& start, const worldvec3& start,
const glm::vec3& dir, const glm::vec3& dir,
float maxDist, float maxDist,
glm::vec3& end, worldvec3& end,
glm::ivec3& norm, glm::ivec3& norm,
glm::ivec3& iend, glm::ivec3& iend,
const RaycastSettings& settings const RaycastSettings& settings

View file

@ -447,10 +447,10 @@ struct RaycastSettings {
/// @return voxel pointer or nullptr /// @return voxel pointer or nullptr
voxel* raycast( voxel* raycast(
const Chunks& chunks, const Chunks& chunks,
const glm::vec3& start, const worldvec3& start,
const glm::vec3& dir, const glm::vec3& dir,
float maxDist, float maxDist,
glm::vec3& end, worldvec3& end,
glm::ivec3& norm, glm::ivec3& norm,
glm::ivec3& iend, glm::ivec3& iend,
const RaycastSettings& settings const RaycastSettings& settings
@ -469,10 +469,10 @@ voxel* raycast(
/// @return voxel pointer or nullptr /// @return voxel pointer or nullptr
voxel* raycast( voxel* raycast(
const GlobalChunks& chunks, const GlobalChunks& chunks,
const glm::vec3& start, const worldvec3& start,
const glm::vec3& dir, const glm::vec3& dir,
float maxDist, float maxDist,
glm::vec3& end, worldvec3& end,
glm::ivec3& norm, glm::ivec3& norm,
glm::ivec3& iend, glm::ivec3& iend,
const RaycastSettings& settings const RaycastSettings& settings
@ -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

@ -3,7 +3,9 @@
#include <cmath> #include <cmath>
#include <glm/ext.hpp> #include <glm/ext.hpp>
Camera::Camera(glm::vec3 position, float fov) : fov(fov), position(position) { inline constexpr double ORIGIN_STEP = 1024.0;
Camera::Camera(worldvec3 position, float fov) : fov(fov), position(position) {
updateVectors(); updateVectors();
} }
@ -40,17 +42,24 @@ glm::mat4 Camera::getProjection() const {
} }
} }
glm::ivec3 Camera::getOrigin() const {
return glm::ivec3(
std::round(position.x / ORIGIN_STEP) * ORIGIN_STEP,
0,
std::round(position.z / ORIGIN_STEP) * ORIGIN_STEP
);
}
glm::vec3 Camera::getLocalPosition() const {
return glm::vec3(position - worldvec3(getOrigin()));
}
glm::mat4 Camera::getView(bool pos) const { glm::mat4 Camera::getView(bool pos) const {
glm::vec3 camera_pos = this->position; glm::mat4 view = glm::lookAt(glm::vec3(0.0f), front, up);
if (!pos) { if (pos) {
camera_pos = glm::vec3(0.0f); view = glm::translate(view, -getLocalPosition());
}
if (perspective) {
return glm::lookAt(camera_pos, camera_pos + front, up);
} else {
return glm::lookAt(camera_pos, camera_pos + front, up);
//return glm::translate(glm::mat4(1.0f), camera_pos);
} }
return view;
} }
glm::mat4 Camera::getProjView(bool pos) const { glm::mat4 Camera::getProjView(bool pos) const {

View file

@ -1,5 +1,7 @@
#pragma once #pragma once
#include "typedefs.hpp"
#define GLM_FORCE_RADIANS #define GLM_FORCE_RADIANS
#include <glm/glm.hpp> #include <glm/glm.hpp>
@ -12,7 +14,7 @@ public:
glm::vec3 right {}; glm::vec3 right {};
glm::vec3 dir {}; glm::vec3 dir {};
glm::vec3 position {}; worldvec3 position {};
float zoom = 1.0f; float zoom = 1.0f;
glm::mat4 rotation {1.0f}; glm::mat4 rotation {1.0f};
@ -27,11 +29,16 @@ public:
Camera() { Camera() {
updateVectors(); updateVectors();
} }
Camera(glm::vec3 position, float fov); Camera(worldvec3 position, float fov);
void updateVectors(); void updateVectors();
void rotate(float x, float y, float z); void rotate(float x, float y, float z);
/// @brief Get origin of the rendering coordinate system: an integer point
/// near the camera, getView() is relative to it
glm::ivec3 getOrigin() const;
glm::vec3 getLocalPosition() const;
glm::mat4 getProjection() const; glm::mat4 getProjection() const;
glm::mat4 getView(bool position = true) const; glm::mat4 getView(bool position = true) const;
glm::mat4 getProjView(bool position = true) const; glm::mat4 getProjView(bool position = true) const;

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);
} }

30
test/physics/Hitbox.cpp Normal file
View file

@ -0,0 +1,30 @@
#include <gtest/gtest.h>
#include "physics/Hitbox.hpp"
TEST(Hitbox, AABBRelativeToOrigin) {
for (double coord : {0.0, 1e6, 3e7}) {
worldvec3 position(coord + 0.3, 64.25, -coord - 0.7);
Hitbox hitbox(
1, BodyType::DYNAMIC, position, glm::vec3(0.3f, 0.9f, 0.3f)
);
AABB aabb = hitbox.getAABB(glm::floor(position));
EXPECT_NEAR(aabb.a.x, 0.0f, 1e-6f) << "at " << coord;
EXPECT_NEAR(aabb.a.y, -0.65f, 1e-6f) << "at " << coord;
EXPECT_NEAR(aabb.a.z, 0.0f, 1e-6f) << "at " << coord;
EXPECT_NEAR(aabb.b.x, 0.6f, 1e-6f) << "at " << coord;
EXPECT_NEAR(aabb.b.y, 1.15f, 1e-6f) << "at " << coord;
EXPECT_NEAR(aabb.b.z, 0.6f, 1e-6f) << "at " << coord;
}
}
TEST(Hitbox, SetPosFarFromOrigin) {
worldvec3 position(3e7 + 0.3, 64.25, -3e7 - 0.7);
Hitbox hitbox(1, BodyType::DYNAMIC, {}, glm::vec3(0.3f, 0.9f, 0.3f));
hitbox.setPos(position);
EXPECT_EQ(hitbox.position, position);
EXPECT_EQ(hitbox.prevPosition, position);
hitbox.setPos(position + worldvec3(0.05, 0.0, 0.0));
EXPECT_EQ(hitbox.prevPosition, position);
}

52
test/window/Camera.cpp Normal file
View file

@ -0,0 +1,52 @@
#include <gtest/gtest.h>
#include <cmath>
#include <glm/ext.hpp>
#include "window/Camera.hpp"
TEST(Camera, ViewRotationFarFromOrigin) {
for (float coord : {0.0f, 1e5f, 1e6f, 3e7f}) {
for (bool rotated : {false, true}) {
Camera camera(glm::vec3(coord, 64.0f, coord), 1.0f);
if (rotated) {
camera.rotate(glm::radians(-20.0f), glm::radians(35.0f), 0.0f);
}
glm::mat4 rotation = camera.getView(false);
glm::mat4 view = camera.getView();
for (int col = 0; col < 4; col++) {
for (int row = 0; row < 4; row++) {
ASSERT_TRUE(std::isfinite(view[col][row]))
<< "at " << coord;
}
}
for (int col = 0; col < 3; col++) {
for (int row = 0; row < 3; row++) {
EXPECT_NEAR(rotation[col][row], view[col][row], 1e-5f)
<< "at " << coord << ", rotated " << rotated;
}
}
}
}
}
TEST(Camera, ViewRelativeToOrigin) {
for (double coord : {0.0, 500.3, -1e5 - 0.3, 1e6 + 0.3, 3e7 + 0.3}) {
Camera camera(worldvec3(coord, 64.0, -coord), 1.0f);
camera.rotate(glm::radians(-20.0f), glm::radians(35.0f), 0.0f);
worldvec3 origin = camera.getOrigin();
worldvec3 local = camera.getLocalPosition();
EXPECT_LE(glm::abs(local.x), 512.0) << "at " << coord;
EXPECT_LE(glm::abs(local.z), 512.0) << "at " << coord;
EXPECT_NEAR(camera.position.x, origin.x + local.x, 1e-4) << coord;
EXPECT_NEAR(camera.position.z, origin.z + local.z, 1e-4) << coord;
worldvec3 point = camera.position + worldvec3(camera.front) * 10.0;
glm::vec4 viewPoint =
camera.getView() * glm::vec4(glm::vec3(point - origin), 1.0f);
EXPECT_NEAR(viewPoint.x, 0.0f, 1e-3f) << "at " << coord;
EXPECT_NEAR(viewPoint.y, 0.0f, 1e-3f) << "at " << coord;
EXPECT_NEAR(viewPoint.z, -10.0f, 1e-3f) << "at " << coord;
}
}