This commit is contained in:
@clasher113 2024-06-13 23:55:33 +03:00
commit 203b8f85eb
37 changed files with 1158 additions and 324 deletions

View File

@ -1,11 +0,0 @@
# Sections
- [Engine usage recommendations](1.Engine-usage-recommendations.md)
- [Content-packs](2.Content-packs.md)
- [Block properties](3.Block-properties.md)
- [Item properties](4.Item-properties.md)
- [XML UI building](5.XML-UI-building.md)
- [Assets preloading](6.Assets-preloading.md)
- [Audio](7.Audio.md)
- [Scripting](8.Scripting.md)
- [Block modoels](9.Block-models.md)

View File

@ -1,4 +1,5 @@
# Block properties # Block properties
## Visual ## Visual
### *texture* ### *texture*
@ -128,3 +129,8 @@ Examples for block `containermod:container`:
Number of block inventory slots. Default - 0 (no inventory). Number of block inventory slots. Default - 0 (no inventory).
## Extended blocks
### *size*
Array of three integers. Default value is `[1, 1, 1]`.

109
doc/en/console.md Normal file
View File

@ -0,0 +1,109 @@
# Console
To work with the command interpreter, use the **console** library.
## Commands creation
To create a console command, use the following function:
```python
console.add_command(scheme: str, executor: function)
```
Scheme has the following syntax:
```
name positional arguments {keyword arguments}
```
Name may contain:
- latin letters
- digits (except the first character)
- `.`, `_`, `-`
Positional arguments are separated by spaces and have the following syntax:
```
name:type (option 1)
name:type=default (option 2)
name:type~origin (option 3)
name:type=default~origin (option 4)
```
Available types:
- **int** - integer
- **num** - floating-point number
- **str** - string
- **sel** - selector (object id represented by an integer)
- **enum** - enumeration
Options 3 and 4 show the `~` operator that allows you to use relative values. *Origin* - the value relative to which the user will be specified. For example, the player's position.
The relative operator only works with numbers (num or int)
Variables assigned via **console.set** can be specified as origin values.
Example:
```python
x:num~pos.x
```
Variables may be specified as default values using the `$` prefix:
```python
t:int=$time
```
Enumerations are declared the following way:
```python
mode:[replace|destruct|none]
```
Or with a variable:
```python
mode:enum $modes
```
Selectors are specified with the `@` prefix. At the moment they are unused due to the lack of an object model. Should be made optional and use variables:
```python
obj:sel=$obj.id # obj.id - player id
```
Keyword arguments are specified in a special block, delimited by curly braces `{ }`, following the same pattern as positional arguments.
Example:
```python
eval name:str="World" {greeting:str='Hello'}
```
## Command scheme examples
Schemes of standard commands can be found in the file `res/script/stdcmd.lua`.
Example - command **tp**:
```python
tp obj:sel=$obj.id x:num~pos.x y:num~pos.y z:num~pos.z
```
Full lua code of the command creation:
```lua
console.add_command(
"tp obj:sel=$obj.id x:num~pos.x y:num~pos.y z:num~pos.z",
"Teleport object",
function (args, kwargs)
player.set_pos(unpack(args))
end
)
```
- Checked values of positional arguments are passed to **args**.
- A table of keyword argument values is passed to **kwargs**.
The command interpreter performs type checking and casting automatically.

14
doc/en/main-page.md Normal file
View File

@ -0,0 +1,14 @@
# Documentation
## Sections
- [Engine usage recommendations](engine-use-recommendations.md)
- [Content-packs](content-packs.md)
- [Block properties](block-properties.md)
- [Item properties](item-properties.md)
- [XML UI building](xml-ui-layouts.md)
- [Assets preloading](assets-preload.md)
- [Audio](audio.md)
- [Scripting](scripting.md)
- [Console](console.md)
- [Block models](block-models.md)

View File

@ -2,15 +2,20 @@
Project uses LuaJIT as a scripting language. Project uses LuaJIT as a scripting language.
Subsections:
- [Engine events](scripting/events.md)
- [User input](scripting/user-input.md)
- [Filesystem and serialization](scripting/filesystem.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)
## Core functions ## Core functions
```lua ```lua
require "packid:module_name" -- load Lua module from pack-folder/modules/ require "packid:module_name" -- load Lua module from pack-folder/modules/
-- no extension included, just name -- no extension included, just name
-- deprecated functions
load_script("packid:scripts/script_name.lua") -- load Lua script if not loaded yet
load_script("packid:scripts/script_name.lua", true) -- load Lua script anyway
``` ```
## *pack* library ## *pack* library
@ -39,10 +44,10 @@ For pack *containermod* will write text to the file `world:data/containermod/exa
## *player* library ## *player* library
```python ```python
player.get_pos(playerid: int) -> number, number, number player.get_pos(playerid: int) -> number, number, number
``` ```
Returns x, y, z coordinates of the player Returns x, y, z coordinates of the player
```python ```python
@ -83,8 +88,25 @@ player.set_noclip(bool)
Getter and setter for player noclip mode (collisions disabled) Getter and setter for player noclip mode (collisions disabled)
```python
player.get_selected_block(playerid: int) -> x,y,z
```
Returns position of the selected block or nil
## *world* library ## *world* library
## Библиотека *world*
```python
world.get_list() -> tables array {
name: str,
icon: str
}
```
Retuns worlds information: name and preview/icon (loading automatically).
```python ```python
world.get_day_time() -> number world.get_day_time() -> number
``` ```
@ -109,29 +131,67 @@ world.get_seed() -> int
Returns world seed. Returns world seed.
```python
world.exists() -> bool
```
Checks the existence of a world by name.
## *pack* library ## *pack* library
```python ```python
pack.get_folder(packid: str) -> str pack.get_folder(packid: str) -> str
``` ```
Returns installed content-pack folder Returns installed content-pack folder.
```python ```python
pack.is_installed(packid: str) -> bool pack.is_installed(packid: str) -> bool
``` ```
Check if the world has specified pack installed Check if the world has specified pack installed.
```python ```python
pack.get_installed() -> array of strings pack.get_installed() -> strings array
``` ```
Returns all installed content-pack ids Returns all installed content-pack ids.
```python
pack.get_available() -> strings array
```
Returns the ids of all content packs available but not installed in the world.
```python
pack.get_base_packs() -> strings array
```
Returns the id of all base packages (non-removeable)
```python
pack.get_info(packid: str) -> {
id: str,
title: str,
creator: str,
description: str,
version: str,
icon: str,
dependencies: optional strings array
}
```
Returns information about the pack (not necessarily installed).
- icon - name of the preview texture (loading automatically)
- dependencies - strings following format `{lvl}{id}`, where lvl:
- `!` - required
- `?` - optional
- `~` - weak
for example `!teal`
## *gui* library ## *gui* library
Library contains ui elements access functions. Library should not be directly used, because script *layouts/layout_name.xml.lua* already has a generated variable **document** (instance of **Document**) The library contains functions for accessing the properties of UI elements. Instead of gui, you should use an object wrapper that provides access to properties through the __index, __newindex meta methods:
Example: Example:
@ -140,7 +200,35 @@ print(document.some_button.text) -- where 'some_button' is an element id
document.some_button.text = "new text" document.some_button.text = "new text"
``` ```
## **inventory** library ```python
gui.str(text: str, context: str) -> str
```
Returns translated text.
```python
gui.get_viewport() -> {int, int}
```
Returns size of the main container (window).
```python
gui.get_env(document: str) -> table
```
Returns environment (global variables table) of the specified document.
```python
get_locales_info() -> table of tables where
key - locale id following isolangcode_ISOCOUNTRYCODE format
value - table {
name: str # name of the locale in its language
}
```
Returns information about all loaded locales (res/texts/\*).
## *inventory* library
Library for inventories interaction. Library for inventories interaction.
@ -208,13 +296,25 @@ If slotB will be chosen automaticly if argument is not specified.
block.name(blockid: int) -> str block.name(blockid: int) -> str
``` ```
Returns block string ID (name) by index Returns block string ID (name) by index.
```python ```python
block.index(name: str) -> int block.index(name: str) -> int
``` ```
Returns block integer ID (index) by name Returns block integer ID (index) by name.
```python
block.material(blockid: int) -> str
```
Returns the id of the block material.
```python
block.caption(blockid: int) -> str
```
Returns the block name displayed in the interface.
```python ```python
block.get(x: int, y: int, z: int) -> int block.get(x: int, y: int, z: int) -> int
@ -291,6 +391,35 @@ block.set_rotation(x: int, y: int, z: int, rotation: int)
Set block rotation by index. Set block rotation by index.
### Extended blocks
Extended blocks are blocks with size greather than 1x1x1
```python
block.is_extended(id: int) -> bool
```
Checks whether the block is extended.
```python
block.get_size(id: int) -> int, int, int
```
Returns the block size.
```python
block.is_segment(x: int, y: int, z: int) -> bool
```
Checks whether the block is a non-origin segment of an extended block.
```python
block.seek_origin(x: int, y: int, z: int) -> int, int, int
```
Returns the position of the main segment of an extended block or the original position,
if the block is not extended.
### User bits ### User bits
Part of a voxel data used for scripting. Size: 8 bit. Part of a voxel data used for scripting. Size: 8 bit.
@ -308,7 +437,6 @@ Set specified bits.
## *item* library ## *item* library
```python ```python
item.name(itemid: int) -> str item.name(itemid: int) -> str
``` ```
@ -383,207 +511,27 @@ Remove an element from the screen
hud.get_block_inventory() -> int hud.get_block_inventory() -> int
``` ```
Get open block inventory ID or 0 Get open block inventory ID or 0.
## Block events
```lua
function on_placed(x, y, z, playerid)
```
Called on block placed by player
```lua
function on_broken(x, y, z, playerid)
```
Called on block broken by player
```lua
function on_interact(x, y, z, playerid) -> bool
```
Called on block RMB click interaction. Prevents block placing if **true** returned.
```lua
function on_update(x, y, z)
```
Called on block update (near block changed)
```lua
function on_random_update(x, y, z)
```
Called on random block update (grass growth)
```lua
function on_blocks_tick(tps: int)
```
Called tps (20) times per second.
## Item events
```lua
function on_use(playerid: int)
```
Called on RMB click out of a block.
```lua
function on_use_on_block(x: int, y: int, z: int, playerid: int)
```
Called on block RMB click. Prevents block **placing-block** placing if returns **true**
```lua
function on_block_break_by(x: int, y: int, z: int, playerid: int)
```
Called on block LMB click (unbreakable blocks included). Prevents block destruction if returns **true**.
## World events
Script *scripts/world.lua* events.
```lua
function on_world_open()
```
Called on world open.
```lua
function on_world_save()
```
Called before world save.
```lua
function on_world_tick()
```
Called 20 times per second
```lua
function on_world_quit()
```
Called on world close (after saving)
## Layout events
Script *layouts/layout_name.xml.lua* events.
```lua
function on_open(invid: int, x: int, y: int, z: int)
```
Called on element added to the screen.
invid=0 if no inventory bound
x,y,z=0 if no block bound
```lua
function on_close(invid: int)
```
Called on element removed from the screen.
## HUD events
Script *scripts/hud.lua* events.
```lua
function on_hud_open(playerid: int)
```
Called after world open.
```lua
function on_hud_close(playerid: int)
```
Called on world close (before saving)
## Engine libraries
### file
Filesystem interaction library.
```python ```python
file.resolve(path: str) -> str hud.get_player() -> int
``` ```
Function turns *entry_point:path* (example *user:worlds/house1*) to a regular path. (example *C://Users/user/.voxeng/worlds/house1*) Gives the ID of the player that the UI is bound to.
> [!NOTE]
> The function should be used for debug only. *entry_point:path* notation is required in all **file** functions.
Resulting path is not canonical and may be relative.
```python ```python
file.read(path: str) -> str hud.pause()
``` ```
Read whole text file. Opens the pause menu
```python ```python
file.read_bytes(path: str) -> array of integers hud.resume()
``` ```
Read file into bytes array. Closes the pause menu.
```python ### *time* library
file.write(path: str, text: str) -> nil
```
Overwrite text file.
```python
file.write_bytes(path: str, data: array of integers)
```
Overwrite binary file with bytes array.
```python
file.length(path: str) -> int
```
Get file length (bytes) or 0.
```python
file.exists(path: str) -> bool
```
Check if file or directory exist.
```python
file.isfile(path: str) -> bool
```
Check if the path points to a file.
```python
file.isdir(path: str) -> bool
```
Check if the path points to a directory.
```python
file.mkdir(path: str) -> bool
```
Create directory. Returns true if new directory created
```python
file.mkdirs(path: str) -> bool
```
Create directories chain. Returns true if new directory created
### time
```python ```python
time.uptime() -> float time.uptime() -> float
@ -591,24 +539,8 @@ time.uptime() -> float
Returns time elapsed since the engine started. Returns time elapsed since the engine started.
## Available modules ```python
time.delta() -> float
### TOML serialization/deserialization
```lua
local toml = require "core:toml"
local t = {a=53, b=42, s="test", sub={x=1, y=6}}
local s = toml.serialize(t)
print(s)
local t2 = toml.deserialize(s)
```
output:
```toml
b = 42
s = "test"
a = 53
[sub]
y = 6
x = 1
``` ```
Returns time elapsed since the last frame.

126
doc/en/scripting/events.md Normal file
View File

@ -0,0 +1,126 @@
# Engine events
## Block events
Callbacks specified in block script.
```lua
function on_placed(x, y, z, playerid)
```
Called on block placed by player
```lua
function on_broken(x, y, z, playerid)
```
Called on block broken by player
```lua
function on_interact(x, y, z, playerid) -> bool
```
Called on block RMB click interaction. Prevents block placing if **true** returned.
```lua
function on_update(x, y, z)
```
Called on block update (near block changed)
```lua
function on_random_update(x, y, z)
```
Called on random block update (grass growth)
```lua
function on_blocks_tick(tps: int)
```
Called tps (20) times per second.
## Item events
Callbacks specified in item script.
```lua
function on_use(playerid: int)
```
Called on RMB click out of a block.
```lua
function on_use_on_block(x: int, y: int, z: int, playerid: int)
```
Called on block RMB click. Prevents block **placing-block** placing if returns **true**
```lua
function on_block_break_by(x: int, y: int, z: int, playerid: int)
```
Called on block LMB click (unbreakable blocks included). Prevents block destruction if returns **true**.
## World events
Callbacks specified in *world.lua* script.
```lua
function on_world_open()
```
Called on world open.
```lua
function on_world_save()
```
Called before world save.
```lua
function on_world_tick()
```
Called 20 times per second
```lua
function on_world_quit()
```
Called on world close (after saving)
## Layout events
Script *layouts/layout_name.xml.lua* events.
```lua
function on_open(invid: int, x: int, y: int, z: int)
```
Called on element added to the screen.
invid=0 if no inventory bound
x,y,z=0 if no block bound
```lua
function on_close(invid: int)
```
Called on element removed from the screen.
## HUD events
Callbacks specified in *hud.lua* script.
```lua
function on_hud_open(playerid: int)
```
Called after world open.
```lua
function on_hud_close(playerid: int)
```
Called on world close (before saving)

View File

@ -0,0 +1,89 @@
# Filesystem and serialization
### *file* library
Filesystem interaction library.
```python
file.resolve(path: str) -> str
```
Function turns `entry_point:path` (example `user:worlds/house1`) to a regular path. (example `C://Users/user/.voxeng/worlds/house1`)
> [!NOTE]
> The function should be used for debug only. *entry_point:path* notation is required in all **file** functions.
Resulting path is not canonical and may be relative.
```python
file.read(path: str) -> str
```
Read whole text file.
```python
file.read_bytes(path: str) -> array of integers
```
Read file into bytes array.
```python
file.write(path: str, text: str) -> nil
```
Overwrite text file.
```python
file.write_bytes(path: str, data: array of integers)
```
Overwrite binary file with bytes array.
```python
file.length(path: str) -> int
```
Get file length (bytes) or 0.
```python
file.exists(path: str) -> bool
```
Check if file or directory exist.
```python
file.isfile(path: str) -> bool
```
Check if the path points to a file.
```python
file.isdir(path: str) -> bool
```
Check if the path points to a directory.
```python
file.mkdir(path: str) -> bool
```
Create directory. Returns true if new directory created
```python
file.mkdirs(path: str) -> bool
```
Create directories chain. Returns true if new directory created.
## Storing data in a world
When saving pack data in the world, you should use the function:
```python
pack.data_file(packid: str, filename: str) -> str
```
Returns data file path like: `world:data/packid/filename`
and creates missing directories.
If paths other than `data/{packid}/...` are used, data may be lost.

View File

@ -0,0 +1,93 @@
# Module core:bit_converter
## Converting values to bytes and back
```lua
function bit_converter.string_to_bytes(string: str) -> table
```
Converts a string to bytes
```lua
function bit_converter.bool_to_byte(boolean: bool) -> integer
```
Converts a boolean to a byte
```lua
function bit_converter.single_to_bytes(number: single) -> table
```
Converts a single precision float value to bytes
```lua
function bit_converter.double_to_bytes(number: double) -> table
```
Converts a double precision float value to bytes
```lua
function bit_converter.uint16_to_bytes(integer: int) -> table
```
Converts an unsigned 2-bytes integer to bytes
```lua
function bit_converter.uint32_to_bytes(integer: int) -> table
```
Converts an unsigned 4-bytes integer to bytes
```lua
function bit_converter.int16_to_bytes(integer: int) -> table
```
Converts a signed 2-bytes integer to bytes
```lua
function bit_converter.int32_to_bytes(integer: int) -> table
```
Converts a signed 4-bytes integer to bytes
```lua
function bit_converter.int64_to_bytes(integer: int) -> table
```
Converts a signed 8-bytes integer to bytes
```lua
function bit_converter.bytes_to_string(table: bytes) -> string
```
Converts a byte array to a string
```lua
function bit_converter.byte_to_bool(integer: byte) -> boolean
```
Converts a byte to a boolean value
```lua
function bit_converter.bytes_to_single(table: bytes) -> number№
```
Converts a byte array to a single-precision float
```lua
function bit_converter.bytes_to_double(table: bytes) -> number
```
Converts a byte array to a double precision float
```lua
function bit_converter.bytes_to_uint16(table: bytes) -> integer
```
Converts a byte array to a 2-bytes unsigned number
```lua
function bit_converter.bytes_to_uint32(table: bytes) -> integer
```
Converts a byte array to a 4-bytes unsigned number
```lua
function bit_converter.bytes_to_int16(table: bytes) -> integer
```
Converts a byte array to a 2-bytes signed number
```lua
function bit_converter.bytes_to_int32(table: bytes) -> integer
```
Converts a byte array to a 4-bytes signed number
```lua
function bit_converter.bytes_to_int64(table: bytes) -> integer
```
Converts a byte array to an 8-bytes signed number

View File

@ -0,0 +1,155 @@
# Module core:data_buffer
## Data buffer
### Stores an array of bytes and allows you to easily get or add different values
```lua
function data_buffer(bytes)
```
Creates a new data_buffer instance (the bytes parameter is optional)
```lua
function data_buffer:put_byte(integer: byte)
```
Writes a byte to the buffer
```lua
function data_buffer:put_bytes(table: bytes)
```
Writes bytes to the buffer
```lua
function data_buffer:put_string(string: str)
```
Converts a string to bytes and writes them to the buffer
```lua
function data_buffer:put_bool(boolean: bool)
```
Converts a boolean value to a byte and writes it to the buffer
```lua
function data_buffer:put_single(number: single)
```
Converts a single precision float to bytes and writes them to the buffer
```lua
function data_buffer:put_double(number: double)
```
Converts a double precision float to bytes and writes them to the buffer
```lua
function data_buffer:put_uint16(integer: int)
```
Converts an unsigned 2-bytes number to bytes and writes them to the buffer
```lua
function data_buffer:put_uint32(integer: int)
```
Converts an unsigned 4-bytes number to bytes and writes them to the buffer
```lua
function data_buffer:put_int16(integer: int)
```
Converts a signed 2-bytes number into bytes and writes them to the buffer
```lua
function data_buffer:put_int32(integer: int)
```
Converts a signed 4-bytes number into bytes and writes them to the buffer
```lua
function data_buffer:put_int64(integer: int)
```
Converts a signed 8-bytes number to bytes and writes them to the buffer
```lua
function data_buffer:put_number(number: num)
```
Converts any number into bytes and writes them to the buffer;
The first byte is the value type:
```lua
zero = 0
uint16 = 1
uint32 = 2
int16 = 3
int32 = 4
int64 = 5
double = 6
```
```lua
function data_buffer:get_byte() -> integer
```
Returns the next byte from the buffer
```lua
function data_buffer:get_bytes(n) -> table
```
Returns the next n bytes, if n is nil or not specified, then an array of all bytes is returned
```lua
function data_buffer:get_string() -> string
```
Reads the next line from the buffer
```lua
function data_buffer:get_bool() -> boolean
```
Reads the next Boolean from the buffer
```lua
function data_buffer:get_single() -> number
```
Reads the next single precision floating number from the buffer
```lua
function data_buffer:get_double() -> number
```
Reads the next double precision floating number from the buffer
```lua
function data_buffer:get_uint16() -> integer
```
Reads the next 2-bytes unsigned integer from the buffer
```lua
function data_buffer:get_uint32() -> integer
```
Reads the next 4-bytes unsigned integer from the buffer
```lua
function data_buffer:get_int16() -> integer
```
Reads the next 2-bytes signed integer from the buffer
```lua
function data_buffer:get_int32() -> integer
```
Reads the next 4-bytes signed integer from the buffer
```lua
function data_buffer:get_int64() -> integer
```
Reads the next 8-bytes signed integer from the buffer
```lua
function data_buffer:get_number() -> number
```
Reads the next number (see data_buffer:put_number)
```lua
function data_buffer:size() -> integer
```
Returns the buffer size
```lua
function data_buffer:set_position(integer: pos)
```
Sets the current position in the buffer
```lua
function data_buffer:set_bytes(table: bytes)
```
Sets bytes into the buffer

View File

@ -0,0 +1,191 @@
# Modules core:vector2, core:vector3
## Vector2
### Operations on vectors
```lua
function vector2:round(decimals: number) -> round[vec2]
```
Rounding vector components
```lua
function vector2:len() -> number
```
Vector length
```lua
function vector2:norm() -> number
```
Vector normalization
```lua
function vector2:abtw(vector: vec2) -> number
```
Angle between two vectors in radians
```lua
function vector2:proj(vector: vec2) -> vec2
```
Vector projection
```lua
function vector2:dot(vector: vec2) -> number
```
Vector (internal) product
```lua
function vector2:lerp(
--Target vector
b:vec2,
--Interpolation coefficient (0 to 1)
t:number
) -> vec2
```
Linear vector interpolation
```lua
function vector2:dist(vector: vec2) -> number
```
Distance between two vectors
```lua
function vector2:cross(vector: vec2) -> number
```
Vector (external) product
```lua
function vector2:rot(
--The angle of rotation of the vector at a given angle (in radians)
angle: number->rad,
--Rotation of the vector relative to the axes ("x", "y", "z")
axis: str,
--If true, then the rotation angle is converted automatically from degrees to radians
convert2deg:bool
) -> vec2
```
Rotate a vector
### Operations with vectors
```lua
local vec2 = require("core:vector2")
local v1 = vec2(5, 10)
local v2 = vec2(10, 15)
-- vec2 .. vec2
sum_vectors = v1 + v2 -- (15, 25)
sub_vectors = v1 - v2 -- (-5, -5)
mul_vectors = v1 * v2 -- (50, 150)
div_vectors = v1 / v2 -- (0.5, 0.66667.)
pow_vectors = v1 ^ v2 -- (9765625, 1e+15)
--vec2 .. scalar
sum_vec2_scalar = v1 + 10 -- (15, 25)
sub_vec2_scalar = v1 - 12 -- (-7, -2)
mul_vec2_scalar = v1 * 20 -- (100, 200)
div_vec2_scalar = v1 / 1 -- (5, 10)
pow_vec2_scalar= v1 ^ 2 -- (25, 100)
```
## Vector3
### Operations on vectors
```lua
function vector3:round(decimals: number) -> round[vec3]
```
Rounding vector components
```lua
function vector3:len() -> number
```
Vector length
```lua
function vector3:norm() -> number
```
Vector normalization
```lua
function vector3:abtw(vector: vec3) -> number
```
Angle between two vectors in radians
```lua
function vector3:isParallel(vector: vec3) -> bool
```
Parallelism of a vector to another vector
```lua
function vector3:proj(vector: vec3) -> vec3
```
Vector projection
...
```lua
function vector3:dot(vector: vec3) -> number
```
Vector (internal) product
```lua
function vector3:lerp(
--Target vector
b:vec3,
--Interpolation coefficient (0 to 1)
t:number
) -> vec3
```
Linear vector interpolation
```lua
function vector3:dist(vector: vec3) -> number
```
Distance between two vectors
```lua
function vector3:dist2line(point1: vec3, point2: vec3) -> number
```
Distance to line
```lua
function vector3:cross(vector: vec3) -> number
```
Vector (external) product
```lua
function vector3:rot(
--The angle of rotation of the vector at a given angle (in radians)
angle: number->rad,
--Rotation of the vector relative to the axes ("x", "y", "z")
axis: str,
--If true, then the rotation angle is converted automatically from degrees to radians
convert2deg:bool
) -> vec2
```
Rotate a vector
### Operations with vectors
```lua
local vec3 = require("core:vector3")
local v1 = vec3(1, 2, 3)
local v2 = vec3(4, 5, 6)
--vec3..vec3
local sum_vectors = v1 + v2 -- (5, 7, 9)
local sub_vectors = v1 - v2 -- (-3, -3, -3)
local mul_vectors = v1 * v2 -- (4, 10, 18)
local div_vectors = v1 / v2 -- (0.25, 0.4, 0.5)
local pow_vectors = v1 ^ v2 -- (1, 32, 216)
--vec3..scalar
local scalar_vector = v1 * 2 -- (2, 4, 6)
local scalar_number = 2 * v1 -- (2, 4, 6)
-- ..etc
```

View File

@ -0,0 +1,61 @@
# User input
User input is performed with *bindings* defined with `config/bindings.toml`.
Example:
```toml
packid.binding.name="inputtype:codename"
```
- packid - optional (recommended)
- inputtype - key or mouse
- codename - key or mouse button code (left/right/middle)
## Key names
- space, backspace, tab, enter, caps-lock, escape
- left-ctrl, left-shift, left-alt, left-super
- right-ctrl, right-shift, right-alt, right-super
- delete, home, end, insert, page-up, page-down
- left, right, down, up
- a..z
- 0..9
- f1..f25
## *input* library
```python
input.keycode(keyname: str) -> int
```
Returns key code or -1 if unknown
```python
input.mousecode(mousename: str) -> int
```
Returns mouse button code or -1 if unknown
```python
input.add_callback(bindname: str, callback: function)
```
Add binding activation callback. Example:
```lua
input.add_callback("hud.inventory", function ()
print("Inventory open key pressed")
end)
```
```python
input.get_mouse_pos() -> {int, int}
```
Returns cursor screen position.
```python
input.get_bindings() -> strings array
```
Returns all binding names.

View File

@ -1,16 +0,0 @@
# Разделы
- [Рекомендации по использованию движка](1.Рекомендации-по-использованию-движка.md)
- [Контент‐паки](2.Контент‐паки.md)
- [Свойства блоков](3.Свойства-блоков.md)
- [Свойства предметов](4.Свойства-предметов.md)
- [XML разметка интерфейса](5.XML-разметка-интерфейса.md)
- [Предзагрузка ассетов](6.Предзагрузка-ассетов.md)
- [Аудио](7.Аудио.md)
- [Скриптинг](8.Скриптинг.md)
- [Модуль core:bit_converter](8.1.Модуль-Lua-core_bit_converter.md)
- [Модуль core:data_buffer](8.2.Модуль-Lua-core_data_buffer.md)
- [Пользовательский ввод](Пользовательский-ввод.md)
- [Файловая система и сериализация](Файловая-система-и-сериализация.md)
- [Консоль](Консоль.md)
- [Модели блоков](9.Модели-блоков.md)

View File

@ -1,12 +1,14 @@
# Вид # Свойства блоков
## Текстура - `texture` ## Вид
### Текстура - `texture`
Название текстуры блока (указывается только имя, без расширения или пути к файлу) Название текстуры блока (указывается только имя, без расширения или пути к файлу)
Файл текстуры должен находиться в `res/textures/blocks/` и иметь формат **png** Файл текстуры должен находиться в `res/textures/blocks/` и иметь формат **png**
## Текстурирование сторон - `texture-faces` ### Текстурирование сторон - `texture-faces`
>[!IMPORTANT] >[!IMPORTANT]
> Не может использоваться одновременно с `texture` > Не может использоваться одновременно с `texture`
@ -25,7 +27,7 @@
] ]
``` ```
## Модель - `model` ### Модель - `model`
Модель блока из списка: Модель блока из списка:
- "block" - используется по-умолчанию для всех обычных блоков - "block" - используется по-умолчанию для всех обычных блоков
@ -33,12 +35,12 @@
- "X" - модель травы (крест из двух спрайтов) - "X" - модель травы (крест из двух спрайтов)
- "aabb" - модель, соответствующая хитбоксу блока (составной хитбокс будет объединен в один). Примеры: трубы, лампочки, панели. - "aabb" - модель, соответствующая хитбоксу блока (составной хитбокс будет объединен в один). Примеры: трубы, лампочки, панели.
## Группа отрисовки - `draw-group` ### Группа отрисовки - `draw-group`
Целое число определяющее номер группы отрисовки данного блока. Целое число определяющее номер группы отрисовки данного блока.
Актуально для полупрозрачных блоков - решает проблемы невидимых сторон блоков за этим блоком. Актуально для полупрозрачных блоков - решает проблемы невидимых сторон блоков за этим блоком.
## Вращение - `rotation` ### Вращение - `rotation`
Профиль вращения (набор положений, в которые можно установить блок) из списка: Профиль вращения (набор положений, в которые можно установить блок) из списка:
@ -46,9 +48,9 @@
- "pipe" - профиль "труба". Примеры блоков: бревно, труба, лампочка - "pipe" - профиль "труба". Примеры блоков: бревно, труба, лампочка
- "pane" - профиль "панель". Примеры блоков: панель, дверь, табличка - "pane" - профиль "панель". Примеры блоков: панель, дверь, табличка
# Освещение ## Освещение
## Излучение - `emission` ### Излучение - `emission`
Массив из трех целых чисел - R, G, B освещения от 0 до 15. Массив из трех целых чисел - R, G, B освещения от 0 до 15.
@ -59,21 +61,21 @@
- `[0, 0, 0]` - блок не излучает свет (по-умолчанию) - `[0, 0, 0]` - блок не излучает свет (по-умолчанию)
## Светопроводимость - `light-passing` ### Светопроводимость - `light-passing`
При значении `true` блок проводит свет от излучающих блоков. При значении `true` блок проводит свет от излучающих блоков.
## Солнечная светопроводимость - `sky-light-passing` ### Солнечная светопроводимость - `sky-light-passing`
При значении `true` блок не препятствует прохождению вертикального луча солнечного света. При значении `true` блок не препятствует прохождению вертикального луча солнечного света.
# Физика ## Физика
## Препятствие - `obstacle`: ### Препятствие - `obstacle`:
Значение false отключает хитбокс у блока (позволяет игроку проходить сквозь блок) Значение false отключает хитбокс у блока (позволяет игроку проходить сквозь блок)
## Хитбокс - `hitbox`: ### Хитбокс - `hitbox`:
Массив из 6 чисел описывающих смещение и размер хитбокса блока. Массив из 6 чисел описывающих смещение и размер хитбокса блока.
@ -87,45 +89,50 @@
- смещен на 0.0 м вверх - смещен на 0.0 м вверх
- смещен на 0.5 м на север - смещен на 0.5 м на север
## Приземленность - `grounded` ### Приземленность - `grounded`
Блок может быть установлен только на полный блок. Блок может быть установлен только на полный блок.
Разрушается при разрушении блока под ним. Разрушается при разрушении блока под ним.
## Выделяемость - `selectable` ### Выделяемость - `selectable`
При значении в `false` курсор будет игнорировать блок, выделяя тот, что находится за ним. При значении в `false` курсор будет игнорировать блок, выделяя тот, что находится за ним.
## Заменяемость - `replaceable` ### Заменяемость - `replaceable`
При значении в `true` на месте блока можно установить любой другой блок. Пример: вода, трава, цветок. При значении в `true` на месте блока можно установить любой другой блок. Пример: вода, трава, цветок.
## Разрушаемость - `breakable` ### Разрушаемость - `breakable`
При значении в `false` блок нельзя сломать. При значении в `false` блок нельзя сломать.
# Инвентарь ## Инвентарь
## Скрытый блок - `hidden` ### Скрытый блок - `hidden`
При значении в `true` блок не появляется в инвентаре и для него не генерируется предмет, поэтому c 0.17 требуется указать свойство `picking-item` При значении в `true` блок не появляется в инвентаре и для него не генерируется предмет, поэтому c 0.17 требуется указать свойство `picking-item`
## Подбираемый предмет - `picking-item` ### Подбираемый предмет - `picking-item`
Предмет, который будет выбран при нажатии средней кнопкой мыши на блок. Предмет, который будет выбран при нажатии средней кнопкой мыши на блок.
Пример: блок `door:door_open` скрыт (hidden) поэтому указывается `picking-item: "door:door.item"` Пример: блок `door:door_open` скрыт (hidden) поэтому указывается `picking-item: "door:door.item"`
## Имя скрипта - `script-name` ### Имя скрипта - `script-name`
Позволяет указать название скрипта блока. Свойство обеспечивает возможность использования одного скрипта для нескольких блоков. Позволяет указать название скрипта блока. Свойство обеспечивает возможность использования одного скрипта для нескольких блоков.
Название указывается без `пак:scripts/` и расширения. Название указывается без `пак:scripts/` и расширения.
## Имя макета UI - `ui-layout` ### Имя макета UI - `ui-layout`
Позволяет указать id XML-макета интерфейса блока. По-умолчанию используется строковый id блока. Позволяет указать id XML-макета интерфейса блока. По-умолчанию используется строковый id блока.
## Размер инвентаря - `inventory-size` ### Размер инвентаря - `inventory-size`
Число слотов инвентаря блока. По-умолчанию - 0 (инвентарь отсутствует) Число слотов инвентаря блока. По-умолчанию - 0 (инвентарь отсутствует)
## Расширенные блоки
### Размер блока - `size`
Массив из трех целых чисел. Значение по-умолчанию - `[1, 1, 1]`.

View File

@ -1,6 +1,6 @@
# Консоль # Консоль
Для работы с командным интерпретатором предоставляется библиотека **console** Для работы с командным интерпретатором предоставляется библиотека **console**.
## Создание команд ## Создание команд
@ -83,7 +83,7 @@ eval name:str="World" {greeting:str='Hello'}
## Примеры схем команд ## Примеры схем команд
Схемы существующих команд можно найти в файле `res/script/stdcmd.lua`. Схемы стандартных команд можно найти в файле `res/script/stdcmd.lua`.
Пример - команда **tp**: Пример - команда **tp**:

14
doc/ru/main-page.md Normal file
View File

@ -0,0 +1,14 @@
# Документация
## Разделы
- [Рекомендации по использованию движка](engine-use-recommendations.md)
- [Контент‐паки](content-packs.md)
- [Свойства блоков](block-properties.md)
- [Свойства предметов](item-properties.md)
- [XML разметка интерфейса](xml-ui-layouts.md)
- [Предзагрузка ассетов](assets-preload.md)
- [Аудио](audio.md)
- [Скриптинг](scripting.md)
- [Консоль](console.md)
- [Модели блоков](block-models.md)

View File

@ -2,11 +2,20 @@
В качестве языка сценариев используется LuaJIT В качестве языка сценариев используется LuaJIT
Подразделы:
- [События движка](scripting/events.md)
- [Пользовательский ввод](scripting/user-input.md)
- [Файловая система и сериализация](scripting/filesystem.md)
- [Модуль core:bit_converter](scripting/modules/core_bit_converter.md)
- [Модуль core:data_buffer](scripting/modules/core_data_buffer.md)
- [Модули core:vector2, core:vector3](scripting/modules/core_vector2_vector3.md)
```lua ```lua
require "контентпак:имя_модуля" -- загружает lua модуль из папки modules (расширение не указывается) require "контентпак:имя_модуля" -- загружает lua модуль из папки modules (расширение не указывается)
``` ```
## Библиотека pack ## Библиотека *pack*
```python ```python
pack.is_installed(packid: str) -> bool pack.is_installed(packid: str) -> bool
@ -29,10 +38,12 @@ file.write(pack.data_file(PACK_ID, "example.txt"), text)
``` ```
Для пака *containermod* запишет текст в файл `world:data/containermod/example.txt` Для пака *containermod* запишет текст в файл `world:data/containermod/example.txt`
## Библиотека player ## Библиотека *player*
```python ```python
player.get_pos(playerid: int) -> number, number, number player.get_pos(playerid: int) -> number, number, number
``` ```
Возвращает x, y, z координаты игрока Возвращает x, y, z координаты игрока
```python ```python
@ -79,7 +90,7 @@ player.get_selected_block(playerid: int) -> x,y,z
Возвращает координаты выделенного блока, либо nil Возвращает координаты выделенного блока, либо nil
## Библиотека world ## Библиотека *world*
```python ```python
world.get_list() -> массив таблиц { world.get_list() -> массив таблиц {
@ -120,13 +131,13 @@ world.exists() -> bool
Проверяет существование мира по имени. Проверяет существование мира по имени.
## Библиотека pack ## Библиотека *pack*
```python ```python
pack.get_folder(packid: str) -> str pack.get_folder(packid: str) -> str
``` ```
Возвращает путь к папке установленного контент-пака Возвращает путь к папке установленного контент-пака.
```python ```python
pack.is_installed(packid: str) -> bool pack.is_installed(packid: str) -> bool
@ -138,13 +149,13 @@ pack.is_installed(packid: str) -> bool
pack.get_installed() -> массив строк pack.get_installed() -> массив строк
``` ```
Возращает id всех установленных в мире контент-паков Возращает id всех установленных в мире контент-паков.
```python ```python
pack.get_available() -> массив строк pack.get_available() -> массив строк
``` ```
Возвращает id всех доступных, но не установленных в мире контент-паков Возвращает id всех доступных, но не установленных в мире контент-паков.
```python ```python
pack.get_base_packs() -> массив строк pack.get_base_packs() -> массив строк
@ -172,13 +183,13 @@ pack.get_info(packid: str) -> {
- `~` - weak - `~` - weak
например `!teal` например `!teal`
## Библиотека gui ## Библиотека *gui*
Библиотека содержит функции для доступа к свойствам UI элементов. Вместо gui следует использовать объектную обертку, предоставляющую доступ к свойствам через мета-методы __index, __newindex: Библиотека содержит функции для доступа к свойствам UI элементов. Вместо gui следует использовать объектную обертку, предоставляющую доступ к свойствам через мета-методы __index, __newindex:
```lua ```lua
local inventory_doc = Document.new("id-макета") print(document.some_button.text) -- где 'some_button' - id элемета
print(inventory_doc.some_button.text) document.some_button.text = "новый текст"
indentory_doc.some_button.text = "new text"
``` ```
В скрипте макета `layouts/файл_макета.xml` - `layouts/файл_макета.xml.lua` уже доступна переменная **document** содержащая объект класса Document В скрипте макета `layouts/файл_макета.xml` - `layouts/файл_макета.xml.lua` уже доступна переменная **document** содержащая объект класса Document
@ -210,7 +221,8 @@ get_locales_info() -> таблица таблиц где
``` ```
Возвращает информацию о всех загруженных локалях (res/texts/\*). Возвращает информацию о всех загруженных локалях (res/texts/\*).
## Библиотека inventory
## Библиотека *inventory*
Библиотека функций для работы с инвентарем. Библиотека функций для работы с инвентарем.
@ -273,19 +285,19 @@ inventory.move(invA: int, slotA: int, invB: int, slotB: int)
invA и invB могут указывать на один инвентарь. invA и invB могут указывать на один инвентарь.
slotB будет выбран автоматически, если не указывать явно. slotB будет выбран автоматически, если не указывать явно.
## Библиотека block ## Библиотека *block*
```python ```python
block.name(blockid: int) -> str block.name(blockid: int) -> str
``` ```
Возвращает строковый id блока по его числовому id Возвращает строковый id блока по его числовому id.
```python ```python
block.index(name: str) -> int block.index(name: str) -> int
``` ```
Возвращает числовой id блока, принимая в качестве агрумента строковый Возвращает числовой id блока, принимая в качестве агрумента строковый.
```python ```python
block.material(blockid: int) -> str block.material(blockid: int) -> str
@ -373,6 +385,35 @@ block.set_rotation(x: int, y: int, z: int, rotation: int)
Устанавливает вращение блока по индексу в его профиле вращения. Устанавливает вращение блока по индексу в его профиле вращения.
### Расширенные блоки
Расширенные блоки - те, размер которых превышает 1x1x1
```python
block.is_extended(id: int) -> bool
```
Проверяет, является ли блок расширенным.
```python
block.get_size(id: int) -> int, int, int
```
Возвращает размер блока.
```python
block.is_segment(x: int, y: int, z: int) -> bool
```
Проверяет является ли блок сегментом расширенного блока, не являющимся главным.
```python
block.seek_origin(x: int, y: int, z: int) -> int, int, int
```
Возвращает позицию главного сегмента расширенного блока или исходную позицию,
если блок не являющийся расширенным.
### Пользовательские биты ### Пользовательские биты
Выделенная под использования в скриптах часть поля `voxel.states` хранящего доп-информацию о вокселе, такую как вращение блока. На данный момент выделенная часть составляет 8 бит. Выделенная под использования в скриптах часть поля `voxel.states` хранящего доп-информацию о вокселе, такую как вращение блока. На данный момент выделенная часть составляет 8 бит.
@ -455,25 +496,25 @@ hud.open_permanent(layoutid: str)
hud.close(layoutid: str) hud.close(layoutid: str)
``` ```
Удаляет элемент с экрана Удаляет элемент с экрана.
```python ```python
hud.get_block_inventory() -> int hud.get_block_inventory() -> int
``` ```
Дает ID инвентаря открытого блока или 0 Дает ID инвентаря открытого блока или 0.
```python ```python
hud.get_player() -> int hud.get_player() -> int
``` ```
Дает ID игрока, к которому привязан пользовательский интерфейс Дает ID игрока, к которому привязан пользовательский интерфейс.
```python ```python
hud.pause() hud.pause()
``` ```
Открывает меню паузы Открывает меню паузы.
```python ```python
hud.resume() hud.resume()
@ -487,7 +528,7 @@ hud.resume()
time.uptime() -> float time.uptime() -> float
``` ```
Возвращает время с момента запуска движка в секундах Возвращает время с момента запуска движка в секундах.
```python ```python
time.delta() -> float time.delta() -> float

View File

@ -1,3 +1,5 @@
# Файловая система и сериализация
## Библиотека *file* ## Библиотека *file*
Библиотека функций для работы с файлами Библиотека функций для работы с файлами
@ -127,11 +129,10 @@ toml.parse(code: str) -> table
При сохранении данных пака в мире следует использовать функцию При сохранении данных пака в мире следует использовать функцию
```python ```python
pack.data_file(packid: str, filename: str) -> str pack.data_file(id_пака: str, имя_файла: str) -> str
``` ```
Функция возвращает путь к файлу данных по типу: `world:data/packid/filename` Функция возвращает путь к файлу данных по типу: `world:data/id_пака/имя_файла`
и создает недостающие директории в пути. и создает недостающие директории в пути.
При использовании путей не соответствующим `data/{packid}/...` возможна потеря данных при перезаписи мира. При использовании путей не соответствующим `data/{packid}/...` возможна потеря данных при перезаписи мира.

View File

@ -1,3 +1,5 @@
# Модуль core:bit_converter
## Конвертация значений в байты и обратно ## Конвертация значений в байты и обратно
```lua ```lua
@ -23,27 +25,27 @@ function bit_converter.double_to_bytes(number: double) -> table
```lua ```lua
function bit_converter.uint16_to_bytes(integer: int) -> table function bit_converter.uint16_to_bytes(integer: int) -> table
``` ```
Конвертирует беззнаковое 2-х битное целое число в байты Конвертирует беззнаковое 2-х байтовое целое число в байты
```lua ```lua
function bit_converter.uint32_to_bytes(integer: int) -> table function bit_converter.uint32_to_bytes(integer: int) -> table
``` ```
Конвертирует беззнаковое 4-х битное целое число в байты Конвертирует беззнаковое 4-х байтовое целое число в байты
```lua ```lua
function bit_converter.int16_to_bytes(integer: int) -> table function bit_converter.int16_to_bytes(integer: int) -> table
``` ```
Конвертирует знаковое 2-х битное целое число в байты Конвертирует знаковое 2-х байтовое целое число в байты
```lua ```lua
function bit_converter.int32_to_bytes(integer: int) -> table function bit_converter.int32_to_bytes(integer: int) -> table
``` ```
Конвертирует знаковое 4-х битное целое число в байты Конвертирует знаковое 4-х байтовое целое число в байты
```lua ```lua
function bit_converter.int64_to_bytes(integer: int) -> table function bit_converter.int64_to_bytes(integer: int) -> table
``` ```
Конвертирует знаковое 8-и битное целое число в байты Конвертирует знаковое 8-и байтовое целое число в байты
```lua ```lua
function bit_converter.bytes_to_string(table: bytes) -> string function bit_converter.bytes_to_string(table: bytes) -> string
@ -68,24 +70,24 @@ function bit_converter.bytes_to_double(table: bytes) -> number
```lua ```lua
function bit_converter.bytes_to_uint16(table: bytes) -> integer function bit_converter.bytes_to_uint16(table: bytes) -> integer
``` ```
Конвертирует массив байтов в 2-х битное беззнаковое число Конвертирует массив байтов в 2-х байтовое беззнаковое число
```lua ```lua
function bit_converter.bytes_to_uint32(table: bytes) -> integer function bit_converter.bytes_to_uint32(table: bytes) -> integer
``` ```
Конвертирует массив байтов в 4-х битное беззнаковое число Конвертирует массив байтов в 4-х байтовое беззнаковое число
```lua ```lua
function bit_converter.bytes_to_int16(table: bytes) -> integer function bit_converter.bytes_to_int16(table: bytes) -> integer
``` ```
Конвертирует массив байтов в 2-х битное знаковое число Конвертирует массив байтов в 2-х байтовое знаковое число
```lua ```lua
function bit_converter.bytes_to_int32(table: bytes) -> integer function bit_converter.bytes_to_int32(table: bytes) -> integer
``` ```
Конвертирует массив байтов в 4-х битное знаковое число Конвертирует массив байтов в 4-х байтовое знаковое число
```lua ```lua
function bit_converter.bytes_to_int64(table: bytes) -> integer function bit_converter.bytes_to_int64(table: bytes) -> integer
``` ```
Конвертирует массив байтов в 8-х битное знаковое число Конвертирует массив байтов в 8-х байтовое знаковое число

View File

@ -1,3 +1,5 @@
# Модуль core:data_buffer
## Буффер данных ## Буффер данных
### Хранит в себе массив байтов и позволяет легко получать или добавлять разные значения ### Хранит в себе массив байтов и позволяет легко получать или добавлять разные значения
@ -39,27 +41,27 @@ function data_buffer:put_double(number: double)
```lua ```lua
function data_buffer:put_uint16(integer: int) function data_buffer:put_uint16(integer: int)
``` ```
Конвертирует беззнаковое 2-х битное число в байты и записывает их в буффер Конвертирует беззнаковое 2-х байтовое число в байты и записывает их в буффер
```lua ```lua
function data_buffer:put_uint32(integer: int) function data_buffer:put_uint32(integer: int)
``` ```
Конвертирует беззнаковое 4-х битное число в байты и записывает их в буффер Конвертирует беззнаковое 4-х байтовое число в байты и записывает их в буффер
```lua ```lua
function data_buffer:put_int16(integer: int) function data_buffer:put_int16(integer: int)
``` ```
Конвертирует знаковое 2-х битное число в байты и записывает их в буффер Конвертирует знаковое 2-х байтовое число в байты и записывает их в буффер
```lua ```lua
function data_buffer:put_int32(integer: int) function data_buffer:put_int32(integer: int)
``` ```
Конвертирует знаковое 4-х битное число в байты и записывает их в буффер Конвертирует знаковое 4-х байтовое число в байты и записывает их в буффер
```lua ```lua
function data_buffer:put_int64(integer: int) function data_buffer:put_int64(integer: int)
``` ```
Конвертирует знаковое 8-и битное число в байты и записывает их в буффер Конвертирует знаковое 8-и байтовое число в байты и записывает их в буффер
```lua ```lua
function data_buffer:put_number(number: num) function data_buffer:put_number(number: num)
@ -110,27 +112,27 @@ function data_buffer:get_double() -> number
```lua ```lua
function data_buffer:get_uint16() -> integer function data_buffer:get_uint16() -> integer
``` ```
Читает следующее 2-х битное беззнаковое целое число из буффера Читает следующее 2-х байтовое беззнаковое целое число из буффера
```lua ```lua
function data_buffer:get_uint32() -> integer function data_buffer:get_uint32() -> integer
``` ```
Читает следующее 4-х битное беззнаковое целое число из буффера Читает следующее 4-х байтовое беззнаковое целое число из буффера
```lua ```lua
function data_buffer:get_int16() -> integer function data_buffer:get_int16() -> integer
``` ```
Читает следующее 2-х битное знаковое целое число из буффера Читает следующее 2-х байтовое знаковое целое число из буффера
```lua ```lua
function data_buffer:get_int32() -> integer function data_buffer:get_int32() -> integer
``` ```
Читает следующее 4-х битное знаковое целое число из буффера Читает следующее 4-х байтовое знаковое целое число из буффера
```lua ```lua
function data_buffer:get_int64() -> integer function data_buffer:get_int64() -> integer
``` ```
Читает следующее 8-х битное знаковое целое число из буффера Читает следующее 8-х байтовое знаковое целое число из буффера
```lua ```lua
function data_buffer:get_number() -> number function data_buffer:get_number() -> number

View File

@ -1,4 +1,5 @@
# Вектора # Модули core:vector2, core:vector3
## Vector2 ## Vector2
### Операции над векторами ### Операции над векторами
@ -7,6 +8,7 @@
function vector2:round(decimals: number) -> round[vec2] function vector2:round(decimals: number) -> round[vec2]
``` ```
Округление компонентов вектора Округление компонентов вектора
```lua ```lua
function vector2:len() -> number function vector2:len() -> number
``` ```
@ -68,7 +70,7 @@ function vector2:rot(
### Операции с векторами ### Операции с векторами
```lua ```lua
local vec2 = require("res:vector2") local vec2 = require("core:vector2")
local v1 = vec2(5, 10) local v1 = vec2(5, 10)
local v2 = vec2(10, 15) local v2 = vec2(10, 15)
@ -170,7 +172,7 @@ function vector3:rot(
```lua ```lua
local vec3 = require("res:vector3") local vec3 = require("core:vector3")
local v1 = vec3(1, 2, 3) local v1 = vec3(1, 2, 3)
local v2 = vec3(4, 5, 6) local v2 = vec3(4, 5, 6)

View File

@ -2,8 +2,24 @@ in vec2 v_coord;
out vec4 f_color; out vec4 f_color;
uniform sampler2D u_texture0; uniform sampler2D u_texture0;
uniform ivec2 u_screenSize;
void main(){ // Vignette
f_color = texture(u_texture0, v_coord); vec4 apply_vignette(vec4 color) {
vec2 position = (gl_FragCoord.xy / u_screenSize) - vec2(0.5);
float dist = length(position);
float radius = 1.3;
float softness = 1.0;
float vignette = smoothstep(radius, radius - softness, dist);
color.rgb = color.rgb * vignette;
return color;
}
void main() {
f_color = texture(u_texture0, v_coord);
f_color = apply_vignette(f_color);
} }