Merge branch 'main' into main

This commit is contained in:
Astazium 2026-10-15 16:19:06 +03:00 • committed by GitHub
commit bf59e520a7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
109 changed files with 1908 additions and 474 deletions

View file

@ -1,10 +1,10 @@
project(VoxelEngineSrc)
project(VoxelCoreSrc)
file(GLOB_RECURSE headers ${CMAKE_CURRENT_SOURCE_DIR}/*.hpp)
file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
list(REMOVE_ITEM sources ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
add_library(VoxelEngineSrc STATIC ${sources} ${headers})
add_library(VoxelCoreSrc STATIC ${sources} ${headers})
find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)
@ -34,23 +34,23 @@ endif()
if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
find_package(vorbis REQUIRED)
set(LUAJIT_PACKAGE_DIR "${_VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}")
if(VCPKG_TARGET_TRIPLET MATCHES "static")
add_library(luajit STATIC IMPORTED)
set_target_properties(
luajit
PROPERTIES
IMPORTED_LOCATION
"$ENV{VCPKG_ROOT}/packages/luajit_${VCPKG_TARGET_TRIPLET}/lib/libluajit-5.1.a"
"${LUAJIT_PACKAGE_DIR}/lib/libluajit-5.1.a"
INTERFACE_INCLUDE_DIRECTORIES
"$ENV{VCPKG_ROOT}/packages/luajit_${VCPKG_TARGET_TRIPLET}/include/"
"${LUAJIT_PACKAGE_DIR}/include/"
)
else()
set(LUAJIT_PACKAGE_DIR "$ENV{VCPKG_ROOT}/packages/luajit_${VCPKG_TARGET_TRIPLET}")
if(EXISTS "$ENV{VCPKG_ROOT}/packages/luajit_${VCPKG_TARGET_TRIPLET}/include/luajit-2.1")
set(LUAJIT_INCLUDE_DIR "$ENV{VCPKG_ROOT}/packages/luajit_${VCPKG_TARGET_TRIPLET}/include/luajit-2.1")
if(EXISTS "${LUAJIT_PACKAGE_DIR}/include/luajit-2.1")
set(LUAJIT_INCLUDE_DIR "${LUAJIT_PACKAGE_DIR}/include/luajit-2.1")
else()
set(LUAJIT_INCLUDE_DIR "$ENV{VCPKG_ROOT}/packages/luajit_${VCPKG_TARGET_TRIPLET}/include/luajit")
set(LUAJIT_INCLUDE_DIR "${LUAJIT_PACKAGE_DIR}/include/luajit")
endif()
add_library(luajit SHARED IMPORTED)
@ -58,9 +58,9 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
luajit
PROPERTIES
IMPORTED_LOCATION
"$ENV{VCPKG_ROOT}/packages/luajit_${VCPKG_TARGET_TRIPLET}/bin/lua51.dll"
"${LUAJIT_PACKAGE_DIR}/bin/lua51.dll"
IMPORTED_IMPLIB
"$ENV{VCPKG_ROOT}/packages/luajit_${VCPKG_TARGET_TRIPLET}/lib/lua51.lib"
"${LUAJIT_PACKAGE_DIR}/lib/lua51.lib"
INTERFACE_INCLUDE_DIRECTORIES "${LUAJIT_INCLUDE_DIR}"
)
endif()
@ -77,10 +77,10 @@ else()
add_library(luajit::luajit ALIAS PkgConfig::luajit)
endif()
target_include_directories(VoxelEngineSrc PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_include_directories(VoxelCoreSrc PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(
VoxelEngineSrc
VoxelCoreSrc
PRIVATE glfw
OpenGL::GL
GLEW::GLEW
@ -98,7 +98,7 @@ target_link_libraries(
)
target_compile_options(
VoxelEngineSrc
VoxelCoreSrc
PUBLIC $<$<CXX_COMPILER_ID:MSVC>:
/utf-8
/MP
@ -136,7 +136,7 @@ target_compile_options(
>)
target_link_options(
VoxelEngineSrc
VoxelCoreSrc
PUBLIC
$<$<CXX_COMPILER_ID:GNU>:
-no-pie

View file

@ -198,6 +198,31 @@ static void perform_rect(const xmlelement& root, ModelBuilder& builder) {
} else {
normal = glm::cross(glm::normalize(right), glm::normalize(up));
}
auto cullFace = root.attr("cull-face", "back").getText();
if (cullFace == "front") {
normal *= -1.0f;
} else if (cullFace == "off") {
builder.addRect(
texture,
shading,
from + right * 0.5f + up * 0.5f,
right * 0.5f,
up * 0.5f,
normal,
region
);
builder.addRect(
texture,
shading,
from + right * 0.5f + up * 0.5f,
right * -0.5f,
up * -0.5f,
-normal,
region
);
return;
}
builder.addRect(
texture,
shading,
@ -246,6 +271,17 @@ static void perform_triangle(const xmlelement& root, ModelBuilder& builder) {
}
std::string texture = root.attr("texture", "$0").getText();
auto cullFace = root.attr("cull-face", "back").getText();
if (cullFace == "front") {
std::swap(pointB, pointC);
std::swap(uvs[1], uvs[2]);
normal *= -1.0f;
} else if (cullFace == "off") {
builder.addTriangle(texture, shading, pointA, pointB, pointC, normal, uvs[0], uvs[1], uvs[2]);
builder.addTriangle(texture, shading, pointA, pointC, pointB, -normal, uvs[0], uvs[2], uvs[1]);
return;
}
builder.addTriangle(texture, shading, pointA, pointB, pointC, normal, uvs[0], uvs[1], uvs[2]);
}

View file

@ -133,6 +133,9 @@ static model::Mesh load_mesh(
if (flags == FLAG_ZLIB) {
throw std::runtime_error("compression is not supported yet");
}
if (attributeCount <= 0) {
throw std::runtime_error("mesh must have at least one attribute");
}
std::vector<VertexAttribute> attributes;
for (int i = 0; i < attributeCount; i++) {
attributes.push_back(load_attribute(reader));

View file

@ -122,10 +122,16 @@ namespace {
std::vector<Glyph>& glyphs
) {
int size = canvas.getWidth() / 16;
const size_t end = (pageid + 1) * 256;
if (glyphs.size() < end) {
glyphs.resize(end);
}
for (int c = 0; c < 256; c++) {
int codepoint = pageid << 8 | c;
if (!renderGlyph(codepoint, bitmapDst)) {
glyphs.push_back(Glyph {0, size / 2});
glyphs[codepoint] = Glyph {0, size / 2};
continue;
}
@ -133,13 +139,10 @@ namespace {
Glyph glyph {
face->glyph->bitmap_top - size,
static_cast<int>(face->glyph->advance.x >> 6)
static_cast<int>(face->glyph->advance.x >> 6),
face->glyph->bitmap_left
};
if (codepoint < glyphs.size()) {
glyphs[codepoint] = std::move(glyph);
} else {
glyphs.push_back(std::move(glyph));
}
glyphs[codepoint] = glyph;
}
canvas.flipY();
}

View file

@ -86,3 +86,4 @@ inline const std::string SOUNDS_FOLDER = "sounds";
inline const std::string TEXTURES_FOLDER = "textures";
inline const std::string FONT_DEFAULT = "normal";
inline const std::string DEFAULT_PROJECT_PATH = "project";

View file

@ -8,7 +8,7 @@ using runnable = std::function<void()>;
template<class T> using supplier = std::function<T()>;
template<class T> using consumer = std::function<void(T)>;
using KeyCallback = std::function<bool()>;
using InputCallback = std::function<bool()>;
// data sources
using wstringsupplier = std::function<std::wstring()>;

View file

@ -132,7 +132,17 @@ void Engine::initialize(CoreParameters coreParameters) {
logger.info() << "engine runs in headless mode";
}
if (params.projectFolder.empty()) {
params.projectFolder = params.resFolder;
auto userDefProjectPath =
params.userFolder / std::filesystem::u8path(DEFAULT_PROJECT_PATH);
auto resDefProjectPath =
params.resFolder / std::filesystem::u8path(DEFAULT_PROJECT_PATH);
if (std::filesystem::is_directory(userDefProjectPath)) {
params.projectFolder = userDefProjectPath;
} else if (std::filesystem::is_directory(resDefProjectPath)) {
params.projectFolder = resDefProjectPath;
} else {
params.projectFolder = params.resFolder;
}
}
paths = std::make_unique<EnginePaths>(params);
loadProject();

View file

@ -6,12 +6,13 @@ class Time {
uint64_t frame = 0;
double lastTime = 0.0;
double delta = 0.0;
double timeMultiplier = 1.0;
public:
Time() {}
void update(double currentTime) {
frame++;
delta = currentTime - lastTime;
delta = (currentTime - lastTime) * timeMultiplier;
lastTime = currentTime;
}

View file

@ -271,11 +271,9 @@ void LevelScreen::draw(float delta) {
if (!hud->isPause()) {
scripting::on_entities_render(engine.getTime().getDelta());
}
renderer->renderFrame(ctx, camera, hudVisible, *postProcessing);
if (!hud->isPause()) {
scripting::on_frontend_render();
}
renderer->renderFrame(ctx, camera, hudVisible, *postProcessing);
if (hudVisible) {
hud->draw(ctx);

View file

@ -28,7 +28,10 @@ MenuScreen::~MenuScreen() = default;
void MenuScreen::onOpen() {
engine.getContentControl().resetContent({});
auto menu = engine.getGUI().getMenu();
auto& gui = engine.getGUI();
gui.setActiveFrame(gui::GUI::CORE_MAIN);
auto menu = gui.getMenu();
menu->reset();
}

View file

@ -29,6 +29,10 @@ Font::Font(
if (this->fontFile.has_value()) {
if (auto fontPtr = this->fontFile->lock()) {
monospace = fontPtr->isMonospace();
if (monospace && this->glyphs.size() > '0' &&
this->glyphs['0'].xAdvance > 0) {
glyphInterval = this->glyphs['0'].xAdvance;
}
}
}
}
@ -62,21 +66,13 @@ bool Font::isPrintableChar(uint codepoint) const {
int FontMetrics::calcWidth(std::wstring_view text, size_t offset, size_t length) const {
auto font = this->font.has_value() ? this->font->lock() : nullptr;
if (font == nullptr || font->isMonospace()) {
return std::min(text.length() - offset, length) * _glyphInterval;
if (font != nullptr) {
return font->calcWidth(text, offset, length);
}
int totalWidth = 0;
for (int i = offset; i < offset + length && i < text.length(); i++) {
auto codepoint = text[i];
if (!font->isPrintableChar(codepoint)) {
totalWidth += _glyphInterval;
} else if (auto glyph = font->getGlyph(codepoint)) {
totalWidth += glyph->xAdvance;
} else {
totalWidth += _glyphInterval;
}
if (offset >= text.length()) {
return 0;
}
return totalWidth;
return std::min(text.length() - offset, length) * _glyphInterval;
}
int Font::calcWidth(std::wstring_view text, size_t length) const {
@ -84,7 +80,24 @@ int Font::calcWidth(std::wstring_view text, size_t length) const {
}
int Font::calcWidth(std::wstring_view text, size_t offset, size_t length) const {
return std::min(text.length()-offset, length) * glyphInterval;
if (offset >= text.length()) {
return 0;
}
size_t end = offset + std::min(text.length() - offset, length);
int width = 0;
for (size_t i = offset; i < end; i++) {
width += getAdvance(text[i]);
}
return width;
}
int Font::getAdvance(uint codepoint) const {
if (isPrintableChar(codepoint)) {
if (auto glyph = getGlyph(codepoint)) {
return glyph->xAdvance;
}
}
return glyphInterval;
}
static inline void draw_glyph(
@ -176,7 +189,7 @@ static inline void draw_text(
int y = 0;
bool hasLines = false;
float baseAdvance = glm::length(right);
const float cellAdvance = interval * font.getLineHeight();
do {
for (size_t i = 0; i < text.length(); i++) {
@ -193,12 +206,11 @@ static inline void draw_text(
continue;
}
int yOffset = 0;
float advance = baseAdvance;
int xOffset = 0;
float advance = font.getAdvance(c) / cellAdvance;
if (auto glyph = font.getGlyph(c)) {
yOffset = glyph->yOffset;
advance = glyph->xAdvance /
static_cast<float>(font.getLineHeight()) * 2.0f *
baseAdvance;
xOffset = glyph->xOffset;
}
uint charpage = c >> 8;
if (charpage == page){
@ -207,7 +219,7 @@ static inline void draw_text(
batch,
pos,
glm::vec2(
x,
x + xOffset / cellAdvance,
y - yOffset * (is3d ? -1 : 1) /
static_cast<float>(font.getLineHeight())
),
@ -221,7 +233,7 @@ static inline void draw_text(
else if (charpage > page && charpage < next){
next = charpage;
}
x += advance / baseAdvance;
x += advance;
}
page = next;
next = MAX_CODEPAGES;
@ -325,27 +337,26 @@ std::unique_ptr<Font> Font::createBitmapFont(
return std::make_unique<Font>(std::move(textures), std::move(glyphs), res, 4);
}
const Glyph* Font::getGlyph(int codepoint) {
const Glyph* Font::getGlyph(int codepoint) const {
if (codepoint < 0) {
return nullptr;
}
if (codepoint < glyphs.size()) {
const int codepage = codepoint >> 8;
if (codepoint < glyphs.size() &&
(!fontFile.has_value() ||
(codepage < pages.size() && pages[codepage]))) {
return &glyphs.at(codepoint);
}
if (!this->fontFile.has_value() || this->fontFile->expired()) {
return nullptr;
}
int codepage = codepoint >> 8;
if (codepage >= 1024) {
return nullptr;
}
if (glyphs.size() < (codepage << 8)) {
glyphs.resize(codepage << 8);
}
auto fontFile = this->fontFile->lock();
if (pages.size() <= codepage) {
pages.resize(codepage);
pages.resize(codepage + 1);
}
pages.push_back(fontFile->renderPage(codepage, glyphs, lineHeight));
pages[codepage] = fontFile->renderPage(codepage, glyphs, lineHeight);
return &glyphs.at(codepoint);
}

View file

@ -26,6 +26,7 @@ namespace vector_fonts {
struct Glyph {
int yOffset;
int xAdvance;
int xOffset = 0;
};
class Font {
@ -56,6 +57,10 @@ public:
/// @return pixel width of the substring
int calcWidth(std::wstring_view text, size_t offset, size_t length) const;
/// @brief Get the horizontal advance of a character in pixels
/// @param codepoint character unicode codepoint
int getAdvance(uint codepoint) const;
/// @brief Check if character is visible (non-whitespace)
/// @param codepoint character unicode codepoint
bool isPrintableChar(uint codepoint) const;
@ -86,7 +91,7 @@ public:
return {std::nullopt, lineHeight, yoffset, glyphInterval};
}
const Glyph* getGlyph(int codepoint);
const Glyph* getGlyph(int codepoint) const;
static std::unique_ptr<Font> createBitmapFont(
std::vector<std::unique_ptr<ImageData>> pages
@ -96,7 +101,7 @@ private:
int yoffset;
int glyphInterval;
bool monospace = true;
std::vector<std::unique_ptr<Texture>> pages;
std::vector<Glyph> glyphs;
mutable std::vector<std::unique_ptr<Texture>> pages;
mutable std::vector<Glyph> glyphs;
std::optional<std::weak_ptr<vector_fonts::FontFile>> fontFile;
};

View file

@ -113,8 +113,6 @@ static inline auto shader_deleter = [](GLuint* shader) {
delete shader;
};
inline const uint GL_LOG_LEN = 512;
// shader should be deleted after shader program linking
using glshader = std::unique_ptr<GLuint, decltype(shader_deleter)>;
@ -125,12 +123,14 @@ glshader compile_shader(GLenum type, const GLchar* source, const std::string& fi
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
GLchar infoLog[GL_LOG_LEN];
glGetShaderInfoLog(shader, GL_LOG_LEN, nullptr, infoLog);
GLint infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
auto infoLog = std::make_unique<GLchar[]>(infoLogLength);
glGetShaderInfoLog(shader, infoLogLength, nullptr, infoLog.get());
glDeleteShader(shader);
throw std::runtime_error(
"vertex shader compilation failed (" + file + "):\n" +
std::string(infoLog)
std::string(infoLog.get(), infoLogLength)
);
}
return glshader(new GLuint(shader), shader_deleter); //-V508
@ -172,10 +172,14 @@ static GLuint compile_program(
glGetProgramiv(program, GL_LINK_STATUS, &success);
if (!success) {
GLchar infoLog[GL_LOG_LEN];
glGetProgramInfoLog(program, GL_LOG_LEN, nullptr, infoLog);
GLint infoLogLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
auto infoLog = std::make_unique<GLchar[]>(infoLogLength);
glGetProgramInfoLog(program, infoLogLength, nullptr, infoLog.get());
glDeleteProgram(program);
throw std::runtime_error(
"shader program linking failed:\n" + std::string(infoLog)
"shader program linking failed:\n" +
std::string(infoLog.get(), infoLogLength)
);
}
return program;

View file

@ -22,7 +22,7 @@ static debug::Logger logger("chunks-render");
size_t ChunksRenderer::visibleChunks = 0;
static constexpr inline size_t MAX_CHUNKS_ENQUEUED_IN_FRAME = 4;
static constexpr inline size_t MAX_CHUNKS_ENQUEUED_IN_FRAME = 64;
class RendererWorker : public util::Worker<RendererJob, RendererResult> {
BlocksRenderer renderer;
@ -197,8 +197,7 @@ void ChunksRenderer::update() {
int loadDistance = settings.chunks.loadDistance.get();
const int topN = 10;
int top = std::min<int>(meshBuildQueue.size(), topN);
int top = std::min<int>(meshBuildQueue.size(), MAX_CHUNKS_ENQUEUED_IN_FRAME);
for (int i = 0; i < top; i++) {
glm::ivec2 offset = meshBuildQueue[i];
size_t index =

View file

@ -8,6 +8,22 @@
#include "debug/Logger.hpp"
#include "core_defs.hpp"
inline constexpr uint FACE_WEST = FACE_MX;
inline constexpr uint FACE_EAST = FACE_PX;
inline constexpr uint FACE_BOTTOM = FACE_MY;
inline constexpr uint FACE_TOP = FACE_PY;
inline constexpr uint FACE_SOUTH = FACE_MZ;
inline constexpr uint FACE_NORTH = FACE_PZ;
inline constexpr std::array<uint8_t, 6> LEGACY_CUSTOM_MODEL_TEXTURE_ORDER = {
FACE_WEST,
FACE_EAST,
FACE_BOTTOM,
FACE_TOP,
FACE_SOUTH,
FACE_NORTH,
};
static debug::Logger logger("models-generator");
static void configure_textures(
@ -49,6 +65,21 @@ static inline UVRegion get_region_for(
return texreg.region;
}
static inline void map_legacy_box_textures(
const std::vector<std::string>& modelTextures,
size_t offset,
UVRegion (&boxtexfaces)[6],
const Assets& assets
) {
for (size_t i = 0; i < 6; ++i) {
const auto legacyFace = LEGACY_CUSTOM_MODEL_TEXTURE_ORDER[i];
boxtexfaces[legacyFace] = get_region_for(modelTextures[offset + i], assets);
}
boxtexfaces[FACE_TOP].scale(glm::vec2(-1, 1));
boxtexfaces[FACE_EAST].scale(glm::vec2(-1, 1));
boxtexfaces[FACE_NORTH].scale(glm::vec2(-1, 1));
}
void ModelsGenerator::prepareModel(
Assets& assets, const Block& def, Variant& variant, uint8_t variantId
) {
@ -120,16 +151,8 @@ model::Model ModelsGenerator::fromCustom(
for (size_t i = 0; i < modelBoxes.size(); i++) {
auto& mesh = model.addMesh("blocks:");
mesh.shading = lighting;
UVRegion boxtexfaces[6] = {
get_region_for(modelTextures[i * 6 + 5], assets),
get_region_for(modelTextures[i * 6 + 4], assets),
get_region_for(modelTextures[i * 6 + 3], assets),
get_region_for(modelTextures[i * 6 + 2], assets),
get_region_for(modelTextures[i * 6 + 1], assets),
get_region_for(modelTextures[i * 6 + 0], assets)
};
boxtexfaces[2].scale(glm::vec2(-1));
boxtexfaces[5].scale(glm::vec2(-1, 1));
UVRegion boxtexfaces[6] = {};
map_legacy_box_textures(modelTextures, i * 6, boxtexfaces, assets);
bool enabled[6] {1,1,1,1,1,1};
mesh.addBox(
@ -232,17 +255,14 @@ model::Model ModelsGenerator::loadCustomBlockModel(
modelBoxes.push_back(modelbox);
if (boxarr.size() == 7) {
for (uint j = 6; j < 12; j++) {
modelTextures.emplace_back(boxarr[6].asString());
}
const auto texture = boxarr[6].asString();
modelTextures.insert(modelTextures.end(), 6, texture);
} else if (boxarr.size() == 12) {
for (uint j = 6; j < 12; j++) {
modelTextures.emplace_back(boxarr[j].asString());
}
} else {
for (uint j = 6; j < 12; j++) {
modelTextures.emplace_back("notfound");
}
modelTextures.insert(modelTextures.end(), 6, "notfound");
}
}
}

View file

@ -135,6 +135,7 @@ WorldRenderer::WorldRenderer(
debugLines = std::make_unique<DebugLinesRenderer>(level);
cloudsRenderer = std::make_unique<CloudsRenderer>();
keepAlive(observe_setting(settings.graphics.enableFog, dirtySettings));
keepAlive(observe_setting(settings.graphics.advancedRender, dirtySettings));
keepAlive(observe_setting(settings.graphics.shadowsQuality, dirtySettings));
keepAlive(observe_setting(settings.graphics.ssao, dirtySettings));
@ -156,10 +157,12 @@ void WorldRenderer::refreshSettings() {
gbufferPipeline = graphics.advancedRender.get();
int shadowsQuality = graphics.shadowsQuality.get() * gbufferPipeline;
bool enableFog = graphics.enableFog.get();
shadowMapping->setQuality(shadowsQuality);
std::vector<std::string> defines;
if (shadowsQuality != 0) defines.emplace_back("ENABLE_SHADOWS");
if (enableFog) defines.emplace_back("ENABLE_FOG");
if (graphics.ssao.get()) defines.emplace_back("ENABLE_SSAO");
if (gbufferPipeline) defines.emplace_back("ADVANCED_RENDER");

View file

@ -25,14 +25,25 @@ void InlineFrame::setDocument(const std::shared_ptr<UiDocument>& document) {
if (document == nullptr) {
return;
}
auto newRoot = document->getRoot();
if (newRoot->hasParent()) {
return;
}
this->document = document;
this->root = document->getRoot();
this->root = std::move(newRoot);
add(root);
root->setSize(size);
gui.postRunnable([this]() {
scripting::on_ui_open(*this->document, {});
gui.postRunnable([weak = weak_from_this(), document]() {
auto node = weak.lock();
if (node == nullptr) {
return;
}
if (static_cast<InlineFrame&>(*node).document != document) {
return;
}
scripting::on_ui_open(*document, {});
});
}

View file

@ -120,7 +120,7 @@ void ModelViewer::draw(const DrawContext& pctx, const Assets& assets) {
if (size.x <= 0 || size.y <= 0) {
return;
}
fbo = std::make_unique<Framebuffer>(size.x, size.y);
fbo = std::make_unique<Framebuffer>(size.x, size.y, true);
}
fbo->resize(size.x, size.y);
{
@ -130,7 +130,13 @@ void ModelViewer::draw(const DrawContext& pctx, const Assets& assets) {
ctx.setViewport({size.x, size.y});
ctx.setDepthTest(true);
ctx.setCullFace(true);
GLfloat clearColor[4];
glGetFloatv(GL_COLOR_CLEAR_VALUE, clearColor);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
display::clear();
glClearColor(
clearColor[0], clearColor[1], clearColor[2], clearColor[3]
);
auto& ui3dShader = assets.require<Shader>("ui3d");
ui3dShader.use();

View file

@ -255,9 +255,9 @@ void TextBox::draw(const DrawContext& pctx, const Assets& assets) {
// drawing caret here
if (isFocused() && editable && static_cast<int>((time - caretLastMove) * 2) % 2 == 0) {
uint line = label->getLineByTextIndex(caret);
auto linestart = label->getTextLineOffset(line);
uint lcaret = caret - label->getTextLineOffset(line);
int width = rawTextCache.metrics.calcWidth(input.substr(linestart), 0, lcaret);
size_t lineStart = label->getTextLineOffset(line);
size_t lineCaret = caret - lineStart;
int width = rawTextCache.metrics.calcWidth(input, lineStart, lineCaret);
batch->rect(
lcoord.x + width,
@ -275,11 +275,13 @@ void TextBox::draw(const DrawContext& pctx, const Assets& assets) {
uint endLine = label->getLineByTextIndex(selectionEnd);
batch->setColor(glm::vec4(0.8f, 0.9f, 1.0f, 0.25f));
size_t startLineOffset = label->getTextLineOffset(startLine);
size_t endLineOffset = label->getTextLineOffset(endLine);
int start = rawTextCache.metrics.calcWidth(
labelText, 0, selectionStart - label->getTextLineOffset(startLine)
labelText, startLineOffset, selectionStart - startLineOffset
);
int end = rawTextCache.metrics.calcWidth(
labelText, 0, selectionEnd - label->getTextLineOffset(endLine)
labelText, endLineOffset, selectionEnd - endLineOffset
);
int lineY = label->getLineYOffset(startLine);
@ -352,6 +354,11 @@ void TextBox::draw(const DrawContext& pctx, const Assets& assets) {
}
void TextBox::drawBackground(const DrawContext& pctx, const Assets& assets) {
if (lineNumbersLabel->getFontName() != label->getFontName()) {
lineNumbersLabel->setFontName(label->getFontName());
}
lineNumbersLabel->setLineInterval(label->getLineInterval());
auto font = assets.getShared<Font>(label->getFontName());
if (font != nullptr) {
rawTextCache.prepare(font, font->getMetrics(), label->getSize().x);
@ -681,13 +688,19 @@ int TextBox::calcIndexAt(int x, int y) const {
uint line = label->getLineByYOffset(y - lcoord.y);
line = std::min(line, label->getLinesNumber() - 1);
size_t lineLength = getLineLength(line);
size_t lineStart = label->getTextLineOffset(line);
uint offset = 0;
while (lcoord.x + rawTextCache.metrics.calcWidth(labelText, 0, offset) < x &&
offset < lineLength - 1) {
while (offset < lineLength - 1) {
int width = rawTextCache.metrics.calcWidth(
labelText, lineStart, offset
);
if (lcoord.x + width >= x) {
break;
}
offset++;
}
return std::min(
offset + label->getTextLineOffset(line), labelText.length()
offset + lineStart, labelText.length()
);
}
@ -1224,9 +1237,12 @@ void TextBox::setCaret(size_t position) {
offset -= getSize().y;
scrolled(-glm::ceil(offset / static_cast<double>(scrollStep) + 0.5f));
}
int lcaret = caret - rawTextCache.getTextLineOffset(line);
int realoffset = rawTextCache.metrics.calcWidth(labelText, 0, lcaret) -
static_cast<int>(textOffset);
size_t lineStart = rawTextCache.getTextLineOffset(line);
size_t lineCaret = caret - lineStart;
int caretWidth = rawTextCache.metrics.calcWidth(
labelText, lineStart, lineCaret
);
int realoffset = caretWidth - static_cast<int>(textOffset);
if (realoffset - width > 0) {
setTextOffset(textOffset + realoffset - width);

View file

@ -60,6 +60,10 @@ bool UINode::isHover() const {
return hover;
}
bool UINode::hasParent() const {
return parent != nullptr;
}
void UINode::setParent(UINode* node) {
parent = node;
}
@ -376,14 +380,14 @@ void UINode::setGravity(Gravity gravity) {
}
}
bool UINode::isSubnodeOf(const UINode* node) {
bool UINode::isDescendantOf(const UINode* node) {
if (parent == nullptr) {
return false;
}
if (parent == node) {
return true;
}
return parent->isSubnodeOf(node);
return parent->isDescendantOf(node);
}
void UINode::getIndices(

View file

@ -176,6 +176,7 @@ namespace gui {
void setMouseOver(bool flag);
virtual void setParent(UINode* node);
bool hasParent() const;
UINode* getParent() const;
std::shared_ptr<UINode> getParentShared() const;
@ -290,7 +291,7 @@ namespace gui {
virtual void setGravity(Gravity gravity);
bool isSubnodeOf(const UINode* node);
bool isDescendantOf(const UINode* node);
/// @brief collect all nodes having id
static void getIndices(

View file

@ -180,6 +180,10 @@ std::unique_ptr<io::PathsGenerator> io::MemoryDevice::list(std::string_view path
}
io::MemoryDevice::Dir* io::MemoryDevice::createDir(std::string path) {
const auto& found = nodes.find(path);
if (found != nodes.end()) {
return found->second.get_if<Dir>();
}
io::path filePath = path;
io::path parent = filePath.parent();
auto parentDir = getDir(parent.string());
@ -195,6 +199,15 @@ io::MemoryDevice::Dir* io::MemoryDevice::createDir(std::string path) {
io::MemoryDevice::Node* io::MemoryDevice::createFile(
std::string path, util::Buffer<char>&& content
) {
const auto& found = nodes.find(path);
if (found != nodes.end()) {
auto& node = found->second;
if (!node.holds_alternative<File>()) {
return nullptr;
}
node.data = File {std::move(content)};
return &node;
}
io::path filePath = path;
io::path parent = filePath.parent();
auto dir = getDir(parent.string());

View file

@ -20,10 +20,29 @@ StdfsDevice::StdfsDevice(fs::path root, bool createDirectory)
<< ": " << ec.message();
}
}
absoluteRoot = fs::absolute(this->root).lexically_normal();
if (!absoluteRoot.has_filename() && absoluteRoot.has_relative_path()) {
absoluteRoot = absoluteRoot.parent_path();
}
}
fs::path StdfsDevice::resolve(std::string_view path) {
return root / fs::u8path(io::path(std::string(path)).normalized().string());
if (path.find_first_of(std::string_view("\0\\:", 3)) != std::string_view::npos) {
throw std::runtime_error("invalid path");
}
fs::path rel = fs::u8path(io::path(std::string(path)).normalized().string());
if (rel.has_root_name() || rel.has_root_directory()) {
throw std::runtime_error("absolute paths are not allowed");
}
fs::path full = (absoluteRoot / rel).lexically_normal();
fs::path inside = full.lexically_relative(absoluteRoot);
if (inside.empty() || *inside.begin() == "..") {
throw std::runtime_error("path escapes device root");
}
if (inside == ".") {
return absoluteRoot;
}
return full;
}
std::unique_ptr<std::ostream> StdfsDevice::write(std::string_view path) {
@ -90,17 +109,32 @@ bool StdfsDevice::mkdirs(std::string_view path) {
bool StdfsDevice::remove(std::string_view path) {
auto resolved = resolve(path);
return fs::remove(resolved);
if (resolved == absoluteRoot) {
throw std::runtime_error("unable to remove device root");
}
std::error_code ec;
bool removed = fs::remove(resolved, ec);
if (ec) {
logger.error() << "error removing " << resolved << ": " << ec.message();
}
return removed;
}
uint64_t StdfsDevice::removeAll(std::string_view path) {
auto resolved = resolve(path);
if (fs::exists(resolved)) {
logger.info() << "removeAll " << resolved;
return fs::remove_all(resolved);
} else {
if (resolved == absoluteRoot) {
throw std::runtime_error("unable to remove device root");
}
std::error_code ec;
auto removed = fs::remove_all(resolved, ec);
if (ec) {
logger.error() << "error removing " << resolved << ": " << ec.message();
return 0;
}
if (removed > 0) {
logger.info() << "removeAll " << resolved << ": " << removed;
}
return removed;
}
class StdfsPathsGenerator : public PathsGenerator {

View file

@ -23,5 +23,6 @@ namespace io {
std::unique_ptr<PathsGenerator> list(std::string_view path) override;
private:
std::filesystem::path root;
std::filesystem::path absoluteRoot;
};
}

View file

@ -58,11 +58,20 @@ namespace {
}
uint32_t to_ms_dos_timestamp(const file_time_type& fileTime) {
// 1980-01-01 00:00, the earliest MS-DOS date
constexpr uint32_t DOS_EPOCH = (0 << 9 | 1 << 5 | 1) << 16;
if (fileTime == file_time_type::min()) {
return DOS_EPOCH;
}
auto timePoint = time_point_cast<system_clock::duration>(
fileTime - file_time_type::clock::now() + system_clock::now()
);
std::time_t timeT = system_clock::to_time_t(timePoint);
std::tm tm = *std::localtime(&timeT);
const std::tm* tmPtr = std::localtime(&timeT);
if (tmPtr == nullptr || tmPtr->tm_year < 80) {
return DOS_EPOCH;
}
const std::tm& tm = *tmPtr;
uint16_t date = (tm.tm_year - 80) << 9 | (tm.tm_mon + 1) << 5 | tm.tm_mday;
uint16_t time = (tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec / 2);
return (date << 16) | time;
@ -173,7 +182,12 @@ ZipFileDevice::ZipFileDevice(
entries[entry.fileName] = std::move(entry);
}
for (auto& [name, _] : entries) {
std::vector<std::string> names;
names.reserve(entries.size());
for (const auto& [name, _] : entries) {
names.push_back(name);
}
for (const auto& name : names) {
io::path path = name;
while (!(path = path.parent()).pathPart().empty()) {
@ -184,7 +198,6 @@ ZipFileDevice::ZipFileDevice(
entry.isDirectory = true;
entries[path.pathPart()] = entry;
}
break;
}
for (auto& [_, entry] : entries) {
@ -253,6 +266,9 @@ file_time_type ZipFileDevice::lastWriteTime(std::string_view path) {
}
bool ZipFileDevice::exists(std::string_view path) {
if (path.empty()) {
return true;
}
return entries.find(std::string(path)) != entries.end();
}
@ -441,7 +457,11 @@ static size_t write_zip(
void io::write_zip(const path& folder, const path& file) {
ByteBuilder central_dir;
auto out = io::write(file);
size_t entries = write_zip(folder.pathPart(), folder, *out, central_dir);
auto root = folder.pathPart();
if (!root.empty() && root.back() != '/') {
root += '/';
}
size_t entries = write_zip(root, folder, *out, central_dir);
size_t central_dir_offset = out->tellp();
out->write(reinterpret_cast<const char*>(central_dir.data()), central_dir.size());

View file

@ -152,6 +152,9 @@ std::vector<ubyte> io::read_bytes(const path& filename) {
std::string io::read_string(const path& filename) {
size_t size;
auto bytes = read_bytes(filename, size);
if (bytes == nullptr) {
throw std::runtime_error("could not read file " + filename.string());
}
return std::string((const char*)bytes.get(), size);
}

View file

@ -50,6 +50,19 @@ protected:
return c;
}
pos_type seekoff(
off_type off,
std::ios_base::seekdir way,
std::ios_base::openmode mode = std::ios_base::out
) override {
// only position query (tellp) is supported
if (off == 0 && way == std::ios_base::cur &&
(mode & std::ios_base::out)) {
return pos_type(off_type(size()));
}
return pos_type(off_type(-1));
}
std::streamsize xsputn(const char* s, std::streamsize count) override {
const std::streamsize avail = epptr() - pptr();

View file

@ -69,6 +69,7 @@ SettingsHandler::SettingsHandler(EngineSettings& settings) {
builder.add("padding", &settings.chunks.padding);
builder.addSection("graphics");
builder.add("enable-fog", &settings.graphics.enableFog);
builder.add("fog-curve", &settings.graphics.fogCurve);
builder.add("backlight", &settings.graphics.backlight);
builder.add("dense-render", &settings.graphics.denseRender);

View file

@ -104,6 +104,8 @@ void CameraControl::updateMouse(PlayerInput& input, int windowHeight) {
glm::vec3 CameraControl::updateCameraShaking(
const Hitbox& hitbox, float delta
) {
delta = glm::min(delta, 0.1f);
glm::vec3 offset {};
const float k = CAM_SHAKE_DELTA_K;
const float ov = CAM_SHAKE_OFFSET_Y;

View file

@ -165,6 +165,13 @@ static int l_container_set_interval(lua::State* L) {
static int l_move_into(lua::State* L) {
auto node = get_document_node(L, 1);
auto dest = get_document_node(L, 2);
if (dest.node == nullptr) {
return 0;
}
if (dest.node->isDescendantOf(node.node.get())) {
luaL_error(L, "unable to move element to its descendant");
return 0;
}
UINode::moveInto(
node.node, std::dynamic_pointer_cast<Container>(dest.node)
);

View file

@ -44,10 +44,13 @@ static int l_add_callback(lua::State* L) {
auto& input = engine->getInput();
if (pos != std::string::npos) {
std::string prefix = bindname.substr(0, pos);
auto prefix = std::string_view(bindname).substr(0, pos);
if (prefix == "key") {
auto key = input_util::keycode_from(bindname.substr(pos + 1));
handler = input.addKeyCallback(key, actual_callback);
} else if (prefix == "mouse") {
auto mouse = input_util::mousecode_from(bindname.substr(pos + 1));
handler = input.addMouseCallback(mouse, actual_callback);
}
}

View file

@ -266,8 +266,10 @@ static int l_peek(lua::State* L, network::Network& network) {
static int l_available(lua::State* L, network::Network& network) {
u64id_t id = lua::tointeger(L, 1);
if (auto connection = network.getConnection(id, false)) {
return lua::pushinteger(L, dynamic_cast<network::TcpConnection*>(connection)->available());
if (auto connection = dynamic_cast<network::ReadableConnection*>(
network.getConnection(id, false)
)) {
return lua::pushinteger(L, connection->available());
}
return 0;

View file

@ -30,7 +30,7 @@ static int push_xml(lua::State* L, const xml::xmlelement& elem) {
}
static std::unique_ptr<xml::xmlelement> toxml(lua::State* L) {
lua::getfield(L, TAG_ATTR);
lua::requirefield(L, TAG_ATTR);
auto tag = lua::require_lstring(L, -1);
lua::pop(L);
@ -39,6 +39,13 @@ static std::unique_ptr<xml::xmlelement> toxml(lua::State* L) {
for (int i = 0; i < length; i++) {
lua::rawgeti(L, i + 1);
if (lua::isstring(L, -1)) {
auto textElement = std::make_unique<xml::xmlelement>("#");
textElement->set("#", std::string(lua::require_lstring(L, -1)));
elem->add(std::move(textElement));
lua::pop(L);
continue;
}
elem->add(toxml(L));
lua::pop(L);
}

View file

@ -196,6 +196,10 @@ void lua::init_state(State* L, StateType stateType) {
if (stateType == StateType::GENERATOR) {
pushnil(L);
setglobal(L, "ffi");
static const char* removed_debug[] {
"getregistry", "getupvalue", "setupvalue", "getinfo", nullptr};
remove_lib_funcs(L, "debug", removed_debug);
}
}

View file

@ -263,7 +263,7 @@ runnable lua::create_runnable(State* L) {
};
}
KeyCallback lua::create_simple_handler(State* L) {
InputCallback lua::create_simple_handler(State* L) {
auto funcptr = create_lambda_handler(L);
return [=]() -> bool {
if (!get_from_registry(L, LAMBDAS_TABLE, *funcptr, false)) {

View file

@ -665,7 +665,7 @@ namespace lua {
}
runnable create_runnable(lua::State*);
KeyCallback create_simple_handler(lua::State*);
InputCallback create_simple_handler(lua::State*);
scripting::common_func create_lambda(lua::State*);
scripting::common_func create_lambda_nothrow(lua::State*);

View file

@ -99,14 +99,21 @@ template <typename T, T(tovalueFunc)(lua::State*, int)>
std::function<T()> create_supplier(
const scriptenv& env, const std::string& src, const std::string& file
) {
return [=]() {
return [=, errorLogged = false]() mutable {
lua::stackguard guard(lua::get_main_state());
if (auto L = process_callback(env, src, file)) {
if (lua::isfunction(L, -1)) {
lua::call_nothrow(L, 0);
if (lua::isfunction(L, -1) && !lua::call_nothrow(L, 0)) {
return T {};
}
try {
return tovalueFunc(L, -1);
} catch (const std::exception& err) {
if (!errorLogged) {
logger.error() << "supplier " << util::quote(src) << ": "
<< err.what();
errorLogged = true;
}
}
auto str = tovalueFunc(L, -1);
lua::pop(L);
return str;
}
return T {};
};
@ -158,16 +165,33 @@ int_array_consumer scripting::create_int_array_consumer(
vec2supplier scripting::create_vec2_supplier(
const scriptenv& env, const std::string& src, const std::string& file
) {
return [=]() {
if (auto L = process_callback(env, src, file)) {
if (lua::isfunction(L, -1)) {
lua::call_nothrow(L, 0);
return [=, errorLogged = false]() mutable {
auto L = lua::get_main_state();
lua::stackguard guard(L);
int top = lua::gettop(L);
if (process_callback(env, src, file)) {
if (lua::isfunction(L, -1) && !lua::call_nothrow(L, 0)) {
return glm::vec2(0, 0);
}
if (lua::gettop(L) - top < 2) {
if (!errorLogged) {
logger.error() << "supplier " << util::quote(src)
<< ": two numbers expected";
errorLogged = true;
}
return glm::vec2(0, 0);
}
try {
auto y = lua::tonumber(L, -1);
auto x = lua::tonumber(L, -2);
return glm::vec2(x, y);
} catch (const std::exception& err) {
if (!errorLogged) {
logger.error() << "supplier " << util::quote(src) << ": "
<< err.what();
errorLogged = true;
}
}
auto y = lua::tonumber(L, -1);
lua::pop(L);
auto x = lua::tonumber(L, -1);
lua::pop(L);
return glm::vec2(x, y);
}
return glm::vec2(0, 0);
};

View file

@ -113,6 +113,14 @@ public:
curl_easy_setopt(curl, CURLOPT_URL, request.url.c_str());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, request.method.c_str());
#if LIBCURL_VERSION_NUM >= 0x075500
curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR, "http,https");
curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS_STR, "http,https");
#else
curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
#endif
curl_slist* hs = nullptr;

View file

@ -328,14 +328,17 @@ void Entities::preparePhysics(float delta) {
auto view = registry->view<EntityId, Rigidbody>();
for (auto [entity, eid, rigidbody] : view.each()) {
auto bodyType = rigidbody.hitbox.type;
if (eid.destroyFlag || !rigidbody.enabled || bodyType == BodyType::STATIC) {
if (eid.destroyFlag || !rigidbody.enabled) {
continue;
}
rigidbody.hitbox.selectable = rigidbody.selectable;
rigidbody.hitbox.mass = bodyType == BodyType::DYNAMIC
? rigidbody.mass
: std::numeric_limits<float>::infinity();
rigidbody.hitbox.elasticity = rigidbody.elasticity;
rigidbody.hitbox.selectable = rigidbody.selectable;
if (bodyType == BodyType::STATIC) {
continue;
}
hitboxes.emplace_back(&rigidbody.hitbox);
if (!eid.def.solid) {
continue;
@ -480,15 +483,17 @@ void Entities::render(
const Frustum* frustum,
entityid_t fpsEntity
) {
auto view = registry->view<EntityId, Transform, rigging::Skeleton>();
for (auto [entity, eid, transform, skeleton] : view.each()) {
auto view = registry->view<EntityId, Transform, rigging::Skeleton, Rigidbody>();
for (auto [entity, eid, transform, skeleton, rigidbody] : view.each()) {
if (eid.uid == fpsEntity) {
continue;
}
const auto& def = eid.def;
const auto& pos = transform.pos;
const auto& size = transform.size;
if (frustum && !frustum->isBoxVisible(pos - size, pos + size)) {
const auto& halfSize = rigidbody.hitbox.getHalfSize();
// todo: more correct frustum culling
if (frustum && !frustum->isBoxVisible(pos - halfSize, pos + halfSize)) {
continue;
}

View file

@ -322,7 +322,7 @@ void Player::deserialize(const dv::value& src) {
src.at("loading-chunks").get(loadingChunks);
setChosenSlot(src["chosen-slot"].asInteger());
eid = src["entity"].asNumber();
eid = src["entity"].asInteger();
if (src.has("inventory")) {
getInventory()->deserialize(src["inventory"]);

View file

@ -14,6 +14,7 @@
inline constexpr float E = 0.03f;
inline constexpr float MAX_FIX = 0.1f;
inline constexpr int MAX_NEARBY_REBUILDS = 4;
static debug::Logger logger("physics-solver");
@ -141,12 +142,15 @@ static void calc_collision(
}
bool PhysicsSolver::calcCollisionNegY(
Hitbox& hitbox, const glm::vec3& half, float dt
Hitbox& hitbox,
const glm::vec3& half,
float dt,
const std::vector<Hitbox*>& solids
) {
auto& pos = hitbox.position;
auto& vel = hitbox.velocity;
for (auto box : solidHitboxes) {
for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) {
continue;
}
@ -215,23 +219,24 @@ void PhysicsSolver::calcCollisions(
glm::vec3& pos,
const glm::vec3& half,
float stepHeight,
float dt
float dt,
const std::vector<Hitbox*>& solids
) {
stepHeight = calc_step_height(chunks, pos, half, stepHeight);
auto prevPos = pos;
calc_collision<0, 1, 2, -1>(hitbox, chunks, solidHitboxes, half, stepHeight);
calc_collision<0, 1, 2, 1>(hitbox, chunks, solidHitboxes, half, stepHeight);
calc_collision<0, 1, 2, -1>(hitbox, chunks, solids, half, stepHeight);
calc_collision<0, 1, 2, 1>(hitbox, chunks, solids, half, stepHeight);
float xpos = pos.x;
pos.x = prevPos.x;
calc_collision<2, 1, 0, -1>(hitbox, chunks, solidHitboxes, half, stepHeight);
calc_collision<2, 1, 0, 1>(hitbox, chunks, solidHitboxes, half, stepHeight);
calc_collision<2, 1, 0, -1>(hitbox, chunks, solids, half, stepHeight);
calc_collision<2, 1, 0, 1>(hitbox, chunks, solids, half, stepHeight);
pos.x = xpos;
if (calcCollisionNegY(hitbox, half, dt)) {
if (calcCollisionNegY(hitbox, half, dt, solids)) {
hitbox.grounded = true;
}
@ -255,7 +260,7 @@ void PhysicsSolver::calcCollisions(
}
}
}
for (auto box : solidHitboxes) {
for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) {
continue;
}
@ -297,7 +302,7 @@ void PhysicsSolver::calcCollisions(
}
}
}
for (auto box : solidHitboxes) {
for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) {
continue;
}
@ -314,7 +319,11 @@ void PhysicsSolver::calcCollisions(
}
void PhysicsSolver::calcSubstep(
Hitbox& hitbox, glm::vec3& vel, glm::vec3& pos, float dt
Hitbox& hitbox,
glm::vec3& vel,
glm::vec3& pos,
float dt,
const std::vector<Hitbox*>& solids
) {
auto initpos = pos;
auto half = hitbox.getHalfSize();
@ -328,7 +337,8 @@ void PhysicsSolver::calcSubstep(
half,
(hitbox.prevGrounded && gravityScale > 0.0f) ? hitbox.stepHeight
: 0.0f,
dt
dt,
solids
);
}
@ -359,7 +369,7 @@ void PhysicsSolver::calcSubstep(
}
}
}
for (auto box : solidHitboxes) {
for (auto box : solids) {
if (glm::distance2(box->position, pos) < E) {
continue;
}
@ -376,6 +386,58 @@ void PhysicsSolver::calcSubstep(
hitbox.grounded = true;
}
static float calc_move_budget(
const Hitbox& hitbox, const glm::vec3& gravity, float time
) {
float speed = glm::length(hitbox.velocity) * 1.25f +
glm::length(gravity) * glm::abs(hitbox.gravityScale) * time;
return speed * time + 0.05f;
}
static glm::vec3 calc_extents(const Hitbox& hitbox) {
return glm::max(hitbox.halfsize, hitbox.getHalfSize());
}
void PhysicsSolver::findNearbySolids(float time) {
size_t count = hitboxes.size();
nearbySolids.resize(count);
nearbyOrigins.resize(count);
nearbyBudgets.resize(count);
solidBudgets.resize(solidHitboxes.size());
float maxSolidHalfY = 0.0f;
for (size_t j = 0; j < solidHitboxes.size(); j++) {
const auto& box = *solidHitboxes[j];
solidBudgets[j] = calc_move_budget(box, gravity, time);
maxSolidHalfY = glm::max(maxSolidHalfY, calc_extents(box).y);
}
for (size_t i = 0; i < count; i++) {
const auto& hitbox = *hitboxes[i];
auto& solids = nearbySolids[i];
solids.clear();
nearbyOrigins[i] = hitbox.position;
nearbyBudgets[i] = calc_move_budget(hitbox, gravity, time);
auto ext = calc_extents(hitbox);
glm::vec3 reach(
0.5f,
hitbox.stepHeight * 2.0f + E * 8.0f + ext.y * 0.5f +
maxSolidHalfY + 0.5f + MAX_FIX * 2.0f,
0.5f
);
reach += ext + nearbyBudgets[i];
for (size_t j = 0; j < solidHitboxes.size(); j++) {
const auto& box = *solidHitboxes[j];
auto limit = reach + calc_extents(box) + solidBudgets[j];
auto diff = glm::abs(box.position - hitbox.position);
if (diff.x <= limit.x && diff.y <= limit.y && diff.z <= limit.z) {
solids.push_back(solidHitboxes[j]);
}
}
}
}
void PhysicsSolver::step(
const GlobalChunks& chunks, float delta, uint substeps
) {
@ -387,11 +449,32 @@ void PhysicsSolver::step(
}
float dt = delta / static_cast<float>(substeps);
findNearbySolids(delta);
int rebuildsLeft = MAX_NEARBY_REBUILDS;
for (uint i = 0; i < substeps; i++) {
for (auto hitbox : hitboxes) {
for (size_t j = 0; j < hitboxes.size(); j++) {
auto hitbox = hitboxes[j];
glm::vec3& pos = hitbox->position;
hitbox->prevPosition = hitbox->position;
calcSubstep(*hitbox, hitbox->velocity, pos, dt);
calcSubstep(
*hitbox,
hitbox->velocity,
pos,
dt,
rebuildsLeft >= 0 ? nearbySolids[j] : solidHitboxes
);
if (rebuildsLeft < 0) {
continue;
}
auto moved = glm::abs(pos - nearbyOrigins[j]);
if (glm::max(moved.x, glm::max(moved.y, moved.z)) >
nearbyBudgets[j]) {
if (--rebuildsLeft >= 0) {
findNearbySolids(dt * static_cast<float>(substeps - i));
}
}
}
}

View file

@ -38,6 +38,12 @@ private:
std::vector<Sensor*> sensors;
std::vector<Hitbox*> solidHitboxes;
std::vector<Hitbox*> hitboxes;
std::vector<std::vector<Hitbox*>> nearbySolids;
std::vector<glm::vec3> nearbyOrigins;
std::vector<float> nearbyBudgets;
std::vector<float> solidBudgets;
void findNearbySolids(float time);
void calcCollisions(
Hitbox& hitbox,
@ -45,12 +51,24 @@ private:
glm::vec3& pos,
const glm::vec3& half,
float stepHeight,
float dt
float dt,
const std::vector<Hitbox*>& solids
);
void calcSubstep(Hitbox& hitbox, glm::vec3& vel, glm::vec3& pos, float dt);
void calcSubstep(
Hitbox& hitbox,
glm::vec3& vel,
glm::vec3& pos,
float dt,
const std::vector<Hitbox*>& solids
);
bool calcCollisionNegY(Hitbox& hitbox, const glm::vec3& half, float dt);
bool calcCollisionNegY(
Hitbox& hitbox,
const glm::vec3& half,
float dt,
const std::vector<Hitbox*>& solids
);
void updateSensors(Hitbox& hitbox);
};

View file

@ -63,6 +63,8 @@ struct CameraSettings {
};
struct GraphicsSettings {
/// @brief Enable fog
FlagSetting enableFog {true};
/// @brief Fog opacity is calculated as `pow(depth*k, fogCurve)` where k depends on chunksLoadDistance.
/// 1.0 is linear, 2.0 is quadratic
NumberSetting fogCurve {1.0f, 1.0f, 6.0f};

View file

@ -1,9 +1,13 @@
#pragma once
#include <cassert>
#include <cstddef>
#include <initializer_list>
#include <stdexcept>
#include <utility>
namespace util {
template<typename T, int capacity>
template<typename T, std::size_t capacity>
class stack_vector {
struct buffer {
alignas(alignof(T)) char data[sizeof(T) * capacity];
@ -16,18 +20,19 @@ namespace util {
}
};
public:
using size_type = std::size_t;
stack_vector() : size_(0) {}
stack_vector(const stack_vector<T, capacity>& other)
: size_(other.size_) {
for (int i = 0; i < size_; ++i) {
for (size_type i = 0; i < size_; ++i) {
new (&data_.ptr()[i]) T(other.data_.ptr()[i]);
}
}
stack_vector(stack_vector<T, capacity>&& other) noexcept
: size_(other.size_) {
for (int i = 0; i < size_; ++i) {
for (size_type i = 0; i < size_; ++i) {
new (&data_.ptr()[i]) T(std::move(other.data_.ptr()[i]));
}
other.size_ = 0;
@ -48,78 +53,85 @@ namespace util {
}
void push_back(const T& value) {
if (size_ < capacity) {
auto data = reinterpret_cast<char*>(data_.ptr() + (size_++));
new (data) T(value);
} else {
if (size_ >= capacity) {
throw std::overflow_error("stack vector capacity exceeded");
}
void* p = data_.data + size_ * sizeof(T);
::new (p) T(value);
++size_;
}
void push_back(T&& value) {
if (size_ < capacity) {
auto data = reinterpret_cast<char*>(data_.ptr() + (size_++));
new (data) T(std::move(value));
} else {
if (size_ >= capacity) {
throw std::overflow_error("stack vector capacity exceeded");
}
void* p = data_.data + size_ * sizeof(T);
::new (p) T(std::move(value));
++size_;
}
void pop_back() {
void pop_back() noexcept {
assert(!empty() && "pop_back() called on empty stack_vector");
if (size_ > 0) {
data_.ptr()[size_ - 1].~T();
--size_;
} else {
throw std::underflow_error("stack vector is empty");
}
}
}
void clear() {
for (int i = 0; i < size_; ++i) {
void clear() noexcept {
for (size_type i = 0; i < size_; ++i) {
data_.ptr()[i].~T();
}
size_ = 0;
}
T& operator[](int index) {
T& operator[](size_type index) {
return data_.ptr()[index];
}
const T& operator[](int index) const {
const T& operator[](size_type index) const {
return data_.ptr()[index];
}
T& at(int index) {
if (index < 0 || index >= size_) {
T& at(size_type index) {
if (index >= size_) {
throw std::out_of_range("index out of range");
}
return data_.ptr()[index];
}
const T& at(int index) const {
if (index < 0 || index >= size_) {
const T& at(size_type index) const {
if (index >= size_) {
throw std::out_of_range("index out of range");
}
return data_.ptr()[index];
}
T& front() {
assert(!empty() && "front() called on empty stack_vector");
return data_.ptr()[0];
}
T& back() {
assert(!empty() && "back() called on empty stack_vector");
return data_.ptr()[size_ - 1];
}
const T& front() const {
assert(!empty() && "front() called on empty stack_vector");
return data_.ptr()[0];
}
const T& back() const {
assert(!empty() && "back() called on empty stack_vector");
return data_.ptr()[size_ - 1];
}
int size() const {
size_type size() const {
return size_;
}
@ -148,6 +160,6 @@ namespace util {
}
private:
buffer data_;
int size_;
size_type size_;
};
}

View file

@ -1,9 +1,11 @@
#include "stringutil.hpp"
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <locale>
#include "stringutil.hpp"
#include <algorithm>
#include <charconv>
#include <cctype>
#include <cmath>
#include <iomanip>
#include <locale>
#include <sstream>
#include <stdexcept>
@ -509,17 +511,22 @@ int util::replaceAll(
return replace_all(str, from, to);
}
// replace it with std::from_chars in the far far future
double util::parse_double(const std::string& str) {
std::istringstream ss(str);
ss.imbue(std::locale("C"));
double d;
ss >> d;
if (ss.fail()) {
throw std::runtime_error("invalid number format");
}
return d;
}
double util::parse_double(const std::string& str) {
const char* begin = str.data();
const char* end = begin + str.size();
while (begin != end && std::isspace(static_cast<unsigned char>(*begin))) {
begin++;
}
if (begin != end && *begin == '+') {
begin++;
}
double d = 0.0;
const auto result = std::from_chars(begin, end, d);
if (result.ec != std::errc()) {
throw std::runtime_error("invalid number format");
}
return d;
}
double util::parse_double(const std::string& str, size_t offset, size_t len) {
return parse_double(str.substr(offset, len));

View file

@ -216,10 +216,17 @@ public:
return bindings;
}
ObserverHandler addKeyCallback(Keycode key, KeyCallback callback) override {
ObserverHandler addKeyCallback(Keycode key, InputCallback callback) override {
return keyCallbacks[key].add(std::move(callback));
}
ObserverHandler addMouseCallback(Mousecode button, InputCallback callback) override {
return addKeyCallback(
static_cast<Keycode>(MOUSE_KEYS_OFFSET + static_cast<int>(button)),
std::move(callback)
);
}
const std::vector<Keycode>& getPressedKeys() const override {
return pressedKeys;
}

View file

@ -36,6 +36,16 @@ static std::unordered_map<std::string, int> keycodes {
{"left-super", GLFW_KEY_LEFT_SUPER},
{"right-super", GLFW_KEY_RIGHT_SUPER},
{"grave-accent", GLFW_KEY_GRAVE_ACCENT},
{"minus", GLFW_KEY_MINUS},
{"equal", GLFW_KEY_EQUAL},
{"left-bracket", GLFW_KEY_LEFT_BRACKET},
{"right-bracket", GLFW_KEY_RIGHT_BRACKET},
{"backslash", GLFW_KEY_BACKSLASH},
{"semicolon", GLFW_KEY_SEMICOLON},
{"apostrophe", GLFW_KEY_APOSTROPHE},
{"comma", GLFW_KEY_COMMA},
{"period", GLFW_KEY_PERIOD},
{"slash", GLFW_KEY_SLASH},
{"left", GLFW_KEY_LEFT},
{"right", GLFW_KEY_RIGHT},
{"down", GLFW_KEY_DOWN},

View file

@ -288,12 +288,13 @@ public:
virtual const Bindings& getBindings() const = 0;
virtual ObserverHandler addKeyCallback(Keycode key, KeyCallback callback) = 0;
virtual ObserverHandler addKeyCallback(Keycode key, InputCallback callback) = 0;
virtual ObserverHandler addMouseCallback(Mousecode button, InputCallback callback) = 0;
virtual const std::vector<Keycode>& getPressedKeys() const = 0;
virtual const std::vector<uint>& getCodepoints() const = 0;
ObserverHandler addCallback(const std::string& name, KeyCallback callback) {
ObserverHandler addCallback(const std::string& name, InputCallback callback) {
return getBindings().require(name).onactived.add(callback);
}
};