diff --git a/.github/workflows/appimage.yml b/.github/workflows/appimage.yml index 7b53b3fbf..8f959eea8 100644 --- a/.github/workflows/appimage.yml +++ b/.github/workflows/appimage.yml @@ -11,6 +11,11 @@ on: required: true type: string description: 'Build name passed as VC_BUILD_NAME define' + version_patch: + required: false + type: string + default: '' + description: 'Engine version patch number passed as VC_VERSION_PATCH define' jobs: build-appimage: @@ -35,14 +40,8 @@ jobs: # fix luajit paths sudo ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua5.1.a sudo ln -s /usr/include/luajit-2.1 /usr/include/lua - # install EnTT - git clone --branch v3.16.0 https://github.com/skypjack/entt.git - cd entt/build - cmake -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DCMAKE_BUILD_TYPE=Release -DENTT_INSTALL=on .. - sudo make install - cd ../.. - name: Configure - run: cmake -S . -B build -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DCMAKE_BUILD_TYPE=Release -DVOXELENGINE_BUILD_APPDIR=1 -DVOXELENGINE_BUILD_TESTS=ON -DVC_BUILD_NAME="${{ inputs.build_name }}" + run: cmake -S . -B build -DCMAKE_POLICY_VERSION_MINIMUM=3.5 -DCMAKE_BUILD_TYPE=Release -DVOXELENGINE_BUILD_APPDIR=1 -DVOXELENGINE_BUILD_TESTS=ON -DVC_BUILD_NAME="${{ inputs.build_name }}" -DVC_VERSION_PATCH="${{ inputs.version_patch }}" - name: Build run: cmake --build build -t install - name: Run tests diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index 6956a1f3d..dc0438164 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -43,12 +43,6 @@ jobs: # fix luajit paths sudo ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua-5.1.a sudo ln -s /usr/include/luajit-2.1 /usr/include/lua - # install EnTT - git clone --branch v3.16.0 https://github.com/skypjack/entt.git - cd entt/build - cmake -DCMAKE_BUILD_TYPE=Release -DENTT_INSTALL=on .. - sudo make install - cd ../.. - name: Configure CMake # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index 22d5291da..60bf1c628 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -11,6 +11,11 @@ on: required: true type: string description: 'Build name passed as VC_BUILD_NAME define' + version_patch: + required: false + type: string + default: '' + description: 'Engine version patch number passed as VC_VERSION_PATCH define' jobs: build-dmg: @@ -23,13 +28,13 @@ jobs: - name: Install dependencies from brew run: | - brew install glfw glew libpng openal-soft luajit libvorbis skypjack/entt/entt googletest glm freetype + brew install glfw glew libpng openal-soft luajit libvorbis googletest glm freetype - name: Configure run: | cmake -DOPENAL_INCLUDE_DIR=$(brew --prefix openal-soft)/include \ -DOPENAL_LIBRARY=$(brew --prefix openal-soft)/lib/libopenal.dylib \ - -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOXELENGINE_BUILD_TESTS=ON -DVOXELENGINE_BUILD_APPDIR=1 -DVC_BUILD_NAME="${{ inputs.build_name }}" + -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOXELENGINE_BUILD_TESTS=ON -DVOXELENGINE_BUILD_APPDIR=1 -DVC_BUILD_NAME="${{ inputs.build_name }}" -DVC_VERSION_PATCH="${{ inputs.version_patch }}" - name: Build run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f6b539ba1..78250be9b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,24 +13,32 @@ jobs: prepare: runs-on: ubuntu-latest steps: - - run: echo "exists just for outputs" + - id: version + run: | + if [[ "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.([0-9]+) ]]; then + echo "patch=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT" + fi outputs: build_name: '${{ env.RELEASE_VERSION }}' + version_patch: '${{ steps.version.outputs.patch }}' build_linux: needs: [prepare] uses: ./.github/workflows/appimage.yml with: build_name: '${{ needs.prepare.outputs.build_name }}' + version_patch: '${{ needs.prepare.outputs.version_patch }}' build_macos: needs: [prepare] uses: ./.github/workflows/macos.yml with: build_name: '${{ needs.prepare.outputs.build_name }}' + version_patch: '${{ needs.prepare.outputs.version_patch }}' build_windows: needs: [prepare] uses: ./.github/workflows/windows-clang.yml with: build_name: '${{ needs.prepare.outputs.build_name }}' + version_patch: '${{ needs.prepare.outputs.version_patch }}' publish_release: runs-on: ubuntu-latest needs: [build_linux, build_macos, build_windows] diff --git a/.github/workflows/windows-clang.yml b/.github/workflows/windows-clang.yml index 1fe591ac8..d8fd69677 100644 --- a/.github/workflows/windows-clang.yml +++ b/.github/workflows/windows-clang.yml @@ -11,6 +11,11 @@ on: required: true type: string description: 'Build name passed as VC_BUILD_NAME define' + version_patch: + required: false + type: string + default: '' + description: 'Engine version patch number passed as VC_VERSION_PATCH define' jobs: build-windows: @@ -53,7 +58,7 @@ jobs: export VCPKG_ROOT=$(pwd)/vcpkg mkdir build cd build - cmake -G "MinGW Makefiles" -DVCPKG_TARGET_TRIPLET=x64-mingw-static -DVC_BUILD_NAME="${{ inputs.build_name }}" -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake .. + cmake -G "MinGW Makefiles" -DVCPKG_TARGET_TRIPLET=x64-mingw-static -DVC_BUILD_NAME="${{ inputs.build_name }}" -DVC_VERSION_PATCH="${{ inputs.version_patch }}" -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=./vcpkg/scripts/buildsystems/vcpkg.cmake .. cmake --build . --config Release - name: Package for Windows run: | diff --git a/CMakeLists.txt b/CMakeLists.txt index 8d93b56a4..4e44e8532 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,6 +12,14 @@ option(VOXELENGINE_BUILD_TESTS "Build tests" OFF) add_compile_definitions(VC_BUILD_NAME="${VC_BUILD_NAME}") +set(VC_VERSION_PATCH "" CACHE STRING "Engine version patch number") +if(NOT VC_VERSION_PATCH STREQUAL "") + if(NOT VC_VERSION_PATCH MATCHES "^[0-9]+$") + message(FATAL_ERROR "invalid VC_VERSION_PATCH: '${VC_VERSION_PATCH}'") + endif() + add_compile_definitions(VC_VERSION_PATCH=${VC_VERSION_PATCH}) +endif() + # Need for static compilation on Windows with MSVC clang TODO: Make single build # on Windows to avoid dependence on combinations of platforms and compilers and # make it independent diff --git a/Dockerfile b/Dockerfile index fb1a628c4..c4c691d92 100644 --- a/Dockerfile +++ b/Dockerfile @@ -38,15 +38,6 @@ RUN wget https://github.com/Kitware/CMake/releases/download/v${CMAKE_VERSION}/cm ./cmake-${CMAKE_VERSION}-linux-x86_64.sh --skip-license --prefix=/usr/local && \ rm cmake-${CMAKE_VERSION}-linux-x86_64.sh - -# Install specific EnTT version (the latest version that supports C++17). -RUN git clone --branch v3.16.0 https://github.com/skypjack/entt.git && \ - cd entt/build && \ - cmake -DCMAKE_BUILD_TYPE=Release -DENTT_INSTALL=on .. && \ - make install && \ - cd ../.. && rm -rf entt - - # CMake missing LUA_INCLUDE_DIR and LUA_LIBRARIES fix: RUN ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua5.1.a \ && ln -s /usr/include/luajit-2.1 /usr/include/lua diff --git a/README.md b/README.md index afd39ca4b..c2a1b0648 100644 --- a/README.md +++ b/README.md @@ -11,26 +11,11 @@ ### Install libraries -#### Install EnTT - -Installing last version that supports C++17. - -```sh -git clone --branch v3.16.0 https://github.com/skypjack/entt.git -cd entt -mkdir -p build && cd build -cmake -DCMAKE_BUILD_TYPE=Release -DENTT_INSTALL=ON .. -sudo make install -``` - -> [!WARNING] -> If you are using ALT Linux, do **not** use this EnTT installation method. - #### ALT Linux based distros ```sh su - -apt-get install entt-devel libglfw3-devel libGLEW-devel libglm-devel libpng-devel libvorbis-devel libopenal-devel libluajit-devel libstdc++13-devel-static libcurl-devel libfreetype-devel libssl-devel +apt-get install libglfw3-devel libGLEW-devel libglm-devel libpng-devel libvorbis-devel libopenal-devel libluajit-devel libstdc++13-devel-static libcurl-devel libfreetype-devel libssl-devel ``` #### Debian based distros @@ -80,7 +65,7 @@ cmake --build . --parallel ### Install libraries ```sh -brew install glfw glew glm libpng libvorbis lua luajit libcurl openal-soft skypjack/entt/entt freetype +brew install glfw glew glm libpng libvorbis lua luajit libcurl openal-soft freetype ``` > [!TIP] diff --git a/dev/tests/hotbar.lua b/dev/tests/hotbar.lua new file mode 100644 index 000000000..efeb655f4 --- /dev/null +++ b/dev/tests/hotbar.lua @@ -0,0 +1,27 @@ +local util = require "core:tests_util" + +util.create_demo_world("core:default") + +local pid = player.create("Xerxes") + +local function selected_slot() + local _, slot = player.get_inventory(pid) + return slot +end + +util.check_int(10, player.get_hotbar_size(pid), "default hotbar size") + +player.set_selected_slot(pid, 12) +util.check_int(2, selected_slot(), "selected slot") + +player.set_selected_slot(pid, 8) +player.set_hotbar_size(pid, 5) +util.check_int(5, player.get_hotbar_size(pid), "hotbar size") +util.check_int(4, selected_slot(), "clamped selected slot") + +player.set_selected_slot(pid, 7) +util.check_int(2, selected_slot(), "selected slot") + +player.set_hotbar_size(pid, 0) +util.check_int(1, player.get_hotbar_size(pid), "min hotbar size") +util.check_int(0, selected_slot(), "selected slot") diff --git a/dev/tests/io_stream.lua b/dev/tests/io_stream.lua index d08c68b0c..da2a2efb0 100644 --- a/dev/tests/io_stream.lua +++ b/dev/tests/io_stream.lua @@ -1,34 +1,385 @@ local device = file.create_memory_device() -file.write(device..":test.txt", "Hello\nWorld") -file.write_bytes(device..":test.bin", Bytearray({20, 30, 100, 200, 255})) -local stream = file.open(device..":test.txt", 'r') +local function path(name) return device .. ":" .. name end -local line1 = stream:read_line() -local line2 = stream:read_line() +local function eq_list(actual, expected, msg) + asserts.equals(#actual, #expected, (msg or "list") .. " length") + for i = 1, #expected do + asserts.equals(actual[i], expected[i], (msg or "list") .. "[" .. i .. "]") + end +end -assert(line1 == "Hello") -assert(line2 == "World") +file.write(path("test.txt"), "Hello\nWorld") +file.write_bytes(path("test.bin"), Bytearray({20, 30, 100, 200, 255})) -local stream2 = file.open(device..":test.bin", 'rb') -local data = stream2:read(5) -assert(data[1] == 20) -assert(data[2] == 30) -assert(data[3] == 100) -assert(data[4] == 200) -assert(data[5] == 255) +do + local stream = file.open(path("test.txt"), 'r') + asserts.equals(stream:read_line(), "Hello") + asserts.equals(stream:read_line(), "World") + stream:close() +end -local stream3 = file.open(device..":test.txt", 'r') -assert(stream3:is_alive()) -stream3:close() -assert(not stream3:is_alive()) +do + local stream = file.open(path("test.bin"), 'rb') + local data = stream:read(5) + asserts.equals(data[1], 20); asserts.equals(data[2], 30); asserts.equals(data[3], 100); asserts.equals(data[4], 200); asserts + .equals(data[5], 255) + stream:close() +end -local stream4 = file.open(device..":test.txt", 'r') -stream4:seek('b', 6) -local line = stream4:read_line() -assert(line == "World") +do + local stream = file.open(path("test.txt"), 'r') + assert(stream:is_alive()) + assert(not stream:is_closed()) + stream:close() + assert(not stream:is_alive()) + assert(stream:is_closed()) +end -local stream5 = file.open(device..":test.txt", 'r') -stream5:seek('e', 0) -local pos = stream5:tell() -assert(pos == 11) +do + local stream = file.open(path("test.txt"), 'r') + stream:seek('b', 6) + asserts.equals(stream:read_line(), "World") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + stream:seek('e', 0) + asserts.equals(stream:tell(), 11) + stream:close() +end + +------------------------------------------------------------------------------- +-- text: line endings and end of stream +------------------------------------------------------------------------------- + +do + local stream = file.open(path("test.txt"), 'r') + stream:read_line(); stream:read_line() + asserts.equals(stream:read_line(), nil, "after last line") + asserts.equals(stream:read_line(), nil, "after last line, again") + stream:close() +end + +do + file.write(path("empty.txt"), "") + local stream = file.open(path("empty.txt"), 'r') + asserts.equals(stream:read_line(), nil, "empty file") + stream:close() +end + +do + file.write(path("crlf.txt"), "a\r\nb\rc\nd\r") + local stream = file.open(path("crlf.txt"), 'r') + asserts.equals(stream:read_line(), "a", "CRLF") + asserts.equals(stream:read_line(), "b\rc", "lone CR is kept") + asserts.equals(stream:read_line(), "d\r", "CR at end of stream") + asserts.equals(stream:read_line(), nil) + stream:close() +end + +------------------------------------------------------------------------------- +-- text: read(count) and read_fully +------------------------------------------------------------------------------- + +do + file.write(path("blank.txt"), "\n\nA\nB\n\n") + local stream = file.open(path("blank.txt"), 'r') + eq_list(stream:read(10), {"A", "B"}, "trimmed") + stream:close() +end + +do + local stream = file.open(path("blank.txt"), 'r') + eq_list(stream:read(10, false), {"", "", "A", "B", ""}, "untrimmed") + stream:close() +end + +do + file.write(path("only_blank.txt"), "\n\n\n") + local stream = file.open(path("only_blank.txt"), 'r') + eq_list(stream:read(5), {}, "only empty lines") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + eq_list(stream:read(5), {"Hello", "World"}, "past end of stream") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + assert(not pcall(stream.read, stream, -1), "negative count must fail") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + asserts.equals(stream:read(), "Hello") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + asserts.equals(stream:read_fully(), "Hello\nWorld", "read_fully as string") + stream:close() +end + +do + local stream = file.open(path("test.txt"), 'r') + eq_list(stream:read_fully(true), {"Hello", "World"}, "read_fully as lines") + stream:close() +end + +------------------------------------------------------------------------------- +-- text: writing +------------------------------------------------------------------------------- + +do + local stream = file.open(path("out.txt"), 'w') + stream:write("one") + stream:write({"two", "three"}) + stream:write_line("four") + stream:close() + asserts.equals(file.read(path("out.txt")), "one\ntwo\nthree\nfour\n", "text write") +end + +do + local stream = file.open(path("out.txt"), 'w') + assert(not pcall(stream.write, stream, 42), "writing a number in text mode must fail") + stream:close() +end + +------------------------------------------------------------------------------- +-- binary +------------------------------------------------------------------------------- + +do + local stream = file.open(path("test.bin"), 'rb') + eq_list(stream:read(5, true), {20, 30, 100, 200, 255}, "read as table") + stream:close() +end + +do + local stream = file.open(path("test.bin"), 'rb') + stream:read(3) + asserts.equals(#stream:read(10), 2, "short read") + asserts.equals(#stream:read(10), 0, "read at end of stream") + stream:close() +end + +do + local stream = file.open(path("test.bin"), 'rb') + local data = stream:read_fully() + asserts.equals(#data, 5); asserts.equals(data[1], 20); asserts.equals(data[5], 255) + stream:close() +end + +do + local stream = file.open(path("test.bin"), 'rb') + eq_list(stream:read_fully(true), {20, 30, 100, 200, 255}, "read_fully as table") + stream:close() +end + +do + local stream = file.open(path("out.bin"), 'wb') + stream:write({1, 2, 3}) + stream:write(Bytearray({4, 5})) + stream:close() + + local data = file.read_bytes(path("out.bin")) + asserts.equals(#data, 5, "binary write length") + for i = 1, 5 do asserts.equals(data[i], i, "binary write byte " .. i) end +end + +do + local stream = file.open(path("fmt.bin"), 'wb') + stream:write("= 0) + +local stdin = app.get_stdin_stream(handle) +assert(stdin ~= nil) +stdin:write_line("sub_instance_test") +stdin:flush() + +app.sleep_until(function() return not app.is_instance_alive(handle) end) +assert(not app.is_instance_alive(handle)) + +local stdout = app.get_stdout_stream(handle) +assert(stdout ~= nil) +local output = table.concat(table.map(stdout:read(1e6), function(_, line) return ""..line end), '\n') +print(output) +assert(output and output:find("hello from sub-instance", 1, true) ~= nil) +assert(output and output:find('stdin-cmd] unknown command "sub_instance_test"', 1, true) ~= nil) +stdout:close() + +file.remove(script_path) +assert(not app.terminate_instance(handle)) diff --git a/doc/en/assets-preload.md b/doc/en/assets-preload.md index e40403298..8591c4402 100644 --- a/doc/en/assets-preload.md +++ b/doc/en/assets-preload.md @@ -38,6 +38,48 @@ Additional load settings example: ] } ``` +## Patterns + +An asset name may contain `*` to include multiple assets at once. The `*` matches any sequence of characters within a single path segment. + +Pattern matching is performed within the pack containing `preload.json`, specifically within the folder corresponding to the asset type (e.g., `textures/`, `sounds/`, etc.). +The resulting asset names are the same as if each discovered asset had been specified explicitly. + +```json +{ + "textures": [ + "gui/*", + "mobs/*/skin-*" + ], + "sounds": [ + "steps/*" + ] +} +``` + +> [!NOTE] +> Sound variations (such as `grass_0.ogg`, `grass_1.ogg`, etc.) are added as a single sound entry (e.g., `steps/grass`). + +A pattern ending in `/` matches directories rather than individual files. This is used for atlases: +```json +{ + "atlases": [ + "smth/*/other-*/*/" + ] +} +``` + +Entry parameters apply to all matched assets. The `path` parameter cannot be used in conjunction with a pattern: +```json +{ + "sounds": [ + { + "name": "ambient/*", + "keep-pcm": true + } + ] +} +``` *preload.json* example from `core:` package (`res/preload.json`): ```json diff --git a/doc/en/block-properties.md b/doc/en/block-properties.md index 3bede279e..65ff4c75d 100644 --- a/doc/en/block-properties.md +++ b/doc/en/block-properties.md @@ -71,6 +71,13 @@ Rotation profile (set of available block rotations and behaviour of placing bloc - "stairs" - "pane" + flipped variants - "ladder" - like a "pipe", but on horizontal surfaces it is installed like "pane" +### *uv-lock* + +Keeps custom model textures aligned to world axes when the block is rotated, +so textures of rotated blocks join seamlessly with neighbours. +Applies to axis-aligned faces of `custom` models with named textures. +Leave it off for directional textures (doors, arrows, wood). `false` by default. + ### *particles* Particles are specified as a JSON object. Property names can be found [in the particles section](particles.md). @@ -112,6 +119,8 @@ Properties available for variance: - model-name - texture - texture-faces +- hitbox +- hitboxes - model-primitives (deprecated) Variants are managed via `block.set_variant(x, y, z, index)`. @@ -142,6 +151,26 @@ In this example: - Variant 1 = `stairs_left` (from variants[0]) - Variant 2 = `stairs_right` (from variants[1]) +### Hitbox variants + +A variant can override `hitbox` or `hitboxes`. Variants without them inherit the root hitboxes. Collisions, raycasts, block selection and `aabb` models use the hitboxes of the current variant. + +```json +{ + "model": "aabb", + "hitbox": [0.0, 0.0, 0.0, 1.0, 0.5, 1.0], + "rotation": "pipe", + "state-based": { + "bits": 1, + "variants": [ + { "hitbox": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] } + ] + } +} +``` + +For extended blocks the variant is taken from the origin segment. + ## Lighting ### *emission* diff --git a/doc/en/entity-properties.md b/doc/en/entity-properties.md index f2d6638a3..6728b4a66 100644 --- a/doc/en/entity-properties.md +++ b/doc/en/entity-properties.md @@ -1,5 +1,17 @@ # Entity properties +## User properties + +Access to custom entity properties is provided through the table `entities.properties[id]["property"]`, where `id` is the entity definition index. + +Custom properties follow the same pack inheritance and override rules as block and item properties, and must be declared in `pack:config/user-props.toml`: + +```toml +"pack:property_name" = {} +``` + +This makes the property available in Lua scripts as `entities.properties[entities.def_index("pack:entity")]["property"]`. + ## Logic ### *components* @@ -132,6 +144,14 @@ The default value is the same as the entity name. Determines which skeleton will - *bone-based* - lighting is calculated for each skeletal bone separately. - *solid* - lighting is calculated for the entire entity. +### *translucent* + +Enables translucency support in the entity textures (semi-transparent parts). +Should only be used when needed, as it impacts performance. +Not required for full transparency (cutout parts) and for fading the entity out with the skeleton tint alpha. + +Default value: *false*. + ## Saving/Loading In addition to custom components, the engine automatically saves data from the built-in ones: transform, rigidbody, skeleton. diff --git a/doc/en/item-properties.md b/doc/en/item-properties.md index 44e8911cc..7913aff3f 100644 --- a/doc/en/item-properties.md +++ b/doc/en/item-properties.md @@ -72,6 +72,45 @@ Property status is displayed in the inventory interface. Display method is defin Defines the name of the script containing the item's event handlers. By default, equals to the item's string id (name). Allows you to reuse a single script for multiple items. +## User properties + +Access to custom item properties is provided through the table `item.properties[id]["property"]`, where `id` is the numeric item index. + +User properties must be declared in `pack:config/user-props.toml`: + +```toml +"pack:property_name" = {} +``` + +### Example usage in Lua - `base_survival:tool` + +```lua +local tool = item.properties[itemid]["base_survival:tool"] +if tool then + local stone_material = tool.materials['base:stone'] + if stone_material then + print(tool.type, stone_material.speed) + end +end +``` + +Definition in item JSON: + +```json +{ + "base_survival:tool": { + "type": "breaker", + "materials": { + "base:stone": { + "speed": 15.0 + } + } + } +} +``` + +Custom property tables follow the same inheritance and override rules as block properties. + ## Tags Tags allow you to designate general properties of items. Names should be formatted as `prefix:tag_name`. diff --git a/doc/en/main-page.md b/doc/en/main-page.md index 61d37bae7..bbcdcf541 100644 --- a/doc/en/main-page.md +++ b/doc/en/main-page.md @@ -1,5 +1,9 @@ # Documentation +>![WARNING] +> This branch is used for VoxelCore 0.33 development, API is unstable. +> [Proceed to VoxelCore 0.32 documentation](https://github.com/MihailRis/voxelcore/blob/release-0.32/doc/en/main-page.md) + ## Sections - [Assets preloading](assets-preload.md) diff --git a/doc/en/scripting/builtins/libapp.md b/doc/en/scripting/builtins/libapp.md index 2ed35f20f..a3eec7986 100644 --- a/doc/en/scripting/builtins/libapp.md +++ b/doc/en/scripting/builtins/libapp.md @@ -119,7 +119,8 @@ app.close_world( ```lua -- Returns the major and minor versions of the engine. -app.get_version() -> int, int +-- If a patch number is available, it also returns it. +app.get_version() -> int, int, int | nil -- Returns the value of a setting. -- Throws an exception if the setting does not exist. @@ -183,4 +184,10 @@ app.is_instance_alive(handle: int) -> boolean -- Stops the engine sub-instance. -- Returns true if the instance was alive at the time of the call. app.terminate_instance(handle: int) -> boolean + +-- Returns the input stream of the engine sub-instance. +app.get_stdin_stream(handle: int) -> stream + +-- Returns the output stream of the engine sub-instance. +app.get_stdout_stream(handle: int) -> stream ``` diff --git a/doc/en/scripting/builtins/libassets.md b/doc/en/scripting/builtins/libassets.md index 45ef138e9..b77b027a7 100644 --- a/doc/en/scripting/builtins/libassets.md +++ b/doc/en/scripting/builtins/libassets.md @@ -25,10 +25,10 @@ assets.load_texture( -- Parses and loads a 3D model assets.parse_model( - -- Model file format (xml / vcm) + -- Model file format (xml / vcm / obj / vec3) format: str, -- Contents of the model file - content: str, + content: str | Bytearray (.vec3), -- Model name after loading name: str, -- The skeleton name after loading. May be the same as the model name. @@ -37,6 +37,16 @@ assets.parse_model( skeleton_name: string ) +-- Parses and loads a skeleton definition +assets.parse_skeleton( + -- Skeleton file format (json / vcm / xml) + format: str, + -- Contents of the skeleton file + content: str, + -- Skeleton name after loading + name: str +) + -- Parses and loads animation assets.parse_animation( -- Animation file format (vca) diff --git a/doc/en/scripting/builtins/libblock.md b/doc/en/scripting/builtins/libblock.md index 689ed4c9c..41f34941d 100644 --- a/doc/en/scripting/builtins/libblock.md +++ b/doc/en/scripting/builtins/libblock.md @@ -177,7 +177,12 @@ block.get_textures(id: int, [optional] variant_index: int = 0) -> string table -- returns array of two vectors (arrays of 3 numbers): -- 1. Minimum point of the hitbox -- 2. Hitbox size -block.get_hitbox(id: int, rotation_index: int, [optional] hitbox_index: int = 0) -> {vec3, vec3} +block.get_hitbox( + id: int, + rotation_index: int, + [optional] hitbox_index: int = 0, + [optional] variant_index: int = 0 +) -> {vec3, vec3} ``` ## Data fields diff --git a/doc/en/scripting/builtins/libentities.md b/doc/en/scripting/builtins/libentities.md index 9e653ba78..78b8b8c76 100644 --- a/doc/en/scripting/builtins/libentities.md +++ b/doc/en/scripting/builtins/libentities.md @@ -41,6 +41,11 @@ entities.defs_count() -> int ``` +```lua +-- Table of custom entity properties (see ../../entity-properties.md) +entities.properties: table> +``` + > [!NOTE] > The following functions for retrieving multiple entities return tables with integer keys (uid). > For iteration, use `pairs`, and for calculating the table size, use `table.count_pairs`. diff --git a/doc/en/scripting/builtins/libgfx-skeletons.md b/doc/en/scripting/builtins/libgfx-skeletons.md index 5518cb349..0dfcd7e27 100644 --- a/doc/en/scripting/builtins/libgfx-skeletons.md +++ b/doc/en/scripting/builtins/libgfx-skeletons.md @@ -26,6 +26,10 @@ skeleton:get_matrix(index: int) -> mat4 -- Sets the transformation matrix of the bone with the specified index skeleton:set_matrix(index: int, matrix: mat4) +-- Returns the offset of the bone with the specified index relative to its parent +-- (as defined in the skeleton config) +skeleton:get_bone_offset(index: int) -> vec3 + -- Returns the texture by key (dynamically assigned textures - '$name') skeleton:get_texture(key: str) -> str diff --git a/doc/en/scripting/builtins/libhud.md b/doc/en/scripting/builtins/libhud.md index 1763ff1fb..337888f51 100644 --- a/doc/en/scripting/builtins/libhud.md +++ b/doc/en/scripting/builtins/libhud.md @@ -82,6 +82,12 @@ hud.is_player_inventory_open() -> boolean -- Sets whether to allow pausing. If false, the pause menu will not pause the game. hud.set_allow_pause(flag: bool) +-- Returns true if the hotbar is not hidden with hud.set_hotbar_visible. +hud.is_hotbar_visible() -> bool + +-- Shows or hides the hotbar. Selecting a slot with the mouse wheel and number keys keeps working. +hud.set_hotbar_visible(flag: bool) + -- Function that controls the named skeleton 'hand' (see gfx.skeletons) hud.hand_controller: function() ``` diff --git a/doc/en/scripting/builtins/libpathfinding.md b/doc/en/scripting/builtins/libpathfinding.md index 19562177b..5976a9e49 100644 --- a/doc/en/scripting/builtins/libpathfinding.md +++ b/doc/en/scripting/builtins/libpathfinding.md @@ -55,6 +55,12 @@ pathfinding.pull_route(agent: int) --> table or nil --- Set the maximum number of visited blocks for the agent. Used to limit the amount of work of the pathfinding algorithm. pathfinding.set_max_visited(agent: int, max_visited: int) +--- Sets the agent's width in blocks. Defaults to 0.6 +pathfinding.set_width(agent: int, width: number) + +--- Sets the agent's height in blocks. Defaults to 2 +pathfinding.set_height(agent: int, height: int) + --- Adding an avoided blocks tag pathfinding.avoid_tag( agent: int, diff --git a/doc/en/scripting/builtins/libplayer.md b/doc/en/scripting/builtins/libplayer.md index 1dd628b0e..8005e1713 100644 --- a/doc/en/scripting/builtins/libplayer.md +++ b/doc/en/scripting/builtins/libplayer.md @@ -142,7 +142,14 @@ Switches the player's camera. See [cameras](libcameras.md). player.set_selected_slot(playerid: int, slotid: int) ``` -Sets the selected slot index +Sets the selected slot index. The index wraps around the hotbar size. + +```lua +player.get_hotbar_size(playerid: int) -> int +player.set_hotbar_size(playerid: int, size: int) +``` + +Hotbar size getter and setter: the number of first player inventory slots that can be selected. `player.set_selected_slot` wraps the index by it, and the selected slot is moved into the range when the size decreases. Default value is `hotbar-size` from `config/defaults.toml` (10); the value is not saved with the world. On the client these slots are shown in the hotbar and selected with the mouse wheel and number keys. ```lua player.get_selected_block(playerid: int) -> x,y,z diff --git a/doc/en/scripting/builtins/libworld.md b/doc/en/scripting/builtins/libworld.md index c69276330..6c64c26e4 100644 --- a/doc/en/scripting/builtins/libworld.md +++ b/doc/en/scripting/builtins/libworld.md @@ -1,5 +1,12 @@ # *world* library +Existing world logic parameters: + +| Parameter | Type | Default | Description | +| -------------- | ---- | ------- | ----------------------------- | +| `random_ticks` | bool | `true` | Enables random block ticking. | +| `block_ticks` | bool | `true` | Enables block ticking. | + ```lua -- Checks if world is open world.is_open() -> bool @@ -33,6 +40,14 @@ world.get_total_time() -> number -- Returns world seed. world.get_seed() -> int +-- Returns a world logic parameter value by name. +-- Only predefined parameters are supported. +world.get_logic(name: str) -> any + +-- Sets a world logic parameter by name. +-- Only predefined parameters are supported. +world.set_logic(name: str, value: any) + -- Returns generator name. world.get_generator() -> str @@ -112,5 +127,3 @@ world.raycast( length: number, -- ray length normal: vec3, -- normal vector of the surface touched by the ray } or nil if the ray did not touch a block or entity -``` -``` diff --git a/doc/en/scripting/ecs.md b/doc/en/scripting/ecs.md index 73add6bda..18f815c6c 100644 --- a/doc/en/scripting/ecs.md +++ b/doc/en/scripting/ecs.md @@ -172,6 +172,9 @@ rig:get_matrix(index: int) -> mat4 -- Sets the bone transformation matrix at the specified index rig:set_matrix(index: int, matrix: mat4) +-- Returns the bone offset relative to its parent (from the skeleton config) +rig:get_bone_offset(index: int) -> vec3 + -- Returns the texture by key (dynamically assigned textures - '$name') rig:get_texture(key: str) -> str diff --git a/doc/en/scripting/events.md b/doc/en/scripting/events.md index 9baa9fd85..48964ba64 100644 --- a/doc/en/scripting/events.md +++ b/doc/en/scripting/events.md @@ -14,6 +14,26 @@ function on_placed(x, y, z, playerid) Called on block placed by player +```lua +function can_be_placed(x, y, z, playerid, rotation) -> bool +``` + +Called before a player places the block, after the built-in checks +(replaceability, `grounded`, intersection with entities). +The block is placed only if the function returns `true`. +`rotation` is the rotation index the block will be placed with +(see `block.get_rotation`). + +Example: a sapling that can only be planted on dirt. + +```lua +function can_be_placed(x, y, z, playerid, rotation) + return block.name(block.get(x, y - 1, z)) == "base:dirt" +end +``` + +The event is not called when the block is placed with `block.place` or `block.set`. + ```lua function on_broken(x, y, z, playerid) ``` @@ -117,10 +137,10 @@ function on_world_save() Called before world save. ```lua -function on_world_tick() +function on_world_tick(tps) ``` -Called 20 times per second +Called *tps* times per second ```lua function on_world_quit() @@ -225,6 +245,12 @@ function on_content_loaded() Called after the content pack has been fully loaded +```lua +function on_assets_loading() +``` + +Called on assets loading start + ## HUD events Callbacks specified in *hud.lua* script. diff --git a/doc/en/scripting/ui.md b/doc/en/scripting/ui.md index fbad3b01c..0e4c6d5ba 100644 --- a/doc/en/scripting/ui.md +++ b/doc/en/scripting/ui.md @@ -78,7 +78,8 @@ Common methods: | clear() | clears content | | add(xml) | adds an element, creating it using xml code. Example: `container:add("")` | | add(xml, data) | overload with table, which in events declared in xml will be available as DATA | -| setInterval(interval, callback) | assigns a function to be executed repeatedly at an interval specified in milliseconds | +| setInterval(interval, callback) | assigns a function to be executed repeatedly at an interval specified in milliseconds, returns interval id | +| clearInterval(id) | cancels an interval created with setInterval | ## Textbox diff --git a/doc/en/vca.md b/doc/en/vca.md index 7b2bda0b5..1299662f0 100644 --- a/doc/en/vca.md +++ b/doc/en/vca.md @@ -28,6 +28,9 @@ Two kinds of curve definitions are currently available, each producing a value ` - `@scale` - scales an object/bone (multiplier) - `@zoom` - camera zoom (multiplier) - `@texture` - change of a dynamically assigned texture (see [skeleton:set_texture](scripting/ecs.md#skeleton)) +- `@model` - bone model replacement (see [skeleton:set_model](scripting/ecs.md#skeleton)) +- `@show` - visibility of a bone or the entire skeleton/object (if no bone is specified) +- `@color` - color of a bone or the entire skeleton/object (if no bone is specified) (RGBA) ## Metadata @@ -96,6 +99,23 @@ If you do not wish to limit the animation duration via `configure` but want to l } ``` +Example of using flag directives like `show`: + +```vcd +# Specific bone +@show bone head period 20 { + @key frame 0 value on + @key frame 10 value off +} + +# Entire skeleton +@show period 30 { + @key frame 0 value on + @key frame 10 value off +} + +``` + ## Expression curves The attribute describes a function `f(t) = x`, where t is time in seconds. diff --git a/doc/en/xml-ui-layouts.md b/doc/en/xml-ui-layouts.md index 5a3b03bb5..4e0cafc58 100644 --- a/doc/en/xml-ui-layouts.md +++ b/doc/en/xml-ui-layouts.md @@ -218,6 +218,8 @@ Element is a container. Does not have specific attributes. > [!WARNING] > Slots not linked to an inventory will not be displayed. "Linked to an inventory" refers to the association between an inventory UI element and an inventory via an ID. This link can be explicitly established using `inventory_ui.inventory = inventory_id`. [(see ui.md)](scripting/ui.md#inventory) +A pack can replace the player inventory screen and the hotbar with its own layouts using `inventory-layout` (`"core:inventory"` by default) and `hotbar-layout` in `config/defaults.toml`. The root element of such a layout must be `inventory`, it is bound to the player inventory. The hotbar layout is placed at the bottom center of the screen unless it has `position-func`. + ## *slot* Element must be a direct sub-element of *inventory*. diff --git a/doc/ru/assets-preload.md b/doc/ru/assets-preload.md index 1d39d76aa..cfc3a1832 100644 --- a/doc/ru/assets-preload.md +++ b/doc/ru/assets-preload.md @@ -39,6 +39,49 @@ ``` +## Шаблоны + +Имя ассета может содержать `*` для добавления сразу нескольких ассетов. `*` соответствует любой последовательности символов в пределах одного сегмента пути. + +Поиск по шаблону производится в паке, содержащем `preload.json`, в папке типа ассетов (`textures/`, `sounds/`, ...). +Имена ассетов получаются такими же, как если бы каждый найденный ассет был указан явно. + +```json +{ + "textures": [ + "gui/*", + "mobs/*/skin-*" + ], + "sounds": [ + "steps/*" + ] +} +``` + +> [!NOTE] +> Вариации звука (`grass_0.ogg`, `grass_1.ogg`, ...) добавляются как один звук (`steps/grass`). + +Шаблон, оканчивающийся на `/`, соответствует папкам, а не файлам. Используется для атласов: +```json +{ + "atlases": [ + "smth/*/other-*/*/" + ] +} +``` + +Параметры записи применяются ко всем найденным ассетам. Параметр `path` нельзя использовать вместе с шаблоном: +```json +{ + "sounds": [ + { + "name": "ambient/*", + "keep-pcm": true + } + ] +} +``` + Пример файла из пакета `core:` (`res/preload.json`): ```json { diff --git a/doc/ru/block-properties.md b/doc/ru/block-properties.md index e6b0ceb85..8a64feb7a 100644 --- a/doc/ru/block-properties.md +++ b/doc/ru/block-properties.md @@ -72,6 +72,13 @@ - "stairs" - профиль "ступеньки" ("pane" + перевернутые варианты) - "ladder" - профиль "лестница" (как "pipe", но на горизонтальных поверхностях как "pane") +### Блокировка UV - *uv-lock* + +Сохраняет ориентацию текстур кастомной модели относительно мировых осей при вращении блока, +чтобы текстуры повёрнутых блоков бесшовно стыковались с соседними. +Работает для выровненных по осям граней `custom`-моделей с именованными текстурами. +Не включайте для направленных текстур (двери, стрелки, бревна). По умолчанию `false`. + ### Испускаемые частицы - *particles* Частицы указываются в виде JSON объекта. Имена свойств можно найти [в разделе, посвященном частицам](particles.md). @@ -113,6 +120,8 @@ - model-name - texture - texture-faces +- hitbox +- hitboxes - model-primitives (устарело) Управление состоянием производится через `block.set_variant(x, y, z, index)`. @@ -143,6 +152,26 @@ - Вариант 1 = `stairs_left` (из variants[0]) - Вариант 2 = `stairs_right` (из variants[1]) +### Хитбоксы по вариантам + +Вариант может переопределять `hitbox` или `hitboxes`. Варианты без них наследуют хитбоксы из корня. Коллизии, рейкасты, выделение блока и модели `aabb` используют хитбоксы текущего варианта. + +```json +{ + "model": "aabb", + "hitbox": [0.0, 0.0, 0.0, 1.0, 0.5, 1.0], + "rotation": "pipe", + "state-based": { + "bits": 1, + "variants": [ + { "hitbox": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] } + ] + } +} +``` + +Для расширенных блоков вариант берётся из сегмента-источника. + ## Освещение ### Излучение - *emission*: diff --git a/doc/ru/entity-properties.md b/doc/ru/entity-properties.md index 69ff6f24a..5b1ba2d07 100644 --- a/doc/ru/entity-properties.md +++ b/doc/ru/entity-properties.md @@ -1,5 +1,17 @@ # Свойства сущностей +## Пользовательские свойства + +Доступ к пользовательским свойствам сущностей осуществляется через таблицу `entities.properties[id]["свойство"]`, где `id` - индекс определения сущности. + +Пользовательские свойства следуют тем же правилам наследования и переопределения пакетов, что и свойства блоков и предметов, и должны быть объявлены в `pack:config/user-props.toml`: + +```toml +"pack:property_name" = {} +``` + +Это делает свойство доступным в Lua-скриптах как `entities.properties[entities.def_index("pack:entity")]["свойство"]`. + ## Логика ### Список компонентов - *components* @@ -132,6 +144,14 @@ - *bone-based* - освещение рассчитывается для каждой кости скелета отдельно. - *solid* - освещение рассчитывается для всей сущности в целом. +### Полупрозрачность - *translucent* + +Включает поддержку полупрозрачности в текстурах сущности. +Следует использовать только при необходимости, так как влияет на производительность. +Не требуется для полной прозрачности (вырезанных частей) и для затухания сущности через альфа-канал оттенка скелета. + +Значение по-умолчанию: *false*. + ## Сохранение/загрузка Кроме данных пользовательских компонентов, движок автоматически сохраняет данные встроенных: transform, rigidbody, skeleton. diff --git a/doc/ru/item-properties.md b/doc/ru/item-properties.md index 1f4be05be..6c170e527 100644 --- a/doc/ru/item-properties.md +++ b/doc/ru/item-properties.md @@ -71,6 +71,45 @@ Определяет имя скрипта, содержащего обработчики событий предмета. По умолчанию соответствует строковому id (имени) предмета. Свойство обеспечивает возможность использования одного скрипта для нескольких предметов. +## Пользовательские свойства + +Доступ к пользовательским свойствам предметов осуществляется через таблицу `item.properties[id]["свойство"]`, где `id` — числовой индекс предмета. + +Пользовательские свойства должны быть объявлены в файле `пак:config/user-props.toml`: + +```toml +"пак:имя_свойства" = {} +``` + +### Пример использования в Lua - `base_survival:tool` + +```lua +local tool = item.properties[itemid]["base_survival:tool"] +if tool then + local stone_material = tool.materials['base:stone'] + if stone_material then + print(tool.type, stone_material.speed) + end +end +``` + +Описание в JSON предмета: + +```json +{ + "base_survival:tool": { + "type": "breaker", + "materials": { + "base:stone": { + "speed": 15.0 + } + } + } +} +``` + +Пользовательские свойства следуют тем же правилам наследования и переопределения, что и свойства блоков. + ## Теги - *tags* Теги позволяют обозначать обобщённые свойства предметов. Названия следует формировать как `префикс:имя_тега`. diff --git a/doc/ru/main-page.md b/doc/ru/main-page.md index 55cf9cd8e..4017b4975 100644 --- a/doc/ru/main-page.md +++ b/doc/ru/main-page.md @@ -1,5 +1,9 @@ # Документация +>![WARNING] +> В этой ветке ведётся разработка VoxelCore 0.33, API нестабилен. +> [Перейти к документации VoxelCore 0.32](https://github.com/MihailRis/voxelcore/blob/release-0.32/doc/ru/main-page.md) + ## Разделы - [XML разметка интерфейса](xml-ui-layouts.md) diff --git a/doc/ru/scripting/builtins/libapp.md b/doc/ru/scripting/builtins/libapp.md index 78c5afdff..bb6490835 100644 --- a/doc/ru/scripting/builtins/libapp.md +++ b/doc/ru/scripting/builtins/libapp.md @@ -116,7 +116,8 @@ app.close_world( ```lua -- Возвращает мажорную и минорную версии движка. -app.get_version() -> int, int +-- При наличии номера патча возвращает и его. +app.get_version() -> int, int, int | nil -- Возвращает значение настройки. -- Бросает исключение, если настройки не существует. @@ -173,4 +174,10 @@ app.is_instance_alive(handle: int) -> boolean -- Останавливает под-экземпляр движка. -- Возвращает true если экземпляр был жив в момент вызова. app.terminate_instance(handle: int) -> boolean + +-- Возвращает поток ввода под-экземпляра движка. +app.get_stdin_stream(handle: int) -> stream + +-- Возвращает поток вывода под-экземпляра движка. +app.get_stdout_stream(handle: int) -> stream ``` diff --git a/doc/ru/scripting/builtins/libassets.md b/doc/ru/scripting/builtins/libassets.md index b9ac18226..45b5a2079 100644 --- a/doc/ru/scripting/builtins/libassets.md +++ b/doc/ru/scripting/builtins/libassets.md @@ -26,10 +26,10 @@ assets.load_texture( -- Парсит и загружает 3D модель assets.parse_model( - -- Формат файла модели (xml / vcm) + -- Формат файла модели (xml / vcm / obj / vec3) format: string, -- Содержимое файла модели - content: string, + content: string | Bytearray (.vec3), -- Имя модели после загрузки name: string, -- Имя скелета после загрузки. Может совпадать с именем модели. @@ -38,6 +38,16 @@ assets.parse_model( skeleton_name: string ) +-- Парсит и загружает определение скелета +assets.parse_skeleton( + -- Формат файла скелета (json / vcm / xml) + format: string, + -- Содержимое файла скелета + content: string, + -- Имя скелета после загрузки + name: string +) + -- Парсит и загружает анимацию assets.parse_animation( -- Формат файла анимации (vca) diff --git a/doc/ru/scripting/builtins/libblock.md b/doc/ru/scripting/builtins/libblock.md index 1e744542e..07677b362 100644 --- a/doc/ru/scripting/builtins/libblock.md +++ b/doc/ru/scripting/builtins/libblock.md @@ -177,7 +177,13 @@ block.get_textures(id: int, [опционально] variant_index: int = 0) -> -- 2. Размер хитбокса -- rotation_index - индекс поворота блока -- hitbox_index - индекс хитбокса -block.get_hitbox(id: int, rotation_index: int, [опционально] hitbox_index: int = 0) -> {vec3, vec3} +-- variant_index - индекс варианта +block.get_hitbox( + id: int, + rotation_index: int, + [опционально] hitbox_index: int = 0, + [опционально] variant_index: int = 0 +) -> {vec3, vec3} ``` ## Данные блоков diff --git a/doc/ru/scripting/builtins/libentities.md b/doc/ru/scripting/builtins/libentities.md index 045dbe2fd..3c2bcf9c4 100644 --- a/doc/ru/scripting/builtins/libentities.md +++ b/doc/ru/scripting/builtins/libentities.md @@ -40,6 +40,11 @@ entities.def_index(name: string) -> int entities.defs_count() -> int ``` +```lua +-- Таблица пользовательских свойств сущностей (см. ../../entity-properties.md) +entities.properties: table> +``` + > [!NOTE] > Следующие функции для получения нескольких сущностей возвращают таблицы с целочисленными ключами (uid). > Для итерации нужно использовать pairs, для подсчёта размера таблицы - table.count_pairs. diff --git a/doc/ru/scripting/builtins/libgfx-skeletons.md b/doc/ru/scripting/builtins/libgfx-skeletons.md index 9465c0df1..0dd8c8462 100644 --- a/doc/ru/scripting/builtins/libgfx-skeletons.md +++ b/doc/ru/scripting/builtins/libgfx-skeletons.md @@ -27,6 +27,10 @@ skeleton:get_matrix(index: int) -> mat4 -- Устанавливает матрицу трансформации кости с указанным индексом skeleton:set_matrix(index: int, matrix: mat4) +-- Возвращает смещение кости с указанным индексом относительно родительской +-- (как задано в конфиге скелета) +skeleton:get_bone_offset(index: int) -> vec3 + -- Возвращает текстуру по ключу (динамически назначаемые текстуры - '$имя') skeleton:get_texture(key: string) -> string diff --git a/doc/ru/scripting/builtins/libhud.md b/doc/ru/scripting/builtins/libhud.md index 210c78573..ed8423bfa 100644 --- a/doc/ru/scripting/builtins/libhud.md +++ b/doc/ru/scripting/builtins/libhud.md @@ -84,6 +84,12 @@ hud.is_player_inventory_open() -> boolean -- Устанавливает разрешение на паузу. При значении false меню паузы не приостанавливает игру. hud.set_allow_pause(flag: boolean) +-- Возвращает true, если хотбар не скрыт через hud.set_hotbar_visible. +hud.is_hotbar_visible() -> boolean + +-- Показывает или скрывает хотбар. Выбор слота колесом мыши и цифровыми клавишами продолжает работать. +hud.set_hotbar_visible(flag: boolean) + -- Функция, управляющая именованным скелетом 'hand' (см. gfx.skeletons) hud.hand_controller: function() ``` diff --git a/doc/ru/scripting/builtins/libpathfinding.md b/doc/ru/scripting/builtins/libpathfinding.md index 3d0a07e2e..eb991730e 100644 --- a/doc/ru/scripting/builtins/libpathfinding.md +++ b/doc/ru/scripting/builtins/libpathfinding.md @@ -55,6 +55,12 @@ pathfinding.pull_route(agent: int) -> table или nil --- Установка максимального количества посещенных блоков для агента. Используется для ограничения объема работы алгоритма поиска пути. pathfinding.set_max_visited(agent: int, max_visited: int) +--- Установка ширины агента в блоках. По-умолчанию 0.6 +pathfinding.set_width(agent: int, width: number) + +--- Установка высоты агента в блоках. По-умолчанию 2 +pathfinding.set_height(agent: int, width: int) + --- Добавление тега избегаемых блоков pathfinding.avoid_tag( agent: int, @@ -63,4 +69,4 @@ pathfinding.avoid_tag( -- стоимость пересечения блока cost: int = 10 ) -``` \ No newline at end of file +``` diff --git a/doc/ru/scripting/builtins/libplayer.md b/doc/ru/scripting/builtins/libplayer.md index 08077e967..758c223e1 100644 --- a/doc/ru/scripting/builtins/libplayer.md +++ b/doc/ru/scripting/builtins/libplayer.md @@ -95,9 +95,17 @@ player.get_interaction_distance(playerid: int) -> number -- Возвращает ID инвентаря и индекс выбранного слота player.get_inventory(playerid: int) -> int, int --- Устанавливает выбранный слот +-- Устанавливает выбранный слот (индекс берётся по модулю размера хотбара) player.set_selected_slot(playerid: int, slotid: int) +-- Возвращает / устанавливает размер хотбара - число первых слотов инвентаря игрока, +-- доступных для выбора. player.set_selected_slot берёт индекс по модулю этого числа, +-- а при уменьшении размера выбранный слот сдвигается в допустимый диапазон. +-- По умолчанию - `hotbar-size` из `config/defaults.toml` (10), в мире не сохраняется. +-- На клиенте эти слоты показывает хотбар, они выбираются колесом мыши и цифровыми клавишами. +player.get_hotbar_size(playerid: int) -> int +player.set_hotbar_size(playerid: int, size: int) + -- Возвращает позицию выбранного блока player.get_selected_block(playerid: int) -> x,y,z diff --git a/doc/ru/scripting/builtins/libworld.md b/doc/ru/scripting/builtins/libworld.md index ef1c95302..c45759ca7 100644 --- a/doc/ru/scripting/builtins/libworld.md +++ b/doc/ru/scripting/builtins/libworld.md @@ -1,5 +1,12 @@ # Библиотека *world* +Существующие параметры логики мира: + +| Параметр | Тип | По умолчанию | Описание | +| -------------- | ---- | ------------ | -------------------------------- | +| `random_ticks` | bool | `true` | Включает случайные такты блоков. | +| `block_ticks` | bool | `true` | Включает такты блоков. | + ```lua -- Проверяет, открыт ли мир world.is_open() -> boolean @@ -32,6 +39,14 @@ world.get_total_time() -> number -- Возвращает зерно мира. world.get_seed() -> int +-- Возвращает значение параметра логики мира по имени. +-- Поддерживаются только предопределённые параметры. +world.get_logic(name: string) -> any + +-- Устанавливает параметр логики мира по имени. +-- Поддерживаются только предопределённые параметры. +world.set_logic(name: string, value: any) + -- Возвращает имя генератора. world.get_generator() -> string @@ -111,4 +126,3 @@ world.raycast( length: number, -- длина луча normal: vec3, -- вектор нормали поверхности, которой касается луч } или nil если луч не коснулся блока или сущности -``` diff --git a/doc/ru/scripting/ecs.md b/doc/ru/scripting/ecs.md index 647a4ee3b..fe963e86b 100644 --- a/doc/ru/scripting/ecs.md +++ b/doc/ru/scripting/ecs.md @@ -161,6 +161,9 @@ rig:get_matrix(index: int) -> mat4 -- Устанавливает матрицу трансформации кости с указанным индексом rig:set_matrix(index: int, matrix: mat4) +-- Возвращает смещение кости относительно родительской (из конфига скелета) +rig:get_bone_offset(index: int) -> vec3 + -- Возвращает текстуру по ключу (динамически назначаемые текстуры - '$имя') rig:get_texture(key: str) -> str diff --git a/doc/ru/scripting/events.md b/doc/ru/scripting/events.md index 8b9dc41e9..f9035ce52 100644 --- a/doc/ru/scripting/events.md +++ b/doc/ru/scripting/events.md @@ -24,6 +24,26 @@ function on_placed(x, y, z, playerid) Вызывается после установки блока игроком +```lua +function can_be_placed(x, y, z, playerid, rotation) -> bool +``` + +Вызывается перед установкой блока игроком, после встроенных проверок +(заменяемость, `grounded`, пересечение с сущностями). +Блок устанавливается, только если функция возвращает `true`. +`rotation` - индекс поворота, с которым будет установлен блок +(см. `block.get_rotation`). + +Пример: саженец, который можно посадить только на землю. + +```lua +function can_be_placed(x, y, z, playerid, rotation) + return block.name(block.get(x, y - 1, z)) == "base:dirt" +end +``` + +Событие не вызывается при установке блока через `block.place` и `block.set`. + ```lua function on_broken(x, y, z, playerid) ``` @@ -104,7 +124,7 @@ function on_block_break_by(x: int, y: int, z: int, playerid: int) Вызывается при нажатии ЛКМ на блок (в т.ч неразрушимый). Предотвращает разрушение блока, если возвращает `true` -## События мира +## События мира События мира для контент-пака прописываются в `scripts/world.lua` @@ -121,10 +141,10 @@ function on_world_save() Вызывается перед сохранением мира ```lua -function on_world_tick() +function on_world_tick(tps) ``` -Вызывается 20 раз в секунду +Вызывается *tps* раз в секунду ```lua function on_world_quit() @@ -236,6 +256,12 @@ function on_content_loaded() Вызывается после того, как контент-пак был полностью загружен +```lua +function on_assets_loading() +``` + +Вызывается в начале загрузки ассетов + ## События HUD События связанные с игровым интерфейсом прописываются в файле `scripts/hud.lua` diff --git a/doc/ru/scripting/ui.md b/doc/ru/scripting/ui.md index 23037a204..875a15d24 100644 --- a/doc/ru/scripting/ui.md +++ b/doc/ru/scripting/ui.md @@ -78,7 +78,8 @@ document["worlds-panel"]:clear() | clear() | очищает контент | | add(xml) | добавляет элемент, создавая его по xml коду. Пример: `container:add("")` | | add(xml, data) | перегрузка с передачей таблицы, которая в событиях, объявленных в xml будет доступна как DATA | -| setInterval(interval, callback) | назначает функцию на повторяющееся выполнение с заданным в миллисекундах интервалом | +| setInterval(interval, callback) | назначает функцию на повторяющееся выполнение с заданным в миллисекундах интервалом, возвращает id интервала | +| clearInterval(id) | отменяет интервал, созданный через setInterval | ## Текстовое поле (textbox) diff --git a/doc/ru/vca.md b/doc/ru/vca.md index d10d0764e..6da0a07dd 100644 --- a/doc/ru/vca.md +++ b/doc/ru/vca.md @@ -28,6 +28,9 @@ VCA файл состоит из набора директив, порядок - `@scale` - масштабирование объекта/кости (множитель) - `@zoom` - масштаб камеры (множитель) - `@texture` - смена динамически-назначаемой текстуры (см. [skeleton:set_texture](scripting/ecs.md#skeleton)) +- `@model` - назначение замены модели кости (см. [skeleton:set_model](scripting/ecs.md#skeleton)) +- `@show` - видимость кости или всего скелета / объекта (если не указана кость) +- `@color` - цвет кости или всего скелета / объекта (если не указана кость) (RGBA) ## Мета-информация @@ -96,6 +99,23 @@ VCA файл состоит из набора директив, порядок } ``` +Пример использования директив-флагов, таких как `show`: + +```vcd +# Конкретная кость +@show bone head period 20 { + @key frame 0 value on + @key frame 10 value off +} + +# Весь скелет +@show period 30 { + @key frame 0 value on + @key frame 10 value off +} + +``` + ## Кривые через выражения Через атрибут описывается функция `f(t) = x` где t - время в секундах. diff --git a/doc/ru/xml-ui-layouts.md b/doc/ru/xml-ui-layouts.md index 9632c40b3..fa50e6c25 100644 --- a/doc/ru/xml-ui-layouts.md +++ b/doc/ru/xml-ui-layouts.md @@ -219,6 +219,8 @@ > [!WARNING] > Слоты без привязки к инвентарю не будут отображаться. Под привязкой к инвентарю понимается связь UI элемента inventory с инвентарём по id. Которая может быть явно создана через `inventory_ui.inventory = inventory_id`. [(см ui.md)](scripting/ui.md#инвентарь-inventory) +Пак может заменить экран инвентаря игрока и хотбар своими макетами через ключи `inventory-layout` (по умолчанию `"core:inventory"`) и `hotbar-layout` в `config/defaults.toml`. Корневой элемент такого макета - `inventory`, он привязывается к инвентарю игрока. Макет хотбара ставится внизу по центру экрана, если у него нет `position-func`. + ## Одиночный слот - *slot* Элемент должен находиться внутри `inventory` элемента, без посредников. diff --git a/flake.nix b/flake.nix index cb6bfe6ca..3bde39be4 100644 --- a/flake.nix +++ b/flake.nix @@ -38,7 +38,6 @@ luajit curl openssl - entt mesa freeglut ]; @@ -47,11 +46,6 @@ glfw mesa freeglut - entt - ]; - cmakeFlags = [ - "-DCMAKE_PREFIX_PATH=${pkgs.entt}" - "-DCMAKE_INCLUDE_PATH=${pkgs.entt}/include" ]; installPhase = '' diff --git a/res/config/defaults.toml b/res/config/defaults.toml index dd2bd314a..60dc656d9 100644 --- a/res/config/defaults.toml +++ b/res/config/defaults.toml @@ -1,2 +1,4 @@ generator = "core:default" player-entity = "" +hotbar-size = 10 +inventory-layout = "core:inventory" diff --git a/res/content/base/package.json b/res/content/base/package.json index 71b4dca9f..11eb30f3e 100644 --- a/res/content/base/package.json +++ b/res/content/base/package.json @@ -1,6 +1,6 @@ { "id": "base", "title": "Base", - "version": "0.32", + "version": "0.33", "description": "basic content package" } diff --git a/res/layouts/reports/missing_content.xml b/res/layouts/reports/missing_content.xml index cd8cacb4f..76b0872fe 100644 --- a/res/layouts/reports/missing_content.xml +++ b/res/layouts/reports/missing_content.xml @@ -3,5 +3,6 @@ + diff --git a/res/layouts/reports/missing_content.xml.lua b/res/layouts/reports/missing_content.xml.lua index 8ea78a1c1..50ac29c2d 100644 --- a/res/layouts/reports/missing_content.xml.lua +++ b/res/layouts/reports/missing_content.xml.lua @@ -1,4 +1,18 @@ +content_report = nil + +function delete_content() + local units = {} + for i, entry in ipairs(content_report.content) do + table.insert(units, entry.name) + end + local request = { + units = units + } + app.delete_world_content(content_report.world, request, true) +end + function on_open(report) + content_report = report for i, entry in ipairs(report.content) do document.content_panel:add(gui.template("content_entry", entry)) end diff --git a/res/modules/animation.lua b/res/modules/animation.lua index 0c7bb7741..664c3bd16 100644 --- a/res/modules/animation.lua +++ b/res/modules/animation.lua @@ -39,12 +39,15 @@ local function bezier_interpolation(k0, k1, t) return bezier(k0.value, k0.ry + k0.value, k1.ly + k1.value, k1.value, u) end -local this = { +local M = { CH_TRANSLATE = 1, CH_ROTATE = 2, CH_SCALE = 3, CH_ZOOM = 4, CH_TEXTURE = 5, + CH_SHOW = 6, + CH_MODEL = 7, + CH_COLOR = 8, INT_CONST = 1, INT_LINEAR = 2, @@ -67,14 +70,14 @@ function internals.store_animation(name, track) loaded_tracks[name] = track end -function this.get_track(identifier) +function M.get_track(identifier) return loaded_tracks[identifier] end local running_actions = {} local playing_tracks = {} -function this.action(func) +function M.action(func) table.insert(running_actions, coroutine.create(func)) end @@ -98,7 +101,7 @@ local PlayingTrack = { } } -function this.play(name, target) +function M.play(name, target) if target and target.reset_pose then target:reset_pose() end @@ -156,4 +159,4 @@ function internals.restore_animation_backup() loaded_tracks, backup_tracks = backup_tracks, {} end -return this +return M diff --git a/res/modules/internal/animation_codegen.lua b/res/modules/internal/animation_codegen.lua index f9180297d..35e535a0b 100644 --- a/res/modules/internal/animation_codegen.lua +++ b/res/modules/internal/animation_codegen.lua @@ -18,7 +18,7 @@ local exclude_patters = { } -- TODO: replace with actual expression -> lua translator -local function process_expression(src, memoised, mode) +local function process_expression(src, mode) if mode == 'mul' then src = string.format("(%s) * intensity + (1.0 - intensity)", src) elseif mode == "add" then @@ -33,7 +33,6 @@ local function process_expression(src, memoised, mode) for i, pattern in ipairs(patterns) do local pattern_safe = string.pattern_safe(pattern.pattern) if src:find(pattern_safe) then - memoised[pattern.name] = pattern.pattern src = src:gsub(pattern_safe, pattern.name) end end @@ -79,7 +78,7 @@ local env = { return keys[left].value end left = keys[left] - if interp == INT_CONST then + if not interp or interp == INT_CONST then return left.value end right = keys[right] @@ -119,8 +118,8 @@ local env = { if target.set_rot then target:set_rot(rot) end - if target.set_scale then - target:set_scale(scale) + if target.set_size then + target:set_size(scale) end end end, @@ -141,42 +140,48 @@ local is_multiplier = { [animation.CH_ZOOM] = true, } -local function codegen_track(raw_track, lineset, memoised, keysets, use_tsf) +local function codegen_line(raw_track, lineset, line, index, keysets) + if line.expression then + return "(" .. process_expression(line.expression, + is_multiplier[line.channel] and "mul" or "add") .. ")" + elseif line.keys then + local target_keysets = keysets[lineset.target_name] + if not target_keysets then + target_keysets = {} + keysets[lineset.target_name] = target_keysets + end + target_keysets[index] = line.keys + + if line.curve_func then + local valueat = string.format("curves[%s]", string.escape(line.curve_func)) + return string.format("value_at_custom(keysets['%s'][%d], t * %s %% %s, %s)", + lineset.target_name, index, raw_track.fps, line.period, valueat) + elseif line.channel == animation.CH_TEXTURE then + return string.format("string_at(keysets['%s'][%d], t * %s %% %s)", + lineset.target_name, index, raw_track.fps, line.period) + else + return string.format("value_at(keysets['%s'][%d], t * %s %% %s, %s)", + lineset.target_name, index, raw_track.fps, line.period, line.interp) + end + end +end + +local function codegen_track(raw_track, lineset, keysets, use_tsf, target_type) + if lineset.target_type ~= target_type then + return "" + end + local lines = lineset.lines local code = "" local has_tsf = false local translation = {false, false, false} local rotation = {false, false, false} local scale = {false, false, false} + local color = {false, false, false, false} + for i, line in ipairs(lines) do - if line.expression then - code = code .. "\n local l" .. i .. " = (" .. - process_expression(line.expression, memoised, - is_multiplier[line.channel] and "mul" or "add") .. ")" - elseif line.keys then - local target_keysets = keysets[lineset.target_name] - if not target_keysets then - target_keysets = {} - keysets[lineset.target_name] = target_keysets - end - target_keysets[i] = line.keys - - if line.curve_func then - local valueat = string.format("curves[%s]", string.escape(line.curve_func)) - - code = code .. string.format( - "\n local l%d = value_at_custom(keysets['%s'][%d], t * %s %% %s, %s)", - i, lineset.target_name, i, raw_track.fps, line.period, valueat) - elseif line.channel == animation.CH_TEXTURE then - code = code .. string.format( - "\n local l%d = string_at(keysets['%s'][%d], t * %s %% %s)", - i, lineset.target_name, i, raw_track.fps, line.period) - else - code = code .. string.format( - "\n local l%d = value_at(keysets['%s'][%d], t * %s %% %s, %s)", - i, lineset.target_name, i, raw_track.fps, line.period, line.interp) - end - end + code = code .. string.format("\n local l%d = ", i) + .. codegen_line(raw_track, lineset, line, i, keysets) if line.channel == animation.CH_TRANSLATE then translation[line.axis] = i @@ -190,7 +195,31 @@ local function codegen_track(raw_track, lineset, memoised, keysets, use_tsf) elseif line.channel == animation.CH_ZOOM then code = code .. "\n zoom = l" .. i elseif line.channel == animation.CH_TEXTURE then - code = code .. string.format("\n target:set_texture(%s, %s)", lineset.target_name:escape(), "l"..i) + code = code .. string.format("\n target:set_texture(%s, l%d)", + lineset.target_name:escape(), i) + elseif line.channel == animation.CH_MODEL then + code = code .. string.format("\n target:set_model(bone_index, l%d)", i) + elseif line.channel == animation.CH_SHOW then + if target_type == "bone" then + code = code .. string.format("\n target:set_visible(bone_index, l%d)", i) + else + code = code .. string.format("\n target:set_visible(l%d)", i) + end + elseif line.channel == animation.CH_COLOR then + color[line.axis] = i + end + end + + if color[1] or color[2] or color[3] or color[4] then + local color_vector = "{" .. + (color[1] and ("l" .. color[1]) or '1').. ", " .. + (color[2] and ("l" .. color[2]) or '1').. ", " .. + (color[3] and ("l" .. color[3]) or '1').. ", " .. + (color[4] and ("l" .. color[4]) or '1').. "}" + if target_type == "bone" then + code = code .. "\n target:set_color(" .. color_vector .. ", bone_index)" + else + code = code .. "\n target:set_color(" .. color_vector .. ")" end end @@ -230,17 +259,18 @@ end local function codegen_rig_target(raw_track, context) local code = "\n if target.set_matrix and target.index then\n" for bone, lineset in pairs(raw_track.linesets) do - if lineset.target_type ~= "bone" and lineset.target_type ~= "texture" then + if lineset.target_type ~= "bone" then goto continue end - local lineset_code = codegen_track( - raw_track, lineset, context.memoised, context.keysets, true) + local lineset_code = codegen_track(raw_track, lineset, context.keysets, true, "bone") + code = code .. string.format("\n local bone_index = target:index(%s)", string.escape(bone)) + if context.has_tsf then + code = code .. "\n local dst = target:get_matrix(bone_index)" + end code = code - .. string.format("\n local bone_index = target:index(%s)" - .. "\n local dst = target:get_matrix(bone_index)", string.escape(bone)) .. "\n do" .. lineset_code .. "\n end\n" - if lineset.target_type == "bone" then + if context.has_tsf then code = code .. " target:set_matrix(bone_index, dst)\n" end @@ -279,14 +309,14 @@ local function codegen_native_rig_target(raw_track, context, track_name) end for bone, lineset in pairs(raw_track.linesets) do - if lineset.target_type ~= "bone" and lineset.target_type ~= "texture" then + if lineset.target_type ~= "bone" then goto continue end local lineset_code = codegen_track( - raw_track, lineset, context.memoised, context.keysets, false) + raw_track, lineset, context.keysets, false, "bone") local exported = {} local entry = {name = bone} - if lineset.target_type == "bone" then + do local channels = { [animation.CH_TRANSLATE] = {}, [animation.CH_ROTATE] = {}, @@ -351,18 +381,35 @@ local function codegen_native_rig_target(raw_track, context, track_name) return "\n if target.__native_rig then" .. code end -local function codegen_object_target(raw_track, context) - local code = "\n if target.set_pos then\n" - code = code .. " local dst = mat4.idt()\n" - local lineset = raw_track.linesets[""] - if not lineset then +local function codegen_texture_target(raw_track, context) + local code = "" + for _, lineset in pairs(raw_track.linesets) do + if lineset.target_type == "texture" then + code = code .. "\n do" + .. codegen_track(raw_track, lineset, context.keysets, false, "texture") + .. "\n end\n" + end + end + if #code == 0 then return "" end - local lineset_code = codegen_track( - raw_track, lineset, context.memoised, context.keysets, true) - code = code .. "\n do" .. lineset_code .. "\n end\n" - .. " set_matrix(target, dst)\n" - return code .. " end" + return "\n if target.set_texture then" .. code .. " end\n" +end + +local function codegen_object_target(raw_track, context) + local code = codegen_texture_target(raw_track, context) + local lineset = raw_track.linesets[""] + if not lineset then + return code + end + local lineset_code = codegen_track(raw_track, lineset, context.keysets, true) + code = code .. " local dst = mat4.idt()\n" + .. "\n do" .. lineset_code .. "\n end\n" + + if context.has_tsf then + code = code .. " set_matrix(target, dst)\n" + end + return code end local function codegen_camera_target(raw_track, context) @@ -372,25 +419,37 @@ local function codegen_camera_target(raw_track, context) if not lineset then return "" end - local lineset_code = codegen_track( - raw_track, lineset, context.memoised, context.keysets, false) + local lineset_code = codegen_track(raw_track, lineset, context.keysets, false, "camera") code = code .. "\n do" .. lineset_code .. "\n end\n" .. " target:set_zoom(zoom)\n" return code .. " end" end +local function has_transform_directive(raw_track) + for _, lineset in pairs(raw_track.linesets) do + for _, line in ipairs(lineset.lines) do + if line.channel == animation.CH_TRANSLATE or + line.channel == animation.CH_ROTATE or + line.channel == animation.CH_SCALE then + return true + end + end + end + return false +end + function internals.compile_animation_track(raw_track, track_name) local code = "" local context = { - memoised = {}, keysets = {}, curves = {}, + has_tsf = has_transform_directive(raw_track), } for name, curve in pairs(raw_track.curves) do context.curves[name] = load(string.format( "return function(kl, kr, t) return %s end", - process_expression(curve.func, context.memoised, "curve") + process_expression(curve.func, "curve") ), "", "t", env)() end @@ -403,17 +462,8 @@ function internals.compile_animation_track(raw_track, track_name) code = code .. codegen_object_target(raw_track, context) code = code .. codegen_camera_target(raw_track, context) - local memoised_code = "" - for name, expression in pairs(context.memoised) do - memoised_code = memoised_code .. "\n local " .. name .. " = " - .. expression - end - - if #memoised_code > 0 then - code = memoised_code .. "\n" .. code - end - - local src = "return function(target, t, intensity, m)\n m = m or 1\n intensity = intensity or 1.0\n" + local src = "return function(target, t, intensity, m)\n" + .. " m = m or 1\n intensity = intensity or 1.0\n" .. code .. "\nend" if animation.TRACE_CODEGEN then diff --git a/res/modules/internal/formats/vca.lua b/res/modules/internal/formats/vca.lua index c44d28904..1ebac16f8 100644 --- a/res/modules/internal/formats/vca.lua +++ b/res/modules/internal/formats/vca.lua @@ -8,6 +8,9 @@ local action_to_channel = { scale = animation.CH_SCALE, zoom = animation.CH_ZOOM, texture = animation.CH_TEXTURE, + show = animation.CH_SHOW, + model = animation.CH_MODEL, + color = animation.CH_COLOR, } local curve_to_interp = { @@ -16,6 +19,10 @@ local curve_to_interp = { bezier = animation.INT_BEZIER, } +local boolean_actions = { + show = true +} + local function parse_configure(raw_track, node) if node.fps then raw_track.fps = tonumber(node.fps) @@ -62,6 +69,70 @@ local function parse_simple_frames(line, node) end end +local function parse_boolean_frames(line, node) + line.keys = {} + for j, key_node in ipairs(node) do + local keyframe = { + frame = tonumber(key_node.frame), + value = key_node.value == "on", + } + table.insert(line.keys, keyframe) + end +end + +local function parse_directive(node, raw_track) + local linesets = raw_track.linesets + local tag = node['#'] + if tag == "configure" then + parse_configure(raw_track, node) + return + elseif tag == "curve" then + raw_track.curves[node.name] = node + return + end + + local target_type = nil + if node.bone then + target_type = "bone" + elseif node.zoom then + target_type = "camera" + elseif tag == "texture" then + target_type = "texture" + end + local target_name = node.bone or node.name or "" + local lineset = linesets[target_name] + if not lineset then + lineset = { + lines = {}, + target_type = target_type, + target_name = target_name, + flag = node.flag, + } + linesets[target_name] = lineset + end + + local channel = action_to_channel[tag] + if not channel then + error("unknown directive " .. tag:escape()) + end + local line = { + axis = node.by and (("xyz"):find(node.by) or ("rgba"):find(node.by)) or "", + channel = channel, + period = node.period or animation.MAX_FRAMES + } + if node.func then + line.expression = node.func + elseif node.curve then + parse_curve(line, node) + elseif boolean_actions[tag] then + parse_boolean_frames(line, node) + else + parse_simple_frames(line, node) + end + + table.insert(lineset.lines, line) +end + local function parse_track(root) local raw_track = { duration = math.huge, @@ -69,56 +140,10 @@ local function parse_track(root) linesets = {}, curves = {}, } - local linesets = raw_track.linesets for i, node in ipairs(root) do - if type(node) == "string" then - goto continue + if type(node) == 'table' then + parse_directive(node, raw_track) end - local tag = node['#'] - if tag == "configure" then - parse_configure(raw_track, node) - goto continue - elseif tag == "curve" then - raw_track.curves[node.name] = node - goto continue - end - - local target_type = nil - if node.bone then - target_type = "bone" - elseif tag == "texture" then - target_type = "texture" - end - local target_name = node.bone or node.name or "" - local lineset = linesets[target_name] - if not lineset then - lineset = { - lines = {}, - target_type = target_type, - target_name = target_name - } - linesets[target_name] = lineset - end - - local channel = action_to_channel[tag] - if not channel then - error("unknown directive " .. tag:escape()) - end - local line = { - axis = node.by and ("xyz"):find(node.by) or "", - channel = channel, - period = node.period or animation.MAX_FRAMES - } - if node.func then - line.expression = node.func - elseif node.curve then - parse_curve(line, node) - else - parse_simple_frames(line, node) - end - - table.insert(lineset.lines, line) - ::continue:: end return raw_track end diff --git a/res/modules/internal/lifetime_events.lua b/res/modules/internal/lifetime_events.lua index d1750e4cb..670f92561 100644 --- a/res/modules/internal/lifetime_events.lua +++ b/res/modules/internal/lifetime_events.lua @@ -197,7 +197,9 @@ local function __process_post_runnables() network.__process_events() if not hud or not hud.is_paused() then internals.process_block_register_events() - internals.tick_updating_blocks(time.delta()) + if world.is_open() and world.get_logic("block_ticks") then + internals.tick_updating_blocks(time.delta()) + end end end diff --git a/res/modules/internal/stdcomp.lua b/res/modules/internal/stdcomp.lua index 65048629f..50af846b4 100644 --- a/res/modules/internal/stdcomp.lua +++ b/res/modules/internal/stdcomp.lua @@ -53,6 +53,7 @@ local Skeleton = {__index={ set_model=function(self, i, s) return __skeleton.set_model(self.eid, i, s) end, get_matrix=function(self, i, ...) return __skeleton.get_matrix(self.eid, i, ...) end, set_matrix=function(self, i, m) return __skeleton.set_matrix(self.eid, i, m) end, + get_bone_offset=function(self, i) return __skeleton.get_bone_offset(self.eid, i) end, reset_pose=function(self) return __skeleton.reset_pose(self.eid) end, get_texture=function(self, s) return __skeleton.get_texture(self.eid, s) end, set_texture=function(self, s, s2) return __skeleton.set_texture(self.eid, s, s2) end, diff --git a/res/modules/internal/stream/binary.lua b/res/modules/internal/stream/binary.lua new file mode 100644 index 000000000..9d38f3b9b --- /dev/null +++ b/res/modules/internal/stream/binary.lua @@ -0,0 +1,72 @@ +local binary = {} +binary.__index = binary + +local DEFAULT_CHUNK = 8192 + +function binary.new(stream) + return setmetatable({ stream = stream }, binary) +end + +local function to_table(bytes) + local t = {} + for i = 1, #bytes do + t[i] = bytes[i] + end + return t +end + +function binary.read_all(stream) + local result = Bytearray() + local avail = stream:available() + local chunk = avail > 0 and avail or DEFAULT_CHUNK + + while true do + local part = stream:read_some(chunk) + if #part == 0 then break end + result:append(part) + end + + return result +end + +function binary:read(arg, as_table) + local t = type(arg) + + if t == "number" then + local bytes = self.stream:read(arg) + return as_table and to_table(bytes) or bytes + elseif t == "string" then + local size = byteutil.get_size(arg) + local bytes = self.stream:read(size) + if #bytes < size then + error(string.format( + "unexpected end of stream: format %q needs %d bytes, got %d", + arg, size, #bytes), 2) + end + return byteutil.unpack(arg, bytes) + elseif t == "nil" then + error("in binary mode the first argument must be a byteutil format string" + .. " or the number of bytes to read") + else + error("unknown argument type: " .. t) + end +end + +function binary:write(arg, ...) + local t = type(arg) + + if t == "string" then + self.stream:write(byteutil.pack(arg, ...)) + elseif t == "table" then + self.stream:write(Bytearray(arg)) + else + self.stream:write(arg) + end +end + +function binary:read_fully(as_table) + local bytes = binary.read_all(self.stream) + return as_table and to_table(bytes) or bytes +end + +return binary diff --git a/res/modules/internal/stream/blocking.lua b/res/modules/internal/stream/blocking.lua new file mode 100644 index 000000000..a722a733e --- /dev/null +++ b/res/modules/internal/stream/blocking.lua @@ -0,0 +1,19 @@ +local wrapper = require "internal/stream/wrapper" + +local blocking = wrapper.extend({}) + +function blocking.new(inner) + return setmetatable({ inner = inner }, blocking) +end + +function blocking:read(n) + local result = self.inner:read(n) + while #result < n do + coroutine.yield() + if not self.inner:is_alive() then break end + result:append(self.inner:read(n - #result)) + end + return result +end + +return blocking diff --git a/res/modules/internal/stream/buffered.lua b/res/modules/internal/stream/buffered.lua new file mode 100644 index 000000000..621e78ebd --- /dev/null +++ b/res/modules/internal/stream/buffered.lua @@ -0,0 +1,90 @@ +local wrapper = require "internal/stream/wrapper" + +local buffered = wrapper.extend({}) + +buffered.DEFAULT_SIZE = 8192 + +function buffered.new(inner, size, flush_inner) + return setmetatable({ + inner = inner, + size = size or buffered.DEFAULT_SIZE, + flush_inner = flush_inner ~= false, + rbuf = Bytearray(), + wbuf = Bytearray(), + }, buffered) +end + +function buffered:_take(n) + local buf = self.rbuf + if n >= #buf then + self.rbuf = Bytearray() + return buf + end + local part = buf:slice(1, n) + buf:remove(1, n) + return part +end + +function buffered:flush_buffer() + if #self.wbuf > 0 then + local data = self.wbuf + self.wbuf = Bytearray() + self.inner:write(data) + end +end + +function buffered:read(n) + local have = #self.rbuf + if have < n then + if have == 0 and n >= self.size then + return self.inner:read(n) + end + self.rbuf:append(self.inner:read(self.size - have)) + end + return self:_take(n) +end + +buffered.read_some = buffered.read + +function buffered:write(data) + if #self.wbuf + #data > self.size then + self:flush_buffer() + end + if #data >= self.size then + self.inner:write(data) + else + self.wbuf:append(data) + end +end + +function buffered:flush() + self:flush_buffer() + if self.flush_inner then + self.inner:flush() + end +end + +function buffered:available() + return self.inner:available() + #self.rbuf +end + +function buffered:seek(mode, offset) + self:flush_buffer() + if mode == "c" then + offset = offset - #self.rbuf + end + self.rbuf = Bytearray() + self.inner:seek(mode, offset) +end + +function buffered:tell() + return self.inner:tell() - #self.rbuf + #self.wbuf +end + +function buffered:close() + self:flush_buffer() + self.rbuf = Bytearray() + return self.inner:close() +end + +return buffered diff --git a/res/modules/internal/stream/raw.lua b/res/modules/internal/stream/raw.lua new file mode 100644 index 000000000..b7db77919 --- /dev/null +++ b/res/modules/internal/stream/raw.lua @@ -0,0 +1,49 @@ +local raw = {} +raw.__index = raw + +function raw.new(descriptor, io_lib) + return setmetatable({ descriptor = descriptor, io_lib = io_lib }, raw) +end + +function raw:read(n) + return self.io_lib.read(self.descriptor, n) +end + +raw.read_some = raw.read + +function raw:write(data) + self.io_lib.write(self.descriptor, data) +end + +function raw:flush() + if self.io_lib.flush then + self.io_lib.flush(self.descriptor) + elseif not self:is_alive() then + error("stream is closed") + end +end + +function raw:available() + local f = self.io_lib.available + return f and f(self.descriptor) or 0 +end + +function raw:seek(mode, offset) + if not self.io_lib.seek then error("cannot seek this stream") end + self.io_lib.seek(self.descriptor, mode, offset) +end + +function raw:tell() + if not self.io_lib.tell then error("cannot tell this stream") end + return self.io_lib.tell(self.descriptor) +end + +function raw:is_alive() + return self.io_lib.is_alive(self.descriptor) +end + +function raw:close() + return self.io_lib.close(self.descriptor) +end + +return raw diff --git a/res/modules/internal/stream/text.lua b/res/modules/internal/stream/text.lua new file mode 100644 index 000000000..835340b47 --- /dev/null +++ b/res/modules/internal/stream/text.lua @@ -0,0 +1,102 @@ +local binary = require "internal/stream/binary" + +local text = {} +text.__index = text + +local CR = string.byte('\r') +local LF = string.byte('\n') + +function text.new(stream) + return setmetatable({stream = stream}, text) +end + +function text:_read_byte() + return self.stream:read(1)[1] +end + +function text:read_line() + local line = Bytearray() + local got_any = false + + while true do + local b = self:_read_byte() + if b == nil then break end + got_any = true + + if b == LF then + break + elseif b == CR then + local nb = self:_read_byte() + if nb == LF then break end + line:append(CR) + if nb == nil then break end + line:append(nb) + else + line:append(b) + end + end + + if not got_any then return nil end + return utf8.tostring(line) +end + +local function trim_empty(lines) + while #lines > 0 and lines[#lines] == "" do + lines[#lines] = nil + end + while #lines > 0 and lines[1] == "" do + table.remove(lines, 1) + end +end + +function text:read_lines(count, trim) + if count < 0 then error("count of lines to read must be positive") end + + local lines = {} + for i = 1, count do + local line = self:read_line() + if line == nil then break end + lines[i] = line + end + + if trim ~= false then trim_empty(lines) end + return lines +end + +function text:read(count, trim) + if count == nil then + return self:read_line() + end + return self:read_lines(count, trim) +end + +function text:read_fully(as_lines) + if as_lines then + local lines = {} + for line in self.read_line, self do + lines[#lines + 1] = line + end + return lines + end + return utf8.tostring(binary.read_all(self.stream)) +end + +function text:write_line(str) + self.stream:write(utf8.tobytes(str .. "\n")) +end + +-- write(string) | write({ lines... }) +function text:write(arg) + local t = type(arg) + if t == "string" then + self:write_line(arg) + elseif t == "table" then + for i = 1, #arg do + self:write_line(arg[i]) + end + else + error("unknown argument type: " .. t) + end +end + +return text diff --git a/res/modules/internal/stream/wrapper.lua b/res/modules/internal/stream/wrapper.lua new file mode 100644 index 000000000..c6c838aff --- /dev/null +++ b/res/modules/internal/stream/wrapper.lua @@ -0,0 +1,26 @@ +local wrapper = {} +wrapper.__index = wrapper + +function wrapper.extend(cls) + cls.__index = cls + return setmetatable(cls, { __index = wrapper }) +end +function wrapper:read(n) return self.inner:read(n) end + +function wrapper:read_some(n) return self.inner:read_some(n) end + +function wrapper:write(data) return self.inner:write(data) end + +function wrapper:flush() return self.inner:flush() end + +function wrapper:available() return self.inner:available() end + +function wrapper:seek(mode, off) return self.inner:seek(mode, off) end + +function wrapper:tell() return self.inner:tell() end + +function wrapper:is_alive() return self.inner:is_alive() end + +function wrapper:close() return self.inner:close() end + +return wrapper diff --git a/res/modules/inventory_utils.lua b/res/modules/inventory_utils.lua index 17089cdab..832eb4f19 100644 --- a/res/modules/inventory_utils.lua +++ b/res/modules/inventory_utils.lua @@ -2,7 +2,9 @@ local M = {} function M.share_default_func(invid, slotid) local blockinv = hud.get_block_inventory() - local playerinv = player.get_inventory(hud.get_player()) + local pid = hud.get_player() + local playerinv = player.get_inventory(pid) + local hotbar_size = player.get_hotbar_size(pid) if blockinv ~= 0 then if invid == blockinv then inventory.move(blockinv, slotid, playerinv) @@ -11,10 +13,10 @@ function M.share_default_func(invid, slotid) end elseif rules.get("allow-content-access") then inventory.set(invid, slotid, 0, 0) - elseif slotid < 10 then - inventory.move_range(invid, slotid, invid, 10) + elseif slotid < hotbar_size then + inventory.move_range(invid, slotid, invid, hotbar_size) else - inventory.move_range(invid, slotid, invid, 0, 9) + inventory.move_range(invid, slotid, invid, 0, hotbar_size - 1) end end diff --git a/res/modules/io_stream.lua b/res/modules/io_stream.lua index 8776ca810..cd318c72c 100644 --- a/res/modules/io_stream.lua +++ b/res/modules/io_stream.lua @@ -1,444 +1,108 @@ -local io_stream = { } +local raw = require "internal/stream/raw" +local buffered = require "internal/stream/buffered" +local blocking = require "internal/stream/blocking" +local binary = require "internal/stream/binary" +local text = require "internal/stream/text" +local io_stream = {} io_stream.__index = io_stream -local MAX_BUFFER_SIZE = 8192 - -local DEFAULT_MODE = "default" -local BUFFERED_MODE = "buffered" -local YIELD_MODE = "yield" - -local ALL_MODES = { - DEFAULT_MODE, - BUFFERED_MODE, - YIELD_MODE -} - -local FLUSH_MODE_ALL = "all" -local FLUSH_MODE_ONLY_BUFFER = "buffer" - -local ALL_FLUSH_MODES = { - FLUSH_MODE_ALL, - FLUSH_MODE_ONLY_BUFFER -} - -local CR = string.byte('\r') -local LF = string.byte('\n') - -local function read_fully(result, read_func) - local isTable = type(result) == "table" - - local buf - - repeat - buf = read_func(MAX_BUFFER_SIZE) - - if isTable then - for i = 1, #buf do - result[#result + 1] = buf[i] - end - else result:append(buf) end - until #buf == 0 -end - ---[[ -descriptor - descriptor of stream for provided I/O library -binaryMode - if enabled, most methods will expect bytes instead of strings -ioLib - I/O library. Should include the following functions: - read(descriptor: int, length: int) -> Bytearray - May return bytearray with a smaller size if bytes have not arrived yet or have run out - May throw error if descriptor isn't readable - write(descriptor: int, data: Bytearray) - May throw error if descriptor isn't writeable - [optional] seek(descriptor: int, mode: string, offset: int) - Mode may be 'b' (relative begin), 'c' (relative current), 'e' (relative end + 1) - [optional] tell(descriptor: int) -> int - [optional] flush(descriptor: int) - [optional] available(descriptor: int) -> int - is_alive(descriptor: int) -> bool - close(descriptor: int) ---]] +local MODES = { default = true, buffered = true, yield = true } +local FLUSH_MODES = { all = true, buffer = true } function io_stream.new(descriptor, binary_mode, io_lib, mode, flush_mode) - mode = mode or DEFAULT_MODE - flush_mode = flush_mode or FLUSH_MODE_ALL - - local self = setmetatable({}, io_stream) - - self.descriptor = descriptor - self.binary_mode = binary_mode - self.max_buffer_size = MAX_BUFFER_SIZE - self.io_lib = io_lib - - self:set_mode(mode) - self:set_flush_mode(flush_mode) + local self = setmetatable({ + descriptor = descriptor, + io_lib = io_lib, + binary_mode = binary_mode and true or false, + max_buffer_size = buffered.DEFAULT_SIZE, + }, io_stream) + self:set_flush_mode(flush_mode or "all") + self:set_mode(mode or "default") return self end -function io_stream:is_binary_mode() - return self.binary_mode +function io_stream:_rebuild() + local old = self.stream + if old and old.flush_buffer and old:is_alive() then + old:flush_buffer() + end + + local s = raw.new(self.descriptor, self.io_lib) + if self.mode == "buffered" then + s = buffered.new(s, self.max_buffer_size, self.flush_mode == "all") + elseif self.mode == "yield" then + s = blocking.new(s) + end + + self.stream = s + self.text = text.new(s) + self.binary = binary.new(s) end -function io_stream:set_binary_mode(binary_mode) - self.binary_mode = binary_mode ~= nil +function io_stream:_format() + return self.binary_mode and self.binary or self.text end -function io_stream:get_mode() - return self.mode -end +function io_stream:is_binary_mode() return self.binary_mode end +function io_stream:set_binary_mode(v) self.binary_mode = v and true or false end + +function io_stream:get_mode() return self.mode end function io_stream:set_mode(mode) - if not table.has(ALL_MODES, mode) then - error("invalid stream mode: "..mode) - end - - if self.write_buffer then - self.write_buffer:clear() - self.write_buffer = nil - end - - if self.read_buffer then - self.read_buffer:clear() - self.read_buffer = nil - end - - if mode == BUFFERED_MODE then - self.write_buffer = Bytearray(self.max_buffer_size) - self.read_buffer = Bytearray(self.max_buffer_size) - end - + if not MODES[mode] then error("invalid stream mode: " .. tostring(mode)) end self.mode = mode + self:_rebuild() end -function io_stream:get_flush_mode() - return self.flush_mode -end +function io_stream:get_flush_mode() return self.flush_mode end function io_stream:set_flush_mode(flush_mode) - if not table.has(ALL_FLUSH_MODES, flush_mode) then - error("invalid flush mode: " .. flush_mode) + if not FLUSH_MODES[flush_mode] then + error("invalid flush mode: " .. tostring(flush_mode)) end - self.flush_mode = flush_mode + if self.mode == "buffered" then + self.stream.flush_inner = flush_mode == "all" + end end -function io_stream:get_max_buffer_size() - return self.max_buffer_size +function io_stream:get_max_buffer_size() return self.max_buffer_size end + +function io_stream:set_max_buffer_size(size) + self.max_buffer_size = size + if self.mode == "buffered" then self:_rebuild() end end -function io_stream:set_max_buffer_size(max_buffer_size) - self.max_buffer_size = max_buffer_size +function io_stream:read(arg, use_table) return self:_format():read(arg, use_table) end - self.write_buffer = Bytearray(self.max_buffer_size) - self.read_buffer = Bytearray(self.max_buffer_size) -end +function io_stream:write(arg, ...) return self:_format():write(arg, ...) end + +function io_stream:read_fully(use_table) return self:_format():read_fully(use_table) end + +function io_stream:read_line() return self.text:read_line() end + +function io_stream:write_line(str) return self.text:write_line(str) end function io_stream:available(length) - local available = self.io_lib.available and self.io_lib.available(self.descriptor) or 0 - - if self.mode == BUFFERED_MODE then - available = available + #self.read_buffer - end - - if not length then - return available - else - return available >= length - end + local n = self.stream:available() + if length then return n >= length end + return n end -function io_stream:__read(length, from_read_fully) - if self.mode == YIELD_MODE then - if from_read_fully then - return self.io_lib.read(self.descriptor, length) - end +function io_stream:seek(mode, offset) return self.stream:seek(mode, offset) end - local buffer = Bytearray() +function io_stream:tell() return self.stream:tell() end - while #buffer < length do - buffer:append(self.io_lib.read(self.descriptor, length - #buffer)) +function io_stream:is_alive() return self.stream:is_alive() end - if #buffer < length then coroutine.yield() end - end +function io_stream:is_closed() return not self.stream:is_alive() end - return buffer - elseif self.mode == BUFFERED_MODE then - local buf_len = #self.read_buffer - - if buf_len < length then - self.read_buffer:append( - self.io_lib.read(self.descriptor, self.max_buffer_size - buf_len) - ) - end - - buf_len = #self.read_buffer - - length = math.min(buf_len, length) - - local copy = self.read_buffer:slice(1, length) - - if buf_len == length then - self.read_buffer:clear() - else - self.read_buffer:remove(1, length) - end - - return copy - elseif self.mode == DEFAULT_MODE then - return self.io_lib.read(self.descriptor, length) - end -end - -function io_stream:__write(data) - if self.mode == BUFFERED_MODE then - local data_length = #data - - if #self.write_buffer + data_length > self.max_buffer_size then - self:flush() - end - - if data_length > self.max_buffer_size then - local to_write = math.floor(data_length / self.max_buffer_size) * self.max_buffer_size - local to_save = data_length - to_write - - self.io_lib.write(self.descriptor, data:slice(1, to_write)) - - self:flush() - - self.write_buffer = data:slice(to_write + 1, to_save) - else self.write_buffer:append(data) end - elseif self.mode == DEFAULT_MODE or self.mode == YIELD_MODE then - return self.io_lib.write(self.descriptor, data) - end -end - -function io_stream:read_fully(use_table) - if self.binary_mode then - local result = use_table and { } or Bytearray() - - local avail = self:available() - - if avail == 0 then - avail = self.max_buffer_size - end - - read_fully(result, function() return self:__read(avail, true) end) - - return result - else - if use_table then - local lines = { } - - local line - - repeat - line = self:read_line() - - lines[#lines + 1] = line - until not line - - return lines - else - local result = Bytearray() - - read_fully(result, function() return self:__read(self.max_buffer_size) end) - - return utf8.tostring(result) - end - end -end - -function io_stream:read_line() - local result = Bytearray() - - local first = true - - while true do - local char = self:__read(1) - - if #char == 0 then - if first then return else break end - end - - char = char[1] - - if char == LF then break - elseif char == CR then - char = self:__read(1) - - if char[1] == LF then break - else - result:append(CR) - result:append(char[1]) - end - else result:append(char) end - - first = false - end - - return utf8.tostring(result) -end - -function io_stream:write_line(str) - self:__write(utf8.tobytes(str .. "\n")) -end - -function io_stream:read(arg, use_table) - local arg_type = type(arg) - - if self.binary_mode then - local byte_arr - - if arg_type == "number" then - -- using 'arg' as length - - byte_arr = self:__read(arg) - - if use_table == true then - local t = { } - - for i = 1, #byte_arr do - t[i] = byte_arr[i] - end - - return t - else - return byte_arr - end - elseif arg_type == "string" then - return byteutil.unpack( - arg, - self:__read(byteutil.get_size(arg)) - ) - elseif arg_type == "nil" then - error( - "in binary mode the first argument must be a string data format".. - " for the library \"byteutil\" or the number of bytes to read" - ) - else - error("unknown argument type: "..arg_type) - end - else - if not arg then - return self:read_line() - else - local lines_count = arg - local trim_last_empty_lines = use_table - - if use_table == nil then - trim_last_empty_lines = true - end - - if lines_count < 0 then error "count of lines to read must be positive" end - - local result = { } - - for i = 1, lines_count do - result[i] = self:read_line() - end - - if trim_last_empty_lines then - local i = #result - - while i >= 0 do - local length = utf8.length(result[i]) - - if length > 0 then break - else result[i] = nil end - - i = i - 1 - end - - local i = 1 - - while #result > 0 do - local length = utf8.length(result[i]) - - if length > 0 then break - else table.remove(result, i) end - end - end - - return result - end - end -end - -function io_stream:write(arg, ...) - local arg_type = type(arg) - - if self.binary_mode then - local byte_arr - - if arg_type ~= "string" then - -- using arg as bytes table/bytearray - - if arg_type == "table" then - byte_arr = Bytearray(arg) - else - byte_arr = arg - end - else - byte_arr = byteutil.pack(arg, ...) - end - - self:__write(byte_arr) - else - if arg_type == "string" then - self:write_line(arg) - elseif arg_type == "table" then - for i = 1, #arg do - self:write_line(arg[i]) - end - else error("unknown argument type: "..arg_type) end - end -end - -function io_stream:seek(mode, offset) - if not self.io_lib.seek then - error("cannot seek this stream") - end - - self.io_lib.seek(self.descriptor, mode, offset) -end - -function io_stream:tell() - if not self.io_lib.tell then - error("cannot tell this stream") - end - - return self.io_lib.tell(self.descriptor) -end - -function io_stream:is_alive() - return self.io_lib.is_alive(self.descriptor) -end - -function io_stream:is_closed() - return not self:is_alive() -end - -function io_stream:close() - if self.mode == BUFFERED_MODE then - self.read_buffer:clear() - self.write_buffer:clear() - end - - return self.io_lib.close(self.descriptor) -end +function io_stream:close() return self.stream:close() end function io_stream:flush() - if self.mode == BUFFERED_MODE and #self.write_buffer > 0 then - self.io_lib.write(self.descriptor, self.write_buffer) - self.write_buffer:clear() - end - - if self.flush_mode ~= FLUSH_MODE_ONLY_BUFFER then - if self.io_lib.flush then - self.io_lib.flush(self.descriptor) - elseif self:is_closed() then error("stream is closed") end - end + if self.mode ~= "buffered" and self.flush_mode == "buffer" then return end + self.stream:flush() end - -return io_stream \ No newline at end of file +return io_stream diff --git a/res/preload.json b/res/preload.json index 51acb129c..6bdbbeb3f 100644 --- a/res/preload.json +++ b/res/preload.json @@ -5,7 +5,9 @@ "main", "lines", "entity", + "model", "translucent", + "translucent_composite", "background", "skybox_gen", "shadows", @@ -23,37 +25,11 @@ } ], "textures": [ - "gui/menubg", - "gui/delete_icon", - "gui/no_icon", - "gui/no_world_icon", - "gui/warning", - "gui/error", - "gui/cross", - "gui/refresh", - "gui/folder_icon", - "gui/settings_icon", - "misc/rain", - "misc/snow", - "gui/check_mark", - "gui/left_arrow", - "gui/right_arrow", - "gui/lock", - "gui/save", - "gui/block", - "gui/item", - "gui/file", - "gui/module", - "gui/play", - "gui/info", - "gui/world", - "gui/hud", - "gui/entity", - "gui/half_block", { "name": "", "path": "textures/misc/blank" - } + }, + "gui/*" ], "fonts": [ { diff --git a/res/scripts/components/pathfinding.lua b/res/scripts/components/pathfinding.lua index fd5990280..bda08ae5a 100644 --- a/res/scripts/components/pathfinding.lua +++ b/res/scripts/components/pathfinding.lua @@ -5,8 +5,11 @@ local started local tsf = entity.transform local body = entity.rigidbody +local size = body:get_size() agent = pathfinding.create_agent() pathfinding.set_max_visited(agent, 1e3) +pathfinding.set_width(agent, math.max(size[1], size[3])) +pathfinding.set_height(agent, math.ceil(size[2])) pathfinding.avoid_tag(agent, "core:liquid", 8) function set_target(new_target) diff --git a/res/scripts/hud.lua b/res/scripts/hud.lua index 562fe19d1..a7c43a71a 100644 --- a/res/scripts/hud.lua +++ b/res/scripts/hud.lua @@ -43,7 +43,8 @@ function on_hud_open() end local id = block.get_picking_item(block.get(x, y, z)) local inv, cur_slot = player.get_inventory(pid) - local slot = inventory.find_by_item(inv, id, 0, 9) + local hotbar_size = player.get_hotbar_size(pid) + local slot = inventory.find_by_item(inv, id, 0, hotbar_size) if slot then player.set_selected_slot(pid, slot) return @@ -51,7 +52,7 @@ function on_hud_open() if not rules.get("allow-content-access") then return end - slot = inventory.find_by_item(inv, 0, 0, 9) + slot = inventory.find_by_item(inv, 0, 0, hotbar_size) if slot then cur_slot = slot end diff --git a/res/scripts/hud_classes.lua b/res/scripts/hud_classes.lua index e6259e22e..0d1804847 100644 --- a/res/scripts/hud_classes.lua +++ b/res/scripts/hud_classes.lua @@ -16,14 +16,16 @@ local Skeleton = {__index={ index=function(self, s) return gfx.skeletons.index(self.name, s) end, get_model=function(self, i) return gfx.skeletons.get_model(self.name, i) end, set_model=function(self, i, s) return gfx.skeletons.set_model(self.name, i, s) end, - get_matrix=function(self, i) return gfx.skeletons.get_matrix(self.name, i) end, + get_matrix=function(self, i, ...) return gfx.skeletons.get_matrix(self.name, i, ...) end, + reset_pose=function(self, ...) return gfx.skeletons.reset_pose(self.name, ...) end, set_matrix=function(self, i, m) return gfx.skeletons.set_matrix(self.name, i, m) end, + get_bone_offset=function(self, i) return gfx.skeletons.get_bone_offset(self.name, i) end, get_texture=function(self, i) return gfx.skeletons.get_texture(self.name, i) end, set_texture=function(self, i, s) return gfx.skeletons.set_texture(self.name, i, s) end, - is_visible=function(self, i) return gfx.skeletons.is_visible(self.name, i) end, - set_visible=function(self, i, b) return gfx.skeletons.set_visible(self.name, i, b) end, - get_color=function(self, i) return gfx.skeletons.get_color(self.name, i) end, - set_color=function(self, i, c) return gfx.skeletons.set_color(self.name, i, c) end, + is_visible=function(self, ...) return gfx.skeletons.is_visible(self.name, ...) end, + set_visible=function(self, ...) return gfx.skeletons.set_visible(self.name, ...) end, + get_color=function(self, ...) return gfx.skeletons.get_color(self.name, ...) end, + set_color=function(self, ...) return gfx.skeletons.set_color(self.name, ...) end, }} gfx.text3d.new = function(pos, text, preset, extension) diff --git a/res/scripts/post_content.lua b/res/scripts/post_content.lua index 97b2e93b6..51b6e627f 100644 --- a/res/scripts/post_content.lua +++ b/res/scripts/post_content.lua @@ -2,7 +2,7 @@ local app = __vc_app local internals = __vc_internals local user_props = file.read_combined_object("config/user-props.toml") -local names = { +local core_names = { "parent", "caption", "texture", "texture-faces", "model", "model-name", "model-primitives", "material", "rotation", "hitboxes", "hitbox", "emission", "size", "obstacle", "replaceable", "light-passing", "sky-light-passing", @@ -10,35 +10,61 @@ local names = { "hidden", "draw-group", "picking-item", "surface-replacement", "script-name", "ui-layout", "inventory-size", "tick-interval", "overlay-texture", "translucent", "fields", "particles", "icon-type", "icon", "placing-block", - "stack-size", "name", "script-file", "culling", "solid" + "stack-size", "name", "script-file", "culling", "solid", + "components", "sensors", "body-type", "save", "save-skeleton-pose", + "save-skeleton-textures", "save-body-velocity", "save-body-settings", + "skeleton-name", "lighting-mode", "mass", "elasticity", "step-height", + "blocking", "material", "translucent", "uv-lock" } for name, _ in pairs(user_props) do - table.insert(names, name) + table.insert(core_names, name) +end + +local function get_parent_props(lib, props) + if not props.parent then + return {} + end + if lib == entities then + local parent_id = entities.def_index(props.parent) + if parent_id == nil then + return {} + end + return entities.properties[parent_id] or {} + end + if lib.index == nil then + return {} + end + local parent_id = lib.index(props.parent) + if parent_id == nil then + return {} + end + return lib.properties[parent_id] or {} end -- remove undefined properties and build tags set local function process_properties(lib) for id, props in pairs(lib.properties) do - if props.parent then - local parent_props = lib.properties[block.index(props.parent)] or {} - for propname, value in pairs(parent_props) do - if not props[propname] then - props[propname] = value - end + local parent_props = get_parent_props(lib, props) + for propname, value in pairs(parent_props) do + if not props[propname] then + props[propname] = value end end for propname, _ in pairs(props) do - if not table.has(names, propname) then + if not table.has(core_names, propname) then props[propname] = nil end end - props.tags_set = lib.__get_tags(id) + if lib.__get_tags then + props.tags_set = lib.__get_tags(id) + end end end process_properties(block) process_properties(item) +process_properties(entities) local function make_read_only(t) setmetatable(t, { @@ -53,6 +79,16 @@ for k,v in pairs(block.properties) do make_read_only(v) end +make_read_only(item.properties) +for k,v in pairs(item.properties) do + make_read_only(v) +end + +make_read_only(entities.properties) +for k,v in pairs(entities.properties) do + make_read_only(v) +end + local function cache_names(library) local indices = {} local names = {} @@ -87,6 +123,26 @@ end cache_names(block) cache_names(item) +local function cache_entity_names() + local indices = {} + local names = {} + for id=0, entities.defs_count() - 1 do + local name = entities.properties[id].name + indices[name] = id + names[id] = name + end + + function entities.name(id) + return names[id] + end + + function entities.index(name) + return indices[name] + end +end + +cache_entity_names() + __vc_scripts_registry.build_registry() local packs = app.get_content() diff --git a/res/scripts/stdlib.lua b/res/scripts/stdlib.lua index 868a8b635..97d4e0342 100644 --- a/res/scripts/stdlib.lua +++ b/res/scripts/stdlib.lua @@ -27,6 +27,7 @@ local function tb_frame_tostring(frame) end local __vc__app_script_coroutine +local __vc_process_streams = { stdin = {}, stdout = {} } local function complete_app_lib(app) local tick_required = true @@ -39,6 +40,45 @@ local function complete_app_lib(app) end local __app_set_setting = app.set_setting local __app_quit = app.quit + local __app_get_stdout_stream = app.get_stdout_stream + local __app_get_stdin_stream = app.get_stdin_stream + local io_stream = require "core:io_stream" + local stdio_stream_lib = { + read = file.__read_descriptor, + write = file.__write_descriptor, + seek = file.__seek_descriptor, + tell = file.__tell_descriptor, + flush = file.__flush_descriptor, + available = file.__available_descriptor, + is_alive = file.__has_descriptor, + close = file.__close_descriptor, + } + + local function get_process_stream(kind, handle, getter) + local cache = __vc_process_streams[kind] + local stream = cache[handle] + if stream and stream:is_alive() then + return stream + end + cache[handle] = nil + + local descriptor = getter(handle) + if descriptor == nil then + return nil + end + + stream = io_stream.new(descriptor, false, stdio_stream_lib) + cache[handle] = stream + return stream + end + + app.get_stdout_stream = function(handle) + return get_process_stream("stdout", handle, __app_get_stdout_stream) + end + + app.get_stdin_stream = function(handle) + return get_process_stream("stdin", handle, __app_get_stdin_stream) + end app.sleep = sleep app.script = __VC_SCRIPT_NAME diff --git a/res/shaders/effects/deferred_lighting.glsl b/res/shaders/effects/deferred_lighting.glsl index ebcf138aa..aa7218dbf 100644 --- a/res/shaders/effects/deferred_lighting.glsl +++ b/res/shaders/effects/deferred_lighting.glsl @@ -1,24 +1,28 @@ -#include +#include #include #define CLOUDS_FOG_FACTOR_MUL 0.3f #define CLOUDS_FOG_CURVE_MUL 0.4f -#define COLOR_TEMPERATURE_COMPENSATION 1.12f vec4 effect() { vec4 pos = texture(u_position, v_uv); - float light = 1.0; + float ao = 1.0; #ifdef ENABLE_SSAO - light = 0.0; - float z = pos.z; - for (int y = -2; y <= 2; y++) { - for (int x = -2; x <= 2; x++) { - vec2 offset = vec2(x, y) / u_screenSize; - light += texture(u_ssao, v_uv + offset * 2.0).r; + vec2 texel = 2.0 / u_screenSize; + float centerZ = pos.z; + float sum = 0.0; + float wsum = 0.0; + for (int y = -2; y < 2; y++) { + for (int x = -2; x < 2; x++) { + vec2 uv = v_uv + vec2(x, y) * texel; + float z = texture(u_position, uv).z; + float w = exp(-abs(centerZ - z) / (abs(centerZ) * 0.05 + 0.001)); + sum += texture(u_ssao, uv).r * w; + wsum += w; } } - light /= 24.0; + ao = sum / wsum; #endif // ENABLE_SSAO vec4 modelpos = u_inverseView * pos; @@ -26,18 +30,7 @@ vec4 effect() { vec3 dir = modelpos.xyz - u_cameraPos; float emission = texture(u_emission, v_uv).r; - - float rg = 1.0; -#ifdef ENABLE_SHADOWS - float shadow_mul = calc_shadow(modelpos, normal, length(pos)); - light *= shadow_mul; - rg *= min(1.0, shadow_mul + emission) * COLOR_TEMPERATURE_COMPENSATION; - light *= 2.0; -#endif - - light = max(light, emission); - - light = pow(light, u_gamma); + vec3 light = calc_deferred_light(modelpos, normal, length(pos), emission, ao); vec3 fogColor = texture(u_skybox, dir).rgb; float fog = calc_fog( @@ -45,5 +38,5 @@ vec4 effect() { mix(1.0, CLOUDS_FOG_FACTOR_MUL, emission), mix(1.0, CLOUDS_FOG_CURVE_MUL, emission) ); - return vec4(mix(texture(u_screen, v_uv).rgb * mix(1.0, light, 1.0) * vec3(rg, 0.5 + rg * 0.5, 1.0), fogColor, fog), 1.0); + return vec4(mix(texture(u_screen, v_uv).rgb * light, fogColor, fog), 1.0); } diff --git a/res/shaders/entity.glslf b/res/shaders/entity.glslf index 47883c327..701d481fb 100644 --- a/res/shaders/entity.glslf +++ b/res/shaders/entity.glslf @@ -1,63 +1 @@ -layout (location = 0) out vec4 f_color; -layout (location = 1) out vec4 f_position; -layout (location = 2) out vec4 f_normal; -layout (location = 3) out vec4 f_emission; - -#include - -in vec4 a_color; - -uniform sampler2D u_texture0; - -uniform vec3 u_fogColor; -uniform float u_fogFactor; -uniform float u_fogCurve; -uniform bool u_alphaClip; -uniform bool u_dithering; -uniform vec3 u_sunDir; - -const float BAYER_MATRIX[64] = float[]( - 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, - 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, - 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, - 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, - 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, - 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, - 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, - 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0 -); - -float calc_bayer(vec2 pos){ - ivec2 p = ivec2(mod(pos, 8.0)); - return BAYER_MATRIX[p.y * 8 + p.x] / 64.0; -} - -void main() { - vec4 texColor = texture(u_texture0, a_texCoord); - float alpha = a_color.a * texColor.a; - // anyway it's any alpha-test alternative required - if (u_dithering) { - if (u_alphaClip) { - float bayer = calc_bayer(gl_FragCoord.xy); - if (alpha - bayer < 0.01f) { - discard; - } - alpha = 1.0; - } else if (alpha < 0.05f) { - discard; - } - } else if (alpha < (u_alphaClip ? 0.5f : 0.15f)) { - discard; - } - f_color = a_color * texColor; - -#ifndef ADVANCED_RENDER - vec3 fogColor = texture(u_skybox, a_dir).rgb; - f_color = mix(f_color, vec4(fogColor, 1.0), a_fog); -#endif - - f_color.a = alpha; - f_position = vec4(a_position, 1.0); - f_normal = vec4(a_normal, 1.0); - f_emission = vec4(vec3(a_emission), 1.0); -} +#include diff --git a/res/shaders/lib/constants.glsl b/res/shaders/lib/constants.glsl index a8a9a4bb3..c41686b5e 100644 --- a/res/shaders/lib/constants.glsl +++ b/res/shaders/lib/constants.glsl @@ -8,8 +8,8 @@ #define CURVATURE_FACTOR 0.002 // lighting -#define SKY_LIGHT_MUL 2.5 -#define SKY_LIGHT_TINT (vec3(1.0, 0.75, 0.6) * 2.0) +#define SKY_LIGHT_MUL 4.0 +#define SKY_LIGHT_TINT (vec3(1.0, 0.2, 0.2) * 2.0) // fog #define FOG_POS_SCALE vec3(1.0, 0.2, 1.0) diff --git a/res/shaders/lib/deferred_light.glsl b/res/shaders/lib/deferred_light.glsl new file mode 100644 index 000000000..defaf19a7 --- /dev/null +++ b/res/shaders/lib/deferred_light.glsl @@ -0,0 +1,24 @@ +#ifndef DEFERRED_LIGHT_GLSL_ +#define DEFERRED_LIGHT_GLSL_ + +#include + +#define COLOR_TEMPERATURE_COMPENSATION 1.14f + +vec3 calc_deferred_light( + vec4 modelpos, vec3 normal, float distance, float emission, float ao +) { + float light = ao; + float rg = 1.0; +#ifdef ENABLE_SHADOWS + float shadow_mul = calc_shadow(modelpos, normal, distance); + light *= shadow_mul; + rg *= min(1.0, shadow_mul + emission) * COLOR_TEMPERATURE_COMPENSATION; + light *= 2.0; +#endif + light = max(light, emission); + light = pow(light, u_gamma); + return light * vec3(rg, 0.5 + rg * 0.5, 1.0); +} + +#endif // DEFERRED_LIGHT_GLSL_ diff --git a/res/shaders/lib/entity_fragment.glsl b/res/shaders/lib/entity_fragment.glsl new file mode 100644 index 000000000..736d8fe5d --- /dev/null +++ b/res/shaders/lib/entity_fragment.glsl @@ -0,0 +1,71 @@ +layout (location = 0) out vec4 f_color; +layout (location = 1) out vec4 f_position; +layout (location = 2) out vec4 f_normal; +layout (location = 3) out vec4 f_emission; + +uniform vec3 u_sunDir; + +#include +#include + +in vec4 a_color; + +uniform sampler2D u_texture0; +uniform float u_alphaThreshold; +uniform bool u_opaque; +uniform bool u_forward; +uniform bool u_forwardLight; +uniform bool u_alphaClip; + +const float BAYER_MATRIX[64] = float[]( + 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, + 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, + 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, + 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, + 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, + 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, + 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, + 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0 +); + +float calc_bayer(vec2 pos){ + ivec2 p = ivec2(mod(pos, 8.0)); + return BAYER_MATRIX[p.y * 8 + p.x] / 64.0; +} + +void main() { + vec4 texColor = texture(u_texture0, a_texCoord); + float alpha = a_color.a * texColor.a; + if (u_opaque) { + float bayer = calc_bayer(gl_FragCoord.xy); + if (alpha - bayer < 0.01) { + discard; + } + alpha = 1.0; + } else { + if (alpha < u_alphaThreshold) { + discard; + } + } + f_color = a_color * texColor; + +#ifdef ADVANCED_RENDER + if (u_forward) { + if (u_forwardLight) { + f_color.rgb *= calc_deferred_light( + a_modelpos, a_realnormal, length(a_position), a_emission, 1.0 + ); + } + vec3 fogColor = texture(u_skybox, a_dir).rgb; + f_color.rgb = mix(f_color.rgb, fogColor, a_fog); + } +#else + vec3 fogColor = texture(u_skybox, a_dir).rgb; + f_color.rgb = mix(f_color.rgb, fogColor, a_fog); +#endif + + f_color.a = u_opaque ? 1.0 : alpha; + f_position = vec4(a_position, 1.0); + f_normal = vec4(a_normal, 1.0); + f_emission = vec4(vec3(a_emission), 1.0); +} diff --git a/res/shaders/lib/shadows.glsl b/res/shaders/lib/shadows.glsl index 658e9a699..fb8e7dec5 100644 --- a/res/shaders/lib/shadows.glsl +++ b/res/shaders/lib/shadows.glsl @@ -19,24 +19,22 @@ float calc_shadow( float bias ) { float step = 1.0 / float(u_shadowsRes); - vec4 mpos = shadowMatrix * vec4(modelPos.xyz + normalOffset, 1.0); + vec4 mpos = shadowMatrix * vec4(modelPos.xyz + normalOffset * 2.0, 1.0); vec3 projCoords = mpos.xyz / mpos.w; projCoords = projCoords * 0.5 + 0.5; projCoords.z -= 0.00001 / u_shadowsRes + bias; float shadow = 0.0; - if (dot(realnormal, u_sunDir) < 0.0) { - // 3x3 kernel - for (int y = -1; y <= 1; y++) { - for (int x = -1; x <= 1; x++) { - vec3 offset = vec3(x, y, -(abs(x) + abs(y)) * 0.8) * step * 1.0 * u_shadowsSoftness; - shadow += texture(shadowsMap, projCoords + offset); - } + // 3x3 kernel + for (int y = -1; y <= 1; y++) { + for (int x = -1; x <= 1; x++) { + vec3 offset = vec3(x, y, -(abs(x) + abs(y)) * 0.1) * step * 1.0 * u_shadowsSoftness; + shadow += texture(shadowsMap, projCoords + offset); } - shadow /= 9.0; - } else { - shadow = 0.0; } + shadow /= 9.0; + + shadow *= max(0.0, sqrt(-dot(realnormal, u_sunDir))); return shadow; } diff --git a/res/shaders/lib/sky.glsl b/res/shaders/lib/sky.glsl index cfdbc3f2b..8f88894dd 100644 --- a/res/shaders/lib/sky.glsl +++ b/res/shaders/lib/sky.glsl @@ -4,7 +4,7 @@ #include vec3 pick_sky_color(samplerCube cubemap, float dayTime, vec3 minSkyLight) { - float elevation = sin(dayTime * PI2) * 0.2; + float elevation = -sin(dayTime * PI2) * 0.1; vec3 skyLightColor = texture(cubemap, vec3(0.0f, elevation, -0.4f)).rgb; skyLightColor *= SKY_LIGHT_TINT; skyLightColor = min(vec3(1.0f), skyLightColor * SKY_LIGHT_MUL); diff --git a/res/shaders/model.glslf b/res/shaders/model.glslf new file mode 100644 index 000000000..701d481fb --- /dev/null +++ b/res/shaders/model.glslf @@ -0,0 +1 @@ +#include diff --git a/res/shaders/model.glslv b/res/shaders/model.glslv new file mode 100644 index 000000000..20202cf1a --- /dev/null +++ b/res/shaders/model.glslv @@ -0,0 +1,58 @@ +#include + +layout (location = 0) in vec3 v_position; +layout (location = 1) in vec2 v_texCoord; +layout (location = 2) in vec3 v_normal; +layout (location = 3) in mat4 i_model; +layout (location = 7) in vec4 i_tint; +layout (location = 8) in vec4 i_light; +layout (location = 9) in vec4 i_uvRegion; +layout (location = 10) in vec4 i_params; + +#include +#include +#include +#include + +out vec4 a_color; + +uniform float u_dayTime; + +const vec3 SUN_VECTOR = vec3(0.411934, 0.863868, -0.279161); + +void main() { + a_modelpos = i_model * vec4(v_position, 1.0); + vec3 pos3d = a_modelpos.xyz - u_cameraPos; + + vec3 normal = mat3(i_model) * v_normal; + float normalLength = length(normal); + normal = normalLength > 1e-6 ? normal / normalLength : v_normal; + + bool shading = i_params.x > 0.5; + vec4 light = i_light; + if (shading) { + light *= 0.8 + dot(normal, SUN_VECTOR) * 0.2; + } + + a_realnormal = normal; + a_normal = calc_screen_normal(a_realnormal); + + a_color = vec4(calc_torch_light( + light.rgb, a_realnormal, a_modelpos.xyz, u_torchlightColor, u_gamma + ), 1.0); + a_texCoord = v_texCoord * i_uvRegion.zw + i_uvRegion.xy; + + a_dir = a_modelpos.xyz - u_cameraPos; + vec3 skyLightColor = pick_sky_color(u_skybox, u_dayTime, u_minSkyLight); + a_color.rgb = max(a_color.rgb, skyLightColor.rgb * light.a) * i_tint.rgb; + a_color.a = u_opacity * i_tint.a; + + mat4 viewmodel = u_view * u_model; + a_distance = length(viewmodel * vec4(pos3d, 0.0)); + a_fog = calc_fog(length(viewmodel * vec4(pos3d * FOG_POS_SCALE, 0.0)) / 256.0); + a_emission = shading ? 0.0 : 1.0; + + vec4 viewmodelpos = u_view * a_modelpos; + a_position = viewmodelpos.xyz; + gl_Position = u_proj * viewmodelpos; +} diff --git a/res/shaders/skybox_gen.glslf b/res/shaders/skybox_gen.glslf index b6f2b7ffb..1831ef4a7 100644 --- a/res/shaders/skybox_gen.glslf +++ b/res/shaders/skybox_gen.glslf @@ -33,7 +33,7 @@ SOFTWARE. #define ABSORPTION_BETA vec3(2.04e-5, 4.97e-5, 1.95e-6) /* what color gets absorbed by the atmosphere (Due to things like ozone) */ #define G 0.9 /* mie scattering direction, or how big the blob around the sun is */ // and the heights (how far to go up before the scattering has no effect) -#define HEIGHT_RAY 8e3 /* rayleigh height */ +#define HEIGHT_RAY 12e3 /* rayleigh height */ #define HEIGHT_MIE 1.2e3 /* and mie */ #define HEIGHT_ABSORPTION 30e3 /* at what height the absorption is at it's maximum */ #define ABSORPTION_FALLOFF 4e3 /* how much the absorption decreases the further away it gets from the maximum height */ diff --git a/res/shaders/translucent_composite.glslf b/res/shaders/translucent_composite.glslf new file mode 100644 index 000000000..f7fbb2002 --- /dev/null +++ b/res/shaders/translucent_composite.glslf @@ -0,0 +1,55 @@ +in vec2 v_uv; +out vec4 f_color; + +#define LAYERS_COUNT 3 + +uniform sampler2D u_layerColor0; +uniform sampler2D u_layerColor1; +uniform sampler2D u_layerColor2; +uniform sampler2D u_layerDepth0; +uniform sampler2D u_layerDepth1; +uniform sampler2D u_layerDepth2; + +void main() { + vec4 colors[LAYERS_COUNT]; + float depths[LAYERS_COUNT]; + colors[0] = texture(u_layerColor0, v_uv); + colors[1] = texture(u_layerColor1, v_uv); + colors[2] = texture(u_layerColor2, v_uv); + depths[0] = texture(u_layerDepth0, v_uv).r; + depths[1] = texture(u_layerDepth1, v_uv).r; + depths[2] = texture(u_layerDepth2, v_uv).r; + + vec4 layerColors[LAYERS_COUNT]; + float layerDepths[LAYERS_COUNT]; + int count = 0; + for (int i = 0; i < LAYERS_COUNT; i++) { + if (colors[i].a > 0.0) { + layerColors[count] = colors[i]; + layerDepths[count] = depths[i]; + count++; + } + } + if (count == 0) { + discard; + } + + for (int i = 1; i < count; i++) { + vec4 color = layerColors[i]; + float depth = layerDepths[i]; + int j = i - 1; + while (j >= 0 && layerDepths[j] < depth) { + layerColors[j + 1] = layerColors[j]; + layerDepths[j + 1] = layerDepths[j]; + j--; + } + layerColors[j + 1] = color; + layerDepths[j + 1] = depth; + } + + vec4 result = vec4(0.0); + for (int i = 0; i < count; i++) { + result = result * (1.0 - layerColors[i].a) + layerColors[i]; + } + f_color = result; +} diff --git a/res/shaders/translucent_composite.glslv b/res/shaders/translucent_composite.glslv new file mode 100644 index 000000000..4351d4e95 --- /dev/null +++ b/res/shaders/translucent_composite.glslv @@ -0,0 +1,8 @@ +layout (location = 0) in vec2 v_position; + +out vec2 v_uv; + +void main() { + v_uv = v_position * 0.5 + 0.5; + gl_Position = vec4(v_position, 0.0, 1.0); +} diff --git a/res/texts/en_US.txt b/res/texts/en_US.txt index 294758a7e..f2312fb34 100644 --- a/res/texts/en_US.txt +++ b/res/texts/en_US.txt @@ -11,6 +11,7 @@ error.dependency-version-not-met=Dependency pack version is not met. world.delete-confirm=Do you want to delete world forever? world.generators.default=Default world.generators.flat=Flat +world.delete-content-confirm=Delete missing content from the world __**(irreversible)**__? editor.info.tooltip=CTRL+S - Save\nCTRL+R - Run\nCTRL+Z - Undo\nCTRL+Y - Redo devtools.traceback=Traceback (most recent call first) diff --git a/res/texts/ru_RU.txt b/res/texts/ru_RU.txt index 295d467af..b11c89365 100644 --- a/res/texts/ru_RU.txt +++ b/res/texts/ru_RU.txt @@ -81,6 +81,8 @@ world.upgrade-request=Формат мира устарел! Конвертиро world.convert-with-loss=Конвертировать мир с потерями? world.convert-block-layouts=Есть изменения в полях блоков! Конвертировать мир? world.delete-confirm=Удалить мир безвозвратно? +world.Delete Content=Удалить контент +world.delete-content-confirm=Удалить отсутствующий контент из мира __**(безвозвратно)**__? # Настройки settings.Ambient=Фон diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 398ee274f..55480b05a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -28,9 +28,6 @@ find_package(CURL REQUIRED) find_package(OpenSSL 3.0 REQUIRED COMPONENTS Crypto) find_package(glfw3 REQUIRED) find_package(Freetype REQUIRED) -if(NOT APPLE) - find_package(EnTT REQUIRED) -endif() if(CMAKE_SYSTEM_NAME STREQUAL "Windows") find_package(vorbis REQUIRED) diff --git a/src/animation/rigging.cpp b/src/animation/rigging.cpp index 7a4061f8a..7d5397c76 100644 --- a/src/animation/rigging.cpp +++ b/src/animation/rigging.cpp @@ -88,6 +88,7 @@ void Skeleton::deserialize(const dv::value& root) { dv::get_mat(posearr[i], pose.matrices[i]); } } + boundsDirty = true; } void Skeleton::setConfig(std::shared_ptr rigConfig) { @@ -105,6 +106,7 @@ void Skeleton::setConfig(std::shared_ptr rigConfig) { for (size_t i = 0; i < bonesCount; i++) { flags[i].visible = true; } + boundsDirty = true; } static void get_all_nodes(std::vector& nodes, Bone* node) { @@ -160,17 +162,87 @@ void SkeletonConfig::update( const glm::vec3& position, const glm::vec3& scale ) const { - if (skeleton.interpolation.isEnabled()) { - const auto& interpolation = skeleton.interpolation; - update( - 0, - skeleton, - root.get(), - build_matrix(rotation, interpolation.getCurrent(), scale) - ); - } else { - update(0, skeleton, root.get(), build_matrix(rotation, position, scale)); + glm::vec3 pos = position; + const auto& interpolation = skeleton.interpolation; + if (interpolation.isEnabled() && interpolation.isRefreshed()) { + pos = interpolation.getCurrent(); } + glm::mat3 rot = rotation; + const auto& rotationInterpolation = skeleton.rotationInterpolation; + if (rotationInterpolation.isEnabled() && rotationInterpolation.isRefreshed()) { + rot = glm::mat3_cast(rotationInterpolation.getCurrent()); + } + update(0, skeleton, root.get(), build_matrix(rot, pos, scale)); +} + +static float max_component(const glm::vec3& v) { + return glm::max(glm::abs(v.x), glm::max(glm::abs(v.y), glm::abs(v.z))); +} + +static float farthest_corner_distance( + const glm::mat4& matrix, const AABB& aabb, const glm::vec3& origin +) { + glm::vec3 center = glm::vec3(matrix * glm::vec4(aabb.center(), 1.0f)); + glm::vec3 halfSize = aabb.size() * 0.5f; + glm::vec3 extent = glm::abs(glm::vec3(matrix[0])) * halfSize.x + + glm::abs(glm::vec3(matrix[1])) * halfSize.y + + glm::abs(glm::vec3(matrix[2])) * halfSize.z; + return glm::length(glm::abs(center - origin) + extent); +} + +void SkeletonConfig::processModels( + const Assets& assets, + Skeleton& skeleton, + const glm::vec3& position, + const glm::vec3& scale, + ModelBatch* batch, + ModelLightingMode lightingMode, + bool translucent +) const { + float radius = 0.0f; + bool pending = false; + for (size_t i = 0; i < nodes.size(); i++) { + auto* node = nodes[i]; + if (!skeleton.flags[i].visible) { + continue; + } + node->model.refresh(assets); + auto model = node->model.model.lock(); // TODO: cache model pointer during frame + auto& modelOverride = skeleton.modelOverrides.at(i); + if (modelOverride.updateFlag) { + modelOverride.refresh(assets); + } + if (auto foundOverride = modelOverride.model.lock()) { + model = std::move(foundOverride); + } + if (model == nullptr) { + if (!node->model.name.empty()) { + node->model.updateFlag = true; + pending = true; + } + continue; + } + const auto& matrix = skeleton.calculated.matrices[i]; + radius = glm::max( + radius, farthest_corner_distance(matrix, model->getBounds(), position) + ); + if (batch == nullptr) { + continue; + } + batch->draw( + matrix, + skeleton.tint * skeleton.boneTints[i], + lightingMode == ModelLightingMode::SOLID + ? position - glm::vec3(matrix * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)) + : glm::vec3(), + model, + &skeleton.textures, + translucent + ); + } + float maxScale = max_component(scale); + skeleton.boundsRadius = maxScale > 0.0f ? radius / maxScale : radius; + skeleton.boundsDirty = pending; } void SkeletonConfig::render( @@ -180,7 +252,8 @@ void SkeletonConfig::render( ModelLightingMode lightingMode, const glm::mat3& rotation, const glm::vec3& position, - const glm::vec3& scale + const glm::vec3& scale, + bool translucent ) const { if (skeleton.config->root == nullptr) { return; @@ -190,39 +263,31 @@ void SkeletonConfig::render( if (!skeleton.visible) { return; } - for (size_t i = 0; i < nodes.size(); i++) { - auto* node = nodes[i]; - if (!skeleton.flags[i].visible) { - continue; - } - node->model.refresh(assets); - auto model = node->model.model.lock().get(); // TODO: cache model pointer during frame - auto& modelOverride = skeleton.modelOverrides.at(i); - if (modelOverride.updateFlag) { - modelOverride.refresh(assets); - } - if (auto foundOverride = modelOverride.model.lock()) { - model = foundOverride.get(); - } - if (model == nullptr) { - if (!node->model.name.empty()) { - node->model.updateFlag = true; - } - continue; - } - batch.draw( - skeleton.calculated.matrices[i], - skeleton.tint * skeleton.boneTints[i], - lightingMode == ModelLightingMode::SOLID - ? position - glm::vec3( - skeleton.calculated.matrices[i] * - glm::vec4(0.0f, 0.0f, 0.0f, 1.0f) - ) - : glm::vec3(), - model, - &skeleton.textures - ); + processModels( + assets, skeleton, position, scale, &batch, lightingMode, translucent + ); +} + +void SkeletonConfig::updateBounds( + const Assets& assets, + Skeleton& skeleton, + const glm::mat3& rotation, + const glm::vec3& position, + const glm::vec3& scale +) const { + if (skeleton.config->root == nullptr) { + return; } + update(skeleton, rotation, position, scale); + processModels( + assets, + skeleton, + position, + scale, + nullptr, + ModelLightingMode::SOLID, + false + ); } const Bone* SkeletonConfig::find(std::string_view str) const { diff --git a/src/animation/rigging.hpp b/src/animation/rigging.hpp index af19810cc..a35650a70 100644 --- a/src/animation/rigging.hpp +++ b/src/animation/rigging.hpp @@ -97,10 +97,15 @@ namespace rigging { std::vector modelOverrides; bool visible; bool culled = false; + /// @brief Bounding radius of visible models around entity position, + /// divided by the largest scale component + float boundsRadius = 0.0f; + bool boundsDirty = true; glm::vec4 tint {1.0f, 1.0f, 1.0f, 1.0f}; std::vector boneTints; util::VecInterpolation<3, float> interpolation {false}; + util::RotationInterpolation rotationInterpolation {false}; Skeleton(std::shared_ptr config); @@ -126,6 +131,16 @@ namespace rigging { size_t update( size_t index, Skeleton& skeleton, Bone* node, const glm::mat4& matrix ) const; + + void processModels( + const Assets& assets, + Skeleton& skeleton, + const glm::vec3& position, + const glm::vec3& scale, + ModelBatch* batch, + ModelLightingMode lightingMode, + bool translucent + ) const; public: SkeletonConfig( const std::string& name, @@ -147,6 +162,15 @@ namespace rigging { ModelLightingMode lightingMode, const glm::mat3& rotation, const glm::vec3& position, + const glm::vec3& scale, + bool translucent = false + ) const; + + void updateBounds( + const Assets& assets, + Skeleton& skeleton, + const glm::mat3& rotation, + const glm::vec3& position, const glm::vec3& scale ) const; diff --git a/src/assets/AssetsLoader.cpp b/src/assets/AssetsLoader.cpp index 04bde9a6f..aa996c025 100644 --- a/src/assets/AssetsLoader.cpp +++ b/src/assets/AssetsLoader.cpp @@ -19,8 +19,14 @@ #include "util/ThreadPool.hpp" #include "voxels/Block.hpp" +#include +#include +#include #include +#include +#include #include +#include namespace fs = std::filesystem; @@ -151,24 +157,14 @@ static std::string assets_def_folder(AssetType tag) { return ""; } -void AssetsLoader::processPreload( - AssetType tag, const std::string& name, const dv::value& map +static std::shared_ptr create_preload_config( + AssetType tag, const dv::value& map ) { - std::string defFolder = assets_def_folder(tag); - std::string path = defFolder + "/" + name; - if (map == nullptr) { - add(tag, path, name, nullptr, true); - return; - } - std::shared_ptr config = nullptr; - map.at("path").get(path); - logger.debug() << "processing preload " << util::quote(name) - << " path: " << util::quote(path); switch (tag) { case AssetType::SOUND: { bool keepPCM = false; - config = std::make_shared(map.at("keep-pcm").get(keepPCM)); - break; + map.at("keep-pcm").get(keepPCM); + return std::make_shared(keepPCM); } case AssetType::ATLAS: { std::string typeName = "atlas"; @@ -177,44 +173,295 @@ void AssetsLoader::processPreload( if (typeName == "separate") { type = AtlasType::SEPARATE; } - config = std::make_shared(type); - break; + return std::make_shared(type); } case AssetType::POST_EFFECT: { bool advanced = false; map.at("advanced").get(advanced); - config = std::make_shared(advanced); - break; + return std::make_shared(advanced); } case AssetType::MODEL: { bool squashed = false; map.at("squash").get(squashed); - config = std::make_shared(squashed); - break; + return std::make_shared(squashed); } case AssetType::FONT: { int size = DEFAULT_FONT_SIZE; map.at("size").get(size); - config = std::make_unique(size); - break; + return std::make_shared(size); } default: - break; + return nullptr; + } +} + +static bool is_pattern(const std::string& name) { + return name.find('*') != std::string::npos; +} + +static bool match_wildcard(std::string_view pattern, std::string_view str) { + size_t p = 0; + size_t s = 0; + size_t starPos = std::string_view::npos; + size_t starMatch = 0; + while (s < str.length()) { + if (p < pattern.length() && pattern[p] == '*') { + starPos = p++; + starMatch = s; + } else if (p < pattern.length() && pattern[p] == str[s]) { + p++; + s++; + } else if (starPos != std::string_view::npos) { + p = starPos + 1; + s = ++starMatch; + } else { + return false; + } + } + while (p < pattern.length() && pattern[p] == '*') { + p++; + } + return p == pattern.length(); +} + +static std::vector split_pattern(const std::string& pattern) { + if (pattern.find("**") != std::string::npos) { + throw std::runtime_error( + "'**' is not supported in preload pattern " + util::quote(pattern) + ); + } + std::vector segments; + size_t start = 0; + while (start < pattern.length()) { + size_t end = pattern.find('/', start); + if (end == std::string::npos) { + end = pattern.length(); + } + if (end > start) { + auto segment = pattern.substr(start, end - start); + if (segment == "." || segment == "..") { + throw std::runtime_error( + "relative segments are not allowed in preload pattern " + + util::quote(pattern) + ); + } + segments.push_back(std::move(segment)); + } + start = end + 1; + } + return segments; +} + +static void glob( + const io::path& folder, + const std::vector& segments, + size_t index, + const std::string& relative, + bool directories, + std::vector& out +) { + const auto& segment = segments[index]; + bool last = index + 1 == segments.size(); + + auto visit = [&](const std::string& name) { + io::path path = folder / name; + std::string rel = relative.empty() ? name : relative + "/" + name; + if (!last) { + if (io::is_directory(path)) { + glob(path, segments, index + 1, rel, directories, out); + } + } else if (directories ? io::is_directory(path) + : io::is_regular_file(path)) { + out.push_back(std::move(rel)); + } + }; + + if (!is_pattern(segment)) { + visit(segment); + return; + } + if (!io::is_directory(folder)) { + return; + } + for (const auto& entry : io::directory_iterator(folder)) { + auto name = entry.name(); + if (match_wildcard(segment, name)) { + visit(name); + } + } +} + +static std::vector asset_search_folders(AssetType tag) { + if (tag == AssetType::ANIMATION) { + return {ANIMATION_FOLDER, ANIMATION_FOLDER_ALIAS}; + } + return {assets_def_folder(tag)}; +} + +static std::vector asset_extensions(AssetType tag) { + switch (tag) { + case AssetType::ANIMATION: + return {".vca"}; + case AssetType::FONT: + return {".png", ".ttf", ".otf"}; + case AssetType::MODEL: + return {".vec3", ".obj", ".xml", ".vcm"}; + case AssetType::POST_EFFECT: + return {".glsl"}; + case AssetType::SHADER: + return {".glslv", ".glslf"}; + case AssetType::SKELETON: + return {".json"}; + case AssetType::SOUND: + return {".ogg", ".wav"}; + case AssetType::TEXTURE: + return {".png"}; + default: + return {}; + } +} + +static std::optional strip_index_suffix(const std::string& stem) { + size_t pos = stem.rfind('_'); + if (pos == std::string::npos || pos + 1 == stem.length()) { + return std::nullopt; + } + for (size_t i = pos + 1; i < stem.length(); i++) { + if (!std::isdigit(static_cast(stem[i]))) { + return std::nullopt; + } + } + return stem.substr(0, pos); +} + +struct PreloadMatch { + std::string name; + std::string path; +}; + +/// @brief Resolve asset name for a file matched by preload pattern +/// @param folder asset type folder the file was found in +/// @param relative file path relative to the folder +/// @return std::nullopt if the file is not a loadable asset of the type +static std::optional resolve_preload_file( + AssetType tag, const io::path& folder, const std::string& relative +) { + io::path file = relative; + std::string extension = file.extension(); + const auto& extensions = asset_extensions(tag); + if (std::find(extensions.begin(), extensions.end(), extension) == + extensions.end()) { + return std::nullopt; + } + std::string base = relative.substr(0, relative.length() - extension.length()); + std::string defFolder = assets_def_folder(tag); + + if (tag == AssetType::FONT) { + if (extension != ".png") { + return PreloadMatch {base, defFolder + "/" + relative}; + } + auto fontName = strip_index_suffix(base); + if (!fontName || !io::exists(folder / (*fontName + "_0.png"))) { + return std::nullopt; + } + base = std::move(*fontName); + } else if (tag == AssetType::SOUND) { + auto soundName = strip_index_suffix(base); + if (soundName && (io::exists(folder / (*soundName + extension)) || + io::exists(folder / (*soundName + "_0" + extension)))) { + base = std::move(*soundName); + } + } + return PreloadMatch {base, defFolder + "/" + base}; +} + +static std::vector find_preload_matches( + AssetType tag, const io::path& packFolder, const std::string& pattern +) { + auto segments = split_pattern(pattern); + if (segments.empty()) { + return {}; + } + bool directories = pattern.back() == '/' || tag == AssetType::ATLAS; + if (directories && tag != AssetType::ATLAS) { + throw std::runtime_error( + "directory pattern " + util::quote(pattern) + + " is not applicable to assets of type " + assets_def_folder(tag) + ); + } + std::map found; + for (const auto& searchFolder : asset_search_folders(tag)) { + io::path folder = packFolder / searchFolder; + std::vector files; + glob(folder, segments, 0, "", directories, files); + for (const auto& relative : files) { + if (directories) { + found.try_emplace(relative, assets_def_folder(tag) + "/" + relative); + continue; + } + if (auto match = resolve_preload_file(tag, folder, relative)) { + found.try_emplace(std::move(match->name), std::move(match->path)); + } + } + } + std::vector matches; + matches.reserve(found.size()); + for (auto& [name, path] : found) { + matches.push_back(PreloadMatch {name, std::move(path)}); + } + return matches; +} + +void AssetsLoader::processPreload( + AssetType tag, + const std::string& name, + const dv::value& map, + const io::path& packFolder +) { + std::shared_ptr config = + map == nullptr ? nullptr : create_preload_config(tag, map); + + if (is_pattern(name)) { + if (map != nullptr && map.has("path")) { + throw std::runtime_error( + "'path' cannot be used with preload pattern " + util::quote(name) + ); + } + auto matches = find_preload_matches(tag, packFolder, name); + if (matches.empty()) { + logger.warning() << "preload pattern " << util::quote(name) + << " matches nothing in " << packFolder.string(); + } + for (const auto& match : matches) { + logger.debug() << "processing preload " << util::quote(match.name) + << " path: " << util::quote(match.path); + add(tag, match.path, match.name, config, true); + } + return; + } + + std::string path = assets_def_folder(tag) + "/" + name; + if (map != nullptr) { + map.at("path").get(path); + logger.debug() << "processing preload " << util::quote(name) + << " path: " << util::quote(path); } add(tag, path, name, std::move(config), true); } -void AssetsLoader::processPreloadList(AssetType tag, const dv::value& list) { +void AssetsLoader::processPreloadList( + AssetType tag, const dv::value& list, const io::path& packFolder +) { if (list == nullptr) { return; } for (const auto& value : list) { switch (value.getType()) { case dv::value_type::string: - processPreload(tag, value.asString(), nullptr); + processPreload(tag, value.asString(), nullptr, packFolder); break; case dv::value_type::object: - processPreload(tag, value["name"].asString(), value); + processPreload(tag, value["name"].asString(), value, packFolder); break; default: throw std::runtime_error("invalid entry type"); @@ -224,15 +471,17 @@ void AssetsLoader::processPreloadList(AssetType tag, const dv::value& list) { void AssetsLoader::processPreloadConfig(const io::path& file) { auto root = io::read_json(file); - processPreloadList(AssetType::ANIMATION, root["animation"]); - processPreloadList(AssetType::ATLAS, root["atlases"]); - processPreloadList(AssetType::FONT, root["fonts"]); - processPreloadList(AssetType::MODEL, root["models"]); - processPreloadList(AssetType::POST_EFFECT, root["post-effects"]); - processPreloadList(AssetType::SHADER, root["shaders"]); - processPreloadList(AssetType::SKELETON, root["skeletons"]); - processPreloadList(AssetType::SOUND, root["sounds"]); - processPreloadList(AssetType::TEXTURE, root["textures"]); + io::path folder = file.parent(); + processPreloadList(AssetType::ANIMATION, root["animations"], folder); + processPreloadList(AssetType::ANIMATION, root["animation"], folder); + processPreloadList(AssetType::ATLAS, root["atlases"], folder); + processPreloadList(AssetType::FONT, root["fonts"], folder); + processPreloadList(AssetType::MODEL, root["models"], folder); + processPreloadList(AssetType::POST_EFFECT, root["post-effects"], folder); + processPreloadList(AssetType::SHADER, root["shaders"], folder); + processPreloadList(AssetType::SKELETON, root["skeletons"], folder); + processPreloadList(AssetType::SOUND, root["sounds"], folder); + processPreloadList(AssetType::TEXTURE, root["textures"], folder); // layouts are loaded automatically } diff --git a/src/assets/AssetsLoader.hpp b/src/assets/AssetsLoader.hpp index a61c3b59e..477c6aaa1 100644 --- a/src/assets/AssetsLoader.hpp +++ b/src/assets/AssetsLoader.hpp @@ -149,9 +149,14 @@ private: AssetsLoadInfo& assetsLoadInfo; void processPreload( - AssetType tag, const std::string& name, const dv::value& map + AssetType tag, + const std::string& name, + const dv::value& map, + const io::path& packFolder + ); + void processPreloadList( + AssetType tag, const dv::value& list, const io::path& packFolder ); - void processPreloadList(AssetType tag, const dv::value& list); void processPreloadConfig(const io::path& file); void processPreloadConfigs(const Content* content); }; diff --git a/src/assets/assetload_funcs.cpp b/src/assets/assetload_funcs.cpp index f6080cd1c..e76e9fb38 100644 --- a/src/assets/assetload_funcs.cpp +++ b/src/assets/assetload_funcs.cpp @@ -44,6 +44,18 @@ static bool load_animated_texture( Atlas* dstAtlas ); +static io::path find_animation(const ResPaths& paths, const std::string& filename) { + auto path = paths.find(filename + ".vca"); + const auto prefix = ANIMATION_FOLDER + "/"; + if (io::is_regular_file(path) || filename.rfind(prefix, 0) != 0) { + return path; + } + auto alias = paths.find( + ANIMATION_FOLDER_ALIAS + "/" + filename.substr(prefix.length()) + ".vca" + ); + return io::is_regular_file(alias) ? alias : path; +} + assetload::postfunc assetload::animation( AssetsLoader& loader, const ResPaths& paths, @@ -51,7 +63,7 @@ assetload::postfunc assetload::animation( const std::string& name, const std::shared_ptr& ) { - auto path = paths.find(filename + ".vca"); + auto path = find_animation(paths, filename); loader.attachToFile(path, {name, AssetType::ANIMATION}); if (io::is_regular_file(path)) { diff --git a/src/audio/audio.cpp b/src/audio/audio.cpp index 1fa8a1966..a20020ced 100644 --- a/src/audio/audio.cpp +++ b/src/audio/audio.cpp @@ -262,6 +262,18 @@ std::unique_ptr audio::create_sound( } std::unique_ptr audio::open_PCM_stream(const io::path& file) { + if (!io::exists(file)) { + io::path candidate = file.string() + ".wav"; + if (io::exists(candidate)) { + return wav::create_stream(candidate); + } + candidate = file.string() + ".ogg"; + if (io::exists(candidate)) { + return ogg::create_stream(candidate); + } + throw std::runtime_error("file not found '" + file.string() + "'"); + } + std::string ext = file.extension(); if (ext == ".wav" || ext == ".WAV") { return wav::create_stream(file); diff --git a/src/coders/obj.cpp b/src/coders/obj.cpp index 6da92a66c..1ea3b3834 100644 --- a/src/coders/obj.cpp +++ b/src/coders/obj.cpp @@ -134,6 +134,7 @@ public: auto model = std::make_unique(); buildMeshes(*model); model->clean(); + model->calcBounds(); return model; } }; diff --git a/src/coders/vcm.cpp b/src/coders/vcm.cpp index a1ca758de..c4323f4ba 100644 --- a/src/coders/vcm.cpp +++ b/src/coders/vcm.cpp @@ -469,6 +469,7 @@ static VcmModel load_model(const xmlelement& root) { perform_element(*elem, builder, ctx); } + model.calcBounds(); vcmModel.parts["root"] = std::move(model); vcmModel.skeleton = SkeletonConfig( "", diff --git a/src/constants.hpp b/src/constants.hpp index a64a05e38..259e5f8e7 100644 --- a/src/constants.hpp +++ b/src/constants.hpp @@ -6,7 +6,12 @@ #include inline constexpr int ENGINE_VERSION_MAJOR = 0; -inline constexpr int ENGINE_VERSION_MINOR = 32; +inline constexpr int ENGINE_VERSION_MINOR = 33; +#ifdef VC_VERSION_PATCH +inline constexpr int ENGINE_VERSION_PATCH = VC_VERSION_PATCH; +#else +inline constexpr int ENGINE_VERSION_PATCH = 0; +#endif #ifdef NDEBUG inline constexpr bool ENGINE_DEBUG_BUILD = false; @@ -14,7 +19,13 @@ inline constexpr bool ENGINE_DEBUG_BUILD = false; inline constexpr bool ENGINE_DEBUG_BUILD = true; #endif // NDEBUG -inline const std::string ENGINE_VERSION_STRING = "0.32"; +inline const std::string ENGINE_VERSION_STRING = + std::to_string(ENGINE_VERSION_MAJOR) + "." + + std::to_string(ENGINE_VERSION_MINOR) +#ifdef VC_VERSION_PATCH + + "." + std::to_string(ENGINE_VERSION_PATCH) +#endif + ; inline constexpr uint MAX_SUBPROCESSES = 1; inline constexpr uint MAX_SUBPROCESS_DEPTH = 2; @@ -75,7 +86,8 @@ inline constexpr int DEFAULT_FONT_SIZE = 16; inline constexpr int DEFAULT_PRE_RENDER_FONT_PAGES = 1; // must be at least 1 -inline const std::string ANIMATION_FOLDER = "animation"; +inline const std::string ANIMATION_FOLDER = "animations"; +inline const std::string ANIMATION_FOLDER_ALIAS = "animation"; inline const std::string FONTS_FOLDER = "fonts"; inline const std::string LAYOUTS_FOLDER = "layouts"; inline const std::string MODELS_FOLDER = "models"; diff --git a/src/content/ContentBuilder.cpp b/src/content/ContentBuilder.cpp index 83836dfe3..4c478f4ef 100644 --- a/src/content/ContentBuilder.cpp +++ b/src/content/ContentBuilder.cpp @@ -1,5 +1,8 @@ #include "ContentBuilder.hpp" +#include "core_defs.hpp" +#include "util/stringutil.hpp" + ContentBuilder::~ContentBuilder() = default; void ContentBuilder::add(std::unique_ptr pack) { @@ -19,6 +22,11 @@ std::unique_ptr ContentBuilder::build() { for (const std::string& name : blocks.names) { Block& def = *blocks.defs[name]; + // Filling auto fields + if (def.caption.empty()) { + def.caption = util::id_to_caption(def.name); + } + // Generating runtime info def.rt.id = blockDefsIndices.size(); def.rt.emissive = *reinterpret_cast(def.emission); @@ -31,39 +39,50 @@ std::unique_ptr ContentBuilder::build() { variant.culling == CullingMode::OPTIONAL; }; + auto prepareHitboxes = [&def](Variant& variant) { + if (def.rotatable) { + for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) { + auto& rotated = variant.rt.hitboxes[i]; + rotated.clear(); + rotated.reserve(variant.hitboxes.size()); + for (AABB aabb : variant.hitboxes) { + def.rotations.variants[i].transform(aabb); + aabb.fix(); + rotated.push_back(aabb); + } + } + } else { + variant.rt.hitboxes[0] = variant.hitboxes; + } + }; + + const float EPSILON = 0.01f; + auto isFullHitbox = [&def, EPSILON](const Variant& variant) { + return !variant.hitboxes.empty() && + glm::i8vec3(variant.hitboxes[0].size() + EPSILON) == def.size; + }; + + bool fullHitboxes; if (def.variants) { + fullHitboxes = true; for (auto& variant : def.variants->variants) { variant.rt.solid = isSolid(variant) || def.explictlySolid; + prepareHitboxes(variant); + fullHitboxes = fullHitboxes && isFullHitbox(variant); } def.defaults = def.variants->variants.at(0); } else { def.defaults.rt.solid = isSolid(def.defaults) || def.explictlySolid; + prepareHitboxes(def.defaults); + fullHitboxes = isFullHitbox(def.defaults); } - def.rt.solid = def.defaults.rt.solid; - - const float EPSILON = 0.01f; - def.rt.solid = def.rt.solid && - def.obstacle && - (glm::i8vec3(def.hitboxes[0].size() + EPSILON) == def.size); + def.rt.solid = def.defaults.rt.solid && def.obstacle && fullHitboxes; def.rt.extended = def.size.x > 1 || def.size.y > 1 || def.size.z > 1; if (def.material.empty()) { defaults.at("block-material").get(def.material); } - if (def.rotatable) { - for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) { - def.rt.hitboxes[i].reserve(def.hitboxes.size()); - for (AABB aabb : def.hitboxes) { - def.rotations.variants[i].transform(aabb); - aabb.fix(); - def.rt.hitboxes[i].push_back(aabb); - } - } - } else { - def.rt.hitboxes[0] = def.hitboxes; - } - blockDefsIndices.push_back(&def); groups->insert(def.defaults.drawGroup); // FIXME: variants } @@ -72,6 +91,11 @@ std::unique_ptr ContentBuilder::build() { for (const std::string& name : items.names) { ItemDef& def = *items.defs[name]; + // Filling auto fields + if (def.caption.empty()) { + def.caption = util::id_to_caption(def.name); + } + // Generating runtime info def.rt.id = itemDefsIndices.size(); def.rt.emissive = *reinterpret_cast(def.emission); @@ -105,8 +129,17 @@ std::unique_ptr ContentBuilder::build() { // Now, it's time to resolve foreign keys for (Block* def : blockDefsIndices) { - def->rt.pickingItem = content->items.require(def->pickingItem).rt.id; - def->rt.surfaceReplacement = content->blocks.require(def->surfaceReplacement).rt.id; + def->rt.pickingItem = + content->items + .require( + def->pickingItem.empty() + ? (def->hidden ? CORE_EMPTY + : def->name + BLOCK_ITEM_SUFFIX) + : def->pickingItem + ) + .rt.id; + def->rt.surfaceReplacement = + content->blocks.require(def->surfaceReplacement).rt.id; if (def->properties == nullptr) { def->properties = dv::object(); } @@ -123,6 +156,13 @@ std::unique_ptr ContentBuilder::build() { def->properties["script-file"] = def->scriptFile; } + for (EntityDef* def : entityDefsIndices) { + if (def->properties == nullptr) { + def->properties = dv::object(); + } + def->properties["name"] = def->name; + } + for (auto& [name, def] : content->generators.getDefs()) { def->prepare(content.get()); } diff --git a/src/content/ContentBuilder.hpp b/src/content/ContentBuilder.hpp index b1c4d26c3..a74cdbe76 100644 --- a/src/content/ContentBuilder.hpp +++ b/src/content/ContentBuilder.hpp @@ -38,16 +38,21 @@ public: T& create(const std::string& id, bool* created = nullptr) { auto found = defs.find(id); if (found != defs.end()) { - if (created) *created = false; + if (created) { + *created = false; + } return *found->second; } - if (created) *created = true; + if (created) { + *created = true; + } checkIdentifier(id); allNames[id] = type; names.push_back(id); defs[id] = std::make_unique(id); return *defs[id]; } + // Only fetch existing definition, return null otherwise. T* get(const std::string& id) { auto found = defs.find(id); diff --git a/src/content/ContentLoader.cpp b/src/content/ContentLoader.cpp index 3c45c4438..bf752531d 100644 --- a/src/content/ContentLoader.cpp +++ b/src/content/ContentLoader.cpp @@ -180,7 +180,8 @@ void ContentUnitLoader::loadUnit( auto configFile = folder / (defsDir + "/" + name + ".json"); if (io::exists(configFile)) { try { - loadUnit(def, full, configFile); + dv::value root = io::read_json(configFile); + loadUnit(def, full, std::move(root)); } catch (const std::runtime_error& err) { throw std::runtime_error( "file " + util::quote(configFile.string()) + ": " + @@ -286,12 +287,15 @@ void ContentLoader::loadContent(const dv::value& root) { }; ContentUnitLoader(*pack, builder.blocks, "blocks", - [this](Block& def) { + [this](const Block& def) { if (!def.hidden) { bool created; - auto& item = builder.items.create(def.name + BLOCK_ITEM_SUFFIX, &created); + auto& item = builder.items.create( + def.name + BLOCK_ITEM_SUFFIX, &created + ); item.generated = true; - item.caption = def.caption; + item.caption = def.caption.empty() ? util::id_to_caption(def.name) + : def.caption; item.iconType = ItemIconType::BLOCK; item.icon = def.name; item.placingBlock = def.name; diff --git a/src/content/loading/BlockLoader.cpp b/src/content/loading/BlockLoader.cpp index d6bcad92b..1c1a1345c 100644 --- a/src/content/loading/BlockLoader.cpp +++ b/src/content/loading/BlockLoader.cpp @@ -42,6 +42,21 @@ static void perform_user_block_fields( layout = StructLayout::create(fields); } +static AABB load_hitbox(const dv::value& box) { + if (box.size() < 6) { + throw std::runtime_error("hitbox requires 6 elements"); + } + AABB aabb; + aabb.a = glm::vec3( + box[0].asNumber(), box[1].asNumber(), box[2].asNumber() + ); + aabb.b = glm::vec3( + box[3].asNumber(), box[4].asNumber(), box[5].asNumber() + ); + aabb.b += aabb.a; + return aabb; +} + static void load_variant( Variant& variant, const dv::value& root, const std::string& name ) { @@ -86,12 +101,22 @@ static void load_variant( logger.error() << "unknown culling mode: " << cullingModeName; } root.at("draw-group").get(variant.drawGroup); + + if (auto found = root.at("hitboxes")) { + const auto& boxarr = *found; + variant.hitboxes.clear(); + variant.hitboxes.reserve(boxarr.size()); + for (uint i = 0; i < boxarr.size(); i++) { + variant.hitboxes.push_back(load_hitbox(boxarr[i])); + } + } else if (auto found = root.at("hitbox")) { + variant.hitboxes = {load_hitbox(*found)}; + } } template<> void ContentUnitLoader::loadUnit( - Block& def, const std::string& name, const io::path& file + Block& def, const std::string& name, dv::value root ) { - auto root = io::read_json(file); process_properties(def, name, root); process_tags(def, root); @@ -100,7 +125,7 @@ template<> void ContentUnitLoader::loadUnit( auto parentDef = builder.get(parentName); if (parentDef == nullptr) { throw std::runtime_error( - "Failed to find parent(" + parentName + ") for " + name + "failed to find parent(" + parentName + ") for " + name ); } parentDef->cloneTo(def); @@ -120,7 +145,7 @@ template<> void ContentUnitLoader::loadUnit( stateBased.at("offset").get(offset); stateBased.at("bits").get(bitsCount); if (offset < 0 || bitsCount <= 0 || offset + bitsCount > 8) { - throw std::runtime_error("Invalid state-based bits configuration"); + throw std::runtime_error("invalid state-based bits configuration"); } def.variants = std::make_unique(); @@ -136,6 +161,13 @@ template<> void ContentUnitLoader::loadUnit( def.variants->variants.push_back(def.defaults); } } + } else if (def.variants) { + auto& variants = def.variants->variants; + variants.at(0) = def.defaults; + + for (int i = 1; i < variants.size(); i++) { + load_variant(variants.at(i), root, name); + } } root.at("material").get(def.material); @@ -158,34 +190,6 @@ template<> void ContentUnitLoader::loadUnit( def.rotatable = false; } - // block hitbox AABB [x, y, z, width, height, depth] - if (auto found = root.at("hitboxes")) { - const auto& boxarr = *found; - def.hitboxes.resize(boxarr.size()); - for (uint i = 0; i < boxarr.size(); i++) { - const auto& box = boxarr[i]; - auto& hitboxesIndex = def.hitboxes[i]; - hitboxesIndex.a = glm::vec3( - box[0].asNumber(), box[1].asNumber(), box[2].asNumber() - ); - hitboxesIndex.b = glm::vec3( - box[3].asNumber(), box[4].asNumber(), box[5].asNumber() - ); - hitboxesIndex.b += hitboxesIndex.a; - } - } else if (auto found = root.at("hitbox")) { - const auto& box = *found; - AABB aabb; - aabb.a = glm::vec3( - box[0].asNumber(), box[1].asNumber(), box[2].asNumber() - ); - aabb.b = glm::vec3( - box[3].asNumber(), box[4].asNumber(), box[5].asNumber() - ); - aabb.b += aabb.a; - def.hitboxes = {aabb}; - } - // block light emission [r, g, b] where r,g,b in range [0..15] if (auto found = root.at("emission")) { const auto& emissionarr = *found; @@ -219,11 +223,19 @@ template<> void ContentUnitLoader::loadUnit( ); } - // should variant modify hitbox? - if (def.defaults.model.type == BlockModelType::BLOCK && - (def.size.x != 1 || def.size.y != 1 || def.size.z != 1)) { - def.defaults.model.type = BlockModelType::AABB; - def.hitboxes = {AABB(def.size)}; + if (def.size.x != 1 || def.size.y != 1 || def.size.z != 1) { + auto applySize = [&def](Variant& variant) { + if (variant.model.type == BlockModelType::BLOCK) { + variant.model.type = BlockModelType::AABB; + variant.hitboxes = {AABB(def.size)}; + } + }; + applySize(def.defaults); + if (def.variants) { + for (auto& variant : def.variants->variants) { + applySize(variant); + } + } } // grounding behaviour @@ -243,6 +255,7 @@ template<> void ContentUnitLoader::loadUnit( root.at("sky-light-passing").get(def.skyLightPassing); root.at("shadeless").get(def.shadeless); root.at("ambient-occlusion").get(def.ambientOcclusion); + root.at("uv-lock").get(def.uvLock); root.at("breakable").get(def.breakable); root.at("selectable").get(def.selectable); root.at("grounded").get(def.grounded); diff --git a/src/content/loading/ContentUnitLoader.hpp b/src/content/loading/ContentUnitLoader.hpp index 1c0578b9a..51f225a9c 100644 --- a/src/content/loading/ContentUnitLoader.hpp +++ b/src/content/loading/ContentUnitLoader.hpp @@ -25,7 +25,7 @@ public: postFunc(std::move(postFunc)) { } void loadUnit(DefT& def, const std::string& full, const std::string& name); - void loadUnit(DefT& def, const std::string& name, const io::path& file); + void loadUnit(DefT& def, const std::string& name, dv::value root); void loadDefs(const dv::value& root); private: const ContentPack& pack; diff --git a/src/content/loading/EntityLoader.cpp b/src/content/loading/EntityLoader.cpp index 625b1927a..7eab074bf 100644 --- a/src/content/loading/EntityLoader.cpp +++ b/src/content/loading/EntityLoader.cpp @@ -1,5 +1,6 @@ #define VC_ENABLE_REFLECTION #include "ContentUnitLoader.hpp" +#include "ContentLoadingCommons.hpp" #include "../ContentBuilder.hpp" #include "coders/json.hpp" @@ -13,9 +14,9 @@ static debug::Logger logger("entity-content-loader"); template<> void ContentUnitLoader::loadUnit( - EntityDef& def, const std::string& name, const io::path& file + EntityDef& def, const std::string& name, dv::value root ) { - auto root = io::read_json(file); + process_properties(def, name, root); if (root.has("parent")) { const auto& parentName = root["parent"].asString(); @@ -94,6 +95,7 @@ template<> void ContentUnitLoader::loadUnit( root.at("mass").get(def.mass); root.at("elasticity").get(def.elasticity); root.at("step-height").get(def.stepHeight); + root.at("translucent").get(def.translucent); std::string lightingModeName; root.at("lighting-mode").get(lightingModeName); diff --git a/src/content/loading/ItemLoader.cpp b/src/content/loading/ItemLoader.cpp index cba07771c..ec9a65fd2 100644 --- a/src/content/loading/ItemLoader.cpp +++ b/src/content/loading/ItemLoader.cpp @@ -15,9 +15,8 @@ static debug::Logger logger("item-content-loader"); template<> void ContentUnitLoader::loadUnit( - ItemDef& def, const std::string& name, const io::path& file + ItemDef& def, const std::string& name, dv::value root ) { - auto root = io::read_json(file); process_properties(def, name, root); process_tags(def, root); diff --git a/src/core_defs.cpp b/src/core_defs.cpp index f30da7286..692773d15 100644 --- a/src/core_defs.cpp +++ b/src/core_defs.cpp @@ -39,7 +39,7 @@ void corecontent::setup(Input* input, ContentBuilder& builder) { for (uint i = 0; i < 6; i++) { block.defaults.textureFaces[i] = "obstacle"; } - block.hitboxes = {AABB()}; + block.defaults.hitboxes = {AABB()}; block.breakable = false; ItemDef& item = builder.items.create(CORE_OBSTACLE+".item"); item.iconType = ItemIconType::BLOCK; @@ -55,7 +55,7 @@ void corecontent::setup(Input* input, ContentBuilder& builder) { block.defaults.drawGroup = -1; block.skyLightPassing = true; block.lightPassing = true; - block.hitboxes = {AABB()}; + block.defaults.hitboxes = {AABB()}; block.obstacle = false; ItemDef& item = builder.items.create(CORE_STRUCT_AIR+".item"); item.iconType = ItemIconType::BLOCK; diff --git a/src/devtools/stdin_cmd_reader.cpp b/src/devtools/stdin_cmd_reader.cpp index 90dc07e2b..1e72fa158 100644 --- a/src/devtools/stdin_cmd_reader.cpp +++ b/src/devtools/stdin_cmd_reader.cpp @@ -28,6 +28,7 @@ void cmd::start_stdin_cmd_reader(Engine& engine) { if (line.empty()) { continue; } + logger.debug() << "input received: " << line; engine.postRunnable([line, &interpreter] () { try { auto result = interpreter.execute(line); diff --git a/src/engine/WindowControl.cpp b/src/engine/WindowControl.cpp index 5a14c02ba..c3d7be4a9 100644 --- a/src/engine/WindowControl.cpp +++ b/src/engine/WindowControl.cpp @@ -42,8 +42,7 @@ WindowControl::Result WindowControl::initialize() { #endif title += "VoxelCore v"; if (buildName.empty()) { - title += std::to_string(ENGINE_VERSION_MAJOR) + "." + - std::to_string(ENGINE_VERSION_MINOR); + title += ENGINE_VERSION_STRING; } else { title += buildName; } diff --git a/src/frontend/ContentGfxCache.cpp b/src/frontend/ContentGfxCache.cpp index 9cdcdf70e..6da851a56 100644 --- a/src/frontend/ContentGfxCache.cpp +++ b/src/frontend/ContentGfxCache.cpp @@ -1,6 +1,6 @@ #include "ContentGfxCache.hpp" -#include +#define GLM_ENABLE_EXPERIMENTAL #include "UiDocument.hpp" #include "assets/Assets.hpp" @@ -8,13 +8,80 @@ #include "content/ContentPack.hpp" #include "graphics/core/Atlas.hpp" #include "maths/UVRegion.hpp" +#include "maths/util.hpp" #include "voxels/Block.hpp" #include "debug/Logger.hpp" #include "core_defs.hpp" #include "settings.hpp" +#include +#include +#include +#include +#include + static debug::Logger logger("content-gfx-cache"); +static void unrotate_triangle_uv( + const glm::vec3 (&coords)[3], glm::vec2 (&uvs)[3], const glm::vec3& normal +) { + glm::vec3 absN = glm::abs(normal); + if (glm::max(absN.x, glm::max(absN.y, absN.z)) < 0.999f) { + return; + } + glm::vec2 d1 = uvs[1] - uvs[0]; + glm::vec2 d2 = uvs[2] - uvs[0]; + + float det = d1.x * d2.y - d2.x * d1.y; + if (std::abs(det) < 1e-6f) { + return; + } + glm::vec3 e1 = coords[1] - coords[0]; + glm::vec3 e2 = coords[2] - coords[0]; + glm::vec3 pu = (e1 * d2.y - e2 * d1.y) / det; + glm::vec3 pv = (e2 * d1.x - e1 * d2.x) / det; + if (glm::length2(pu) < 1e-6f || glm::length2(pv) < 1e-6f) { + return; + } + pu = glm::normalize(pu); + pv = glm::normalize(pv); + + glm::vec3 cu; + glm::vec3 cv; + util::uv_by_normal(normal, cu, cv); + + glm::mat2 uvTransform( + std::round(glm::dot(pu, cu)), std::round(glm::dot(pu, cv)), + std::round(glm::dot(pv, cu)), std::round(glm::dot(pv, cv)) + ); + if (std::abs(std::abs(glm::determinant(uvTransform)) - 1.0f) > 1e-3f) { + return; + } + for (auto& uv : uvs) { + uv = uvTransform * (uv - 0.5f) + 0.5f; + } +} + +static void unrotate_mesh_uv(model::Mesh& mesh, const CoordSystem& orient) { + glm::vec3 X = orient.axes[0]; + glm::vec3 Y = orient.axes[1]; + glm::vec3 Z = orient.axes[2]; + for (size_t j = 0; j + 2 < mesh.vertices.size(); j += 3) { + glm::vec3 pos[3]; + glm::vec2 uv[3]; + for (int i = 0; i < 3; i++) { + auto origin = mesh.vertices[j + i].coord - 0.5f; + pos[i] = origin.x * X + origin.y * Y + origin.z * Z; + uv[i] = mesh.vertices[j + i].uv; + } + const auto& normal = mesh.vertices[j].normal; + unrotate_triangle_uv(pos, uv, normal.x * X + normal.y * Y + normal.z * Z); + for (int i = 0; i < 3; i++) { + mesh.vertices[j + i].uv = uv[i]; + } + } +} + ContentGfxCache::ContentGfxCache( const Content& content, const Assets& assets, @@ -51,11 +118,14 @@ void ContentGfxCache::refreshVariant( sideregions[index + 1] = atlas.get(texOpaque); } if (variant.model.type == BlockModelType::CUSTOM) { - auto model = assets.require(variant.model.name); + const auto& srcModel = assets.require(variant.model.name); - for (auto& mesh : model.meshes) { + std::vector> regions; + regions.reserve(srcModel.meshes.size()); + for (const auto& mesh : srcModel.meshes) { size_t pos = mesh.texture.find(':'); if (pos == std::string::npos) { + regions.emplace_back(std::nullopt); continue; } std::string texture = mesh.texture.substr(pos+1); @@ -63,13 +133,28 @@ void ContentGfxCache::refreshVariant( if (found != optionalTextures.end()) { texture = found->second; } - if (auto region = atlas.getIf(texture)) { + regions.emplace_back(atlas.getIf(texture)); + } + + bool uvLock = def.uvLock && def.rotatable; + int rotationsCount = uvLock ? def.rotations.variantsCount : 1; + for (int rotation = 0; rotation < rotationsCount; rotation++) { + model::Model model = srcModel; + for (size_t i = 0; i < model.meshes.size(); i++) { + auto& mesh = model.meshes[i]; + const auto& region = regions[i]; + if (!region) { + continue; + } + if (uvLock) { + unrotate_mesh_uv(mesh, def.rotations.variants[rotation]); + } for (auto& vertex : mesh.vertices) { vertex.uv = region->apply(vertex.uv); } } + models[modelKey(def.rt.id, variantIndex, rotation)] = std::move(model); } - models[modelKey(def.rt.id, variantIndex)] = std::move(model); } } @@ -101,8 +186,13 @@ void ContentGfxCache::refresh() { ContentGfxCache::~ContentGfxCache() = default; -const model::Model& ContentGfxCache::getModel(blockid_t id, uint8_t variant) const { - const auto& found = models.find(modelKey(id, variant)); +const model::Model& ContentGfxCache::getModel( + blockid_t id, uint8_t variant, uint8_t rotation +) const { + auto found = models.find(modelKey(id, variant, rotation)); + if (found == models.end() && rotation != 0) { + found = models.find(modelKey(id, variant, 0)); + } if (found == models.end()) { throw std::runtime_error("model not found"); } diff --git a/src/frontend/ContentGfxCache.hpp b/src/frontend/ContentGfxCache.hpp index 2d2bacaa1..095850b12 100644 --- a/src/frontend/ContentGfxCache.hpp +++ b/src/frontend/ContentGfxCache.hpp @@ -2,13 +2,12 @@ #include "typedefs.hpp" -#include -#include -#include - #include "maths/UVRegion.hpp" #include "graphics/commons/Model.hpp" +#include +#include + class Content; class Assets; class Atlas; @@ -17,28 +16,9 @@ struct UVRegion; struct Variant; struct GraphicsSettings; -inline constexpr int GFXC_MAX_VARIANTS = 16; -inline constexpr int GFXC_SIDES = 6; - class ContentGfxCache { - const Content& content; - const Assets& assets; - const GraphicsSettings& settings; - - // array of block sides uv regions (6 per block) - std::unique_ptr sideregions; - std::unordered_map models; - - static inline uint64_t modelKey(blockid_t id, uint8_t variant) { - return (uint64_t(id) << 8) | uint64_t(variant & 0xFF); - } - - void refreshVariant( - const Block& def, - const Variant& variant, - uint8_t variantIndex, - const Atlas& atlas - ); + static constexpr int GFXC_MAX_VARIANTS = 16; + static constexpr int GFXC_SIDES = 6; public: ContentGfxCache( const Content& content, @@ -50,16 +30,44 @@ public: static inline size_t getRegionIndex( blockid_t id, uint8_t variant, int side, bool opaque ) { - return ((id * GFXC_SIDES + side) * GFXC_MAX_VARIANTS + variant) * 2 + opaque; + return ((id * GFXC_SIDES + side) * GFXC_MAX_VARIANTS + variant) * 2 + + opaque; } - inline const UVRegion& getRegion(blockid_t id, uint8_t variant, int side, bool dense) const { + inline const UVRegion& getRegion( + blockid_t id, uint8_t variant, int side, bool dense + ) const { return sideregions[getRegionIndex(id, variant, side, !dense)]; } - const model::Model& getModel(blockid_t id, uint8_t variant) const; + const model::Model& getModel( + blockid_t id, uint8_t variant, uint8_t rotation = 0 + ) const; void refresh(const Block& block, const Atlas& atlas); void refresh(); + +private: + const Content& content; + const Assets& assets; + const GraphicsSettings& settings; + + // array of block sides uv regions (6 per block) + std::unique_ptr sideregions; + std::unordered_map models; + + static inline uint64_t modelKey( + blockid_t id, uint8_t variant, uint8_t rotation = 0 + ) { + return (uint64_t(id) << 16) | (uint64_t(rotation & 0xFF) << 8) | + uint64_t(variant & 0xFF); + } + + void refreshVariant( + const Block& def, + const Variant& variant, + uint8_t variantIndex, + const Atlas& atlas + ); }; diff --git a/src/frontend/hud.cpp b/src/frontend/hud.cpp index 6751b885c..ea097e875 100644 --- a/src/frontend/hud.cpp +++ b/src/frontend/hud.cpp @@ -143,9 +143,11 @@ std::shared_ptr Hud::createHotbar() { auto inventory = player.getInventory(); auto& content = frontend.getLevel().content; + int size = player.getHotbarSize(); + SlotLayout slotLayout(-1, glm::vec2(), false, false, nullptr, nullptr, nullptr); InventoryBuilder builder(gui); - builder.addGrid(10, 10, glm::vec2(), glm::vec4(4), true, slotLayout); + builder.addGrid(size, size, glm::vec2(), glm::vec4(4), true, slotLayout); auto view = builder.build(); view->setId("hud.hotbar"); view->setOrigin(glm::vec2(view->getSize().x/2, 0)); @@ -177,7 +179,25 @@ Hud::Hud(Engine& engine, LevelFrontend& frontend, Player& player) contentAccessPanel->setScrollable(true); contentAccessPanel->setId("hud.content-access-panel"); - hotbarView = createHotbar(); + auto hotbarLayout = + frontend.getLevel().content.getDefaults()["hotbar-layout"].asString(""); + if (hotbarLayout.empty()) { + hotbarView = createHotbar(); + } else { + hotbarDocument = &assets.require(hotbarLayout); + hotbarView = + std::dynamic_pointer_cast(hotbarDocument->getRoot()); + if (hotbarView == nullptr) { + throw std::runtime_error( + "hotbar UI root element must be 'inventory'" + ); + } + hotbarView->bind(player.getInventory(), &frontend.getLevel().content); + hotbarView->setInteractive(false); + if (hotbarView->getPositionFunc() == nullptr) { + hotbarView->setOrigin(glm::vec2(hotbarView->getSize().x / 2, 0)); + } + } darkOverlay = guiutil::create( gui, "" @@ -229,6 +249,7 @@ Hud::~Hud() { for (auto& element : elements) { onRemove(element); } + hotbarView->unbind(); gui.remove(hotbarView); gui.remove(darkOverlay); gui.remove(inventoryDropArea); @@ -263,12 +284,13 @@ void Hud::processInput(bool visible) { } void Hud::updateHotbarControl() { + int size = player.getHotbarSize(); int scroll = input.getScroll(); if (!inventoryOpen && scroll) { int slot = player.getChosenSlot(); - slot = (slot - scroll) % 10; + slot = (slot - scroll) % size; if (slot < 0) { - slot += 10; + slot += size; } player.setChosenSlot(slot); } @@ -277,11 +299,12 @@ void Hud::updateHotbarControl() { i <= static_cast(Keycode::NUM_9); i++ ) { - if (input.jpressed(static_cast(i))) { - player.setChosenSlot(i - static_cast(Keycode::NUM_1)); + int slot = i - static_cast(Keycode::NUM_1); + if (slot < size && input.jpressed(static_cast(i))) { + player.setChosenSlot(slot); } } - if (input.jpressed(Keycode::NUM_0)) { + if (size > 9 && input.jpressed(Keycode::NUM_0)) { player.setChosenSlot(9); } } @@ -375,7 +398,16 @@ void Hud::update(bool visible) { contentAccessPanel->setVisible(inventoryView != nullptr && showContentPanel); contentAccessPanel->setSize(glm::vec2(caSize.x, windowSize.y)); contentAccess->setMinSize(glm::vec2(1, windowSize.y)); - hotbarView->setVisible(visible && !(secondUI && !inventoryView)); + if (hotbarDocument == nullptr && + static_cast(hotbarView->getSlotsCount()) != + player.getHotbarSize()) { + gui.remove(hotbarView); + hotbarView = createHotbar(); + gui.add(hotbarView); + } + hotbarView->setVisible( + visible && hotbarVisible && !(secondUI && !inventoryView) + ); darkOverlay->setVisible(isMenuOpen); inventoryDropArea->setVisible(inventoryOpen); menu.setVisible(isMenuOpen); @@ -404,8 +436,16 @@ void Hud::openInventory(bool playerInventory) { if (playerInventory) { auto& content = frontend.getLevel().content; auto inventory = player.getInventory(); - auto inventoryDocument = assets.get("core:inventory"); + auto layout = content.getDefaults()["inventory-layout"].asString( + "core:inventory" + ); + auto inventoryDocument = &assets.require(layout); inventoryView = std::dynamic_pointer_cast(inventoryDocument->getRoot()); + if (inventoryView == nullptr) { + throw std::runtime_error( + "player inventory UI root element must be 'inventory'" + ); + } inventoryView->bind(inventory, &content); add(HudElement(HudElementMode::INVENTORY, inventoryDocument, inventoryView, false)); } @@ -700,7 +740,9 @@ void Hud::updateElementsPosition(const glm::uvec2& viewport) { if (exchangeSlot != nullptr) { exchangeSlot->setPos(input.getCursor().pos); } - hotbarView->setPos(glm::vec2(viewport.x / 2, viewport.y - 65)); + if (hotbarView->getPositionFunc() == nullptr) { + hotbarView->setPos(glm::vec2(viewport.x / 2, viewport.y - 65)); + } hotbarView->setSelected(player.getChosenSlot()); } @@ -790,6 +832,14 @@ void Hud::setAllowPause(bool flag) { allowPause = flag; } +void Hud::setHotbarVisible(bool flag) { + hotbarVisible = flag; +} + +bool Hud::isHotbarVisible() const { + return hotbarVisible; +} + bool Hud::isOpen(const std::string& layoutid) const { for (const auto& element : elements) { auto doc = element.getDocument(); diff --git a/src/frontend/hud.hpp b/src/frontend/hud.hpp index 6b5d62130..1f3b8df93 100644 --- a/src/frontend/hud.hpp +++ b/src/frontend/hud.hpp @@ -89,6 +89,10 @@ class Hud : public util::ObjectsKeeper { std::shared_ptr contentAccess; /// @brief Player inventory hotbar std::shared_ptr hotbarView; + /// @brief Hotbar layout set by 'hotbar-layout', nullptr for built-in + UiDocument* hotbarDocument = nullptr; + /// @brief Hotbar is not hidden by scripts + bool hotbarVisible = true; /// @brief Debug info and control panel (F3 key) std::shared_ptr debugPanel; /// @brief Overlay used in pause mode @@ -219,6 +223,10 @@ public: void setAllowPause(bool flag); + void setHotbarVisible(bool flag); + + bool isHotbarVisible() const; + bool isOpen(const std::string& layoutid) const; static bool showGeneratorMinimap; diff --git a/src/frontend/menu.cpp b/src/frontend/menu.cpp index ab06b42dc..66431f92b 100644 --- a/src/frontend/menu.cpp +++ b/src/frontend/menu.cpp @@ -79,7 +79,9 @@ UiDocument* menus::show( auto documentPtr = UiDocument::read( engine.getGUI(), - scripting::get_root_environment(), + scripting::create_doc_environment( + scripting::get_root_environment(), fullname, true + ), fullname, file, "core:layouts/" + name diff --git a/src/frontend/screens/LevelScreen.cpp b/src/frontend/screens/LevelScreen.cpp index 44fd66d8c..2f29e8b7d 100644 --- a/src/frontend/screens/LevelScreen.cpp +++ b/src/frontend/screens/LevelScreen.cpp @@ -85,10 +85,30 @@ LevelScreen::LevelScreen( }; keepAlive(settings.graphics.backlight.observe(resetChunks)); keepAlive(settings.graphics.softLighting.observe(resetChunks)); - keepAlive(settings.graphics.denseRender.observe([=](bool flag) { - resetChunks(flag); + keepAlive(settings.graphics.denseRender.observe([=](bool) { + resetChunks(false); frontend->getContentGfxCache().refresh(); })); + auto graphics = &settings.graphics; + auto shadowsMeshing = std::make_shared( + graphics->shadowsQuality.get() > 0 && graphics->advancedRender.get() + ); + auto updateShadowsMeshing = [=]() { + bool enabled = + graphics->shadowsQuality.get() > 0 && graphics->advancedRender.get(); + if (enabled == *shadowsMeshing) { + return; + } + *shadowsMeshing = enabled; + resetChunks(false); + frontend->getContentGfxCache().refresh(); + }; + keepAlive(settings.graphics.shadowsQuality.observe([=](int) { + updateShadowsMeshing(); + })); + keepAlive(settings.graphics.advancedRender.observe([=](bool) { + updateShadowsMeshing(); + })); keepAlive(settings.camera.fov.observe([=](double value) { player->fpCamera->setFov(glm::radians(value)); })); diff --git a/src/graphics/commons/Model.cpp b/src/graphics/commons/Model.cpp index 8c2194775..eda9bc748 100644 --- a/src/graphics/commons/Model.cpp +++ b/src/graphics/commons/Model.cpp @@ -3,6 +3,7 @@ #include "Model.hpp" #include +#include #include #include @@ -168,6 +169,25 @@ void Mesh::translate(const glm::vec3& offset) { } } +void Model::calcBounds() { + glm::vec3 min(std::numeric_limits::max()); + glm::vec3 max(std::numeric_limits::lowest()); + for (const auto& mesh : meshes) { + for (const auto& vertex : mesh.vertices) { + min = glm::min(min, vertex.coord); + max = glm::max(max, vertex.coord); + } + } + if (min.x > max.x) { + min = max = glm::vec3(0.0f); + } + bounds = AABB(min, max); +} + +const AABB& Model::getBounds() const { + return bounds; +} + void Model::clean() { meshes.erase( std::remove_if(meshes.begin(), meshes.end(), diff --git a/src/graphics/commons/Model.hpp b/src/graphics/commons/Model.hpp index e42928fba..c2fdf2daf 100644 --- a/src/graphics/commons/Model.hpp +++ b/src/graphics/commons/Model.hpp @@ -5,6 +5,7 @@ #include #include "maths/UVRegion.hpp" +#include "maths/aabb.hpp" namespace model { struct Vertex { @@ -82,6 +83,7 @@ namespace model { struct Model { std::vector meshes; + AABB bounds {glm::vec3(0.0f), glm::vec3(0.0f)}; /// @brief Add mesh to the model /// @param texture texture name @@ -96,6 +98,9 @@ namespace model { return meshes[meshes.size() - 1]; } + void calcBounds(); + const AABB& getBounds() const; + /// @brief Remove all empty meshes void clean(); diff --git a/src/graphics/core/DrawContext.cpp b/src/graphics/core/DrawContext.cpp index 86e2131b1..fdb6b4e44 100644 --- a/src/graphics/core/DrawContext.cpp +++ b/src/graphics/core/DrawContext.cpp @@ -19,6 +19,14 @@ static void set_blend_mode(BlendMode mode) { case BlendMode::inversion: glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); break; + case BlendMode::coverage: + glBlendFuncSeparate( + GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA + ); + break; + case BlendMode::premultiplied: + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + break; } } diff --git a/src/graphics/core/GBuffer.cpp b/src/graphics/core/GBuffer.cpp index 0d8e833e4..fbb67711a 100644 --- a/src/graphics/core/GBuffer.cpp +++ b/src/graphics/core/GBuffer.cpp @@ -8,7 +8,11 @@ using namespace advanced_pipeline; static debug::Logger logger("gl-gbuffer"); -void GBuffer::createBuffer(Buffer& buffer) { +uint GBuffer::getSSAODownsample() const { + return 2; +} + +void GBuffer::createBuffer(Buffer& buffer, int downsample) { if (buffer.buffer == 0) { if (&buffer == &depthBuffer) glGenRenderbuffers(1, &depthBuffer.buffer); @@ -27,8 +31,8 @@ void GBuffer::createBuffer(Buffer& buffer) { GL_TEXTURE_2D, 0, buffer.internalformat, - width, - height, + width / downsample, + height / downsample, 0, buffer.format, buffer.type, @@ -48,8 +52,7 @@ void GBuffer::createBuffer(Buffer& buffer) { } GBuffer::GBuffer(uint width, uint height) - : width(width), height(height), - + : width(width), height(height), colorBuffer {0, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, GL_COLOR_ATTACHMENT0}, positionsBuffer {0, GL_RGBA16F, GL_RGBA, GL_FLOAT, GL_COLOR_ATTACHMENT1}, normalsBuffer {0, GL_RGBA16F, GL_RGB, GL_FLOAT, GL_COLOR_ATTACHMENT2}, @@ -83,7 +86,7 @@ GBuffer::GBuffer(uint width, uint height) glGenFramebuffers(1, &ssaoFbo); glBindFramebuffer(GL_FRAMEBUFFER, ssaoFbo); - createBuffer(ssaoBuffer); + createBuffer(ssaoBuffer, getSSAODownsample()); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ssaoBuffer.buffer, 0 ); @@ -168,7 +171,7 @@ void GBuffer::resize(uint width, uint height) { glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, ssaoFbo); - createBuffer(ssaoBuffer); + createBuffer(ssaoBuffer, getSSAODownsample()); glBindTexture(GL_TEXTURE_2D, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); } diff --git a/src/graphics/core/GBuffer.hpp b/src/graphics/core/GBuffer.hpp index 1614b39ea..5b18a7de8 100644 --- a/src/graphics/core/GBuffer.hpp +++ b/src/graphics/core/GBuffer.hpp @@ -24,6 +24,8 @@ public: uint getHeight() const; std::unique_ptr toImage() const; + + uint getSSAODownsample() const; private: struct Buffer { uint buffer; @@ -45,5 +47,5 @@ private: uint ssaoFbo; Buffer ssaoBuffer; - void createBuffer(Buffer& buffer); + void createBuffer(Buffer& buffer, int downsample = 1); }; diff --git a/src/graphics/core/InstanceBuffer.hpp b/src/graphics/core/InstanceBuffer.hpp new file mode 100644 index 000000000..4513a353e --- /dev/null +++ b/src/graphics/core/InstanceBuffer.hpp @@ -0,0 +1,20 @@ +#pragma once + +#include + +#include "MeshData.hpp" + +template +class InstanceBuffer { + unsigned int vbo; + size_t capacity; +public: + InstanceBuffer(); + ~InstanceBuffer(); + + void reload(const InstanceStructure* instances, size_t count); + + void bind(int location, size_t first) const; +}; + +#include "graphics/core/InstanceBuffer.inl" diff --git a/src/graphics/core/InstanceBuffer.inl b/src/graphics/core/InstanceBuffer.inl new file mode 100644 index 000000000..67110705c --- /dev/null +++ b/src/graphics/core/InstanceBuffer.inl @@ -0,0 +1,55 @@ +#pragma once + +#include + +#include "gl_util.hpp" + +template +InstanceBuffer::InstanceBuffer() : vbo(0), capacity(0) { + static_assert( + calc_size(InstanceStructure::ATTRIBUTES) == sizeof(InstanceStructure) + ); + glGenBuffers(1, &vbo); +} + +template +InstanceBuffer::~InstanceBuffer() { + glDeleteBuffers(1, &vbo); +} + +template +void InstanceBuffer::reload( + const InstanceStructure* instances, size_t count +) { + size_t size = count * sizeof(InstanceStructure); + if (size > capacity) { + capacity = std::max(size, capacity * 2); + } + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glBufferData(GL_ARRAY_BUFFER, capacity, nullptr, GL_STREAM_DRAW); + glBufferSubData(GL_ARRAY_BUFFER, 0, size, instances); + glBindBuffer(GL_ARRAY_BUFFER, 0); +} + +template +void InstanceBuffer::bind(int location, size_t first) const { + const auto& attrs = InstanceStructure::ATTRIBUTES; + + glBindBuffer(GL_ARRAY_BUFFER, vbo); + size_t offset = first * sizeof(InstanceStructure); + for (int i = 0; attrs[i].count; i++) { + const VertexAttribute& attr = attrs[i]; + glVertexAttribPointer( + location + i, + attr.count, + gl::to_glenum(attr.type), + attr.normalized, + sizeof(InstanceStructure), + (GLvoid*)offset + ); + glVertexAttribDivisor(location + i, 1); + glEnableVertexAttribArray(location + i); + offset += attr.size(); + } + glBindBuffer(GL_ARRAY_BUFFER, 0); +} diff --git a/src/graphics/core/Mesh.hpp b/src/graphics/core/Mesh.hpp index f27fc4e2a..35fc894ac 100644 --- a/src/graphics/core/Mesh.hpp +++ b/src/graphics/core/Mesh.hpp @@ -3,6 +3,7 @@ #include #include "MeshData.hpp" +#include "InstanceBuffer.hpp" struct MeshStats { @@ -65,6 +66,13 @@ public: /// @brief Draw mesh as triangles void draw() const; + + template + void drawInstanced( + const InstanceBuffer& instances, + size_t first, + size_t count + ) const; private: }; diff --git a/src/graphics/core/Mesh.inl b/src/graphics/core/Mesh.inl index b92c1b26e..df1b20185 100644 --- a/src/graphics/core/Mesh.inl +++ b/src/graphics/core/Mesh.inl @@ -3,14 +3,6 @@ #include "MeshData.hpp" #include "gl_util.hpp" -inline constexpr size_t calc_size(const VertexAttribute attrs[]) { - size_t vertexSize = 0; - for (int i = 0; attrs[i].count; i++) { - vertexSize += attrs[i].size(); - } - return vertexSize; -} - template inline std::vector convert_to_ibd(const MeshData& data) { std::vector indices; @@ -147,3 +139,22 @@ template void Mesh::draw() const { draw(GL_TRIANGLES); } + +template +template +void Mesh::drawInstanced( + const InstanceBuffer& instances, + size_t first, + size_t count +) const { + if (vertexCount == 0 || count == 0) { + return; + } + MeshStats::drawCalls++; + + glBindVertexArray(vao); + instances.bind(count_attributes(VertexStructure::ATTRIBUTES), first); + glDrawArraysInstanced(GL_TRIANGLES, 0, vertexCount, count); + glBindVertexArray(0); + MeshStats::vertices += vertexCount * count; +} diff --git a/src/graphics/core/MeshData.hpp b/src/graphics/core/MeshData.hpp index e9a0630c5..c26f53fd2 100644 --- a/src/graphics/core/MeshData.hpp +++ b/src/graphics/core/MeshData.hpp @@ -37,6 +37,22 @@ struct VertexAttribute { } }; +inline constexpr size_t calc_size(const VertexAttribute attrs[]) { + size_t vertexSize = 0; + for (int i = 0; attrs[i].count; i++) { + vertexSize += attrs[i].size(); + } + return vertexSize; +} + +inline constexpr int count_attributes(const VertexAttribute attrs[]) { + int count = 0; + while (attrs[count].count) { + count++; + } + return count; +} + /// @brief Raw mesh data structure template struct MeshData { diff --git a/src/graphics/core/PostProcessing.cpp b/src/graphics/core/PostProcessing.cpp index b50fad388..3a0b538fd 100644 --- a/src/graphics/core/PostProcessing.cpp +++ b/src/graphics/core/PostProcessing.cpp @@ -34,7 +34,8 @@ PostProcessing::PostProcessing(size_t effectSlotsCount) quadMesh = std::make_unique>(meshData, 6); std::vector ssaoNoise; - for (unsigned int i = 0; i < 16; i++) + int res = 4; + for (unsigned int i = 0; i < res*res; i++) { glm::vec3 noise( (rand() / static_cast(RAND_MAX)) * 2.0 - 1.0, @@ -44,7 +45,7 @@ PostProcessing::PostProcessing(size_t effectSlotsCount) } glGenTextures(1, &noiseTexture); glBindTexture(GL_TEXTURE_2D, noiseTexture); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, 4, 4, 0, GL_RGB, GL_FLOAT, ssaoNoise.data()); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, res, res, 0, GL_RGB, GL_FLOAT, ssaoNoise.data()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); @@ -94,7 +95,8 @@ void PostProcessing::configureEffect( PostEffect& effect, Shader& shader, float timer, - const Camera& camera + const Camera& camera, + unsigned int downsample ) { const auto& viewport = context.getViewport(); shader.uniform1i("u_screen", TARGET_COLOR); @@ -106,7 +108,7 @@ void PostProcessing::configureEffect( } shader.uniform1i("u_noise", TARGET_SSAO); // used in SSAO pass shader.uniform1i("u_ssao", TARGET_SSAO); - shader.uniform2i("u_screenSize", viewport); + shader.uniform2i("u_screenSize", viewport / downsample); shader.uniform3f("u_cameraPos", camera.position); shader.uniform1f("u_timer", timer); shader.uniformMatrix("u_projection", camera.getProjection()); @@ -134,15 +136,14 @@ void PostProcessing::renderDeferredShading( auto& ssaoEffect = assets.require("ssao"); auto& shader = ssaoEffect.use(); - configureEffect( - context, - ssaoEffect, - shader, - timer, - camera - ); + uint ssaoDownscale = gbuffer->getSSAODownsample(); + configureEffect(context, ssaoEffect, shader, timer, camera, ssaoDownscale); gbuffer->bindSSAO(); - quadMesh->draw(); + { + auto ssaoContext = context.sub(); + ssaoContext.setViewport(context.getViewport() / ssaoDownscale); + quadMesh->draw(); + } gbuffer->unbind(); { diff --git a/src/graphics/core/PostProcessing.hpp b/src/graphics/core/PostProcessing.hpp index 095e4e2b3..c85a27c0f 100644 --- a/src/graphics/core/PostProcessing.hpp +++ b/src/graphics/core/PostProcessing.hpp @@ -66,7 +66,8 @@ private: PostEffect& effect, Shader& shader, float timer, - const Camera& camera + const Camera& camera, + unsigned downsample = 1U ); void refreshFbos(uint width, uint height); diff --git a/src/graphics/core/TranslucentLayers.cpp b/src/graphics/core/TranslucentLayers.cpp new file mode 100644 index 000000000..e88951118 --- /dev/null +++ b/src/graphics/core/TranslucentLayers.cpp @@ -0,0 +1,146 @@ +#include "TranslucentLayers.hpp" + +#include +#include + +#include "Mesh.hpp" +#include "PostProcessing.hpp" +#include "Shader.hpp" +#include "debug/Logger.hpp" + +static debug::Logger logger("gl-translucent-layers"); + +inline constexpr int FIRST_TEXTURE_UNIT = advanced_pipeline::TARGETS_COUNT; + +static void setup_texture(uint texture) { + glBindTexture(GL_TEXTURE_2D, texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); +} + +TranslucentLayers::Layer::Layer() { + glGenFramebuffers(1, &fbo); + glGenTextures(1, &color); + glGenTextures(1, &depth); +} + +TranslucentLayers::Layer::~Layer() { + glDeleteFramebuffers(1, &fbo); + glDeleteTextures(1, &color); + glDeleteTextures(1, &depth); +} + +void TranslucentLayers::Layer::bind() const { + glBindFramebuffer(GL_FRAMEBUFFER, fbo); +} + +void TranslucentLayers::Layer::unbind() const { + glBindFramebuffer(GL_FRAMEBUFFER, 0); +} + +void TranslucentLayers::Layer::allocate(uint width, uint height) { + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + + setup_texture(color); + glTexImage2D( + GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, + GL_RGBA, GL_UNSIGNED_BYTE, nullptr + ); + glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color, 0 + ); + + setup_texture(depth); + glTexImage2D( + GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, + GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr + ); + glFramebufferTexture2D( + GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0 + ); + + GLenum attachments[1] = {GL_COLOR_ATTACHMENT0}; + glDrawBuffers(1, attachments); + + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + logger.error() << "translucent layer framebuffer is not complete!"; + } + glBindTexture(GL_TEXTURE_2D, 0); + glBindFramebuffer(GL_FRAMEBUFFER, 0); +} + +TranslucentLayers::TranslucentLayers(size_t count, uint width, uint height) + : width(width), height(height) { + for (size_t i = 0; i < count; i++) { + auto layer = std::make_unique(); + layer->allocate(width, height); + layers.push_back(std::move(layer)); + } + PostProcessingVertex meshData[] { + {{-1.0f, -1.0f}}, + {{-1.0f, 1.0f}}, + {{1.0f, 1.0f}}, + {{-1.0f, -1.0f}}, + {{1.0f, 1.0f}}, + {{1.0f, -1.0f}}, + }; + quadMesh = std::make_unique>(meshData, 6); +} + +TranslucentLayers::~TranslucentLayers() = default; + +void TranslucentLayers::resize(uint width, uint height) { + if (this->width == width && this->height == height) { + return; + } + this->width = width; + this->height = height; + for (auto& layer : layers) { + layer->allocate(width, height); + } +} + +void TranslucentLayers::prepare(uint sourceFbo) { + const GLfloat transparent[4] {0.0f, 0.0f, 0.0f, 0.0f}; + for (const auto& layer : layers) { + glBindFramebuffer(GL_READ_FRAMEBUFFER, sourceFbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, layer->fbo); + glBlitFramebuffer( + 0, 0, width, height, 0, 0, width, height, + GL_DEPTH_BUFFER_BIT, GL_NEAREST + ); + glBindFramebuffer(GL_FRAMEBUFFER, layer->fbo); + glClearBufferfv(GL_COLOR, 0, transparent); + } + glBindFramebuffer(GL_FRAMEBUFFER, sourceFbo); +} + +Bindable& TranslucentLayers::getLayer(size_t index) { + return *layers.at(index); +} + +void TranslucentLayers::compose(Shader& shader) { + shader.use(); + int count = static_cast(layers.size()); + for (int i = 0; i < count; i++) { + int colorUnit = FIRST_TEXTURE_UNIT + i; + int depthUnit = FIRST_TEXTURE_UNIT + count + i; + + glActiveTexture(GL_TEXTURE0 + colorUnit); + glBindTexture(GL_TEXTURE_2D, layers[i]->color); + shader.uniform1i("u_layerColor" + std::to_string(i), colorUnit); + + glActiveTexture(GL_TEXTURE0 + depthUnit); + glBindTexture(GL_TEXTURE_2D, layers[i]->depth); + shader.uniform1i("u_layerDepth" + std::to_string(i), depthUnit); + } + quadMesh->draw(); + + for (int i = 0; i < count * 2; i++) { + glActiveTexture(GL_TEXTURE0 + FIRST_TEXTURE_UNIT + i); + glBindTexture(GL_TEXTURE_2D, 0); + } + glActiveTexture(GL_TEXTURE0); +} diff --git a/src/graphics/core/TranslucentLayers.hpp b/src/graphics/core/TranslucentLayers.hpp new file mode 100644 index 000000000..71d39727c --- /dev/null +++ b/src/graphics/core/TranslucentLayers.hpp @@ -0,0 +1,46 @@ +#pragma once + +#include "typedefs.hpp" +#include "commons.hpp" + +#include +#include + +template class Mesh; +struct PostProcessingVertex; +class Shader; + +class TranslucentLayers { +public: + TranslucentLayers(size_t count, uint width, uint height); + ~TranslucentLayers(); + + void resize(uint width, uint height); + + void prepare(uint sourceFbo); + + Bindable& getLayer(size_t index); + + void compose(Shader& shader); + +private: + class Layer : public Bindable { + public: + uint fbo = 0; + uint color = 0; + uint depth = 0; + + Layer(); + ~Layer() override; + + void bind() const override; + void unbind() const override; + + void allocate(uint width, uint height); + }; + + uint width; + uint height; + std::vector> layers; + std::unique_ptr> quadMesh; +}; diff --git a/src/graphics/core/commons.hpp b/src/graphics/core/commons.hpp index 0ca5a6470..ef1c92cb8 100644 --- a/src/graphics/core/commons.hpp +++ b/src/graphics/core/commons.hpp @@ -17,7 +17,11 @@ enum class BlendMode { /// @brief Additive blending mode. addition, /// @brief Subtractive blending mode. - inversion + inversion, + /// @brief Normal color blending with alpha accumulated as coverage. + coverage, + /// @brief Blending of premultiplied-alpha color. + premultiplied }; /// @brief Standard GLFW 3.4 cursor shapes (same order and count as in GLFW). diff --git a/src/graphics/render/BlockWrapsRenderer.cpp b/src/graphics/render/BlockWrapsRenderer.cpp index 7548afa34..d892605e0 100644 --- a/src/graphics/render/BlockWrapsRenderer.cpp +++ b/src/graphics/render/BlockWrapsRenderer.cpp @@ -70,9 +70,7 @@ void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) { ); break; case BlockModelType::AABB: { - const auto& aabb = - (def.rotatable ? def.rt.hitboxes[vox->state.rotation] - : def.hitboxes).at(0); + const auto& aabb = def.getHitboxes(vox->state).at(0); const auto& size = aabb.size(); batch->cube( glm::vec3(wrapper.position) + aabb.center(), @@ -121,9 +119,7 @@ void BlockWrapsRenderer::refreshWrapper(BlockWrapper& wrapper) { wrapper.modelType = def.getModel(vox->state.userbits).type; switch (wrapper.modelType) { case BlockModelType::AABB: { - const auto& aabb = - (def.rotatable ? def.rt.hitboxes[vox->state.rotation] - : def.hitboxes).at(0); + const auto& aabb = def.getHitboxes(vox->state).at(0); const auto& size = aabb.size(); wrapper.uvRegions[0].scale(size.z, size.y); wrapper.uvRegions[1].scale(size.z, size.y); @@ -143,8 +139,10 @@ void BlockWrapsRenderer::draw(const DrawContext& pctx) { auto& shader = assets.require("entity"); shader.use(); - shader.uniform1i("u_alphaClip", false); - shader.uniform1i("u_dithering", 0); + shader.uniform1f("u_alphaThreshold", 0.15f); + shader.uniform1i("u_opaque", false); + shader.uniform1i("u_forward", false); + shader.uniform1i("u_forwardLight", false); for (const auto& [_, wrapper] : wrappers) { if (wrapper->dirtySides) { diff --git a/src/graphics/render/BlocksPreview.cpp b/src/graphics/render/BlocksPreview.cpp index ad025d3c8..aab38a705 100644 --- a/src/graphics/render/BlocksPreview.cpp +++ b/src/graphics/render/BlocksPreview.cpp @@ -46,7 +46,7 @@ std::unique_ptr BlocksPreview::draw( case BlockModelType::AABB: { glm::vec3 hitbox {}; - for (const auto& box : def.hitboxes) { + for (const auto& box : def.defaults.hitboxes) { hitbox = glm::max(hitbox, box.size()); } offset = glm::vec3(1, 1, 0.0f); diff --git a/src/graphics/render/BlocksRenderer.cpp b/src/graphics/render/BlocksRenderer.cpp index 8b8a667eb..7fbb09e82 100644 --- a/src/graphics/render/BlocksRenderer.cpp +++ b/src/graphics/render/BlocksRenderer.cpp @@ -10,7 +10,6 @@ #include "frontend/ContentGfxCache.hpp" const glm::vec3 BlocksRenderer::SUN_VECTOR(0.528265, 0.833149, -0.163704); -constexpr float DIRECTIONAL_LIGHT_FACTOR = 0.3f; BlocksRenderer::BlocksRenderer( size_t capacity, @@ -128,7 +127,7 @@ void BlocksRenderer::faceAO( float s = 0.5f; if (lights) { float d = glm::dot(glm::normalize(Z), SUN_VECTOR); - d = (1.0f - DIRECTIONAL_LIGHT_FACTOR) + d * DIRECTIONAL_LIGHT_FACTOR; + d = (1.0f - directionalLightFactor) + d * directionalLightFactor; auto axisX = glm::normalize(X); auto axisY = glm::normalize(Y); @@ -167,7 +166,7 @@ void BlocksRenderer::face( float s = 0.5f; if (lights) { float d = glm::dot(glm::normalize(Z), SUN_VECTOR); - d = (1.0f - DIRECTIONAL_LIGHT_FACTOR) + d * DIRECTIONAL_LIGHT_FACTOR; + d = (1.0f - directionalLightFactor) + d * directionalLightFactor; tint *= d; } vertex(coord + (-X - Y + Z) * s, region.u1, region.v1, tint, Z, lights ? 0 : 1); @@ -225,15 +224,16 @@ void BlocksRenderer::blockAABB( const glm::ivec3& icoord, const UVRegion(&texfaces)[6], const Block* block, - ubyte rotation, + blockstate states, bool lights, bool ao ) { - if (block->hitboxes.empty()) { + const auto& hitboxes = block->getVariantByBits(states.userbits).hitboxes; + if (hitboxes.empty()) { return; } - AABB hitbox = block->hitboxes[0]; - for (const auto& box : block->hitboxes) { + AABB hitbox = hitboxes[0]; + for (const auto& box : hitboxes) { hitbox.a = glm::min(hitbox.a, box.a); hitbox.b = glm::max(hitbox.b, box.b); } @@ -244,7 +244,7 @@ void BlocksRenderer::blockAABB( glm::vec3 coord(icoord); if (block->rotatable) { auto& rotations = block->rotations; - auto& orient = rotations.variants[rotation]; + auto& orient = rotations.variants[states.rotation]; X = orient.axes[0]; Y = orient.axes[1]; Z = orient.axes[2]; @@ -317,7 +317,11 @@ void BlocksRenderer::blockCustomModel( ); } - const auto& model = cache.getModel(block.rt.id, block.getVariantIndex(states.userbits)); + const auto& model = cache.getModel( + block.rt.id, + block.getVariantIndex(states.userbits), + block.uvLock && block.rotatable ? states.rotation : 0 + ); for (const auto& mesh : model.meshes) { if (vertexCount + mesh.vertices.size() >= capacity || indexCount + mesh.vertices.size() >= capacity) { @@ -349,7 +353,7 @@ void BlocksRenderer::blockCustomModel( } float d = glm::dot(n, SUN_VECTOR); - d = (1.0f - DIRECTIONAL_LIGHT_FACTOR) + d * DIRECTIONAL_LIGHT_FACTOR; + d = (1.0f - directionalLightFactor) + d * directionalLightFactor; glm::vec3 t = glm::cross(r, n); for (int i = 0; i < 3; i++) { @@ -538,7 +542,7 @@ void BlocksRenderer::render( } case BlockModelType::AABB: { if (!denseRender) - blockAABB({x, y, z}, texfaces, &def, vox.state.rotation, + blockAABB({x, y, z}, texfaces, &def, vox.state, !def.shadeless, def.ambientOcclusion && enableAO); break; } @@ -610,7 +614,7 @@ SortingMeshData BlocksRenderer::renderTranslucent( {x, y, z}, texfaces, &def, - vox.state.rotation, + vox.state, !def.shadeless, def.ambientOcclusion && enableAO ); @@ -692,6 +696,11 @@ SortingMeshData BlocksRenderer::renderTranslucent( void BlocksRenderer::build( const Chunk* chunk, const VoxelsRenderVolume& volume ) { + directionalLightFactor = settings.graphics.shadowsQuality.get() > 0 && + settings.graphics.advancedRender.get() + ? 0.0f + : DEFAULT_DIRECTIONAL_LIGHT_FACTOR; + meshAABB = AABB(glm::vec3(CHUNK_W, CHUNK_H, CHUNK_D)); this->chunk = chunk; this->voxelsBuffer = &volume; diff --git a/src/graphics/render/BlocksRenderer.hpp b/src/graphics/render/BlocksRenderer.hpp index 819e79bca..a276d78a5 100644 --- a/src/graphics/render/BlocksRenderer.hpp +++ b/src/graphics/render/BlocksRenderer.hpp @@ -23,6 +23,8 @@ struct UVRegion; class BlocksRenderer final { public: + static constexpr float DEFAULT_DIRECTIONAL_LIGHT_FACTOR = 0.3f; + BlocksRenderer( size_t capacity, const Block* const* blockDefs, @@ -56,6 +58,8 @@ private: bool cancelled = false; bool densePass = false; bool denseRender = false; + float directionalLightFactor = 0.0f; + AABB meshAABB {}; const Chunk* chunk = nullptr; const VoxelsRenderVolume* voxelsBuffer = nullptr; @@ -124,7 +128,7 @@ private: const glm::ivec3& coord, const UVRegion(&faces)[6], const Block* block, - ubyte rotation, + blockstate states, bool lights, bool ambientOcclusion ); diff --git a/src/graphics/render/Decorator.cpp b/src/graphics/render/Decorator.cpp index 26a2b302e..dfe86b289 100644 --- a/src/graphics/render/Decorator.cpp +++ b/src/graphics/render/Decorator.cpp @@ -159,7 +159,7 @@ void Decorator::updateAcoustics(const Camera& camera) { acoustics.reverbReflectionsDelay = minDistance / speedOfSound; acoustics.reverbLateReflectionsDelay = averageDistance / speedOfSound; acoustics.reverbDecayTime = decayTime; - acoustics.reverbRoomRolloff = escapeRatio * 1.5f; + acoustics.reverbRoomRolloff = 0.1f + escapeRatio * 1.5f; acoustics.reverbAbsorption = averageAbsorption; audio::set_acoustics(std::move(acoustics)); diff --git a/src/graphics/render/EntitiesRenderer.cpp b/src/graphics/render/EntitiesRenderer.cpp new file mode 100644 index 000000000..9cbc82dcf --- /dev/null +++ b/src/graphics/render/EntitiesRenderer.cpp @@ -0,0 +1,177 @@ +#include "EntitiesRenderer.hpp" + +#include "animation/rigging.hpp" +#include "assets/Assets.hpp" +#include "graphics/core/DrawContext.hpp" +#include "graphics/core/LineBatch.hpp" +#include "maths/FrustumCulling.hpp" +#include "objects/Entities.hpp" +#include "objects/Entity.hpp" +#include "objects/EntityDef.hpp" +#include "ModelBatch.hpp" + +static void debug_render_skeleton( + LineBatch& batch, + const rigging::Bone* bone, + const rigging::Skeleton& skeleton +) { + size_t pindex = bone->getIndex(); + for (auto& sub : bone->getBones()) { + size_t sindex = sub->getIndex(); + const auto& matrices = skeleton.calculated.matrices; + batch.line( + glm::vec3(matrices[pindex] * glm::vec4(0, 0, 0, 1)), + glm::vec3(matrices[sindex] * glm::vec4(0, 0, 0, 1)), + glm::vec4(0, 0.5f, 0, 1) + ); + debug_render_skeleton(batch, sub.get(), skeleton); + } +} + +static glm::vec3 calc_extent( + const Transform& transform, + const Rigidbody& rigidbody, + const rigging::Skeleton& skeleton +) { + const auto& size = transform.size; + float scale = glm::max( + glm::abs(size.x), glm::max(glm::abs(size.y), glm::abs(size.z)) + ); + return glm::max( + rigidbody.hitbox.getHalfSize(), glm::vec3(skeleton.boundsRadius * scale) + ); +} + +static bool check_frustum( + const Frustum& frustum, + const Transform& transform, + const Rigidbody& rigidbody, + const rigging::Skeleton& skeleton +) { + glm::vec3 ext = calc_extent(transform, rigidbody, skeleton); + return frustum.isBoxVisible(transform.pos - ext, transform.pos + ext); +} + +EntitiesRenderer::EntitiesRenderer(const Assets& assets, Entities& entities) + : assets(assets), entities(entities) { +} + +void EntitiesRenderer::render( + ModelBatch& batch, const Frustum* frustum, entityid_t fpsEntity +) { + for (const auto& [uid, entity] : entities.getEntities()) { + if (!entity->getSkeleton() || uid == fpsEntity) { + continue; + } + const auto& transform = entity->getTransform(); + const auto& rigidbody = entity->getRigidbody(); + auto& skeleton = *entity->getSkeleton(); + const auto& def = entity->getID().def; + const auto& pos = transform.pos; + const auto& size = transform.size; + const auto& rigConfig = skeleton.config; + if (rigConfig == nullptr) { + continue; + } + if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { + if (!skeleton.boundsDirty || !skeleton.visible) { + continue; + } + rigConfig->updateBounds(assets, skeleton, transform.rot, pos, size); + if (!check_frustum(*frustum, transform, rigidbody, skeleton)) { + continue; + } + } + rigConfig->render( + assets, + batch, + skeleton, + def.lightingMode, + transform.rot, + pos, + size, + def.translucent + ); + } +} + +void EntitiesRenderer::renderDebug( + LineBatch& batch, + const Frustum* frustum, + const DrawContext& pctx, + entityid_t fpsEntity +) { + const auto& all = entities.getEntities(); + { + auto ctx = pctx.sub(&batch); + ctx.setLineWidth(1); + for (const auto& [uid, entity] : all) { + if (!entity->getSkeleton()) { + continue; + } + const auto& transform = entity->getTransform(); + const auto& rigidbody = entity->getRigidbody(); + const auto& skeleton = *entity->getSkeleton(); + const auto& hitbox = rigidbody.hitbox; + if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { + continue; + } + batch.box( + hitbox.position, hitbox.getHalfSize() * 2.0f, glm::vec4(1.0f) + ); + glm::vec3 ext = calc_extent(transform, rigidbody, skeleton); + batch.box( + transform.pos, ext * 2.0f, glm::vec4(0.0f, 0.0f, 1.0f, 1.0f) + ); + for (auto& sensor : rigidbody.sensors) { + if (sensor.type != SensorType::AABB) continue; + batch.box( + sensor.calculated.aabb.center(), + sensor.calculated.aabb.size(), + glm::vec4(1.0f, 1.0f, 0.0f, 1.0f) + ); + } + } + } + { + auto ctx = pctx.sub(&batch); + ctx.setDepthTest(false); + ctx.setDepthMask(false); + ctx.setLineWidth(2); + for (const auto& [uid, entity] : all) { + if (!entity->getSkeleton() || uid == fpsEntity) { + continue; + } + const auto& transform = entity->getTransform(); + const auto& rigidbody = entity->getRigidbody(); + const auto& skeleton = *entity->getSkeleton(); + auto config = skeleton.config; + if (config == nullptr) { + continue; + } + if (frustum && !check_frustum(*frustum, transform, rigidbody, skeleton)) { + continue; + } + auto bone = config->getRoot(); + debug_render_skeleton(batch, bone, skeleton); + } + } +} + +void EntitiesRenderer::updateCulling( + const Frustum* frustum, entityid_t fpsEntity +) { + for (const auto& [uid, entity] : entities.getEntities()) { + if (!entity->getSkeleton()) { + continue; + } + auto& skeleton = *entity->getSkeleton(); + if (frustum == nullptr || uid == fpsEntity) { + skeleton.culled = false; + continue; + } + skeleton.culled = !check_frustum( + *frustum, entity->getTransform(), entity->getRigidbody(), skeleton + ); + } +} diff --git a/src/graphics/render/EntitiesRenderer.hpp b/src/graphics/render/EntitiesRenderer.hpp new file mode 100644 index 000000000..8a91ad3ce --- /dev/null +++ b/src/graphics/render/EntitiesRenderer.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "typedefs.hpp" + +class Assets; +class DrawContext; +class Entities; +class Frustum; +class LineBatch; +class ModelBatch; + +class EntitiesRenderer { + const Assets& assets; + Entities& entities; +public: + EntitiesRenderer(const Assets& assets, Entities& entities); + + void render( + ModelBatch& batch, const Frustum* frustum, entityid_t fpsEntity + ); + + void renderDebug( + LineBatch& batch, + const Frustum* frustum, + const DrawContext& ctx, + entityid_t fpsEntity + ); + + void updateCulling(const Frustum* frustum, entityid_t fpsEntity); +}; diff --git a/src/graphics/render/ModelBatch.cpp b/src/graphics/render/ModelBatch.cpp index 35b5e6274..958f2bc0d 100644 --- a/src/graphics/render/ModelBatch.cpp +++ b/src/graphics/render/ModelBatch.cpp @@ -2,47 +2,18 @@ #include "assets/assets_util.hpp" #include "graphics/commons/Model.hpp" -#include "graphics/core/Mesh.hpp" -#include "graphics/core/Atlas.hpp" #include "graphics/core/Texture.hpp" +#include "graphics/core/ImageData.hpp" +#include "graphics/core/Mesh.hpp" #include "assets/Assets.hpp" #include "voxels/Chunks.hpp" -#include "lighting/Lightmap.hpp" #include "settings.hpp" #include "MainBatch.hpp" -#define GLM_ENABLE_EXPERIMENTAL -#include -#include -#include - #include -inline constexpr glm::vec3 X(1, 0, 0); -inline constexpr glm::vec3 Y(0, 1, 0); -inline constexpr glm::vec3 Z(0, 0, 1); - -struct DecomposedMat4 { - glm::vec3 scale; - glm::mat3 rotation; - glm::vec3 translation; - glm::vec3 skew; - glm::vec4 perspective; -}; - -static glm::mat4 extract_rotation(glm::mat4 matrix) { - DecomposedMat4 decomposed = {}; - glm::quat rotation; - glm::decompose( - matrix, - decomposed.scale, - rotation, - decomposed.translation, - decomposed.skew, - decomposed.perspective - ); - return glm::toMat3(rotation); -} +inline constexpr uint64_t COLLECT_EVERY = 600; +inline constexpr uint64_t UNUSED_FRAMES = 1200; ModelBatch::ModelBatch( size_t capacity, @@ -50,108 +21,204 @@ ModelBatch::ModelBatch( const Chunks& chunks, const EngineSettings& settings ) - : assets(assets), - chunks(chunks), - settings(settings), - batch(std::make_unique(capacity)) {} + : assets(assets), chunks(chunks), settings(settings) { + entries.reserve(capacity / 36); + + const ubyte pixels[] = {255, 255, 255, 255}; + ImageData image(ImageFormat::RGBA8888, 1, 1, pixels); + blank = Texture::from(&image); + + instanceBuffer = std::make_unique>(); +} ModelBatch::~ModelBatch() = default; -void ModelBatch::draw( - const model::Mesh& mesh, - const glm::mat4& matrix, - const glm::mat3& rotation, - const glm::vec4& tint, - const TextureNamesMap* varTextures, - bool backlight +ModelBatch::GpuModel& ModelBatch::upload( + const std::shared_ptr& model ) { - setTexture(mesh.texture, varTextures); - size_t vcount = mesh.vertices.size(); - const auto& vertexData = mesh.vertices.data(); - - glm::vec4 lights(1, 1, 1, 0); - if (mesh.shading) { - glm::vec3 gpos = matrix * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f); - gpos += lightsOffset + localLightsOffset; - lights = MainBatch::sampleLight(gpos, chunks, backlight); + auto& gpuModel = models[model.get()]; + bool valid = gpuModel.model.lock() == model && + gpuModel.meshes.size() == model->meshes.size(); + for (size_t i = 0; valid && i < gpuModel.meshes.size(); i++) { + valid = gpuModel.meshes[i].vertexCount == + model->meshes[i].vertices.size(); } - for (size_t i = 0; i < vcount / 3; i++) { - batch->prepare(3); - for (size_t j = 0; j < 3; j++) { - const auto vert = vertexData[i * 3 + j]; - float d = 1.0f; - auto norm = rotation * vert.normal; - if (mesh.shading) { - d = glm::dot(norm, SUN_VECTOR); - d = 0.8f + d * 0.2f; - } - batch->vertex( - matrix * glm::vec4(vert.coord, 1.0f), - vert.uv, - lights * d, - tint, - norm, - mesh.shading ? 0.0f : 1.0f - ); + static_assert(sizeof(Vertex) == sizeof(model::Vertex)); + if (!valid) { + gpuModel.meshes.clear(); + gpuModel.model = model; + for (const auto& mesh : model->meshes) { + gpuModel.meshes.push_back(GpuMesh { + std::make_unique>( + reinterpret_cast(mesh.vertices.data()), + mesh.vertices.size() + ), + mesh.vertices.size()}); } } + gpuModel.lastUsed = frame; + return gpuModel; +} + +void ModelBatch::collectUnused() { + for (auto it = models.begin(); it != models.end();) { + if (frame - it->second.lastUsed > UNUSED_FRAMES || + it->second.model.expired()) { + it = models.erase(it); + } else { + ++it; + } + } +} + +const util::TextureRegion& ModelBatch::getTexture( + const std::string& name, const TextureNamesMap* varTextures +) { + static const util::TextureRegion NONE {nullptr, UVRegion(0, 0, 1, 1)}; + if (varTextures && !name.empty() && name.at(0) == '$') { + const auto& found = varTextures->find(name); + if (found == varTextures->end()) { + return NONE; + } + return getTexture(found->second, varTextures); + } + const auto& found = textures.find(&name); + if (found != textures.end()) { + return found->second; + } + auto byName = texturesByName.find(name); + if (byName == texturesByName.end()) { + byName = texturesByName.emplace( + name, util::get_texture_region(assets, name, "blocks:notfound") + ).first; + } + return textures[&name] = byName->second; } void ModelBatch::draw( const glm::mat4& matrix, const glm::vec4& tint, const glm::vec3& lightSampleOffset, - const model::Model* model, - const TextureNamesMap* varTextures + const std::shared_ptr& model, + const TextureNamesMap* varTextures, + bool translucent ) { - for (const auto& mesh : model->meshes) { - entries.push_back(DrawEntry { - matrix, - extract_rotation(matrix), - tint, - lightSampleOffset, - &mesh, - varTextures}); + auto& queue = + translucent || tint.a < 1.0f ? translucentEntries : entries; + const auto& gpuModel = upload(model); + glm::vec3 lightSamplePos = + glm::vec3(matrix[3]) + lightsOffset + lightSampleOffset; + for (size_t i = 0; i < model->meshes.size(); i++) { + const auto& mesh = model->meshes[i]; + if (mesh.vertices.empty()) { + continue; + } + const auto& region = getTexture(mesh.texture, varTextures); + const auto& uv = region.region; + queue.push_back(DrawEntry { + region.texture ? region.texture : blank.get(), + gpuModel.meshes[i].mesh.get(), + lightSamplePos, + mesh.shading, + Instance { + matrix, + tint, + glm::vec4(1, 1, 1, 0), + glm::vec4(uv.u1, uv.v1, uv.getWidth(), uv.getHeight()), + glm::vec4(mesh.shading ? 1.0f : 0.0f, 0, 0, 0)}}); + } +} + +void ModelBatch::resetOrder(size_t count) { + order.resize(count); + for (size_t i = 0; i < count; i++) { + order[i] = i; + } +} + +void ModelBatch::render(std::vector& queue) { + if (queue.empty()) { + return; + } + bool backlight = settings.graphics.backlight.get(); + + instances.resize(queue.size()); + for (size_t i = 0; i < order.size(); i++) { + auto& entry = queue[order[i]]; + if (entry.shading) { + entry.instance.light = + MainBatch::sampleLight(entry.lightSamplePos, chunks, backlight); + } + instances[i] = entry.instance; + } + + instanceBuffer->reload(instances.data(), instances.size()); + + const Texture* boundTexture = nullptr; + size_t start = 0; + for (size_t i = 1; i <= order.size(); i++) { + if (i < order.size()) { + const auto& prev = queue[order[i - 1]]; + const auto& next = queue[order[i]]; + if (prev.texture == next.texture && prev.mesh == next.mesh) { + continue; + } + } + const auto& entry = queue[order[start]]; + if (entry.texture != boundTexture) { + boundTexture = entry.texture; + boundTexture->bind(); + } + entry.mesh->drawInstanced(*instanceBuffer, start, i - start); + start = i; + } + queue.clear(); +} + +void ModelBatch::finishFrame() { + frame++; + textures.clear(); + texturesByName.clear(); + if (frame % COLLECT_EVERY == 0) { + collectUnused(); } } void ModelBatch::render() { - std::sort(entries.begin(), entries.end(), - [](const DrawEntry& a, const DrawEntry& b) { - return a.mesh->texture < b.mesh->texture; + renderOpaque(); + resetOrder(translucentEntries.size()); + render(translucentEntries); + finishFrame(); +} + +void ModelBatch::renderOpaque() { + resetOrder(entries.size()); + std::sort(order.begin(), order.end(), [this](size_t a, size_t b) { + const auto& ea = entries[a]; + const auto& eb = entries[b]; + if (ea.texture != eb.texture) { + return ea.texture < eb.texture; } - ); - bool backlight = settings.graphics.backlight.get(); - for (auto& entry : entries) { - localLightsOffset = entry.lightSampleOffset; - draw( - *entry.mesh, - entry.matrix, - entry.rotation, - entry.tint, - entry.varTextures, - backlight - ); - localLightsOffset = {}; + return ea.mesh < eb.mesh; + }); + render(entries); +} + +void ModelBatch::renderTranslucent(const glm::vec3& cameraPosition) { + distances.resize(translucentEntries.size()); + for (size_t i = 0; i < translucentEntries.size(); i++) { + glm::vec3 delta = + glm::vec3(translucentEntries[i].instance.matrix[3]) - cameraPosition; + distances[i] = glm::dot(delta, delta); } - batch->flush(); - entries.clear(); + resetOrder(translucentEntries.size()); + std::stable_sort(order.begin(), order.end(), [this](size_t a, size_t b) { + return distances[a] > distances[b]; + }); + render(translucentEntries); + finishFrame(); } void ModelBatch::setLightsOffset(const glm::vec3& offset) { lightsOffset = offset; } - -void ModelBatch::setTexture(const std::string& name, - const TextureNamesMap* varTextures) { - if (varTextures && !name.empty() && name.at(0) == '$') { - const auto& found = varTextures->find(name); - if (found == varTextures->end()) { - return batch->setTexture(nullptr); - } else { - return setTexture(found->second, varTextures); - } - } - auto region = util::get_texture_region(assets, name, "blocks:notfound"); - batch->setTexture(region.texture, region.region); -} diff --git a/src/graphics/render/ModelBatch.hpp b/src/graphics/render/ModelBatch.hpp index 5d43024d5..d75131c43 100644 --- a/src/graphics/render/ModelBatch.hpp +++ b/src/graphics/render/ModelBatch.hpp @@ -6,12 +6,17 @@ #include #include -template class Mesh; +#include "assets/assets_util.hpp" +#include "graphics/core/MeshData.hpp" + +template +class Mesh; +template +class InstanceBuffer; class Texture; class Chunks; class Assets; struct EngineSettings; -class MainBatch; namespace model { struct Mesh; @@ -34,11 +39,17 @@ public: const glm::mat4& matrix, const glm::vec4& tint, const glm::vec3& lightSampleOffset, - const model::Model* model, - const TextureNamesMap* varTextures + const std::shared_ptr& model, + const TextureNamesMap* varTextures, + bool translucent = false ); + void render(); + void renderOpaque(); + + void renderTranslucent(const glm::vec3& cameraPosition); + void setLightsOffset(const glm::vec3& offset); private: const Assets& assets; @@ -46,31 +57,77 @@ private: const EngineSettings& settings; glm::vec3 lightsOffset {}; - glm::vec3 localLightsOffset {}; - static inline glm::vec3 SUN_VECTOR {0.411934f, 0.863868f, -0.279161f}; + struct Vertex { + glm::vec3 coord; + glm::vec2 uv; + glm::vec3 normal; - std::unique_ptr batch; + static constexpr VertexAttribute ATTRIBUTES[] = { + {VertexAttribute::Type::FLOAT, false, 3}, + {VertexAttribute::Type::FLOAT, false, 2}, + {VertexAttribute::Type::FLOAT, false, 3}, + {{}, 0}}; + }; - void draw( - const model::Mesh& mesh, - const glm::mat4& matrix, - const glm::mat3& rotation, - const glm::vec4& tint, - const TextureNamesMap* varTextures, - bool backlight - ); + struct Instance { + glm::mat4 matrix; + glm::vec4 tint; + glm::vec4 light; + glm::vec4 uvRegion; + glm::vec4 params; - void setTexture(const std::string& name, - const TextureNamesMap* varTextures); + static constexpr VertexAttribute ATTRIBUTES[] = { + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {{}, 0}}; + }; + + struct GpuMesh { + std::unique_ptr> mesh; + size_t vertexCount = 0; + }; + + struct GpuModel { + std::weak_ptr model; + std::vector meshes; + uint64_t lastUsed = 0; + }; struct DrawEntry { - glm::mat4 matrix; - glm::mat3 rotation; - glm::vec4 tint; - glm::vec3 lightSampleOffset; - const model::Mesh* mesh; - const TextureNamesMap* varTextures; + const Texture* texture; + const Mesh* mesh; + glm::vec3 lightSamplePos; + bool shading; + Instance instance; }; + + std::unordered_map models; + std::unordered_map textures; + std::unordered_map texturesByName; std::vector entries; + std::vector translucentEntries; + std::vector order; + std::vector distances; + std::vector instances; + + std::unique_ptr> instanceBuffer; + std::unique_ptr blank; + uint64_t frame = 0; + + GpuModel& upload(const std::shared_ptr& model); + void collectUnused(); + void resetOrder(size_t count); + void render(std::vector& queue); + void finishFrame(); + + const util::TextureRegion& getTexture( + const std::string& name, const TextureNamesMap* varTextures + ); }; diff --git a/src/graphics/render/ModelsGenerator.cpp b/src/graphics/render/ModelsGenerator.cpp index d69987d28..b1848e238 100644 --- a/src/graphics/render/ModelsGenerator.cpp +++ b/src/graphics/render/ModelsGenerator.cpp @@ -187,6 +187,7 @@ model::Model ModelsGenerator::fromCustom( mesh.vertices.push_back({v2, glm::vec2(reg.u2, reg.v2), norm}); mesh.vertices.push_back({v3, glm::vec2(reg.u1, reg.v2), norm}); } + model.calcBounds(); return model; } @@ -213,7 +214,7 @@ model::Model ModelsGenerator::generate( mesh.shading = !blockDef.shadeless; switch (blockModel.type) { case BlockModelType::AABB: { - glm::vec3 size = blockDef.hitboxes.at(0).size(); + glm::vec3 size = variant.hitboxes.at(0).size(); float m = glm::max(size.x, glm::max(size.y, size.z)); m = glm::min(1.0f, m); mesh.scale(size / m); diff --git a/src/graphics/render/WorldRenderer.cpp b/src/graphics/render/WorldRenderer.cpp index 11e0fd6d6..54d5b3b2b 100644 --- a/src/graphics/render/WorldRenderer.cpp +++ b/src/graphics/render/WorldRenderer.cpp @@ -6,6 +6,7 @@ #include "CloudsRenderer.hpp" #include "DebugLinesRenderer.hpp" #include "Emitter.hpp" +#include "EntitiesRenderer.hpp" #include "HandsRenderer.hpp" #include "ModelBatch.hpp" #include "NamedSkeletons.hpp" @@ -35,6 +36,7 @@ #include "graphics/core/Shadows.hpp" #include "graphics/core/Cubemap.hpp" #include "graphics/core/Texture.hpp" +#include "graphics/core/TranslucentLayers.hpp" #include "items/Inventory.hpp" #include "items/ItemDef.hpp" #include "items/ItemStack.hpp" @@ -47,6 +49,7 @@ #include "voxels/Block.hpp" #include "voxels/Chunk.hpp" #include "voxels/Chunks.hpp" +#include "voxels/blocks_agent.hpp" #include "voxels/Pathfinding.hpp" #include "window/Window.hpp" #include "world/Level.hpp" @@ -66,6 +69,31 @@ inline constexpr size_t MODEL_BATCH_CAPACITY = 20'000; static debug::Logger logger("world-renderer"); +namespace translucent { + enum Layer : size_t { + BLOCKS, + ENTITIES, + WEATHER, + COUNT + }; +} + +struct EntityShaderPass { + float alphaThreshold; + bool opaque; + bool forward; + bool forwardLight; + float opacity; +}; + +static void setup_entity_pass(Shader& shader, const EntityShaderPass& pass) { + shader.uniform1f("u_alphaThreshold", pass.alphaThreshold); + shader.uniform1i("u_opaque", pass.opaque); + shader.uniform1i("u_forward", pass.forward); + shader.uniform1i("u_forwardLight", pass.forwardLight); + shader.uniform1f("u_opacity", pass.opacity); +} + bool WorldRenderer::showChunkBorders = false; bool WorldRenderer::showEntitiesDebug = false; @@ -134,6 +162,7 @@ WorldRenderer::WorldRenderer( shadowMapping = std::make_unique(level); debugLines = std::make_unique(level); cloudsRenderer = std::make_unique(); + entitiesRenderer = std::make_unique(assets, *level.entities); keepAlive(observe_setting(settings.graphics.enableFog, dirtySettings)); keepAlive(observe_setting(settings.graphics.advancedRender, dirtySettings)); @@ -147,6 +176,7 @@ void WorldRenderer::refreshSettings() { Shader* affectedShaders[] { &assets.require("main"), &assets.require("entity"), + &assets.require("model"), &assets.require("clouds"), &assets.require("translucent"), &assets.require("deferred_lighting").getShader(), @@ -246,17 +276,19 @@ void WorldRenderer::renderOpaque( frustumCulling->update(camera.getProjView()); } - entityShader.uniform1i("u_alphaClip", true); - entityShader.uniform1i("u_dithering", 1); - entityShader.uniform1f("u_opacity", 1.0f); - level.entities->render( - assets, + setup_entity_pass(entityShader, {0.5f, true, false, false, 1.0f}); + + auto& modelShader = assets.require("model"); + setupWorldShader(modelShader, camera, settings, fogFactor); + setup_entity_pass(modelShader, {0.5f, true, false, false, 1.0f}); + entitiesRenderer->render( *modelBatch, culling ? frustumCulling.get() : nullptr, player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0 ); - modelBatch->render(); + modelBatch->renderOpaque(); + entityShader.use(); particles->render(camera); auto& mainShader = assets.require("main"); @@ -292,9 +324,9 @@ void WorldRenderer::renderBlockSelection() { const glm::vec3 point = selection.hitPosition; const glm::vec3 norm = selection.normal; - const std::vector& hitboxes = - block.rotatable ? block.rt.hitboxes[selection.vox.state.rotation] - : block.hitboxes; + const auto& hitboxes = block.getHitboxes( + blocks_agent::hitbox_state(*player.chunks, pos, selection.vox.state) + ); lineBatch->lineWidth(2.0f); for (auto& hitbox : hitboxes) { @@ -323,7 +355,7 @@ void WorldRenderer::renderInWorldLines( if (debug && showEntitiesDebug) { auto ctx = pctx.sub(lineBatch.get()); bool culling = engine.getSettings().graphics.frustumCulling.get(); - level.entities->renderDebug( + entitiesRenderer->renderDebug( *lineBatch, culling ? frustumCulling.get() : nullptr, ctx, player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0 ); @@ -335,7 +367,7 @@ void WorldRenderer::updateEntitiesCulling(const Camera& camera) { if (culling) { frustumCulling->update(camera.getProjView()); } - level.entities->updateCulling( + entitiesRenderer->updateCulling( culling ? frustumCulling.get() : nullptr, player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0 @@ -373,21 +405,7 @@ void WorldRenderer::renderFrameClassic( renderDebugLines(ctx, camera); } - DrawContext wctx = ctx.sub(); - wctx.useTexture(advanced_pipeline::TARGET_SKYBOX, skybox->getCubemap()); - wctx.useTexture(advanced_pipeline::TARGET_COLOR, nullptr); - // Translucent blocks - { - const auto& settings = engine.getSettings(); - auto& translucentShader = assets.require("translucent"); - auto sctx = wctx.sub(); - sctx.setCullFace(true); - translucentShader.use(); - setupWorldShader(translucentShader, camera, settings, calcFogFactor()); - chunksRenderer->drawSortedMeshes(camera, translucentShader); - } - - renderWeatherEffects(camera); + renderTranslucency(ctx, camera, postProcessing); glBindFramebuffer(GL_FRAMEBUFFER, 0); } @@ -418,6 +436,7 @@ void WorldRenderer::renderFrameAdvanced( ctx.useTexture(advanced_pipeline::TARGET_COLOR, nullptr); postProcessing.bindDepthBuffer(); + ctx.setFramebuffer(postProcessing.getFramebuffer()); skybox->draw( level.environment, ctx, camera, worldInfo.daytime, weather.clouds() ); @@ -426,21 +445,7 @@ void WorldRenderer::renderFrameAdvanced( renderDebugLines(ctx, camera); } - DrawContext wctx = ctx.sub(); - wctx.useTexture(advanced_pipeline::TARGET_SKYBOX, skybox->getCubemap()); - wctx.useTexture(advanced_pipeline::TARGET_COLOR, nullptr); - // Translucent blocks - { - const auto& settings = engine.getSettings(); - auto& translucentShader = assets.require("translucent"); - auto sctx = wctx.sub(); - sctx.setCullFace(true); - translucentShader.use(); - setupWorldShader(translucentShader, camera, settings, fogFactor); - chunksRenderer->drawSortedMeshes(camera, translucentShader); - } - - renderWeatherEffects(camera); + renderTranslucency(ctx, camera, postProcessing); glBindFramebuffer(GL_FRAMEBUFFER, 0); } @@ -528,10 +533,10 @@ void WorldRenderer::renderWeatherEffects(Camera& camera) { float zero = weather->fall.minOpacity; float one = weather->fall.maxOpacity; float t = (weather->intensity * (one - zero)) * maxIntensity + zero; - entityShader.uniform1i("u_alphaClip", weather->fall.opaque); - entityShader.uniform1i("u_dithering", 0); - entityShader.uniform1f( - "u_opacity", weather->fall.opaque ? t * t : t + bool opaque = weather->fall.opaque; + setup_entity_pass( + entityShader, + {opaque ? 0.5f : 0.15f, false, true, false, opaque ? t * t : t} ); if (weather->intensity > 1.e-3f && !weather->fall.texture.empty()) { precipitation->render(camera, *weather); @@ -539,6 +544,67 @@ void WorldRenderer::renderWeatherEffects(Camera& camera) { } } +void WorldRenderer::renderTranslucency( + const DrawContext& pctx, + Camera& camera, + PostProcessing& postProcessing +) { + const auto& settings = engine.getSettings(); + float fogFactor = calcFogFactor(); + auto& frame = *postProcessing.getFramebuffer(); + const auto& vp = pctx.getViewport(); + + if (translucentLayers == nullptr) { + translucentLayers = std::make_unique( + translucent::COUNT, vp.x, vp.y + ); + } else { + translucentLayers->resize(vp.x, vp.y); + } + translucentLayers->prepare(frame.getFBO()); + + DrawContext ctx = pctx.sub(); + ctx.setFramebuffer(&frame); + ctx.setDepthTest(true); + ctx.setDepthMask(true); + ctx.setBlendMode(BlendMode::coverage); + ctx.useTexture(advanced_pipeline::TARGET_SKYBOX, skybox->getCubemap()); + ctx.useTexture(advanced_pipeline::TARGET_COLOR, nullptr); + + { + auto lctx = ctx.sub(); + lctx.setFramebuffer(&translucentLayers->getLayer(translucent::BLOCKS)); + lctx.setCullFace(true); + auto& shader = assets.require("translucent"); + shader.use(); + setupWorldShader(shader, camera, settings, fogFactor); + chunksRenderer->drawSortedMeshes(camera, shader); + } + { + auto lctx = ctx.sub(); + lctx.setFramebuffer(&translucentLayers->getLayer(translucent::ENTITIES)); + lctx.setCullFace(true); + auto& shader = assets.require("model"); + setupWorldShader(shader, camera, settings, fogFactor); + setup_entity_pass(shader, {0.002f, false, true, true, 1.0f}); + modelBatch->renderTranslucent(camera.position); + } + { + auto lctx = ctx.sub(); + lctx.setFramebuffer(&translucentLayers->getLayer(translucent::WEATHER)); + renderWeatherEffects(camera); + } + { + auto cctx = ctx.sub(); + cctx.setDepthTest(false); + cctx.setDepthMask(false); + cctx.setBlendMode(BlendMode::premultiplied); + translucentLayers->compose( + assets.require("translucent_composite") + ); + } +} + void WorldRenderer::renderDebugLines(const DrawContext& ctx, Camera& camera) { auto& linesShader = assets.require("lines"); linesShader.use(); @@ -550,7 +616,7 @@ void WorldRenderer::renderDebugLines(const DrawContext& ctx, Camera& camera) { } void WorldRenderer::renderHandsPass(const DrawContext& pctx, Camera& camera) { - auto& entityShader = assets.require("entity"); + auto& modelShader = assets.require("model"); DrawContext ctx = pctx.sub(); ctx.setDepthTest(true); @@ -565,7 +631,8 @@ void WorldRenderer::renderHandsPass(const DrawContext& pctx, Camera& camera) { hudcam.setFov(0.9f); hudcam.position = {}; - setupWorldShader(entityShader, hudcam, engine.getSettings(), 0.0f); + setupWorldShader(modelShader, hudcam, engine.getSettings(), 0.0f); + setup_entity_pass(modelShader, {0.15f, false, false, false, 1.0f}); hands->render(camera); } diff --git a/src/graphics/render/WorldRenderer.hpp b/src/graphics/render/WorldRenderer.hpp index 243fe8b94..c302a4819 100644 --- a/src/graphics/render/WorldRenderer.hpp +++ b/src/graphics/render/WorldRenderer.hpp @@ -18,6 +18,7 @@ class ChunksRenderer; class DebugLinesRenderer; class DrawContext; class Engine; +class EntitiesRenderer; class Frustum; class HandsRenderer; class Level; @@ -33,6 +34,7 @@ class Shader; class Shadows; class Skybox; class TextsRenderer; +class TranslucentLayers; class CloudsRenderer; struct EngineSettings; struct Weather; @@ -79,6 +81,8 @@ private: std::unique_ptr debugLines; std::unique_ptr precipitation; std::unique_ptr cloudsRenderer; + std::unique_ptr entitiesRenderer; + std::unique_ptr translucentLayers; float timer = 0.0f; bool debug = false; @@ -125,6 +129,12 @@ private: void renderWeatherEffects(Camera& camera); + void renderTranslucency( + const DrawContext& context, + Camera& camera, + PostProcessing& postProcessing + ); + void renderHandsPass(const DrawContext& pctx, Camera& camera); void renderDebugLines(const DrawContext& context, Camera& camera); diff --git a/src/graphics/ui/elements/Container.cpp b/src/graphics/ui/elements/Container.cpp index a9ab71e9d..727d46b07 100644 --- a/src/graphics/ui/elements/Container.cpp +++ b/src/graphics/ui/elements/Container.cpp @@ -92,10 +92,18 @@ void Container::act(float delta) { // TODO: make it interval-based gui.getWindow().setShouldRefresh(); } - for (IntervalEvent& event : intervalEvents) { - event.timer += delta; - if (event.timer > event.interval) { - event.callback(); + for (size_t i = 0; i < intervalEvents.size(); i++) { + if (intervalEvents[i].repeat == 0) { + continue; + } + intervalEvents[i].timer += delta; + if (intervalEvents[i].timer > intervalEvents[i].interval) { + auto callback = intervalEvents[i].callback; + callback(); + IntervalEvent& event = intervalEvents[i]; + if (event.repeat == 0) { + continue; + } event.timer = fmod(event.timer, event.interval); if (event.repeat > 0) { event.repeat--; @@ -232,8 +240,19 @@ void Container::clear() { refresh(); } -void Container::listenInterval(float interval, OnTimeOut callback, int repeat) { - intervalEvents.push_back({std::move(callback), interval, 0.0f, repeat}); +int Container::listenInterval(float interval, OnTimeOut callback, int repeat) { + int id = nextIntervalId++; + intervalEvents.push_back({id, std::move(callback), interval, 0.0f, repeat}); + return id; +} + +void Container::cancelInterval(int id) { + for (auto& event : intervalEvents) { + if (event.id == id) { + event.repeat = 0; + return; + } + } } void Container::setSize(const glm::vec2& size) { diff --git a/src/graphics/ui/elements/Container.hpp b/src/graphics/ui/elements/Container.hpp index b5664c139..7febbc324 100644 --- a/src/graphics/ui/elements/Container.hpp +++ b/src/graphics/ui/elements/Container.hpp @@ -13,6 +13,7 @@ namespace gui { protected: std::vector> nodes; std::vector intervalEvents; + int nextIntervalId = 1; int scrollY = 0; int scrollX = 0; int scrollStep = 40; @@ -41,7 +42,8 @@ namespace gui { virtual void remove(const std::string& id); virtual void scrolled(int value) override; virtual void setScrollable(bool flag); - void listenInterval(float interval, OnTimeOut callback, int repeat=-1); + int listenInterval(float interval, OnTimeOut callback, int repeat=-1); + void cancelInterval(int id); virtual glm::vec2 getContentOffset() const override { return glm::vec2(scrollX, scrollY); }; diff --git a/src/graphics/ui/elements/commons.hpp b/src/graphics/ui/elements/commons.hpp index 8012abeb8..80a539d64 100644 --- a/src/graphics/ui/elements/commons.hpp +++ b/src/graphics/ui/elements/commons.hpp @@ -8,6 +8,7 @@ namespace gui { using OnTimeOut = std::function; struct IntervalEvent { + int id; OnTimeOut callback; float interval; float timer; diff --git a/src/graphics/ui/gui_util.cpp b/src/graphics/ui/gui_util.cpp index 13364b0ed..86c28864c 100644 --- a/src/graphics/ui/gui_util.cpp +++ b/src/graphics/ui/gui_util.cpp @@ -125,6 +125,7 @@ void guiutil::confirm( label->setSize(glm::vec2(600, 50)); label->setMultiline(true); label->setTextWrapping(true); + label->setMarkup("md"); panel->add(label); auto subpanel = std::make_shared(gui, glm::vec2(600, 53)); diff --git a/src/interfaces/SystemProcess.hpp b/src/interfaces/SystemProcess.hpp new file mode 100644 index 000000000..dffb2634b --- /dev/null +++ b/src/interfaces/SystemProcess.hpp @@ -0,0 +1,11 @@ +#pragma once + +#include "interfaces/Process.hpp" + +class SystemProcess : public Process { +public: + virtual ~SystemProcess() override = default; + + virtual int getStdinDescriptor() const = 0; + virtual int getStdoutDescriptor() const = 0; +}; diff --git a/src/io/devices/MemoryDevice.cpp b/src/io/devices/MemoryDevice.cpp index 8cf440c4e..8b0016cdf 100644 --- a/src/io/devices/MemoryDevice.cpp +++ b/src/io/devices/MemoryDevice.cpp @@ -14,8 +14,13 @@ std::filesystem::path io::MemoryDevice::resolve(std::string_view path) { std::unique_ptr io::MemoryDevice::write(std::string_view path) { std::string filePath = std::string(path); + + auto memoryStream = std::make_unique(); + memoryStream->set_sync_callback([this, filePath](std::string_view data) { + createFile(std::move(filePath), util::Buffer(data.data(), data.size())); + }); return std::make_unique( - std::make_unique(), + std::move(memoryStream), [this, filePath](auto ostream) { auto& memoryStream = dynamic_cast(*ostream); createFile(std::move(filePath), memoryStream.release()); diff --git a/src/io/fd_istream.hpp b/src/io/fd_istream.hpp new file mode 100644 index 000000000..74af1e6b7 --- /dev/null +++ b/src/io/fd_istream.hpp @@ -0,0 +1,132 @@ +#pragma once + +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#endif + +#ifndef _WIN32 +#include +#endif + +class fd_istreambuf final : public std::streambuf { + static constexpr size_t BUFFER_SIZE = 4096; +public: +#ifdef _WIN32 + explicit fd_istreambuf(HANDLE handle) + : handle(handle) { + setg(buffer.data(), buffer.data(), buffer.data()); + } + + ~fd_istreambuf() override { + if (handle != nullptr && handle != INVALID_HANDLE_VALUE) { + CloseHandle(handle); + handle = INVALID_HANDLE_VALUE; + } + } + +protected: + int_type underflow() override { + if (handle == nullptr || handle == INVALID_HANDLE_VALUE) { + return traits_type::eof(); + } + if (gptr() != egptr()) { + return traits_type::to_int_type(*gptr()); + } + + std::array chunk {}; + DWORD readCount = 0; + if (!ReadFile( + handle, + chunk.data(), + static_cast(chunk.size()), + &readCount, + nullptr + ) || + readCount == 0) { + return traits_type::eof(); + } + + buffer.assign(chunk.begin(), chunk.begin() + readCount); + setg(buffer.data(), buffer.data(), buffer.data() + buffer.size()); + return traits_type::to_int_type(*gptr()); + } + + pos_type seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode) + override { + return pos_type(off_type(-1)); + } + + pos_type seekpos(pos_type, std::ios_base::openmode) override { + return pos_type(off_type(-1)); + } +private: + HANDLE handle; + std::vector buffer; +#else + explicit fd_istreambuf(int fd) + : fd(fd) { + setg(buffer.data(), buffer.data(), buffer.data()); + } + + ~fd_istreambuf() override { + if (fd >= 0) { + ::close(fd); + fd = -1; + } + } + +protected: + int_type underflow() override { + if (fd < 0) { + return traits_type::eof(); + } + if (gptr() != egptr()) { + return traits_type::to_int_type(*gptr()); + } + + buffer.resize(BUFFER_SIZE); + const auto count = ::read(fd, buffer.data(), buffer.size()); + if (count <= 0) { + return traits_type::eof(); + } + buffer.resize(static_cast(count)); + setg(buffer.data(), buffer.data(), buffer.data() + buffer.size()); + return traits_type::to_int_type(*gptr()); + } + + pos_type seekoff( + off_type, + std::ios_base::seekdir, + std::ios_base::openmode + ) override { + return pos_type(off_type(-1)); + } + + pos_type seekpos(pos_type, std::ios_base::openmode) override { + return pos_type(off_type(-1)); + } + +private: + int fd; + std::vector buffer; +#endif +}; + +class fd_istream final : public std::istream { +public: +#ifdef _WIN32 + explicit fd_istream(HANDLE handle) + : std::istream(&buf), buf(handle) {} +#else + explicit fd_istream(int fd) + : std::istream(&buf), buf(fd) {} +#endif + +private: + fd_istreambuf buf; +}; diff --git a/src/io/fd_ostream.hpp b/src/io/fd_ostream.hpp new file mode 100644 index 000000000..b5131a54d --- /dev/null +++ b/src/io/fd_ostream.hpp @@ -0,0 +1,158 @@ +#pragma once + +#include +#include +#include + +#ifdef _WIN32 +#include +#endif + +#ifndef _WIN32 +#include +#endif + + +class fd_ostreambuf final : public std::streambuf { + static constexpr size_t BUFFER_SIZE = 4096; +public: +#ifdef _WIN32 + explicit fd_ostreambuf(HANDLE handle) : handle(handle) { + setp(buffer.data(), buffer.data() + buffer.size()); + } + + ~fd_ostreambuf() override { + fd_ostreambuf::sync(); + if (handle != nullptr && handle != INVALID_HANDLE_VALUE) { + CloseHandle(handle); + handle = INVALID_HANDLE_VALUE; + } + } +protected: + int_type overflow(int_type ch) override { + if (ch == traits_type::eof()) { + return traits_type::not_eof(ch); + } + if (pptr() == epptr()) { + if (sync() != 0) { + return traits_type::eof(); + } + } + *pptr() = traits_type::to_char_type(ch); + pbump(1); + return ch; + } + + int sync() override { + if (handle == nullptr || handle == INVALID_HANDLE_VALUE) { + return -1; + } + + const auto size = static_cast(pptr() - pbase()); + if (size == 0) { + return 0; + } + + DWORD written = 0; + if (!WriteFile( + handle, pbase(), static_cast(size), &written, nullptr + )) { + return -1; + } + + setp(buffer.data(), buffer.data() + buffer.size()); + return 0; + } + + pos_type seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode) + override { + return pos_type(off_type(-1)); + } + + pos_type seekpos(pos_type, std::ios_base::openmode) override { + return pos_type(off_type(-1)); + } +private: + HANDLE handle; + std::array buffer {}; +#else + explicit fd_ostreambuf(int fd) : fd(fd) { + setp(buffer.data(), buffer.data() + buffer.size()); + } + + ~fd_ostreambuf() override { + fd_ostreambuf::sync(); + if (fd >= 0) { + ::close(fd); + fd = -1; + } + } +protected: + int_type overflow(int_type ch) override { + if (ch == traits_type::eof()) { + return traits_type::not_eof(ch); + } + if (pptr() == epptr()) { + if (sync() != 0) { + return traits_type::eof(); + } + } + *pptr() = traits_type::to_char_type(ch); + pbump(1); + return ch; + } + + int sync() override { + if (fd < 0) { + return -1; + } + + const auto size = static_cast(pptr() - pbase()); + if (size == 0) { + return 0; + } + + char* ptr = pbase(); + size_t remaining = size; + while (remaining > 0) { + const auto written = ::write(fd, ptr, remaining); + if (written < 0) { + if (errno == EINTR) { + continue; + } + return -1; + } + ptr += written; + remaining -= static_cast(written); + } + + setp(buffer.data(), buffer.data() + buffer.size()); + return 0; + } + + pos_type seekoff(off_type, std::ios_base::seekdir, std::ios_base::openmode) + override { + return pos_type(off_type(-1)); + } + + pos_type seekpos(pos_type, std::ios_base::openmode) override { + return pos_type(off_type(-1)); + } +private: + int fd; + std::array buffer {}; +#endif +}; + +class fd_ostream final : public std::ostream { +public: +#ifdef _WIN32 + explicit fd_ostream(HANDLE handle) : std::ostream(&buf), buf(handle) { + } +#else + explicit fd_ostream(int fd) : std::ostream(&buf), buf(fd) { + } +#endif +private: + fd_ostreambuf buf; +}; diff --git a/src/io/memory_ostream.hpp b/src/io/memory_ostream.hpp index 329277aff..a46043ba8 100644 --- a/src/io/memory_ostream.hpp +++ b/src/io/memory_ostream.hpp @@ -3,6 +3,9 @@ #include #include #include +#include +#include +#include #include #include @@ -13,94 +16,111 @@ public: explicit memory_buffer(size_t initial_size = 64) : buffer(std::make_unique(initial_size)), capacity(initial_size) { - setp(buffer.get(), buffer.get() + initial_size); + setp(buffer.get(), buffer.get() + capacity); } std::string_view view() const { - return std::string_view(pbase(), pptr() - pbase()); + return std::string_view(pbase(), size()); } util::Buffer release() { - return {std::move(buffer), size()}; + size_t n = size(); + return {std::move(buffer), n}; } size_t size() const { - return pptr() - pbase(); + return std::max(length, position()); + } + + void set_sync_callback(std::function callback) { + on_sync = std::move(callback); } protected: int_type overflow(int_type c) override { if (c == traits_type::eof()) return traits_type::eof(); - const size_t data_size = pptr() - pbase(); - const size_t new_capacity = std::max(capacity * 2, data_size + 1); - auto new_buffer = std::make_unique(new_capacity); - - std::memcpy(new_buffer.get(), pbase(), data_size); - - buffer = std::move(new_buffer); - capacity = new_capacity; - - setp(buffer.get(), buffer.get() + new_capacity); - pbump(data_size); - + reserve(position() + 1); *pptr() = traits_type::to_char_type(c); pbump(1); - return c; } pos_type seekoff( off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode mode = std::ios_base::out + std::ios_base::seekdir dir, + std::ios_base::openmode which ) 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())); + if (!(which & std::ios_base::out)) { + return pos_type(off_type(-1)); } - return pos_type(off_type(-1)); + length = size(); + + off_type base; + switch (dir) { + case std::ios_base::beg: base = 0; break; + case std::ios_base::cur: base = position(); break; + case std::ios_base::end: base = length; break; + default: return pos_type(off_type(-1)); + } + + off_type target = base + off; + if (target < 0 || target > static_cast(length)) { + return pos_type(off_type(-1)); + } + set_position(target); + return pos_type(target); } - std::streamsize xsputn(const char* s, std::streamsize count) override { - const std::streamsize avail = epptr() - pptr(); - - if (avail >= count) { - std::memcpy(pptr(), s, count); - pbump(count); - return count; - } - - std::streamsize written = 0; - if (avail > 0) { - std::memcpy(pptr(), s, avail); - written += avail; - s += avail; - count -= avail; - pbump(avail); - } - - const size_t data_size = pptr() - pbase(); - const size_t required_capacity = data_size + count; - const size_t new_capacity = std::max(capacity * 2, required_capacity); - auto new_buffer = std::make_unique(new_capacity); - - std::memcpy(new_buffer.get(), pbase(), data_size); - std::memcpy(new_buffer.get() + data_size, s, count); - - buffer = std::move(new_buffer); - capacity = new_capacity; - - setp(buffer.get(), buffer.get() + new_capacity); - pbump(data_size + count); - written += count; - - return written; + pos_type seekpos(pos_type pos, std::ios_base::openmode which) override { + return seekoff(off_type(pos), std::ios_base::beg, which); } private: std::unique_ptr buffer; size_t capacity; + size_t length = 0; + + size_t position() const { + return pptr() - pbase(); + } + + void advance(size_t n) { + while (n > 0) { + int step = static_cast(std::min(n, INT_MAX)); + pbump(step); + n -= step; + } + } + + void set_position(size_t pos) { + setp(buffer.get(), buffer.get() + capacity); + advance(pos); + } + + void reserve(size_t required) { + if (required <= capacity) { + return; + } + size_t pos = position(); + length = size(); + + size_t new_capacity = std::max(capacity * 2, required); + auto new_buffer = std::make_unique(new_capacity); + std::memcpy(new_buffer.get(), buffer.get(), length); + + buffer = std::move(new_buffer); + capacity = new_capacity; + set_position(pos); + } + + int sync() override { + if (on_sync) { + on_sync(view()); + } + return 0; + } + + std::function on_sync; }; class memory_ostream : public std::ostream { @@ -115,6 +135,10 @@ public: util::Buffer release() { return buffer.release(); } + + void set_sync_callback(std::function callback) { + buffer.set_sync_callback(std::move(callback)); + } private: memory_buffer buffer; }; diff --git a/src/items/ItemDef.cpp b/src/items/ItemDef.cpp index bff25e7af..d180c1fc0 100644 --- a/src/items/ItemDef.cpp +++ b/src/items/ItemDef.cpp @@ -3,8 +3,7 @@ #include "util/stringutil.hpp" ItemDef::ItemDef(const std::string& name) - : name(name), - caption(util::id_to_caption(name)), + : name(name), scriptName(name.substr(name.find(':') + 1)) { } void ItemDef::cloneTo(ItemDef& dst) { diff --git a/src/logic/BlocksController.cpp b/src/logic/BlocksController.cpp index 58594f6ee..73951ff4b 100644 --- a/src/logic/BlocksController.cpp +++ b/src/logic/BlocksController.cpp @@ -69,11 +69,11 @@ void BlocksController::breakBlock( onBlockInteraction( player, glm::ivec3(x, y, z), def, BlockInteraction::destruction ); + scripting::on_block_broken(player, def, glm::ivec3(x, y, z)); blocks_agent::set(chunks, x, y, z, 0, {}); if (lighting) { lighting->onBlockSet(x, y, z, 0); } - scripting::on_block_broken(player, def, glm::ivec3(x, y, z)); if (def.rt.extended) { updateSides(x, y, z , def.size.x, def.size.y, def.size.z); } else { @@ -130,14 +130,26 @@ void BlocksController::updateBlock(int x, int y, int z) { } void BlocksController::update(float delta, uint padding) { - if (int parts = randTickClock.update(delta)) { - for (int i = 0; i < parts; i++) { - randomTick(randTickClock.convertPart(i), randTickClock.getParts(), padding); + auto& worldInfo = level.getWorld().getInfo(); + + if (worldInfo.getLogicFlag("random_ticks", true)) { + if (int parts = randTickClock.update(delta)) { + for (int i = 0; i < parts; i++) { + randomTick( + randTickClock.convertPart(i), + randTickClock.getParts(), + padding + ); + } } } - if (int parts = blocksTickClock.update(delta)) { - for (int i = 0; i < parts; i++) { - onBlocksTick(blocksTickClock.convertPart(i), blocksTickClock.getParts()); + if (worldInfo.getLogicFlag("block_ticks", true)) { + if (int parts = blocksTickClock.update(delta)) { + for (int i = 0; i < parts; i++) { + onBlocksTick( + blocksTickClock.convertPart(i), blocksTickClock.getParts() + ); + } } } if (worldTickClock.update(delta)) { diff --git a/src/logic/EngineController.cpp b/src/logic/EngineController.cpp index 51b32e0c4..4d62f6cec 100644 --- a/src/logic/EngineController.cpp +++ b/src/logic/EngineController.cpp @@ -55,6 +55,32 @@ void EngineController::deleteWorld(const std::string& name) { ); } +void EngineController::deleteWorldContent( + const std::string& name, ContentRemovalRequest request, bool loadWorld +) { + io::path folder = engine.getPaths().getWorldFolderByName(name); + auto deletion = [this, folder, loadWorld, request=std::move(request)]() { + logger.info() << "deleting content from the world"; + WorldFiles worldFiles(folder); + worldFiles.deleteContent(std::move(request)); + if (loadWorld) { + openWorld(folder.name(), true); + } + }; + + if (engine.isHeadless()) { + deletion(); + return; + } + + guiutil::confirm( + engine, + langs::get(L"delete-content-confirm", L"world") + L" (" + + util::str2wstr_utf8(folder.string()) + L")", + deletion + ); +} + std::shared_ptr create_converter( Engine& engine, const std::shared_ptr& worldFiles, @@ -174,20 +200,20 @@ static dv::value create_missing_content_report( } void EngineController::onMissingContent( + const std::string& worldName, const std::shared_ptr& report ) { + auto fullReport = create_missing_content_report(report); + fullReport["world"] = worldName; + if (engine.isHeadless()) { throw std::runtime_error( "missing content: " + - util::quote(json::stringify(create_missing_content_report(report), true, " ")) + util::quote(json::stringify(std::move(fullReport), true, " ")) ); } else { engine.setScreen(std::make_shared(engine)); - menus::show( - engine, - "reports/missing_content", - {create_missing_content_report(report)} - ); + menus::show(engine, "reports/missing_content", {std::move(fullReport)}); } } @@ -234,7 +260,7 @@ void EngineController::openWorld(const std::string& name, bool confirmConvert) { return; } if (report->hasMissingContent()) { - onMissingContent(report); + onMissingContent(name, report); return; } diff --git a/src/logic/EngineController.hpp b/src/logic/EngineController.hpp index a40f3476f..147ba482f 100644 --- a/src/logic/EngineController.hpp +++ b/src/logic/EngineController.hpp @@ -9,12 +9,16 @@ class Engine; class World; class ContentReport; class LevelController; +struct ContentRemovalRequest; class EngineController { Engine& engine; int64_t localPlayer = -1; - void onMissingContent(const std::shared_ptr& report); + void onMissingContent( + const std::string& worldName, + const std::shared_ptr& report + ); public: EngineController(Engine& engine); @@ -27,6 +31,10 @@ public: /// @param name world name void deleteWorld(const std::string& name); + void deleteWorldContent( + const std::string& name, ContentRemovalRequest request, bool loadWorld + ); + void reconfigPacks( LevelController* controller, const std::vector& packsToAdd, diff --git a/src/logic/PlayerController.cpp b/src/logic/PlayerController.cpp index 891c4c086..9d515d533 100644 --- a/src/logic/PlayerController.cpp +++ b/src/logic/PlayerController.cpp @@ -459,7 +459,7 @@ void PlayerController::processRightClick( blockid_t chosenBlock = def.rt.id; if (def.obstacle) { - const auto& hitboxes = def.rt.hitboxes[state.rotation]; + const auto& hitboxes = def.getHitboxes(state); for (const AABB& blockAABB : hitboxes) { if (level.entities->hasBlockingInside(blockAABB.translated(coord) )) { @@ -480,6 +480,11 @@ void PlayerController::processRightClick( } } if (chosenBlock != vox->id && chosenBlock) { + if (!scripting::can_block_be_placed( + &player, def, coord, state.rotation + )) { + return; + } if (!player.isInfiniteItems()) { auto& slot = player.getInventory()->getSlot(player.getChosenSlot()); slot.setCount(slot.getCount() - 1); @@ -493,11 +498,11 @@ void PlayerController::processRightClick( void PlayerController::updateEntityInteraction( entityid_t eid, bool lclick, bool rclick ) { - auto entityOpt = level.entities->get(eid); - if (!entityOpt.has_value()) { + auto entityPtr = level.entities->get(eid); + if (entityPtr == nullptr) { return; } - auto entity = *entityOpt; + const auto& entity = *entityPtr; if (lclick) { scripting::on_attacked(entity, &player, player.getEntity()); } diff --git a/src/logic/scripting/io_descriptors.cpp b/src/logic/scripting/io_descriptors.cpp index ead8566d1..71811141a 100644 --- a/src/logic/scripting/io_descriptors.cpp +++ b/src/logic/scripting/io_descriptors.cpp @@ -19,6 +19,18 @@ namespace { std::unique_ptr out; }; std::vector> descriptors; + + int add_descriptor(StreamDescriptor descriptor) { + for (int i = 0; i < static_cast(descriptors.size()); ++i) { + if (!descriptors[i].has_value()) { + descriptors[i] = std::move(descriptor); + return i; + } + } + + descriptors.emplace_back(std::move(descriptor)); + return static_cast(descriptors.size() - 1); + } } std::istream* io_descriptors::get_input(int id) { @@ -121,6 +133,18 @@ void io_descriptors::close(int id) { ::descriptors[id] = std::nullopt; } +int io_descriptors::add_descriptor(std::unique_ptr stream) { + return add_descriptor(StreamDescriptor { + std::move(stream), nullptr + }); +} + +int io_descriptors::add_descriptor(std::unique_ptr stream) { + return add_descriptor(StreamDescriptor { + nullptr, std::move(stream) + }); +} + int io_descriptors::open_descriptor(const io::path& path, bool write, bool read) { std::unique_ptr in; std::unique_ptr out; @@ -138,15 +162,9 @@ int io_descriptors::open_descriptor(const io::path& path, bool write, bool read) return -1; } - for (int i = 0; i < static_cast(descriptors.size()); ++i) { - if (!descriptors[i].has_value()) { - descriptors[i] = StreamDescriptor{ std::move(in), std::move(out) }; - return i; - } - } - - ::descriptors.emplace_back(StreamDescriptor{ std::move(in), std::move(out) }); - return static_cast(::descriptors.size() - 1); + return add_descriptor(StreamDescriptor{ + std::move(in), std::move(out) + }); } diff --git a/src/logic/scripting/io_descriptors.hpp b/src/logic/scripting/io_descriptors.hpp index 56ed21a7a..c3dd5985d 100644 --- a/src/logic/scripting/io_descriptors.hpp +++ b/src/logic/scripting/io_descriptors.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include "io/fwd.hpp" @@ -22,6 +23,8 @@ namespace scripting::io_descriptors { void close(int id); int open_descriptor(const io::path& path, bool write, bool read); + int add_descriptor(std::unique_ptr stream); + int add_descriptor(std::unique_ptr stream); void close_all_descriptors(); } diff --git a/src/logic/scripting/lua/libs/lib__skeleton.cpp b/src/logic/scripting/lua/libs/lib__skeleton.cpp index b39b3287b..d87a3bb9e 100644 --- a/src/logic/scripting/lua/libs/lib__skeleton.cpp +++ b/src/logic/scripting/lua/libs/lib__skeleton.cpp @@ -62,6 +62,7 @@ static int l_set_model(lua::State* L) { } else { modelOverride = {lua::require_string(L, 3), {}, true}; } + skeleton->boundsDirty = true; } return 0; } @@ -85,6 +86,18 @@ static int l_set_matrix(lua::State* L) { } auto index = index_range_check(*skeleton, lua::tointeger(L, 2)); skeleton->pose.matrices[index] = lua::tomat4(L, 3); + skeleton->boundsDirty = true; + } + return 0; +} + +static int l_get_bone_offset(lua::State* L) { + if (auto skeleton = get_skeleton(L)) { + if (skeleton->config == nullptr) { + return 0; + } + auto index = index_range_check(*skeleton, lua::tointeger(L, 2)); + return lua::pushvec(L, skeleton->config->getBones()[index]->getOffset()); } return 0; } @@ -93,6 +106,7 @@ static int l_reset_pose(lua::State* L) { if (auto skeleton = get_skeleton(L)) { auto& pose = skeleton->pose; std::fill(pose.matrices.begin(), pose.matrices.end(), glm::mat4(1.0f)); + skeleton->boundsDirty = true; } return 0; } @@ -146,6 +160,7 @@ static int l_set_visible(lua::State* L) { } else { skeleton->visible = lua::toboolean(L, 2); } + skeleton->boundsDirty = true; } return 0; } @@ -190,7 +205,9 @@ static int l_is_interpolated(lua::State* L) { static int l_set_interpolated(lua::State* L) { if (auto skeleton = get_skeleton(L)) { - skeleton->interpolation.setEnabled(lua::toboolean(L, 2)); + bool enabled = lua::toboolean(L, 2); + skeleton->interpolation.setEnabled(enabled); + skeleton->rotationInterpolation.setEnabled(enabled); } return 0; } @@ -332,6 +349,7 @@ static int l_apply_track(lua::State* L) { return index > 0 && index <= MAX_TRACK_VALUES ? values[index] : fallback; }; auto& matrices = skeleton->pose.matrices; + skeleton->boundsDirty = true; for (size_t i = 0; i < track.bones.size(); i++) { int index = track.indices[i]; if (index < 0 || static_cast(index) >= matrices.size()) { @@ -372,6 +390,7 @@ const luaL_Reg skeletonlib[] = { {"set_model", lua::wrap}, {"get_matrix", lua::wrap}, {"set_matrix", lua::wrap}, + {"get_bone_offset", lua::wrap}, {"reset_pose", lua::wrap}, {"get_texture", lua::wrap}, {"set_texture", lua::wrap}, diff --git a/src/logic/scripting/lua/libs/lib__transform.cpp b/src/logic/scripting/lua/libs/lib__transform.cpp index 16662daaa..dbe2d8c75 100644 --- a/src/logic/scripting/lua/libs/lib__transform.cpp +++ b/src/logic/scripting/lua/libs/lib__transform.cpp @@ -61,9 +61,11 @@ static int l_get_rot(lua::State* L) { static int l_set_rot(lua::State* L) { if (auto entity = get_entity(L, 1)) { - auto matrix = lua::tomat4(L, 2); + glm::mat3 matrix(lua::tomat4(L, 2)); check_valid(matrix); - entity->getTransform().setRot(matrix); + auto rotation = glm::normalize(glm::quat_cast(matrix)); + entity->getTransform().setRot(glm::mat3_cast(rotation)); + entity->setInterpolatedRotation(rotation); } return 0; } diff --git a/src/logic/scripting/lua/libs/libapp.cpp b/src/logic/scripting/lua/libs/libapp.cpp index 0058fcada..0cb38a808 100644 --- a/src/logic/scripting/lua/libs/libapp.cpp +++ b/src/logic/scripting/lua/libs/libapp.cpp @@ -19,13 +19,16 @@ #include "util/stringutil.hpp" #include "window/Window.hpp" #include "world/Level.hpp" +#include "world/files/WorldFiles.hpp" #include +#include using namespace scripting; namespace { - static std::array, MAX_SUBPROCESSES> processes; + static std::unordered_map> processes; + static int next_process_id = 1; } /// @brief Check if content is loaded @@ -325,11 +328,45 @@ static int l_delete_world(lua::State* L) { return 0; } +static ContentRemovalRequest parse_content_removal_request(lua::State* L, int idx) { + ContentRemovalRequest request; + if (!lua::istable(L, idx)) { + throw std::runtime_error("table expected as argument"); + } + if (!lua::getfield(L, "units", idx)) { + throw std::runtime_error("table with 'units' field expected"); + } + if (!lua::istable(L, -1)) { + throw std::runtime_error("'units' field must be a table"); + } + int len = lua::objlen(L, -1); + for (int i = 0; i < len; i++) { + lua::rawgeti(L, i + 1); + request.units.emplace_back(lua::require_lstring(L, -1)); + lua::pop(L); + } + return request; +} + +static int l_delete_world_content(lua::State* L) { + auto name = lua::require_string(L, 1); + auto controller = engine->getController(); + auto request = parse_content_removal_request(L, 2); + bool loadWorld = lua::toboolean(L, 3); + controller->deleteWorldContent(name, request, loadWorld); + return 0; +} + /// @brief Get engine version -/// @return major, minor +/// @return major, minor, [patch] static int l_get_version(lua::State* L) { return lua::pushvec_stack( - L, glm::vec2(ENGINE_VERSION_MAJOR, ENGINE_VERSION_MINOR) + L, +#ifdef VC_VERSION_PATCH + glm::vec3(ENGINE_VERSION_MAJOR, ENGINE_VERSION_MINOR, ENGINE_VERSION_PATCH) +#else + glm::vec2(ENGINE_VERSION_MAJOR, ENGINE_VERSION_MINOR) +#endif ); } @@ -429,6 +466,7 @@ static int l_start_background_instance(lua::State* L) { "--sub-depth", std::to_string(engine->getCoreParameters() .subProcessDepth + 1), "--log", io::resolve(outputPath).u8string(), + "--stdin-cmd", }; args.emplace_back("--project"); args.emplace_back(io::resolve(engine->getProject().path).u8string()); @@ -444,25 +482,17 @@ static int l_start_background_instance(lua::State* L) { } } - int handle = -1; - for (int i = 0; i < ::processes.size(); i++) { - if (!::processes[i] || !::processes[i]->isActive()) { - handle = i; - break; - } - } - if (handle == -1) { + if (::processes.size() >= MAX_SUBPROCESSES) { throw std::runtime_error("sub-processes limit exceeded"); } - ::processes[handle] = - platform::new_engine_instance(std::move(args), "", true); - - return lua::pushinteger(L, handle); + int id = ::next_process_id++; + ::processes[id] = platform::new_engine_instance(std::move(args), "", true); + return lua::pushinteger(L, id); } static int l_is_instance_alive(lua::State* L) { int handle = lua::tointeger(L, 1); - if (handle < 0 || handle >= ::processes.size()) { + if (handle < 0 || ::processes.find(handle) == ::processes.end()) { throw std::runtime_error("invalid process handle"); } auto& process = ::processes[handle]; @@ -471,16 +501,42 @@ static int l_is_instance_alive(lua::State* L) { static int l_terminate_instance(lua::State* L) { int handle = lua::tointeger(L, 1); - if (handle < 0 || handle >= ::processes.size()) { + if (handle < 0 || ::processes.find(handle) == ::processes.end()) { + throw std::runtime_error("invalid process handle"); + } + auto it = ::processes.find(handle); + if (it->second == nullptr) { + ::processes.erase(it); + return lua::pushboolean(L, false); + } + bool active = it->second->isActive(); + it->second.reset(); + ::processes.erase(it); + return lua::pushboolean(L, active); +} + +static int l_get_stdin_stream(lua::State* L) { + int handle = lua::tointeger(L, 1); + if (handle < 0 || ::processes.find(handle) == ::processes.end()) { throw std::runtime_error("invalid process handle"); } auto& process = ::processes[handle]; if (process == nullptr) { - return lua::pushboolean(L, false); + return 0; } - bool active = process->isActive(); - process.reset(); - return lua::pushboolean(L, active); + return lua::pushinteger(L, process->getStdinDescriptor()); +} + +static int l_get_stdout_stream(lua::State* L) { + int handle = lua::tointeger(L, 1); + if (handle < 0 || ::processes.find(handle) == ::processes.end()) { + throw std::runtime_error("invalid process handle"); + } + auto& process = ::processes[handle]; + if (process == nullptr) { + return 0; + } + return lua::pushinteger(L, process->getStdoutDescriptor()); } const luaL_Reg applib[] = { @@ -512,12 +568,16 @@ const luaL_Reg applib[] = { {"save_world", lua::wrap}, {"close_world", lua::wrap}, {"delete_world", lua::wrap}, + {"delete_world_content", lua::wrap}, /// other {"get_version", lua::wrap}, {"create_memory_device", lua::wrap}, + // sub-instances {"start_debug_instance", lua::wrap}, {"start_background_instance", lua::wrap}, {"is_instance_alive", lua::wrap}, {"terminate_instance", lua::wrap}, + {"get_stdin_stream", lua::wrap}, + {"get_stdout_stream", lua::wrap}, {nullptr, nullptr} }; diff --git a/src/logic/scripting/lua/libs/libassets.cpp b/src/logic/scripting/lua/libs/libassets.cpp index 9a61ce9a8..776c19c9c 100644 --- a/src/logic/scripting/lua/libs/libassets.cpp +++ b/src/logic/scripting/lua/libs/libassets.cpp @@ -6,6 +6,7 @@ #include "coders/obj.hpp" #include "coders/png.hpp" #include "coders/vcm.hpp" +#include "coders/vec3.hpp" #include "debug/Logger.hpp" #include "engine/Engine.hpp" #include "graphics/commons/Model.hpp" @@ -27,6 +28,35 @@ static void load_texture( } } +static void store_vcm( + Assets& assets, + const std::string& modelName, + const std::string& skeletonName, + vcm::VcmModel& vcmModel +) { + auto skeleton = std::make_unique( + std::move(*vcmModel.skeleton) + ); + if (vcmModel.parts.size() > 1) { + for (auto& [partName, model] : vcmModel.parts) { + assets.store( + std::make_unique(std::move(model)), + modelName + "." + partName + ); + } + for (auto& bone : skeleton->getBones()) { + bone->setModel(modelName + "." + bone->model.name); + } + } else { + assets.store( + std::make_unique(std::move(vcmModel.parts["root"])), + modelName + ); + skeleton->getRoot()->setModel(modelName); + } + assets.store(std::move(skeleton), skeletonName); +} + static int l_request_texture(lua::State* L) { std::string filename = lua::require_string(L, 1); std::string alias = lua::require_string(L, 2); @@ -85,7 +115,6 @@ static int l_parse_model(lua::State* L) { auto& assets = engine->requireAssets(); auto format = lua::require_lstring(L, 1); - auto string = lua::require_lstring(L, 2); std::string name = lua::require_string(L, 3); std::string skeletonName; if (lua::isstring(L, 4)) { @@ -93,10 +122,71 @@ static int l_parse_model(lua::State* L) { } if (format == "obj") { + auto string = lua::require_lstring(L, 2); assets.store(obj::parse(name, string), name); return 0; } + if (format == "vec3") { + auto content = lua::bytearray_as_string(L, 2); + util::Buffer buffer(content.size()); + for (size_t i = 0; i < content.size(); i++) { + buffer[i] = static_cast(content[i]); + } + auto vec3File = vec3::load(name, buffer); + for (auto& [modelName, model] : vec3File.models) { + auto fullName = name; + if (name != modelName) { + fullName += "." + modelName; + } + model.model.translate(model.origin); + assets.store( + std::make_unique(std::move(model.model)), + fullName + ); + } + return 0; + } + + if (format != "xml" && format != "vcm") { + throw std::runtime_error( + "unknown format " + util::quote(std::string(format)) + ); + } + + auto string = lua::require_lstring(L, 2); + auto vcmModel = vcm::parse(name, string, format == "xml"); + + if (skeletonName.empty()) { + assets.store( + std::make_unique(std::move(vcmModel.squash())), name + ); + return 0; + } + + if (!vcmModel.skeleton) { + throw std::runtime_error( + "model format " + util::quote(std::string(format)) + + " does not define a skeleton" + ); + } + store_vcm(assets, name, skeletonName, vcmModel); + return 0; +} + +static int l_parse_skeleton(lua::State* L) { + auto& assets = engine->requireAssets(); + + auto format = lua::require_lstring(L, 1); + auto string = lua::require_lstring(L, 2); + std::string name = lua::require_string(L, 3); + + if (format == "json") { + auto skeleton = rigging::SkeletonConfig::parse(string, name, name); + assets.store(std::move(skeleton), name); + return 0; + } + if (format != "xml" && format != "vcm") { throw std::runtime_error( "unknown format " + util::quote(std::string(format)) @@ -104,34 +194,17 @@ static int l_parse_model(lua::State* L) { } auto vcmModel = vcm::parse(name, string, format == "xml"); - - if (skeletonName.empty()) { - assets.store( - std::make_unique(std::move(vcmModel.squash())), name + if (!vcmModel.skeleton) { + throw std::runtime_error( + "model format " + util::quote(std::string(format)) + + " does not define a skeleton" ); - } else { - auto skeleton = std::make_unique( - std::move(*vcmModel.skeleton) - ); - if (vcmModel.parts.size() > 1) { - for (auto& [partName, model] : vcmModel.parts) { - assets.store( - std::make_unique(std::move(model)), - name + "." + partName - ); - } - for (auto& bone : skeleton->getBones()) { - bone->setModel(name + "." + bone->model.name); - } - } else { - assets.store( - std::make_unique( - std::move(vcmModel.parts["root"])), name - ); - skeleton->getRoot()->setModel(name); - } - assets.store(std::move(skeleton), skeletonName); } + + assets.store( + std::make_unique(std::move(*vcmModel.skeleton)), + name + ); return 0; } @@ -151,7 +224,7 @@ static int l_to_canvas(lua::State* L) { return 0; } auto atlasName = alias.substr(0, sep); - + if (auto atlas = assets.get(std::string(atlasName))) { auto textureName = std::string(alias.substr(sep + 1)); auto image = atlas->shareImageData(); @@ -178,6 +251,7 @@ const luaL_Reg assetslib[] = { {"load_texture", lua::wrap}, {"parse_animation", lua::wrap}, {"parse_model", lua::wrap}, + {"parse_skeleton", lua::wrap}, {"to_canvas", lua::wrap}, {nullptr, nullptr} }; diff --git a/src/logic/scripting/lua/libs/libaudio.cpp b/src/logic/scripting/lua/libs/libaudio.cpp index 31be7553f..bda2784e8 100644 --- a/src/logic/scripting/lua/libs/libaudio.cpp +++ b/src/logic/scripting/lua/libs/libaudio.cpp @@ -4,9 +4,9 @@ #include "engine/EnginePaths.hpp" #include "api_lua.hpp" -inline const char* DEFAULT_CHANNEL = "regular"; +static inline const char* DEFAULT_CHANNEL = "regular"; -inline int extract_channel_index(lua::State* L, int idx) { +static int extract_channel_index(lua::State* L, int idx) { const char* channel = DEFAULT_CHANNEL; if (lua::isstring(L, idx)) { channel = lua::tostring(L, idx); @@ -18,7 +18,7 @@ inline int extract_channel_index(lua::State* L, int idx) { return index; } -inline audio::speakerid_t play_sound( +static audio::speakerid_t play_sound( const char* name, bool relative, lua::Number x, @@ -54,7 +54,7 @@ inline audio::speakerid_t play_sound( ); } -inline audio::speakerid_t play_stream( +static audio::speakerid_t play_stream( const char* filename, bool relative, lua::Number x, diff --git a/src/logic/scripting/lua/libs/libblock.cpp b/src/logic/scripting/lua/libs/libblock.cpp index cd3df5c0f..6958d811d 100644 --- a/src/logic/scripting/lua/libs/libblock.cpp +++ b/src/logic/scripting/lua/libs/libblock.cpp @@ -468,7 +468,10 @@ static int l_get_hitbox(lua::State* L) { } else { rotation = 0; } - auto& hitbox = def->rt.hitboxes[rotation].at(hitboxIndex); + const auto& variant = + def->variants ? def->variants->variants[get_variant_index(L, *def, 4)] + : def->defaults; + auto& hitbox = variant.rt.hitboxes[rotation].at(hitboxIndex); lua::createtable(L, 2, 0); lua::pushvec3(L, hitbox.min()); diff --git a/src/logic/scripting/lua/libs/libentity.cpp b/src/logic/scripting/lua/libs/libentity.cpp index 879614da8..02e66991b 100644 --- a/src/logic/scripting/lua/libs/libentity.cpp +++ b/src/logic/scripting/lua/libs/libentity.cpp @@ -28,7 +28,7 @@ static const EntityDef* require_entity_def(lua::State* L) { } static int l_exists(lua::State* L) { - return lua::pushboolean(L, get_entity(L, 1).has_value()); + return lua::pushboolean(L, get_entity(L, 1) != nullptr); } static int l_def_index(lua::State* L) { @@ -138,8 +138,7 @@ static int l_get_all_in_box(lua::State* L) { auto found = level->entities->getAllInside(AABB(pos, pos + size)); lua::createtable(L, found.size(), 0); for (size_t i = 0; i < found.size(); i++) { - const auto& entity = found[i]; - lua::pushinteger(L, entity.getUID()); + lua::pushinteger(L, found[i]->getUID()); lua::rawseti(L, i + 1); } return 1; @@ -151,8 +150,7 @@ static int l_get_all_in_radius(lua::State* L) { auto found = level->entities->getAllInRadius(pos, radius); lua::createtable(L, found.size(), 0); for (size_t i = 0; i < found.size(); i++) { - const auto& entity = found[i]; - lua::pushinteger(L, entity.getUID()); + lua::pushinteger(L, found[i]->getUID()); lua::rawseti(L, i + 1); } return 1; diff --git a/src/logic/scripting/lua/libs/libentity.hpp b/src/logic/scripting/lua/libs/libentity.hpp index 5400b449a..77baeca69 100644 --- a/src/logic/scripting/lua/libs/libentity.hpp +++ b/src/logic/scripting/lua/libs/libentity.hpp @@ -1,7 +1,5 @@ #pragma once -#include - #include "frontend/hud.hpp" #include "objects/Entities.hpp" #include "objects/Entity.hpp" @@ -13,7 +11,7 @@ namespace scripting { extern Hud* hud; } -inline std::optional get_entity(lua::State* L, int idx) { +inline Entity* get_entity(lua::State* L, int idx) { auto id = lua::tointeger(L, idx); auto level = scripting::controller->getLevel(); return level->entities->get(id); diff --git a/src/logic/scripting/lua/libs/libfile.cpp b/src/logic/scripting/lua/libs/libfile.cpp index 1bcceb6d3..61a7e2191 100644 --- a/src/logic/scripting/lua/libs/libfile.cpp +++ b/src/logic/scripting/lua/libs/libfile.cpp @@ -305,13 +305,14 @@ static int l_read_descriptor(lua::State* L) { int maxlen = lua::tointeger(L, 2); auto& stream = io_descriptors::require_input(descriptor); - if (stream.eof()) { - stream.clear(); - } util::Buffer buffer(maxlen); stream.read(buffer.data(), maxlen); - std::streamsize read_len = stream.gcount(); + std::streamsize read_len = stream.gcount(); + + if (stream.eof()) { + stream.clear(stream.rdstate() & std::ios::badbit); + } return lua::create_bytearray(L, buffer.data(), read_len); } diff --git a/src/logic/scripting/lua/libs/libgui.cpp b/src/logic/scripting/lua/libs/libgui.cpp index dc4806d00..d409bf381 100644 --- a/src/logic/scripting/lua/libs/libgui.cpp +++ b/src/logic/scripting/lua/libs/libgui.cpp @@ -157,7 +157,18 @@ static int l_container_set_interval(lua::State* L) { if (auto container = std::dynamic_pointer_cast(node.node)) { lua::pushvalue(L, 3); auto runnable = lua::create_runnable(L); - container->listenInterval(interval, runnable); + return lua::pushinteger( + L, container->listenInterval(interval, runnable) + ); + } + return 0; +} + +static int l_container_clear_interval(lua::State* L) { + auto node = get_document_node(L, 1); + auto id = lua::tointeger(L, 2); + if (auto container = std::dynamic_pointer_cast(node.node)) { + container->cancelInterval(id); } return 0; } @@ -502,6 +513,13 @@ static int p_set_interval(UINode* node, lua::State* L) { return 0; } +static int p_clear_interval(UINode* node, lua::State* L) { + if (dynamic_cast(node)) { + return lua::pushcfunction(L, lua::wrap); + } + return 0; +} + static int p_get_content_offset(UINode* node, lua::State* L) { return lua::pushvec(L, node->getContentOffset()); } @@ -667,6 +685,7 @@ static int l_gui_getattr(lua::State* L) { {"reposition", p_get_reposition}, {"clear", p_get_clear}, {"setInterval", p_set_interval}, + {"clearInterval", p_clear_interval}, {"placeholder", p_get_placeholder}, {"hint", p_get_hint}, {"valid", p_is_valid}, diff --git a/src/logic/scripting/lua/libs/libhud.cpp b/src/logic/scripting/lua/libs/libhud.cpp index a457ca6ee..eddc64401 100644 --- a/src/logic/scripting/lua/libs/libhud.cpp +++ b/src/logic/scripting/lua/libs/libhud.cpp @@ -194,6 +194,15 @@ static int l_set_allow_pause(lua::State* L) { return 0; } +static int l_is_hotbar_visible(lua::State* L) { + return lua::pushboolean(L, hud->isHotbarVisible()); +} + +static int l_set_hotbar_visible(lua::State* L) { + hud->setHotbarVisible(lua::toboolean(L, 1)); + return 0; +} + static int l_reload_script(lua::State* L) { auto packid = lua::require_string(L, 1); if (content == nullptr) { @@ -237,6 +246,8 @@ const luaL_Reg hudlib[] = { {"_set_content_access", wrap_hud}, {"_set_debug_cheats", wrap_hud}, {"set_allow_pause", wrap_hud}, + {"is_hotbar_visible", wrap_hud}, + {"set_hotbar_visible", wrap_hud}, {"reload_script", wrap_hud}, {"is_open", wrap_hud}, {nullptr, nullptr} diff --git a/src/logic/scripting/lua/libs/libpathfinding.cpp b/src/logic/scripting/lua/libs/libpathfinding.cpp index ae880912d..d702633e3 100644 --- a/src/logic/scripting/lua/libs/libpathfinding.cpp +++ b/src/logic/scripting/lua/libs/libpathfinding.cpp @@ -100,6 +100,20 @@ static int l_set_jump_height(lua::State* L) { return 0; } +static int l_set_width(lua::State* L) { + if (auto agent = get_agent(L)) { + agent->width = lua::tonumber(L, 2); + } + return 0; +} + +static int l_set_height(lua::State* L) { + if (auto agent = get_agent(L)) { + agent->height = lua::touinteger(L, 2); + } + return 0; +} + static int l_avoid_tag(lua::State* L) { if (auto agent = get_agent(L)) { int index = @@ -125,6 +139,8 @@ const luaL_Reg pathfindinglib[] = { {"pull_route", lua::wrap}, {"set_max_visited", lua::wrap}, {"set_jump_height", lua::wrap}, + {"set_width", lua::wrap}, + {"set_height", lua::wrap}, {"avoid_tag", lua::wrap}, {nullptr, nullptr} }; diff --git a/src/logic/scripting/lua/libs/libplayer.cpp b/src/logic/scripting/lua/libs/libplayer.cpp index e143d368a..2ad96e7b2 100644 --- a/src/logic/scripting/lua/libs/libplayer.cpp +++ b/src/logic/scripting/lua/libs/libplayer.cpp @@ -121,7 +121,21 @@ static int l_get_inv(lua::State* L) { static int l_set_selected_slot(lua::State* L) { if (auto player = get_player(L, 1)) { - player->setChosenSlot(lua::tointeger(L, 2) % 10); + player->setChosenSlot(lua::tointeger(L, 2) % player->getHotbarSize()); + } + return 0; +} + +static int l_get_hotbar_size(lua::State* L) { + if (auto player = get_player(L, 1)) { + return lua::pushinteger(L, player->getHotbarSize()); + } + return 0; +} + +static int l_set_hotbar_size(lua::State* L) { + if (auto player = get_player(L, 1)) { + player->setHotbarSize(lua::tointeger(L, 2)); } return 0; } @@ -401,6 +415,8 @@ const luaL_Reg playerlib[] = { {"get_interaction_distance", lua::wrap}, {"set_interaction_distance", lua::wrap}, {"set_selected_slot", lua::wrap}, + {"get_hotbar_size", lua::wrap}, + {"set_hotbar_size", lua::wrap}, {"get_selected_block", lua::wrap}, {"get_selected_entity", lua::wrap}, {"set_spawnpoint", lua::wrap}, diff --git a/src/logic/scripting/lua/libs/libworld.cpp b/src/logic/scripting/lua/libs/libworld.cpp index c45b7bd35..b2257d45e 100644 --- a/src/logic/scripting/lua/libs/libworld.cpp +++ b/src/logic/scripting/lua/libs/libworld.cpp @@ -108,6 +108,17 @@ static int l_get_seed(lua::State* L) { return lua::pushinteger(L, require_world_info().seed); } +static int l_get_logic(lua::State* L) { + auto name = lua::require_string(L, 1); + return lua::pushvalue(L, require_world_info().getLogicValue(name)); +} + +static int l_set_logic(lua::State* L) { + auto name = lua::require_string(L, 1); + require_world_info().setLogicValue(name, lua::tovalue(L, 2)); + return 0; +} + static int l_exists(lua::State* L) { auto name = lua::require_string(L, 1); auto worldsDir = engine->getPaths().getWorldFolderByName(name); @@ -250,6 +261,8 @@ const luaL_Reg worldlib[] = { {"set_day_time_speed", lua::wrap}, {"get_day_time_speed", lua::wrap}, {"get_seed", lua::wrap}, + {"get_logic", lua::wrap}, + {"set_logic", lua::wrap}, {"get_generator", lua::wrap}, {"is_day", lua::wrap}, {"is_night", lua::wrap}, diff --git a/src/logic/scripting/scripting.cpp b/src/logic/scripting/scripting.cpp index efaf32866..64037775b 100644 --- a/src/logic/scripting/scripting.cpp +++ b/src/logic/scripting/scripting.cpp @@ -24,6 +24,7 @@ #include "world/Level.hpp" #include "world/World.hpp" #include "interfaces/Process.hpp" +#include "objects/EntityDef.hpp" #include #include @@ -215,7 +216,7 @@ std::unique_ptr scripting::start_app_script(const io::path& script) { } [[nodiscard]] scriptenv scripting::create_doc_environment( - const scriptenv& parent, const std::string& name + const scriptenv& parent, const std::string& name, bool app ) { auto L = lua::get_main_state(); int id = lua::create_environment(L, *parent); @@ -225,6 +226,12 @@ std::unique_ptr scripting::start_app_script(const io::path& script) { lua::pushstring(L, name); lua::setfield(L, "DOC_NAME"); + if (app) { + if (lua::getregistry(L, "app")) { + lua::setfield(L, "app"); + } + } + if (lua::getglobal(L, "Document")) { if (lua::getfield(L, "new")) { lua::pushstring(L, name); @@ -261,7 +268,12 @@ static int push_properties_tables( } void scripting::on_assets_loading() { - lua::call_internal(lua::get_main_state(), "backup_and_clear_animation"); + auto L = lua::get_main_state(); + lua::call_internal(L, "backup_and_clear_animation"); + + for (auto& pack : content_control->getAllContentPacks()) { + lua::emit_event(L, pack.id + ":.onassetsloading"); + } } void scripting::revert_assets_loading() { @@ -293,6 +305,11 @@ void scripting::on_content_load(Content* content) { lua::setfield(L, "properties"); lua::pop(L); } + if (lua::getglobal(L, "entities")) { + push_properties_tables(L, indices.entities); + lua::setfield(L, "properties"); + lua::pop(L); + } lua::getregistry(L, "app"); lua::setglobal(L, "__vc_app"); @@ -345,7 +362,9 @@ void scripting::on_world_tick(int tps) { lua::pop(L); } for (auto& pack : content_control->getAllContentPacks()) { - lua::emit_event(L, pack.id + ":.worldtick"); + lua::emit_event(L, pack.id + ":.worldtick", [tps](lua::State* L) { + return lua::pushinteger(L, tps); + }); } } @@ -451,6 +470,23 @@ static bool on_block_common( return result; } +bool scripting::can_block_be_placed( + Player* player, const Block& block, const glm::ivec3& pos, int rotation +) { + if (!block.rt.funcsset.canbeplaced) { + return true; + } + std::string name = block.name + ".canbeplaced"; + return lua::emit_event( + lua::get_main_state(), name, [pos, player, rotation](auto L) { + lua::pushivec_stack(L, pos); + lua::pushinteger(L, player ? player->getId() : -1); + lua::pushinteger(L, rotation); + return 5; + } + ); +} + void scripting::on_block_placed( Player* player, const Block& block, const glm::ivec3& pos ) { @@ -717,6 +753,8 @@ void scripting::load_content_script( register_event(env, "on_breaking", prefix + ".breaking"); funcsset.onbroken = register_event(env, "on_broken", prefix + ".broken"); funcsset.onplaced = register_event(env, "on_placed", prefix + ".placed"); + funcsset.canbeplaced = + register_event(env, "can_be_placed", prefix + ".canbeplaced"); funcsset.onreplaced = register_event(env, "on_replaced", prefix + ".replaced"); funcsset.oninteract = @@ -821,6 +859,7 @@ void scripting::load_content_script( register_event(env, "on_scripts_loading", prefix + ":.onscriptsloading"); register_event(env, "on_content_loaded", prefix + ":.oncontentloaded"); + register_event(env, "on_assets_loading", prefix + ":.onassetsloading"); } void scripting::load_layout_script( diff --git a/src/logic/scripting/scripting.hpp b/src/logic/scripting/scripting.hpp index 116226aff..65f8836e9 100644 --- a/src/logic/scripting/scripting.hpp +++ b/src/logic/scripting/scripting.hpp @@ -65,7 +65,7 @@ namespace scripting { scriptenv create_pack_environment(const ContentPack& pack); scriptenv create_environment(const scriptenv& parent); scriptenv create_doc_environment( - const scriptenv& parent, const std::string& name + const scriptenv& parent, const std::string& name, bool app = false ); void process_post_runnables(); @@ -92,6 +92,9 @@ namespace scripting { void on_blocks_tick(const Block& block, int tps); void update_block(const Block& block, const glm::ivec3& pos); void random_update_block(const Block& block, const glm::ivec3& pos); + bool can_block_be_placed( + Player* player, const Block& block, const glm::ivec3& pos, int rotation + ); void on_block_placed( Player* player, const Block& block, const glm::ivec3& pos ); diff --git a/src/main.cpp b/src/main.cpp index 4e739acde..c837d1295 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -33,6 +33,9 @@ int main(int argc, char** argv) { std::cerr << err.what() << std::endl; return EXIT_FAILURE; } +#ifndef _WIN32 + std::signal(SIGPIPE, SIG_IGN); +#endif std::signal(SIGTERM, sigterm_handler); #ifdef NDEBUG std::signal(SIGINT, sigterm_handler); diff --git a/src/maths/UVRegion.hpp b/src/maths/UVRegion.hpp index f7e398d8e..fc6c0ff39 100644 --- a/src/maths/UVRegion.hpp +++ b/src/maths/UVRegion.hpp @@ -35,7 +35,7 @@ struct UVRegion { v2 = v1 + uvh * h; } - inline glm::vec2 apply(const glm::vec2& uv) { + glm::vec2 apply(const glm::vec2& uv) const { float w = getWidth(); float h = getHeight(); return glm::vec2(u1 + uv.x * w, v1 + uv.y * h); diff --git a/src/maths/util.hpp b/src/maths/util.hpp index 08f0f4585..c35450719 100644 --- a/src/maths/util.hpp +++ b/src/maths/util.hpp @@ -183,4 +183,19 @@ namespace util { } return false; } + + inline void uv_by_normal( + const glm::vec3& n, glm::vec3& u, glm::vec3& v + ) { + if (std::abs(n.y) > 0.5f) { + u = {n.y > 0 ? 1 : -1, 0, 0}; + v = {0, 0, -1}; + } else if (std::abs(n.z) > 0.5f) { + u = {n.z > 0 ? 1 : -1, 0, 0}; + v = {0, 1, 0}; + } else { + u = {0, 0, n.x > 0 ? -1 : 1}; + v = {0, 1, 0}; + } + } } diff --git a/src/objects/Entities.cpp b/src/objects/Entities.cpp index a57c3a06e..d02ede8d8 100644 --- a/src/objects/Entities.cpp +++ b/src/objects/Entities.cpp @@ -9,18 +9,12 @@ #include "engine/Engine.hpp" #include "Entity.hpp" #include "EntityDef.hpp" -#include "graphics/commons/Model.hpp" -#include "graphics/core/DrawContext.hpp" -#include "graphics/core/LineBatch.hpp" -#include "graphics/render/ModelBatch.hpp" #include "logic/scripting/scripting.hpp" -#include "maths/FrustumCulling.hpp" #include "maths/rays.hpp" #include "maths/util.hpp" #include "physics/PhysicsSolver.hpp" #include "world/Level.hpp" -#include #include #include #include @@ -28,8 +22,7 @@ static debug::Logger logger("entities"); Entities::Entities(Level& level) - : registry(std::make_unique()), - level(level), + : level(level), sensorsTickClock(20, 3), updateTickClock(20, 3) { } @@ -40,12 +33,12 @@ void Entities::setAssets(Assets& assets) { this->assets = &assets; } -std::optional Entities::get(entityid_t id) { +Entity* Entities::get(entityid_t id) { const auto& found = entities.find(id); - if (found != entities.end() && registry->valid(found->second)) { - return Entity(*this, id, *registry, found->second); + if (found != entities.end()) { + return found->second.get(); } - return std::nullopt; + return nullptr; } entityid_t Entities::spawn( @@ -81,33 +74,30 @@ entityid_t Entities::spawn( throw std::runtime_error(ss.str()); } } - auto entity = registry->create(); - entities[id] = entity; - uids[entity] = id; - - registry->emplace(entity, id, def); - const auto& tsf = registry->emplace( - entity, - position, - glm::vec3(1.0f), - glm::mat3(1.0f), - glm::mat4(1.0f), - true - ); - auto& body = registry->emplace( - entity, - true, - Hitbox {id, def.bodyType, position, def.hitbox * 0.5f}, - std::vector {} - ); - body.initialize(def, id, *this); - - auto& scripting = registry->emplace(entity); + std::unique_ptr skeletonInstance; if (assets) { - registry->emplace( - entity, skeleton ? skeleton->instance() : rigging::Skeleton(nullptr) + skeletonInstance = std::make_unique( + skeleton ? skeleton->instance() : rigging::Skeleton(nullptr) ); } + auto& entity = *(entities[id] = std::make_unique( + *this, + EntityId {id, def}, + Transform { + position, glm::vec3(1.0f), glm::mat3(1.0f), glm::mat4(1.0f), true + }, + Rigidbody { + true, + Hitbox {id, def.bodyType, position, def.hitbox * 0.5f}, + std::vector {} + }, + std::move(skeletonInstance) + )); + const auto& tsf = entity.getTransform(); + auto& body = entity.getRigidbody(); + body.initialize(def, id, *this); + + auto& scripting = entity.getScripting(); for (auto& instance : def.components) { auto component = std::make_unique( @@ -118,7 +108,7 @@ entityid_t Entities::spawn( dv::value componentsMap = nullptr; if (saved != nullptr) { componentsMap = saved["comps"]; - loadEntity(saved, get(id).value()); + loadEntity(saved, entity); } body.hitbox.position = tsf.pos; scripting::on_entity_spawn( @@ -144,7 +134,7 @@ void Entities::loadEntity(const dv::value& map) { spawn(def, {}, nullptr, map, uid); } -void Entities::loadEntity(const dv::value& map, Entity entity) { +void Entities::loadEntity(const dv::value& map, Entity& entity) { auto& transform = entity.getTransform(); auto& body = entity.getRigidbody(); auto skeleton = entity.getSkeleton(); @@ -175,12 +165,12 @@ std::optional Entities::rayCast( const RaycastSettings& settings ) { Ray ray(start, dir); - auto view = registry->view(); - entityid_t foundUID = 0; glm::ivec3 foundNormal; - for (auto [entity, eid, transform, body] : view.each()) { + for (const auto& [uid, entity] : entities) { + const auto& eid = entity->getID(); + const auto& body = entity->getRigidbody(); const auto& hitbox = body.hitbox; if (eid.uid == settings.ignoredUid || !body.enabled || (settings.solidEntitiesOnly && !eid.def.solid) || @@ -227,40 +217,38 @@ void Entities::onSave(const Entity& entity) { scripting::on_entity_save(entity); } -dv::value Entities::serialize(const std::vector& entities) { +dv::value Entities::serialize(const std::vector& entities) { auto list = dv::list(); - for (auto& entity : entities) { - const EntityId& eid = entity.getID(); - if (!entity.getDef().save.enabled || eid.destroyFlag) { + for (auto entity : entities) { + const EntityId& eid = entity->getID(); + if (!entity->getDef().save.enabled || eid.destroyFlag) { continue; } - level.entities->onSave(entity); + level.entities->onSave(*entity); if (!eid.destroyFlag) { - list.add(entity.serialize()); + list.add(entity->serialize()); } } return list; } -void Entities::despawn(std::vector entities) { - for (auto& entity : entities) { - entity.destroy(); +void Entities::despawn(const std::vector& entities) { + for (auto entity : entities) { + entity->destroy(); } } void Entities::clean() { for (auto it = entities.begin(); it != entities.end();) { - if (!registry->get(it->second).destroyFlag) { + if (!it->second->getID().destroyFlag) { ++it; } else { - auto& rigidbody = registry->get(it->second); + auto& rigidbody = it->second->getRigidbody(); // todo: refactor auto physics = level.physics.get(); for (auto& sensor : rigidbody.sensors) { physics->removeSensor(&sensor); } - uids.erase(it->second); - registry->destroy(it->second); it = entities.erase(it); } } @@ -309,15 +297,16 @@ void Entities::preparePhysics(float delta) { auto part = sensorsTickClock.convertPart(i); auto allParts = sensorsTickClock.getParts(); - auto view = registry->view(); - for (auto [entity, eid, transform, rigidbody] : view.each()) { + for (const auto& [uid, entity] : entities) { + const auto& eid = entity->getID(); + auto& rigidbody = entity->getRigidbody(); if (!rigidbody.enabled) { continue; } if ((eid.uid + part) % allParts != 0) { continue; } - updateSensors(rigidbody, transform, sensors); + updateSensors(rigidbody, entity->getTransform(), sensors); } } } @@ -325,8 +314,9 @@ void Entities::preparePhysics(float delta) { hitboxes.clear(); solidHitboxes.clear(); - auto view = registry->view(); - for (auto [entity, eid, rigidbody] : view.each()) { + for (const auto& [uid, entity] : entities) { + const auto& eid = entity->getID(); + auto& rigidbody = entity->getRigidbody(); auto bodyType = rigidbody.hitbox.type; if (eid.destroyFlag || !rigidbody.enabled) { continue; @@ -350,13 +340,15 @@ void Entities::preparePhysics(float delta) { void Entities::updatePhysics(float delta) { preparePhysics(delta); - auto view = registry->view(); auto physics = level.physics.get(); int substeps = std::max(std::min(delta * 1000, 200), 8); physics->step(*level.chunks, delta, substeps); - for (auto [entity, eid, transform, rigidbody] : view.each()) { + for (const auto& [uid, entity] : entities) { + const auto& eid = entity->getID(); + auto& transform = entity->getTransform(); + auto& rigidbody = entity->getRigidbody(); if (!rigidbody.enabled || rigidbody.hitbox.type == BodyType::STATIC) { continue; @@ -373,11 +365,11 @@ void Entities::updatePhysics(float delta) { } if (hitbox.grounded && !hitbox.prevGrounded) { scripting::on_entity_grounded( - *get(eid.uid), glm::length(hitbox.prevVelocity - hitbox.velocity) + *entity, glm::length(hitbox.prevVelocity - hitbox.velocity) ); } if (!hitbox.grounded && hitbox.prevGrounded) { - scripting::on_entity_fall(*get(eid.uid)); + scripting::on_entity_fall(*entity); } } } @@ -395,178 +387,51 @@ void Entities::update(float delta) { updatePhysics(delta); scripting::on_entities_physics_update(delta); - auto view = registry->view(); - for (auto [entity, transform, skeleton] : view.each()) { + for (const auto& [uid, entity] : entities) { + if (!entity->getSkeleton()) { + continue; + } + auto& transform = entity->getTransform(); + auto& skeleton = *entity->getSkeleton(); if (transform.dirty) { transform.refresh(); } if (skeleton.interpolation.isEnabled()) { skeleton.interpolation.updateTimer(delta); } - } -} - -static void debug_render_skeleton( - LineBatch& batch, - const rigging::Bone* bone, - const rigging::Skeleton& skeleton -) { - size_t pindex = bone->getIndex(); - for (auto& sub : bone->getBones()) { - size_t sindex = sub->getIndex(); - const auto& matrices = skeleton.calculated.matrices; - batch.line( - glm::vec3(matrices[pindex] * glm::vec4(0, 0, 0, 1)), - glm::vec3(matrices[sindex] * glm::vec4(0, 0, 0, 1)), - glm::vec4(0, 0.5f, 0, 1) - ); - debug_render_skeleton(batch, sub.get(), skeleton); - } -} - -void Entities::renderDebug( - LineBatch& batch, const Frustum* frustum, const DrawContext& pctx, entityid_t fpsEntity -) { - { - auto ctx = pctx.sub(&batch); - ctx.setLineWidth(1); - auto view = registry->view(); - for (auto [entity, transform, rigidbody] : view.each()) { - const auto& hitbox = rigidbody.hitbox; - const auto& pos = transform.pos; - const auto& size = transform.size; - if (frustum && !frustum->isBoxVisible(pos - size, pos + size)) { - continue; - } - batch.box( - hitbox.position, hitbox.getHalfSize() * 2.0f, glm::vec4(1.0f) - ); - - for (auto& sensor : rigidbody.sensors) { - if (sensor.type != SensorType::AABB) continue; - batch.box( - sensor.calculated.aabb.center(), - sensor.calculated.aabb.size(), - glm::vec4(1.0f, 1.0f, 0.0f, 1.0f) - ); - } + if (skeleton.rotationInterpolation.isEnabled()) { + skeleton.rotationInterpolation.updateTimer(delta); } } - { - auto view = registry->view(); - auto ctx = pctx.sub(&batch); - ctx.setDepthTest(false); - ctx.setDepthMask(false); - ctx.setLineWidth(2); - for (auto [entity, eid, transform, skeleton] : view.each()) { - if (eid.uid == fpsEntity) { - continue; - } - auto config = skeleton.config; - if (config == nullptr) { - continue; - } - const auto& pos = transform.pos; - const auto& size = transform.size; - if (frustum && !frustum->isBoxVisible(pos - size, pos + size)) { - continue; - } - auto bone = config->getRoot(); - debug_render_skeleton(batch, bone, skeleton); - } - } -} - -void Entities::render( - const Assets& assets, - ModelBatch& batch, - const Frustum* frustum, - entityid_t fpsEntity -) { - auto view = registry->view(); - 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; - const auto& halfSize = rigidbody.hitbox.getHalfSize(); - // todo: more correct frustum culling - if (frustum && !frustum->isBoxVisible(pos - halfSize, pos + halfSize)) { - continue; - } - - const auto& rigConfig = skeleton.config; - if (rigConfig) { - rigConfig->render( - assets, - batch, - skeleton, - def.lightingMode, - transform.rot, - pos, - size - ); - } - } -} - -void Entities::updateCulling(const Frustum* frustum, entityid_t fpsEntity) { - auto view = registry->view(); - for (auto [entity, eid, transform, skeleton, rigidbody] : view.each()) { - if (frustum == nullptr || eid.uid == fpsEntity) { - skeleton.culled = false; - continue; - } - const auto& pos = transform.pos; - const auto& halfSize = rigidbody.hitbox.getHalfSize(); - skeleton.culled = !frustum->isBoxVisible(pos - halfSize, pos + halfSize); - } } bool Entities::hasBlockingInside(AABB aabb) { constexpr float eps = 0.05f; - auto view = registry->view(); - for (auto [entity, eid, body] : view.each()) { - AABB bodyAABB(body.hitbox.getAABB()); + for (const auto& [uid, entity] : entities) { + AABB bodyAABB(entity->getRigidbody().hitbox.getAABB()); bodyAABB.scale(glm::vec3(1.0f - eps)); - if (eid.def.blocking && aabb.intersects(bodyAABB)) { + if (entity->getID().def.blocking && aabb.intersects(bodyAABB)) { return true; } } return false; } -std::vector Entities::getAllInside(AABB aabb) { - std::vector collected; - auto view = registry->view(); - for (auto [entity, eid, transform] : view.each()) { - if (!eid.destroyFlag && aabb.contains(transform.pos)) { - const auto& found = uids.find(entity); - if (found == uids.end()) { - continue; - } - if (auto wrapper = get(found->second)) { - collected.push_back(*wrapper); - } +std::vector Entities::getAllInside(AABB aabb) { + std::vector collected; + for (const auto& [uid, entity] : entities) { + if (!entity->getID().destroyFlag && aabb.contains(entity->getTransform().pos)) { + collected.push_back(entity.get()); } } return collected; } -std::vector Entities::getAllInRadius(glm::vec3 center, float radius) { - std::vector collected; - auto view = registry->view(); - for (auto [entity, transform] : view.each()) { - if (glm::distance2(transform.pos, center) <= radius * radius) { - const auto& found = uids.find(entity); - if (found == uids.end()) { - continue; - } - if (auto wrapper = get(found->second)) { - collected.push_back(*wrapper); - } +std::vector Entities::getAllInRadius(glm::vec3 center, float radius) { + std::vector collected; + for (const auto& [uid, entity] : entities) { + if (glm::distance2(entity->getTransform().pos, center) <= radius * radius) { + collected.push_back(entity.get()); } } return collected; diff --git a/src/objects/Entities.hpp b/src/objects/Entities.hpp index 8b656d2f3..c92aa990f 100644 --- a/src/objects/Entities.hpp +++ b/src/objects/Entities.hpp @@ -6,6 +6,7 @@ #include #include "constants.hpp" +#include "Entity.hpp" #include "physics/Hitbox.hpp" #include "Transform.hpp" #include "Rigidbody.hpp" @@ -13,19 +14,13 @@ #include "typedefs.hpp" #include "util/Clock.hpp" -#include -#include +#include struct EntityDef; class Level; class Assets; class Entity; -class LineBatch; -class ModelBatch; -class Frustum; -class Entities; -class DrawContext; namespace rigging { struct Skeleton; @@ -33,10 +28,8 @@ namespace rigging { } class Entities final { - std::unique_ptr registry; Level& level; - std::unordered_map entities; - std::unordered_map uids; + std::map> entities; entityid_t nextID = 1; util::Clock sensorsTickClock; util::Clock updateTickClock; @@ -57,18 +50,6 @@ public: void updatePhysics(float delta); void update(float delta); - void renderDebug( - LineBatch& batch, const Frustum* frustum, const DrawContext& ctx, entityid_t fpsEntity - ); - void render( - const Assets& assets, - ModelBatch& batch, - const Frustum* frustum, - entityid_t fpsEntity - ); - - void updateCulling(const Frustum* frustum, entityid_t fpsEntity); - entityid_t spawn( const EntityDef& def, glm::vec3 position, @@ -77,7 +58,7 @@ public: entityid_t uid = 0 ); - std::optional get(entityid_t id); + Entity* get(entityid_t id); struct RaycastSettings { /// @param ignore Ignored entity uid @@ -111,19 +92,24 @@ public: void loadEntities(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); bool hasBlockingInside(AABB aabb); - std::vector getAllInside(AABB aabb); - std::vector getAllInRadius(glm::vec3 center, float radius); + std::vector getAllInside(AABB aabb); + std::vector getAllInRadius(glm::vec3 center, float radius); void despawn(entityid_t id); - void despawn(std::vector entities); - dv::value serialize(const std::vector& entities); + void despawn(const std::vector& entities); + dv::value serialize(const std::vector& entities); void setNextID(entityid_t id) { nextID = id; } + inline const std::map>& getEntities( + ) const { + return entities; + } + inline size_t size() const { return entities.size(); } diff --git a/src/objects/Entity.cpp b/src/objects/Entity.cpp index 697c6618f..a5aa4eeec 100644 --- a/src/objects/Entity.cpp +++ b/src/objects/Entity.cpp @@ -8,51 +8,62 @@ #include "ScriptComponents.hpp" #include "Transform.hpp" -#include - static inline std::string SAVED_DATA_VARNAME = "SAVED_DATA"; +Entity::Entity( + Entities& entities, + EntityId id, + Transform transform, + Rigidbody rigidbody, + std::unique_ptr skeleton +) + : entities(entities), + id(std::move(id)), + transform(std::move(transform)), + rigidbody(std::move(rigidbody)), + skeleton(std::move(skeleton)) { +} + +Entity::~Entity() = default; + void Entity::setInterpolatedPosition(const glm::vec3& position) { - if (auto skeleton = getSkeleton()) { + if (skeleton) { skeleton->interpolation.refresh(position); } } glm::vec3 Entity::getInterpolatedPosition() const { - if (auto skeleton = getSkeleton()) { - if (skeleton->interpolation.isEnabled()) { - return skeleton->interpolation.getCurrent(); + if (skeleton) { + const auto& interpolation = skeleton->interpolation; + if (interpolation.isEnabled() && interpolation.isRefreshed()) { + return interpolation.getCurrent(); } } - return getTransform().pos; + return transform.pos; +} + +void Entity::setInterpolatedRotation(const glm::quat& rotation) { + if (skeleton) { + skeleton->rotationInterpolation.refresh(rotation); + } } void Entity::destroy() { - if (isValid()) { - entities.despawn(id); - } -} - -rigging::Skeleton* Entity::getSkeleton() const { - return registry.try_get(entity); + entities.despawn(id.uid); } void Entity::setRig(std::shared_ptr rigConfig) { - auto& skeleton = registry.get(entity); - skeleton.setConfig(std::move(rigConfig)); + if (skeleton) { + skeleton->setConfig(std::move(rigConfig)); + } } dv::value Entity::serialize() const { - const auto& eid = getID(); - const auto& def = eid.def; - const auto& transform = getTransform(); - const auto& rigidbody = getRigidbody(); - const auto& scripts = getScripting(); - auto skeleton = getSkeleton(); + const auto& def = id.def; auto root = dv::object(); root["def"] = def.name; - root["uid"] = eid.uid; + root["uid"] = id.uid; root[COMP_TRANSFORM] = transform.serialize(); root[COMP_RIGIDBODY] = @@ -68,9 +79,9 @@ dv::value Entity::serialize() const { ); } } - if (!scripts.components.empty()) { + if (!scripting.components.empty()) { auto& compsMap = root.object("comps"); - for (auto& comp : scripts.components) { + for (auto& comp : scripting.components) { if (comp->env == nullptr) { continue; } @@ -82,45 +93,11 @@ dv::value Entity::serialize() const { return root; } -EntityId& Entity::getID() const { - return registry.get(entity); -} - -bool Entity::isValid() const { - return registry.valid(entity); -} - -Transform& Entity::getTransform() const { - return registry.get(entity); -} - - -ScriptComponents& Entity::getScripting() const { - return registry.get(entity); -} - -const EntityDef& Entity::getDef() const { - return registry.get(entity).def; -} - -Rigidbody& Entity::getRigidbody() const { - return registry.get(entity); -} - -entityid_t Entity::getUID() const { - return registry.get(entity).uid; -} - -int64_t Entity::getPlayer() const { - return registry.get(entity).player; -} - -void Entity::setPlayer(int64_t id) { - auto& eid = registry.get(entity); - if (eid.player == id) { +void Entity::setPlayer(int64_t player) { + if (id.player == player) { return; } - eid.player = id; - scripting::on_entity_player_set(*this, id); + id.player = player; + scripting::on_entity_player_set(*this, player); } diff --git a/src/objects/Entity.hpp b/src/objects/Entity.hpp index 960bdfc9a..f7c7c3b5d 100644 --- a/src/objects/Entity.hpp +++ b/src/objects/Entity.hpp @@ -2,16 +2,17 @@ #include "typedefs.hpp" #include "data/dv_fwd.hpp" +#include "Transform.hpp" +#include "Rigidbody.hpp" +#include "ScriptComponents.hpp" +#include #include -#include #include +#include class Entities; struct EntityDef; -struct Transform; -struct Rigidbody; -struct ScriptComponents; inline std::string COMP_TRANSFORM = "transform"; inline std::string COMP_RIGIDBODY = "rigidbody"; @@ -31,50 +32,83 @@ struct EntityId { class Entity { Entities& entities; - entityid_t id; - entt::registry& registry; - const entt::entity entity; + EntityId id; + Transform transform; + Rigidbody rigidbody; + ScriptComponents scripting; + std::unique_ptr skeleton; public: Entity( Entities& entities, - entityid_t id, - entt::registry& registry, - const entt::entity entity - ) - : entities(entities), id(id), registry(registry), entity(entity) { - } + EntityId id, + Transform transform, + Rigidbody rigidbody, + std::unique_ptr skeleton + ); + + Entity(const Entity&) = delete; + Entity& operator=(const Entity&) = delete; + + ~Entity(); dv::value serialize() const; - EntityId& getID() const; + EntityId& getID() { + return id; + } + const EntityId& getID() const { + return id; + } - bool isValid() const; + const EntityDef& getDef() const { + return id.def; + } - const EntityDef& getDef() const; + Transform& getTransform() { + return transform; + } + const Transform& getTransform() const { + return transform; + } - Transform& getTransform() const; + Rigidbody& getRigidbody() { + return rigidbody; + } + const Rigidbody& getRigidbody() const { + return rigidbody; + } - Rigidbody& getRigidbody() const; + ScriptComponents& getScripting() { + return scripting; + } + const ScriptComponents& getScripting() const { + return scripting; + } - ScriptComponents& getScripting() const; - - rigging::Skeleton* getSkeleton() const; + rigging::Skeleton* getSkeleton() { + return skeleton.get(); + } + const rigging::Skeleton* getSkeleton() const { + return skeleton.get(); + } void setRig(std::shared_ptr rigConfig); - entityid_t getUID() const; + entityid_t getUID() const { + return id.uid; + } - int64_t getPlayer() const; + int64_t getPlayer() const { + return id.player; + } - void setPlayer(int64_t id); + void setPlayer(int64_t player); void setInterpolatedPosition(const glm::vec3& position); glm::vec3 getInterpolatedPosition() const; - entt::entity getHandler() const { - return entity; - } + void setInterpolatedRotation(const glm::quat& rotation); void destroy(); }; diff --git a/src/objects/EntityDef.cpp b/src/objects/EntityDef.cpp index 54e0aefef..6c3999e98 100644 --- a/src/objects/EntityDef.cpp +++ b/src/objects/EntityDef.cpp @@ -15,4 +15,5 @@ void EntityDef::cloneTo(EntityDef& dst) { dst.stepHeight = stepHeight; dst.save = save; dst.lightingMode = lightingMode; + dst.translucent = translucent; } diff --git a/src/objects/EntityDef.hpp b/src/objects/EntityDef.hpp index 139bce48c..57b88f113 100644 --- a/src/objects/EntityDef.hpp +++ b/src/objects/EntityDef.hpp @@ -19,6 +19,8 @@ struct EntityDef { /// @brief Entity string id (with prefix included) std::string const name; + dv::value properties = nullptr; + /// @brief Component instances std::vector components; @@ -42,6 +44,9 @@ struct EntityDef { /// @brief Model lighting mode ModelLightingMode lightingMode = ModelLightingMode::SOLID; + /// @brief Render the entity in the translucent pass + bool translucent = false; + /// @brief Can the entity be interacted with cursor (on_attack, on_use) bool selectable = true; diff --git a/src/objects/Player.cpp b/src/objects/Player.cpp index 28153d635..760b14ef7 100644 --- a/src/objects/Player.cpp +++ b/src/objects/Player.cpp @@ -41,6 +41,12 @@ Player::Player( name(name), speed(speed), chosenSlot(0), + hotbarSize(glm::max( + 1, + static_cast( + level.content.getDefaults()["hotbar-size"].asInteger(10) + ) + )), position(position), inventory(std::move(inv)), eid(eid), @@ -101,7 +107,7 @@ void Player::updateSelectedEntity() { void Player::postUpdate() { auto entity = level.entities->get(eid); - if (!entity.has_value()) { + if (entity == nullptr) { return; } auto& hitbox = entity->getRigidbody().hitbox; @@ -153,13 +159,22 @@ void Player::attemptToChooseSpawnpoint() { } void Player::setChosenSlot(int index) { - chosenSlot = index; + chosenSlot = glm::clamp(index, 0, hotbarSize - 1); } int Player::getChosenSlot() const { return chosenSlot; } +void Player::setHotbarSize(int size) { + hotbarSize = glm::max(1, size); + setChosenSlot(chosenSlot); +} + +int Player::getHotbarSize() const { + return hotbarSize; +} + float Player::getSpeed() const { return speed; } diff --git a/src/objects/Player.hpp b/src/objects/Player.hpp index 54ed70023..57e7cb4b2 100644 --- a/src/objects/Player.hpp +++ b/src/objects/Player.hpp @@ -49,6 +49,7 @@ class Player : public Serializable { float speed; int chosenSlot; + int hotbarSize; glm::vec3 position; glm::vec3 spawnpoint {std::nanf(""), std::nanf(""), std::nanf("")}; std::shared_ptr inventory; @@ -96,6 +97,10 @@ public: int getChosenSlot() const; + void setHotbarSize(int size); + + int getHotbarSize() const; + float getSpeed() const; bool isSuspended() const; diff --git a/src/objects/Rigidbody.cpp b/src/objects/Rigidbody.cpp index 337bb9f67..eedb0dbc1 100644 --- a/src/objects/Rigidbody.cpp +++ b/src/objects/Rigidbody.cpp @@ -45,9 +45,7 @@ template static sensorcallback create_sensor_callback(Entities& entities) { return [&entities](auto entityid, auto index, auto otherid) { if (auto entity = entities.get(entityid)) { - if (entity->isValid()) { - callback(*entity, index, otherid); - } + callback(*entity, index, otherid); } }; } diff --git a/src/objects/Rigidbody.hpp b/src/objects/Rigidbody.hpp index fb96f138f..4a11d4525 100644 --- a/src/objects/Rigidbody.hpp +++ b/src/objects/Rigidbody.hpp @@ -4,7 +4,6 @@ #include "physics/Hitbox.hpp" #include -#include class Entities; struct EntityDef; @@ -13,9 +12,9 @@ struct Rigidbody { bool enabled = true; Hitbox hitbox; std::vector sensors; - float mass; - float elasticity; - bool selectable; + float mass = 1.0f; + float elasticity = 0.0f; + bool selectable = false; dv::value serialize(bool saveVelocity, bool saveBodySettings) const; void deserialize(const dv::value& root); diff --git a/src/objects/Transform.cpp b/src/objects/Transform.cpp index da876b81e..c398c48e7 100644 --- a/src/objects/Transform.cpp +++ b/src/objects/Transform.cpp @@ -5,6 +5,7 @@ #include "maths/util.hpp" #include +#include static debug::Logger logger("entity-transform"); diff --git a/src/objects/Transform.hpp b/src/objects/Transform.hpp index 8c49d6859..5cea5c83c 100644 --- a/src/objects/Transform.hpp +++ b/src/objects/Transform.hpp @@ -16,8 +16,8 @@ struct Transform { glm::mat4 combined; bool dirty = true; - glm::vec3 displayPos; - glm::vec3 displaySize; + glm::vec3 displayPos {}; + glm::vec3 displaySize {}; dv::value serialize() const; void deserialize(const dv::value& root); diff --git a/src/physics/BroadPhase.cpp b/src/physics/BroadPhase.cpp new file mode 100644 index 000000000..521b12804 --- /dev/null +++ b/src/physics/BroadPhase.cpp @@ -0,0 +1,209 @@ +#include "BroadPhase.hpp" +#include "collisions.hpp" + +#include + +inline constexpr size_t GRID_SCAN_RATIO = 8; + +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()); +} + +static glm::vec3 calc_nearby_reach( + const Hitbox& hitbox, float maxSolidHalfY, float budget +) { + auto ext = calc_extents(hitbox); + + glm::vec3 reach( + 0.5f, + hitbox.stepHeight * 2.0f + physics::E * 8.0f + ext.y * 0.5f + + maxSolidHalfY + 0.5f + physics::MAX_FIX * 2.0f, + 0.5f + ); + reach += ext + budget; + return reach; +} + +BroadPhase::BroadPhase( + const std::vector& hitboxes, + const std::vector& solidHitboxes, + const glm::vec3& gravity +) + : hitboxes(hitboxes), solidHitboxes(solidHitboxes), gravity(gravity) { +} + +void BroadPhase::build(float time) { + size_t count = hitboxes.size(); + nearbySolids.resize(count); + nearbyOrigins.resize(count); + nearbyBudgets.resize(count); + nearbyReaches.resize(count); + solidBudgets.resize(solidHitboxes.size()); + solidOrigins.resize(solidHitboxes.size()); + solidStamps.assign(solidHitboxes.size(), 0); + solidStamp = 0; + + 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); + solidOrigins[j] = box.position; + maxSolidHalfY = glm::max(maxSolidHalfY, calc_extents(box).y); + } + buildGrid(); + + for (size_t i = 0; i < count; i++) { + const auto& hitbox = *hitboxes[i]; + nearbyOrigins[i] = hitbox.position; + nearbyBudgets[i] = calc_move_budget(hitbox, gravity, time); + nearbyReaches[i] = + calc_nearby_reach(hitbox, maxSolidHalfY, nearbyBudgets[i]); + collectNearbySolids(i); + } + indexSolids(); +} + +void BroadPhase::update(size_t index, float time) { + auto moved = glm::abs(hitboxes[index]->position - nearbyOrigins[index]); + if (glm::max(moved.x, glm::max(moved.y, moved.z)) > nearbyBudgets[index]) { + rebuildNearbySolids(index, time); + } +} + +void BroadPhase::buildGrid() { + grid.clear(); + movedSolids.clear(); + solidMoved.assign(solidHitboxes.size(), false); + + for (uint j = 0; j < solidHitboxes.size(); j++) { + grid.insert( + j, + solidOrigins[j], + calc_extents(*solidHitboxes[j]) + solidBudgets[j] + ); + } + grid.build(); +} + +void BroadPhase::indexSolids() { + solidIndices.resize(solidHitboxes.size()); + for (size_t j = 0; j < solidHitboxes.size(); j++) { + solidIndices[j] = {solidHitboxes[j], static_cast(j)}; + } + std::sort(solidIndices.begin(), solidIndices.end()); + + hitboxSolids.resize(hitboxes.size()); + for (size_t i = 0; i < hitboxes.size(); i++) { + auto it = std::lower_bound( + solidIndices.begin(), + solidIndices.end(), + std::make_pair(hitboxes[i], 0u) + ); + bool found = it != solidIndices.end() && it->first == hitboxes[i]; + hitboxSolids[i] = found ? static_cast(it->second) : -1; + } +} + +uint BroadPhase::getSolidIndex(Hitbox* box) const { + return std::lower_bound( + solidIndices.begin(), solidIndices.end(), std::make_pair(box, 0u) + )->second; +} + +bool BroadPhase::isSolidNearby(size_t index, uint solid) const { + auto limit = nearbyReaches[index] + + calc_extents(*solidHitboxes[solid]) + solidBudgets[solid]; + auto diff = glm::abs(solidOrigins[solid] - nearbyOrigins[index]); + return diff.x <= limit.x && diff.y <= limit.y && diff.z <= limit.z; +} + +void BroadPhase::collectNearbySolids(size_t index) { + auto& solids = nearbySolids[index]; + solids.clear(); + auto testSolid = [&](uint j) { + if (isSolidNearby(index, j)) { + solids.push_back(solidHitboxes[j]); + } + }; + + size_t stamp = ++solidStamp; + candidates.clear(); + auto addCandidate = [&](uint j) { + if (solidStamps[j] != stamp) { + solidStamps[j] = stamp; + candidates.push_back(j); + } + }; + if (!grid.query(nearbyOrigins[index], nearbyReaches[index], addCandidate)) { + for (uint j = 0; j < solidHitboxes.size(); j++) { + testSolid(j); + } + return; + } + for (uint j : movedSolids) { + addCandidate(j); + } + if (candidates.size() * GRID_SCAN_RATIO > solidHitboxes.size()) { + for (uint j = 0; j < solidHitboxes.size(); j++) { + if (solidStamps[j] == stamp) { + testSolid(j); + } + } + return; + } + std::sort(candidates.begin(), candidates.end()); + for (uint j : candidates) { + testSolid(j); + } +} + +void BroadPhase::rebuildNearbySolids(size_t index, float time) { + const auto& hitbox = *hitboxes[index]; + nearbyOrigins[index] = hitbox.position; + nearbyBudgets[index] = calc_move_budget(hitbox, gravity, time); + nearbyReaches[index] = + calc_nearby_reach(hitbox, maxSolidHalfY, nearbyBudgets[index]); + + int solid = hitboxSolids[index]; + if (solid >= 0) { + solidOrigins[solid] = hitbox.position; + solidBudgets[solid] = nearbyBudgets[index]; + if (!solidMoved[solid]) { + solidMoved[solid] = true; + movedSolids.push_back(solid); + } + if (movedSolids.size() * GRID_SCAN_RATIO > solidHitboxes.size()) { + buildGrid(); + } + } + collectNearbySolids(index); + if (solid < 0) { + return; + } + auto box = solidHitboxes[solid]; + for (size_t i = 0; i < hitboxes.size(); i++) { + if (i == index || !isSolidNearby(i, solid)) { + continue; + } + auto& list = nearbySolids[i]; + auto it = std::lower_bound( + list.begin(), + list.end(), + static_cast(solid), + [this](Hitbox* other, uint value) { + return getSolidIndex(other) < value; + } + ); + if (it == list.end() || *it != box) { + list.insert(it, box); + } + } +} diff --git a/src/physics/BroadPhase.hpp b/src/physics/BroadPhase.hpp new file mode 100644 index 000000000..7b9eabbc6 --- /dev/null +++ b/src/physics/BroadPhase.hpp @@ -0,0 +1,57 @@ +#pragma once + +#include "Hitbox.hpp" +#include "SpatialGrid.hpp" + +#include "typedefs.hpp" + +#include +#include + +class BroadPhase { +public: + BroadPhase( + const std::vector& hitboxes, + const std::vector& solidHitboxes, + const glm::vec3& gravity + ); + + void build(float time); + + void update(size_t index, float time); + + const std::vector& getNearbySolids(size_t index) const { + return nearbySolids[index]; + } +private: + const std::vector& hitboxes; + const std::vector& solidHitboxes; + glm::vec3 gravity; + SpatialGrid grid; + std::vector> nearbySolids; + std::vector nearbyOrigins; + std::vector nearbyBudgets; + std::vector nearbyReaches; + std::vector solidOrigins; + std::vector solidBudgets; + std::vector candidates; + std::vector solidStamps; + std::vector movedSolids; + std::vector solidMoved; + std::vector> solidIndices; + std::vector hitboxSolids; + size_t solidStamp = 0; + float maxSolidHalfY = 0.0f; + + void buildGrid(); + + void indexSolids(); + + uint getSolidIndex(Hitbox* box) const; + + bool isSolidNearby(size_t index, uint solid) const; + + void collectNearbySolids(size_t index); + + void rebuildNearbySolids(size_t index, float time); +}; diff --git a/src/physics/Hitbox.hpp b/src/physics/Hitbox.hpp index 91cabb2b3..01e657236 100644 --- a/src/physics/Hitbox.hpp +++ b/src/physics/Hitbox.hpp @@ -73,6 +73,9 @@ struct Hitbox { glm::vec3 prevPosition {}; glm::vec3 prevVelocity {}; bool prevGrounded = false; + float substepTime = 0.0f; + uint doneSubsteps = 0; + uint nextSubstep = 0; static inline constexpr float TELEPORT_THRESOLD_SQR = 0.5f; diff --git a/src/physics/PhysicsSolver.cpp b/src/physics/PhysicsSolver.cpp index 1b32a6ae5..8ee956088 100644 --- a/src/physics/PhysicsSolver.cpp +++ b/src/physics/PhysicsSolver.cpp @@ -1,441 +1,20 @@ #include "PhysicsSolver.hpp" #include "Hitbox.hpp" +#include "collisions.hpp" +#include "scheduling.hpp" +#include "sensors.hpp" -#include "maths/aabb.hpp" -#include "voxels/Block.hpp" #include "voxels/GlobalChunks.hpp" -#include "voxels/voxel.hpp" -#include "objects/Entities.hpp" #include "debug/Logger.hpp" #include -#define GLM_ENABLE_EXPERIMENTAL -#include - -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"); PhysicsSolver::PhysicsSolver(const GlobalChunks& chunks, glm::vec3 gravity) - : chunks(chunks), gravity(std::move(gravity)) { -} - -static glm::vec3 calc_collsion_velocity_result( - const Hitbox& a, const Hitbox& b -) { - const auto& vA = a.velocity; - const auto& vB = b.velocity; - if (glm::isinf(a.mass)) { - return vA; - } - if (glm::isinf(b.mass)) { - return vB - a.elasticity * (vA - vB); - } - const auto& mA = a.mass; - const auto& mB = b.mass; - return (mA * vA + mB * vB + a.elasticity * mB * (vB - vA)) / (mA + mB); -} - -static float calc_step_height( - const GlobalChunks& chunks, - const glm::vec3& pos, - const glm::vec3& half, - float stepHeight -) { - AABB aabb(-half, +half); - aabb.scale(glm::vec3(1.0f - E * 2, 1.0f, 1.0f - E * 2)); - aabb = aabb + pos + glm::vec3(0.0f, stepHeight, 0.0f); - if (stepHeight <= 0.0f) { - return stepHeight; - } - for (int ix = 0; ix <= glm::ceil((half.x - E) * 2); ix++) { - float x = (pos.x - half.x) + ix; - for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { - float z = (pos.z - half.z) + iz; - if (chunks.isObstacleAt(x, pos.y + half.y + stepHeight, z, aabb)) { - return 0.0f; - } - } - } - return stepHeight; -} - -// todo: reduce code duplication - -template -static void calc_collision( - Hitbox& hitbox, - const GlobalChunks& chunks, - const std::vector& solidHitboxes, - const glm::vec3& half, - float stepHeight -) { - auto& pos = hitbox.position; - auto& vel = hitbox.velocity; - - glm::vec3 offset(0.0f, stepHeight + E, 0.0f); - for (auto box : solidHitboxes) { - if (glm::distance2(box->position, pos) < E) { - continue; - } - auto boxhalf = box->getHalfSize(); - auto aabb = AABB(pos - half, pos + half); - glm::vec3 scale(1.0f); - scale[nz] = 1.0f - E * 8.0f; - scale[ny] = 1.0f - E * 2.0f; - aabb.scale(scale); - aabb = aabb + offset; - aabb.b.y -= stepHeight + E * 2; - - if ((box->position[nx] - pos[nx]) * sign <= 0.0f || !box->getAABB().intersects(aabb)) { - continue; - } - - float newnegx = box->position[nx] - boxhalf[nx] - half[nx]; - float newposx = box->position[nx] + boxhalf[nx] + half[nx]; - float newx; - if ((glm::abs(newnegx - pos[nx]) - glm::abs(newposx - pos[nx]))*sign < 0.0f) { - newx = sign > 0 ? newnegx : newposx; - } else { - continue; - } - if ((pos[nx] - newx) * sign > 0.0f && glm::abs(pos[nx] - newx) < MAX_FIX) { - auto velA = calc_collsion_velocity_result(hitbox, *box); - auto velB = calc_collsion_velocity_result(*box, hitbox); - if ((vel[nx] - box->velocity[nx]) * sign > 0.0f) { - vel[nx] = velA[nx]; - box->velocity[nx] = velB[nx]; - } - pos[nx] = newx; - } - } - if (vel[nx] * sign <= 0.0f && hitbox.groundVelocity[nx] * sign <= 0.0f) { - return; - } - for (int iy = 0; iy <= glm::ceil(((half - offset * 0.5f)[ny] - E) * 2); iy++) { - glm::vec3 coord; - coord[ny] = ((pos + offset)[ny] - half[ny] + E) + iy; - for (int iz = 0; iz <= glm::ceil((half[nz] - E) * 2); iz++) { - coord[nz] = (pos[nz] - half[nz] + E) + iz; - coord[nx] = pos[nx] + (half[nx] + E * 2) * sign; - - auto aabb = AABB(pos - half, pos + half); - glm::vec3 scale(1.0f); - scale[nz] = 1.0f - E * 2.0f; - aabb.scale(scale); - aabb = aabb + offset; - aabb.b.y -= stepHeight + E * 2; - - if (const auto obstacle = chunks.isObstacleAt(coord.x, coord.y, coord.z, aabb)) { - float newx = std::floor(coord[nx]) - half[nx] * sign + - (sign > 0 ? obstacle->min() : obstacle->max())[nx]; - if ((pos[nx] - newx) * sign > 0.0f && glm::abs(pos[nx] - newx) < MAX_FIX) { - vel[nx] = -hitbox.elasticity * vel[nx]; - pos[nx] = newx; - } - return; - } - } - } -} - -bool PhysicsSolver::calcCollisionNegY( - Hitbox& hitbox, - const glm::vec3& half, - float dt, - const std::vector& solids -) { - auto& pos = hitbox.position; - auto& vel = hitbox.velocity; - - for (auto box : solids) { - if (glm::distance2(box->position, pos) < E) { - continue; - } - auto aabb = AABB(pos - half, pos + half); - glm::vec3 scale(1.0f); - scale.x = 1.0f - E * 4.0f; - scale.z = 1.0f - E * 4.0f; - aabb.scale(scale); - - auto boxhalf = box->getHalfSize(); - if (box->position.y < pos.y && box->getAABB().intersects(aabb)) { - float newy = box->position.y + boxhalf.y + half.y; - if (pos.y < newy && glm::abs(pos.y - newy) < boxhalf.y) { - pos.y = newy; - } - - auto velA = calc_collsion_velocity_result(hitbox, *box); - auto velB = calc_collsion_velocity_result(*box, hitbox); - - hitbox.groundVelocity = (box->position - box->prevPosition) / dt; - if (vel.y < hitbox.groundVelocity.y) { - vel.y = velA.y; - box->velocity.y = velB.y; - if (hitbox.groundMaterial.empty() && !box->material.empty()) { - hitbox.groundMaterial = box->material; - } - return true; - } - } - } - if (vel.y >= 0.0f) { - return false; - } - for (int ix = 0; ix <= glm::ceil((half.x - E) * 2); ix++) { - glm::vec3 coord; - coord.x = (pos.x - half.x + E) + ix; - for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { - coord.z = (pos.z - half.z + E) + iz; - coord.y = pos.y - half.y - E * 2; - - auto aabb = AABB(pos - half, pos + half); - glm::vec3 scale(1.0f); - scale.x = 1.0f - E * 4.0f; - scale.z = 1.0f - E * 4.0f; - aabb.scale(scale); - - if (const auto obstacle = - chunks.isObstacleAt(coord.x, coord.y, coord.z, aabb)) { - float newy = std::floor(coord.y) + half.y + obstacle->max().y; - - if (newy >= pos.y) { - vel.y = -hitbox.elasticity * vel.y; - pos.y = newy; - } - hitbox.groundVelocity = {}; - return true; - } - } - } - return false; -} - -void PhysicsSolver::calcCollisions( - Hitbox& hitbox, - glm::vec3& vel, - glm::vec3& pos, - const glm::vec3& half, - float stepHeight, - float dt, - const std::vector& solids -) { - stepHeight = calc_step_height(chunks, pos, half, stepHeight); - - auto prevPos = pos; - - 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, solids, half, stepHeight); - calc_collision<2, 1, 0, 1>(hitbox, chunks, solids, half, stepHeight); - pos.x = xpos; - - if (calcCollisionNegY(hitbox, half, dt, solids)) { - hitbox.grounded = true; - } - - if (vel.y > 0.0f){ - AABB boxAABB = AABB(-half, +half); - boxAABB.scale(glm::vec3(1.0f - E * 4, 1.0f + E * 2, 1.0f - E * 4)); - boxAABB = boxAABB.translated(pos); - - for (int ix = 0; ix <= glm::ceil((half.x - E) * 2); ix++) { - float x = (pos.x - half.x + E) + ix; - for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { - float z = (pos.z - half.z + E) + iz; - float y = (pos.y + half.y + E) - E; - if (auto aabb = chunks.isObstacleAt(x, y, z, boxAABB)) { - float newy = std::floor(y) - half.y + aabb->min().y - E; - if (pos.y >= newy) { - vel.y = -hitbox.elasticity * vel.y; - pos.y = newy; - } - break; - } - } - } - for (auto box : solids) { - if (glm::distance2(box->position, pos) < E) { - continue; - } - auto boxhalf = box->getHalfSize(); - if (box->position.y > pos.y && box->getAABB().intersects(boxAABB)) { - float newy = box->position.y - boxhalf.y - half.y; - if (pos.y > newy && glm::abs(pos.y - newy) < 0.5f) { - pos.y = newy; - } - auto velA = calc_collsion_velocity_result(hitbox, *box); - auto velB = calc_collsion_velocity_result(*box, hitbox); - if (vel.y > hitbox.groundVelocity.y) { - vel.y = velA.y; - box->velocity.y = velB.y; - break; - } - } - } - } - - // step on - if (stepHeight > 0.0 && vel.y <= 0.0f) { - AABB boxAABB = AABB(pos - half, pos + half); - boxAABB.scale(glm::vec3(1.0f - E * 4.0f, 1.0f - E * 2, 1.0f - E * 4.0f)); - for (int ix = 0; ix <= glm::ceil((half.x - E) * 2); ix++) { - float x = (pos.x - half.x) + ix; - for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { - float z = (pos.z - half.z) + iz; - float y = (pos.y - half.y + E) + E; - if (auto aabb = chunks.isObstacleAt(x, y, z, boxAABB)) { - if (vel.y < 0.0f) { - vel.y = 0.0f; - } - float newy = std::floor(y) + aabb->max().y + half.y; - if (std::abs(newy - pos.y) <= stepHeight) { - pos.y = newy; - } - break; - } - } - } - for (auto box : solids) { - if (glm::distance2(box->position, pos) < E) { - continue; - } - auto boxhalf = box->getHalfSize(); - if (box->getAABB().intersects(boxAABB)) { - vel.y = 0.0f; - float newy = box->position.y + boxhalf.y + half.y; - if (std::abs(newy - pos.y) <= stepHeight + E * 4) { - pos.y = newy; - } - } - } - } -} - -void PhysicsSolver::calcSubstep( - Hitbox& hitbox, - glm::vec3& vel, - glm::vec3& pos, - float dt, - const std::vector& solids -) { - auto initpos = pos; - auto half = hitbox.getHalfSize(); - float gravityScale = hitbox.gravityScale; - - if (hitbox.type == BodyType::DYNAMIC) { - calcCollisions( - hitbox, - vel, - pos, - half, - (hitbox.prevGrounded && gravityScale > 0.0f) ? hitbox.stepHeight - : 0.0f, - dt, - solids - ); - } - - vel += gravity * dt * gravityScale; - pos += vel * dt + gravity * gravityScale * dt * dt * 0.5f; - - // crouching - if (!hitbox.crouching || !hitbox.grounded) { - return; - } - float y = (pos.y - half.y - E); - for (int axis = 0; axis <= 2; axis += 2) { - hitbox.grounded = false; - - auto checkPos = pos; - checkPos.x = axis != 0 ? initpos.x : pos.x; - checkPos.z = axis == 0 ? initpos.z : pos.z; - - AABB boxAABB(checkPos - half, checkPos + half); - boxAABB.scale(glm::vec3(1.0f - E * 4, 1.5f, 1.0f - E * 4)); - for (int ix = 0; ix <= glm::ceil((half.x - E) * 2); ix++) { - float x = (pos.x - half.x + E) + ix; - for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++){ - float z = (pos.z - half.z + E) + iz; - if (chunks.isObstacleAt(x, y, z, boxAABB)){ - hitbox.grounded = true; - break; - } - } - } - for (auto box : solids) { - if (glm::distance2(box->position, pos) < E) { - continue; - } - if (box->position.y < pos.y && box->getAABB().intersects(boxAABB)) { - hitbox.grounded = true; - break; - } - } - if (!hitbox.grounded) { - pos[axis] = initpos[axis]; - vel[axis] = 0.0f; - } - } - 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]); - } - } - } + : chunks(chunks), + gravity(gravity), + broadPhase(hitboxes, solidHitboxes, gravity) { } void PhysicsSolver::step( @@ -447,34 +26,44 @@ void PhysicsSolver::step( hitbox->grounded = false; hitbox->prevVelocity = hitbox->velocity; } - - float dt = delta / static_cast(substeps); - findNearbySolids(delta); - int rebuildsLeft = MAX_NEARBY_REBUILDS; + float dt = delta / static_cast(substeps); + broadPhase.build(delta); + for (auto hitbox : hitboxes) { + physics::schedule_substep(*hitbox, gravity, 0, substeps, dt); + } + for (uint i = 0; i < substeps; i++) { 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, - rebuildsLeft >= 0 ? nearbySolids[j] : solidHitboxes - ); - if (rebuildsLeft < 0) { + if (hitbox->nextSubstep > i) { 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(substeps - i)); + hitbox->prevPosition = hitbox->position; + hitbox->substepTime = + dt * static_cast(i + 1 - hitbox->doneSubsteps); + while (hitbox->doneSubsteps <= i) { + uint left = i + 1 - hitbox->doneSubsteps; + uint skip = + physics::calc_substep_stride(*hitbox, gravity, dt, left) - + 1; + if (skip > 0) { + physics::integrate(*hitbox, gravity, dt, skip); + hitbox->doneSubsteps += skip; } + physics::calc_substep( + *hitbox, + {this->chunks, + broadPhase.getNearbySolids(j), + gravity, + dt, + i + 1} + ); + hitbox->doneSubsteps++; + + broadPhase.update(j, dt * static_cast(substeps - i)); } + physics::schedule_substep(*hitbox, gravity, i + 1, substeps, dt); } } @@ -496,37 +85,8 @@ void PhysicsSolver::step( if (!hitbox->grounded) { hitbox->groundVelocity *= 1.0f - delta; } - - updateSensors(*hitbox); - } -} -void PhysicsSolver::updateSensors(Hitbox& hitbox) { - auto aabb = hitbox.getAABB(); - - for (size_t i = 0; i < sensors.size(); i++) { - auto& sensor = *sensors[i]; - if (sensor.entity == hitbox.entity) { - continue; - } - bool triggered = false; - switch (sensor.type) { - case SensorType::AABB: - triggered = aabb.intersects(sensor.calculated.aabb); - break; - case SensorType::RADIUS: - triggered = glm::distance2( - hitbox.position, glm::vec3(sensor.calculated.radial)) - < sensor.calculated.radial.w; - break; - } - if (!triggered) { - continue; - } - if (sensor.prevEntered.find(hitbox.entity) == sensor.prevEntered.end()) { - sensor.enterCallback(sensor.entity, sensor.index, hitbox.entity); - } - sensor.nextEntered.insert(hitbox.entity); + physics::update_sensors(*hitbox, sensors); } } diff --git a/src/physics/PhysicsSolver.hpp b/src/physics/PhysicsSolver.hpp index 32edfcaf1..124564876 100644 --- a/src/physics/PhysicsSolver.hpp +++ b/src/physics/PhysicsSolver.hpp @@ -1,6 +1,7 @@ #pragma once #include "Hitbox.hpp" +#include "BroadPhase.hpp" #include "typedefs.hpp" #include "voxels/voxel.hpp" @@ -38,37 +39,5 @@ private: std::vector sensors; std::vector solidHitboxes; std::vector hitboxes; - std::vector> nearbySolids; - std::vector nearbyOrigins; - std::vector nearbyBudgets; - std::vector solidBudgets; - - void findNearbySolids(float time); - - void calcCollisions( - Hitbox& hitbox, - glm::vec3& vel, - glm::vec3& pos, - const glm::vec3& half, - float stepHeight, - float dt, - const std::vector& solids - ); - - void calcSubstep( - Hitbox& hitbox, - glm::vec3& vel, - glm::vec3& pos, - float dt, - const std::vector& solids - ); - - bool calcCollisionNegY( - Hitbox& hitbox, - const glm::vec3& half, - float dt, - const std::vector& solids - ); - - void updateSensors(Hitbox& hitbox); + BroadPhase broadPhase; }; diff --git a/src/physics/SpatialGrid.cpp b/src/physics/SpatialGrid.cpp new file mode 100644 index 000000000..ad686500f --- /dev/null +++ b/src/physics/SpatialGrid.cpp @@ -0,0 +1,70 @@ +#include "SpatialGrid.hpp" + +#include + +inline constexpr float GRID_CELL_SIZE = 4.0f; +inline constexpr float GRID_PADDING = 0.01f; +inline constexpr float GRID_MAX_COORD = 1e9f; +inline constexpr int GRID_MAX_CELLS = 64; + +void SpatialGrid::clear() { + cells.clear(); + oversized.clear(); +} + +void SpatialGrid::insert( + uint id, const glm::vec3& center, const glm::vec3& extents +) { + glm::ivec2 min, max; + if (!calcRange(center, extents, min, max)) { + oversized.push_back(id); + return; + } + for (int x = min.x; x <= max.x; x++) { + for (int z = min.y; z <= max.y; z++) { + cells.emplace_back(calcKey(x, z), id); + } + } +} + +void SpatialGrid::build() { + std::sort(cells.begin(), cells.end()); +} + +uint64_t SpatialGrid::calcKey(int x, int z) { + return (static_cast(static_cast(x)) << 32) | + static_cast(z); +} + +bool SpatialGrid::calcRange( + const glm::vec3& center, + const glm::vec3& extents, + glm::ivec2& min, + glm::ivec2& max +) { + glm::vec2 c(center.x, center.z); + glm::vec2 e = glm::vec2(extents.x, extents.z) + GRID_PADDING; + glm::vec2 a = glm::floor((c - e) / GRID_CELL_SIZE); + glm::vec2 b = glm::floor((c + e) / GRID_CELL_SIZE); + 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)) { + return false; + } + if ((b.x - a.x + 1.0f) * (b.y - a.y + 1.0f) > GRID_MAX_CELLS) { + return false; + } + min = glm::ivec2(a); + max = glm::ivec2(b); + return true; +} + +std::vector::const_iterator SpatialGrid::findCell( + uint64_t key +) const { + return std::lower_bound( + cells.begin(), + cells.end(), + key, + [](const Cell& cell, uint64_t value) { return cell.first < value; } + ); +} diff --git a/src/physics/SpatialGrid.hpp b/src/physics/SpatialGrid.hpp new file mode 100644 index 000000000..d35e94786 --- /dev/null +++ b/src/physics/SpatialGrid.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include "typedefs.hpp" + +#include +#include +#include + +class SpatialGrid { +public: + void clear(); + + void insert(uint id, const glm::vec3& center, const glm::vec3& extents); + + void build(); + + template + bool query( + const glm::vec3& center, const glm::vec3& extents, const Func& func + ) const { + glm::ivec2 min, max; + if (!calcRange(center, extents, min, max)) { + return false; + } + for (uint id : oversized) { + func(id); + } + for (int x = min.x; x <= max.x; x++) { + for (int z = min.y; z <= max.y; z++) { + uint64_t key = calcKey(x, z); + for (auto it = findCell(key); + it != cells.end() && it->first == key; + ++it) { + func(it->second); + } + } + } + return true; + } +private: + using Cell = std::pair; + + std::vector cells; + std::vector oversized; + + static uint64_t calcKey(int x, int z); + + static bool calcRange( + const glm::vec3& center, + const glm::vec3& extents, + glm::ivec2& min, + glm::ivec2& max + ); + + std::vector::const_iterator findCell(uint64_t key) const; +}; diff --git a/src/physics/collisions.cpp b/src/physics/collisions.cpp new file mode 100644 index 000000000..bac65c9e5 --- /dev/null +++ b/src/physics/collisions.cpp @@ -0,0 +1,385 @@ +#include "collisions.hpp" +#include "scheduling.hpp" + +#include "maths/aabb.hpp" +#include "voxels/GlobalChunks.hpp" + +#define GLM_ENABLE_EXPERIMENTAL +#include + +using namespace physics; + +static glm::vec3 calc_collsion_velocity_result( + const Hitbox& a, const Hitbox& b +) { + const auto& vA = a.velocity; + const auto& vB = b.velocity; + if (glm::isinf(a.mass)) { + return vA; + } + if (glm::isinf(b.mass)) { + return vB - a.elasticity * (vA - vB); + } + const auto& mA = a.mass; + const auto& mB = b.mass; + return (mA * vA + mB * vB + a.elasticity * mB * (vB - vA)) / (mA + mB); +} + +static float calc_step_height( + const GlobalChunks& chunks, + const glm::vec3& pos, + const glm::vec3& half, + float stepHeight +) { + AABB aabb(-half, +half); + aabb.scale(glm::vec3(1.0f - E * 2, 1.0f, 1.0f - E * 2)); + aabb = aabb + pos + glm::vec3(0.0f, stepHeight, 0.0f); + if (stepHeight <= 0.0f) { + return stepHeight; + } + for (int ix = 0; ix <= glm::ceil((half.x - E) * 2); ix++) { + float x = (pos.x - half.x) + ix; + for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { + float z = (pos.z - half.z) + iz; + if (chunks.isObstacleAt(x, pos.y + half.y + stepHeight, z, aabb)) { + return 0.0f; + } + } + } + return stepHeight; +} + +// todo: reduce code duplication + +template +static void calc_collision( + Hitbox& hitbox, + const GlobalChunks& chunks, + const std::vector& solidHitboxes, + const glm::vec3& half, + float stepHeight, + uint wakeSubstep +) { + auto& pos = hitbox.position; + auto& vel = hitbox.velocity; + + glm::vec3 offset(0.0f, stepHeight + E, 0.0f); + for (auto box : solidHitboxes) { + if (glm::distance2(box->position, pos) < E) { + continue; + } + auto boxhalf = box->getHalfSize(); + auto aabb = AABB(pos - half, pos + half); + glm::vec3 scale(1.0f); + scale[nz] = 1.0f - E * 8.0f; + scale[ny] = 1.0f - E * 2.0f; + aabb.scale(scale); + aabb = aabb + offset; + aabb.b.y -= stepHeight + E * 2; + + if ((box->position[nx] - pos[nx]) * sign <= 0.0f || !box->getAABB().intersects(aabb)) { + continue; + } + + float newnegx = box->position[nx] - boxhalf[nx] - half[nx]; + float newposx = box->position[nx] + boxhalf[nx] + half[nx]; + float newx; + if ((glm::abs(newnegx - pos[nx]) - glm::abs(newposx - pos[nx]))*sign < 0.0f) { + newx = sign > 0 ? newnegx : newposx; + } else { + continue; + } + if ((pos[nx] - newx) * sign > 0.0f && glm::abs(pos[nx] - newx) < MAX_FIX) { + auto velA = calc_collsion_velocity_result(hitbox, *box); + auto velB = calc_collsion_velocity_result(*box, hitbox); + if ((vel[nx] - box->velocity[nx]) * sign > 0.0f) { + vel[nx] = velA[nx]; + push_body(*box, nx, velB[nx], wakeSubstep); + } + pos[nx] = newx; + } + } + if (vel[nx] * sign <= 0.0f && hitbox.groundVelocity[nx] * sign <= 0.0f) { + return; + } + for (int iy = 0; iy <= glm::ceil(((half - offset * 0.5f)[ny] - E) * 2); iy++) { + glm::vec3 coord; + coord[ny] = ((pos + offset)[ny] - half[ny] + E) + iy; + for (int iz = 0; iz <= glm::ceil((half[nz] - E) * 2); iz++) { + coord[nz] = (pos[nz] - half[nz] + E) + iz; + coord[nx] = pos[nx] + (half[nx] + E * 2) * sign; + + auto aabb = AABB(pos - half, pos + half); + glm::vec3 scale(1.0f); + scale[nz] = 1.0f - E * 2.0f; + aabb.scale(scale); + aabb = aabb + offset; + aabb.b.y -= stepHeight + E * 2; + + if (const auto obstacle = chunks.isObstacleAt(coord.x, coord.y, coord.z, aabb)) { + float newx = std::floor(coord[nx]) - half[nx] * sign + + (sign > 0 ? obstacle->min() : obstacle->max())[nx]; + if ((pos[nx] - newx) * sign > 0.0f && glm::abs(pos[nx] - newx) < MAX_FIX) { + vel[nx] = -hitbox.elasticity * vel[nx]; + pos[nx] = newx; + } + return; + } + } + } +} + +static bool calc_collision_neg_y( + Hitbox& hitbox, const glm::vec3& half, const CollisionContext& ctx +) { + const auto& chunks = ctx.chunks; + const auto& solids = ctx.solids; + auto& pos = hitbox.position; + auto& vel = hitbox.velocity; + + for (auto box : solids) { + if (glm::distance2(box->position, pos) < E) { + continue; + } + auto aabb = AABB(pos - half, pos + half); + glm::vec3 scale(1.0f); + scale.x = 1.0f - E * 4.0f; + scale.z = 1.0f - E * 4.0f; + aabb.scale(scale); + + auto boxhalf = box->getHalfSize(); + if (box->position.y < pos.y && box->getAABB().intersects(aabb)) { + float newy = box->position.y + boxhalf.y + half.y; + if (pos.y < newy && glm::abs(pos.y - newy) < boxhalf.y) { + pos.y = newy; + } + + auto velA = calc_collsion_velocity_result(hitbox, *box); + auto velB = calc_collsion_velocity_result(*box, hitbox); + + float boxdt = box->substepTime > 0.0f ? box->substepTime : ctx.dt; + hitbox.groundVelocity = (box->position - box->prevPosition) / boxdt; + if (vel.y < hitbox.groundVelocity.y) { + vel.y = velA.y; + push_body(*box, 1, velB.y, ctx.wakeSubstep); + if (hitbox.groundMaterial.empty() && !box->material.empty()) { + hitbox.groundMaterial = box->material; + } + return true; + } + } + } + if (vel.y >= 0.0f) { + return false; + } + for (int ix = 0; ix <= glm::ceil((half.x - E) * 2); ix++) { + glm::vec3 coord; + coord.x = (pos.x - half.x + E) + ix; + for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { + coord.z = (pos.z - half.z + E) + iz; + coord.y = pos.y - half.y - E * 2; + + auto aabb = AABB(pos - half, pos + half); + glm::vec3 scale(1.0f); + scale.x = 1.0f - E * 4.0f; + scale.z = 1.0f - E * 4.0f; + aabb.scale(scale); + + if (const auto obstacle = + chunks.isObstacleAt(coord.x, coord.y, coord.z, aabb)) { + float newy = std::floor(coord.y) + half.y + obstacle->max().y; + + if (newy >= pos.y) { + vel.y = -hitbox.elasticity * vel.y; + pos.y = newy; + } + hitbox.groundVelocity = {}; + return true; + } + } + } + return false; +} + +static void calc_collisions( + Hitbox& hitbox, + const glm::vec3& half, + float stepHeight, + const CollisionContext& ctx +) { + const auto& chunks = ctx.chunks; + const auto& solids = ctx.solids; + uint wakeSubstep = ctx.wakeSubstep; + auto& pos = hitbox.position; + auto& vel = hitbox.velocity; + + stepHeight = calc_step_height(chunks, pos, half, stepHeight); + + auto prevPos = pos; + + calc_collision<0, 1, 2, -1>( + hitbox, chunks, solids, half, stepHeight, wakeSubstep + ); + calc_collision<0, 1, 2, 1>( + hitbox, chunks, solids, half, stepHeight, wakeSubstep + ); + + float xpos = pos.x; + pos.x = prevPos.x; + + calc_collision<2, 1, 0, -1>( + hitbox, chunks, solids, half, stepHeight, wakeSubstep + ); + calc_collision<2, 1, 0, 1>( + hitbox, chunks, solids, half, stepHeight, wakeSubstep + ); + pos.x = xpos; + + if (calc_collision_neg_y(hitbox, half, ctx)) { + hitbox.grounded = true; + } + + if (vel.y > 0.0f){ + AABB boxAABB = AABB(-half, +half); + boxAABB.scale(glm::vec3(1.0f - E * 4, 1.0f + E * 2, 1.0f - E * 4)); + boxAABB = boxAABB.translated(pos); + + for (int ix = 0; ix <= glm::ceil((half.x - E) * 2); ix++) { + float x = (pos.x - half.x + E) + ix; + for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { + float z = (pos.z - half.z + E) + iz; + float y = (pos.y + half.y + E) - E; + if (auto aabb = chunks.isObstacleAt(x, y, z, boxAABB)) { + float bottom = std::floor(y) + aabb->min().y; + float newy = bottom - half.y - E; + if (pos.y >= newy && pos.y - half.y < bottom) { + vel.y = -hitbox.elasticity * vel.y; + pos.y = newy; + } + break; + } + } + } + for (auto box : solids) { + if (glm::distance2(box->position, pos) < E) { + continue; + } + auto boxhalf = box->getHalfSize(); + if (box->position.y > pos.y && box->getAABB().intersects(boxAABB)) { + float newy = box->position.y - boxhalf.y - half.y; + if (pos.y > newy && glm::abs(pos.y - newy) < 0.5f) { + pos.y = newy; + } + auto velA = calc_collsion_velocity_result(hitbox, *box); + auto velB = calc_collsion_velocity_result(*box, hitbox); + if (vel.y > hitbox.groundVelocity.y) { + vel.y = velA.y; + push_body(*box, 1, velB.y, wakeSubstep); + break; + } + } + } + } + + // step on + if (stepHeight > 0.0 && vel.y <= 0.0f) { + AABB boxAABB = AABB(pos - half, pos + half); + boxAABB.scale(glm::vec3(1.0f - E * 4.0f, 1.0f - E * 2, 1.0f - E * 4.0f)); + for (int ix = 0; ix <= glm::ceil((half.x - E) * 2); ix++) { + float x = (pos.x - half.x) + ix; + for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++) { + float z = (pos.z - half.z) + iz; + float y = (pos.y - half.y + E) + E; + if (auto aabb = chunks.isObstacleAt(x, y, z, boxAABB)) { + if (vel.y < 0.0f) { + vel.y = 0.0f; + } + float newy = std::floor(y) + aabb->max().y + half.y; + if (std::abs(newy - pos.y) <= stepHeight) { + pos.y = newy; + } + break; + } + } + } + for (auto box : solids) { + if (glm::distance2(box->position, pos) < E) { + continue; + } + auto boxhalf = box->getHalfSize(); + if (box->getAABB().intersects(boxAABB)) { + vel.y = 0.0f; + float newy = box->position.y + boxhalf.y + half.y; + if (std::abs(newy - pos.y) <= stepHeight + E * 4) { + pos.y = newy; + } + } + } + } +} + +void physics::calc_substep(Hitbox& hitbox, const CollisionContext& ctx) { + const auto& chunks = ctx.chunks; + const auto& solids = ctx.solids; + const auto& gravity = ctx.gravity; + float dt = ctx.dt; + auto& pos = hitbox.position; + auto& vel = hitbox.velocity; + + auto initpos = pos; + auto half = hitbox.getHalfSize(); + float gravityScale = hitbox.gravityScale; + + if (hitbox.type == BodyType::DYNAMIC) { + calc_collisions( + hitbox, + half, + (hitbox.prevGrounded && gravityScale > 0.0f) ? hitbox.stepHeight + : 0.0f, + ctx + ); + } + + vel += gravity * dt * gravityScale; + pos += vel * dt + gravity * gravityScale * dt * dt * 0.5f; + + // crouching + if (!hitbox.crouching || !hitbox.grounded) { + return; + } + float y = (pos.y - half.y - E); + for (int axis = 0; axis <= 2; axis += 2) { + hitbox.grounded = false; + + auto checkPos = pos; + checkPos.x = axis != 0 ? initpos.x : pos.x; + checkPos.z = axis == 0 ? initpos.z : pos.z; + + AABB boxAABB(checkPos - half, checkPos + half); + boxAABB.scale(glm::vec3(1.0f - E * 4, 1.5f, 1.0f - E * 4)); + for (int ix = 0; ix <= glm::ceil((half.x - E) * 2); ix++) { + float x = (pos.x - half.x + E) + ix; + for (int iz = 0; iz <= glm::ceil((half.z - E) * 2); iz++){ + float z = (pos.z - half.z + E) + iz; + if (chunks.isObstacleAt(x, y, z, boxAABB)){ + hitbox.grounded = true; + break; + } + } + } + for (auto box : solids) { + if (glm::distance2(box->position, pos) < E) { + continue; + } + if (box->position.y < pos.y && box->getAABB().intersects(boxAABB)) { + hitbox.grounded = true; + break; + } + } + if (!hitbox.grounded) { + pos[axis] = initpos[axis]; + vel[axis] = 0.0f; + } + } + hitbox.grounded = true; +} diff --git a/src/physics/collisions.hpp b/src/physics/collisions.hpp new file mode 100644 index 000000000..9cbee38af --- /dev/null +++ b/src/physics/collisions.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include "Hitbox.hpp" + +#include "typedefs.hpp" + +#include +#include + +class GlobalChunks; + +namespace physics { + inline constexpr float E = 0.03f; + inline constexpr float MAX_FIX = 0.1f; + + struct CollisionContext { + const GlobalChunks& chunks; + const std::vector& solids; + glm::vec3 gravity; + float dt; + uint wakeSubstep; + }; + + void calc_substep(Hitbox& hitbox, const CollisionContext& ctx); +} diff --git a/src/physics/scheduling.cpp b/src/physics/scheduling.cpp new file mode 100644 index 000000000..4d6400f73 --- /dev/null +++ b/src/physics/scheduling.cpp @@ -0,0 +1,45 @@ +#include "scheduling.hpp" + +inline constexpr float MAX_SUBSTEP_MOVE = 0.03f; +inline constexpr float MAX_SUBSTEP_SINK = 0.015f; + +uint physics::calc_substep_stride( + const Hitbox& hitbox, const glm::vec3& gravity, float dt, uint left +) { + if (hitbox.crouching) { + return 1; + } + float speed = glm::length(hitbox.velocity); + float accel = glm::length(gravity) * glm::abs(hitbox.gravityScale) * 1.5f; + float time; + if (accel > 0.0f) { + time = (glm::sqrt(speed * speed + 4.0f * accel * MAX_SUBSTEP_MOVE) - + speed) / (2.0f * accel); + time = glm::min(time, glm::sqrt(MAX_SUBSTEP_SINK / accel)); + } else if (speed > 0.0f) { + time = MAX_SUBSTEP_MOVE / speed; + } else { + return left; + } + float stride = glm::floor(time / dt); + if (stride >= static_cast(left)) { + return left; + } + return glm::max(1u, static_cast(stride)); +} + +void physics::schedule_substep( + Hitbox& hitbox, const glm::vec3& gravity, uint done, uint substeps, float dt +) { + hitbox.doneSubsteps = done; + if (done >= substeps) { + hitbox.nextSubstep = substeps; + return; + } + uint left = substeps - done; + if (left > 1) { + left--; + } + hitbox.nextSubstep = + done + calc_substep_stride(hitbox, gravity, dt, left) - 1; +} diff --git a/src/physics/scheduling.hpp b/src/physics/scheduling.hpp new file mode 100644 index 000000000..1caf69ac5 --- /dev/null +++ b/src/physics/scheduling.hpp @@ -0,0 +1,41 @@ +#pragma once + +#include "Hitbox.hpp" + +#include "typedefs.hpp" + +#include +#include + +namespace physics { + inline void integrate( + Hitbox& box, const glm::vec3& gravity, float dt, uint substeps + ) { + float n = static_cast(substeps); + auto accel = gravity * box.gravityScale; + box.position += box.velocity * (dt * n) + + accel * (dt * dt * n * (n + 2.0f) * 0.5f); + box.velocity += accel * (dt * n); + } + + inline void push_body( + Hitbox& box, int axis, float value, uint wakeSubstep + ) { + if (box.velocity[axis] != value) { + box.velocity[axis] = value; + box.nextSubstep = std::min(box.nextSubstep, wakeSubstep); + } + } + + uint calc_substep_stride( + const Hitbox& hitbox, const glm::vec3& gravity, float dt, uint left + ); + + void schedule_substep( + Hitbox& hitbox, + const glm::vec3& gravity, + uint done, + uint substeps, + float dt + ); +} diff --git a/src/physics/sensors.cpp b/src/physics/sensors.cpp new file mode 100644 index 000000000..641d1c09b --- /dev/null +++ b/src/physics/sensors.cpp @@ -0,0 +1,32 @@ +#include "sensors.hpp" + +void physics::update_sensors( + Hitbox& hitbox, const std::vector& sensors +) { + auto aabb = hitbox.getAABB(); + + for (size_t i = 0; i < sensors.size(); i++) { + auto& sensor = *sensors[i]; + if (sensor.entity == hitbox.entity) { + continue; + } + bool triggered = false; + switch (sensor.type) { + case SensorType::AABB: + triggered = aabb.intersects(sensor.calculated.aabb); + break; + case SensorType::RADIUS: + triggered = glm::distance2( + hitbox.position, glm::vec3(sensor.calculated.radial)) + < sensor.calculated.radial.w; + break; + } + if (!triggered) { + continue; + } + if (sensor.prevEntered.find(hitbox.entity) == sensor.prevEntered.end()) { + sensor.enterCallback(sensor.entity, sensor.index, hitbox.entity); + } + sensor.nextEntered.insert(hitbox.entity); + } +} diff --git a/src/physics/sensors.hpp b/src/physics/sensors.hpp new file mode 100644 index 000000000..c78eae81c --- /dev/null +++ b/src/physics/sensors.hpp @@ -0,0 +1,9 @@ +#pragma once + +#include "Hitbox.hpp" + +#include + +namespace physics { + void update_sensors(Hitbox& hitbox, const std::vector& sensors); +} diff --git a/src/util/Interpolation.hpp b/src/util/Interpolation.hpp index 757bb6f4d..e24c13c3a 100644 --- a/src/util/Interpolation.hpp +++ b/src/util/Interpolation.hpp @@ -1,7 +1,9 @@ #pragma once +#include #include #include +#include const float INTERPOLATION_DURATION = 0.15f; // seconds @@ -9,6 +11,7 @@ namespace util { template class VecInterpolation { bool enabled; + bool refreshed = false; glm::vec prevPos {std::numeric_limits::quiet_NaN()}; glm::vec nextPos {}; mutable glm::vec interpolationStep {}; @@ -37,6 +40,7 @@ namespace util { } else { interpolationStep = (nextPos - prevPos) / currentDuration.x; } + refreshed = true; timer = 0.0; } @@ -57,6 +61,50 @@ namespace util { return interpolated; } + bool isRefreshed() const { + return refreshed; + } + + bool isEnabled() const { + return enabled; + } + + void setEnabled(bool enabled) { + this->enabled = enabled; + } + }; + + class RotationInterpolation { + bool enabled; + bool refreshed = false; + glm::quat prevRot {1.0f, 0.0f, 0.0f, 0.0f}; + glm::quat nextRot {1.0f, 0.0f, 0.0f, 0.0f}; + float timer = 0.0f; + public: + RotationInterpolation(bool enabled) : enabled(enabled) {} + + void refresh(const glm::quat& rotation) { + prevRot = refreshed ? getCurrent() : rotation; + nextRot = rotation; + refreshed = true; + timer = 0.0f; + } + + void updateTimer(float delta) { + timer += delta; + } + + glm::quat getCurrent() const { + if (timer >= INTERPOLATION_DURATION) { + return nextRot; + } + return glm::slerp(prevRot, nextRot, timer / INTERPOLATION_DURATION); + } + + bool isRefreshed() const { + return refreshed; + } + bool isEnabled() const { return enabled; } diff --git a/src/util/platform.cpp b/src/util/platform.cpp index 278fbaa1b..996236dc3 100644 --- a/src/util/platform.cpp +++ b/src/util/platform.cpp @@ -1,7 +1,6 @@ #include "platform.hpp" #include - #include #include #include @@ -11,6 +10,10 @@ #include "typedefs.hpp" #include "debug/Logger.hpp" #include "frontend/locale.hpp" +#include "interfaces/SystemProcess.hpp" +#include "logic/scripting/io_descriptors.hpp" +#include "io/fd_istream.hpp" +#include "io/fd_ostream.hpp" #ifdef _WIN32 #include @@ -22,9 +25,13 @@ #include #include #include +#include +#include #endif #ifdef __linux__ #include +#endif +#if defined(__linux__) || defined(__APPLE__) #include #endif @@ -71,23 +78,17 @@ void platform::sleep(size_t millis) { return tc.wPeriodMin; }(); - // Set the timer resolution to the minimum for the Sleep call timeBeginPeriod(periodMin); - - // Wait... Sleep(static_cast(millis)); - - // Reset the timer resolution back to the system default timeEndPeriod(periodMin); } int platform::get_process_id() { - return GetCurrentProcessId(); + return GetCurrentProcessId(); } bool platform::open_url(const std::string& url) { if (url.empty()) return false; - // UTF-8 → UTF-16 int wlen = MultiByteToWideChar(CP_UTF8, 0, url.c_str(), -1, nullptr, 0); if (wlen <= 0) return false; @@ -105,11 +106,10 @@ bool platform::open_url(const std::string& url) { void platform::configure_encoding() { } - + std::string platform::detect_locale() { const char* const programLocaleName = setlocale(LC_ALL, nullptr); - const char* const preferredLocaleName = - setlocale(LC_ALL, ""); // locale name format: ll_CC.encoding + const char* const preferredLocaleName = setlocale(LC_ALL, ""); if (programLocaleName && preferredLocaleName) { setlocale(LC_ALL, programLocaleName); @@ -224,34 +224,46 @@ std::filesystem::path platform::get_executable_path() { #endif } -class SystemProcess final : public Process { +class SystemProcessImpl final : public SystemProcess { public: -#ifdef __linux__ - SystemProcess(pid_t pid) : pid(pid) { +#if defined(__linux__) || defined(__APPLE__) + SystemProcessImpl( + pid_t pid, int stdinDescriptor = -1, int stdoutDescriptor = -1 + ) + : pid(pid), + stdinDescriptor(stdinDescriptor), + stdoutDescriptor(stdoutDescriptor) { } - ~SystemProcess() { + ~SystemProcessImpl() { terminate(); } #elif defined(_WIN32) - SystemProcess(const PROCESS_INFORMATION& pi) - : processHandle(pi.hProcess), pid(pi.dwProcessId) { + SystemProcessImpl( + const PROCESS_INFORMATION& pi, + int stdinDescriptor = -1, + int stdoutDescriptor = -1 + ) + : processHandle(pi.hProcess), + pid(pi.dwProcessId), + stdinDescriptor(stdinDescriptor), + stdoutDescriptor(stdoutDescriptor) { if (pi.hThread != nullptr) { CloseHandle(pi.hThread); } } - ~SystemProcess() { + ~SystemProcessImpl() { terminate(); } #endif - SystemProcess(const SystemProcess&) = delete; - SystemProcess(SystemProcess&&) noexcept = default; - SystemProcess& operator=(const SystemProcess&) = delete; + SystemProcessImpl(const SystemProcessImpl&) = delete; + SystemProcessImpl(SystemProcessImpl&&) noexcept = default; + SystemProcessImpl& operator=(const SystemProcessImpl&) = delete; - SystemProcess& operator=(SystemProcess&& other) noexcept { + SystemProcessImpl& operator=(SystemProcessImpl&& other) noexcept { if (this != &other) { -#ifdef __linux__ +#if defined(__linux__) || defined(__APPLE__) pid = other.pid; #elif defined(_WIN32) if (processHandle != nullptr) { @@ -262,16 +274,36 @@ public: other.processHandle = nullptr; other.pid = 0; #endif + stdinDescriptor = other.stdinDescriptor; + stdoutDescriptor = other.stdoutDescriptor; + other.stdinDescriptor = -1; + other.stdoutDescriptor = -1; } return *this; } bool isActive() const override { -#ifdef __linux__ - if (kill(pid, 0) == 0) { +#if defined(__linux__) || defined(__APPLE__) + if (pid <= 0) { + return false; + } + + // fixme: ugly ugly ugly + int status = 0; + pid_t result = waitpid(pid, &status, WNOHANG); + if (result == -1) { + if (errno == ECHILD) { + const_cast(this)->pid = 0; + return false; + } + return false; + } + if (result == 0) { return true; } - return errno != ESRCH; + + const_cast(this)->pid = 0; + return false; #elif defined(_WIN32) if (processHandle == nullptr) { return false; @@ -283,6 +315,7 @@ public: return false; #elif defined(__APPLE__) // FIXME: completely implement SystemProcess for MacOS +#else return false; #endif } @@ -290,8 +323,12 @@ public: void update() override {} void waitForEnd() override { -#ifdef __linux__ +#if defined(__linux__) || defined(__APPLE__) + if (pid <= 0) { + return; + } waitpid(pid, nullptr, 0); + pid = 0; #elif defined(_WIN32) if (processHandle != nullptr) { WaitForSingleObject(processHandle, INFINITE); @@ -300,7 +337,10 @@ public: }; void terminate() final override { -#ifdef __linux__ +#if defined(__linux__) || defined(__APPLE__) + if (pid <= 0) { + return; + } logger.info() << "terminating " << pid; kill(pid, SIGTERM); #elif defined(_WIN32) @@ -310,16 +350,149 @@ public: } #endif } + + int getStdinDescriptor() const override { + return stdinDescriptor; + } + + int getStdoutDescriptor() const override { + return stdoutDescriptor; + } + private: -#ifdef __linux__ +#if defined(__linux__) || defined(__APPLE__) pid_t pid; + int stdinDescriptor; + int stdoutDescriptor; #elif defined(_WIN32) HANDLE processHandle = nullptr; DWORD pid = 0; + int stdinDescriptor; + int stdoutDescriptor; #endif }; -std::unique_ptr platform::new_engine_instance( +#ifndef _WIN32 +static void close_fd(int& fd) { + if (fd >= 0) { + close(fd); + fd = -1; + } +} + +static bool make_cloexec_pipe(int fds[2]) { +#ifdef __linux__ + return pipe2(fds, O_CLOEXEC) == 0; +#else + if (pipe(fds) != 0) { + return false; + } + fcntl(fds[0], F_SETFD, FD_CLOEXEC); + fcntl(fds[1], F_SETFD, FD_CLOEXEC); + return true; +#endif +} + +static void report_error_and_exit(int fd) { + int err = errno; + [[maybe_unused]] ssize_t _ = write(fd, &err, sizeof(err)); + _exit(127); +} + +// TODO: make sub-process die with parent in MacOS +static std::unique_ptr start_engine_subprocess( + const std::filesystem::path& executable, + const std::vector& args +) { + int stdinPipe[2] = {-1, -1}; + int stdoutPipe[2] = {-1, -1}; + int execPipe[2] = {-1, -1}; + auto closeAll = [&]() { + for (int* fd : + {&stdinPipe[0], + &stdinPipe[1], + &stdoutPipe[0], + &stdoutPipe[1], + &execPipe[0], + &execPipe[1]}) { + close_fd(*fd); + } + }; + + if (!make_cloexec_pipe(stdinPipe) || !make_cloexec_pipe(stdoutPipe) || + !make_cloexec_pipe(execPipe)) { + closeAll(); + throw std::runtime_error("failed to create subprocess pipes"); + } + + std::string path = executable.string(); + std::vector argv; + argv.reserve(args.size() + 2); + argv.push_back(path.data()); + for (const auto& arg : args) { + argv.push_back(const_cast(arg.c_str())); + } + argv.push_back(nullptr); + +#ifdef __linux__ + const pid_t parentPid = getpid(); +#endif + const pid_t pid = fork(); + if (pid < 0) { + int err = errno; + closeAll(); + throw std::runtime_error("fork failed: "s + std::strerror(err)); + } + + if (pid == 0) { +#ifdef __linux__ + prctl(PR_SET_PDEATHSIG, SIGTERM); + if (getppid() != parentPid) { + _exit(1); + } + prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); +#endif + if (dup2(stdinPipe[0], STDIN_FILENO) < 0 || + dup2(stdoutPipe[1], STDOUT_FILENO) < 0 || + dup2(stdoutPipe[1], STDERR_FILENO) < 0) { + report_error_and_exit(execPipe[1]); + } + execv(argv[0], argv.data()); + report_error_and_exit(execPipe[1]); + } + + close_fd(stdinPipe[0]); + close_fd(stdoutPipe[1]); + close_fd(execPipe[1]); + + int childErrno = 0; + ssize_t n; + do { + n = read(execPipe[0], &childErrno, sizeof(childErrno)); + } while (n < 0 && errno == EINTR); + close_fd(execPipe[0]); + + if (n > 0) { + waitpid(pid, nullptr, 0); + closeAll(); + throw std::runtime_error( + "starting an engine instance failed: "s + std::strerror(childErrno) + ); + } + + const int stdinDescriptorId = scripting::io_descriptors::add_descriptor( + std::make_unique(stdinPipe[1]) + ); + const int stdoutDescriptorId = scripting::io_descriptors::add_descriptor( + std::make_unique(stdoutPipe[0]) + ); + return std::make_unique( + pid, stdinDescriptorId, stdoutDescriptorId + ); +} +#endif + +std::unique_ptr platform::new_engine_instance( const std::vector& args, std::filesystem::path outputFile, bool subProcess @@ -334,7 +507,7 @@ std::unique_ptr platform::new_engine_instance( } auto toWString = [](const std::string& src) -> std::wstring { - if (src.empty()) + if (src.empty()) return L""; int size = MultiByteToWideChar(CP_UTF8, 0, src.c_str(), -1, nullptr, 0); if (size == 0) { @@ -358,10 +531,81 @@ std::unique_ptr platform::new_engine_instance( auto commandString = toWString(ss.str()); STARTUPINFOW si = { sizeof(si) }; + PROCESS_INFORMATION pi = { 0 }; + + if (subProcess) { + SECURITY_ATTRIBUTES pipeAttributes{}; + pipeAttributes.nLength = sizeof(pipeAttributes); + pipeAttributes.bInheritHandle = TRUE; + + HANDLE stdinRead = nullptr; + HANDLE stdinWrite = nullptr; + HANDLE stdoutRead = nullptr; + HANDLE stdoutWrite = nullptr; + + if (!CreatePipe(&stdinRead, &stdinWrite, &pipeAttributes, 0) || + !CreatePipe(&stdoutRead, &stdoutWrite, &pipeAttributes, 0)) { + throw std::runtime_error( + "CreatePipe failed with code: " + std::to_string(GetLastError()) + ); + } + + if (!SetHandleInformation(stdinWrite, HANDLE_FLAG_INHERIT, 0) || + !SetHandleInformation(stdoutRead, HANDLE_FLAG_INHERIT, 0)) { + CloseHandle(stdinRead); + CloseHandle(stdinWrite); + CloseHandle(stdoutRead); + CloseHandle(stdoutWrite); + throw std::runtime_error( + "SetHandleInformation failed with code: " + std::to_string(GetLastError()) + ); + } + + si.dwFlags = STARTF_USESTDHANDLES; + si.hStdInput = stdinRead; + si.hStdOutput = stdoutWrite; + si.hStdError = stdoutWrite; + + const DWORD flags = CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS; + const BOOL success = CreateProcessW( + nullptr, + commandString.data(), + nullptr, + nullptr, + TRUE, + flags, + nullptr, + nullptr, + &si, + &pi + ); + + CloseHandle(stdinRead); + CloseHandle(stdoutWrite); + + if (!success) { + CloseHandle(stdinWrite); + CloseHandle(stdoutRead); + throw std::runtime_error( + "starting an engine instance failed with code: " + + std::to_string(GetLastError()) + ); + } + + int stdinDescriptor = scripting::io_descriptors::add_descriptor( + std::make_unique(stdinWrite) + ); + int stdoutDescriptor = scripting::io_descriptors::add_descriptor( + std::make_unique(stdoutRead) + ); + return std::make_unique(pi, stdinDescriptor, stdoutDescriptor); + } + if (!outputFile.empty()) { si.dwFlags |= STARTF_USESTDHANDLES; + const auto outputPath = toWString(outputFile.u8string()); si.hStdOutput = CreateFileW( - toWString(outputFile.empty() ? outputFile.u8string() : "NUL"s).data(), + outputPath.c_str(), GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, nullptr, @@ -371,15 +615,13 @@ std::unique_ptr platform::new_engine_instance( ); if (si.hStdOutput == INVALID_HANDLE_VALUE) { throw std::runtime_error( - "CreateFileW failed with code: " + - std::to_string(GetLastError()) + "CreateFileW failed with code: " + std::to_string(GetLastError()) ); } } - PROCESS_INFORMATION pi = { 0 }; - DWORD flags = CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS; - // | CREATE_NO_WINDOW; - BOOL success = CreateProcessW( + + const DWORD flags = CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS; + const BOOL success = CreateProcessW( nullptr, commandString.data(), nullptr, @@ -391,38 +633,6 @@ std::unique_ptr platform::new_engine_instance( &si, &pi ); - if (subProcess) { - HANDLE job = CreateJobObjectW(nullptr, nullptr); - - JOBOBJECT_EXTENDED_LIMIT_INFORMATION info{}; - info.BasicLimitInformation.LimitFlags = - JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; - - try { - if (!SetInformationJobObject( - job, - JobObjectExtendedLimitInformation, - &info, - sizeof(info))) { - throw std::runtime_error( - "SetInformationJobObject failed with code: " + - std::to_string(GetLastError()) - ); - } - if (!AssignProcessToJobObject(job, pi.hProcess)) { - throw std::runtime_error( - "SetInformationJobObject failed with code: " + - std::to_string(GetLastError()) - ); - } - return std::make_unique(pi); - } catch (const std::exception& err) { - CloseHandle(job); - CloseHandle(pi.hProcess); - CloseHandle(pi.hThread); - return nullptr; - } - } if (success) { CloseHandle(pi.hProcess); CloseHandle(pi.hThread); @@ -433,51 +643,12 @@ std::unique_ptr platform::new_engine_instance( ); } #else - -// TODO: implement -#ifndef __APPLE__ if (subProcess) { - pid_t pid = fork(); - - if (outputFile.empty()) { - outputFile = "/dev/null"; - } - int fd = open( - outputFile.string().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644 - ); - - if (pid == 0) { - prctl(PR_SET_PDEATHSIG, SIGTERM); - - if (getppid() == 1) { - _exit(1); - } - - dup2(fd, STDOUT_FILENO); - dup2(fd, STDERR_FILENO); - close(fd); - - std::vector argv(args.size() + 2); - argv[0] = const_cast(executable.c_str()); - for (int i = 0; i < args.size(); i++) { - argv[i + 1] = args[i].c_str(); - } - argv[args.size() + 1] = nullptr; - - prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); - execvp(executable.c_str(), const_cast(argv.data())); - - _exit(127); - } else { - close(fd); - usleep(1000); // waiting for execvp call - return std::make_unique(pid); - } + return start_engine_subprocess(executable, args); } -#endif std::stringstream ss; - ss << executable; + ss << util::quote(executable.u8string()); for (int i = 0; i < args.size(); i++) { ss << " " << util::quote(args[i]); } @@ -501,7 +672,22 @@ std::unique_ptr platform::new_engine_instance( bool platform::stdin_has_data() { #ifdef _WIN32 - return _kbhit(); + const HANDLE inputHandle = GetStdHandle(STD_INPUT_HANDLE); + if (inputHandle == nullptr || inputHandle == INVALID_HANDLE_VALUE) { + return false; + } + + DWORD mode = 0; + if (GetConsoleMode(inputHandle, &mode)) { + return _kbhit() != 0; + } + + DWORD available = 0; + if (!PeekNamedPipe(inputHandle, nullptr, 0, nullptr, &available, nullptr)) { + const DWORD error = GetLastError(); + return error != ERROR_BROKEN_PIPE && error != ERROR_INVALID_HANDLE; + } + return available > 0; #else struct pollfd fds; fds.fd = STDIN_FILENO; diff --git a/src/util/platform.hpp b/src/util/platform.hpp index 18dc052b6..457642fd3 100644 --- a/src/util/platform.hpp +++ b/src/util/platform.hpp @@ -5,7 +5,7 @@ #include #include -#include "interfaces/Process.hpp" +#include "interfaces/SystemProcess.hpp" namespace platform { void configure_encoding(); @@ -21,7 +21,7 @@ namespace platform { /// @brief Get current process running executable path std::filesystem::path get_executable_path(); /// @brief Run a separate engine instance with specified arguments - std::unique_ptr new_engine_instance( + std::unique_ptr new_engine_instance( const std::vector& args, std::filesystem::path outputFile, bool subProcess diff --git a/src/voxels/Block.cpp b/src/voxels/Block.cpp index 8e28c54c4..fb3c5888b 100644 --- a/src/voxels/Block.cpp +++ b/src/voxels/Block.cpp @@ -120,8 +120,7 @@ const BlockRotProfile BlockRotProfile::LADDER { 4 }; -Block::Block(const std::string& name) - : name(name), caption(util::id_to_caption(name)) { +Block::Block(const std::string& name) : name(name) { for (int i = 0; i < defaults.textureFaces.size(); i++) { defaults.textureFaces[i] = TEXTURE_NOTFOUND; } @@ -154,9 +153,9 @@ void Block::cloneTo(Block& dst) { dst.replaceable = replaceable; dst.breakable = breakable; dst.rotatable = rotatable; + dst.uvLock = uvLock; dst.grounded = grounded; dst.hidden = hidden; - dst.hitboxes = hitboxes; dst.rotations = rotations; dst.pickingItem = pickingItem; dst.scriptName = scriptName; diff --git a/src/voxels/Block.hpp b/src/voxels/Block.hpp index a5185106b..27029f43c 100644 --- a/src/voxels/Block.hpp +++ b/src/voxels/Block.hpp @@ -10,6 +10,7 @@ #include "maths/UVRegion.hpp" #include "maths/aabb.hpp" #include "typedefs.hpp" +#include "voxel.hpp" #include "util/EnumMetadata.hpp" #include "util/stack_vector.hpp" #include "interfaces/Serializable.hpp" @@ -41,6 +42,7 @@ struct BlockFuncsSet { bool init : 1; bool update : 1; bool onplaced : 1; + bool canbeplaced : 1; bool onbreaking : 1; bool onbroken : 1; bool onreplaced : 1; @@ -181,10 +183,14 @@ struct Variant { CullingMode culling = CullingMode::DEFAULT; /// @brief Influences visible block sides for transparent blocks uint8_t drawGroup = 0; + /// @brief Set of block physical hitboxes + std::vector hitboxes {AABB()}; struct { /// @brief is the block completely opaque for render bool solid = true; + /// @brief set of hitboxes sets with all coord-systems precalculated + std::vector hitboxes[BlockRotProfile::MAX_COUNT]; } rt; }; @@ -244,6 +250,10 @@ public: /// @brief Can the block be oriented different ways bool rotatable = false; + /// @brief Keep custom model textures aligned to world axes + /// when the block is rotated + bool uvLock = false; + /// @brief Can the block exist without physical support be a solid block /// below bool grounded = false; @@ -260,14 +270,11 @@ public: /// @brief Grounding behaviour GroundingBehaviour groundingBehaviour = GroundingBehaviour::PARTIAL; - /// @brief Set of block physical hitboxes - std::vector hitboxes {AABB()}; - /// @brief Set of available block rotations (coord-systems) BlockRotProfile rotations = BlockRotProfile::NONE; /// @brief Item will be picked on MMB click on the block - std::string pickingItem = name + BLOCK_ITEM_SUFFIX; + std::string pickingItem; /// @brief Block script name in blocks/ without extension std::string scriptName = name.substr(name.find(':') + 1); @@ -311,9 +318,6 @@ public: // @brief block size is greater than 1x1x1 bool extended = false; - /// @brief set of hitboxes sets with all coord-systems precalculated - std::vector hitboxes[BlockRotProfile::MAX_COUNT]; - /// @brief set of block callbacks flags BlockFuncsSet funcsset {}; @@ -358,6 +362,13 @@ public: return getVariantByBits(bits).model; } + /// @brief Get precalculated hitboxes of the variant and rotation + /// by the block state + const std::vector& getHitboxes(blockstate state) const { + return getVariantByBits(state.userbits) + .rt.hitboxes[rotatable ? state.rotation : 0]; + } + static bool isReservedBlockField(std::string_view view); }; diff --git a/src/voxels/Chunks.cpp b/src/voxels/Chunks.cpp index 615ed2fbb..60bac04d5 100644 --- a/src/voxels/Chunks.cpp +++ b/src/voxels/Chunks.cpp @@ -70,12 +70,14 @@ const AABB* Chunks::isObstacleAt(float x, float y, float z) const { return nullptr; } glm::ivec3 offset {}; - if (v->state.segment) { + blockstate state = v->state; + if (state.segment) { glm::ivec3 point(ix, iy, iz); - offset = seekOrigin(point, def, v->state) - point; + auto origin = seekOrigin(point, def, state); + offset = origin - point; + state = blocks_agent::hitbox_state(*this, origin, state); } - const auto& boxes = - def.rotatable ? def.rt.hitboxes[v->state.rotation] : def.hitboxes; + const auto& boxes = def.getHitboxes(state); for (const auto& hitbox : boxes) { if (hitbox.contains( {x - ix - offset.x, y - iy - offset.y, z - iz - offset.z} @@ -262,18 +264,18 @@ glm::vec3 Chunks::rayCastToObstacle( const auto& def = indices.blocks.require(voxel->id); if (def.obstacle) { if (!def.rt.solid) { - const std::vector& hitboxes = - def.rt.hitboxes[voxel->state.rotation]; - scalar_t distance; glm::ivec3 norm; Ray ray(start, dir); glm::ivec3 offset {}; - if (voxel->state.segment) { - offset = seekOrigin({ix, iy, iz}, def, voxel->state) - - glm::ivec3(ix, iy, iz); + blockstate state = voxel->state; + if (state.segment) { + auto origin = seekOrigin({ix, iy, iz}, def, state); + offset = origin - glm::ivec3(ix, iy, iz); + state = blocks_agent::hitbox_state(*this, origin, state); } + const auto& hitboxes = def.getHitboxes(state); for (const auto& box : hitboxes) { // norm is dummy now, can be inefficient diff --git a/src/voxels/Pathfinding.cpp b/src/voxels/Pathfinding.cpp index 999711f0b..7a3285b79 100644 --- a/src/voxels/Pathfinding.cpp +++ b/src/voxels/Pathfinding.cpp @@ -1,62 +1,336 @@ #include "Pathfinding.hpp" +#include "constants.hpp" #include "content/Content.hpp" +#include "maths/voxmaths.hpp" +#include "voxels/Block.hpp" #include "voxels/Chunk.hpp" #include "voxels/GlobalChunks.hpp" -#include "voxels/blocks_agent.hpp" #include "world/Level.hpp" -inline constexpr float SQRT2 = 1.4142135623730951f; // sqrt(2) +#include +#include +#include +#include + +static constexpr float SQRT2 = 1.4142135623730951f; // sqrt(2) +static constexpr int16_t SOLID = -1; +static constexpr int16_t UNKNOWN = std::numeric_limits::min(); +static constexpr int NO_SURFACE = std::numeric_limits::min(); +static constexpr int MAX_DROP = 1; +static constexpr float SEGMENT_SAMPLE_STEP = 0.2f; +static constexpr size_t MAX_SEGMENT_NODES = 32; using namespace voxels; +static const glm::ivec2 NEIGHBORS[] { + {0, 1}, {1, 0}, {0, -1}, {-1, 0}, + {-1, -1}, {1, -1}, {1, 1}, {-1, 1}, +}; + static float heuristic(const glm::ivec3& a, const glm::ivec3& b) { return glm::distance(glm::vec3(a), glm::vec3(b)); } +class BlocksSampler { +public: + BlocksSampler( + const GlobalChunks& chunks, + const ContentUnitIndices& defs, + const Agent& agent, + std::vector& costs + ) + : height(std::max(agent.height, 1)), + radius(static_cast( + std::ceil(std::max(agent.width - 1.0f, 0.0f) * 0.5f - 1e-4f) + )), + halfWidth(std::max(agent.width * 0.5f, 0.05f)), + jumpHeight(std::max(agent.jumpHeight, 0)), + chunks(chunks), + defs(defs), + agent(agent), + costs(costs) { + if (costs.size() != defs.count()) { + costs.assign(defs.count(), UNKNOWN); + } + } + + int16_t at(int x, int y, int z) { + if (y < 0) { + return SOLID; + } + if (y >= CHUNK_H) { + return 0; + } + int cx = floordiv(x); + int cz = floordiv(z); + if (!hasChunk || cx != chunkX || cz != chunkZ) { + chunk = chunks.getChunk(cx, cz); + chunkX = cx; + chunkZ = cz; + hasChunk = true; + } + if (chunk == nullptr) { + return SOLID; + } + int lx = x - cx * CHUNK_W; + int lz = z - cz * CHUNK_D; + blockid_t id = chunk->voxels[(y * CHUNK_D + lz) * CHUNK_W + lx].id; + if (id >= costs.size()) { + return SOLID; + } + auto& cost = costs[id]; + if (cost == UNKNOWN) { + cost = classify(id); + } + return cost; + } + + int16_t getMaxCostInBox(int x0, int z0, int x1, int z1, int y0, int y1) { + int16_t result = 0; + for (int y = y0; y < y1; y++) { + for (int z = z0; z <= z1; z++) { + for (int x = x0; x <= x1; x++) { + int16_t cost = at(x, y, z); + if (cost == SOLID) { + return SOLID; + } + result = std::max(result, cost); + } + } + } + return result; + } + + int16_t getFootprintCost(int x, int z, int y0, int y1) { + return getMaxCostInBox( + x - radius, z - radius, x + radius, z + radius, y0, y1 + ); + } + + int16_t getStandingCost(const glm::ivec3& pos) { + return getFootprintCost(pos.x, pos.z, pos.y, pos.y + height); + } + + int findSurfaceHeight(int x, int y, int z) { + if (at(x, y, z) == SOLID) { + for (int i = 1; i <= jumpHeight; i++) { + if (at(x, y + i, z) != SOLID) { + return y + i; + } + } + return NO_SURFACE; + } + for (int i = 0; i <= MAX_DROP; i++) { + if (at(x, y - i - 1, z) == SOLID) { + return y - i; + } + } + return NO_SURFACE; + } + + int16_t getMovementCost(const glm::ivec3& from, const glm::ivec3& to) { + int top = std::max(from.y, to.y) + height; + int16_t cost = getFootprintCost(to.x, to.z, to.y, top); + if (cost == SOLID) { + return SOLID; + } + if (to.y > from.y && + getFootprintCost(from.x, from.z, from.y + height, top) == SOLID) { + return SOLID; + } + int dx = to.x - from.x; + int dz = to.z - from.z; + if (dx == 0 || dz == 0) { + return cost; + } + int bottom = std::min(from.y, to.y); + int ax = from.x + dx * (radius + 1); + int az = from.z - dz * radius; + int bx = from.x - dx * radius; + int bz = from.z + dz * (radius + 1); + int16_t a = getMaxCostInBox(ax, az, ax, az, bottom, top); + int16_t b = getMaxCostInBox(bx, bz, bx, bz, bottom, top); + if (a == SOLID || b == SOLID) { + return SOLID; + } + return std::max({cost, a, b}); + } + + int16_t getLineCost(glm::vec2 a, glm::vec2 b, int y0, int y1) { + auto min = [this](float a, float b) { + return static_cast(std::floor(std::min(a, b) - halfWidth)); + }; + auto max = [this](float a, float b) { + return static_cast(std::ceil(std::max(a, b) + halfWidth)); + }; + int x0 = min(a.x, b.x); + int z0 = min(a.y, b.y); + int x1 = max(a.x, b.x); + int z1 = max(a.y, b.y); + return getMaxCostInBox( + x0, z0, std::max(x0, x1 - 1), std::max(z0, z1 - 1), y0, y1 + ); + } + + bool canWalkDirectly( + const glm::ivec3& a, const glm::ivec3& b, int16_t maxCost + ) { + if (b.y > a.y) { + return false; + } + glm::vec2 from(a.x + 0.5f, a.z + 0.5f); + glm::vec2 to(b.x + 0.5f, b.z + 0.5f); + int steps = std::max( + 1, + static_cast( + std::ceil(glm::distance(from, to) / SEGMENT_SAMPLE_STEP) + ) + ); + int cx = a.x; + int cz = a.z; + int y = a.y; + glm::vec2 prev = from; + auto isBlocked = [&](glm::vec2 p, int y0, int y1) { + int16_t cost = getLineCost(prev, p, y0, y1); + return cost == SOLID || cost > maxCost; + }; + for (int i = 1; i <= steps; i++) { + float t = i / static_cast(steps); + glm::vec2 p = from + (to - from) * t; + int px = static_cast(std::floor(p.x)); + int pz = static_cast(std::floor(p.y)); + int top = y + height; + if (px != cx || pz != cz) { + int ny = findSurfaceHeight(px, y, pz); + if (ny == NO_SURFACE || ny > y) { + return false; + } + if (ny < y) { + if (isBlocked(p, y, top)) { + return false; + } + prev = p; + } + cx = px; + cz = pz; + y = ny; + } + if (isBlocked(p, y, top)) { + return false; + } + prev = p; + } + return y == b.y; + } + + std::vector simplifyPath( + const std::vector& path + ) { + if (path.size() <= 2) { + return path; + } + std::vector nodeCosts(path.size()); + for (size_t i = 0; i < path.size(); i++) { + nodeCosts[i] = std::max(getStandingCost(path[i]), 0); + } + auto isDirect = [&](size_t from, size_t to) { + int16_t maxCost = std::max(nodeCosts[from], nodeCosts[to]); + return canWalkDirectly(path[from], path[to], maxCost); + }; + const size_t last = path.size() - 1; + + std::vector result {path.front()}; + size_t anchor = 0; + while (anchor < last) { + size_t limit = std::min(last, anchor + MAX_SEGMENT_NODES); + size_t good = anchor + 1; + size_t bad = limit + 1; + for (size_t step = 2; good < limit; step *= 2) { + size_t next = std::min(anchor + step, limit); + if (!isDirect(anchor, next)) { + bad = next; + break; + } + good = next; + } + while (bad - good > 1) { + size_t mid = (good + bad) / 2; + (isDirect(anchor, mid) ? good : bad) = mid; + } + result.push_back(path[good]); + anchor = good; + } + return result; + } + + const int height; + const int radius; + const float halfWidth; + const int jumpHeight; +private: + const GlobalChunks& chunks; + const ContentUnitIndices& defs; + const Agent& agent; + std::vector& costs; + const Chunk* chunk = nullptr; + int chunkX = 0; + int chunkZ = 0; + bool hasChunk = false; + + int16_t classify(blockid_t id) const { + const auto& def = defs.require(id); + if (def.obstacle) { + return SOLID; + } + int cost = 0; + for (const auto& [tag, tagCost] : agent.avoidTags) { + if (def.rt.tags.find(tag) != def.rt.tags.end()) { + cost = std::max(cost, tagCost); + } + } + return static_cast( + std::clamp(cost, 0, static_cast(INT16_MAX)) + ); + } +}; + Pathfinding::Pathfinding(const Level& level) : level(level), chunks(*level.chunks), blockDefs(level.content.getIndices()->blocks) { } -static bool check_passability( - const Agent& agent, - const GlobalChunks& chunks, - const Node& node, - const glm::ivec2& offset, - bool diagonal +static Route finish_route( + Agent& agent, BlocksSampler& sampler, const glm::ivec3& last, bool found ) { - if (!diagonal) { - return true; - } - auto a = node.pos + glm::ivec3(offset.x, 0, 0); - auto b = node.pos + glm::ivec3(0, 0, offset.y); - - for (int i = 0; i < agent.height; i++) { - if (blocks_agent::is_obstacle_at(chunks, a.x, a.y + i, a.z)) - return false; - if (blocks_agent::is_obstacle_at(chunks, b.x, b.y + i, b.z)) - return false; - } - return true; -} - -static void restore_route( - Route& route, - const glm::ivec3& lastPos, - const std::unordered_map& parents -) { - auto pos = lastPos; - while (true) { - const auto& found = parents.find(pos); - if (found == parents.end()) { - route.nodes.push_back({pos}); + auto& state = agent.state; + std::vector path; + for (auto pos = last;;) { + path.push_back(pos); + const auto& visit = state.visits.find(pos); + if (visit == state.visits.end() || visit->second.parent == pos) { break; } - route.nodes.push_back({pos}); - pos = found->second.pos; + pos = visit->second.parent; } + std::reverse(path.begin(), path.end()); + path = sampler.simplifyPath(path); + + Route route {}; + route.found = found; + route.totalVisited = state.closedCount; + route.nodes.reserve(path.size()); + + for (auto it = path.rbegin(); it != path.rend(); ++it) { + route.nodes.push_back({*it}); + } + + state.finished = true; + state.queue = {}; + state.visits = {}; + agent.route = route; + return route; } int Pathfinding::createAgent() { @@ -83,124 +357,77 @@ void Pathfinding::performAllAsync(int stepsPerAgent) { } } -static Route finish_route(Agent& agent, State&& state) { - Route route {}; - restore_route(route, state.nearest, state.parents); - route.totalVisited = state.blocked.size(); - route.nodes.push_back({agent.start}); - route.found = true; - state.finished = true; - agent.state = std::move(state); - agent.route = route; - return route; -} - -enum Passability { - NON_PASSABLE = -1, - OBSTACLE = 0, - PASSABLE = 1, -}; - Route Pathfinding::perform(Agent& agent, int maxVisited) { - using namespace blocks_agent; + auto& state = agent.state; + BlocksSampler sampler(chunks, blockDefs, agent, state.blockCosts); - State state = std::move(agent.state); - if (state.queue.empty()) { - state.queue.push( - {agent.start, {}, 0, heuristic(agent.start, agent.target)} - ); - } - - const auto& chunks = *level.chunks; - int height = std::max(agent.height, 1); - - if (state.nearest == glm::ivec3(0)) { + if (state.visits.empty()) { + float hScore = heuristic(agent.start, agent.target); + state.queue.push({agent.start, 0.0f, hScore}); + state.visits[agent.start] = {agent.start, 0.0f, false}; + state.closedCount = 0; state.nearest = agent.start; - state.minHScore = heuristic(agent.start, agent.target); + state.minHScore = hScore; } - int visited = -1; + int visited = 0; while (!state.queue.empty()) { - if (state.blocked.size() == agent.maxVisitedBlocks) { - if (agent.mayBeIncomplete) { - return finish_route(agent, std::move(state)); - } - break; + if (state.closedCount >= agent.maxVisitedBlocks) { + return finish_route( + agent, sampler, state.nearest, agent.mayBeIncomplete + ); } - visited++; - if (visited == maxVisited) { + if (visited++ == maxVisited) { state.finished = false; - agent.state = std::move(state); return {}; } auto node = state.queue.top(); state.queue.pop(); - if (node.pos.x == agent.target.x && - glm::abs((node.pos.y - agent.target.y) / height) == 0 && - node.pos.z == agent.target.z) { - return finish_route(agent, std::move(state)); + auto& current = state.visits[node.pos]; + if (current.closed) { + continue; + } + current.closed = true; + state.closedCount++; + float gScore = current.gScore; + + if (node.pos.x == agent.target.x && node.pos.z == agent.target.z && + glm::abs(node.pos.y - agent.target.y) < sampler.height) { + return finish_route(agent, sampler, node.pos, true); } - state.blocked.emplace(node.pos); - glm::ivec2 neighbors[8] { - {0, 1}, - {1, 0}, - {0, -1}, - {-1, 0}, - {-1, -1}, - {1, -1}, - {1, 1}, - {-1, 1}, - }; - - for (int i = 0; i < sizeof(neighbors) / sizeof(glm::ivec2); i++) { - auto offset = neighbors[i]; - auto pos = node.pos; - - float cost = glm::abs(node.pos.y - pos.y) * 10; - int surface = getSurfaceAt( - agent, pos + glm::ivec3(offset.x, 0, offset.y), 1, cost - ); - - if (surface == NON_PASSABLE) { + for (size_t i = 0; i < std::size(NEIGHBORS); i++) { + const auto& offset = NEIGHBORS[i]; + glm::ivec3 point(node.pos.x + offset.x, 0, node.pos.z + offset.y); + point.y = sampler.findSurfaceHeight(point.x, node.pos.y, point.z); + if (point.y == NO_SURFACE) { continue; } - pos.y = surface; - auto point = pos + glm::ivec3(offset.x, 0, offset.y); - if (state.blocked.find(point) != state.blocked.end()) { + auto found = state.visits.find(point); + if (found != state.visits.end() && found->second.closed) { continue; } - - if (is_obstacle_at( - chunks, pos.x, pos.y + agent.jumpHeight, pos.z - )) { + int16_t cost = sampler.getMovementCost(node.pos, point); + if (cost == SOLID) { continue; } - if (!check_passability(agent, chunks, node, offset, i >= 4)) { + float nextGScore = gScore + (i >= 4 ? SQRT2 : 1.0f) + cost; + if (found != state.visits.end() && + found->second.gScore <= nextGScore) { continue; } - - float sum = glm::abs(offset.x) + glm::abs(offset.y); - float gScore = node.gScore + sum + cost; - const auto& found = state.parents.find(point); - if (found == state.parents.end()) { - float hScore = heuristic(point, agent.target); - if (hScore < state.minHScore) { - state.minHScore = hScore; - state.nearest = point; - } - float fScore = gScore * 0.75f + hScore; - Node nNode {point, node.pos, gScore, fScore}; - state.parents[point] = node; - state.queue.push(nNode); + float hScore = heuristic(point, agent.target); + if (hScore < state.minHScore) { + state.minHScore = hScore; + state.nearest = point; } + state.visits[point] = {node.pos, nextGScore, false}; + state.queue.push({point, nextGScore, nextGScore * 0.75f + hScore}); } } - state.finished = true; - agent.state = std::move(state); - return finish_route(agent, std::move(agent.state)); + return finish_route(agent, sampler, state.nearest, agent.mayBeIncomplete); } Agent* Pathfinding::getAgent(int id) { @@ -214,56 +441,3 @@ Agent* Pathfinding::getAgent(int id) { const std::unordered_map& Pathfinding::getAgents() const { return agents; } - -int Pathfinding::checkPoint(const Agent& agent, int x, int y, int z, int& cost) { - auto vox = blocks_agent::get(chunks, x, y, z); - if (vox == nullptr) { - return OBSTACLE; - } - const auto& def = blockDefs.require(vox->id); - if (def.obstacle) { - return OBSTACLE; - } - for (const auto& pair : agent.avoidTags) { - if (def.rt.tags.find(pair.first) != def.rt.tags.end()) { - cost = pair.second; - return NON_PASSABLE; - } - } - return PASSABLE; -} - -int Pathfinding::getSurfaceAt( - const Agent& agent, const glm::ivec3& pos, int maxDelta, float& cost -) { - using namespace blocks_agent; - - int status; - int surface = pos.y; - int ncost = 0; - if ((status = checkPoint(agent, pos.x, surface, pos.z, ncost)) == OBSTACLE) { - if ((status = checkPoint(agent, pos.x, surface + 1, pos.z, ncost)) == OBSTACLE) { - return NON_PASSABLE; - } else if (status == NON_PASSABLE) { - cost += 5; - } - cost += ncost; - return surface + 1; - } else { - if (status == NON_PASSABLE) { - cost += 5; - } - if ((status = checkPoint(agent, pos.x, surface - 1, pos.z, ncost)) == OBSTACLE) { - cost += ncost; - return surface; - } else if (status == NON_PASSABLE) { - cost += 5; - } - if ((status = checkPoint(agent, pos.x, surface - 2, pos.z, ncost)) == OBSTACLE) { - cost += ncost; - return surface - 1; - } - return NON_PASSABLE; - } - return NON_PASSABLE; -} diff --git a/src/voxels/Pathfinding.hpp b/src/voxels/Pathfinding.hpp index 2e079076e..d81b51bee 100644 --- a/src/voxels/Pathfinding.hpp +++ b/src/voxels/Pathfinding.hpp @@ -4,11 +4,11 @@ #include #include #include +#include #include #include #include #include -#include #include #include "typedefs.hpp" @@ -26,14 +26,13 @@ namespace voxels { }; struct Route { - bool found; std::vector nodes; int totalVisited; + bool found; }; struct Node { glm::ivec3 pos; - glm::ivec3 parent; float gScore; float fScore; }; @@ -44,12 +43,19 @@ namespace voxels { } }; + struct Visit { + glm::ivec3 parent; + float gScore; + bool closed; + }; + struct State { std::priority_queue, NodeLess> queue; - std::unordered_set blocked; - std::unordered_map parents; - glm::ivec3 nearest; - float minHScore; + std::unordered_map visits; + std::vector blockCosts; + int closedCount = 0; + glm::ivec3 nearest {}; + float minHScore = 0.0f; bool finished = true; }; @@ -57,6 +63,7 @@ namespace voxels { bool enabled = false; bool mayBeIncomplete = true; int height = 2; + float width = 0.6f; int jumpHeight = 1; int maxVisitedBlocks = 1e3; glm::ivec3 start; @@ -87,11 +94,5 @@ namespace voxels { const ContentUnitIndices& blockDefs; std::unordered_map agents; int nextAgent = 1; - - int getSurfaceAt( - const Agent& agent, const glm::ivec3& pos, int maxDelta, float& cost - ); - - int checkPoint(const Agent& agent, int x, int y, int z, int& cost); }; } diff --git a/src/voxels/blocks_agent.cpp b/src/voxels/blocks_agent.cpp index d72ddcceb..360862c22 100644 --- a/src/voxels/blocks_agent.cpp +++ b/src/voxels/blocks_agent.cpp @@ -275,19 +275,19 @@ static inline voxel* raycast_blocks( iend = {ix, iy, iz}; if (!def.rt.solid) { - const std::vector& hitboxes = - def.rotatable ? def.rt.hitboxes[voxel->state.rotation] - : def.hitboxes; - scalar_t distance = maxDist; Ray ray(start, dir); bool hit = false; glm::vec3 offset {}; - if (voxel->state.segment) { - offset = seek_origin(chunks, iend, def, voxel->state) - iend; + blockstate state = voxel->state; + if (state.segment) { + auto origin = seek_origin(chunks, iend, def, state); + offset = origin - iend; + state = hitbox_state(chunks, origin, state); } + const auto& hitboxes = def.getHitboxes(state); for (auto box : hitboxes) { box.a += offset; diff --git a/src/voxels/blocks_agent.hpp b/src/voxels/blocks_agent.hpp index 22144c618..810e4f1b4 100644 --- a/src/voxels/blocks_agent.hpp +++ b/src/voxels/blocks_agent.hpp @@ -264,6 +264,22 @@ inline glm::ivec3 seek_origin( } } +/// @brief Get block state selecting the variant hitboxes. +/// Variant bits of an extended block are stored in its origin segment +/// @param origin extended block origin position +/// @param state state of the checked segment +template +inline blockstate hitbox_state( + Storage& chunks, const glm::ivec3& origin, blockstate state +) { + if (state.segment) { + if (auto* voxel = get(chunks, origin.x, origin.y, origin.z)) { + state.userbits = voxel->state.userbits; + } + } + return state; +} + /// @brief Check blocks replaceability with specified block /// @tparam Storage chunks storage class /// @param chunks chunks storage @@ -490,12 +506,14 @@ inline std::optional is_obstacle_at( return std::nullopt; } glm::ivec3 offset {}; - if (v->state.segment) { + blockstate state = v->state; + if (state.segment) { glm::ivec3 point(ix, iy, iz); - offset = seek_origin(chunks, point, def, v->state) - point; + auto origin = seek_origin(chunks, point, def, state); + offset = origin - point; + state = hitbox_state(chunks, origin, state); } - const auto& boxes = - def.rotatable ? def.rt.hitboxes[v->state.rotation] : def.hitboxes; + const auto& boxes = def.getHitboxes(state); for (const auto& hitbox : boxes) { if (hitbox.intersects(aabb - glm::ivec3(ix, iy, iz))) { diff --git a/src/world/World.cpp b/src/world/World.cpp index d65dd2636..bf74ed990 100644 --- a/src/world/World.cpp +++ b/src/world/World.cpp @@ -3,6 +3,7 @@ #include #include +#include #include #include "content/Content.hpp" @@ -14,6 +15,7 @@ #include "objects/Player.hpp" #include "objects/Players.hpp" #include "settings.hpp" +#include "util/stringutil.hpp" #include "voxels/Chunk.hpp" #include "voxels/Chunks.hpp" #include "voxels/GlobalChunks.hpp" @@ -24,6 +26,7 @@ static debug::Logger logger("world"); const float DAYIME_SPECIFIC_SPEED = 1.0f / 1440.0f; // 1.0f/60.0f/24.0f; + world_load_error::world_load_error(const std::string& message) : std::runtime_error(message) { } @@ -38,8 +41,7 @@ World::World( packs(packs), wfile(std::move(worldFiles)) {} -World::~World() { -} +World::~World() = default; void World::updateTimers(float delta) { info.daytime += delta * info.daytimeSpeed * DAYIME_SPECIFIC_SPEED; @@ -76,6 +78,49 @@ void World::write(Level& level) { writeResources(content); } +dv::value WorldInfo::getLogicValue(const std::string& name, + const dv::value& def) const { + if (logic.isObject()) { + if (auto field = logic.at(name)) { + return *field; + } + } + const auto& defaults = defaultLogic(); + if (defaults.isObject()) { + if (auto field = defaults.at(name)) { + return *field; + } + } + return def; +} + +void WorldInfo::setLogicValue(const std::string& name, dv::value value) { + if (!WorldInfo::isLogicKey(name)) { + throw std::runtime_error("unknown logic parameter " + util::quote(name)); + } + if (!logic.isObject()) { + logic = dv::object(); + } + logic[name] = std::move(value); +} + +bool WorldInfo::getLogicFlag(const std::string& name, bool def) const { + auto value = getLogicValue(name, dv::value(def)); + if (value.isBoolean()) { + return value.asBoolean(); + } + if (value.isInteger()) { + return value.asInteger() != 0; + } + if (value.isNumber()) { + return value.asNumber() != 0.0; + } + if (value.isString()) { + return !value.asString().empty(); + } + return def; +} + std::unique_ptr World::create( const std::string& name, const std::string& environment, @@ -216,6 +261,14 @@ void WorldInfo::deserialize(const dv::value& root) { daytimeSpeed = timeobj["day-time-speed"].asNumber(); totalTime = timeobj["total-time"].asNumber(); } + if (root.has("logic")) { + logic = root["logic"]; + } else { + logic = dv::object({ + {"random_ticks", true}, + {"block_ticks", true} + }); + } nextInventoryId = root["next-inventory-id"].asInteger(2); nextEntityId = root["next-entity-id"].asInteger(1); root.at("next-player-id").get(nextPlayerId); @@ -244,5 +297,6 @@ dv::value WorldInfo::serialize() const { root["next-inventory-id"] = nextInventoryId; root["next-entity-id"] = nextEntityId; root["next-player-id"] = nextPlayerId; + root["logic"] = logic; return root; } diff --git a/src/world/World.hpp b/src/world/World.hpp index dc9439906..51a9bb236 100644 --- a/src/world/World.hpp +++ b/src/world/World.hpp @@ -22,6 +22,18 @@ public: }; struct WorldInfo : public Serializable { + static const dv::value& defaultLogic() { + static const dv::value logic = dv::object({ + {"random_ticks", true}, + {"block_ticks", true} + }); + return logic; + } + + static bool isLogicKey(const std::string& name) { + return defaultLogic().has(name); + } + std::string name; std::string environment; std::string explicitGenerator; @@ -29,6 +41,8 @@ struct WorldInfo : public Serializable { int64_t nextInventoryId = 1; int64_t nextPlayerId = 0; + dv::value logic = defaultLogic(); + /// @brief Day/night loop timer in range 0..1 where /// 0.0 - is midnight and /// 0.5 - is noon @@ -45,6 +59,12 @@ struct WorldInfo : public Serializable { bool isLoaded = false; + dv::value getLogicValue( + const std::string& name, const dv::value& def = nullptr + ) const; + void setLogicValue(const std::string& name, dv::value value); + bool getLogicFlag(const std::string& name, bool def = true) const; + dv::value serialize() const override; void deserialize(const dv::value& src) override; }; diff --git a/src/world/files/WorldFiles.cpp b/src/world/files/WorldFiles.cpp index 8e471772a..c06df4160 100644 --- a/src/world/files/WorldFiles.cpp +++ b/src/world/files/WorldFiles.cpp @@ -235,3 +235,23 @@ void WorldFiles::removeIndices(const std::vector& packs) { io::path WorldFiles::getFolder() const { return directory; } + +static void replace_all( + dv::value& list, const std::string& unit, const std::string& placeholder +) { + for (uint i = 0; i < list.size(); i++) { + auto& name = list[i].asString(); + if (name == unit) { + list[i] = placeholder; + } + } +} + +void WorldFiles::deleteContent(const ContentRemovalRequest& request) { + auto root = io::read_json(getIndicesFile()); + for (const auto& unit : request.units) { + replace_all(root["blocks"], unit, CORE_AIR); + replace_all(root["items"], unit, CORE_EMPTY); + } + io::write_json(getIndicesFile(), root); +} diff --git a/src/world/files/WorldFiles.hpp b/src/world/files/WorldFiles.hpp index f14c3c33c..31f859e2d 100644 --- a/src/world/files/WorldFiles.hpp +++ b/src/world/files/WorldFiles.hpp @@ -23,6 +23,10 @@ class World; struct WorldInfo; struct DebugSettings; +struct ContentRemovalRequest { + std::vector units; +}; + class WorldFiles { io::path directory; WorldRegions regions; @@ -77,5 +81,7 @@ public: return doWriteLights; } + void deleteContent(const ContentRemovalRequest& request); + static const inline std::string WORLD_FILE = "world.json"; }; diff --git a/test/io/memory_ostream.cpp b/test/io/memory_ostream.cpp new file mode 100644 index 000000000..c1f83e0f8 --- /dev/null +++ b/test/io/memory_ostream.cpp @@ -0,0 +1,22 @@ +#include + +#include "io/memory_ostream.hpp" + +TEST(io, memory_ostream) { + const char data[] = "Hello, world!"; + const int n = std::strlen(data); + + memory_ostream stream; + ASSERT_TRUE(stream.good()); + + stream.write(data, n); + ASSERT_EQ(std::string(stream.view()), std::string(data)); + + stream.seekp(0); + ASSERT_TRUE(stream.good()); + stream.write("Remove", 6); + ASSERT_EQ(std::string(stream.view()), "Remove world!"); + + auto buffer = stream.release(); + ASSERT_EQ(std::string(buffer.data(), buffer.size()), "Remove world!"); +} diff --git a/vcpkg.json b/vcpkg.json index 89e0bd844..e6bff2329 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -11,17 +11,9 @@ "zlib", "luajit", "libvorbis", - "entt", "gtest", "curl", "freetype", "openssl" - ], - "builtin-baseline": "802d61d714db2714e3fefcfc59447431166b8367", - "overrides": [ - { - "name": "entt", - "version": "3.16.0" - } ] }