diff --git a/.github/workflows/appimage.yml b/.github/workflows/appimage.yml
index f43254bd3..5bfebeb4d 100644
--- a/.github/workflows/appimage.yml
+++ b/.github/workflows/appimage.yml
@@ -31,7 +31,7 @@ jobs:
sudo apt-get update
sudo apt-get install -y build-essential libglfw3-dev libglfw3 libglew-dev libglew2.2 \
libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev \
- libcurl4-openssl-dev libgtest-dev libfreetype6-dev cmake squashfs-tools valgrind
+ libcurl4-openssl-dev libssl-dev libgtest-dev libfreetype6-dev cmake squashfs-tools valgrind
# 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
@@ -46,13 +46,13 @@ jobs:
- name: Build
run: cmake --build build -t install
- name: Run tests
- run: ctest --test-dir build
+ run: ctest --output-on-failure --test-dir build
- name: Run engine tests
- timeout-minutes: 1
+ timeout-minutes: 5
run: |
chmod +x build/VoxelEngine
chmod +x AppDir/usr/bin/vctest
- AppDir/usr/bin/vctest -e build/VoxelEngine -d dev/tests -u build
+ AppDir/usr/bin/vctest -e build/VoxelEngine -d dev/tests -u build --memchecker valgrind
- name: Build AppImage
uses: AppImageCrafters/build-appimage-action@fe2205a4d6056be47051f7b1b3811106e9814910
env:
diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml
index f41e940e9..52f7b7183 100644
--- a/.github/workflows/cmake.yml
+++ b/.github/workflows/cmake.yml
@@ -39,7 +39,7 @@ jobs:
# make && make install INSTALL_INC=/usr/include/lua
run: |
sudo apt-get update
- sudo apt-get install libglfw3-dev libglfw3 libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev libgtest-dev libcurl4-openssl-dev libfreetype6-dev
+ sudo apt-get install libglfw3-dev libglfw3 libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev libgtest-dev libcurl4-openssl-dev libssl-dev libfreetype6-dev
# 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
diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml
index c3f5156f9..b4d9f6328 100644
--- a/.github/workflows/macos.yml
+++ b/.github/workflows/macos.yml
@@ -23,13 +23,13 @@ jobs:
- name: Install dependencies from brew
run: |
- brew install glfw3 glew libpng openal-soft luajit libvorbis skypjack/entt/entt googletest glm freetype
+ brew install glfw3 glew libpng openal-soft luajit libvorbis skypjack/entt/entt 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=Release -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 }}"
- name: Build
run: |
@@ -45,11 +45,11 @@ jobs:
run: ctest --output-on-failure --test-dir build
- name: Run engine tests
- timeout-minutes: 1
+ timeout-minutes: 5
run: |
chmod +x build/VoxelEngine
chmod +x AppDir/usr/bin/vctest
- AppDir/usr/bin/vctest -e build/VoxelEngine -d dev/tests -u build --output-always
+ AppDir/usr/bin/vctest -e build/VoxelEngine -d dev/tests -u build --output-always --debugger "lldb -batch -o 'run' -o 'thread backtrace all' -o 'quit' -- "
- name: Create DMG
run: |
mkdir VoxelEngineDmgContent
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index d13479cd3..ffcb0c318 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -12,7 +12,7 @@ jobs:
strategy:
matrix:
include:
- - os: windows-latest
+ - os: windows-2022
runs-on: ${{ matrix.os }}
@@ -38,7 +38,7 @@ jobs:
- name: Run engine tests
run: |
build/vctest/RelWithDebInfo/vctest.exe -e build/RelWithDebInfo/VoxelEngine.exe -d dev/tests -u build
- timeout-minutes: 1
+ timeout-minutes: 5
- name: Package for Windows
run: |
mkdir packaged
diff --git a/.gitignore b/.gitignore
index c0b0e1c9d..4d0155832 100644
--- a/.gitignore
+++ b/.gitignore
@@ -49,3 +49,6 @@ appimage-build/
# libs
/libs/
/vcpkg_installed/
+
+# vcstudio
+.vcstudio
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 281924189..74efa6b3e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,6 @@
-# 0.31 - 2026.03.22
+# 0.32 - 2026.10.03
-[Documentation](https://github.com/MihailRis/VoxelEngine-Cpp/tree/release-0.31/doc/en/main-page.md) for 0.31
+[Documentation](https://github.com/MihailRis/VoxelEngine-Cpp/tree/release-0.32/doc/en/main-page.md) for 0.32
Table of contents:
@@ -13,169 +13,288 @@ Table of contents:
## New Features
-- solid entities with solid hitboxes
-- rendering ui to texture with 'frame' element
-- loading vector fonts support with freetype library
-- defining skeletons in VCM files
-- project permissions system
-- executing commands from stdin ('--stdin-cmd' command line argument enables it)
+- animation
+- semi-transparent entities
+- client-side --script, --test support
+- environments (in-development)
+- translators
+- VCA format
## Added
-- added clouds, so sky is no more so deadly clear
-- ui:
- - added 'onmouseenter', 'onmouseleave' events
- - added 'zIndex' common scripting property
- - added 'inventory' scripting property to slot element
- - added 'font' attribute
- - added 'text-align' label attribute
- - added 'frame' element
- - added 'fallback' image attribute
-- particles:
- - added 'spawn_offset' property
-- audio:
- - added acoustic effects (reverb)
- - added 'audio.acoustic-effects' setting
- - added 'record-audio' project permission
-- projects system:
- - added project permissions configuration
- - added 'debugging' permission
-- added 'base:flat_grass' world generator
-- added ssao quality setting
-- added background assets loader
-- vcm format:
- - added 'bone' (model/skeleton node) element
- - added 'tri' (triangle) element
-- added 'on_inventory_interact' hud event
-- added weather properties:
- - 'sky_tint'
- - 'clouds_tint'
- - 'min_sky_light'
-- added block properties:
- - 'grounding-behaviour' (extended blocks)
- - explicit 'solid' visual property
-- added world generator parameters:
- - 'player-spawn-radius'
- - 'player-min-spawn-height'
- - 'player-max-spawn-height'
-- added 'material' entity property
-- added patch number to engine build produced by release pipeline
-- new functions arguments:
- - added 'skeleton_name' argument to assets.parse_model
- - added 'include_non_selectable' argument to block.raycast
- - added 'variant_index' argument to block.get_model, block.model_name, block.get_textures
- - added optional 'emission' argument to gfx.blockwraps.wrap
- - added gui.load_document namespace extension table
-- added freetype dependency
+- events:
+ - main.lua script:
+ - on_scripts_loading
+ - on_content_loaded
+ - world.lua script:
+ - on_entity_spawned
+ - on_entity_despawned
+ - entity component:
+ - on_player_set
+- libraries:
+ - animation
+ - crypto
+ - ctypes
+ - test
+ - vc
+ - xml
+- new classes:
+ - debug.Logger
+ - I8view
+ - I64view
+ - U64view
+ - FLTview
+ - DBLview
+ - private PlayingTrack
+ - private Hash
+- 3d text 'font' property
+- documented:
+ - block `material` property
+- defaults:
+ - block-material
+- permissions:
+ - sub-instances
+- `--log` command line argument
+- `ladder` rotation profile
+- new ui properties:
+ - `select` element `button` mode
+ - `onrightclick`
+ - `onmiddleclick`
+- verbose parsing error messages
+- content menu: pack version display
+- Heightmap.normalNoise field
+- content menu: filtering by pack id
+- `hot-reload` VC-DBG signal
+- `normal` attribute for `tri` and `rect` VCM primitives
+- `lighting-mode` entity property
+- vca syntax highlighting
+- `cull-face` property for `tri` and `rect` VCM primitives
+- `graphics.enable-fog` setting
## New Functions
-- assets.request_texture
-- block.get_hitbox
-- entity.rigidbody:get_elasticity
-- entity.rigidbody:get_mass
-- entity.rigidbody:get_material
-- entity.rigidbody:set_elasticity
-- entity.rigidbody:set_mass
-- entity.rigidbody:set_material
-- entity.rigidbody:get_ground_vel
-- gfx.blockwraps.set_faces
-- gfx.blockwraps.set_tints
-- gui.close_menu
-- gui.create_frame
-- gui.get_active_frame
-- gui.set_active_frame
-- hud.get_second_inventory
-- hud.is_player_inventory_open
-- mat4.perspective
-- quat.from_euler
-- session.get
-- session.has
-- session.reset
+- animation.action
+- animation.play
+- app.get_content
+- app.is_instance_alive
+- app.start_background_instance
+- app.terminate_instance
+- assets.parse_animation
+- Bytearray:copy
+- Bytearray:fill
+- Bytearray:move
+- crypto.aes_gcm_decrypt
+- crypto.aes_gcm_encrypt
+- crypto.chacha20_poly1305_decrypt
+- crypto.chacha20_poly1305_encrypt
+- crypto.constant_time_equal
+- crypto.ecdsa_keypair
+- crypto.ecdsa_public
+- crypto.ecdsa_sign
+- crypto.ecdsa_verify
+- crypto.ed25519_keypair
+- crypto.ed25519_public
+- crypto.ed25519_sign
+- crypto.ed25519_verify
+- crypto.features
+- crypto.hash
+- crypto.hkdf_expand
+- crypto.hkdf_extract
+- crypto.hmac
+- crypto.md5
+- crypto.p256_keypair
+- crypto.p256_public
+- crypto.p256_shared
+- crypto.pbkdf2
+- crypto.random_bytes
+- crypto.rsa_pkcs1_verify
+- crypto.rsa_pss_verify
+- crypto.scrypt
+- crypto.sha256
+- crypto.sha384
+- crypto.sha512
+- crypto.x25519
+- crypto.x25519_keypair
+- crypto.x25519_public
+- crypto.x25519_shared
+- ctypes.int16
+- ctypes.int32
+- ctypes.int64
+- ctypes.int8
+- ctypes.uint16
+- ctypes.uint32
+- ctypes.uint64
+- ctypes.uint8
+- entities.def_solid
+- events.remove
+- file.remove_ext
+- gfx.text3d.get_entity
+- gfx.text3d.set_entity
+- gui.screenshot
+- Hash:final
+- Hash:update
+- Heightmap:ceil
+- Heightmap:cos
+- Heightmap:floor
+- Heightmap:round
+- Heightmap:sin
+- Heightmap:tan
+- input.get_mouse_scroll
+- inventory.set_all_data
+- io_stream:available
+- io_stream:tell
+- io_stream:wrap_bytearray
+- math.noise
+- math.noise2d
+- math.sign
+- network.request
+- PlayingTrack:pause
+- PlayingTrack:stop
+- quat.mul
+- quat.mul_vec3
+- rigidbody:set_selectable
+- socket:as_stream
+- socket:peek
+- socket:peek_async
+- string.url_decode
+- string.url_encode
+- table.keys
+- test.click
+- test.fill
+- test.find_by_attr
+- test.find_by_attr_presence
+- test.find_by_text
+- test.press
+- time.precise_time
+- time.precise_utc_time
+- Tview:typesize
+- vc.get_setting
+- vc.get_setting_info
+- vc.get_version
+- vc.is_client
+- vc.is_headless
+- vc.str_setting
+- world.raycast
+- xml.parse
+- xml.parse_vcd
+- xml.tostring
-now documented:
+New overloads:
-- audio.input.get_input_info
-- gui.ask
-- gui.show_message
+- asserts.equals(Canvas)
+- skeleton:set_color(int, ...)
## Changes
-- minor visual restoration
-- assets.parse_model now supports OBJ format
-- chunks loading optimizations
-- app.load_content, app.reset_content, app.reconfig_packs and app.config_packs calling limited to app script coroutine and time.post_runnable context
-- debug panel updated a bit
-- pass app library from standard pages loader
-- skeletons are now assets
+- inventory interaction enchancements [#897](https://github.com/MihailRis/voxelcore/issues/897)
+- breaking: document events removed from 'events' library temporary
## Fixes
-- [fix vec3 shadeless flag](https://github.com/MihailRis/voxelcore/commit/5e05b44c26c1b57aaceb5e3478ccf5f98e3f14d7)
-- [fix: missing extended block size limit check](https://github.com/MihailRis/voxelcore/commit/9628177698b29488965bffc60fa305e752245c13)
-- [fix extended block grounding](https://github.com/MihailRis/voxelcore/commit/0b7dc14f5512478c7b7df408bab007d06de6f9ae)
-- [fix blocks variants](https://github.com/MihailRis/voxelcore/commit/0cc8c70a1704bf511635c1c1e19fe707e8477127)
-- [fix fatal exception caused by empty skeleton model texture name](https://github.com/MihailRis/voxelcore/commit/fc04284b34d5dfc8afd008933b61644dda6b73c6)
-- [fix blocks random tick](https://github.com/MihailRis/voxelcore/commit/9ac8406558ebe6183071545aeb8e34a968503c18)
-- [fix 'attempt to compare string with number' in audio.input.fetch](https://github.com/MihailRis/voxelcore/commit/ba2546e096c93e13fc0abfcf0e0447eb1721960f)
-- [fix: FFI library access from non-built-in scripts vulnerability](https://github.com/MihailRis/voxelcore/commit/a32845d083f3d2528f04eebe173ed7358cd2cf14)
-- [fix non-lighted chunks saving](https://github.com/MihailRis/voxelcore/commit/5b8c2d6162092f3655e2d857fa75ee42d879e604)
-- [fix: attempting to build lights in non-local players chunk matrices](https://github.com/MihailRis/voxelcore/commit/3308a61d560c2d9bbff0c81d2ed5d391103ec5d0)
-- [fix extended blocks collision detection](https://github.com/MihailRis/voxelcore/commit/c8e884009bdc7b7ee8025b05cfb12284f340d0af)
-- [fix: block inventory not removing in some cases](https://github.com/MihailRis/voxelcore/commit/e4d21c940be9048076180976eaba31f0138661a3)
-- [fix extended blocks culling on chunk borders](https://github.com/MihailRis/voxelcore/commit/7abbe43c3cf21bbf7afa3cf392b08e52950fa163)
-- [fix: player name text is still visible when suspended](https://github.com/MihailRis/voxelcore/commit/49aa7cdfba19ebc6d141dca28f7ed269c2e443fa)
-- [fix: crouching falling prevention does not reset velocity & fix small hitboxes horizontal collision](https://github.com/MihailRis/voxelcore/commit/bfa8b7cf3d483b2ea3f4f7166f49b1682a471363)
-- [fix: macos build pipeline uses OpenAL.Framework instead of openal-soft](https://github.com/MihailRis/voxelcore/commit/cd537cc1cbf490b614cdbd8ab38a3a26364c29f6)
-- [fix: assets access attempts in headless mode leading to segfaults](https://github.com/MihailRis/voxelcore/commit/a92efe581f3b6a37f3217684a7174efb50bb6ef9)
-- [fix crash in headless](https://github.com/MihailRis/voxelcore/commit/2b4c3c08f35c0ce0de85789a27b77a47ce134c53)
-- [fix advanced render setting tooltip](https://github.com/MihailRis/voxelcore/commit/fcbbf4814a10b6db09ba30e90b21be7dc0c96d9f)
-- [fix io_stream.write_line](https://github.com/MihailRis/voxelcore/commit/4809003aa8af28ed04d78a396f32580ee5506c39)
-- [fix bytearray view classes](https://github.com/MihailRis/voxelcore/commit/3f68fc1fc4fce39328a570253583d9a796779d7d)
-- [fix extra faces when dense mode is off](https://github.com/MihailRis/voxelcore/commit/89485dc592f138cd244d61ac6871d745c3e82e9d)
-- [fix fatal error when skeleton is missing](https://github.com/MihailRis/voxelcore/commit/8b5261f4f14ee31894dcf5125a4836ff140de8a9)
-- [fix entity skeleton name serialization](https://github.com/MihailRis/voxelcore/commit/d07c8e523429393a26dbccaaf7fc7275079fa577)
-- [fix on_chunk_register_event](https://github.com/MihailRis/voxelcore/commit/d197415739f0e75369a4b14de808ce9c16c808d8)
-- [fix: player entity body is active before player flight state applied](https://github.com/MihailRis/voxelcore/commit/5785060ffb85edb33c72410e0c65123c094fb3dd)
-- [fix: player not spawning entity after set_suspended(pid, false)](https://github.com/MihailRis/voxelcore/commit/088bfc878efc05fdd92078581068e16d1e38f652)
-- [fix incorrect 3d text preset for existing players](https://github.com/MihailRis/voxelcore/commit/d9a914ee5423ec216e216f6839785a887eb47036)
-- [fix: player.set_suspend(pid, true) leaves entity in the world](https://github.com/MihailRis/voxelcore/commit/a4fc4a5044d394a8f1d054ecf76d18c6ebba0a78)
-- [fix nested vcm elements](https://github.com/MihailRis/voxelcore/commit/22e0c469c006217b82b1dcac9193cd38b8072cd2)
-- [fix unchecked indices buffer overflow](https://github.com/MihailRis/voxelcore/commit/336ae09f669fe734ac9a69ebcbb3550596f26a56)
-- [fix gui.show_input_dialog key:escape reaction](https://github.com/MihailRis/voxelcore/commit/1644751b1a32a3ecc2b4604e4a5a1cb00c7692bd)
-- [fix app.reset_content args](https://github.com/MihailRis/voxelcore/commit/43fa181398c6064fd165cd6244ed4847933cef4c)
-- [fix gfx.posteffects.set_intensity](https://github.com/MihailRis/voxelcore/commit/f171d3e30844c69a0675d23db583f34abdcd4f6c)
-- [fix blocks raycast filter](https://github.com/MihailRis/voxelcore/commit/ce769143f881afbaa1136ec6a0692ff2b4cc2bd4)
-- [fix conditional jump or move depends on uninitialised value in GLFWWindow](https://github.com/MihailRis/voxelcore/commit/e371153288c3eb99e568fe19fb725f151d6a58ac)
-- [fix debugging server creation](https://github.com/MihailRis/voxelcore/commit/72040b5dbb37c6588a53e6d7584f16e98ed0a8e2)
-- [fix on_blocks_tick interval](https://github.com/MihailRis/voxelcore/commit/cd43d9545a52ca153b7548585c65af8b98bbfc7f)
-- [fix: inventory interaction on "disablePlayerInventory = true"](https://github.com/MihailRis/voxelcore/commit/dba10805f8d98aedf6d7ab3f5f8d7ca5c2280e8e)
-- [fix: checkbox hover color](https://github.com/MihailRis/voxelcore/commit/76d5af85cc04b6560e7dde4cb9116b8d6d638036)
-- [fix a typo in the vector3:rot and duplicate vector2.\_\_eq](https://github.com/MihailRis/voxelcore/commit/334666a5615e0996fa036cc44ed94777aee76867)
-- [fix gfx.blockwraps.set_texture](https://github.com/MihailRis/voxelcore/commit/e423c746280c690ab26a217b1e8668253cdd1372)
-- [fix: chunk border wigth change when render block selection](https://github.com/MihailRis/voxelcore/commit/963e7d78f5f555940517e9afa4dccafbe7085d17)
-- [fix block model change wrapper reaction](https://github.com/MihailRis/voxelcore/commit/6d6d38c2180ae79d69498acdd3a525399579995a)
-- [fix: InventoryView: when moving one object with the right mouse button, the phantom remained](https://github.com/MihailRis/voxelcore/commit/c7da5fa5698113710dca986516372a483ebfa0c7)
-- [fix: integers signs are unspecified in binary_json_spec.md](https://github.com/MihailRis/voxelcore/commit/e5f9e4d02aba96678afac533be9679523487006b)
-- [fix fragment:place lights](https://github.com/MihailRis/voxelcore/commit/7a513949e94764797abd09410836f4475da8156a)
-- [fix: 'shadeless' block property ignored if custom model is used](https://github.com/MihailRis/voxelcore/commit/78062e2197be750d3a6fa87d44e8079286323cdd)
-- [fix custom model blocks lighting](https://github.com/MihailRis/voxelcore/commit/36f7fb759a6266edae91f2e2986882eba066bdaf)
-- [fix inventory.set](https://github.com/MihailRis/voxelcore/commit/c394df4e07641b9c18dc8a4ee1bcd1c519a82f66)
-- [fix fatal error on invalid item id in inventory](https://github.com/MihailRis/voxelcore/commit/180dd5051b5a7358200ae705fd20b632b0d96f72)
-- [fix on_block_tick timer](https://github.com/MihailRis/voxelcore/commit/77b4382577dc9cc3a21317190290e9019355ec9b)
-- [fix on_block_tick triggered while paused](https://github.com/MihailRis/voxelcore/commit/4d53eb97c359b7453209af91eedfe56b03042a6e)
-- [fix hover elements lifetime](https://github.com/MihailRis/voxelcore/commit/55e4e6de02e606b756dba57cefe2fdb3574c389d)
-- [fix shadeless blocks with soft lights disabled](https://github.com/MihailRis/voxelcore/commit/ea8e1301eadcc1298668bcc5d7c6d9893f916e1d)
-- [fix libpng error handling](https://github.com/MihailRis/voxelcore/commit/ba405ee6fc1541c2e84f62a6a047da711a313ff4)
-- [fix corrupted voxel reset](https://github.com/MihailRis/voxelcore/commit/e0b5c8457b93d2caa9d7959a28960cd456bbd61d)
-- [fix overriden content units scripts overriding](https://github.com/MihailRis/voxelcore/commit/719ba6e17a995d689e2c6e4845d920b6c42856c1)
-- [fix block ticks](https://github.com/MihailRis/voxelcore/commit/4a880177da63b282d0889493c4497bf81c4780ae)
-- [fix nil coords passed to on_block_tick](https://github.com/MihailRis/voxelcore/commit/ee21debe520a48759af9bbe2a27de148d91b371c)
-- [fix: incomplete size transform support by entities](https://github.com/MihailRis/voxelcore/commit/fefc975832685f1377736aefd8a048b1fd943130)
-- [fix exception if model having invalid variable texture passed to modelviewer](https://github.com/MihailRis/voxelcore/commit/1d56d83b72d59da34ceac5cc104ce3aa278dd299)
-- [fix canvas:set_data with table argument](https://github.com/MihailRis/voxelcore/commit/e678195a2ae3cfd1ddc39435dd103292806dd4bc)
-- [fix generated item's script](https://github.com/MihailRis/voxelcore/commit/4df4209bc59944e97102be7a618292378dc301a4)
-- [fix ui elements overriding](https://github.com/MihailRis/voxelcore/commit/c214d70f1d33785f9262c552a6f7b933b41e9125)
-- [fix: pack environment not passed to components](https://github.com/MihailRis/voxelcore/commit/69cf4c1c046281106571341702c48d74c27a3788)
-- [fix 'unexpected end' while parsing .obj](https://github.com/MihailRis/voxelcore/commit/31e7a4ebc0076b6fdb12f4775ffba0903a11ba4e)
-- [fix: bad_alloc if canvas element size is negative](https://github.com/MihailRis/voxelcore/commit/7c74eece99e1ec52e3022803975c92b951ec11c0)
+- [fix exception safety in util::stack_vector::push_back](https://github.com/MihailRis/voxelcore/commit/273682355a32827658568757a76830864249a12d)
+- [fix recursive iframe](https://github.com/MihailRis/voxelcore/commit/c3b50b5ab2ebc88719e25f8964d70a4f389e389f)
+- [fix infinite recursion on moveInto used to move to descendant node](https://github.com/MihailRis/voxelcore/commit/4f1411b005859a510fe8d8f1af8db9b848dd4454)
+- [fix camera exponentially shaking](https://github.com/MihailRis/voxelcore/commit/3de6d7f4025f310426a5111fa6ce047e190888f1)
+- [fix slow xml/vcm loading in Windows](https://github.com/MihailRis/voxelcore/pull/983)
+- [fix file.ext](https://github.com/MihailRis/voxelcore/commit/b9b17358a1576e740c4dcf7cf28e553b9d829db0)
+- [fix stack_vector](https://github.com/MihailRis/voxelcore/commit/1fbf16e3dcf145f322849b182be20bac1272a82b)
+- [fix audio.input.request_open](https://github.com/MihailRis/voxelcore/commit/8a19c903e44b7569a38e470ec7b260a03cd4d673)
+- [fix: block/item.properties not inheriting parent content unit properties](https://github.com/MihailRis/voxelcore/commit/a9d185256ae14789c17b005b27f7be94895f7dca)
+- [fix: player name 3d text not updating by Decorator](https://github.com/MihailRis/voxelcore/commit/33db2633a282a9ba532143e223e3ae8b4d12fc22)
+- [fix lua::toquat](https://github.com/MihailRis/voxelcore/commit/9d7e95db807f6210cd18e3e4b58d05eb5ab165d3)
+- [fix: destroyed skeleton config access on skeleton reload](https://github.com/MihailRis/voxelcore/commit/9893c09fd5459eda2f013b7603fd32db18e02b98)
+- [fix entity bounding box check on block place](https://github.com/MihailRis/voxelcore/commit/bb44b4186bd617281614c5f04329bd4221b08c0d)
+- [fix: cursor is not hidden in wayland if previously changed by glfwSetCursor](https://github.com/MihailRis/voxelcore/commit/6896fa433ca2a5f6bfd5205072edfaded7107a42)
+- [fix process_properties](https://github.com/MihailRis/voxelcore/commit/dde8c674b81835e6d7a6591bd0732a9c5c140be0)
+- [fix stringutil locale-related functions](https://github.com/MihailRis/voxelcore/commit/30177b9d2a3f87955005f39418dbcf8b1c76dfca)
+- [fix teleports loop on low obstacles](https://github.com/MihailRis/voxelcore/commit/e28af89de2ff4b79cbfc84515005fc3ae3074004)
+- [fix entity spawn/despawn](https://github.com/MihailRis/voxelcore/commit/2dd8024b7e0f82bfc79cd6e5e389c3dd6a5a700c)
+- [fix 3d text scaling in projected display mode](https://github.com/MihailRis/voxelcore/commit/736cdb0980f68f64e5b3c0135cf5962169c05349)
+- [fix audio.play type checks](https://github.com/MihailRis/voxelcore/commit/6daaa4895bee30e4a92b3e769116ec8e473f2728)
+- [fix app.reconfig_packs](https://github.com/MihailRis/voxelcore/commit/73837082c2f629614dd28e04880d9ca6f59908b1)
+- [fix skeletons behaviour in preload.json](https://github.com/MihailRis/voxelcore/commit/acff9454924f630fb69719f868e78bcf319956e4)
+- [fix LevelScreen::saveWorldPreview](https://github.com/MihailRis/voxelcore/commit/91b14f4264b57cda3779e991b426bf832fc1d9a7)
+- [fix core:player component mob.set_flight call](https://github.com/MihailRis/voxelcore/commit/66796019af77d33be0577bb7bf7a0f30307246e7)
+- [fix components parent environment](https://github.com/MihailRis/voxelcore/commit/dcaf87988bfac2b622eba4003ff7c52b41088601)
+- [fix utf8.sub behaviour](https://github.com/MihailRis/voxelcore/commit/31478977099e501752271094802a6f057eb4f01e)
+- [fix multiline textbox wrappping](https://github.com/MihailRis/voxelcore/commit/99c66c61bb4da0b8defc7aa3219088de32ae4fab)
+- [fix: manually changing textbox.caret does not reset selection](https://github.com/MihailRis/voxelcore/commit/843cc3769dffe1318b32a25f1dbeb8a0390a074d)
+- [fix tick intervals in headless mode](https://github.com/MihailRis/voxelcore/commit/0975fcd8193025c171acf0644babfb570e53c468)
+- [fix player ticks](https://github.com/MihailRis/voxelcore/commit/47f2bf75d79f73a28afd618f52509767c0876881)
+- [fix selection reset on end reached with shift pressed](https://github.com/MihailRis/voxelcore/commit/1d4abd7758db633fd389990ddd015f37c5803ed3)
+- [fix textbox scrolling](https://github.com/MihailRis/voxelcore/commit/bebb5049efaa8b242b3eba25eeb8227dfb06a161)
+- [fix lua syntax highlighting](https://github.com/MihailRis/voxelcore/commit/b307b5c93b6ab2d2102e81310e3441930f55e682)
+- [fix controls settings panel height](https://github.com/MihailRis/voxelcore/commit/c4bddba6b73a42b7ed1da4cbc81e4c79d48b7117)
+- [fix lua::bytearray_as_string](https://github.com/MihailRis/voxelcore/commit/3f81494d4b14f3a8d6be0f9e9a489f0d26c88e37)
+- [particles fix](https://github.com/MihailRis/voxelcore/commit/e6ac30143c8e0ade446d61b92119ebdecb616e28)
+- [blocks.fill fix](https://github.com/MihailRis/voxelcore/commit/31a90bd91172eb07923ea41c0ed18bdaee83f462)
+- [lighting fix](https://github.com/MihailRis/voxelcore/commit/0bbde3a778762f7f6740cd65b494824111313c2e)
+- [fix gui.load_document environment extension](https://github.com/MihailRis/voxelcore/commit/b1974405c69596edf0cfd4a4b5cd42ba0d65448e)
+- [fix serialization error for specific types](https://github.com/MihailRis/voxelcore/commit/2f729bd3cbb793f20c5e060a75e38a18d0d88d0f)
+- [fix vcm texture sides](https://github.com/MihailRis/voxelcore/commit/38bebac37ee2a290315c3148576e98c825efa46d)
+- [fix post-runnable context in content-related functions](https://github.com/MihailRis/voxelcore/commit/0ffefddee1781389fc6e8014ea00856e09cfff1d)
+- [fix: app.reconfig_packs attempts to remove indices in generator test mode](https://github.com/MihailRis/voxelcore/commit/ce189c810d13512225b82933724603781a1ecef1)
+- [fix: duplicating core:chat event handlers in in-game chat](https://github.com/MihailRis/voxelcore/commit/52829023c2718876ce97bc91345b3cadfdd7d10e)
+- [fix document events & breaking: document events removed from 'events' library temporary](https://github.com/MihailRis/voxelcore/commit/089bcbbb64b8009db03fb9b6ed04c491e46d6933)
+- [fix uinode.parent property](https://github.com/MihailRis/voxelcore/commit/902c885fe0d72cbe5bd2ea9a95d4551516197d4a)
+- [fix ui elements related things](https://github.com/MihailRis/voxelcore/commit/84b2aef81f82d46b07d9bd059540d7ac90cae3ec)
+- [fix segfault on world.get_chunk_data if no world open](https://github.com/MihailRis/voxelcore/commit/4a11dd28ec9b7a0344c21a6fc4c3ab80c429eb50)
+- [fix ceiling collision](https://github.com/MihailRis/voxelcore/commit/625a5caeccbce1d06a0ad1c743e56995d9b42343)
+- [fix of io_stream:read_fully for binary and yield mode](https://github.com/MihailRis/voxelcore/commit/fdec2d722d2b81e7bdbdfec2209a9df28d10dde0)
+- [fix of io_stream:available for non-buffered streams when "length" arg defined](https://github.com/MihailRis/voxelcore/commit/cd040cfeb47f91b29c6d138f745b442483f4cf44)
+- [fix dead skeleton model references](https://github.com/MihailRis/voxelcore/commit/9d3a60328f7a44e0361a31e2e8c5b9079282810b)
+- [fix maths_inline version of mat4.rotate](https://github.com/MihailRis/voxelcore/commit/87310dd38f848ca059b627fc0b6d1d2503d05071)
+- [fix BasicParser power function](https://github.com/MihailRis/voxelcore/commit/c45d994216e57811b36d9463fab7ad2c7cc051c0)
+- [fix exponential notation parsing (](https://github.com/MihailRis/voxelcore/commit/b024b6cddfcee9bc436d8260cdb3f1647087af96 "fix exponential notation parsing (#857)")[#857](https://github.com/MihailRis/voxelcore/pull/857)[)](https://github.com/MihailRis/voxelcore/commit/b024b6cddfcee9bc436d8260cdb3f1647087af96)
+- [fix graphics settings & reduce extra GL calls](https://github.com/MihailRis/voxelcore/commit/5b868ae857b1b425a4f529c663b3dad55fcbf59a)
+- [fix integer raycast filters & add simple raycast test](https://github.com/MihailRis/voxelcore/commit/39a42365534ebd4c4c0be690e9ea0646e1459a7b)
+- [fix canvas:encode produces flipped images for png](https://github.com/MihailRis/voxelcore/commit/279fb92b94a0f8b8d28ed141b54b160450ec91f7)
+- [fix canvas:line lines clipping](https://github.com/MihailRis/voxelcore/commit/a5596ed5cd65bc62b983ec9dff3263beeced2dd7)
+- [fix newly created raycast bug](https://github.com/MihailRis/voxelcore/commit/46b4aab6dce9e7c195b5c29584168f8e5b8fbb52)
+- [fix Skeleton::setConfig](https://github.com/MihailRis/voxelcore/commit/a0b7e81a94d8a4f2750fbbd507ba6bd2e688f8b4)
+- [fix audio input device settings](https://github.com/MihailRis/voxelcore/commit/a99c6aa8e08d440d9b049007747ac769c2fff431)
+- [fix: missing font usage produces fatal error](https://github.com/MihailRis/voxelcore/commit/420d0daf28853e1db1a985f9a74ec38f3d978ddc)
+- [fix texture-faces reading](https://github.com/MihailRis/voxelcore/commit/d3eb7a10bea6825c0ff2da9f459a1b528a6a410f)
+- [fix the margin](https://github.com/MihailRis/voxelcore/commit/86fdcb289b1cfa510c861c677731599b4f0f0519)
+- [fix components order & add skeleton:get_matrix overload & add skeleton:reset_pose](https://github.com/MihailRis/voxelcore/commit/8242d299ed68c8f27e691e464562e43c936788da)
+- [fix user component initialization exception handling & fix fatal error on uninitialized component access](https://github.com/MihailRis/voxelcore/commit/28385f236c3e3d2ccf020b116f08a8f6d33ec1a3)
+- [fix projected 3d text for non-monospace fonts](https://github.com/MihailRis/voxelcore/commit/4837e1de027e738bd59c4ba9c91b654e5d866f9a)
+- [fix custom model blocks render (with some conditions)](https://github.com/MihailRis/voxelcore/commit/e0be7a8d8c9f8d54d7af1b6b976fefc941ebba1f)
+- [fix 3d texts antialiasing render issue](https://github.com/MihailRis/voxelcore/commit/40e73ca34b14939468f64a5d349a98400e704bbb)
+- [fixing errors in rules.lua](https://github.com/MihailRis/voxelcore/commit/81af4b9e2acba5d67b5bacdb343618c686dd9d5f)
+- [fix block.index() calls in grass_block.lua and export base:util.calc_loot()](https://github.com/MihailRis/voxelcore/commit/2eae8f6f275e7a41ac30309e61f8d22d8a644ac7)
+- [fix fix lua version comparision](https://github.com/MihailRis/voxelcore/commit/4be73acc61f6805c9df2743e68a86ee646d43e25)
+- [fix lua version compare](https://github.com/MihailRis/voxelcore/commit/9444dc0c4596bd0c1fd2710488c8d412da8aab1f)
+- [fix zIndex type in docs](https://github.com/MihailRis/voxelcore/commit/c445f1a68f9bc1c9c9877cd91d010a1dd5240f0d)
+- [fix double click behaviour](https://github.com/MihailRis/voxelcore/commit/9ea50148b8a02a74befbcbc618a6a7dca7643316)
+- [fix horizontal panel behaviour](https://github.com/MihailRis/voxelcore/commit/2448869bf922a5773dbfd420a0a0e2cb151b0712)
+- [fix: stdcomp calling non-component global functions](https://github.com/MihailRis/voxelcore/commit/64a5a74f53722aa0db17b47bd0aa9fce106a661c)
+- [fix missing keys support](https://github.com/MihailRis/voxelcore/commit/df67236adbb9c29eddb3ec5a455dd61fb03c0a16)
+- [fix: temporary focus fix](https://github.com/MihailRis/voxelcore/commit/9fa6070cced55583ff6e0eaa654e4ca5b5495c32)
+- [fix rivers in base:demo](https://github.com/MihailRis/voxelcore/commit/75cd9aeefb2cccb544e0169063908760977d6615)
+- [fix gui.ask](https://github.com/MihailRis/voxelcore/commit/dd7e01488f3cbc4b2df58a945027ac3a9ea35eac)
+- [fix 3d text render](https://github.com/MihailRis/voxelcore/commit/717d41e7a544d657ae8b27397b5c5dbd9fb50b80)
+- [fix skeleton:get_model](https://github.com/MihailRis/voxelcore/commit/a73c181b0173b4d1c61159e03407cb5f3b3eb3bd)
+- [fix iframe.src = ""](https://github.com/MihailRis/voxelcore/commit/e2a65412bc6d49b0b2d264b11cd8df2e2c4e1d8f)
+- [fix blank texture overwritten by screen frame output](https://github.com/MihailRis/voxelcore/commit/fa0f87349b5c61ee0ca43d7d6b5b64237c39a6a4)
+- [fix stairs model](https://github.com/MihailRis/voxelcore/commit/423685139fe83bb2e571fbdfa41327ce61a64dd0)
+- [fix custom models solidity detection](https://github.com/MihailRis/voxelcore/commit/02dbd01e73f2c69168a1ba4c1929c9d5be263718)
+- [fix default vcm aabb uv generation](https://github.com/MihailRis/voxelcore/commit/693befcde8d6a4dddfc9049d74d303b027953b25)
+- [fix panel extra interval at end](https://github.com/MihailRis/voxelcore/commit/bd4d5f0e4bc8dd1d9652cde42b3c2b13a9924be4)
+- [fix xml escapes in attribute values](https://github.com/MihailRis/voxelcore/commit/fc8065e5505654906e59d744ba636753d79e0210)
+- [fix Texture::reload](https://github.com/MihailRis/voxelcore/commit/f2018334cb97c7b9a8187eb4e155dbda97b0b1cb)
+- [fix side collision](https://github.com/MihailRis/voxelcore/commit/78e27c812a87c8ee2cec1d6605049b9f8535ef2d)
+- [fix WorldConverter::createBlockFieldsConvertTasks](https://github.com/MihailRis/voxelcore/commit/fbe992755e70a3b4d321dc7d17981aec512bf0c1)
+- [fix heightmap noise multiplier argument](https://github.com/MihailRis/voxelcore/commit/95b9b346ac16a50d3c72423503f579d3d712c392)
+- [fix blocks render at the top of the world](https://github.com/MihailRis/voxelcore/commit/8214f1bd096ca3682212ac57648017ab8179948f)
+- [fix containers scroll](https://github.com/MihailRis/voxelcore/commit/bf50c37b823cab0a5bc20d8877ae4b5c23eee697)
+- [fix typos in comments and log messages](https://github.com/MihailRis/voxelcore/commit/515e27b402fd09a33d0e9800792e15f1f6caa7f8)
+- [fix models load functions](https://github.com/MihailRis/voxelcore/commit/395dc15fb6460d5e50c3e613cb1ea46d3332580c)
+- [fix rig:set_matrix for nil index](https://github.com/MihailRis/voxelcore/commit/4370eedc0a4324de15916f1a7890295133aa75c3)
+- [fix maths_inline mat4.idt(dst)](https://github.com/MihailRis/voxelcore/commit/32876aa9e461afb687ddb1f94a8672bd81543018)
+- [fixed packages for arch distro](https://github.com/MihailRis/voxelcore/commit/05cea922eb334607a2ffbb9229b9f22bf6b2dc74)
+- [fix weather effects render](https://github.com/MihailRis/voxelcore/commit/9989f8119601b6f8d21eaccc7c554253a5cd5667)
+- [fix missing textures load request for vcm](https://github.com/MihailRis/voxelcore/commit/41713e89a4f2a8d83d7dc62f8d25b7e23653c8ca)
+- [fix: block fields not inherited](https://github.com/MihailRis/voxelcore/commit/7d0f714cf232809f609862c3a2b793ae84012e5e)
+- [fix: validate content pack dependency versions](https://github.com/MihailRis/voxelcore/commit/28b849229c7bd7d52c25aa1f009ff1d342f3f423)
+- [fix custom model blocks with disabled ambient-occlusion](https://github.com/MihailRis/voxelcore/commit/56d2ab9f1466b781a45e17298c3b4907c70a40bc)
diff --git a/CMakePresets.json b/CMakePresets.json
index 47ba71e34..86a6fd075 100644
--- a/CMakePresets.json
+++ b/CMakePresets.json
@@ -2,19 +2,52 @@
"version": 6,
"configurePresets": [
{
- "name": "default-vs-msvc-windows",
+ "name": "windows-msvc-base",
+ "hidden": true,
"condition": {
"type": "equals",
"rhs": "${hostSystemName}",
"lhs": "Windows"
},
- "generator": "Visual Studio 17 2022",
"binaryDir": "${sourceDir}/build",
"cacheVariables": {
"CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake",
"VOXELENGINE_BUILD_TESTS": "ON"
}
},
+ {
+ "name": "default-vs-msvc-windows",
+ "displayName": "Visual Studio (auto: latest installed)",
+ "inherits": "windows-msvc-base"
+ },
+ {
+ "name": "vs2022",
+ "displayName": "Visual Studio 2022",
+ "inherits": "windows-msvc-base",
+ "generator": "Visual Studio 17 2022"
+ },
+ {
+ "name": "vs2026",
+ "displayName": "Visual Studio 2026",
+ "inherits": "windows-msvc-base",
+ "generator": "Visual Studio 18 2026"
+ },
+ {
+ "name": "default-ninja-mingw-windows",
+ "condition": {
+ "type": "equals",
+ "lhs": "${hostSystemName}",
+ "rhs": "Windows"
+ },
+ "generator": "Ninja Multi-Config",
+ "binaryDir": "${sourceDir}/build-mingw",
+ "cacheVariables": {
+ "CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake",
+ "VCPKG_HOST_TRIPLET": "x64-mingw-static",
+ "VCPKG_TARGET_TRIPLET": "x64-mingw-static",
+ "VOXELENGINE_BUILD_TESTS": "ON"
+ }
+ },
{
"name": "default-ninja-gnu-linux",
"condition": {
@@ -60,6 +93,11 @@
"configurePreset": "default-vs-msvc-windows",
"configuration": "Debug"
},
+ {
+ "name": "default-ninja-mingw-windows",
+ "configurePreset": "default-ninja-mingw-windows",
+ "configuration": "Debug"
+ },
{
"name": "default-ninja-gnu-linux",
"configurePreset": "default-ninja-gnu-linux",
diff --git a/Dockerfile b/Dockerfile
index da90324fc..3a06d1afc 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -26,6 +26,7 @@ RUN apt-get update && apt-get install --no-install-recommends -y \
libvorbis-dev \
libcurl4-openssl-dev \
libfreetype6-dev \
+ libssl-dev \
ca-certificates \
wget \
&& rm -rf /var/lib/apt/lists/*
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000..d0a1fa148
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
diff --git a/README.md b/README.md
index 1d6a462c9..72fb19957 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
## Latest release
- [Download](https://github.com/MihailRis/VoxelCore/releases/latest) | [Скачать](https://github.com/MihailRis/VoxelCore/releases/latest)
-- [Documentation](https://github.com/MihailRis/VoxelCore/blob/release-0.31/doc/en/main-page.md) | [Документация](https://github.com/MihailRis/VoxelCore/blob/release-0.31/doc/ru/main-page.md)
+- [Documentation](https://github.com/MihailRis/VoxelCore/blob/release-0.32/doc/en/main-page.md) | [Документация](https://github.com/MihailRis/VoxelCore/blob/release-0.32/doc/ru/main-page.md)
---
@@ -18,7 +18,7 @@ Installing last version that supports C++17.
```sh
git clone --branch v3.16.0 https://github.com/skypjack/entt.git
cd entt
-mkdir build && cd build
+mkdir -p build && cd build
cmake -DCMAKE_BUILD_TYPE=Release -DENTT_INSTALL=ON ..
sudo make install
```
@@ -55,22 +55,8 @@ sudo dnf install glfw-devel glew-devel glm-devel libpng-devel libvorbis-devel op
#### Arch based distros
-If you use X11:
-
```sh
-sudo pacman -S glfw-x11 glew glm libpng libvorbis openal luajit libcurl freetype2
-```
-
-If you use Wayland:
-
-```sh
-sudo pacman -S glfw-wayland glew glm libpng libvorbis openal luajit libcurl freetype2
-```
-
-And install EnTT:
-
-```sh
-yay -S entt
+sudo pacman -S glfw glew glm libpng libvorbis openal luajit curl freetype2
```
### Building engine with CMake
@@ -152,6 +138,26 @@ cmake --build --preset default-vs-msvc-windows
> [!NOTE]
> Make sure your `CMakeUserPresets.json` (if used) contains the correct `VCPKG_ROOT` path.
+---
+### Building with CLion (MinGW / Ninja)
+
+> [!NOTE]
+> Requirements: **vcpkg**, **Git**, and **CLion** (bundled with CMake, Ninja and MinGW toolchain).
+
+> [!WARNING]
+> Avoid installing tools in paths with spaces (e.g. `Program Files`).
+> This may break MinGW builds (especially `windres`).
+
+Install **vcpkg** manually as described in the Visual Studio section.
+
+
+#### Configure CLion
+Open the project in CLion and configure CMake profile:
+```text
+Settings → Build, Execution, Deployment → CMake
+```
+Reload CMake project and build the engine.
+
---
## Build using Docker
diff --git a/dev/tests/attachments/line_clipping_test.png b/dev/tests/attachments/line_clipping_test.png
new file mode 100644
index 000000000..bb20d1841
Binary files /dev/null and b/dev/tests/attachments/line_clipping_test.png differ
diff --git a/dev/tests/bytearray.lua b/dev/tests/bytearray.lua
index 415768c65..71e895d37 100644
--- a/dev/tests/bytearray.lua
+++ b/dev/tests/bytearray.lua
@@ -18,19 +18,86 @@ Bytearray.insert(arr, {5, 3, 6})
assert(#arr == 12)
Bytearray.insert(arr, 2, 8)
-assert(#arr == 13)
+asserts.equals(13, #arr)
for i=1,10 do
assert(arr[i] == 10 - i)
end
print(#arr, arr:get_capacity())
arr:trim()
-assert(#arr == arr:get_capacity())
+asserts.equals(#arr, arr:get_capacity())
arr = Bytearray({0, 2, 7, 1, 16, 75, 25})
assert(arr[6] == 75)
arr:insert(2, {5, 6})
-assert(arr[#arr] == 25)
-assert(arr[2] == 5)
-assert(arr[3] == 6)
+asserts.equals(25, arr[#arr])
+asserts.equals(5, arr[2])
+asserts.equals(6, arr[3])
+
+-- =============================
+
+arr = Bytearray({254, 255, 255, 255, 255, 255, 255, 255})
+asserts.equals(U64view(arr)[1], ctypes.uint64(2) ^ 64 - 2)
+asserts.equals(I64view(arr)[1], -2)
+asserts.equals(U32view(arr)[1], 2 ^ 32 - 2)
+asserts.equals(I32view(arr)[1], -2)
+asserts.equals(U16view(arr)[1], 2 ^ 16 - 2)
+asserts.equals(I16view(arr)[1], -2)
+asserts.equals(I8view(arr)[1], -2)
+
+asserts.equals(I8view(arr)[2], -1)
+asserts.equals(I32view(arr)[2], -1)
+
+arr = Bytearray({0xFF, 0x7F})
+local arri16 = I16view(arr)
+local arru16 = U16view(arr)
+asserts.equals(arri16[1], 32767)
+
+arru16[1] = arru16[1] + 1
+asserts.equals(arri16[1], -32768)
+asserts.equals(arru16[1], 32768)
+
+arr = Bytearray({0x9A, 0x99, 0x59, 0x40}) -- approx. equal 3.4 in hexadecimal representation of single-precision float number.
+local arrflt = FLTview(arr)
+local arru32 = U32view(arr)
+asserts.equals(arrflt[1], 3.4000000953674316)
+asserts.equals(arru32[1], 0x4059999A)
+
+arrflt[1] = arrflt[1] + 0.1
+asserts.equals(arrflt[1], 3.5)
+asserts.equals(arru32[1], 0x40600000) -- hexadecimal representation of 3.5 single-precision float number.
+
+arr = Bytearray({0x18, 0x2D, 0x44, 0x54, 0xFB, 0x21, 9, 64}) -- hexadecimal representation of 3.141592653589793 double-precision float number.
+assert(DBLview(arr)[1] == 3.141592653589793)
+
+-- =============================================
+
+function barrtostr(barr)
+ local outstr = ""
+ for i = 1, #barr do
+ local lastfmt = ""
+ if i ~= #barr then lastfmt = "|" end
+ outstr = outstr .. barr[i] .. lastfmt
+ end
+ return outstr
+end
+
+arr = Bytearray({0, 5, 34, 87, 21, 0, 210})
+asserts.equals(barrtostr(arr), "0|5|34|87|21|0|210")
+arr:move(2, 3, 4)
+asserts.equals(barrtostr(arr), "0|5|5|34|87|21|210")
+
+local arr2 = Bytearray({1, 2, 3, 4, 6, 7, 8})
+asserts.equals(barrtostr(arr2), "1|2|3|4|6|7|8")
+arr:copy(4, arr2, 2, 3)
+asserts.equals(barrtostr(arr2), "1|34|87|21|6|7|8")
+
+arr:fill(nil, nil, 192)
+asserts.equals(barrtostr(arr), "192|192|192|192|192|192|192")
+arr:fill(nil, 3, 233)
+asserts.equals(barrtostr(arr), "233|233|233|233|233|233|233")
+arr:fill(2, nil, 254)
+asserts.equals(barrtostr(arr), "254|254|254|254|254|254|254")
+arr:fill(2, 2, 66)
+asserts.equals(barrtostr(arr), "254|66|66|254|254|254|254")
diff --git a/dev/tests/canvas_lines.lua b/dev/tests/canvas_lines.lua
new file mode 100644
index 000000000..c7ef68520
--- /dev/null
+++ b/dev/tests/canvas_lines.lua
@@ -0,0 +1,51 @@
+local W, H = 128, 128
+
+local canvas = Canvas({W, H})
+canvas:clear(0xff202020)
+
+local WHITE = 0xffffffff
+local RED = 0xffff4040
+local GREEN = 0xff40ff40
+local BLUE = 0xff4080ff
+local YELLOW = 0xffffff40
+
+-- border
+canvas:line(0, 0, W - 1, 0, WHITE)
+canvas:line(W - 1, 0, W - 1, H - 1, WHITE)
+canvas:line(W - 1, H - 1, 0, H - 1, WHITE)
+canvas:line(0, H - 1, 0, 0, WHITE)
+
+-- horizontal
+canvas:line(-40, 16, W + 40, 16, RED)
+canvas:line(-40, H / 2, W + 40, H / 2, RED)
+canvas:line(-40, H - 17, W + 40, H - 17, RED)
+
+-- vertical
+canvas:line(16, -40, 16, H + 40, GREEN)
+canvas:line(W / 2, -40, W / 2, H + 40, GREEN)
+canvas:line(W - 17, -40, W - 17, H + 40, GREEN)
+
+-- diagonals
+canvas:line(-40, -40, W + 40, H + 40, BLUE)
+canvas:line(-40, H + 40, W + 40, -40, BLUE)
+
+canvas:line(W / 2, -40, W + 40, H / 2, BLUE)
+canvas:line(-40, H / 2, W / 2, H + 40, BLUE)
+
+-- outer
+canvas:line(-30, -30, 20, 20, YELLOW)
+canvas:line(W - 20, H - 20, W + 30, H + 30, YELLOW)
+
+canvas:line(W + 30, -30, W - 20, 20, YELLOW)
+canvas:line(-30, H + 30, 20, H - 20, YELLOW)
+
+-- completely outside
+canvas:line(-50, -20, -10, H + 20, 0xffff00ff)
+canvas:line(W + 10, -20, W + 50, H + 20, 0xffff00ff)
+canvas:line(-20, -20, W + 20, -10, 0xffff00ff)
+canvas:line(-20, H + 10, W + 20, H + 30, 0xffff00ff)
+
+local expected = Canvas.decode(
+ file.read_bytes("script:attachments/line_clipping_test.png"), "png"
+)
+asserts.equals(expected, canvas)
diff --git a/dev/tests/crypto.lua b/dev/tests/crypto.lua
new file mode 100644
index 000000000..96b36ecd9
--- /dev/null
+++ b/dev/tests/crypto.lua
@@ -0,0 +1,41 @@
+assert(crypto.API_VERSION == 1)
+local features = crypto.features()
+assert(features.api_version == 1)
+assert(features.backend == "OpenSSL")
+
+local binary = "a\0b"
+assert(crypto.hash("SHA256", binary) == crypto.sha256(binary))
+local stream = crypto.hash_new("SHA256")
+assert(stream:update("a"):update("\0b"):final() == crypto.sha256(binary))
+stream:reset():update("abc")
+assert(stream:final() == crypto.sha256("abc"))
+
+local private, public = crypto.ed25519_keypair()
+assert(crypto.ed25519_public(private) == public)
+local signature = crypto.ed25519_sign(private, binary)
+assert(crypto.ed25519_verify(public, binary, signature) == true)
+local ok, error_code = crypto.ed25519_verify(public, "changed", signature)
+assert(ok == false and error_code == "invalid_signature")
+
+local x_private_a, x_public_a = crypto.x25519_keypair()
+local x_private_b, x_public_b = crypto.x25519_keypair()
+assert(crypto.x25519(x_private_a, x_public_b) ==
+ crypto.x25519_shared(x_private_b, x_public_a))
+
+local p_private_a, p_public_a = crypto.p256_keypair()
+local p_private_b, p_public_b = crypto.p256_keypair()
+assert(crypto.p256_public(p_private_a) == p_public_a)
+assert(crypto.p256_shared(p_private_a, p_public_b) ==
+ crypto.p256_shared(p_private_b, p_public_a))
+
+local key = crypto.random_bytes(16)
+local nonce = crypto.random_bytes(12)
+local ciphertext = crypto.aes_gcm_encrypt(key, nonce, "aad", binary)
+assert(crypto.aes_gcm_decrypt(key, nonce, "aad", ciphertext) == binary)
+local plaintext, decrypt_error = crypto.aes_gcm_decrypt(
+ key, nonce, "changed", ciphertext
+)
+assert(plaintext == nil and decrypt_error == "authentication_failed")
+
+assert(#crypto.pbkdf2("SHA256", "password", "salt", 1, 32) == 32)
+assert(#crypto.scrypt("password", "salt", 16, 1, 1, 32) == 32)
diff --git a/dev/tests/filesystem.lua b/dev/tests/filesystem.lua
index 38e7c4a04..cb5a052ac 100644
--- a/dev/tests/filesystem.lua
+++ b/dev/tests/filesystem.lua
@@ -1,3 +1,9 @@
+debug.log("file extension")
+asserts.equals(nil, file.ext("config:test"))
+asserts.equals("cfg", file.ext("config:test.cfg"))
+asserts.equals("gz", file.ext("config:test.cfg.gz"))
+asserts.equals("config:test.cfg", file.remove_ext("config:test.cfg.gz"))
+
debug.log("check initial state")
assert(file.exists("config:"))
diff --git a/dev/tests/io_stream.lua b/dev/tests/io_stream.lua
new file mode 100644
index 000000000..d08c68b0c
--- /dev/null
+++ b/dev/tests/io_stream.lua
@@ -0,0 +1,34 @@
+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 line1 = stream:read_line()
+local line2 = stream:read_line()
+
+assert(line1 == "Hello")
+assert(line2 == "World")
+
+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)
+
+local stream3 = file.open(device..":test.txt", 'r')
+assert(stream3:is_alive())
+stream3:close()
+assert(not stream3:is_alive())
+
+local stream4 = file.open(device..":test.txt", 'r')
+stream4:seek('b', 6)
+local line = stream4:read_line()
+assert(line == "World")
+
+local stream5 = file.open(device..":test.txt", 'r')
+stream5:seek('e', 0)
+local pos = stream5:tell()
+assert(pos == 11)
diff --git a/dev/tests/network_http.lua b/dev/tests/network_http.lua
index 6bd9ba797..12149de09 100644
--- a/dev/tests/network_http.lua
+++ b/dev/tests/network_http.lua
@@ -4,8 +4,8 @@ network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/lat
print(json.parse(s).name)
response_received = true
end, function (code)
- print("repond with code", code)
+ print("respond with code", code)
response_received = true
end)
-app.sleep_until(function () return response_received end, nil, 10)
+app.sleep_until(function () return response_received end, nil, 5)
diff --git a/dev/tests/network_tcp.lua b/dev/tests/network_tcp.lua
index 379065476..a7e57ff22 100644
--- a/dev/tests/network_tcp.lua
+++ b/dev/tests/network_tcp.lua
@@ -13,6 +13,7 @@ for i=1,3 do
print("client-listener started")
local received_text = ""
while client:is_alive() and #received_text < #text do
+ client:peek(math.random(0, 100))
local received = client:recv(512)
if received then
received_text = received_text .. utf8.tostring(received)
diff --git a/dev/tests/parsing.lua b/dev/tests/parsing.lua
new file mode 100644
index 000000000..3b1a4840d
--- /dev/null
+++ b/dev/tests/parsing.lua
@@ -0,0 +1,33 @@
+local src = "test"
+local parsed = xml.parse(src)
+asserts.equals(src, xml.tostring(parsed, false))
+
+local src = "{\"test\": \"test\", \"sub\": {\"test\": \"test\"}}"
+local parsed = json.parse(src)
+asserts.equals("test", parsed.test)
+asserts.equals("test", parsed.sub.test)
+
+-- toml
+local src = [[
+[section]
+key = "value"
+# comment
+key2 = "other value"
+number = 42
+pi = 3.14159
+enabled = true
+items = ["a", "b", "c"]
+table = { x = 1, y = 2 }
+]]
+local parsed = toml.parse(src)
+
+asserts.equals("value", parsed.section.key)
+asserts.equals("other value", parsed.section.key2)
+asserts.equals(42, parsed.section.number)
+asserts.equals(3.14159, parsed.section.pi)
+asserts.equals(true, parsed.section.enabled)
+asserts.equals("a", parsed.section.items[1])
+asserts.equals("b", parsed.section.items[2])
+asserts.equals("c", parsed.section.items[3])
+asserts.equals(1, parsed.section.table.x)
+asserts.equals(2, parsed.section.table.y)
diff --git a/dev/tests/raycast.lua b/dev/tests/raycast.lua
new file mode 100644
index 000000000..6016989d8
--- /dev/null
+++ b/dev/tests/raycast.lua
@@ -0,0 +1,47 @@
+local util = require "core:tests_util"
+
+-- Create world and prepare settings
+util.create_demo_world("core:default")
+app.set_setting("chunks.load-distance", 3)
+app.set_setting("chunks.load-speed", 1)
+
+-- Create player
+local pid = player.create("Xerxes")
+player.set_spawnpoint(pid, 0, 100, 0)
+player.set_pos(pid, 0, 100, 0)
+app.sleep_until(function () return block.get(0, 0, 0) ~= -1 end)
+app.sleep_until(function () return block.get(-5, 8, 2) ~= -1 end)
+
+local sand_idx = block.index("base:sand")
+block.set(0, 1, 0, sand_idx)
+
+local start = {-5, 8, 2}
+local target = {0.5, 1.5, 0.5}
+local ray = world.raycast({
+ start = start,
+ dir = vec3.normalize(vec3.sub(target, start)),
+ distance = 10,
+})
+debug.print(ray)
+
+assert(ray, "ray didn't hit")
+util.check_int(sand_idx, ray.block, "ray.block")
+util.check_vec3({0, 1, 0}, ray.normal, "ray.normal")
+util.check_vec3({0.0769, 2, 0.6153}, ray.endpoint, "ray.endpoint")
+util.check_vec3({0, 1, 0}, ray.iendpoint, "ray.iendpoint")
+util.check_float(7.9807, ray.length, "ray.length")
+
+ray = world.raycast({
+ start = start,
+ dir = vec3.normalize(vec3.sub(target, start)),
+ distance = 10,
+ filter_blocks = {sand_idx},
+})
+debug.print(ray)
+
+assert(ray, "ray didn't hit")
+util.check_int(block.index("core:obstacle"), ray.block, "ray.block")
+util.check_vec3({0, 1, 0}, ray.normal, "ray.normal")
+util.check_vec3({0.923, 1, 0.3846}, ray.endpoint, "ray.endpoint")
+util.check_vec3({0, 0, 0}, ray.iendpoint, "ray.iendpoint")
+util.check_float(9.3108, ray.length, "ray.length")
diff --git a/doc/en/3d-text.md b/doc/en/3d-text.md
index b0c9fd1f6..be4a2757f 100644
--- a/doc/en/3d-text.md
+++ b/doc/en/3d-text.md
@@ -4,14 +4,15 @@
The appearance of 3D text, is configured via a table, like [particles](particles.md). All fields are optional.
-| Field | Description | Default |
-| --------------- | ---------------------------- | ---------------- |
-| display | Display format | static_billboard |
-| color | Text color | {1, 1, 1, 1} |
-| scale | Text scale | 1 |
-| render_distance | Text rendering distance | 32 |
-| xray_opacity | Visibility through obstacles | 0 |
-| perspective | Perspective coefficient | 1 |
+| Field | Description | Default |
+| --------------- | ---------------------------------------- | ---------------- |
+| display | Display format | static_billboard |
+| color | Text color | {1, 1, 1, 1} |
+| scale | Text scale | 1 |
+| render_distance | Text rendering distance | 32 |
+| xray_opacity | Visibility through obstacles | 0 |
+| perspective | Perspective coefficient | 1 |
+| font | Font. If absent, the default one is used | "" |
Available display formats:
diff --git a/doc/en/assets-preload.md b/doc/en/assets-preload.md
index f66f451c8..3d2cd6f34 100644
--- a/doc/en/assets-preload.md
+++ b/doc/en/assets-preload.md
@@ -3,11 +3,13 @@
`preload.json` in content-pack folder is used for specifying additional assets should be loaded, like sounds.
The file contains following categories available:
+- animation
- fonts
-- shaders
-- textures
-- sounds
- models
+- shaders
+- skeletons
+- sounds
+- textures
> [!NOTE]
> Sound loading with all variations following template:
diff --git a/doc/en/block-models.md b/doc/en/block-models.md
index ba2f75858..4f598cad7 100644
--- a/doc/en/block-models.md
+++ b/doc/en/block-models.md
@@ -1,23 +1,23 @@
-# Block Models (depricated)
-
-> ![WARNING]
-> The `model-primitives` property is deprecated. Use the [VCM format](vcm.md) for a textual description of the model's primitives.
-
-Block model may be created with following properties:
-
-```js
-"model": "custom",
-"model-primitives": {
- "aabbs": [
- // list of AABB primitives
- ],
- // ... other primitives
-}
-```
-
-**AABB** primitive is an array of values:
-```
-[x, y, z, width, height, depth, texture names for all 6 sides]
-```
-
-**tetragon** primitive (more like parallelogram) an array of three vectors, describing primitive position, X vector \* width, Y vector \* height.
+# Block Models (deprecated)
+
+> ![WARNING]
+> The `model-primitives` property is deprecated. Use the [VCM format](vcm.md) for a textual description of the model's primitives.
+
+Block model may be created with following properties:
+
+```js
+"model": "custom",
+"model-primitives": {
+ "aabbs": [
+ // list of AABB primitives
+ ],
+ // ... other primitives
+}
+```
+
+**AABB** primitive is an array of values:
+```
+[x, y, z, width, height, depth, texture names for all 6 sides]
+```
+
+**tetragon** primitive (more like parallelogram) an array of three vectors, describing primitive position, X vector \* width, Y vector \* height.
diff --git a/doc/en/block-properties.md b/doc/en/block-properties.md
index f3137dd60..82ba10484 100644
--- a/doc/en/block-properties.md
+++ b/doc/en/block-properties.md
@@ -1,6 +1,6 @@
# Block properties
-## Visual
+## Visual & Audio
### *texture*
@@ -69,6 +69,19 @@ Rotation profile (set of available block rotations and behaviour of placing bloc
- "pipe" - wood logs, pipes, pillars
- "pane" - panels, doors, signs
- "stairs" - "pane" + flipped variants
+- "ladder" - like a "pipe", but on horizontal surfaces it is installed like "pane"
+
+### *particles*
+
+Particles are specified as a JSON object. Property names can be found [in the particles section](particles.md).
+
+When camera is near to the block, the engine will create an emitter that will run
+until the block is destroyed or the camera moves away a certain distance.
+
+### Material - *material*
+
+Defines the name of the block's material in the format `pack:material_name`, which affects the selection of block interaction sounds.
+Material definitions are located in /block_materials.
## Variants
@@ -179,12 +192,12 @@ An array of 6 numbers describing an offset an size of a block hitbox.
The numbers are specified in the range [0.0, 1.0] - i.e. within the block (in the case of an extended block, the hitbox can be larger than one, but must not go beyond the "size" property).
Array *\[0.25, 0.0, 0.5, 0.75, 0.4, 0.3\]* describes hitbox width:
-- offset 0.25m east
+- offset 0.25m west
- offset 0.0m up
-- offset 0.5m north
-- 0.75m width (from east to west)
+- offset 0.5m south
+- 0.75m width (from west to east)
- 0.4m height
-- 0.3m length (from south to north)
+- 0.3m length (from north to south)
For composite hitboxes, the *hitboxes* property is used - an array of hitboxes, for example:
diff --git a/doc/en/content-packs.md b/doc/en/content-packs.md
index c193fb188..48ec57e6d 100644
--- a/doc/en/content-packs.md
+++ b/doc/en/content-packs.md
@@ -12,7 +12,7 @@ Content-pack folder must contain file **package.json** with following contents:
{
"id": "pack_id",
"title": "pack name will be displayed in the content menu",
- "version": "content-pack version - major.minor",
+ "version": "content-pack version - major.minor.[patch])",
"creator": "content-pack creator",
"description": "short description",
"dependencies": [
@@ -26,6 +26,7 @@ Dependency levels are indicated by prefixes in the name:
- '!' - required dependency
- '?' - optional dependency
- '~' - weak dependency
+
If prefix is not specified, '!' level will be used.
Example: '~randutil' - weak dependency 'randutil'.
diff --git a/doc/en/entity-properties.md b/doc/en/entity-properties.md
index 8bc4d5d37..c2c852c35 100644
--- a/doc/en/entity-properties.md
+++ b/doc/en/entity-properties.md
@@ -61,12 +61,17 @@ Determines how the physics engine will work with it.
### *blocking*
-Determines whether the entity blocks installation of blocks.
+If true - the entity blocks the placement of a block that intersects with the entity's hitbox.
*In the future will also block other entities movement.*
Default value: *true*.
+### *selectable* (raycast opacity)
+
+If set to `false` the cursor will ignore the entity, passing the ray.
+Applies to all uses of raycast without the include_non_selectable flag.
+
### *sensors*
A sensor is an area attached to a physical body that detects the entry of other bodies into it.
@@ -122,6 +127,11 @@ Defines the entity's material (same as for blocks).
The default value is the same as the entity name. Determines which skeleton will be used by the entity. See [rigging](rigging.md).
+### *lighting-mode*
+
+- *bone-based* - lighting is calculated for each skeletal bone separately.
+- *solid* - lighting is calculated for the entire entity.
+
## 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 7bef07664..d3ae82e7d 100644
--- a/doc/en/item-properties.md
+++ b/doc/en/item-properties.md
@@ -60,13 +60,18 @@ Property used via [inventory.use](scripting/builtins/libinventory.md).
Property status is displayed in the inventory interface. Display method is defined via `uses-display`.
-### Display of uses - `uses-display`
+### Display of remaining uses count - `uses-display`
- `none` - display disabled
- `number` - number
- `relation` - current value to initial value (x/y)
- `vbar` - vertical scale (used by default)
+### *script-name*
+
+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.
+
## 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 65a22ee85..1f91efdc5 100644
--- a/doc/en/main-page.md
+++ b/doc/en/main-page.md
@@ -1,8 +1,5 @@
# Documentation
-> [!WARNING]
-> Version is in development. Proceed to [Documentation for 0.31.](https://github.com/MihailRis/voxelcore/blob/release-0.31/doc/en/main-page.md)
-
## Sections
- [Assets preloading](assets-preload.md)
@@ -20,5 +17,6 @@
- [Scripting](scripting.md)
- [Text styles](text-styles.md)
- [VCM models format](vcm.md)
+- [VCM animation format](vca.md)
- [World generator engine](world-generator.md)
- [XML UI building](xml-ui-layouts.md)
diff --git a/doc/en/particles.md b/doc/en/particles.md
index 66d3858d5..ecded4096 100644
--- a/doc/en/particles.md
+++ b/doc/en/particles.md
@@ -9,14 +9,14 @@ Particles are a table, all fields of which are optional.
| lighting | Lighting. | true |
| collision | Collision detection. | true |
| max_distance | Maximum distance from the camera at which particles may spawn. | 16.0 |
-| spawn_interval | Particle spawn interval in seconds. | 1.0 |
+| spawn_interval | Particle spawn interval in seconds. Also initial spawn delay | 1.0 |
| lifetime | Average lifetime of particles in seconds. | 5.0 |
| lifetime_spread | Maximum deviation of particle lifetime (from 0.0 to 1.0). | 0.2 |
| velocity | Initial linear velocity of particles. | {0, 0, 0} |
| acceleration | Particles acceleration. | {0, -16, 0} |
| explosion | Force of particles explosion on spawn. | {2, 2, 2} |
| size | Size of particles. | {0.1, 0.1, 0.1} |
-| size_spread | Maximum particle size spread over time. | 0.2 |
+| size_spread | Maximum particle size spread. | 0.2 |
| angle_spread | Maximum initial rotation angle spread (0 to 1) | 0.0 |
| min_angular_vel | Minimum angular velocity (radians per sec). Non-negative. | 0.0 |
| max_angular_vel | Maximum angular velocity (radians per sec). Non-negative. | 0.0 |
@@ -35,7 +35,8 @@ gfx.particles.emit(
count: int,
-- particle settings table
preset: table,
- -- additional particle settings table
+ -- particle settings table overriding 'preset' parameters
+ -- use it instead of 'presets' table copying for modification
[optional] extension: table
) -> int
```
@@ -63,7 +64,7 @@ Returns the static position or uid of the entity the emitter is bound to.
Returns nil if the emitter does not exist.
-``lua
+```lua
gfx.particles.set_origin(id: int, origin: vec3 | int)
```
diff --git a/doc/en/rigging.md b/doc/en/rigging.md
index 4b69b5769..abb5ad81a 100644
--- a/doc/en/rigging.md
+++ b/doc/en/rigging.md
@@ -38,7 +38,7 @@ Models are loaded automatically; adding them to preload.json is not required.
## Models
-Models should be located in the models folder. Currently only OBJ format is supported.
+Models must be located in the models folder. Currently, the following formats are supported: obj, vec3, and [vcm](vcm.md).
>[!IMPORTANT]
> When loading an obj model, the \*.mtl file is ignored.
diff --git a/doc/en/scripting.md b/doc/en/scripting.md
index a21b959ed..5557c8185 100644
--- a/doc/en/scripting.md
+++ b/doc/en/scripting.md
@@ -14,8 +14,10 @@ Subsections:
- [base64](scripting/builtins/libbase64.md)
- [bjson, json, toml, yaml](scripting/filesystem.md)
- [block](scripting/builtins/libblock.md)
- - [byteutil](scripting/builtins/libbyteutil.md)
+ - [byteutil](scripting/builtins/libbyteutil.md)
+ - [crypto](scripting/builtins/libcrypto.md)
- [cameras](scripting/builtins/libcameras.md)
+ - [ctypes](scripting/builtins/libctypes.md)
- [entities](scripting/builtins/libentities.md)
- [file](scripting/builtins/libfile.md)
- [gfx.blockwraps](scripting/builtins/libgfx-blockwraps.md)
@@ -42,6 +44,7 @@ Subsections:
- [utf8](scripting/builtins/libutf8.md)
- [vec2, vec3, vec4](scripting/builtins/libvecn.md)
- [world](scripting/builtins/libworld.md)
+- [Extensions for standard libraries](scripting/extensions.md)
- [Module core:bit_converter](scripting/modules/core_bit_converter.md)
- [Module core:data_buffer](scripting/modules/core_data_buffer.md)
- [Module core:vector2, core:vector3](scripting/modules/core_vector2_vector3.md)
@@ -58,9 +61,58 @@ not part of Lua syntax.
- quat - array of four numbers - quaternion
- matrix - array of 16 numbers - matrix
-## Core functions
+## Namespaces
+
+Currently, the engine uses a namespace hierarchy that minimizes conflicts between individual modules, scripts, and even packs.
+
+The following structure is relevant:
+
+- Global namespace (_G), which is the root namespace. Writing to it outside of engine core modules is highly undesirable, as it can waste hours of debugging time.
+ - Pack namespace - created each time content is loaded for each pack included in the configuration. This namespace is used by modules, as well as item and block scripts.
+ - [Component namespace](scripting/ecs.md#built-in-components).
+ - [UI document namespace](scripting/ui.md).
+- Isolated world generator namespace.
+
+## Modules
+
+A module is a global object with a lifetime limited to the lifetime of the loaded content, used both for interaction between different packages and as a substitute for global variables within the package itself.
+
+The module must be located in `contentpack/modules/**` (subfolders are allowed, but you will need to specify them)
```lua
-require "packid:module_name" -- load Lua module from pack-folder/modules/
--- no extension included, just name
+local module_name = require "contentpack:module_name" -- imports the module
+
+-- If the module is in the same pack in which it is imported, you can use the shortcut:
+local module_name = require "module_name"
+
+-- When using nested folders:
+local module_name = require "contentpack:path/to/module_name" -- the path does not include `modules`
+local module_name = require "path/to/module_name" -- if in the same pack
```
+
+The module will have the namespace of the folder in which it is located, regardless of the namespace from which the first import was performed.
+
+When creating a module, you should follow the following approach, which is what *require* expects:
+
+```lua
+local this = {
+ variable_name = ... -- public variables
+}
+
+-- private module variables
+local variable_name = ...
+
+-- private module functions
+local function function_name(...)
+ ...
+end
+
+-- public module functions
+function this.function_name(...)
+ ...
+end
+
+return this -- the result that require will return and cache
+```
+
+When reimported, the module will not be reloaded; instead, require will return the cached result.
diff --git a/doc/en/scripting/builtins/libapp.md b/doc/en/scripting/builtins/libapp.md
index 0ec755689..f3d46238f 100644
--- a/doc/en/scripting/builtins/libapp.md
+++ b/doc/en/scripting/builtins/libapp.md
@@ -9,21 +9,22 @@ local filename = "script:"..app.script..".lua"
Since the control script may not belong to any of the packs, it does not belongs to its own package and has its own global namespace in which all global functions and tables are available, as well as the `app` library.
-## Functions
+
+## Common functions
```lua
+-- Performs one tick of the main engine loop.
app.tick()
-```
-Performs one tick of the main engine loop.
-
-```lua
+-- Waits for the specified time in seconds, performing the main engine loop.
app.sleep(time: number)
-```
-Waits for the specified time in seconds, performing the main engine loop.
+-- Terminates the engine, printing the call stack
+-- to trace the function call location.
+app.quit()
-```lua
+-- Waits for the condition checked by the function to be true,
+-- performing the main engine loop.
app.sleep_until(
-- function that checks the condition for ending the wait
predicate: function() -> bool,
@@ -36,51 +37,54 @@ app.sleep_until(
)
```
-Waits for the condition checked by the function to be true, performing the main engine loop.
+## Content
```lua
-app.quit()
-```
+-- Checks if content is loaded.
+app.is_content_loaded() -> bool
-Terminates the engine, printing the call stack to trace the function call location.
+-- Returns the current content configuration
+-- (list of packs IDs in loading order)
+app.get_content() -> table
-```lua
+-- Loads content based on the current configuration.
+-- Cannot be used if content is already loaded (see app.reset_content).
+app.load_content()
+
+-- Unloads all content, resetting it to a single core pack.
+app.reset_content(
+ -- Packs for which modules, events, and environment will not be reset
+ [optional] non_reset_packs: table
+)
+
+-- Updates the packs configuration, checking its correctness
+-- (dependencies and availability of packs).
+-- Automatically adds and reorders packs based on dependencies.
app.reconfig_packs(
-- packs to add
add_packs: table,
-- packs to remove
remove_packs: table
)
-```
-Updates the packs configuration, checking its correctness (dependencies and availability of packs).
-Automatically adds dependencies.
-
-To remove all packs from the configuration, you can use `pack.get_installed()`:
-
-```lua
+-- To remove all packs from the configuration,you can use `pack.get_installed()`:
app.reconfig_packs({}, pack.get_installed())
-```
+-- In this case, `base` will also be removed from the configuration.
-In this case, `base` will also be removed from the configuration.
-
-```lua
+-- Updates the packs configuration, automatically removing unspecified ones,
+-- adding those missing in the previous configuration.
+-- Uses app.reconfig_packs.
app.config_packs(
-- expected set of packs (excluding dependencies)
packs: table
)
```
-Updates the packs configuration, automatically removing unspecified ones, adding those missing in the previous configuration.
-Uses app.reconfig_packs.
-
-```lua
-app.is_content_loaded() -> bool
-```
-
-Checks if content is loaded.
+## Worlds
+
```lua
+-- Creates a new world and opens it.
app.new_world(
-- world name, empty string will create a nameless world
name: str,
@@ -91,62 +95,42 @@ app.new_world(
-- local player id
[optional] local_player: int=0
)
-```
-Creates a new world and opens it.
+-- Deletes a world by name.
+app.delete_world(name: str)
-```lua
+-- Opens a world by name.
app.open_world(name: str)
-```
-Opens a world by name.
-
-```lua
+-- Reopens the world.
app.reopen_world()
-```
-Reopens the world.
-
-```lua
+-- Saves the world.
app.save_world()
-```
-Saves the world.
-
-```lua
+-- Closes the world.
app.close_world(
-- save the world before closing
[optional] save_world: bool=false
)
```
-Closes the world.
-
-```lua
-app.delete_world(name: str)
-```
-
-Deletes a world by name.
+## Engine settings and information
```lua
+-- Returns the major and minor versions of the engine.
app.get_version() -> int, int
-```
-Returns the major and minor versions of the engine.
-
-```lua
+-- Returns the value of a setting.
+-- Throws an exception if the setting does not exist.
app.get_setting(name: str) -> value
-```
-Returns the value of a setting. Throws an exception if the setting does not exist.
-
-```lua
+-- Sets the value of a setting.
+-- Throws an exception if the setting does not exist.
app.set_setting(name: str, value: value)
-```
-Sets the value of a setting. Throws an exception if the setting does not exist.
-
-```lua
+-- Returns a table with information about a setting.
+-- Throws an exception if the setting does not exist.
app.get_setting_info(name: str) -> {
-- default value
def: value,
@@ -155,39 +139,48 @@ app.get_setting_info(name: str) -> {
-- maximum value
[only for numeric settings] max: number
}
-```
-Returns a table with information about a setting. Throws an exception if the setting does not exist.
-
-```lua
+-- Brings the window to front and sets input focus.
app.focus()
```
-Brings the window to front and sets input focus.
+## Paths and entry points
```lua
+-- Creates an in-memory filesystem.
app.create_memory_device(
-- entry-point name
name: str
)
-```
-Creates an in-memory filesystem.
-
-```lua
+-- Returns a list of content sources (paths), in descending priority order.
app.get_content_sources() -> table
-```
-Returns a list of content sources (paths), in descending priority order.
-
-``lua
+-- Sets a list of content sources (paths). Specified in descending priority order.
app.set_content_sources(sources: table)
-```
-Sets a list of content sources (paths). Specified in descending priority order.
-
-``lua
+-- Resets content sources.
app.reset_content_sources()
```
-Resets content sources.
+## Sub-instances
+
+```lua
+-- Creates a headless engine instance with the current project and the specified application script.
+-- Returns the instance ID. The number of active sub-instances is currently limited to one.
+app.start_background_instance(
+ -- script file
+ app_script: string,
+ -- log file
+ output_file: string,
+ -- project parameters (can be read with vc.get_project_arg(name))
+ project_args: table | nil
+) -> int
+
+-- Checks if the engine sub-instance is alive.
+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
+```
diff --git a/doc/en/scripting/builtins/libassets.md b/doc/en/scripting/builtins/libassets.md
index 8f51dd762..45ef138e9 100644
--- a/doc/en/scripting/builtins/libassets.md
+++ b/doc/en/scripting/builtins/libassets.md
@@ -37,6 +37,16 @@ assets.parse_model(
skeleton_name: string
)
+-- Parses and loads animation
+assets.parse_animation(
+ -- Animation file format (vca)
+ format: string,
+ -- Animation file content
+ content: string,
+ -- Animation name after loading
+ name: string
+)
+
-- Creates a Canvas from a loaded texture.
assets.to_canvas(
-- The name of the loaded texture.
diff --git a/doc/en/scripting/builtins/libblock.md b/doc/en/scripting/builtins/libblock.md
index db407e92a..4f0b02809 100644
--- a/doc/en/scripting/builtins/libblock.md
+++ b/doc/en/scripting/builtins/libblock.md
@@ -28,7 +28,8 @@ block.get(x: int, y: int, z: int) -> int
block.get_states(x: int, y: int, z: int) -> int
-- Set block with given integer ID and state (default - 0) at given position.
-block.set(x: int, y: int, z: int, id: int, states: int)
+-- If noupdate=true is passed, the `on_update` event will not be called for adjacent blocks.
+block.set(x: int, y: int, z: int, id: int, states: int, noupdate: boolean=false)
-- Places a block with a given integer id and state (default - 0) at given position.
-- on behalf of the player, calling the on_placed event.
@@ -150,7 +151,7 @@ block.raycast(start: vec3, dir: vec3, max_distance: number, [optional] dest: tab
Casts a ray from the start point in the direction of *dir*. Max_distance specifies the maximum ray length.
Argument `filter` can be used to tell ray what blocks can be skipped(passed through) during ray-casting.
-To use filter `dest` argument must be filled with some value(can be nil), it's done for backwards compatability
+To use filter `dest` argument must be filled with some value(can be nil), it's done for backwards compatibility
The `include_non_selectable` argument determines whether blocks that cannot be selected by the cursor will be included.
Example - `base:water`
@@ -159,6 +160,8 @@ The function returns a table with the results or nil if the ray does not hit any
The result will use the destination table instead of creating a new one if the optional argument specified.
+Use `world.raycast(...)` for more detailed configuration.
+
## Model and physics
```lua
diff --git a/doc/en/scripting/builtins/libcrypto.md b/doc/en/scripting/builtins/libcrypto.md
new file mode 100644
index 000000000..b3106d104
--- /dev/null
+++ b/doc/en/scripting/builtins/libcrypto.md
@@ -0,0 +1,144 @@
+# *crypto* library
+
+The library provides common cryptographic functions
+
+## Hashing
+
+```lua
+crypto.sha256(data: str) -> str
+crypto.sha384(data: str) -> str
+crypto.sha512(data: str) -> str
+crypto.md5(data: str) -> str
+
+crypto.hash(hash: str, data: str) -> str
+crypto.hmac(hash: str, key: str, data: str) -> str
+```
+
+Supported names are `SHA256`, `SHA384`, `SHA512` and `MD5`
+
+MD5 is needed for compatibility with old formats. SHA256 is better for new data
+
+Large files can be passed in parts
+
+```lua
+local hash = crypto.hash_new("SHA256")
+
+hash:update(part1)
+hash:update(part2)
+
+local result = hash:final()
+```
+
+The context can be cleared with `reset` after `final`
+
+## Signatures
+
+```lua
+crypto.ed25519_keypair() -> private_key, public_key
+crypto.ed25519_public(private_key: str) -> str
+crypto.ed25519_sign(private_key: str, message: str) -> str
+crypto.ed25519_verify(public_key: str, message: str, signature: str)
+ -> true
+ -> false, error
+```
+
+Ed25519 keys are 32 bytes long. A signature is 64 bytes long
+
+```lua
+crypto.ecdsa_keypair(curve: str) -> private_key, public_key
+crypto.ecdsa_public(curve: str, private_key: str) -> str
+crypto.ecdsa_sign(curve: str, private_key: str, message: str, hash: str) -> str
+crypto.ecdsa_verify(curve: str, public_key: str, message: str,
+ signature: str, hash: str)
+ -> true
+ -> false, error
+```
+
+Available curves are `P-256`, `P-384` and `P-521`
+
+An ECDSA public key is stored as an uncompressed SEC1 point. A signature is
+stored in DER format
+
+```lua
+crypto.rsa_pkcs1_verify(hash: str, modulus: str, exponent: str,
+ message: str, signature: str)
+ -> true
+ -> false, error
+
+crypto.rsa_pss_verify(hash: str, modulus: str, exponent: str,
+ message: str, signature: str, salt_length: int)
+ -> true
+ -> false, error
+```
+
+RSA modulus and exponent are passed in big endian. A `salt_length` value of `-1`
+uses the hash size
+
+## Key exchange
+
+```lua
+crypto.x25519_keypair() -> private_key, public_key
+crypto.x25519_public(private_key: str) -> str
+crypto.x25519(private_key: str, peer_public_key: str) -> str
+crypto.x25519_shared(private_key: str, peer_public_key: str) -> str
+
+crypto.p256_keypair() -> private_key, public_key
+crypto.p256_public(private_key: str) -> str
+crypto.p256_shared(private_key: str, peer_public_key: str) -> str
+```
+
+`x25519` and `x25519_shared` perform the same operation
+
+The shared secret should not be used as a ready key. Pass it through HKDF first
+
+## Encryption
+
+```lua
+crypto.aes_gcm_encrypt(key: str, nonce: str, aad: str, plaintext: str) -> str
+crypto.aes_gcm_decrypt(key: str, nonce: str, aad: str, ciphertext: str)
+ -> plaintext
+ -> nil, error
+
+crypto.chacha20_poly1305_encrypt(key: str, nonce: str, aad: str,
+ plaintext: str) -> str
+crypto.chacha20_poly1305_decrypt(key: str, nonce: str, aad: str,
+ ciphertext: str)
+ -> plaintext
+ -> nil, error
+```
+
+AES GCM accepts 16 and 32 byte keys
+
+ChaCha20 Poly1305 uses a 32 byte key and a 12 byte nonce
+
+A 16 byte tag is appended to encrypted data
+
+Never reuse a nonce with the same key
+
+## Other functions
+
+```lua
+crypto.random_bytes(length: int) -> str
+crypto.constant_time_equal(left: str, right: str) -> bool
+
+crypto.hkdf_extract(hash: str, salt: str, ikm: str) -> str
+crypto.hkdf_expand(hash: str, prk: str, info: str, length: int) -> str
+
+crypto.pbkdf2(hash: str, password: str, salt: str,
+ iterations: int, length: int) -> str
+crypto.scrypt(password: str, salt: str, n: int, r: int, p: int,
+ length: int, [optional]max_memory: int=0) -> str
+
+crypto.features() -> table
+```
+
+Use scrypt or PBKDF2 with a random salt for passwords. A regular SHA256 hash is
+not suitable for passwords
+
+`features` returns the OpenSSL version and a list of available features
+
+An invalid signature returns `false, "invalid_signature"`
+
+An invalid encryption tag returns `nil, "authentication_failed"`
+
+Invalid arguments raise a regular Lua error
diff --git a/doc/en/scripting/builtins/libctypes.md b/doc/en/scripting/builtins/libctypes.md
new file mode 100644
index 000000000..5517af0fa
--- /dev/null
+++ b/doc/en/scripting/builtins/libctypes.md
@@ -0,0 +1,28 @@
+# *ctypes* Library
+
+A library for safe work with C types.
+
+| ctypes.\ | C-Type | Minimum | Maximum |
+| --------------- | -------- | -------------------- | -------------------- |
+| uint8 | uint8_t | 0 | 255 |
+| uint16 | uint16_t | 0 | 65535 |
+| uint32 | uint32_t | 0 | 4294967295 |
+| uint64 | uint64_t | 0 | 18446744073709551615 |
+| int8 | int8_t | -128 | 127 |
+| int16 | int16_t | -32768 | 32767 |
+| int32 | int32_t | -2147483648 | 2147483647 |
+| int64 | int64_t | -9223372036854775808 | 9223372036854775807 |
+
+
+Usage examples:
+
+```lua
+local x = ctypes.uint64(1234)
+print(x) --> 1234ULL (cdata)
+local y = ctypes.uint64("18446744073709551615")
+print(y) --> 18446744073709551615ULL (cdata)
+print(x + y) --> 1233ULL
+
+local z = tonumber(x)
+print(z) --> 1234 (number)
+```
diff --git a/doc/en/scripting/builtins/libentities.md b/doc/en/scripting/builtins/libentities.md
index d65d95f05..9e653ba78 100644
--- a/doc/en/scripting/builtins/libentities.md
+++ b/doc/en/scripting/builtins/libentities.md
@@ -30,6 +30,9 @@ entities.def_hitbox(id: int) -> vec3
-- Returns entity definition name by index (string ID).
entities.def_name(id: int) -> str
+-- Returns true if the entity is a solid obstacle.
+entities.def_solid(id: int) -> boolean
+
-- Returns entity definition index by name (integer ID).
entities.def_index(name: str) -> int
@@ -51,12 +54,12 @@ entities.get_all() -> table
-- Returns a table of loaded entities based on the passed list of UIDs
entities.get_all(uids: array) -> table
--- Returns a list of UIDs of entities inside the rectangular area
+-- Returns a list of UIDs of entities with origin inside the rectangular area
-- pos - minimal area corner
-- size - area size
entities.get_all_in_box(pos: vec3, size: vec3) -> array
--- Returns a list of UIDs of entities inside the radius
+-- Returns a list of UIDs of entities with origin inside the radius
-- center - center of the area
-- radius - radius of the area
entities.get_all_in_radius(center: vec3, radius: number) -> array
@@ -71,3 +74,5 @@ entities.raycast(start: vec3, dir: vec3, max_distance: number, ignore: int, [opt
The function is an extended version of [block.raycast](libblock.md#raycast). Returns a table with the results if the ray touches a block or entity.
Accordingly, this will affect the presence of the *entity* and *block* fields.
+
+Use `world.raycast(...)` for more detailed configuration.
diff --git a/doc/en/scripting/builtins/libfile.md b/doc/en/scripting/builtins/libfile.md
index 0d4374cac..8f4378b44 100644
--- a/doc/en/scripting/builtins/libfile.md
+++ b/doc/en/scripting/builtins/libfile.md
@@ -163,6 +163,12 @@ file.ext(path: str) --> str
Extracts the extension from the path. Example: `world:data/base/config.toml` -> `toml`.
+```lua
+file.remove_ext(path: string) -> string
+```
+
+Returns the path without the extension. Example: `world:data/base/config.toml` -> `world:data/base/config`.
+
```lua
file.prefix(path: str) --> str
```
diff --git a/doc/en/scripting/builtins/libgui.md b/doc/en/scripting/builtins/libgui.md
index 53d6e4ad2..3dc10612b 100644
--- a/doc/en/scripting/builtins/libgui.md
+++ b/doc/en/scripting/builtins/libgui.md
@@ -61,6 +61,12 @@ gui.set_active_frame(
-- Used for custom projection (e.g., in 3D)
[optional] cursorLocator: function() -> number, number
)
+
+-- Creates a screenshot of a frame as a Canvas object if the frame ID is specified, or the entire window if nil.
+gui.screenshot(
+ -- ID of the frame created via gui.create_frame
+ [optional] frameId: str
+) -> Canvas | nil
```
## Markup
@@ -139,7 +145,7 @@ gui.confirm(
## Documents and templates
```lua
--- Loads a UI document with its script, returns the name of the document if successfully loaded.
+-- Loads a UI document with its script. Returns document environment table
gui.load_document(
-- Path to the xml file of the page. Example: `core:layouts/pages/main.xml`
path: str,
@@ -147,7 +153,7 @@ gui.load_document(
name: str
-- Table of parameters passed to the on_open event
args: table
-) -> str
+) -> table
-- Loads and processes layout template from file
gui.template(
diff --git a/doc/en/scripting/builtins/libhud.md b/doc/en/scripting/builtins/libhud.md
index 1d6264b2d..550659ccc 100644
--- a/doc/en/scripting/builtins/libhud.md
+++ b/doc/en/scripting/builtins/libhud.md
@@ -57,6 +57,10 @@ hud.get_block_inventory() -> int
-- Gives the ID of the second open inventory (block, virtual inventory...) or 0.
hud.get_second_inventory() -> int
+-- Get the inventory ID of exchange item (grabbed item in inventory) or 0.
+-- It has only one slot - 0
+hud.get_exchange_inventory() -> int
+
-- Gives the ID of the player that the UI is bound to.
hud.get_player() -> int
diff --git a/doc/en/scripting/builtins/libinput.md b/doc/en/scripting/builtins/libinput.md
index 9856abc0b..9cf754d33 100644
--- a/doc/en/scripting/builtins/libinput.md
+++ b/doc/en/scripting/builtins/libinput.md
@@ -63,6 +63,13 @@ input.get_mouse_delta() --> {int, int}
Returns cursor movement delta.
+```lua
+input.get_mouse_scroll() --> int
+```
+
+Returns the vertical mouse wheel offset accumulated during the current frame.
+A positive value indicates scrolling up; a negative value indicates scrolling down.
+
```lua
input.get_bindings() --> strings array
```
diff --git a/doc/en/scripting/builtins/libinventory.md b/doc/en/scripting/builtins/libinventory.md
index 8cf2d7c3e..63c25a3c9 100644
--- a/doc/en/scripting/builtins/libinventory.md
+++ b/doc/en/scripting/builtins/libinventory.md
@@ -162,7 +162,19 @@ inventory.get_all_data(
invid: int,
-- slot index
slot: int,
-) -> table
+) -> table | nil
+
+-- Sets the values of all local item properties.
+inventory.set_all_data(
+ -- inventory id
+ invid: int,
+ -- slot index
+ slot: int,
+ -- property:value table
+ fields: table,
+ -- clear other property values
+ [optional] clear: boolean = false
+)
```
```lua
@@ -174,7 +186,7 @@ inventory.clone(invid: int) -> int
-- Move an item from slotA of invA to slotB of invB.
-- invA may be the same as invB.
--- If slotB will be chosen automaticly if argument is not specified.
+-- If slotB will be chosen automatically if argument is not specified.
-- The move may be incomplete if the available slot has no enough stack space.
inventory.move(invA: int, slotA: int, invB: int, slotB: int)
diff --git a/doc/en/scripting/builtins/libnetwork.md b/doc/en/scripting/builtins/libnetwork.md
index 3ceac9c84..8893407d4 100644
--- a/doc/en/scripting/builtins/libnetwork.md
+++ b/doc/en/scripting/builtins/libnetwork.md
@@ -4,6 +4,39 @@ A library for working with the network.
## HTTP requests
+There is a configurable function `network.request` that allows performing HTTP requests with various methods (GET, POST, PUT, DELETE, etc.) and configuring headers, request body, timeout, and other parameters.
+
+> To pass binary data in the request body, use a byte array (Bytearray) or a string. In `on_response`, the `body` string can be converted to a byte array using `Bytearray(response.body)`.
+
+```lua
+network.request(
+ url: string,
+ parameters: {
+ -- Request method (GET, POST, PUT, DELETE, etc.)
+ method: string,
+ -- Request body as a string or Bytearray
+ body: table|string,
+ -- List of additional request headers
+ headers: table,
+ -- Timeout in milliseconds
+ timeout: int,
+ -- Whether to verify the SSL certificate
+ verify_ssl: boolean,
+ -- Function called when a response is received
+ on_response: function(response: {
+ -- HTTP response status code
+ status: int,
+ -- Response body as a string
+ body: string,
+ -- List of response headers
+ headers: table
+ }),
+ }
+)
+```
+
+### Simplified functions for GET and POST requests
+
```lua
-- Performs a GET request to the specified URL.
network.get(
@@ -92,6 +125,19 @@ socket:recv_async(
[optional] usetable: bool=false
) -> nil|table|Bytearray
+-- `peek` and `peek_async` are analogous to the `recv` and `recv_async` methods
+-- with the exception that `peek` and `peek_async` do not advance the socket buffer position
+-- This means they do not remove bytes from the socket, so the bytes can be received after
+socket:peek(
+ length: int,
+ [optional] usetable: boolean=false
+) -> nil|table|Bytearray
+
+socket:peek_async(
+ length: int,
+ [optional] usetable: boolean=false
+) -> nil|table|Bytearray
+
-- Closes the connection
socket:close()
diff --git a/doc/en/scripting/builtins/libplayer.md b/doc/en/scripting/builtins/libplayer.md
index 4b632d798..1dd628b0e 100644
--- a/doc/en/scripting/builtins/libplayer.md
+++ b/doc/en/scripting/builtins/libplayer.md
@@ -154,7 +154,7 @@ Returns position of the selected block or nil
player.get_selected_entity(playerid: int) -> int
```
-Returns unique indentifier of the entity selected by player
+Returns unique identifier of the entity selected by player
```lua
player.get_entity(playerid: int) -> int
diff --git a/doc/en/scripting/builtins/libquat.md b/doc/en/scripting/builtins/libquat.md
index f7cc7a0f6..5d72413e2 100644
--- a/doc/en/scripting/builtins/libquat.md
+++ b/doc/en/scripting/builtins/libquat.md
@@ -2,14 +2,36 @@
Quaternions manipulation library.
-## Quaternion from matrix - *mat4.from_quat(...)*
+Quaternions can be created as a table of 4 numbers:
+`{w, x, y, z}`
+
+## Quaternion from matrix - *quat.from_mat4(...)*
```lua
-- creates a quaternion based on the rotation matrix
-quat.from_mat4(m: matrix)
+quat.from_mat4(m: matrix, [optional] dst: quat) -> quat
+```
--- writes a quaternion from the rotation matrix to dst
-quat.from_mat4(m: matrix, dst: quat)
+## Quaternion of Euler angles - *quat.from_euler(...)*
+
+```lua
+-- creates quaternion from euler angles passed as XYZ (pitch, yaw, roll)
+-- angles in degrees
+quat.from_euler(euler: vec3, [optional] dst: quat) -> quat
+```
+
+## Quaternion composition - quat.mul(...)
+
+```lua
+-- multiplies quaternions
+quat.mul(a: quat, b: quat, [optional] dst: quat) -> quat
+```
+
+## 3D vector rotation - quat.mul_vec3(...)
+
+```lua
+-- rotates vector by quaternion
+quat.mul_vec3(a: quat, b: vec3, [optional] dst: vec3) -> vec3
```
## Spherical linear interpolation - *quat.slerp(...)*
@@ -19,16 +41,12 @@ The interpolation always take the short path and the rotation is performed at co
```lua
-- creates a quaternion as an interpolation between a and b,
-- where t is interpolation factor
-quat.slerp(a: quat, b: quat, t: number)
-
--- writes a quaternion as an interpolation between a and b to dst,
--- where t is interpolation factor
-quat.slerp(a: quat, b: quat, t: number, dst: quat)
+quat.slerp(a: quat, b: quat, t: number, [optional] dst: quat) -> quat
```
## Casting to string - *quat.tostring(...)*
```lua
-- returns a string representing the contents of the quaternion
-quat.tostring(q: quat)
+quat.tostring(q: quat) -> string
```
diff --git a/doc/en/scripting/builtins/libtime.md b/doc/en/scripting/builtins/libtime.md
index 51e125e9c..320e330d1 100644
--- a/doc/en/scripting/builtins/libtime.md
+++ b/doc/en/scripting/builtins/libtime.md
@@ -10,6 +10,9 @@ time.delta() -> number
-- Returns UTC time in seconds
time.utc_time() -> int
+-- Returns UTC time in seconds with millisecond precision
+time.precise_utc_time() -> number
+
-- Returns local (system) time in seconds
time.local_time() -> int
diff --git a/doc/en/scripting/builtins/libworld.md b/doc/en/scripting/builtins/libworld.md
index b2453b34b..72bfaf8e4 100644
--- a/doc/en/scripting/builtins/libworld.md
+++ b/doc/en/scripting/builtins/libworld.md
@@ -70,4 +70,47 @@ world.save_chunk_data(
-- compressed chunk data
data: Bytearray
)
+
+-- Casts a ray from the start point in the dir direction.
+world.raycast(
+ params: table {
+ [==[ required parameters ]==]
+ -- starting point
+ start: vec3,
+ -- ray direction vector
+ dir: vec3,
+ -- maximum distance
+ distance: number,
+
+ [==[ additional parameters (entities) ]==]
+ -- consider entities
+ entities: bool = true,
+ -- uid of the ignored entity
+ ignore_uid: number = 0 (ENTITY_NONE),
+ -- id of the entity types used for filtering
+ filter_entities: table = nil,
+ -- exclusion filtering mode:
+ -- if true, filter_entities defines the list of ignored entity types
+ entities_exclusion: bool = false,
+ -- include entities with selectable=false
+ nonselect_entities: bool = false;
+
+ [==[ additional parameters (blocks) ]==]
+ -- id of the block types used for filtering
+ filter_blocks: table = nil,
+ -- exclusion filtering mode:
+ -- if true, filter_blocks defines the list Ignored
+ blocks_exclusion: bool = true,
+ -- include blocks with selectable=false
+ nonselect_blocks: bool = false;
+ }
+) -> {
+ block: int or nil, -- block id
+ entity: int or nil, -- entity uid
+ endpoint: vec3, -- ray touchpoint
+ iendpoint: vec3, -- position of the block touched by the ray
+ 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 878452928..0473fc852 100644
--- a/doc/en/scripting/ecs.md
+++ b/doc/en/scripting/ecs.md
@@ -8,7 +8,7 @@ The entity object is available in components as a global variable **entity**.
-- Deletes an entity (the entity may continue to exist until the frame ends, but will not be displayed in that frame)
entity:despawn()
--- Returns entity defintion index (integer ID)
+-- Returns entity definition index (integer ID)
entity:def_index() -> int
-- Returns entity definition name (string ID)
@@ -17,7 +17,7 @@ entity:def_name() -> str
-- Returns the name of the entity skeleton
entity:get_skeleton() -> str
-- Replaces the entity skeleton
-entity:set_skeleton(name: str)
+entity:set_skeleton(name: str | nil)
-- Returns the unique entity identifier
entity:get_uid() -> int
@@ -36,8 +36,24 @@ entity:set_enabled(name: str, enable: bool)
-- At components initialization -1 is also returned,
-- since the binding occurs after initialization.
entity:get_player() -> int or nil
+
+-- Checks the 'selectable' property of an entity (raycast opacity)
+body:is_selectable() -> bool
+-- Sets the value of the 'selectable' property of an entity
+body:set_selectable(flag: bool)
```
+## Custom Components
+
+A component is defined as a script in `{pack}/scripts/components/{name}.lua`.
+The component will be available for use in the entity definition as `{pack}:{name}`.
+Example: `core:scripts/components/pathfinding.lua` -> `core:pathfinding`.
+
+For **each** entity containing a component, a **separate instance** is created with **its own namespace** within the pack namespace.
+Global variables declared in it act as public fields of the component (same for global functions).
+
+Entity components are specified via the ["components" list](../entity-properties.md#components)
+
## Built-in components
### Transform
@@ -174,10 +190,14 @@ rig:is_visible([optional] index: int) -> bool
rig:set_visible([optional] index: int, status: bool)
-- Returns the color of the entity
-rig:get_color() -> vec3
+rig:get_color() -> vec4
+-- Return the color of the bone by index
+rig:get_color(index: int) -> vec4
-- Sets the color of the entity
-rig:set_color(color: vec3)
+rig:set_color(color: vec3 | vec4)
+-- Sets the color of the bone by index
+rig:set_color(color: vec3 | vec4, index: int)
```
> [!WARNING]
@@ -264,3 +284,9 @@ function on_used(playerid: int)
```
Called when an entity is used (RMB by entity). The player ID is passed as an argument.
+
+```lua
+function on_player_set(playerid: int)
+```
+
+Called when an entity is attached to a player.
diff --git a/doc/en/scripting/events.md b/doc/en/scripting/events.md
index 75180edc3..9baa9fd85 100644
--- a/doc/en/scripting/events.md
+++ b/doc/en/scripting/events.md
@@ -24,7 +24,7 @@ Called on block broken by player
function on_replaced(x, y, z, playerid)
```
-Called on block replaced with other by player
+Called before a player replaces a block
```lua
function on_interact(x, y, z, playerid) -> bool
diff --git a/doc/en/scripting/extensions.md b/doc/en/scripting/extensions.md
new file mode 100644
index 000000000..9ba99f1ef
--- /dev/null
+++ b/doc/en/scripting/extensions.md
@@ -0,0 +1,210 @@
+# Standard Library Extensions
+
+The **stdmin.lua** kernel script defines functions that extend and complement some of the standard **Lua** libraries.
+
+## Contents:
+- [table extensions](#table-extensions)
+- [string extensions](#string-extensions)
+- [math extensions](#math-extensions)
+- [bit extensions](#bit-extensions)
+- [additional global functions](#additional-global-functions)
+
+## Table Extensions
+```lua
+-- Creates and returns a copy of the given table by creating a new one and copying all elements from the given table into it.
+table.copy(t: table) -> table
+
+-- The deep copy function creates a full copy of the source table, including all its subtables.
+table.deep_copy(t: table) -> table
+
+-- Returns the number of pairs in the given table.
+table.count_pairs(t: table) -> int
+
+-- Returns one element from the given table at a random position.
+table.random(t: table) -> any
+
+-- Returns true if x is contained in t.
+table.has(t: table, x: any) -> boolean
+
+-- Returns the index of x in t. If the given object is not contained in the table, the function returns -1.
+table.index(t: table, x: any) -> int
+
+-- Removes element x from t.
+table.remove_value(t: table, x: any)
+
+-- Shuffles values in the table.
+table.shuffle(t: table) -> table
+
+-- Adds values from table t2 to table t1. If table t2 contains a key from t1, the key's value will not be changed.
+table.merge(t1: table, t2: table) -> table
+
+-- Iterates through the table and applies a func to all its elements, returning the new value of the element.
+table.map(t: table, func: function(indx, value)) -> table
+
+-- Iterates through the table using a func that returns true if the element should be kept and false if it should be deleted.
+table.filter(t: table, func: function(indx, value)) -> table
+
+-- Allows you to safely retrieve the value for the specified key. If the key exists in the table, the method will return its value.
+-- If the key is missing, the method will set it to the default value and return it.
+table.set_default(t: table, key: int | string, default: any) -> any
+
+-- Returns a "flattened" version of the original table.
+table.flat(t: table) -> table
+
+-- Returns a deep "flat" version of the original table.
+table.deep_flat(t: table) -> table
+
+-- Returns a truncated version of the table from index start to index stop, inclusive. Key-value pairs
+-- are not preserved in the new table. For nil values, the value starts at 1 and ends at #arr, respectively.
+table.sub(arr: table, start: number | nil, stop: number | nil) -> table
+
+-- Adds a value to the table only if it was not originally there.
+table.insert_unique(t: table, val: any)
+table.insert_unique(t: table, pos: int, val: any)
+
+-- Returns a table containing all keys of the given table, including numeric ones. table.keys(t: table) -> table
+
+-- Adds all key-value pairs from table extension to table t. If a key from t is present in extension, its value will be overwritten.
+table.extend(t: table, extension: table) -> table
+
+-- Converts the passed table to a string.
+table.tostring(t: table) -> string
+```
+
+## String extensions
+
+It's important to note that all of the functions listed below that extend **string** can be used as meta-methods on string instances, i.e.:
+
+```lua
+local str = "ABA str BAB"
+
+if str:starts_with("ABA") and str:ends_with("BAB") then
+print(str:replace("BA", "DC"))
+end
+```
+
+```lua
+-- Splits the string into parts based on the specified separator/expression and returns the result as a table of strings. If withpattern is true, the separator parameter will be evaluated as a regular expression. string.explode(separator: string, str: string, withpattern: boolean) -> table
+
+-- Splits the string into parts based on the specified delimiter and returns the result as a table of strings.
+string.split(str: string, delimiter: string) -> table
+
+-- Escapes special characters in the string, such as `()[]+-.$%^?*`, into `%character` format. The `NUL` character (`\0`) will be converted to `%z`.
+string.pattern_safe(str: string) -> string
+
+-- Splits seconds into hours, minutes, and milliseconds and formats them using the following parameter order: `minutes, seconds, milliseconds`, and then returns the result. If format is not specified, it returns a table where:
+-- h - hours,
+-- m - minutes,
+-- s - seconds,
+-- ms - milliseconds.
+string.formatted_time(seconds: number, format: string) -> string | table
+
+-- Replaces all substrings in str equal to tofind with toreplace and returns a string with all the modified substrings.
+string.replace(str: string, tofind: string, toreplace: string) -> string
+
+-- Removes all characters equal to char from the string from the left and right ends and returns the result.
+-- If the char parameter is undefined, all empty characters will be selected.
+string.trim(str: string, char: string) -> string
+
+-- Removes all characters equal to char from the string from the left end and returns the result.
+-- If the char parameter is undefined, all empty characters will be selected.
+string.trim_left(str: string, char: string) -> string
+
+-- Removes all characters equal to char from the right end of the string and returns the result.
+-- If the char parameter is undefined, all empty characters will be selected.
+string.trim_right(str: string, char: string) -> string
+
+-- Returns true if the string begins with the substring start.
+string.starts_with(str: string, start: string) -> boolean
+
+-- Returns true if the string ends with the substring endStr.
+string.ends_with(str: string, endStr: string) -> boolean
+
+-- The string.lower and string.upper functions are also overridden by utf8.lower and utf8.upper.
+
+-- Escapes a string. It is an alias for utf8.escape.
+string.escape(str: string) -> string
+
+-- Escapes special XML characters. An alias for utf8.escape_xml.
+string.escape_xml(text: string) -> string
+
+-- Adds a char to the left and right of the string until its size equals size.
+-- By default, char is equal to the space character.
+string.pad(str: string, size: int, char: string) -> string
+
+-- Adds a char to the left of the string until its size equals size.
+-- By default, char is equal to the space character.
+string.left_pad(str: string, size: int, char: string) -> string
+
+-- Adds a char to the right of the string until its size equals size.
+-- By default, char is equal to the space character.
+string.right_pad(str: string, size: int, char: string) -> string
+
+-- Encodes a string into URL format, replacing special characters with their hexadecimal representations.
+string.url_encode(str: string) -> string
+
+-- Decodes a string from URL format, replacing hexadecimal representations with their corresponding characters.
+string.url_decode(str: string) -> string
+```
+
+## Math extensions
+
+```lua
+-- Returns _in if it is in the range low <= _in <= high
+-- Otherwise, returns the boundary to which _in is closest.
+math.clamp(_in: number, low: number, high: number) -> number
+
+-- Returns a random fractional number in the range low to high.
+math.rand(low: number, high: number) -> number
+
+-- Returns the normalized value of num relative to conf.
+math.normalize(num: number, [optional] conf: number) -> number
+
+-- Returns the rounded value of num to the specified number of decimal places.
+math.round(num: number, [optional] places: number) -> number
+
+-- Returns the sum of all received arguments. If a table was passed as an argument, the method will return the sum of all its elements.
+math.sum(x: number, ... | t: table) -> number
+
+```
+
+## Bit extensions
+```lua
+
+-- Common arguments:
+-- * expr: A string containing a bitwise expression, conforming to the Lua 5.3 bitwise operations format
+-- * args: A list of names of the expression arguments. If nil, the list is automatically generated based on the detected identifiers.
+
+- Compiles the function to perform bitwise operations
+-- * asFunction: If true, returns the function; otherwise, returns a string of function code
+bit.compile(expr: string, args: table | nil, asFunction: boolean=true) -> function | string
+
+-- Compiles the function to perform bitwise operations and executes it in place
+-- * ...: Values to be passed to the compiled function. bit.execute(expr: string, args: table | nil, ...) -> number
+```
+## Additional Global Functions
+
+This script also defines other global functions that are available for use. Their list is below.
+
+```lua
+-- Returns true if the passed table is an array, that is, if each key is an integer greater than or equal to one
+-- and if each key follows the previous one.
+is_array(x: table) -> boolean
+
+-- Splits the path into two parts and returns them: the entry point and the file path.
+parse_path(path: string) -> string, string
+
+-- Calls the function func iters times, passing it the arguments ..., and then prints to the console the time in microseconds that has elapsed
+-- since the call to timeit. timeit(iters: int, func: function, ...)
+
+-- Causes the coroutine to pause until the number of seconds specified in timesec has elapsed.
+-- The function can only be used inside a coroutine.
+sleep(timesec: number)
+
+-- Waits for the passed coroutine to complete, returning the control flow. The function can only be used inside a coroutine.
+-- Returns values similar to those returned by pcall.
+await(co: coroutine) -> result, error
+
+-- A constant storing the PID of the current engine instance.
+os.pid -> number
+```
diff --git a/doc/en/scripting/filesystem.md b/doc/en/scripting/filesystem.md
index 8341e9665..29da88194 100644
--- a/doc/en/scripting/filesystem.md
+++ b/doc/en/scripting/filesystem.md
@@ -52,6 +52,60 @@ yaml.parse(code: str) -> table
Parses a YAML string into a table.
+## XML Library
+
+The library contains functions for serializing and deserializing XML:
+
+Further, XML as a data type denotes a Lua table with the following structure:
+- Element tag is accessible by the key `#`
+- XML attributes are accessible as key = value pairs
+- Inner elements are accessible by index
+
+The table is used both as a dictionary and an array.
+
+Example:
+
+```xml
+
+
+
+```
+
+Equivalent Lua table:
+
+```lua
+{
+ ['#'] = "panel",
+ size = "400",
+ color = "0",
+ interval = "1",
+ context = "menu",
+ {
+ ['#'] = "button",
+ onclick = 'menu.page="worlds"',
+ {
+ "@Worlds"
+ }
+ }
+}
+```
+
+Consequently, the button element is accessible as `panel_element[1]`.
+
+```lua
+-- Serializes a tree in XML format
+-- multiline - use multiline formatting
+xml.tostring(data: XML, multiline: bool = true) -> str
+
+-- Parses XML
+xml.parse(code: str) -> XML
+
+-- Parses the VCD (VoxelCore Declaration) format used by VCM and VCA formats.
+-- root_tag - a root element with the specified tag will be implicitly created,
+-- containing all root elements
+xml.parse_vcd(code: str, root_tag: str = "root") -> XML
+```
+
## *bjson* library
The library contains functions for working with the binary data exchange format [vcbjson](../../specs/binary_json_spec.md).
diff --git a/doc/en/scripting/ui.md b/doc/en/scripting/ui.md
index 04784b449..7a11b2f5e 100644
--- a/doc/en/scripting/ui.md
+++ b/doc/en/scripting/ui.md
@@ -1,7 +1,7 @@
# UI properties and methods
UI elements in scripts are accessed through a Document instance
-(*document* variable) by id specified in xml.
+(global *document* variable) by id specified in xml.
Example: print the pos property of an element with id: "worlds-panel" to the console:
```lua
@@ -53,7 +53,7 @@ Properties that apply to all elements:
| contentOffset | vec2 | yes | *no* | element content offset |
| cursor | string | yes | yes | cursor displayed on hover |
| parent | Element | yes | *no* | parent element or nil |
-| zIndex | bool | yes | *no* | z-index value. In panel, it determines the order |
+| zIndex | int | yes | *no* | z-index value. In panel, it determines the order |
Common element methods:
diff --git a/doc/en/vca.md b/doc/en/vca.md
new file mode 100644
index 000000000..7b2bda0b5
--- /dev/null
+++ b/doc/en/vca.md
@@ -0,0 +1,141 @@
+# VCA
+
+A text-based animation format that uses [VCM](vcm.md) syntax.
+
+A VCA file consists of a set of directives. The order of the directives does not affect the order in which transformations are applied.
+
+Directives are applied to the given target, which can be an entity skeleton or a camera.
+When targeting a skeleton, the directive specifies the bone name via the `bone` attribute:
+
+```vcd
+@move bone bone_name ...
+```
+
+Each directive controls a single scalar value, such as x, y, z, etc., specified via the `by` attribute:
+
+```vcd
+@move bone hand by y ...
+```
+
+Two kinds of curve definitions are currently available, each producing a value `f(t) = x`, where t is time:
+- [keyframe curves (curve)](#keyframe-curves)
+- [expression curves (func)](#expression-curves)
+
+## Animation directives
+
+- `@move` - translates an object/bone
+- `@rotate` - rotates an object/bone
+- `@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))
+
+## Metadata
+
+Animation metadata is set in the file via the `configure` directive:
+- `fps` - frame rate, used as the divisor when calculating duration
+- `frames` - number of animation frames, used as the dividend when calculating duration
+- `duration` - explicitly specified duration in seconds (requires `fps` to be specified when keyframes are present)
+- `rotation-order` - specifies the order in which Euler angles are applied during rotation (since the format does not take directive order into account). Examples: XYZ, ZYX, YZX.
+
+Metadata applies globally. Its behavior does not depend on its position in the file, but placing it at the beginning is recommended.
+
+## Additional
+
+- `curve` - declares a custom curve type. Specify the curve name `name` and the value expression `func`.
+
+Two keys, `kl` and `kr`, and the value `t` in the range [0..1] are available in the expression.
+
+Example:
+
+`@curve test-linear func (kl.value + (kr.value - kl.value) * t)`
+
+Custom curves are referenced with a `.` prefix. Example: `@move by y curve .test-linear {...}`.
+
+## Keyframe curves
+
+The curve type must be specified via the `curve` attribute:
+- `const` - values are not interpolated; they switch when a keyframe is reached
+- `linear` - a polyline; linear interpolation is used
+- `bezier` - Bézier curve keyframes with explicitly specified left and right tangents (lx, ly, rx, ry)
+
+Keyframes are described in the following `{...}` block as ordered `@key` directives:
+
+```vcd
+@rotate by z curve linear {
+ @key ...
+ @key ...
+}
+```
+
+A keyframe must contain a frame number `frame` and a value `value`. For `bezier` keyframes, the tangents are also specified.
+
+Example for `curve bezier`:
+```vcd
+@key frame 138 value 53.00411 lx 127.067 ly 53.00411 rx 138.001 ry 53.00411
+```
+
+For the `texture` directive, it is simpler. Example:
+
+```vcd
+@texture name $0 {
+ @key frame 0 value entities/tireman:face_0
+ @key frame 24 value entities/tireman:face_1
+}
+```
+
+> Here, `entities/tireman` is the name of the texture atlas containing `face_*` textures.
+> The texture does not necessarily have to be in an atlas.
+
+If you do not wish to limit the animation duration via `configure` but want to loop the keyframe animation for a specific line, you can use the `period` parameter to specify the animation's repetition period in frames. Example:
+
+```vcd
+@move by y curve linear period 24 {
+ @key frame 0 value 0
+ @key frame 12 value 1
+ @key frame 24 value 0
+}
+```
+
+## Expression curves
+
+The attribute describes a function `f(t) = x`, where t is time in seconds.
+
+Example: `func (sin(t * 2.5) + pi)`.
+
+Operators available in expressions:
+
+- `a + b` - addition
+- `a * b` - multiplication
+- `a / b` - division
+- `a % b` - modulo
+- `a ^ b` - exponentiation
+
+Constants available in expressions:
+
+- `pi` - the number π
+- `e` - Euler's number
+
+Functions available in expressions:
+
+- `sin(x)` - sine of x
+- `cos(x)` - cosine of x
+- `tan(x)` - tangent of x
+- `noise(x, octaves)` - fast 1D noise of x with the given number of octaves
+- `noise2d(x, y, octaves)` - 2D noise of x,y with the given number of octaves
+- `sign(x)` - an integer indicating the sign of x (-1/0/1)
+- `rand(low, high)` - a pseudo-random floating-point number in the range from low to high
+- `round(x, places)` - rounds x to the given number of decimal places `places` (optional)
+- `floor(x)` - rounds x down to the nearest integer
+- `ceil(x)` - rounds x up to the nearest integer
+- `exp(x)` - $e^{x}$
+- `min(x, ...)` - returns the smallest of the given arguments
+- `max(x, ...)` - returns the largest of the given arguments
+- `sqrt(x)` - square root of x
+- `log(x)` - $ln({x})$
+- `log10(x)` - $log_{10}({x})$
+- `deg(x)` - converts radians to degrees
+- `rad(x)` - converts degrees to radians
+
+
+>[!WARNING]
+> Using undocumented functions may have any undocumented consequences.
diff --git a/doc/en/vcm.md b/doc/en/vcm.md
index d384bb7d4..b09c615a4 100644
--- a/doc/en/vcm.md
+++ b/doc/en/vcm.md
@@ -41,6 +41,8 @@ This primitive describes a triangle.
- `region` - UV region within the selected texture, defined by the positions of opposite corners of a square of normalized texture coordinates. Example: `region (0,0,1,1)`
- `region-scale` - multiplier vector for the UV region. Example: `region-scale (0.5,1)`
- `shading` - determines whether shading is enabled on the primitive. Example: `shading off`
+- `normal` - overrides normal vector. Example: `normal (0,1,0)`
+- `cull-face` - determines which side will be culled. Example: `cull-face front` or `cull-face off` (disables face culling)
By default, texture coordinates are not affected by shape or size, unlike other primitives.
@@ -56,6 +58,8 @@ This primitive describes a parallelogram using the right and up vectors.
- `region-scale` - the multiplier vector for the automatically selected UV region. Example: `region-scale (0.5,1)`
- `shading` - determines whether shading is enabled on the primitive. Example: `shading off`
- `flip` - flips the UV region horizontally or vertically. Example: `flip v`
+- `normal` - overrides normal vector. Example: `normal (0,1,0)`
+- `cull-face` - determines which side will be culled. Example: `cull-face front` or `cull-face off` (disables face culling)
### `box` Properties
@@ -66,8 +70,8 @@ This primitive describes a rectangular parallelepiped.
- `origin` - the point relative to which the rotation will be applied. Default: the center of the primitive. Example: `origin (0.5,0.5,0.5)`
- `rotate` - rotation around the (x,y,z) axes in degrees, or a quaternion (x,y,z,w). Example: `rotate (45,0,0)` or `rotate (0.3826834, 0, 0, 0.9238795)`
- `texture` - the default texture to display for all sides.
-- `shading` determines whether shading is enabled on the primitive. Example: `shading off`
-- `delete` deletes sides by name (top, bottom, east, west, north, south)
+- `shading` - determines whether shading is enabled on the primitive. Example: `shading off`
+- `delete` - deletes sides by name (top, bottom, east, west, north, south)
### `part` properties (nested in `box`)
@@ -76,7 +80,7 @@ This primitive describes the properties of the sides of a rectangular parallelep
- `tags` - determines which side the properties will be applied to. Example: `tags (top,bottom)`
- `texture` - the texture to display. Default: `$side_index`.
- `region` - the UV region within the selected texture, defined by the positions of opposite corners. Example: `region (0,0,1,1)`
-- `region-scale` is a multiplier vector for the automatically selected UV region. Example: `region-scale (0.5,1)`
+- `region-scale` - multiplier vector for the automatically selected UV region. Example: `region-scale (0.5,1)`
## Skeleton
diff --git a/doc/en/world-generator.md b/doc/en/world-generator.md
index cd868b404..6432cb421 100644
--- a/doc/en/world-generator.md
+++ b/doc/en/world-generator.md
@@ -212,10 +212,27 @@ local map = Heightmap(width, height)
Operations apply to all height values.
```lua
+-- Convert to absolute values
map:abs()
-```
-Casts height values to absolute.
+-- Round down
+map:floor()
+
+-- Round up
+map:ceil()
+
+-- Round to the nearest integer
+map:round()
+
+-- Sine of height values (in radians)
+map:sin()
+
+-- Cosine of height values (in radians)
+map:cos()
+
+-- Tangent of height values (in radians)
+map:tan()
+```
### Binary Operations
@@ -267,6 +284,14 @@ A method that generates simplex noise, adding it to the existing values.
The noise seed can be specified in the `map.noiseSeed` field.
+By default, noise octaves are mixed using addition:
+
+$noise_{out} = noise_{source} + noise_{applied} * 2^{-{octave}}$
+
+To obtain more normalized multi-octave noise, you can enable the `map.normalNoise = true` flag, which changes the scheme:
+
+$noise_{out} = noise_{source} * (1 - 2^{-{octave}}) + noise_{applied} * 2^{-{octave}}$
+
```lua
map:noise(
-- coordinate offset
@@ -296,6 +321,10 @@ The noise seed can be specified in the `map.noiseSeed` field.

+> [!NOTE] cell noise looks better with `map.normalNoise = true`
+
+
+
### heightmap:resize(...)
```lua
diff --git a/doc/en/xml-ui-layouts.md b/doc/en/xml-ui-layouts.md
index 0bd1b5353..704a0b786 100644
--- a/doc/en/xml-ui-layouts.md
+++ b/doc/en/xml-ui-layouts.md
@@ -39,6 +39,8 @@ Examples:
- `position-func` - position supplier for an element (two numbers), called on every parent container size update or on element adding on a container. May be called before *on_hud_open*
- `size-func` - element size provider (two numbers), called when the size of the container in which the element is located changes, or when an element is added to the container. Can be called before on_hud_open is called.
- `onclick` - lua function called when an element is clicked.
+- `onrightclick` - lua function called when the right mouse button is pressed on an element.
+- `onmiddleclick` - lua function called when the middle mouse button is pressed on an element.
- `ondoubleclick` - lua function called when you double click on an element.
- `onfocus` - lua function called when focusing on an element.
- `ondefocus` - lua function called when the element loses focus.
@@ -192,6 +194,9 @@ Example of list description:
- `width` - minimum content width. Default: 100.
- `selected` - initially selected value. Default: "".
- `onselect` - function to which the user-selected value is passed
+- `mode` - behaviour / display mode:
+ - `select` - default mode.
+ - `button` - button mode: the text is not replaced with the selected option; the element rendered as a regular button.
## *bindbox*
diff --git a/doc/images/normal-cell-noise.png b/doc/images/normal-cell-noise.png
new file mode 100644
index 000000000..c1c103185
Binary files /dev/null and b/doc/images/normal-cell-noise.png differ
diff --git a/doc/ru/3d-text.md b/doc/ru/3d-text.md
index c2d209434..548289701 100644
--- a/doc/ru/3d-text.md
+++ b/doc/ru/3d-text.md
@@ -12,6 +12,7 @@
| render_distance | Дистанция отрисовки текста | 32 |
| xray_opacity | Коэффициент видимости через препятствия (просвечивание) | 0 |
| perspective | Коэффициент перспективы | 1 |
+| font | Шрифт. При отсутствии используется основной | "" |
Доступные форматы отображения:
diff --git a/doc/ru/animation.md b/doc/ru/animation.md
new file mode 100644
index 000000000..45e69a0e3
--- /dev/null
+++ b/doc/ru/animation.md
@@ -0,0 +1,34 @@
+# Анимация
+
+Для того, чтобы загрузить дорожку анимации для скелета сущности ([см. риггинг](rigging.md)) или камеры ([см. камеры](scripting/builtins/libcameras.md)) её, как любой, незагружаемый по-умолчанию, следует указать в [preload.json пака](assets-preload.md) в секции animation.
+
+На данный момент, движком поддерживается один формат описания анимации - [VCA](vca.md).
+
+Общий API для работы с анимацией, как и другими продолжительными событиями, существует библиотека animation, доступная в виде глобальной переменной.
+
+Самый простой способ анимировать что-то:
+
+```lua
+animation.play("имя_анимации", цель)
+```
+
+Где цель может быть камерой:
+
+```lua
+local camera = cameras.get(cameras.index("пак:имя_камеры"))
+animation.play("имя_анимации", camera)
+```
+
+Или скелет сущности:
+
+```lua
+animation.play("имя_анимации", entity.skeleton)
+```
+
+Но для скелетов, подразумевающих переключение между состояниями (те же мобы), лучше использовать [компонент](scripting/ecs.md), реализующий простую машину состояний для анимации - [core:animator](#компонент-coreanimator)
+
+Более подробно функциональность библиотеки animation описана [в соответствующем разделе](scripting/builtins/libanimation.md)
+
+## Компонент core:animator
+
+Компонент находится в работе. Зайдите позже.
diff --git a/doc/ru/assets-preload.md b/doc/ru/assets-preload.md
index b3920e288..5b0c3b4ec 100644
--- a/doc/ru/assets-preload.md
+++ b/doc/ru/assets-preload.md
@@ -3,11 +3,13 @@
Для загрузки ассетов, не загружаемых автоматически, такие как звуки, дополнительные текстуры, используется файл `preload.json`, создающийся в папке контент-пака.
Ассеты в файле разделяются на категории:
+- animation - анимация
- fonts - шрифты
-- shaders - шейдеры
-- textures - текстуры
-- sounds - звуки
- models - модели
+- shaders - шейдеры
+- skeletons - скелеты
+- sounds - звуки
+- textures - текстуры
> [!NOTE]
> При загрузке звука подгружаются все его вариации, по шаблону:
diff --git a/doc/ru/block-properties.md b/doc/ru/block-properties.md
index 50bd7f023..09db5c8ef 100644
--- a/doc/ru/block-properties.md
+++ b/doc/ru/block-properties.md
@@ -1,6 +1,6 @@
# Свойства блоков
-## Вид
+## Вид & Звук
### Текстура - *texture*
@@ -70,6 +70,7 @@
- "pipe" - профиль "труба". Примеры блоков: бревно, труба, лампочка
- "pane" - профиль "панель". Примеры блоков: панель, дверь, табличка
- "stairs" - профиль "ступеньки" ("pane" + перевернутые варианты)
+- "ladder" - профиль "лестница" (как "pipe", но на горизонтальных поверхностях как "pane")
### Испускаемые частицы - *particles*
@@ -78,6 +79,11 @@
При приближении к блоку движок создаст эмиттер, который будет работать
до разрушения блока или отдаления камеры на некоторое расстояние.
+### Материал - *material*
+
+Определяет имя материала блока в формате `пак:имя_материала`, что влияет на выбор звуков взаимодействия с блоком.
+Определения материалов расположены в /block_materials.
+
## Варианты
Некоторые свойства могут варьироваться динамически, в зависимости от номера варианта, хранимого в пользовательских битах блока.
@@ -188,12 +194,12 @@
Числа указываются в диапазоне [0.0, 1.0] - т.е в пределах блока (в случае расширенного блока хитбокс может быть больше единицы, но не должен выходить за пределы size).
Массив `[0.25, 0.0, 0.5, 0.75, 0.4, 0.3]` описывает хитбокс:
-- смещен на 0.25 м на запад
+- смещен на 0.25 м на восток
- смещен на 0.0 м вверх
-- смещен на 0.5 м на север
-- шириной (с востока на запад) 0.75 м
+- смещен на 0.5 м на юг
+- шириной (с запада на восток) 0.75 м
- высотой 0.4 м
-- длиной (с юга на север) 0.3 м
+- длиной (с севера на юг) 0.3 м
Для составных хитбоксов используется свойство *hitboxes* - массив хитбоксов, например:
diff --git a/doc/ru/content-packs.md b/doc/ru/content-packs.md
index 32f9be593..4ab002104 100644
--- a/doc/ru/content-packs.md
+++ b/doc/ru/content-packs.md
@@ -12,7 +12,7 @@
{
"id": "выбранное_имя_пака",
"title": "имя контент-пака для отображения в меню контента",
- "version": "версия контент-пака в формате major.minor",
+ "version": "версия контент-пака в формате major.minor.[patch]",
"creator": "создатель контент-пака",
"description": "краткое описание",
"dependencies": [
@@ -28,6 +28,7 @@
- '!' - обязательная зависимость
- '?' - опциональная зависимость
- '~' - слабая зависимость
+
Отсутствие префикса интерпретируется как '!'.
Пример: '~randutil' - слабая зависимость 'randutil'.
diff --git a/doc/ru/entity-properties.md b/doc/ru/entity-properties.md
index de10cfd32..20ff752c7 100644
--- a/doc/ru/entity-properties.md
+++ b/doc/ru/entity-properties.md
@@ -61,12 +61,17 @@
### Блокирование - *blocking*
-Определяет блокирует ли сущность установку блоков.
+Определяет, блокирует ли сущность установку блока, пересекающегося с хитбоксом сущности.
*В будущем будет также блокировать движение других сущностей.*
Значение по-умолчанию: *true*.
+### Непрозрачность для лучей - *selectable*
+
+При значении в `false` курсор будет игнорировать cущность, пропуская луч далее.
+Распространяется на все использования raycast без флага include_non_selectable.
+
### Список сенсоров - *sensors*
Сенсор - область пространства, привязанная к физическому телу, детектирующее попадание в него других тел.
@@ -122,6 +127,11 @@
Значение по-умолчанию совпадает с именем сущности. Определяет то, какой скелет будет использоваться сущностью. См. [риггинг](rigging.md).
+### Тип освещения - *lighting-mode*
+
+- *bone-based* - освещение рассчитывается для каждой кости скелета отдельно.
+- *solid* - освещение рассчитывается для всей сущности в целом.
+
## Сохранение/загрузка
Кроме данных пользовательских компонентов, движок автоматически сохраняет данные встроенных: transform, rigidbody, skeleton.
diff --git a/doc/ru/item-properties.md b/doc/ru/item-properties.md
index cb45827a1..7453789fb 100644
--- a/doc/ru/item-properties.md
+++ b/doc/ru/item-properties.md
@@ -66,6 +66,10 @@
- `relation` - отношение текущего значения к изначальному (x/y)
- `vbar` - вертикальная шкала (используется по-умолчанию)
+### Имя скрипта - `script-name`
+
+Определяет имя скрипта, содержащего обработчики событий предмета. По-умолчанию соответствует строковому id (имени) предмета.
+Свойство обеспечивает возможность использования одного скрипта для нескольких предметов.
## Теги - *tags*
diff --git a/doc/ru/main-page.md b/doc/ru/main-page.md
index 772f327fd..b826d9dfd 100644
--- a/doc/ru/main-page.md
+++ b/doc/ru/main-page.md
@@ -1,11 +1,9 @@
# Документация
-> [!WARNING]
-> Версия находится в разработке. Перейдите к [документации для 0.31.](https://github.com/MihailRis/voxelcore/blob/release-0.31/doc/ru/main-page.md)
-
## Разделы
- [XML разметка интерфейса](xml-ui-layouts.md)
+- [Анимация](animation.md)
- [Аудио](audio.md)
- [Движок генерации мира](world-generator.md)
- [Консоль](console.md)
@@ -21,4 +19,5 @@
- [Скриптинг](scripting.md)
- [Стили текста](text-styles.md)
- [Формат моделей VCM](vcm.md)
+- [Формат анимации VCA](vca.md)
- [Частицы](particles.md)
diff --git a/doc/ru/particles.md b/doc/ru/particles.md
index 445ded593..e1e9fb34a 100644
--- a/doc/ru/particles.md
+++ b/doc/ru/particles.md
@@ -10,14 +10,14 @@
| lighting | Освещение. | true |
| collision | Обнаружение столкновений. | true |
| max_distance | Максимальная дистанция от камеры, при которой происходит спавн частиц. | 16.0 |
-| spawn_interval | Интервал спавна частиц в секундах. | 1.0 |
+| spawn_interval | Интервал спавна частиц в секундах, также задержка перед спавном первой. | 1.0 |
| lifetime | Среднее время жизни частиц в секундах. | 5.0 |
| lifetime_spread | Максимальное отклонение времени жизни частицы (от 0.0 до 1.0). | 0.2 |
| velocity | Начальная линейная скорость частиц. | {0, 0, 0} |
| acceleration | Ускорение частиц. | {0, -16, 0} |
| explosion | Сила разлёта частиц при спавне. | {2, 2, 2} |
| size | Размер частиц. | {0.1, 0.1, 0.1} |
-| size_spread | Максимальное отклонение времени размера частиц. | 0.2 |
+| size_spread | Максимальное отклонение размера частиц. | 0.2 |
| angle_spread | Максимальное отклонение начального угла поворота (от 0 до 1) | 0.0 |
| min_angular_vel | Минимальная угловая скорость (радианы в сек.). Неотрицательное. | 0.0 |
| max_angular_vel | Максимальная угловая скорость (радианы в сек.). Неотрицательное. | 0.0 |
@@ -36,7 +36,8 @@ gfx.particles.emit(
count: int,
-- таблица настроек частиц
preset: table,
- -- дополнительная таблица настроек частиц
+ -- таблица настроек частиц перезаписывающая значения параметров
+ -- используется вместо копирования и модификации 'preset'
[опционально] extension: table
) -> int
```
diff --git a/doc/ru/rigging.md b/doc/ru/rigging.md
index 86ec0a09b..388b19ea2 100644
--- a/doc/ru/rigging.md
+++ b/doc/ru/rigging.md
@@ -38,7 +38,7 @@
## Модели
-Модели должны располагаться в папке models. На данный момент поддерживается только OBJ формат.
+Модели должны располагаться в папке models. На данный момент поддерживаются форматы: obj, vec3 и [vcm](vcm.md).
>[!IMPORTANT]
> При загрузке obj модели игнорируется файл \*.mtl.
diff --git a/doc/ru/scripting.md b/doc/ru/scripting.md
index cd8a3b00a..377b2c6da 100644
--- a/doc/ru/scripting.md
+++ b/doc/ru/scripting.md
@@ -9,13 +9,16 @@
- [Свойства и методы UI элементов](scripting/ui.md)
- [Сущности и компоненты](scripting/ecs.md)
- [Библиотеки](#)
+ - [animation](scripting/builtins/libanimation.md)
- [app](scripting/builtins/libapp.md)
- [assets](scripting/builtins/libassets.md)
- [base64](scripting/builtins/libbase64.md)
- [bjson, json, toml, yaml](scripting/filesystem.md)
- [block](scripting/builtins/libblock.md)
- [byteutil](scripting/builtins/libbyteutil.md)
+ - [crypto](scripting/builtins/libcrypto.md)
- [cameras](scripting/builtins/libcameras.md)
+ - [ctypes](scripting/builtins/libctypes.md)
- [entities](scripting/builtins/libentities.md)
- [file](scripting/builtins/libfile.md)
- [gfx.blockwraps](scripting/builtins/libgfx-blockwraps.md)
@@ -60,6 +63,58 @@
- quat - массив из четырех чисел - кватернион
- matrix - массив из 16 чисел - матрица
+## Пространства имён
+
+В настоящее время, движок использует иерархию пространств имён, минимизирующую конфликты между отдельными модулями, скриптами, да и паками.
+
+Актуальна следующая структура:
+
+- Глобальное пространство (оно же - _G), являющееся корневым, запись в которое, вне модулей ядра движка, является крайне нежелательным для вашего же времени, что может уйти на лишние часы отладки.
+ - Пространство пака - создаётся каждый раз при загрузке контента для каждого, включённого в конфигурацию, пака. Это пространство используют модули, а также скрипты предметов и блоков.
+ - Пространство [компонента](scripting/ecs.md#пользовательские-компоненты).
+ - Пространство [UI-документа](scripting/ui.md)
+- Изолированное пространство имён генератора мира.
+
+## Модули
+
+Модуль - глобальный объект со сроком жизни, ограниченным сроком жизни контента, используемый как для взаимодействия разных паков, так и для вместо глобальных переменных в пределах самого пака.
+
+Модуль должен находиться в `контентпак/modules/**` (допускаются вложенные папки, что нужно будет указывать)
+
```lua
-require "контентпак:имя_модуля" -- загружает lua модуль из папки modules (расширение не указывается)
+local имя_модуля = require "контентпак:имя_модуля" -- импортирует модуль
+
+-- если модуль находится в том же паке, в котором импортируется, можно использовать сокращённый вариант:
+local имя_модуля = require "имя_модуля"
+
+-- при использовании вложенных папок:
+local имя_модуля = require "контентпак:путь/к/имя_модуля" -- путь не включает `modules`
+local имя_модуля = require "путь/к/имя_модуля" -- если в том же паке
```
+
+Модуль будет иметь пространство имён того пака, в котором находится, независимо от пространства имён, из которого был выполнен первый импорт.
+
+При создании модуля следует придерживаться следующего подхода, которого и ожидает *require*:
+
+```lua
+local this = {
+ имя_переменной = ... -- публичные переменные
+}
+
+-- приватные переменные модуля
+local имя_переменной = ...
+
+-- приватные функции модуля
+local function имя_функции(...)
+ ...
+end
+
+-- публичные функции модуля
+function this.имя_функции(...)
+ ...
+end
+
+return this -- результат, который и будет возвращать и кешировать require
+```
+
+При повторном импорте модуль не будет перезагружен - вместо этого require вернёт кешированный результат.
diff --git a/doc/ru/scripting/builtins/libanimation.md b/doc/ru/scripting/builtins/libanimation.md
new file mode 100644
index 000000000..25048c151
--- /dev/null
+++ b/doc/ru/scripting/builtins/libanimation.md
@@ -0,0 +1,21 @@
+# Библиотека *animation*
+
+Библиотека для работы с анимацией и решения некоторых сопутствующих задач.
+
+```lua
+-- Воспроизводит анимацию на указанном объекте
+animation.play(
+ -- Имя дорожки анимации
+ name: string,
+ -- Цель, что будет анимирована
+ target: Skeleton | Camera
+)
+```
+
+```lua
+-- Запускает корутину, обновляющуюся вне паузы и завершающуюся вместе с выходом из мира.
+animation.action(
+ -- Целевая асинхронная функция
+ func: function()
+)
+```
diff --git a/doc/ru/scripting/builtins/libapp.md b/doc/ru/scripting/builtins/libapp.md
index 07e358ef4..71886a61f 100644
--- a/doc/ru/scripting/builtins/libapp.md
+++ b/doc/ru/scripting/builtins/libapp.md
@@ -28,7 +28,8 @@ app.sleep(time: number)
-- Завершает выполнение движка, выводя стек вызовов для ослеживания места вызова функции.
app.quit()
--- Ожидает истинности утверждения (условия), проверяемого функцией, выполняя основной цикл движка.
+-- Ожидает истинности утверждения (условия), проверяемого функцией,
+-- выполняя основной цикл движка.
app.sleep_until(
-- функция, проверяющее условия завершения ожидания
predicate: function() -> boolean,
@@ -46,7 +47,11 @@ app.sleep_until(
-- Проверяет, загружен ли контент.
app.is_content_loaded() -> boolean
--- Загружает контент из конфига, нельзя использовать, если контент уже загружен
+-- Возвращает текущую конфигурацию контента (список id паков в порядке загрузки)
+app.get_content() -> table
+
+-- Загружает контент на основе текущей конфигурации.
+-- Не может быть использован, если контент уже загружен (см. app.reset_content).
app.load_content()
-- Выгружает весь контент, сбрасывая до единственного пака ядра (`core`).
@@ -56,7 +61,7 @@ app.reset_content(
)
-- Обновляет конфигурацию паков, проверяя её корректность (зависимости и доступность паков).
--- Автоматически добавляет зависимости.
+-- Автоматически добавляет и упорядочивает паки в соответствии с зависимостями.
-- Для удаления ВСЕХ паков из конфигурации можно использовать `pack.get_installed()`
app.reconfig_packs(
-- добавляемые паки
@@ -107,19 +112,22 @@ app.close_world(
)
```
-
## Свойства и настройки движка
+
```lua
-- Возвращает мажорную и минорную версии движка.
app.get_version() -> int, int
--- Возвращает значение настройки. Бросает исключение, если настройки не существует.
+-- Возвращает значение настройки.
+-- Бросает исключение, если настройки не существует.
app.get_setting(name: string) -> any
--- Устанавливает значение настройки. Бросает исключение, если настройки не существует.
+-- Устанавливает значение настройки.
+-- Бросает исключение, если настройки не существует.
app.set_setting(name: string, value: any)
--- Возвращает таблицу с информацией о настройке. Бросает исключение, если настройки не существует.
+-- Возвращает таблицу с информацией о настройке.
+-- Бросает исключение, если настройки не существует.
app.get_setting_info(name: string) -> table
-- Переводит окно на передний план и устанавливает фокус ввода.
@@ -127,6 +135,7 @@ app.focus()
```
## Точки входа и пути
+
```lua
-- Создаёт файловую систему в памяти.
app.create_memory_device(
@@ -142,4 +151,26 @@ app.set_content_sources(sources: table)
-- Сбрасывает список источников контента.
app.reset_content_sources()
-```
\ No newline at end of file
+```
+
+## Под-экземпляры
+
+```lua
+-- Создаёт headless-экземпляр движка с текущим проектом и указанным сценарием.
+-- Возвращает id экземпляра. Число живых под-экземпляров, на данный момент, ограничено одним.
+app.start_background_instance(
+ -- файл сценария
+ app_script: string,
+ -- файл лога
+ output_file: string,
+ -- параметры проекта, что будут доступны через vc.get_project_arg(name)
+ project_args: table | nil,
+) -> int
+
+-- Проверяет, жив ли под-экземпляр движка.
+app.is_instance_alive(handle: int) -> boolean
+
+-- Останавливает под-экземпляр движка.
+-- Возвращает true если экземпляр был жив в момент вызова.
+app.terminate_instance(handle: int) -> boolean
+```
diff --git a/doc/ru/scripting/builtins/libassets.md b/doc/ru/scripting/builtins/libassets.md
index c7f5b8620..1bf0d301f 100644
--- a/doc/ru/scripting/builtins/libassets.md
+++ b/doc/ru/scripting/builtins/libassets.md
@@ -38,6 +38,16 @@ assets.parse_model(
skeleton_name: string
)
+-- Парсит и загружает анимацию
+assets.parse_animation(
+ -- Формат файла анимации (vca)
+ format: string,
+ -- Содержимое файла анимации
+ content: string,
+ -- Имя анимации после загрузки
+ name: string
+)
+
-- Создаёт холст (Canvas) из загруженной текстуры
assets.to_canvas(
-- Имя загруженной текстуры.
diff --git a/doc/ru/scripting/builtins/libblock.md b/doc/ru/scripting/builtins/libblock.md
index b7af3e462..9725d2b3d 100644
--- a/doc/ru/scripting/builtins/libblock.md
+++ b/doc/ru/scripting/builtins/libblock.md
@@ -115,6 +115,8 @@ block.raycast(start: vec3, dir: vec3, max_distance: number, [опциональ
Для результата будет использоваться целевая (dest) таблица вместо создания новой, если указан опциональный аргумент.
+Для более тонкой настройки используйте `world.raycast(...)`.
+
## Вращение
```lua
@@ -209,4 +211,4 @@ block.get_field(
name: string,
[опционально] index: int = 0
) -> any | nil
-```
\ No newline at end of file
+```
diff --git a/doc/ru/scripting/builtins/libcrypto.md b/doc/ru/scripting/builtins/libcrypto.md
new file mode 100644
index 000000000..50112710b
--- /dev/null
+++ b/doc/ru/scripting/builtins/libcrypto.md
@@ -0,0 +1,146 @@
+# Библиотека *crypto*
+
+Библиотека предоставляет основные криптографические функции
+
+## Хеширование
+
+```lua
+crypto.sha256(data: str) -> str
+crypto.sha384(data: str) -> str
+crypto.sha512(data: str) -> str
+crypto.md5(data: str) -> str
+
+crypto.hash(hash: str, data: str) -> str
+crypto.hmac(hash: str, key: str, data: str) -> str
+```
+
+Поддерживаются `SHA256`, `SHA384`, `SHA512` и `MD5`
+
+MD5 нужен для совместимости со старыми форматами. Для новых данных лучше
+использовать SHA256
+
+Большой файл можно передавать частями
+
+```lua
+local hash = crypto.hash_new("SHA256")
+
+hash:update(part1)
+hash:update(part2)
+
+local result = hash:final()
+```
+
+После `final` контекст можно очистить через `reset`
+
+## Подписи
+
+```lua
+crypto.ed25519_keypair() -> private_key, public_key
+crypto.ed25519_public(private_key: str) -> str
+crypto.ed25519_sign(private_key: str, message: str) -> str
+crypto.ed25519_verify(public_key: str, message: str, signature: str)
+ -> true
+ -> false, error
+```
+
+Ключи Ed25519 имеют длину 32 байта. Подпись имеет длину 64 байта
+
+```lua
+crypto.ecdsa_keypair(curve: str) -> private_key, public_key
+crypto.ecdsa_public(curve: str, private_key: str) -> str
+crypto.ecdsa_sign(curve: str, private_key: str, message: str, hash: str) -> str
+crypto.ecdsa_verify(curve: str, public_key: str, message: str,
+ signature: str, hash: str)
+ -> true
+ -> false, error
+```
+
+Доступны кривые `P-256`, `P-384` и `P-521`
+
+Публичный ключ ECDSA записывается как несжатая SEC1 точка. Подпись хранится в
+DER формате
+
+```lua
+crypto.rsa_pkcs1_verify(hash: str, modulus: str, exponent: str,
+ message: str, signature: str)
+ -> true
+ -> false, error
+
+crypto.rsa_pss_verify(hash: str, modulus: str, exponent: str,
+ message: str, signature: str, salt_length: int)
+ -> true
+ -> false, error
+```
+
+Модуль и экспонента RSA передаются в big endian. Значение `salt_length = -1`
+использует размер хеша
+
+## Обмен ключами
+
+```lua
+crypto.x25519_keypair() -> private_key, public_key
+crypto.x25519_public(private_key: str) -> str
+crypto.x25519(private_key: str, peer_public_key: str) -> str
+crypto.x25519_shared(private_key: str, peer_public_key: str) -> str
+
+crypto.p256_keypair() -> private_key, public_key
+crypto.p256_public(private_key: str) -> str
+crypto.p256_shared(private_key: str, peer_public_key: str) -> str
+```
+
+`x25519` и `x25519_shared` выполняют одну и ту же операцию
+
+Общий секрет не стоит использовать как готовый ключ. Сначала его нужно
+обработать через HKDF
+
+## Шифрование
+
+```lua
+crypto.aes_gcm_encrypt(key: str, nonce: str, aad: str, plaintext: str) -> str
+crypto.aes_gcm_decrypt(key: str, nonce: str, aad: str, ciphertext: str)
+ -> plaintext
+ -> nil, error
+
+crypto.chacha20_poly1305_encrypt(key: str, nonce: str, aad: str,
+ plaintext: str) -> str
+crypto.chacha20_poly1305_decrypt(key: str, nonce: str, aad: str,
+ ciphertext: str)
+ -> plaintext
+ -> nil, error
+```
+
+AES GCM принимает ключи размером 16 или 32 байта
+
+ChaCha20 Poly1305 использует ключ размером 32 байта и nonce размером 12 байт
+
+В конец зашифрованных данных добавляется тег размером 16 байт
+
+Нельзя повторно использовать один nonce с тем же ключом
+
+## Остальные функции
+
+```lua
+crypto.random_bytes(length: int) -> str
+crypto.constant_time_equal(left: str, right: str) -> bool
+
+crypto.hkdf_extract(hash: str, salt: str, ikm: str) -> str
+crypto.hkdf_expand(hash: str, prk: str, info: str, length: int) -> str
+
+crypto.pbkdf2(hash: str, password: str, salt: str,
+ iterations: int, length: int) -> str
+crypto.scrypt(password: str, salt: str, n: int, r: int, p: int,
+ length: int, [опционально]max_memory: int=0) -> str
+
+crypto.features() -> table
+```
+
+Для хранения паролей следует использовать scrypt или PBKDF2 со случайной
+солью. Обычный SHA256 для паролей не подходит
+
+`features` возвращает версию OpenSSL и список доступных возможностей
+
+Неверная подпись возвращает `false, "invalid_signature"`
+
+Неверный тег при расшифровке возвращает `nil, "authentication_failed"`
+
+Ошибки в аргументах вызывают обычную Lua ошибку
diff --git a/doc/ru/scripting/builtins/libctypes.md b/doc/ru/scripting/builtins/libctypes.md
new file mode 100644
index 000000000..d6c985b44
--- /dev/null
+++ b/doc/ru/scripting/builtins/libctypes.md
@@ -0,0 +1,28 @@
+# Библиотека *ctypes*
+
+Библиотека для безопасной работы с типами языка С.
+
+| ctypes.\ | С-тип | Минимум | Максимум |
+| ------------- | -------- | -------------------- | -------------------- |
+| uint8 | uint8_t | 0 | 255 |
+| uint16 | uint16_t | 0 | 65535 |
+| uint32 | uint32_t | 0 | 4294967295 |
+| uint64 | uint64_t | 0 | 18446744073709551615 |
+| int8 | int8_t | -128 | 127 |
+| int16 | int16_t | -32768 | 32767 |
+| int32 | int32_t | -2147483648 | 2147483647 |
+| int64 | int64_t | -9223372036854775808 | 9223372036854775807 |
+
+
+Примеры использования:
+
+```lua
+local x = ctypes.uint64(1234)
+print(x) --> 1234ULL (cdata)
+local y = ctypes.uint64("18446744073709551615")
+print(y) --> 18446744073709551615ULL (cdata)
+print(x + y) --> 1233ULL
+
+local z = tonumber(x)
+print(z) --> 1234 (number)
+```
diff --git a/doc/ru/scripting/builtins/libentities.md b/doc/ru/scripting/builtins/libentities.md
index f37dc1b32..9753c7e15 100644
--- a/doc/ru/scripting/builtins/libentities.md
+++ b/doc/ru/scripting/builtins/libentities.md
@@ -30,6 +30,9 @@ entities.def_name(id: int) -> string
-- Возвращает значение свойства 'hitbox' сущности
entities.def_hitbox(id: int) -> vec3
+-- Возвращает true если сущность является осязаемым препятствием.
+entities.def_solid(id: int) -> boolean
+
-- Возвращает индекс определения сущности по имени (числовой ID).
entities.def_index(name: string) -> int
@@ -50,12 +53,12 @@ entities.get_all() -> table
-- Возвращает таблицу загруженных сущностей по переданному списку UID
entities.get_all(uids: table) -> table
--- Возвращает список UID сущностей, попадающих в прямоугольную область
+-- Возвращает список UID сущностей, позиции которых попадают в прямоугольную область
-- pos - минимальный угол области
-- size - размер области
entities.get_all_in_box(pos: vec3, size: vec3) -> table
--- Возвращает список UID сущностей, попадающих в радиус
+-- Возвращает список UID сущностей, позиции которых попадают в радиус
-- center - центр области
-- radius - радиус области
entities.get_all_in_radius(center: vec3, radius: number) -> table
@@ -69,4 +72,6 @@ entities.raycast(start: vec3, dir: vec3, max_distance: number, ignore: int, [opt
Функция является расширенным вариантом [block.raycast](libblock.md#raycast). Возвращает таблицу с результатами если луч касается блока, либо сущности.
-Соответственно это повлияет на наличие полей *entity* и *block*.
\ No newline at end of file
+Соответственно это повлияет на наличие полей *entity* и *block*.
+
+Для более тонкой настройки используйте `world.raycast(...)`.
diff --git a/doc/ru/scripting/builtins/libfile.md b/doc/ru/scripting/builtins/libfile.md
index 0d1b9d58c..0c1e03ff6 100644
--- a/doc/ru/scripting/builtins/libfile.md
+++ b/doc/ru/scripting/builtins/libfile.md
@@ -78,6 +78,9 @@ file.stem(путь: string) -> string
-- Извлекает расширение из пути. Пример: `world:data/base/config.toml` -> `toml`.
file.ext(путь: string) -> string
+
+-- Возвращает путь без расширения. Пример: `world:data/base/config.toml` -> `world:data/base/config`.
+file.remove_ext(путь: string) -> string
```
## Директории
@@ -145,4 +148,4 @@ file.open(путь: string, режим: string) -> io_stream
-- * `/tmp/` или `\\\\.\\pipe\\` добавлять не нужно - движок делает это автоматически.
-- * Недоступен режим с `+`
file.open_named_pipe(имя: string, режим: string) -> io_stream
-```
\ No newline at end of file
+```
diff --git a/doc/ru/scripting/builtins/libgui.md b/doc/ru/scripting/builtins/libgui.md
index 9c2eb7418..51ac7307f 100644
--- a/doc/ru/scripting/builtins/libgui.md
+++ b/doc/ru/scripting/builtins/libgui.md
@@ -69,6 +69,12 @@ gui.set_active_frame(
-- Используется для пользовательской проекции (например в 3D)
[опционально] cursorLocator: function() -> number, number
)
+
+-- Создаёт снимок фрейма в виде объекта Canvas если указан id фрейма, или всего окна, в случае nil.
+gui.screenshot(
+ -- id фрейма, созданного через gui.create_frame
+ [опционально] frameId: str
+) -> Canvas | nil
```
## Разметка
@@ -140,12 +146,12 @@ gui.confirm(
## Документы и шаблоны
```lua
--- Загружает UI документ и его скрипт. Возвращает имя документа.
+-- Загружает UI документ и его скрипт. Возвращает пространство имён документа
gui.load_document(
path: string, -- путь к xml файлу, например: core:layouts/pages/main.xml
name: string, -- id документа, например: core:pages/main
args: table -- параметры для события on_open
-) -> string
+) -> table
-- Обрабатывает xml шаблон макета из файла
gui.template(
diff --git a/doc/ru/scripting/builtins/libhud.md b/doc/ru/scripting/builtins/libhud.md
index bad0e93c6..7a93c93e4 100644
--- a/doc/ru/scripting/builtins/libhud.md
+++ b/doc/ru/scripting/builtins/libhud.md
@@ -58,6 +58,11 @@ hud.get_block_inventory() -> int
-- Дает ID второго открытого инвентаря (блок, виртуальный инвентарь...) или 0.
hud.get_second_inventory() -> int
+-- Получить ID инвентаря, в котором находится предмет во время
+-- его перемещения в инвентаре, или 0 если его не существует.
+-- Имеет единственный слот - 0
+hud.get_exchange_inventory() -> int
+
-- Дает ID игрока, к которому привязан пользовательский интерфейс.
hud.get_player() -> int
@@ -81,4 +86,4 @@ hud.set_allow_pause(flag: boolean)
-- Функция, управляющая именованным скелетом 'hand' (см. gfx.skeletons)
hud.hand_controller: function()
-```
\ No newline at end of file
+```
diff --git a/doc/ru/scripting/builtins/libinput.md b/doc/ru/scripting/builtins/libinput.md
index 7d04747a9..f3ac4b699 100644
--- a/doc/ru/scripting/builtins/libinput.md
+++ b/doc/ru/scripting/builtins/libinput.md
@@ -21,7 +21,7 @@ input.get_bindings() -> table
input.get_binding_text(bindname: string) -> string
-- Проверяет активность привязки.
-input.is_active(bindname: string) -> string
+input.is_active(bindname: string) -> boolean
-- Включает/выключает привязку до выхода из мира.
input.set_enabled(bindname: string, flag: boolean)
@@ -34,6 +34,10 @@ input.get_mouse_pos() -> {number, number}
-- Возращает дельту позиции курсора.
input.get_mouse_delta() -> {number, number}
+
+-- Возвращает вертикальное смещение колеса мыши, накопленное за текущий кадр.
+-- Положительное значение соответствует прокрутке вверх, отрицательное - вниз.
+input.get_mouse_scroll() -> number
```
## Создание обработчиков
@@ -74,4 +78,4 @@ input.add_callback("key:escape", function ()
print("NO")
return true -- предотвращает вызов назначенных ранее функций
end, document.root)
-```
\ No newline at end of file
+```
diff --git a/doc/ru/scripting/builtins/libinventory.md b/doc/ru/scripting/builtins/libinventory.md
index 50ed8dccb..4a836f83b 100644
--- a/doc/ru/scripting/builtins/libinventory.md
+++ b/doc/ru/scripting/builtins/libinventory.md
@@ -170,7 +170,19 @@ inventory.get_all_data(
invid: int,
-- индекс слота
slot: int,
-) -> table
+) -> table | nil
+
+-- Устанавливает значения локальных cвойств предмета.
+inventory.set_all_data(
+ -- id инвентаря
+ invid: int,
+ -- индекс слота
+ slot: int,
+ -- таблица cвойство:значение
+ fields: table,
+ -- удалить остальные значения свойств
+ [опционально] clear: boolean = false
+)
```
```lua
@@ -222,4 +234,4 @@ inventory.use(
-- индекс слота
slot: int
)
-```
\ No newline at end of file
+```
diff --git a/doc/ru/scripting/builtins/libnetwork.md b/doc/ru/scripting/builtins/libnetwork.md
index 31f59fb25..c60f0f178 100644
--- a/doc/ru/scripting/builtins/libnetwork.md
+++ b/doc/ru/scripting/builtins/libnetwork.md
@@ -4,6 +4,39 @@
## HTTP-Запросы
+Существует настраиваемая функция `network.request`, которая позволяет выполнять HTTP-запросы с различными методами (GET, POST, PUT, DELETE и т.д.) и настраивать заголовки, тело запроса, таймаут и другие параметры.
+
+> Для передачи двоичных данных в теле запроса, используйте массив байт (Bytearray) или строку. В `on_response` строку `body` можно преобразовать в массив байт с помощью `Bytearray(response.body)`.
+
+```lua
+network.request(
+ url: string,
+ parameters: {
+ -- Метод запроса (GET, POST, PUT, DELETE и т.д.)
+ method: string,
+ -- Тело запроса в виде строки или массива байт (Bytearray)
+ body: table|string,
+ -- Список дополнительных заголовков запроса
+ headers: table,
+ -- Таймаут в миллисекундах
+ timeout: int,
+ -- Проверять ли SSL-сертификат
+ verify_ssl: boolean,
+ -- Функция, вызываемая при получении ответа
+ on_response: function(response: {
+ -- HTTP-код ответа
+ status: int,
+ -- Тело ответа в виде строки
+ body: string,
+ -- Список заголовков ответа
+ headers: table
+ }),
+ }
+)
+```
+
+### Упрощённые функции для GET и POST запросов
+
```lua
-- Выполняет GET запрос к указанному URL.
network.get(
@@ -92,6 +125,24 @@ socket:recv_async(
[опционально] usetable: boolean=false
) -> nil|table|Bytearray
+-- `peek` и `peek_async` являются аналогами методов `recv` и `recv_async`
+-- за тем исключением, что `peek` и `peek_async` не двигают позицию буфера сокета
+-- Это означает, что они не удаляют байты из сокета, а значит байты могут быть прочитаны после
+socket:peek(
+ length: int,
+ [опционально] usetable: boolean=false
+) -> nil|table|Bytearray
+
+socket:peek_async(
+ length: int,
+ [опционально] usetable: boolean=false
+) -> nil|table|Bytearray
+
+-- Оборачивает сокет в io_stream (см. ../io_stream.md)
+socket:as_stream(
+ [опционально] binary_mode: boolean=true
+) -> io_stream
+
-- Закрывает соединение
socket:close()
@@ -213,4 +264,4 @@ network.get_total_download() -> int
```lua
-- Ищет свободный для использования порт.
network.find_free_port() -> int | nil
-```
\ No newline at end of file
+```
diff --git a/doc/ru/scripting/builtins/libquat.md b/doc/ru/scripting/builtins/libquat.md
index e991de252..a32a24e6d 100644
--- a/doc/ru/scripting/builtins/libquat.md
+++ b/doc/ru/scripting/builtins/libquat.md
@@ -2,14 +2,14 @@
Библиотека для работы с кватернионами.
+Кватернионы задаюся таблицей, состоящей из 4 компонентов:
+`{w, x, y, z}`
+
## Кватернион из матрицы - *quat.from_mat4(...)*
```lua
-- создаёт кватернион на основе матрицы вращения
-quat.from_mat4(m: matrix) -> quat
-
--- записывает кватернион по матрице вращения в dst
-quat.from_mat4(m: matrix, dst: quat)
+quat.from_mat4(m: matrix, [опционально] dst: quat) -> quat
```
## Кватернион из углов Эйлера - *quat.from_euler(...)*
@@ -17,11 +17,21 @@ quat.from_mat4(m: matrix, dst: quat)
```lua
-- создаёт кватернион на основе вектора, содержащего углы Эйлера в порядке XYZ (pitch, yaw, roll)
-- (значения углов строго в градусах)
-quat.from_euler(euler: vec3) -> quat
+quat.from_euler(euler: vec3, [опционально] dst: quat) -> quat
+```
--- записывает кватернион в dst на основе вектора, содержащего углы Эйлера в порядке XYZ (pitch, yaw, roll)
--- (значения углов строго в градусах)
-quat.from_euler(euler: vec3, dst: quat)
+## Композиция кватернионов - quat.mul(...)
+
+```lua
+-- Умножает два кватерниона (композиция поворотов)
+quat.mul(a: quat, b: quat, [опционально] dst: quat) -> quat
+```
+
+## Поворот 3д вектора на кватернион - quat.mul_vec3(...)
+
+```lua
+-- Поворачивает вектор на заданный кватернион
+quat.mul_vec3(a: quat, b: vec3, [опционально] dst: vec3) -> vec3
```
## Сферическая линейная интерполяция - *quat.slerp(...)*
@@ -31,11 +41,7 @@ quat.from_euler(euler: vec3, dst: quat)
```lua
-- создаёт кватернион как интерполяцию между a и b,
-- где t - фактор интерполяции
-quat.slerp(a: quat, b: quat, t: number) -> quat
-
--- записывает кватернион как интерполяцию между a и b в dst,
--- где t - фактор интерполяции
-quat.slerp(a: quat, b: quat, t: number, dst: quat)
+quat.slerp(a: quat, b: quat, t: number, [опционально] dst: quat) -> quat
```
## Перевод в строку - *quat.tostring(...)*
diff --git a/doc/ru/scripting/builtins/libtime.md b/doc/ru/scripting/builtins/libtime.md
index 62e95892a..86d02488f 100644
--- a/doc/ru/scripting/builtins/libtime.md
+++ b/doc/ru/scripting/builtins/libtime.md
@@ -1,15 +1,18 @@
# Библиотека *time*
```lua
--- Возвращает время с момента запуска движка в секундах и милисекундах.
+-- Возвращает время с момента запуска движка в секундах и миллисекундах.
time.uptime() -> number
--- Возвращает дельту времени в секундах и милисекундах (время прошедшее с предыдущего кадра)
+-- Возвращает дельту времени в секундах и миллисекундах (время прошедшее с предыдущего кадра)
time.delta() -> number
--- Возвращает время UTC в секундах
+-- Возвращает время UTC (секунды с 1970-01-01 UTC)
time.utc_time() -> int
+-- Возвращает время UTC (секунды с 1970-01-01 UTC) с точностью до миллисекунд
+time.precise_utc_time() -> number
+
-- Возвращает локальное (системное) время в секундах
time.local_time() -> int
diff --git a/doc/ru/scripting/builtins/libworld.md b/doc/ru/scripting/builtins/libworld.md
index 215329df3..52812f295 100644
--- a/doc/ru/scripting/builtins/libworld.md
+++ b/doc/ru/scripting/builtins/libworld.md
@@ -69,4 +69,46 @@ world.save_chunk_data(
-- сжатые данные чанка
data: Bytearray
)
-```
\ No newline at end of file
+
+-- Бросает луч из точки start в направлении dir.
+world.raycast(
+ params: table {
+ [==[ обязательные параметры ]==]
+ -- стартовая точка
+ start: vec3,
+ -- вектор направления луча
+ dir: vec3,
+ -- максимальное расстояние
+ distance: number,
+
+ [==[ дополнительные параметры (сущности) ]==]
+ -- учитывать сущности
+ entities: bool = true,
+ -- uid игнорируемой сущности
+ ignore_uid: number = 0 (ENTITY_NONE),
+ -- id типов сущностей используемых для фильтрации
+ filter_entities: table = nil,
+ -- исключающий режим фильтрации:
+ -- при значении (true) filter_entities определяет список игнорируемых
+ entities_exclusion: bool = false,
+ -- учитывать сущности с selectable=false
+ nonselect_entities: bool = false;
+
+ [==[ дополнительные параметры (блоки) ]==]
+ -- id типов блоков используемых для фильтрации
+ filter_blocks: table = nil,
+ -- исключающий режим фильтрации:
+ -- при значении (true) filter_blocks определяет список игнорируемых
+ blocks_exclusion: bool = true,
+ -- учитывать блоки с selectable=false
+ nonselect_blocks: bool = false;
+ }
+) -> {
+ block: int или nil, -- id блока
+ entity: int или nil, -- uid сущности
+ endpoint: vec3, -- точка касания луча
+ iendpoint: vec3, -- позиция блока, которого касается луч
+ length: number, -- длина луча
+ normal: vec3, -- вектор нормали поверхности, которой касается луч
+} или nil если луч не коснулся блока или сущности
+```
diff --git a/doc/ru/scripting/bytearray.md b/doc/ru/scripting/bytearray.md
index c90b6d67e..d15cd6a58 100644
--- a/doc/ru/scripting/bytearray.md
+++ b/doc/ru/scripting/bytearray.md
@@ -2,6 +2,8 @@
*Bytearray* - динамический байтовый массив, реализованный через LuaJIT FFI. По нему можно итерироваться стандартными функциями **pairs** и **ipairs**
+Примечание касаемо условных обозначений в документации: псведотип `posint` означает натуральное (положительное ненулевое целое) число.
+
## Основное
### Создание массива
```lua
@@ -22,29 +24,64 @@ bytes:insert(index: int, value: int)
-- Удаляет элемент(ы), если передан `count`, удалит `count` кол-во элементов с выбранного индекса.
bytes:remove(index: int, [опционально] count: int)
--- Очищает массив
+-- Очищает массив.
bytes:clear()
+--[[
+Заполняет массив определённым байтом полностью либо в определённом диапазоне.
+Логика работы следующая: если параметр size или index равны nil, то указанным байтом будет заполнен весь массив,
+ иначе будет заполнен диапазон внутри массива начиная с индекса index и размером size.
+В случае выхода заполняемого блока за границы массива генерирует соответствующую ошибку.
+]]
+bytes:fill(index: posint/nil, size: posint/nil, byte: uint8)
+
-- Создаёт новый Bytearray, содержащий копию части данных с offset до offset+length
bytes:slice(offset: int, length: int) -> Bytearray
+
+--[[
+Копирует блок байт из исходного массива, начиная с индекса srcindex, в массив dst, начиная в нём с индекса dstindex.
+В случае выхода за границы исходного, конечного массива, либо при некорректном значении параметра size генерирует соответствующую ошибку.
+]]
+bytes:copy(srcindex: posint, dst: Bytearray, dstindex: posint, size: posint)
+
+--[[
+Безопасно копирует перекрывающиеся области памяти (байт) в пределах одного массива.
+В случае выхода за пределы массива начального или конечного диапазона байт генерирует соответствующую ошибку.
+]]
+bytes:move(fromindex: posint, toindex: posint, size: posint)
```
## View
Это "вьюшки" поверх Bytearray, которые интерпретируют его байты как массив чисел другого размера - **без копирования данных**.
-Не имеет своих методов, является просто объектной ссылкой на оригинальный Bytearray.
+Практически не имеют своих методов, являются простыми объектными ссылками на оригинальный Bytearray.
-| Класс | Тип элементов | Размер |
-| ------------ | ------------------ | ------- |
-| `I16view` | `int16_t` | 2 байта |
-| `U16view` | `uint16_t` | 2 байта |
-| `I32view` | `int32_t` | 4 байта |
-| `U32view` | `uint32_t` | 4 байта |
+| Класс | Тип элементов | Размер |
+| ------------ | ------------------ | --------- |
+| `I8view` | `int8_t` | 1 байт |
+| `I16view` | `int16_t` | 2 байта |
+| `U16view` | `uint16_t` | 2 байта |
+| `I32view` | `int32_t` | 4 байта |
+| `U32view` | `uint32_t` | 4 байта |
+| `I64view` | `int64_t` | 8 байт |
+| `U64view` | `uint64_t` | 8 байт |
+| `FLTview` | `float` | 4 байта* |
+| `DBLview` | `double` | 8 байт* |
----
+* Размеры "оригинальных" C-шных типов являются платформозависимыми и их точный размер не описан в стандарте языка. В данной таблице предоставлены наиболее распространённые размеры типов.
-### Пример использования
+### Специфические методы "вьюшек"
+
+```lua
+--[[
+Возвращает размер типа вьюшки. Результат тот же, что и от применения оператора sizeof() из языка C для данного типа.
+ Полезно для вьюшек, использующих C-шные типы нефиксированного размера, например те же float или double.
+]]
+view:typesize() -> posint
+```
+
+## Пример использования
```lua
local bytes = Bytearray({1, 0, 2, 0, 250, 255})
@@ -59,4 +96,4 @@ print(i16[3]) -- -6 (signed вьюшка)
for _, num in ipairs(i16) do
print(num)
end -- 1; 2; -6
-```
\ No newline at end of file
+```
diff --git a/doc/ru/scripting/ecs.md b/doc/ru/scripting/ecs.md
index 1a5f6ccf3..d6a823cf0 100644
--- a/doc/ru/scripting/ecs.md
+++ b/doc/ru/scripting/ecs.md
@@ -17,7 +17,7 @@ entity:def_name() -> str
-- Возращает имя скелета сущности
entity:get_skeleton() -> str
-- Заменяет скелет сущности
-entity:set_skeleton(name: str)
+entity:set_skeleton(name: str | nil)
-- Возращает уникальный идентификатор сущности
entity:get_uid() -> int
@@ -134,6 +134,11 @@ body:set_elasticity(elasticity: number)
-- Возвращает скорость поверхности, на которой находится тело, либо {0,0,0}
body:get_ground_vel() -> vec3
+
+-- Проверяет свойство 'selectable' у сущности (непрозрачность для лучей)
+body:is_selectable() -> bool
+-- Устанавливает значение свойство 'selectable' у сущности
+body:set_selectable(flag: bool)
```
### Skeleton
@@ -174,12 +179,27 @@ rig:is_visible([optional] index: int) -> bool
rig:set_visible([optional] index: int, status: bool)
-- Возвращает цвет сущности
-rig:get_color() -> vec3
+rig:get_color() -> vec4
+-- Возвращает цвет кости по индексу
+rig:get_color(index: int) -> vec4
-- Устанавливает цвет сущности
-rig:set_color(color: vec3)
+rig:set_color(color: vec3 | vec4)
+-- Устанавливает цвет кости по индексу
+rig:set_color(color: vec3 | vec4, index: int)
```
+## Пользовательские компоненты
+
+Компонент описывается в виде скрипта `{пак}/scripts/components/{имя}.lua`.
+Компонент будет доступен для использования в описании сущности как `{пак}:{имя}`.
+Пример: `core:scripts/components/pathfinding.lua` -> `core:pathfinding`.
+
+Для **каждой** сущности, содержащей компонент, создаётся **отдельный экземпляр** со **своим пространством имен** внутри пространства имён пака.
+Глобальные переменные, объявляемые в нём, играют роль публичных полей компонента (как и глобальные функции).
+
+Компоненты сущности указываются через [список "components"](../entity-properties.md#cписок-компонентов---components)
+
> [!WARNING]
> При выходе сущности за пределы зоны прогрузки она удаляется, вызывая события.
> При повторном попадании в зону прогрузки сущность спавнится заново.
@@ -265,3 +285,8 @@ function on_used(playerid: int)
Вызывается при использовании сущности (ПКМ по сущности). ID игрока передается в качестве аргумента.
+```lua
+function on_player_set(playerid: int)
+```
+
+Вызывается при прикреплении сущности к игроку.
diff --git a/doc/ru/scripting/events.md b/doc/ru/scripting/events.md
index ff4bfb456..bfa0b9388 100644
--- a/doc/ru/scripting/events.md
+++ b/doc/ru/scripting/events.md
@@ -34,7 +34,7 @@ function on_broken(x, y, z, playerid)
function on_replaced(x, y, z, playerid)
```
-Вызывается после замены блока игроком
+Вызывается перед заменой блока игроком
```lua
function on_interact(x, y, z, playerid) -> bool
diff --git a/doc/ru/scripting/extensions.md b/doc/ru/scripting/extensions.md
index 868210056..3a372a9a5 100644
--- a/doc/ru/scripting/extensions.md
+++ b/doc/ru/scripting/extensions.md
@@ -7,7 +7,7 @@
- [расширения для string](#расширения-для-string)
- [расширения для math](#расширения-для-math)
- [расширения для bit](#расширения-для-bit)
-- [Дополнительные глобальные функции](#дополнительные-глобальные-функции)
+- [дополнительные глобальные функции](#дополнительные-глобальные-функции)
## Расширения для table
```lua
@@ -62,6 +62,12 @@ table.sub(arr: table, start: number | nil, stop: number | nil) -> table
table.insert_unique(t: table, val: any)
table.insert_unique(t: table, pos: int, val: any)
+-- Возвращает таблицу, содержащую все ключи переданной таблицы, включая числовые.
+table.keys(t: table) -> table
+
+-- Добавляет в таблицу t все пары ключ-значение из таблицы extension, при этом если в extension присутствует ключ из t, то его значение будет перезаписано.
+table.extend(t: table, extension: table) -> table
+
-- Конвертирует переданную таблицу в строку.
table.tostring(t: table) -> string
```
@@ -135,6 +141,12 @@ string.left_pad(str: string, size: int, char: string) -> string
-- Добавляет char справа от строки, пока её размер не будет равен size.
-- По стандарту char равен символу пробела.
string.right_pad(str: string, size: int, char: string) -> string
+
+-- Кодирует строку в формат URL, заменяя специальные символы на их шестнадцатеричные представления.
+string.url_encode(str: string) -> string
+
+-- Декодирует строку из формата URL, заменяя шестнадцатеричные представления на соответствующие символы.
+string.url_decode(str: string) -> string
```
## Расширения для math
@@ -156,6 +168,14 @@ math.round(num: number, [опционально] places: number) -> number
-- Возвращает сумму всех принимаемых аргументов. Если в качестве аргумента была передана таблица, метод вернёт сумму всех её элементов.
math.sum(x: number, ... | t: table) -> number
+-- Возвращает целое число, указывающее знак числа (-1/0/1)
+math.sign(x: number) -> int
+
+-- Одномерный шум с значениями в диапазоне [-1..1].
+math.noise(x: number, [опционально] octaves: int = 1) -> number
+
+-- Двумерный шум с значениями в диапазоне [-1..1].
+math.noise2d(x: number, y: number [опционально] octaves: int = 1) -> number
```
## Расширения для bit
@@ -200,4 +220,4 @@ await(co: coroutine) -> result, error
-- Константа, в которой хранится PID текущего инстанса движка.
os.pid -> number
-```
\ No newline at end of file
+```
diff --git a/doc/ru/scripting/filesystem.md b/doc/ru/scripting/filesystem.md
index 0e060d94c..546722101 100644
--- a/doc/ru/scripting/filesystem.md
+++ b/doc/ru/scripting/filesystem.md
@@ -52,6 +52,60 @@ yaml.parse(code: str) -> table
Парсит YAML строку в таблицу.
+## Библиотека xml
+
+Библиотека содержит функции для сериализации и десериализации XML:
+
+Далее XML как тип данных обозначает Lua-таблицу со следующей структурой:
+- Тег элемента доступен по ключу `#`
+- XML-аттрибуты доступны как пары ключ = значение
+- Вложенные элементы доступны по индексу
+
+Таблица используется как словарь, так и массив.
+
+Пример:
+
+```xml
+
+
+
+```
+
+Эквивалентная Lua-таблица:
+
+```lua
+{
+ ['#'] = "panel",
+ size = "400",
+ color = "0",
+ interval = "1",
+ context = "menu",
+ {
+ ['#'] = "button",
+ onclick = 'menu.page="worlds"',
+ {
+ "@Worlds"
+ }
+ }
+}
+```
+
+Соответственно, элемент button доступен как `элемент_panel[1]`.
+
+```lua
+-- Сериализует дерево в формате XML
+-- multiline - использовать ли многострочное форматирование
+xml.tostring(data: XML, multiline: bool = true) -> str
+
+-- Парсит XML
+xml.parse(code: str) -> XML
+
+-- Парсит формат VCD (VoxelCore Declaration), используемый форматами VCM и VCA.
+-- root_tag - будет неявно создан корневой элемент с указанным тегом,
+-- содержащий все корневые элементы
+xml.parse_vcd(code: str, root_tag: str | nil = nil) -> XML
+```
+
## Библиотека bjson
Библиотека содержит функции для работы с двоичным форматом обмена данными [vcbjson](../../specs/binary_json_spec.md).
diff --git a/doc/ru/scripting/io_stream.md b/doc/ru/scripting/io_stream.md
index cc3403eda..e54ca1fdb 100644
--- a/doc/ru/scripting/io_stream.md
+++ b/doc/ru/scripting/io_stream.md
@@ -18,7 +18,7 @@
Поток имеет три различных вида режима:
- Режим общего поведения (`general` / `mode`)
-- Режим сброса (`flush` / `flushMode`)
+- Режим сброса (`flush` / `flush_mode`)
- Двоичный режим (`binary`)
@@ -27,34 +27,34 @@
Определяет, как поток обрабатывает чтение и запись,
имеет три подрежима:
-| Режим | Описание |
-|---------------|--------|
-| `"default"` | Прямой режим. `read` может вернуть меньше байт, чем запрошено. `write` сразу отправляет данные в низкоуровневый дескриптор. Нет буферизации. |
+| Режим | Описание |
+|---------------|-------------------------------------------------------------------------------------------------------------------------------------------------|
+| `"default"` | Прямой режим. `read` может вернуть меньше байт, чем запрошено. `write` сразу отправляет данные в низкоуровневый дескриптор. Нет буферизации. |
| `"yield"` | Как `default`, но при нехватке данных в `read(n)` поток будет вызывать `coroutine.yield()`, пока не соберёт ровно `n` байт. Удобно для корутин. |
-| `"buffered"` | Включает внутренние буферы чтения и записи. `read` берёт данные из буфера, `write` — складывает в буфер. При превышении `maxBufferSize` — ошибка `buffer overflow`. |
+| `"buffered"` | Включает внутренние буферы чтения и записи. `read` берёт данные из буфера , `write` — складывает в буфер. |
### flush
Работает только в режиме `"buffered"`,
имеет два подрежима:
-| Режим | Что делает `flush()` |
-|------------------|----------------------|
-| `"all"` (по умолчанию) | Сначала сбрасывает буфер записи → низкоуровневый `write`, затем вызывает `ioLib.flush(descriptor)` |
-| `"buffer"` | Сбрасывает только буфер записи, без вызова системного `flush` |
+| Режим | Что делает `flush()` |
+|------------------------|-----------------------------------------------------------------------------------------------------|
+| `"all"` (по умолчанию) | Сначала сбрасывает буфер записи → низкоуровневый `write`, затем вызывает `io_lib.flush(descriptor)` |
+| `"buffer"` | Сбрасывает только буфер записи, без вызова системного `flush` |
### binary
**Независимый флаг** (включается через `set_binary_mode(true)` или при создании потока).
Определяет, в каком виде методы `read` и `write` принимают и возвращают данные:
-| binary = true | binary = false (по умолчанию) |
-|-----------------------------------------|----------------------------------------|
+| binary = true | binary = false (по умолчанию) |
+|------------------------------------------------------------|----------------------------------------|
| Данные — это **байты** (`Bytearray`, таблица чисел 0..255) | Данные — это **текстовые строки** |
-| `read(n)` → `Bytearray` или `table`| `read()` → одна строка |
-| `read("i4 f")` → распаковка через `byteutil.unpack` | `read(n)` → n строк в таблице |
-| `write(Bytearray)` → запись байтов | `write("hello")` → строка + `\n` |
-| `write("i4", 42)` → `byteutil.pack` | `write({"a","b"})` → две строки с `\n`|
+| `read(n)` → `Bytearray` или `table` | `read()` → одна строка |
+| `read("i4 f")` → распаковка через `byteutil.unpack` | `read(n)` → n строк в таблице |
+| `write(Bytearray)` → запись байтов | `write("hello")` → строка + `\n` |
+| `write("i4", 42)` → `byteutil.pack` | `write({"a","b"})` → две строки с `\n` |
`read_line` / `write_line` — работают как в текстовом режиме
@@ -90,25 +90,25 @@ io_stream:set_flush_mode(string)
--[[
Читает данные из потока
В двоичном режиме:
- Если arg - number, то читает из потока arg байт и возвращает ввиде Bytearray или таблицы, если useTable = true
+ Если arg - int, то читает из потока arg байт и возвращает ввиде Bytearray или таблицы, если use_table = true
Если arg - string, то функция интерпретирует arg как шаблон для byteutil. Прочитает кол-во байт, которое определено шаблоном, передаст их в byteutil.unpack и вернёт результат
В текстовом режиме:
- Если arg - number, то читает нужное кол-во строк с окончанием CRLF/LF из arg и возвращает ввиде таблицы. Также, если trimEmptyLines = true, то удаляет пустые строки с начала и конца из итоговой таблицы
+ Если arg - int, то читает нужное кол-во строк с окончанием CRLF/LF из arg и возвращает ввиде таблицы. Также, если trim_empty_lines = true, то удаляет пустые строки с начала и конца из итоговой таблицы
Если arg не определён, то читает одну строку с окончанием CRLF/LF и возвращает её.
--]]
io_stream:read(
- [опционально] arg: number | string,
- [опционально] useTable | trimEmptyLines: boolean
-) -> Bytearray | table | string | table | ...
+ [опционально] arg: int | string,
+ [опционально] use_table = false | trim_empty_lines = true: boolean
+) -> Bytearray | table | string | table | ...
--[[
Записывает данные в поток
В двоичном режиме:
Если arg - string, то функция интерпретирует arg как шаблон для byteutil, передаст его и ... в byteutil.pack и результат запишет в поток
- Если arg - Bytearray | table, то записывает байты в поток
+ Если arg - Bytearray | table, то записывает байты в поток
В текстовом режиме:
Если arg - string, то записывает строку в поток (вместе с окончанием LF)
@@ -116,7 +116,7 @@ io_stream:read(
Если arg - table, то записывает каждую строку из таблицы отдельно
--]]
io_stream:write(
- arg: Bytearray | table | string | table,
+ arg: Bytearray | table | string | table,
[опционально] ...
)
@@ -128,53 +128,59 @@ io_stream:write_line(string)
--[[
В двоичном режиме:
- Читает все доступные байты из потока и возвращает ввиде Bytearray или table, если useTable = true
+ Читает все доступные байты из потока и возвращает ввиде Bytearray или table, если use_table = true
В текстовом режиме:
- Читает все доступные строки из потока в table если useTable = true, или в одну строку вместе с окончаниями, если нет
+ Читает все доступные строки из потока в table если use_table = true, или в одну строку вместе с окончаниями, если нет
--]]
io_stream:read_fully(
- [опционально] useTable: boolean
-) -> Bytearray | table | table | string
+ [опционально] use_table: boolean
+) -> Bytearray | table | table | string
--[[
-Устанавливает позицию в потоке
+Если length определён, то возвращает true, если length байт доступно к чтению. Иначе возвращает false.
+
+Если не определён, то возвращает количество байт, которое можно прочитать.
+
+В не буферизированном режиме потока может всегда возвращать 0 или false, если поток не поддерживает available.
+--]]
+io_stream:available(
+ [опционально] length: int
+) -> int | boolean
+
+--[[
+Устанавливает позицию в потоке (всегда в байтах)
Режимы:
b - Задаёт позицию относительно начало файла
c - Задаёт позицию относительно текущей позиции
e - Задаёт позицию относительно конца файла
+
+Может бросать ошибку, если поток не поддерживает seek.
--]]
io_stream:seek(
mode: string
- offset: number
+ offset: int
)
+
+-- Возвращает текущую позицию в потоке от начала.
+-- Может бросать ошибку, если поток не поддерживает tell.
+io_stream:tell() -> int
```
## Методы Buffered-режима
```lua
---[[
-Если length определён, то возвращает true, если length байт доступно к чтению. Иначе возвращает false
-
-Если не определён, то возвращает количество байт, которое можно прочитать
-
---]]
-io_stream:available(
- [опционально] length: number
-) -> number | boolean
-
-- Возвращает максимальный размер буферов
-io_stream:get_max_buffer_size() -> number
+io_stream:get_max_buffer_size() -> int
-- Задаёт новый максимальный размер буферов
-io_stream:set_max_buffer_size(max_size: number)
+io_stream:set_max_buffer_size(max_size: int)
```
## Методы контроля состояния потока
```lua
-
-- Возвращает true, если поток открыт на данный момент
io_stream:is_alive() -> bool
@@ -185,16 +191,27 @@ io_stream:is_closed() -> bool
io_stream:close()
-- Записывает все данные из write-буфера в поток в buffer/all flush-режимах
--- Вызывает ioLib.flush() в all flush-режиме
+-- Вызывает ioLib.flush() в all flush-режиме, или ничего не делает, если
+-- ioLib не поддерживает flush.
io_stream:flush()
+-- Создаёт новый поток из Bytearray.
+-- Может использоваться одновременно как для чтения, так и для записи.
+-- Результат записи будет записан в тот же Bytearray, что был передан в функцию.
+io_stream.wrap_bytearray(
+ buffer: Bytearray,
+
+ -- по-умолчанию равен true, поскольку функция из вводных аргументов
+ -- будет использоваться преимущественно для работы с двоичными данными.
+ [опционально] binary_mode: boolean = true
+ ) -> io_stream
-- Создаёт новый поток с переданным дескриптором и использующим переданную I/O библиотеку. (Более подробно в core:io_stream.lua)
io_stream.new(
descriptor: int,
- binaryMode: bool,
- ioLib: table,
+ binary_mode: boolean,
+ io_lib: table,
[опционально] mode: string = "default",
- [опционально] flushMode: string = "all"
+ [опционально] flush_mode: string = "all"
) -> io_stream
```
\ No newline at end of file
diff --git a/doc/ru/scripting/ui.md b/doc/ru/scripting/ui.md
index 6cff70e2e..09e296f9b 100644
--- a/doc/ru/scripting/ui.md
+++ b/doc/ru/scripting/ui.md
@@ -1,7 +1,7 @@
# Свойства и методы UI элементов
Обращение к UI элементов в скриптах произодится через экземпляр Document
-(переменная document) по id, указанному в xml.
+(глобальная переменная document) по id, указанному в xml.
Пример: вывод в консоль свойства pos элемента с id: "worlds-panel":
```lua
@@ -53,7 +53,7 @@ document["worlds-panel"]:clear()
| contentOffset | vec2 | да | *нет* | смещение содержимого |
| cursor | string | да | да | курсор, отображаемый при наведении |
| parent | Element | да | *нет* | родительский элемент или nil |
-| zIndex | bool | да | *нет* | значение z-индекса. В panel определяет порядок |
+| zIndex | int | да | *нет* | значение z-индекса. В panel определяет порядок |
Общие методы элементов:
diff --git a/doc/ru/vca.md b/doc/ru/vca.md
new file mode 100644
index 000000000..2cba3c3ab
--- /dev/null
+++ b/doc/ru/vca.md
@@ -0,0 +1,142 @@
+# VCA
+
+Текстовый формат анимации, использующий синтаксис [VCM](vcm.md).
+
+VCA файл состоит из набора директив, порядок следования которых не влияет на порядок применение трансформаций.
+
+Директивы применяются к переданной цели, которая может быть скелетом сущности и камерой.
+При использовании скелета, в директиве указывается имя кости через атрибут `bone`:
+
+```vcd
+@move bone имя_кости ...
+```
+
+Директивы отвечают за отдельные скалярные значения, такие как x, y, z и т.д., указываемые через атрибут `by`:
+
+```vcd
+@move bone hand by y ...
+```
+
+На данный момент доступны два вида описания кривых, дающих значение `f(t) = x` где t - время:
+- [кривые с ключевыми кадрами (curve)](#кривые-с-ключевыми-кадрами)
+- [кривые через выражения (func)](#кривые-через-выражения)
+
+## Директивы анимации
+
+- `@move` - смещение объекта/кости
+- `@rotate` - поворот объекта/кости
+- `@scale` - масштабирование объекта/кости (множитель)
+- `@zoom` - масштаб камеры (множитель)
+- `@texture` - смена динамически-назначаемой текстуры (см. [skeleton:set_texture](scripting/ecs.md#skeleton))
+
+## Мета-информация
+
+Информация о анимации в файле настраивается через директиву `configure`:
+- `fps` - частота кадров, являющаяся делителем при рассчёте длительности
+- `frames` - число кадров анимации, являющееся делимым при рассчёте длительности
+- `duration` - явно указанная длительность в секундах (требуется указание fps при наличии ключевых кадров)
+- `rotation-order` - указывает порядок применения углов Эйлера при вращении (так как порядок директив не учитывается форматом). Примеры: XYZ, ZYX, YZX.
+
+Мета-информация применяется глобально. Поведение не зависит от её положения в файле, но рекомендуется располагать её в начале.
+
+## Дополнительно
+
+- `curve` - объявляет пользовательский тип кривой. Указывается имя кривой `name` и выражение вычисления значения `func`.
+
+В выражении доступны два ключа `kl`, `kr` и значение `t` в диапазоне [0..1].
+
+Пример:
+
+`@curve test-linear func (kl.value + (kr.value - kl.value) * t)`
+
+Пользовательские кривые указываются с префиксом `.`. Пример: `@move by y curve .test-linear {...}`.
+
+## Кривые с ключевыми кадрами
+
+Требуется через атрибут `curve` указать тип кривой:
+- `const` - значения не интерполируются, сменяясь в момент достижения ключевого кадра
+- `linear` - ломанная линия, используется линейная интерполяция
+- `bezier` - ключевые кадры кривой Безье с явно указанными левой и правой касательными (lx, ly, rx, ry)
+
+Ключевые кадры описываются в последующем `{...}` блоке в виде упорядоченных `@key` директив:
+
+```vcd
+@rotate by z curve linear {
+ @key ...
+ @key ...
+}
+```
+
+Ключевой кадр должен содержать номер кадра `frame` и значенин `value`. Для `bezier` кадров также описываются касательные.
+
+Пример для `curve bezier`:
+```vcd
+@key frame 138 value 53.00411 lx 127.067 ly 53.00411 rx 138.001 ry 53.00411
+```
+
+Для директивы texture всё проще. Пример:
+
+```vcd
+@texture name $0 {
+ @key frame 0 value entities/tireman:face_0
+ @key frame 24 value entities/tireman:face_1
+}
+```
+
+> entities/tireman здесь - имя текстурного атласа, в котором находятся face_\* текстуры.
+> Текстура не обязательно должна находиться в атласе.
+
+Если вы не хотите ограничивать длительность анимации через `configure`, но хотите зациклить анимацию по ключевым кадрам для конкретной линии, то можно использовать параметр `period` для указания периода повторения анимации в кадрах. Пример:
+
+```vcd
+@move by y curve linear period 24 {
+ @key frame 0 value 0
+ @key frame 12 value 1
+ @key frame 24 value 0
+}
+```
+
+## Кривые через выражения
+
+Через атрибут описывается функция `f(t) = x` где t - время в секундах.
+
+Пример: `func (sin(t * 2.5) + pi)`.
+
+Операции доступные в выражениях:
+
+- `a + b` - сложение
+- `a * b` - умножение
+- `a / b` - деление
+- `a % b` - деление по модулю
+- `a ^ b` - возведение в степень
+
+Константы доступные в выражениях:
+
+- `pi` число π
+- `e` число Эйлера
+
+Функции доступные в выражениях:
+
+- `sin(x)` - синус от x
+- `cos(x)` - косинус от x
+- `tan(x)` - тангенс от x
+- `noise(x, octaves)` - быстрый одномерный шум от x с указанным числом октав
+- `noise2d(x, y, octaves)` - двумерный шум от x,y с указанным числом октав
+- `sign(x)` - целое число, указывающее знак x (-1/0/1)
+- `rand(low, high)` - псевдослучайное дробное число в диапазоне от low до high
+- `round(x, places)` - округляет значение x до указанного количества знаков после запятой places (опционально).
+- `floor(x)` - округляет значение x до ближайшего меньшего целого
+- `ceil(x)` - округляет значение x до ближайшего большего целого
+- `exp(x)` - $e^{x}$
+- `min(x, ...)` - выбирает наименьшее значение из переданных аргументов
+- `max(x, ...)` - выбирает наибольшее значение из переданных аргументов
+- `sqrt(x)` - квадратный корень от x
+- `log(x)` - $ln({x})$
+- `log10(x)` - $log_{10}({x})$
+- `deg(x)` - конвертирует радианы в градусы
+- `rad(x)` - конвертирует градусы в радианы
+
+
+>[!WARNING]
+> Использование незадокументированных функций может иметь иметь любые незадокументированные последствия.
+
diff --git a/doc/ru/vcm.md b/doc/ru/vcm.md
index a1b72ca48..0a1dbc314 100644
--- a/doc/ru/vcm.md
+++ b/doc/ru/vcm.md
@@ -41,6 +41,8 @@
- `region` - UV регион в границах выбранной текстуры, определяется позициями противоположных углов квадрата нормализованных текстурных координат. Пример: `region (0,0,1,1)`
- `region-scale` вектор-множитель для UV региона. Пример: `region-scale (0.5,1)`
- `shading` определяет возможность затенения на примитиве. Пример: `shading off`
+- `normal` переопределяет вектор нормали. Пример: `normal (0,1,0)`
+- `cull-face` - определяет, какая сторона будет отсечена. Пример: `cull-face front` или `cull-face off` (отлючает отсечение сторон)
Текстурные координаты по-умолчанию не зависят от формы из размера, в отличие от других примитивов.
@@ -53,9 +55,11 @@
- `up` - вектор Y, также определяющий высоту примитива. Пример: `up (0,1,0)`
- `texture` - отображаемая текстура. По-умолчанию: `$0`. Пример: `texture "blocks:sand"`
- `region` - UV регион в границах выбранной текстуры, определяется позициями противоположных углов. Пример: `region (0,0,1,1)`
-- `region-scale` вектор-множитель для автоматически выбранного UV региона. Пример: `region-scale (0.5,1)`
-- `shading` определяет возможность затенения на примитиве. Пример: `shading off`
-- `flip` отражает UV регион по горизонтали или вертикали. Пример: `flip v`
+- `region-scale` - вектор-множитель для автоматически выбранного UV региона. Пример: `region-scale (0.5,1)`
+- `shading` - определяет возможность затенения на примитиве. Пример: `shading off`
+- `flip` - отражает UV регион по горизонтали или вертикали. Пример: `flip v`
+- `normal` - переопределяет вектор нормали. Пример: `normal (0,1,0)`
+- `cull-face` - определяет, какая сторона будет отсечена. Пример: `cull-face front` или `cull-face off` (отлючает отсечение сторон)
### Свойства `box`
@@ -66,8 +70,8 @@
- `origin` - точка, относительно которой будет применено вращение. По-умолчанию: центр примитива. Пример: `origin (0.5,0.5,0.5)`
- `rotate` - вращение вокруг осей (x,y,z) в градусах, или кватернион (x,y,z,w). Пример: `rotate (45,0,0)` или `rotate (0.3826834, 0, 0, 0.9238795)`
- `texture` - отображаемая текстура для всех сторон по-умолчанию.
-- `shading` определяет возможность затенения на примитиве. Пример: `shading off`
-- `delete` удаляет стороны по именам (top, bottom, east, west, north, south)
+- `shading` - определяет возможность затенения на примитиве. Пример: `shading off`
+- `delete` - удаляет стороны по именам (top, bottom, east, west, north, south)
### Свойства `part` (вложен в `box`)
@@ -76,7 +80,7 @@
- `tags` - определяет то, на какаие из сторон будут применены свойства. Пример: `tags (top,bottom)`
- `texture` - отображаемая текстура. По-умолчанию: `$индекс_стороны`.
- `region` - UV регион в границах выбранной текстуры, определяется позициями противоположных углов. Пример: `region (0,0,1,1)`
-- `region-scale` вектор-множитель для автоматически выбранного UV региона. Пример: `region-scale (0.5,1)`
+- `region-scale` - вектор-множитель для автоматически выбранного UV региона. Пример: `region-scale (0.5,1)`
## Скелет
diff --git a/doc/ru/world-generator.md b/doc/ru/world-generator.md
index 30e4b1098..34738d4b3 100644
--- a/doc/ru/world-generator.md
+++ b/doc/ru/world-generator.md
@@ -215,12 +215,28 @@ local map = Heightmap(ширина, высота)
Операции применяются ко всем значениям высоты.
```lua
+-- Приведение значений высот к абсолютным
map:abs()
+
+-- Округление к меньшему целому
+map:floor()
+
+-- Округление к большему целому
+map:ceil()
+
+-- Округление к ближайшему целому
+map:round()
+
+-- Синус от значений высот (в радианах)
+map:sin()
+
+-- Косинус от значений высот (в радианах)
+map:cos()
+
+-- Тангенс от значений высот (в радианах)
+map:tan()
```
-Приводит значения высот к абсолютным.
-
-
### Бинарные операции
Операции с применением второй карты или скаляра.
@@ -271,6 +287,14 @@ map:dump('export:test.png')
Зерно шума может быть указано в поле `map.noiseSeed`.
+По-умолчанию октавы шума совмещаются через сложение:
+
+$шум_{результат} = шум_{исходный} + шум_{применяемый} * 2^{-{октава}}$
+
+Для более получения нормализованного многооктавного шума можно включить флаг `map.normalNoise = true`, меняющий схему на:
+
+$шум_{результат} = шум_{исходный} * (1 - 2^{-{октава}}) + шум_{применяемый} * 2^{-{октава}}$
+
```lua
map:noise(
-- смещение координат
@@ -300,6 +324,10 @@ map:noise(

+> [!NOTE] клеточный шум выглядит лучше с `map.normalNoise = true`
+
+
+
### heightmap:resize(...)
```lua
diff --git a/doc/ru/xml-ui-layouts.md b/doc/ru/xml-ui-layouts.md
index 2ca6da1ce..9be788e7f 100644
--- a/doc/ru/xml-ui-layouts.md
+++ b/doc/ru/xml-ui-layouts.md
@@ -43,6 +43,8 @@
- `position-func` - поставщик позиции элемента (два числа), вызываемый при изменении размера контейнера, в котором находится элемент, либо при добавлении элемента в контейнер. Может быть вызван до вызова on_hud_open.
- `size-func` - поставщик размера элемента (два числа), вызываемый при изменении размера контейнера, в котором находится элемент, либо при добавлении элемента в контейнер. Может быть вызван до вызова on_hud_open.
- `onclick` - lua функция вызываемая при нажатии на элемент.
+- `onrightclick` - lua функция вызываемая при нажатии правой кнопки мыши на элемент.
+- `onmiddleclick` - lua функция вызываемая при нажатии средней кнопки мыши на элемент.
- `ondoubleclick` - lua функция вызываемая при двойном нажатии на элемент.
- `onfocus` - lua функция вызываемая при фокусировке на элемент.
- `ondefocus` - lua функция вызываемая при потере фокуса элеметом.
@@ -193,6 +195,9 @@
- `width` - минимальная ширина содержимого. По-умолчанию: 100.
- `selected` - изначально выбранное значение. По-умолчанию: "".
- `onselect` - функция, в которую передаётся выбранное пользователем значение
+- `mode` - режим работы:
+ - `select` - режим по-умолчанию.
+ - `button` - режим кнопки: текст не заменяется на выбранную опцию, а элемент выглядит как обычная кнопка.
## Привязка ввода - *bindbox*
diff --git a/doc/specs/debugging_protocol.md b/doc/specs/debugging_protocol.md
index ba4cf96a8..fbf206f28 100644
--- a/doc/specs/debugging_protocol.md
+++ b/doc/specs/debugging_protocol.md
@@ -1,4 +1,4 @@
-# VC-DBG protocol v1
+# VC-DBG protocol v1.1
## Notes
@@ -79,7 +79,7 @@ Configuring connection. Disconnect-action is action that debugged instance must
- `frame` - Call stack frame index (indexing from most recent call)
- `local` - Local variable index (based on `paused` event stack trace)
-- `path` - Requsted value path segments. Example: `['a', 'b', 5]` is `local_variable.a.b[5]`
+- `path` - Requested value path segments. Example: `['a', 'b', 5]` is `local_variable.a.b[5]`
Responds with:
@@ -116,6 +116,15 @@ Then `value` is:
}
```
+### File hot-reload signal
+
+```json
+{
+ "type": "hot-reload",
+ "file": "string"
+}
+```
+
## Server-to-client
### Response signals
diff --git a/doc/specs/vec3_model_spec.md b/doc/specs/vec3_model_spec.md
index b9c2868c7..80c6e7073 100644
--- a/doc/specs/vec3_model_spec.md
+++ b/doc/specs/vec3_model_spec.md
@@ -16,7 +16,7 @@ enum AttributeType:uint8 {
sizeof(AttributeType) == 1;
struct VertexAttribute {
- AttributeType type; // data type is infered from attribute type
+ AttributeType type; // data type is inferred from attribute type
uint8 flags;
uint32 size;
float data[]; // if compressed, first 4 bytes of compressed data is decompressed size
diff --git a/flake.nix b/flake.nix
index ee1e6baa9..ead09d092 100644
--- a/flake.nix
+++ b/flake.nix
@@ -37,6 +37,7 @@
openal
luajit
curl
+ openssl
entt
mesa
freeglut
diff --git a/res/content/base/config/defaults.toml b/res/content/base/config/defaults.toml
index 650c24d74..d2c5142cc 100644
--- a/res/content/base/config/defaults.toml
+++ b/res/content/base/config/defaults.toml
@@ -1,3 +1,4 @@
generator = "base:demo"
player-entity = "base:player"
hand-skeleton = "base:hand"
+block-material = "base:stone"
diff --git a/res/content/base/generators/demo.files/script.lua b/res/content/base/generators/demo.files/script.lua
index 7a3282c3c..ff05e08cc 100644
--- a/res/content/base/generators/demo.files/script.lua
+++ b/res/content/base/generators/demo.files/script.lua
@@ -86,12 +86,27 @@ function generate_heightmap(x, y, w, h, s, inputs)
local rivermap = Heightmap(w, h)
rivermap.noiseSeed = SEED
- rivermap:noise({x+21, y+12}, 0.1*s, 4)
- rivermap:abs()
- rivermap:mul(2.0)
- rivermap:pow(0.15)
- rivermap:max(0.5)
- map:mul(rivermap)
+ rivermap:noise({ x + 21, y + 12 }, 0.1 * s, 4)
+ rivermap:pow(4)
+ rivermap:mul(3500)
+ rivermap:add(1)
+ rivermap:pow(-1)
+ rivermap:mul(-1)
+ rivermap:add(1)
+
+ local rivermap_bottom = Heightmap(w, h)
+ rivermap_bottom:add(0.23)
+ rivermap_bottom:noise({ x, y }, 2 * s, 4, 0.005)
+
+ map:sub(rivermap_bottom)
+
+ local map_multiplied = Heightmap(w, h)
+ map_multiplied:add(map)
+ map_multiplied:mul(rivermap)
+
+ map:min(map_multiplied)
+
+ map:add(rivermap_bottom)
local desertmap = Heightmap(w, h)
desertmap.noiseSeed = SEED
diff --git a/res/content/base/modules/util.lua b/res/content/base/modules/util.lua
index b1a97ad06..843f818c7 100644
--- a/res/content/base/modules/util.lua
+++ b/res/content/base/modules/util.lua
@@ -1,25 +1,91 @@
local util = {}
-function util.drop(ppos, itemid, count, data, pickup_delay)
- if itemid == 0 or not itemid then
- return nil
+util.DROP_FORCE = 8
+util.DROP_INIT_VEL = { 0, 3, 0 }
+util.DROP_MAX_ITEM_DIR_SHIFT_DEGREES = 65
+
+---@param dir_shift? vec2 direction shift for drop; x and y must be clamped to [-0.5, 0.5]
+local function calculate_item_drop_dir(pid, dir_shift)
+ if not dir_shift then
+ dir_shift = { 0, 0 }
end
- return entities.spawn("base:drop", ppos, {base__drop={
- id=itemid,
- count=count,
- data=data,
- pickup_delay=pickup_delay
- }})
+ local yaw, pitch = player.get_rot(pid)
+ local q_yaw = quat.from_euler({ 0, yaw, 0 })
+ local q_pitch = quat.from_euler({ pitch, 0, 0 })
+ local q_rotation = quat.mul(q_yaw, q_pitch)
+
+ local q_shift = quat.from_euler({
+ -dir_shift[2] * util.DROP_MAX_ITEM_DIR_SHIFT_DEGREES * 2,
+ -dir_shift[1] * util.DROP_MAX_ITEM_DIR_SHIFT_DEGREES * 2,
+ 0,
+ })
+ quat.mul(q_rotation, q_shift, q_rotation)
+ return quat.mul_vec3(q_rotation, { 0, 0, -1 })
end
-local function calc_loot(loot_table)
+--- Create a drop from slot, set it velocity, and return it
+---@param mode integer 0 - whole stack, 1 - single item, 2 - dupe whole stack
+---@param dir_shift? vec2 direction shift for drop; x and y must be clamped to [-0.5, 0.5]
+---@return table? entity, string? error
+function util.drop_from_slot(pid, invid, slot, mode, dir_shift)
+ if invid == 0 then
+ return nil, "invid cannot be 0"
+ end
+ if mode == 2 and not player.is_infinite_items(pid) then
+ return nil, "no permission to dupe items"
+ end
+ local itemid, itemcount = inventory.get(invid, slot)
+ if itemid == 0 then
+ return nil, "no item in slot"
+ end
+
+ local drop_itemcount = 1
+ if mode == 0 then
+ drop_itemcount = itemcount
+ end
+ if mode == 2 then
+ drop_itemcount = item.stack_size(itemid)
+ else
+ inventory.set(invid, slot, itemid, itemcount - drop_itemcount)
+ end
+
+ local data = inventory.get_all_data(invid, slot)
+ local pvel = { player.get_vel(pid) }
+ local ppos = vec3.add({ player.get_pos(pid) }, { 0, 0.7, 0 })
+ local dir = calculate_item_drop_dir(pid, dir_shift)
+ local throw_force = vec3.mul(dir, util.DROP_FORCE)
+ local drop, err = util.drop(ppos, itemid, drop_itemcount, data, 1.5)
+ if not drop then
+ return nil, err
+ end
+ local velocity = vec3.add(throw_force, vec3.add(pvel, util.DROP_INIT_VEL))
+ drop.rigidbody:set_vel(velocity)
+ return drop
+end
+
+---@return table? entity, string? error
+function util.drop(ppos, itemid, count, data, pickup_delay)
+ if itemid == 0 or not itemid then
+ return nil, "item is empty"
+ end
+ return entities.spawn("base:drop", ppos, {
+ base__drop = {
+ id = itemid,
+ count = count,
+ data = data,
+ pickup_delay = pickup_delay
+ }
+ })
+end
+
+function util.calc_loot(loot_table)
local results = {}
for _, loot in ipairs(loot_table) do
local chance = loot.chance or 1
local count = loot.count or 1
-
+
local roll = math.random()
-
+
if roll < chance then
if loot.min and loot.max then
count = math.random(loot.min, loot.max)
@@ -27,7 +93,9 @@ local function calc_loot(loot_table)
if count == 0 then
goto continue
end
- table.insert(results, {item=item.index(loot.item), count=count})
+ table.insert(results, {
+ item = item.index(loot.item), count = count
+ })
end
::continue::
end
@@ -37,9 +105,9 @@ end
function util.block_loot(blockid)
local lootscheme = block.properties[blockid]["base:loot"]
if lootscheme then
- return calc_loot(lootscheme)
+ return util.calc_loot(lootscheme)
end
- return {{item=block.get_picking_item(blockid), count=1}}
+ return { { item = block.get_picking_item(blockid), count = 1 } }
end
return util
diff --git a/res/content/base/scripts/components/drop.lua b/res/content/base/scripts/components/drop.lua
index 39bd03ceb..335b81d89 100644
--- a/res/content/base/scripts/components/drop.lua
+++ b/res/content/base/scripts/components/drop.lua
@@ -10,7 +10,7 @@ dropitem = ARGS
if dropitem.item then
dropitem.id = item.index(dropitem.item)
end
-if dropitem then
+if dropitem then
timer = dropitem.pickup_delay or timer
end
if SAVED_DATA.item then
@@ -26,6 +26,7 @@ function on_save()
end
if vc.is_client() then
+ local SCALE = 0.3
local scale = {1, 1, 1}
local rotation = mat4.rotate({
math.random(), math.random(), math.random()
@@ -35,7 +36,7 @@ if vc.is_client() then
local matrix = mat4.idt()
rig:set_model(0, item.model_name(dropitem.id))
local bodysize = math.min(scale[1], scale[2], scale[3])
- body:set_size({scale[1], bodysize, scale[3]})
+ body:set_size(vec3.mul({scale[1], bodysize, scale[3]}, SCALE))
mat4.mul(matrix, rotation, matrix)
mat4.scale(matrix, scale, matrix)
rig:set_matrix(0, matrix)
diff --git a/res/content/base/scripts/grass_block.lua b/res/content/base/scripts/grass_block.lua
index fb7482c20..b5965de43 100644
--- a/res/content/base/scripts/grass_block.lua
+++ b/res/content/base/scripts/grass_block.lua
@@ -1,3 +1,6 @@
+local dirtid = block.index("base:dirt")
+local grass_blockid = block.index("base:grass_block")
+
local offsets = {}
for lx=-1,1 do
for ly=-1,1 do
@@ -8,18 +11,17 @@ for lx=-1,1 do
end
function on_random_update(x, y, z)
- local dirtid = block.index('base:dirt');
if block.is_solid_at(x, y+1, z) then
block.set(x, y, z, dirtid, 0)
return
end
- local grassblockid = block.index('base:grass_block')
+
for _, offset in ipairs(offsets) do
local nx, ny, nz = x + offset[1], y + offset[2], z + offset[3]
if block.get(nx, ny, nz) == dirtid and
not block.is_solid_at(nx, ny + 1, nz) then
- block.set(nx, ny, nz, grassblockid, 0)
+ block.set(nx, ny, nz, grass_blockid, 0)
return
end
end
diff --git a/res/content/base/scripts/hud.lua b/res/content/base/scripts/hud.lua
index 9fc10f2a1..5d3bfeb46 100644
--- a/res/content/base/scripts/hud.lua
+++ b/res/content/base/scripts/hud.lua
@@ -1,30 +1,26 @@
local base_util = require "util"
-local DROP_FORCE = 8
-local DROP_INIT_VEL = {0, 3, 0}
-
function on_hud_open()
- input.add_callback("player.drop", function ()
+ events.on("core:drop_outside_inventory", function(mode)
+ local pid = hud.get_player()
+ local invid = hud.get_exchange_inventory()
+ local vp = gui.get_viewport()
+ local dir_shift = table.map(input.get_mouse_pos(), function(i, v)
+ return v / vp[i] - 0.5
+ end)
+ base_util.drop_from_slot(pid, invid, 0, mode, dir_shift)
+ end)
+ input.add_callback("player.drop", function()
if hud.is_paused() or hud.is_inventory_open() then
return
end
local pid = hud.get_player()
local invid, slot = player.get_inventory(pid)
- local itemid, itemcount = inventory.get(invid, slot)
- if itemid == 0 then
- return
+ local mode = 1
+ if input.is_pressed("key:left-ctrl") or input.is_pressed("key:right-ctrl") then
+ mode = 0
end
- local data = inventory.get_all_data(invid, slot)
- inventory.set(invid, slot, itemid, itemcount-1)
-
- local pvel = {player.get_vel(pid)}
- local ppos = vec3.add({player.get_pos(pid)}, {0, 0.7, 0})
- local throw_force = vec3.mul(player.get_dir(pid), DROP_FORCE)
- local drop = base_util.drop(ppos, itemid, 1, data, 1.5)
- if not drop then
- return
- end
- local velocity = vec3.add(throw_force, vec3.add(pvel, DROP_INIT_VEL))
- drop.rigidbody:set_vel(velocity)
+ base_util.drop_from_slot(pid, invid, slot, mode)
end)
+ rules.create("do-loot-non-player", true)
end
diff --git a/res/content/base/scripts/world.lua b/res/content/base/scripts/world.lua
index 419dcc769..3da6f6c2a 100644
--- a/res/content/base/scripts/world.lua
+++ b/res/content/base/scripts/world.lua
@@ -16,6 +16,4 @@ function on_block_broken(id, x, y, z, playerid)
spawn_spread=vec3.mul(size, 0.4)
})
end
-
- rules.create("do-loot-non-player", true)
end
diff --git a/res/devtools/syntax/vca.toml b/res/devtools/syntax/vca.toml
new file mode 100644
index 000000000..b87411998
--- /dev/null
+++ b/res/devtools/syntax/vca.toml
@@ -0,0 +1,7 @@
+language = "VCA"
+extensions = ["vca"]
+line-comment = "#"
+identifier-part-chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"
+keywords = [
+ "bone", "by", "func", "curve", "fps", "duration", "frames", "rotation-order"
+]
diff --git a/res/layouts/code_editor.xml b/res/layouts/code_editor.xml
index b3cd2ed9c..fb4833da1 100644
--- a/res/layouts/code_editor.xml
+++ b/res/layouts/code_editor.xml
@@ -17,7 +17,7 @@
color="#FFFFFF80" size="16" pos="4,6"
hover-color="#1080FF">
+ size="76,24" padding="8,6,8,2" interval="8" color="0">
+
+
diff --git a/res/layouts/code_editor.xml.lua b/res/layouts/code_editor.xml.lua
index 733fa9036..61e90842f 100644
--- a/res/layouts/code_editor.xml.lua
+++ b/res/layouts/code_editor.xml.lua
@@ -113,6 +113,78 @@ local function reload_model(filename, name)
assets.parse_model(file.ext(filename), document.editor.text, name)
end
+-- === TODO: remove after 0.32 ===
+local pattern =
+ "region %(%s*"
+ .. "([+-]?%d+%.?%d*[eE]?[+-]?%d*)%s*,%s*"
+ .. "([+-]?%d+%.?%d*[eE]?[+-]?%d*)%s*,%s*"
+ .. "([+-]?%d+%.?%d*[eE]?[+-]?%d*)%s*,%s*"
+ .. "([+-]?%d+%.?%d*[eE]?[+-]?%d*)"
+ .. "%s*%)"
+
+local function replace1(x1, y1, x2, y2)
+ return string.format("region (%s, %s, %s, %s)", x2, y2, x1, y1)
+end
+
+local function replace2(x1, y1, x2, y2)
+ return string.format("region (%s, %s, %s, %s)", x2, y1, x1, y2)
+end
+
+function convert_vcm(text)
+ local lines = {}
+ local zpairs = {
+ {"%(north%)", "%(south%)", "(TMPS)", "(TMPN)"},
+ {"%,north", "%,south", ",TMPS", ",TMPN"},
+ {"north%,", "south%,", "TMPS,", "TMPN,"},
+ }
+ local xpairs = {
+ {"%(west%)", "%(east%)", "(TMPE)", "(TMPW)"},
+ {"%,west", "%,east", ",TMPE", ",TMPW"},
+ {"west%,", "east%,", "TMPE,", "TMPW,"},
+ }
+
+ for i, pair in ipairs(zpairs) do
+ text = text:gsub(pair[1], pair[3])
+ text = text:gsub(pair[2], pair[4])
+ end
+ text = text:gsub("TMPS", "south")
+ text = text:gsub("TMPN", "north")
+
+ for i, pair in ipairs(xpairs) do
+ text = text:gsub(pair[1], pair[3])
+ text = text:gsub(pair[2], pair[4])
+ end
+ text = text:gsub("TMPW", "west")
+ text = text:gsub("TMPE", "east")
+
+ for line in text:gmatch("[^\n]*\n?") do
+ if line == "" then
+ break
+ end
+
+ if line:find("(top)", 1, true) then
+ line = line:gsub(pattern, replace1)
+ end
+
+ if line:find("(bottom)", 1, true)
+ or line:find("(east)", 1, true) then
+ line = line:gsub(pattern, replace2)
+ end
+
+ table.insert(lines, line)
+ end
+
+ return table.concat(lines)
+end
+
+function fix_vcm_regions()
+ if not current_file.filename then
+ return
+ end
+ document.editor.text = convert_vcm(document.editor.text)
+end
+-- ===============================
+
function run_current_file()
if not current_file.filename then
return
diff --git a/res/layouts/ingame_chat.xml.lua b/res/layouts/ingame_chat.xml.lua
index dce629887..fdd535045 100644
--- a/res/layouts/ingame_chat.xml.lua
+++ b/res/layouts/ingame_chat.xml.lua
@@ -19,7 +19,7 @@ local function update_line(line, uptime)
end
end
-events.on("core:chat", function(message)
+local core_chat_handler = events.on("core:chat", function(message)
while #lines >= max_lines do
document[lines[1][1]]:destruct()
table.remove(lines, 1)
@@ -36,7 +36,7 @@ end)
function on_open()
if not initialized then
initialized = true
-
+
document.root:setInterval(1/animation_fps * 1000, function ()
local uptime = time.uptime()
for _, line in ipairs(lines) do
@@ -52,3 +52,7 @@ function on_open()
end)
end
end
+
+function on_destroy()
+ events.remove("core:chat", core_chat_handler)
+end
diff --git a/res/layouts/inventory.xml b/res/layouts/inventory.xml
index 4291ab4d3..7a33b054f 100644
--- a/res/layouts/inventory.xml
+++ b/res/layouts/inventory.xml
@@ -1,4 +1,4 @@
-
-
+
+
diff --git a/res/layouts/inventory.xml.lua b/res/layouts/inventory.xml.lua
index 9f836223d..5c79db6ff 100644
--- a/res/layouts/inventory.xml.lua
+++ b/res/layouts/inventory.xml.lua
@@ -1,12 +1 @@
-function inventory_share_func(invid, slotid)
- local blockinv = hud.get_block_inventory()
- if blockinv ~= 0 then
- inventory.move(invid, slotid, blockinv)
- elseif rules.get("allow-content-access") then
- inventory.set(invid, slotid, 0, 0)
- elseif slotid < 10 then
- inventory.move_range(invid, slotid, invid, 10)
- else
- inventory.move_range(invid, slotid, invid, 0, 9)
- end
-end
+share_func = require("core:inventory_utils").share_default_func
diff --git a/res/layouts/pages/content.xml.lua b/res/layouts/pages/content.xml.lua
index 2937542f4..268875874 100644
--- a/res/layouts/pages/content.xml.lua
+++ b/res/layouts/pages/content.xml.lua
@@ -3,6 +3,7 @@ function on_open(params)
mode = params.mode
end
refresh()
+ document.search_textbox.focused = true
end
-- add - packs to be added to the world (after apply)
@@ -66,16 +67,16 @@ function refresh_search()
local new_included = table.copy(packs_included)
local new_excluded = table.copy(packs_excluded)
- local function score(pack_name)
- if pack_name:lower():find(search_text) then
+ local function score(pack_id, pack_name)
+ if pack_name:lower():find(search_text) or pack_id:lower():find(search_text) then
return 1
end
return 0
end
local function sorting(a, b)
- local score_a = score(packs_info[a][2])
- local score_b = score(packs_info[b][2])
+ local score_a = score(a, packs_info[a][2])
+ local score_b = score(b, packs_info[b][2])
if score_a ~= score_b then
return score_a > score_b
@@ -178,40 +179,40 @@ function place_pack(panel, packinfo, callback, position_func)
end
end
-local Version = {};
+local Version = {}
function Version.matches_pattern(version)
- for _, letter in string.gmatch(version, "%.+") do
- if type(letter) ~= "number" or letter ~= "." then
- return false;
- end
+ local t = string.split(version, ".")
+ if #t ~= 2 and #t ~= 3 then return false end
- local t = string.split(version, ".");
-
- return #t == 2 or #t == 3;
+ for i = 1, #t do
+ local matched = string.match(t[i], "^%d+$")
+ if not matched then return false end
end
+
+ return true
end
function Version.__equal(ver1, ver2)
- return ver1[1] == ver2[1] and ver1[2] == ver2[2] and ver1[3] == ver2[3];
+ return ver1[1] == ver2[1] and ver1[2] == ver2[2] and ver1[3] == ver2[3]
end
function Version.__greater(ver1, ver2)
- if ver1[1] ~= ver2[1] then return ver1[1] > ver2[1] end;
- if ver1[2] ~= ver2[2] then return ver1[2] > ver2[2] end;
- return ver1[3] > ver2[3];
+ if ver1[1] ~= ver2[1] then return ver1[1] > ver2[1] end
+ if ver1[2] ~= ver2[2] then return ver1[2] > ver2[2] end
+ return ver1[3] > ver2[3]
end
function Version.__less(ver1, ver2)
- return Version.__greater(ver2, ver1);
+ return Version.__greater(ver2, ver1)
end
function Version.__greater_or_equal(ver1, ver2)
- return not Version.__less(ver1, ver2);
+ return not Version.__less(ver1, ver2)
end
function Version.__less_or_equal(ver1, ver2)
- return not Version.__greater(ver1, ver2);
+ return not Version.__greater(ver1, ver2)
end
Version.operators = {
@@ -223,40 +224,44 @@ Version.operators = {
}
function Version.compare(op, ver1, ver2)
- ver1 = string.split(ver1, ".");
- ver2 = string.split(ver2, ".");
+ ver1 = string.split(ver1, ".")
+ ver2 = string.split(ver2, ".")
+
+ for i = 1, 3 do
+ ver1[i] = tonumber(ver1[i]) or 0
+ ver2[i] = tonumber(ver2[i]) or 0
+ end
local comparison_func = Version.operators[op];
if comparison_func then
- return comparison_func(ver1, ver2);
+ return comparison_func(ver1, ver2)
else
- return false;
+ return false
end
end
function Version.parse(version)
- local op = string.sub(version, 1, 2);
+ local op = string.sub(version, 1, 2)
if op == ">=" or op == "<=" then
- return op, string.sub(version, #op + 1);
+ return op, string.sub(version, #op + 1)
end
op = string.sub(version, 1, 1);
if op == ">" or op == "<" then
- return op, string.sub(version, #op + 1);
+ return op, string.sub(version, #op + 1)
end
- return "=", version;
+ return "=", version
end
-local function compare_version(dependent_version, actual_version)
+local function compare_version(op, dependent_version, actual_version)
if Version.matches_pattern(dependent_version) and Version.matches_pattern(actual_version) then
- local op, dep_ver = Version.parse_version(dependent_version);
- Version.compare(op, dep_ver, actual_version);
+ return Version.compare(op, actual_version, dependent_version)
elseif dependent_version == "*" or dependent_version == actual_version then
- return true;
+ return true
else
- return false;
+ return false
end
end
@@ -276,15 +281,15 @@ function check_dependencies(packinfo)
)
end
- local dep_pack = pack.get_info(depid);
-
- if not compare_version(depver, dep_pack.version) then
- local op, ver = Version.parse(depver)
+ local dep_pack = pack.get_info(depid)
+ local op, ver = Version.parse(depver)
+
+ if not compare_version(op, ver, dep_pack.version) then
return string.format(
"%s: %s != %s (%s)",
gui.str("error.dependency-version-not-met"),
dep_pack.version, ver, depid
- );
+ )
end
if table.has(packs_installed, packinfo.id) then
diff --git a/res/layouts/pages/content_menu.xml.lua b/res/layouts/pages/content_menu.xml.lua
index 8abe215fa..6eb7e779b 100644
--- a/res/layouts/pages/content_menu.xml.lua
+++ b/res/layouts/pages/content_menu.xml.lua
@@ -11,6 +11,7 @@ local CONFIG_NAMES = {
function on_open()
refresh()
+ document.search_textbox.focused = true
end
function place_pack(panel, packinfo, callback)
@@ -39,7 +40,7 @@ function refresh_search()
local pos = content.pos
local size = content.size
- if title:lower():find(search_text) or search_text == '' then
+ if title:lower():find(search_text) or id:lower():find(search_text) or search_text == '' then
content.enabled = true
content.pos = {pos[1], visible * (size[2] + interval) - step}
visible = visible + 1
diff --git a/res/layouts/pages/new_world.xml b/res/layouts/pages/new_world.xml
index 84a9519fa..fc13d5084 100644
--- a/res/layouts/pages/new_world.xml
+++ b/res/layouts/pages/new_world.xml
@@ -11,7 +11,7 @@
@World generator
-