Merge pull request #617 from MihailRis/dev

0.29 development
This commit is contained in:
MihailRis
2025-09-20 00:01:40 +03:00
committed by GitHub
239 changed files with 7949 additions and 1859 deletions
+26
View File
@@ -297,3 +297,29 @@ Methods are used to manage the overwriting of properties when extending a block
### `property_name@append`
Adds elements to the end of the list instead of completely overwriting it.
## Tags
Tags allow you to designate general properties of blocks. Names should be formatted as `prefix:tag_name`.
The prefix is optional, but helps avoid unwanted logical collisions. Example:
```json
{
"tags": [
"core:ore",
"base_survival:food",
]
}
```
Block tags can also be added from other packs using the `your_pack:tags.toml` file. Example:
```toml
"prefix:tag_name" = [
"random_pack:some_block",
"another_pack:item",
]
"other_prefix:other_tag_name" = [
# ...
]
``
+5
View File
@@ -30,6 +30,11 @@ If prefix is not specified, '!' level will be used.
Example: '~randutil' - weak dependency 'randutil'.
Dependency version is indicated after '@' symbol and have operators to restrict acceptable versions.
If version is not specified, '\*' (any) version will be used.
Example: 'randutil@>=1.0' - dependency 'randutil' which requires version 1.0 or newer.
Example:
```json
{
+16
View File
@@ -20,6 +20,22 @@ Example:
]
```
You can pass values in ARGS from the entity configuration.
They will be passed both when creating a new entity and when loading a saved one.
The `args` list is used for this:
```json
"components": [
{
"name": "base:drop",
"args": {
"item": "base:stone.item",
"count": 1
}
}
]
```
The components code should be in `scripts/components`.
## Physics
+34
View File
@@ -18,6 +18,14 @@ Name of the item model. The model will be loaded automatically.
Default value is `packid:itemname.model`.
If the model is not specified, an automatic one will be generated.
### Caption and Description
`caption` - name of item in inventory
`description` - item description in inventory
this props allow to use `md`
*see [Text Styles](/doc/en/text-styles.md)*
## Behaviour
### *placing-block*
@@ -58,3 +66,29 @@ Property status is displayed in the inventory interface. Display method is defin
- `number` - number
- `relation` - current value to initial value (x/y)
- `vbar` - vertical scale (used by default)
## Tags
Tags allow you to designate general properties of items. Names should be formatted as `prefix:tag_name`.
The prefix is optional, but helps avoid unwanted logical collisions. Example:
```json
{
"tags": [
"core:fuel",
"base_survival:poison",
]
}
```
Tags can also be added to items from other packs using the `your_pack:tags.toml` file. Example
```toml
"prefix:tag_name" = [
"random_pack:item",
"another_pack:some_block",
]
"other_prefix:other_tag_name" = [
# ...
]
```
+1 -1
View File
@@ -1,6 +1,6 @@
# Documentation
Documentation for release 0.28.
Documentation for 0.29.
## Sections
+4
View File
@@ -10,6 +10,7 @@ Subsections:
- [Entities and components](scripting/ecs.md)
- [Libraries](#)
- [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)
@@ -20,6 +21,7 @@ Subsections:
- [gfx.blockwraps](scripting/builtins/libgfx-blockwraps.md)
- [gfx.particles](particles.md#gfxparticles-library)
- [gfx.posteffects](scripting/builtins/libgfx-posteffects.md)
- [gfx.skeletons](scripting/builtins/libgfx-skeletons.md)
- [gfx.text3d](3d-text.md#gfxtext3d-library)
- [gfx.weather](scripting/builtins/libgfx-weather.md)
- [gui](scripting/builtins/libgui.md)
@@ -30,8 +32,10 @@ Subsections:
- [mat4](scripting/builtins/libmat4.md)
- [network](scripting/builtins/libnetwork.md)
- [pack](scripting/builtins/libpack.md)
- [pathfinding](scripting/builtins/libpathfinding.md)
- [player](scripting/builtins/libplayer.md)
- [quat](scripting/builtins/libquat.md)
- [random](scripting/builtins/librandom.md)
- [rules](scripting/builtins/librules.md)
- [time](scripting/builtins/libtime.md)
- [utf8](scripting/builtins/libutf8.md)
+5 -2
View File
@@ -25,9 +25,12 @@ Waits for the specified time in seconds, performing the main engine loop.
app.sleep_until(
-- function that checks the condition for ending the wait
predicate: function() -> bool,
-- the maximum number of engine loop ticks after which
-- maximum number of engine loop ticks after which
-- a "max ticks exceed" exception will be thrown
[optional] max_ticks = 1e9
[optional] max_ticks = 1e9,
-- maximum wait time in seconds.
-- (works with system time, including test mode)
[optional] timeout = 1e9
)
```
+28
View File
@@ -0,0 +1,28 @@
# *assets* library
A library for working with audio/visual assets.
## Functions
```lua
-- Loads a texture
assets.load_texture(
-- Array of bytes of an image file
data: table | Bytearray,
-- Texture name after loading
name: str,
-- Image file format (only png is supported)
[optional]
format: str = "png"
)
-- Parses and loads a 3D model
assets.parse_model(
-- Model file format (xml / vcm)
format: str,
-- Contents of the model file
content: str,
-- Model name after loading
name: str
)
```
+6
View File
@@ -8,4 +8,10 @@ base64.encode(bytes: table|ByteArray) -> str
-- Decode base64 string to ByteArray or lua table if second argument is set to true
base64.decode(base64string: str, [optional]usetable: bool=false) -> table|ByteArray
-- Encode bytes to urlsafe-base64 string ('-', '_' instead of '+', '/')
base64.encode_urlsafe(bytes: table|ByteArray) -> str
-- Decodes urlsafe-base64 string to a ByteArray or a table of numbers if the second argument is set to true
base64.decode_urlsafe(base64string: str, [optional]usetable: bool=false) -> table|ByteArray
```
+20 -2
View File
@@ -68,6 +68,9 @@ block.get_variant(x: int, y: int, z: int) -> int
-- Sets the block variant by index
block.set_variant(x: int, y: int, z: int, index: int) -> int
-- Checks if an block has specified tag
block.has_tag(id: int, tag: str) -> bool
```
## Rotation
@@ -119,13 +122,13 @@ block.seek_origin(x: int, y: int, z: int) -> int, int, int
Part of a voxel data used for scripting. Size: 8 bit.
```python
```lua
block.get_user_bits(x: int, y: int, z: int, offset: int, bits: int) -> int
```
Get specified bits as an unsigned integer.
```python
```lua
block.set_user_bits(x: int, y: int, z: int, offset: int, bits: int, value: int) -> int
```
Set specified bits.
@@ -151,6 +154,21 @@ 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.
## Model
Block model information.
```lua
-- returns block model type (block/aabb/custom/...)
block.get_model(id: int) -> str
-- returns block model name
block.model_name(id: int) -> str
-- returns array of 6 textures assigned to sides of block
block.get_textures(id: int) -> string table
```
## Data fields
```lua
@@ -0,0 +1,48 @@
# gfx.skeletons library
A library for working with named skeletons, such as 'hand',
used to control the hand and the carried item displayed in first-person view.
The set of functions is similar to the skeleton component of entities.
The first argument to the function is the name of the skeleton.
```lua
-- Returns an object wrapper over the skeleton
local skeleton = gfx.skeletons.get(name: str)
-- Returns the index of the bone by name or nil
skeleton:index(name: str) -> int
-- Returns the name of the model assigned to the bone with the specified index
skeleton:get_model(index: int) -> str
-- Reassigns the model of the bone with the specified index
-- Resets to the original if you do not specify a name
skeleton:set_model(index: int, name: str)
-- Returns the transformation matrix of the bone with the specified index
skeleton:get_matrix(index: int) -> mat4
-- Sets the transformation matrix of the bone with the specified index
skeleton:set_matrix(index: int, matrix: mat4)
-- Returns the texture by key (dynamically assigned textures - '$name')
skeleton:get_texture(key: str) -> str
-- Assigns a texture by key
skeleton:set_texture(key: str, value: str)
-- Checks the visibility status of a bone by index
-- or the entire skeleton if index is not specified
skeleton:is_visible([optional] index: int) -> bool
-- Sets the visibility status of a bone by index
-- or the entire skeleton if index is not specified
skeleton:set_visible([optional] index: int, status: bool)
-- Returns the color of the entity
skeleton:get_color() -> vec3
-- Sets the color of the entity
skeleton:set_color(color: vec3)
```
+6
View File
@@ -103,3 +103,9 @@ gui.load_document(
```
Loads a UI document with its script, returns the name of the document if successfully loaded.
```lua
gui.root: Document
```
Root UI document
+3
View File
@@ -65,4 +65,7 @@ hud.is_inventory_open() -> bool
-- Sets whether to allow pausing. If false, the pause menu will not pause the game.
hud.set_allow_pause(flag: bool)
-- Function that controls the named skeleton 'hand' (see gfx.skeletons)
hud.hand_controller: function()
```
+34
View File
@@ -97,6 +97,40 @@ inventory.set(...)
inventory.set_all_data(...)
```
for moving is inefficient, use inventory.move or inventory.move_range.
```lua
-- Get item caption
inventory.get_caption(
-- id of inventory
invid: int,
-- slot id
slot: int
)
-- Set item caption
inventory.set_caption(
-- id of inventory
invid: int,
-- slot id
slot: int,
-- Item Caption
caption: string
)
-- Get item description
inventory.get_description(
-- id of inventory
invid: int,
-- slot id
slot: int
)
-- Set item description
inventory.set_description(
-- id of inventory
invid: int,
-- slot id
slot: int,
-- Item Description
description: string
)
```
```lua
-- Returns a copy of value of a local property of an item by name or nil.
+6
View File
@@ -10,6 +10,9 @@ item.index(name: str) -> int
-- Returns the item display name.
block.caption(blockid: int) -> str
-- Returns the item display description.
item.description(itemid: int) -> str
-- Returns max stack size for the item
item.stack_size(itemid: int) -> int
@@ -30,4 +33,7 @@ item.emission(itemid: int) -> str
-- Returns the value of the `uses` property
item.uses(itemid: int) -> int
-- Checks if an item has specified tag
item.has_tag(itemid: int, tag: str) -> bool
```
+26 -5
View File
@@ -6,9 +6,15 @@ A library for working with the network.
```lua
-- Performs a GET request to the specified URL.
-- After receiving the response, passes the text to the callback function.
-- In case of an error, the HTTP response code will be passed to onfailure.
network.get(url: str, callback: function(str), [optional] onfailure: function(int))
network.get(
url: str,
-- Function to call when response is received
callback: function(str),
-- Error handler
[optional] onfailure: function(int, str),
-- List of additional request headers
[optional] headers: table<str>
)
-- Example:
network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/latest", function (s)
@@ -16,13 +22,28 @@ network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/lat
end)
-- A variant for binary files, with a byte array instead of a string in the response.
network.get_binary(url: str, callback: function(table|ByteArray), [optional] onfailure: function(int))
network.get_binary(
url: str,
callback: function(ByteArray),
[optional] onfailure: function(int, str),
[optional] headers: table<str>
)
-- Performs a POST request to the specified URL.
-- Currently, only `Content-Type: application/json` is supported
-- After receiving the response, passes the text to the callback function.
-- In case of an error, the HTTP response code will be passed to onfailure.
network.post(url: str, data: table, callback: function(str), [optional] onfailure: function(int))
network.post(
url: str,
-- Request body as a table (will be converted to JSON) or string
body: table|str,
-- Function called when response is received
callback: function(str),
-- Error handler
[optional] onfailure: function(int, str),
-- List of additional request headers
[optional] headers: table<str>
)
```
## TCP Connections
@@ -0,0 +1,66 @@
# *pathfinding* library
The *pathfinding* library provides functions for working with the pathfinding system in the game world. It allows you to create and manage agents finding routes between points in the world.
When used in entity logic, the `core:pathfinding` component should be used.
## `core:pathfinding` component
```lua
local pf = entity:get_component("core:pathfinding")
--- ...
local x = ...
local y = ...
local z = ...
--- Set the target for the agent
pf.set_target({x, y, z})
--- Get the current target of the agent
local target = pf.get_target() --> vec3 or nil
--- ...
--- Get the current route of the agent
local route = pf.get_route() --> table<vec3> or nil
--- ...
```
## Library functions
```lua
--- Create a new agent. Returns the ID of the created agent
local agent = pathfinding.create_agent() --> int
--- Delete an agent by ID. Returns true if the agent existed, otherwise false
pathfinding.remove_agent(agent: int) --> bool
--- Set the agent state (enabled/disabled)
pathfinding.set_enabled(agent: int, enabled: bool)
--- Check the agent state. Returns true if the agent is enabled, otherwise false
pathfinding.is_enabled(agent: int) --> bool
--- Create a route based on the given points. Returns an array of route points
pathfinding.make_route(start: vec3, target: vec3) --> table<vec3>
--- Asynchronously create a route based on the given points.
--- This function allows to perform pathfinding in the background without blocking the main thread of execution
pathfinding.make_route_async(agent: int, start: vec3, target: vec3)
--- Get the route that the agent has already found. Used to get the route after an asynchronous search.
--- If the search has not yet completed, returns nil. If the route is not found, returns an empty table.
pathfinding.pull_route(agent: int) --> table<vec3> or nil
--- Set the maximum number of visited blocks for the agent. Used to limit the amount of work of the pathfinding algorithm.
pathfinding.set_max_visited(agent: int, max_visited: int)
--- Adding an avoided blocks tag
pathfinding.avoid_tag(
agent: int,
-- tag for avoided blocks
tag: string, [optional],
-- cost of crossing a block
cost: int = 10
)
```
+38
View File
@@ -0,0 +1,38 @@
# *random* library
A library of functions for generating random numbers.
## Non-deterministic numbers
```lua
-- Generates a random number in the range [0..1)
random.random() --> number
-- Generates a random integer in the range [0..n]
random.random(n) --> number
-- Generates a random integer in the range [a..b]
random.random(a, b) --> number
-- Generates a random byte array of length n
random.bytes(n: number) -> Bytearray
-- Generates a UUID version 4
random.uuid() -> str
```
## Pseudorandom numbers
The library provides the Random class - a generator with its own isolated state.
```lua
local rng = random.Random()
-- Used similarly to math.random
local a = rng:random() --> [0..1)
local b = rng:random(10) --> [0..10]
local c = rng:random(5, 20) --> [5..20]
-- Sets the generator state to generate a reproducible sequence of random numbers
rng:seed(42)
```
+31
View File
@@ -100,6 +100,13 @@ vecn.length(a: vector)
```
#### Distance - *vecn.distance(...)*
```lua
-- returns the distance between two vectors
vecn.distance(a: vector, b: vector)
```
#### Absolute value - *vecn.abs(...)*
```lua
@@ -136,6 +143,16 @@ vecn.pow(v: vector, exponent: number, dst: vector)
vecn.dot(a: vector, b: vector)
```
#### Mixing - *vecn.mix(...)*
```lua
-- returns vector a * (1.0 - t) + b * t
vecn.mix(a: vector, b: vector, t: number)
-- writes to dst vector a * (1.0 - t) + b * t
vecn.mix(a: vector, b: vector, t: number, dst: vector)
```
#### Convert to string - *vecn.tostring(...)*
> [!WARNING]
> Returns only if the content is a vector
@@ -160,6 +177,12 @@ vec2.angle(v: vec2)
-- returns the direction angle of the vector {x, y} in degrees [0, 360]
vec2.angle(x: number, y: number)
-- returns the vector rotated by an angle in degrees counterclockwise
vec2.rotate(v: vec2, angle: number) -> vec2
-- writes the vector rotated by an angle in degrees counterclockwise to dst
vec2.rotate(v: vec2, angle: number, dst: vec2) -> vec2
```
@@ -188,6 +211,10 @@ print("mul: " .. vec3.tostring(result_mul)) -- {10, 40, 80}
local result_mul_scal = vec3.mul(v1_3d, scal)
print("mul_scal: " .. vec3.tostring(result_mul_scal)) -- {6, 12, 12}
-- calculating distance between vectors
local result_distance = vec3.distance(v1_3d, v2_3d)
print("distance: " .. result_distance) -- 43
-- vector normalization
local result_norm = vec3.normalize(v1_3d)
print("norm: " .. vec3.tostring(result_norm)) -- {0.333, 0.667, 0.667}
@@ -211,3 +238,7 @@ print("pow: " .. vec3.tostring(result_pow)) -- {1, 4, 4}
-- scalar product of vectors
local result_dot = vec3.dot(v1_3d, v2_3d)
print("dot: " ..result_dot) -- 250
-- mixing vectors
local result_mix = vec3.mix(v1_3d, v2_3d, 0.25)
print("mix: " .. vec3.tostring(result_mix)) -- {3.25, 6.5, 11.5}
+13 -3
View File
@@ -26,6 +26,8 @@ entity:get_uid() -> int
entity:get_component(name: str) -> component or nil
-- Checks for the presence of a component by name
entity:has_component(name: str) -> bool
-- Retrieves a component by name. Throws an exception if it does not exist
entity:require_component(name: str) -> component
-- Enables/disables the component
entity:set_enabled(name: str, enable: bool)
@@ -93,10 +95,12 @@ body:get_linear_damping() -> number
-- Sets the linear velocity attenuation multiplier
body:set_linear_damping(value: number)
-- Checks if vertical velocity attenuation is enabled
-- Checks if vertical damping is enabled
body:is_vdamping() -> bool
-- Enables/disables vertical velocity attenuation
body:set_vdamping(enabled: bool)
-- Returns the vertical damping multiplier
body:get_vdamping() -> number
-- Enables/disables vertical damping / sets vertical damping multiplier
body:set_vdamping(enabled: bool | number)
-- Checks if the entity is on the ground
body:is_grounded() -> bool
@@ -188,6 +192,12 @@ function on_update(tps: int)
Called every entities tick (currently 20 times per second).
```lua
function on_physics_update(delta: number)
```
Called after each physics step
```lua
function on_render(delta: number)
```
+7
View File
@@ -46,6 +46,13 @@ function on_blocks_tick(tps: int)
Called tps (20) times per second. Use 1/tps instead of `time.delta()`.
```lua
function on_block_tick(x, y, z, tps: number)
```
Called tps (20 / tick-interval) times per second for a block.
Use 1/tps instead of `time.delta()`.
```lua
function on_player_tick(playerid: int, tps: int)
```
+26
View File
@@ -306,3 +306,29 @@
### `имя_свойства@append`
Добавляет элементы в конец списка, вместо его полной перезаписи.
## Теги - *tags*
Теги позволяют обозначать обобщённые свойства блоков. Названия следует формировать как `префикс:имя_тега`.
Префикс не является обязательным, но позволяет избегать нежелательных логических коллизий. Пример:
```json
{
"tags": [
"core:ore",
"base_survival:food",
]
}
```
Теги блокам можно добавлять и из других паков, с помощью файла `ваш_пак:tags.toml`. Пример
```toml
"префикс:имя_тега" = [
"рандомный_пак:какой_то_блок",
"ещё_один_пак:предмет",
]
"другой_префикс:другое_имя_тега" = [
# ...
]
```
+5
View File
@@ -32,6 +32,11 @@
Пример: '~randutil' - слабая зависимость 'randutil'.
Версии зависимостей указываются после '@' и имеют операторы для ограничения допустимых версий.
Отсутствие версии зависимости интерпретируется как '\*', т.е. любая версия.
Пример: 'randutil@>=1.0' - зависимость 'randutil' версии 1.0 и старше.
Пример:
```json
{
+16
View File
@@ -20,6 +20,22 @@
]
```
Из конфигурации сущности можно передавать значения в ARGS.
Они будут передаваться как при создании новой сущности, так и при загрузке сохранённой.
Для этого используется список `args`:
```json
"components": [
{
"name": "base:drop",
"args": {
"item": "base:stone.item",
"count": 1
}
}
]
```
Код компонентов должен находиться в `scripts/components`.
## Физика
+35
View File
@@ -17,6 +17,14 @@
Значение по-умолчанию - `packid:itemname.model`.
Если модель не указана, будет сгенерирована автоматическию
### Имя и Описание
`caption` - имя предмета в инвентаре
`description` - описание предмета в инвентаре
Можно использовать `md`
*см. [Text Styles](/doc/en/text-styles.md)*
## Поведение
### Устанавливаемый блок - `placing-block`
@@ -57,3 +65,30 @@
- `number` - число
- `relation` - отношение текущего значения к изначальному (x/y)
- `vbar` - вертикальная шкала (используется по-умолчанию)
## Теги - *tags*
Теги позволяют обозначать обобщённые свойства предметов. Названия следует формировать как `префикс:имя_тега`.
Префикс не является обязательным, но позволяет избегать нежелательных логических коллизий. Пример:
```json
{
"tags": [
"core:fuel",
"base_survival:poison",
]
}
```
Теги предметам можно добавлять и из других паков, с помощью файла `ваш_пак:tags.toml`. Пример
```toml
"префикс:имя_тега" = [
"рандомный_пак:предмет",
"ещё_один_пак:какой_то_блок",
]
"другой_префикс:другое_имя_тега" = [
# ...
]
```
+1 -1
View File
@@ -1,6 +1,6 @@
# Документация
Документация версии 0.28.
Документация версии 0.29.
## Разделы
+4
View File
@@ -10,6 +10,7 @@
- [Сущности и компоненты](scripting/ecs.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)
@@ -20,6 +21,7 @@
- [gfx.blockwraps](scripting/builtins/libgfx-blockwraps.md)
- [gfx.particles](particles.md#библиотека-gfxparticles)
- [gfx.posteffects](scripting/builtins/libgfx-posteffects.md)
- [gfx.skeletons](scripting/builtins/libgfx-skeletons.md)
- [gfx.text3d](3d-text.md#библиотека-gfxtext3d)
- [gfx.weather](scripting/builtins/libgfx-weather.md)
- [gui](scripting/builtins/libgui.md)
@@ -30,8 +32,10 @@
- [mat4](scripting/builtins/libmat4.md)
- [network](scripting/builtins/libnetwork.md)
- [pack](scripting/builtins/libpack.md)
- [pathfinding](scripting/builtins/libpathfinding.md)
- [player](scripting/builtins/libplayer.md)
- [quat](scripting/builtins/libquat.md)
- [random](scripting/builtins/librandom.md)
- [rules](scripting/builtins/librules.md)
- [time](scripting/builtins/libtime.md)
- [utf8](scripting/builtins/libutf8.md)
+4 -1
View File
@@ -27,7 +27,10 @@ app.sleep_until(
predicate: function() -> bool,
-- максимальное количество тактов цикла движка, после истечения которых
-- будет брошено исключение "max ticks exceed"
[опционально] max_ticks = 1e9
[опционально] max_ticks = 1e9,
-- максимальное длительность ожидания в секундах.
-- (работает с системным временем, включая test-режим)
[опционально] timeout = 1e9
)
```
+28
View File
@@ -0,0 +1,28 @@
# Библиотека *assets*
Библиотека для работы с аудио/визуальными загружаемыми ресурсами.
## Функции
```lua
-- Загружает текстуру
assets.load_texture(
-- Массив байт файла изображения
data: table | Bytearray,
-- Имя текстуры после загрузки
name: str,
-- Формат файла изображения (поддерживается только png)
[опционально]
format: str = "png"
)
-- Парсит и загружает 3D модель
assets.parse_model(
-- Формат файла модели (xml / vcm)
format: str,
-- Содержимое файла модели
content: str,
-- Имя модели после загрузки
name: str
)
```
+6
View File
@@ -8,4 +8,10 @@ base64.encode(bytes: table|ByteArray) -> str
-- Декодирует base64 строку в ByteArray или таблицу чисел, если второй аргумент установлен на true
base64.decode(base64string: str, [опционально]usetable: bool=false) -> table|ByteArray
-- Кодирует массив байт в urlsafe-base64 строку ('-', '_' вместо '+', '/')
base64.encode_urlsafe(bytes: table|ByteArray) -> str
-- Декодирует urlsafe-base64 строку в ByteArray или таблицу чисел, если второй аргумент установлен на true
base64.decode_urlsafe(base64string: str, [опционально]usetable: bool=false) -> table|ByteArray
```
+6
View File
@@ -67,6 +67,9 @@ block.get_variant(x: int, y: int, z: int) -> int
-- Устанавливает вариант блока по индексу
block.set_variant(x: int, y: int, z: int, index: int) -> int
-- Проверяет наличие тега у блока
block.has_tag(id: int, tag: str) -> bool
```
### Raycast
@@ -171,6 +174,9 @@ block.get_hitbox(id: int, rotation_index: int) -> {vec3, vec3}
-- возвращает тип модели блока (block/aabb/custom/...)
block.get_model(id: int) -> str
-- возвращает имя модели блока
block.model_name(id: int) -> str
-- возвращает массив из 6 текстур, назначенных на стороны блока
block.get_textures(id: int) -> таблица строк
```
+23
View File
@@ -183,3 +183,26 @@ file.join(директория: str, путь: str) --> str
Соединяет путь. Пример: `file.join("world:data", "base/config.toml)` -> `world:data/base/config.toml`.
Следует использовать данную функцию вместо конкатенации с `/`, так как `префикс:/путь` не является валидным.
```lua
file.open(путь: str, режим: str) --> io_stream
```
Открывает поток для записи/чтения в файл по пути `путь`.
Аргумент `режим` это список отдельных режимов, в котором каждый обозначается одним символом
`r` - Чтение из файла
`w` - Запись в файл
`b` - Открыть поток в двоичном режиме (см. `../io_stream.md`)
`+` - Работает совместно с `w`. Добавляет к существующим данным новые (`append-mode`)
```lua
file.open_named_pipe(имя: str, режим: str) -> io_stream
```
Открывает поток для записи/чтения в Named Pipe по пути `путь`
`/tmp/` или `\\\\.\\pipe\\` добавлять не нужно - движок делает это автоматически.
Доступные режимы такие же, как и в `file.open`, за исключением `+`
@@ -0,0 +1,49 @@
# Библиотека gfx.skeletons
Библиотека для работы с именованными скелетами, такими как 'hand',
использующийся для управления, отображаемыми при виде от первого лица,
рукой и переносимым предметом. Набор функций аналогичен компоненту skeleton
у сущностей.
Первым аргументом в функции передаётся имя скелета.
```lua
-- Возвращает объектную обёртку над скелетом
local skeleton = gfx.skeletons.get(name: str)
-- Возвращает индекс кости по имени или nil
skeleton:index(name: str) -> int
-- Возвращает имя модели, назначенной на кость с указанным индексом
skeleton:get_model(index: int) -> str
-- Переназначает модель кости с указанным индексом
-- Сбрасывает до изначальной, если не указывать имя
skeleton:set_model(index: int, name: str)
-- Возвращает матрицу трансформации кости с указанным индексом
skeleton:get_matrix(index: int) -> mat4
-- Устанавливает матрицу трансформации кости с указанным индексом
skeleton:set_matrix(index: int, matrix: mat4)
-- Возвращает текстуру по ключу (динамически назначаемые текстуры - '$имя')
skeleton:get_texture(key: str) -> str
-- Назначает текстуру по ключу
skeleton:set_texture(key: str, value: str)
-- Проверяет статус видимости кости по индесу
-- или всего скелета, если индекс не указан
skeleton:is_visible([опционально] index: int) -> bool
-- Устанавливает статус видимости кости по индексу
-- или всего скелета, если индекс не указан
skeleton:set_visible([опционально] index: int, status: bool)
-- Возвращает цвет сущности
skeleton:get_color() -> vec3
-- Устанавливает цвет сущности
skeleton:set_color(color: vec3)
```
+6
View File
@@ -100,3 +100,9 @@ gui.load_document(
```
Загружает UI документ с его скриптом, возвращает имя документа, если успешно загружен.
```lua
gui.root: Document
```
Корневой UI документ
+3
View File
@@ -68,4 +68,7 @@ hud.is_inventory_open() -> bool
-- Устанавливает разрешение на паузу. При значении false меню паузы не приостанавливает игру.
hud.set_allow_pause(flag: bool)
-- Функция, управляющая именованным скелетом 'hand' (см. gfx.skeletons)
hud.hand_controller: function()
```
+34
View File
@@ -94,6 +94,40 @@ inventory.set(...)
inventory.set_all_data(...)
```
для перемещения вляется неэффективным, используйте inventory.move или inventory.move_range.
```lua
-- Получает имя предмета в слоте
inventory.get_caption(
-- id инвентаря
invid: int,
-- индекс слота
slot: int
)
-- Задает имя предмету в слоте
inventory.set_caption(
-- id инвентаря
invid: int,
-- индекс слота
slot: int,
-- Имя предмета
caption: string
)
-- Получает описание предмета в слоте
inventory.get_description(
-- id инвентаря
invid: int,
-- индекс слота
slot: int
)
-- Задает описание предмету в слоте
inventory.set_description(
-- id инвентаря
invid: int,
-- индекс слота
slot: int,
-- Описание предмета
description: string
)
```
```lua
-- Проверяет наличие локального свойства по имени без копирования его значения.
+6
View File
@@ -10,6 +10,9 @@ item.index(name: str) -> int
-- Возвращает название предмета, отображаемое в интерфейсе.
item.caption(itemid: int) -> str
-- Возвращает описание предмета, отображаемое в интерфейсе.
item.description(itemid: int) -> str
-- Возвращает максимальный размер стопки для предмета.
item.stack_size(itemid: int) -> int
@@ -30,6 +33,9 @@ item.emission(itemid: int) -> str
-- Возвращает значение свойства `uses`
item.uses(itemid: int) -> int
-- Проверяет наличие тега у предмета
item.has_tag(itemid: int, tag: str) -> bool
```
+86 -6
View File
@@ -2,13 +2,19 @@
Библиотека для работы с сетью.
## HTTP-запросы
## HTTP-Запросы
```lua
-- Выполняет GET запрос к указанному URL.
-- После получения ответа, передаёт текст в функцию callback.
-- В случае ошибки в onfailure будет передан HTTP-код ответа.
network.get(url: str, callback: function(str), [опционально] onfailure: function(int))
network.get(
url: str,
-- Функция, вызываемая при получении ответа
callback: function(str),
-- Обработчик ошибок
[опционально] onfailure: function(int, str),
-- Список дополнительных заголовков запроса
[опционально] headers: table<str>
)
-- Пример:
network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/latest", function (s)
@@ -16,13 +22,28 @@ network.get("https://api.github.com/repos/MihailRis/VoxelEngine-Cpp/releases/lat
end)
-- Вариант для двоичных файлов, с массивом байт вместо строки в ответе.
network.get_binary(url: str, callback: function(table|ByteArray), [опционально] onfailure: function(int))
network.get_binary(
url: str,
callback: function(ByteArray),
[опционально] onfailure: function(int, Bytearray),
[опционально] headers: table<str>
)
-- Выполняет POST запрос к указанному URL.
-- На данный момент реализована поддержка только `Content-Type: application/json`
-- После получения ответа, передаёт текст в функцию callback.
-- В случае ошибки в onfailure будет передан HTTP-код ответа.
network.post(url: str, data: table, callback: function(str), [опционально] onfailure: function(int))
network.post(
url: str,
-- Тело запроса в виде таблицы, конвертируемой в JSON или строки
body: table|str,
-- Функция, вызываемая при получении ответа
callback: function(str),
-- Обработчик ошибок
[опционально] onfailure: function(int, str),
-- Список дополнительных заголовков запроса
[опционально] headers: table<str>
)
```
## TCP-Соединения
@@ -98,6 +119,65 @@ server:is_open() --> bool
server:get_port() --> int
```
## UDP-Датаграммы
```lua
network.udp_connect(
address: str,
port: int,
-- Функция, вызываемая при получении датаграммы с указанного при открытии сокета адреса и порта
datagramHandler: function(Bytearray),
-- Функция, вызываемая после открытия сокета
-- Опциональна, так как в UDP нет handshake
[опционально] openCallback: function(WriteableSocket),
) --> WriteableSocket
```
Открывает UDP-сокет с привязкой к удалённому адресу и порту
Класс WriteableSocket имеет следующие методы:
```lua
-- Отправляет датаграмму на адрес и порт, заданные при открытии сокета
socket:send(table|Bytearray|str)
-- Закрывает сокет
socket:close()
-- Проверяет открыт ли сокет
socket:is_open() --> bool
-- Возвращает адрес и порт, на которые привязан сокет
socket:get_address() --> str, int
```
```lua
network.udp_open(
port: int,
-- Функция, вызываемая при получении датаграмы
-- В параметры передаётся адрес и порт отправителя, а также сами данные
datagramHandler: function(address: str, port: int, data: Bytearray, server: DatagramServerSocket)
) --> DatagramServerSocket
```
Открывает UDP-сервер на указанном порту
Класс DatagramServerSocket имеет следующие методы:
```lua
-- Отправляет датаграмму на переданный адрес и порт
server:send(address: str, port: int, data: table|Bytearray|str)
-- Завершает принятие датаграмм
server:stop()
-- Проверяет возможность принятия датаграмм
server:is_open() --> bool
-- Возвращает порт, который слушает сервер
server:get_port() --> int
```
## Аналитика
```lua
@@ -0,0 +1,66 @@
# Библиотека *pathfinding*
Библиотека *pathfinding* предоставляет функции для работы с системой поиска пути в игровом мире. Она позволяет создавать и управлять агентами, которые могут находить маршруты между точками в мире.
При использовании в логике сущностей следует использовать компонент `core:pathfinding`.
## Компонент `core:pathfinding`
```lua
local pf = entity:get_component("core:pathfinding")
--- ...
local x = ...
local y = ...
local z = ...
--- Установка цели для агента
pf.set_target({x, y, z})
--- Получение текущей цели агента
local target = pf.get_target() --> vec3 или nil
--- ...
--- Получение текущего маршрута агента
local route = pf.get_route() --> table<vec3> или nil
--- ...
```
## Функции библиотеки
```lua
--- Создание нового агента. Возвращает идентификатор созданного агента
local agent = pathfinding.create_agent() --> int
--- Удаление агента по идентификатору. Возвращает true, если агент существовал, иначе false
pathfinding.remove_agent(agent: int) --> bool
--- Установка состояния агента (включен/выключен)
pathfinding.set_enabled(agent: int, enabled: bool)
--- Проверка состояния агента. Возвращает true, если агент включен, иначе false
pathfinding.is_enabled(agent: int) --> bool
--- Создание маршрута на основе заданных точек. Возвращает массив точек маршрута
pathfinding.make_route(start: vec3, target: vec3) --> table<vec3>
--- Асинхронное создание маршрута на основе заданных точек.
--- Функция позволяет выполнять поиск пути в фоновом режиме, не блокируя основной поток выполнения
pathfinding.make_route_async(agent: int, start: vec3, target: vec3)
--- Получение маршрута, который агент уже нашел. Используется для получения маршрута после асинхронного поиска.
--- Если поиск ещё не завершён, возвращает nil. Если маршрут не найден, возвращает пустую таблицу.
pathfinding.pull_route(agent: int) --> table<vec3> или nil
--- Установка максимального количества посещенных блоков для агента. Используется для ограничения объема работы алгоритма поиска пути.
pathfinding.set_max_visited(agent: int, max_visited: int)
--- Добавление тега избегаемых блоков
pathfinding.avoid_tag(
agent: int,
-- тег избегаемых блоков
tag: string, [опционально],
-- стоимость пересечения блока
cost: int = 10
)
```
+38
View File
@@ -0,0 +1,38 @@
# Библиотека *random*
Библиотека функций для генерации случайный чисел.
## Недетерминированные числа
```lua
-- Генерирует случайное число в диапазоне [0..1)
random.random() --> number
-- Генерирует случайное целое число в диапазоне [0..n]
random.random(n) --> number
-- Генерирует случайное целое число в диапазоне [a..b]
random.random(a, b) --> number
-- Генерирует случайный массив байт длиной n
random.bytes(n: number) -> Bytearray
-- Генерирует UUID версии 4
random.uuid() -> str
```
## Псевдослучайные числа
Библиотека предоставляет класс Random - генератор с собственным изолированным состоянием.
```lua
local rng = random.Random()
-- Используется аналогично math.random
local a = rng:random() --> [0..1)
local b = rng:random(10) --> [0..10]
local c = rng:random(5, 20) --> [5..20]
-- Устанавливает состояние генератора для генерации воспроизводимой последовательности случайных чисел
rng:seed(42)
```
+18
View File
@@ -11,3 +11,21 @@ time.delta() -> float
```
Возвращает дельту времени (время прошедшее с предыдущего кадра)
```python
time.utc_time() -> int
```
Возвращает время UTC в секундах
```python
time.local_time() -> int
```
Возвращает локальное (системное) время в секундах
```python
time.utc_offset() -> int
```
Возвращает смещение локального времени от UTC в секундах
+32
View File
@@ -100,6 +100,13 @@ vecn.length(a: vector)
```
#### Дистанция - *vecn.distance(...)*
```lua
-- возвращает расстояние между двумя векторами
vecn.distance(a: vector, b: vector)
```
#### Абсолютное значение - *vecn.abs(...)*
```lua
@@ -136,6 +143,16 @@ vecn.pow(v: vector, exponent: number, dst: vector)
vecn.dot(a: vector, b: vector)
```
#### Смешивание - *vecn.mix(...)*
```lua
-- возвращает вектор a * (1.0 - t) + b * t
vecn.mix(a: vector, b: vector, t: number)
-- записывает в dst вектор a * (1.0 - t) + b * t
vecn.mix(a: vector, b: vector, t: number, dst: vector)
```
#### Перевод в строку - *vecn.tostring(...)*
> [!WARNING]
> Возвращает только тогда, когда содержимым является вектор
@@ -160,6 +177,12 @@ vec2.angle(v: vec2)
-- возвращает угол направления вектора {x, y} в градусах [0, 360]
vec2.angle(x: number, y: number)
-- возвращает повернутый вектор на угол в градусах против часовой стрелки
vec2.rotate(v: vec2, angle: number) -> vec2
-- записывает повернутый вектор на угол в градусах против часовой стрелки в dst
vec2.rotate(v: vec2, angle: number, dst: vec2) -> vec2
```
@@ -192,6 +215,10 @@ print("mul_scal: " .. vec3.tostring(result_mul_scal)) -- {6, 12, 12}
local result_norm = vec3.normalize(v1_3d)
print("norm: " .. vec3.tostring(result_norm)) -- {0.333, 0.667, 0.667}
-- дистанция между векторами
local result_distance = vec3.distance(v1_3d, v2_3d)
print("distance: " .. result_distance) -- 43
-- длина вектора
local result_len = vec3.length(v1_3d)
print("len: " .. result_len) -- 3
@@ -211,4 +238,9 @@ print("pow: " .. vec3.tostring(result_pow)) -- {1, 4, 4}
-- скалярное произведение векторов
local result_dot = vec3.dot(v1_3d, v2_3d)
print("dot: " .. result_dot) -- 250
-- смешивание векторов
local result_mix = vec3.mix(v1_3d, v2_3d, 0.25)
print("mix: " .. vec3.tostring(result_mix)) -- {3.25, 6.5, 11.5}
```
+12 -2
View File
@@ -26,6 +26,8 @@ entity:get_uid() -> int
entity:get_component(name: str) -> компонент или nil
-- Проверяет наличие компонента по имени
entity:has_component(name: str) -> bool
-- Запрашивает компонент по имени. Бросает исключение при отсутствии
entity:require_component(name: str) -> компонент
-- Включает/выключает компонент по имени
entity:set_enabled(name: str, enable: bool)
@@ -95,8 +97,10 @@ body:set_linear_damping(value: number)
-- Проверяет, включено ли вертикальное затухание скорости
body:is_vdamping() -> bool
-- Включает/выключает вертикальное затухание скорости
body:set_vdamping(enabled: bool)
-- Возвращает множитель вертикального затухания скорости
body:get_vdamping() -> number
-- Включает/выключает вертикальное затухание скорости / устанавливает значение множителя
body:set_vdamping(enabled: bool | number)
-- Проверяет, находится ли сущность на земле (приземлена)
body:is_grounded() -> bool
@@ -188,6 +192,12 @@ function on_update(tps: int)
Вызывается каждый такт сущностей (на данный момент - 20 раз в секунду).
```lua
function on_physics_update(delta: number)
```
Вызывается после каждого шага физики
```lua
function on_render(delta: number)
```
+7
View File
@@ -46,6 +46,13 @@ function on_blocks_tick(tps: int)
Вызывается tps (20) раз в секунду. Используйте 1/tps вместо `time.delta()`.
```lua
function on_block_tick(x, y, z, tps: number)
```
Вызывается tps (20 / tick-interval) раз в секунду для конкретного блока.
Используйте 1/tps вместо `time.delta()`.
```lua
function on_player_tick(playerid: int, tps: int)
```
+13
View File
@@ -258,3 +258,16 @@ function sleep(timesec: number)
```
Вызывает остановку корутины до тех пор, пока не пройдёт количество секунд, указанное в **timesec**. Функция может быть использована только внутри корутины.
```lua
function await(co: coroutine) -> result, error
```
Ожидает завершение переданной корутины, возвращая поток управления. Функция может быть использована только внутри корутины.
Возвращает значения аналогичные возвращаемым значениям *pcall*.
```lua
os.pid -> number
```
Константа, в которой хранится PID текущего инстанса движка
+188
View File
@@ -0,0 +1,188 @@
# Класс *io_stream*
Класс, предназначенный для работы с потоками
## Режимы
Поток имеет три различных вида режима:
**general** - Общий режим работы I/O
**binary** - Формат записи и чтения I/O
**flush** - Режим работы flush
### general
Имеет три режима:
**default** - Дефолтный режим работы потока. При read может вернуть только часть от требуемых данных, при write сразу записывает данные в поток.
**yield** - Почти тоже самое, что и **default**, но всегда будет возвращать все требуемые данные. Пока они не будут прочитаны, будет вызывать `coroutine.yield()`. Предназначен для работы в корутинах.
**buffered** - Буферизирует записываемые и читаемые данные.
При вызове `available`/`read` обновляет буфер чтения.
После обновления в `read`, если буфер чтения переполнен, то бросает ошибку `buffer overflow`.
Если требуемого кол-ва байт недостаточно в буфере для чтения, то бросает ошибку `buffer-underflow`.
При вызове `write` записывает итоговые байты в буфер для записи. Если он переполнен, то бросает ошибку `buffer overflow`.
При вызове `flush` проталкивает данные из буфера для записи в напрямую в поток
### flush
**all** - Сначала проталкивает данные из буфера напрямую в поток (если используется **buffered** режим), а после вызывает `flush` напрямую из библиотеки
**buffer** - Только проталкивает данные из буфера в поток (если используется **buffered** режим)
## Методы
Методы, позволяющие изменить или получить различные режимы поведения потока
```lua
-- Возвращает true, если поток используется в двоичном режиме
io_stream:is_binary_mode() --> bool
-- Включает или выключает двоичный режим
io_stream:set_binary_mode(bool)
-- Возвращает режим работы потока
io_stream:get_mode() --> string
-- Задаёт режим работы потока. Выбрасывает ошибку, если передан неизвестный режим
io_stream:set_mode(string)
-- Возвращает режим работы flush
io_stream:get_flush_mode() --> string
-- Задаёт режим работы flush
io_stream:set_flush_mode(string)
```
I/O методы
```lua
--[[
Читает данные из потока
В двоичном режиме:
Если arg - int, то читает из потока arg байт и возвращает ввиде Bytearray или таблицы, если useTable = true
Если arg - string, то функция интерпретирует arg как шаблон для byteutil. Прочитает кол-во байт, которое определено шаблоном, передаст их в byteutil.unpack и вернёт результат
В текстовом режиме:
Если arg - int, то читает нужное кол-во строк с окончанием CRLF/LF из arg и возвращает ввиде таблицы. Также, если trimEmptyLines = true, то удаляет пустые строки с начала и конца из итоговой таблицы
Если arg не определён, то читает одну строку с окончанием CRLF/LF и возвращает её.
--]]
io_stream:read(
[опционально] arg: int | string,
[опционально] useTable | trimEmptyLines: bool
) --> Bytearray | table<int> | string | table<string> | ...
--[[
Записывает данные в поток
В двоичном режиме:
Если arg - string, то функция интерпретирует arg как шаблон для byteutil, передаст его и ... в byteutil.pack и результат запишет в поток
Если arg - Bytearray | table<int>, то записывает байты в поток
В текстовом режиме:
Если arg - string, то записывает строку в поток (вместе с окончанием LF)
Если arg - table<string>, то записывает каждую строку из таблицы отдельно
--]]
io_stream:write(
arg: Bytearray | table<int> | string | table<string>,
[опционально] ...
)
-- Читает одну строку с окончанием CRLF/LF из потока вне зависимости от двоичного режима
io_stream:read_line() --> string
-- Записывает одну строку с окончанием LF в поток вне зависимости от двоичного режима
io_stream:write_line(string)
--[[
В двоичном режиме:
Читает все доступные байты из потока и возвращает ввиде Bytearray или table<int>, если useTable = true
В текстовом режиме:
Читает все доступные строки из потока в table<string> если useTable = true, или в одну строку вместе с окончаниями, если нет
--]]
io_stream:read_fully(
[опционально] useTable: bool
) --> Bytearray | table<int> | table<string> | string
```
Методы, имеющие смысл в использовании только в buffered режиме
```lua
--[[
Если length определён, то возвращает true, если length байт доступно к чтению. Иначе возвращает false
Если не определён, то возвращает количество байт, которое можно прочитать
--]]
io_stream:available(
[опционально] length: int
) --> int | bool
-- Возвращает максимальный размер буферов
io_stream:get_max_buffer_size() --> int
-- Задаёт новый максимальный размер буферов
io_stream:set_max_buffer_size(max_size: int)
```
Методы, контролирующие состояние потока
```lua
-- Возвращает true, если поток открыт на данный момент
io_stream:is_alive() --> bool
-- Возвращает true, если поток закрыт на данный момент
io_stream:is_closed() --> bool
-- Закрывает поток
io_stream:close()
--[[
Записывает все данные из write-буфера в поток в buffer/all flush-режимах
Вызывает ioLib.flush() в all flush-режиме
--]]
io_stream:flush()
```
Создание нового потока
```lua
--[[
Создаёт новый поток с переданным дескриптором и использующим переданную I/O библиотеку. (Более подробно в core:io_stream.lua)
--]]
io_stream.new(
descriptor: int,
binaryMode: bool,
ioLib: table,
[опционально] mode: string = "default",
[опционально] flushMode: string = "all"
) -> io_stream
```