This commit is contained in:
@clasher113 2024-06-13 16:59:09 +03:00
commit c88bbe7fcb
220 changed files with 3524 additions and 3112 deletions

View File

@ -2,7 +2,7 @@ name: C/C++ AppImage
on:
push:
branches: [ "main" ]
branches: [ "main", "release-**"]
pull_request:
branches: [ "main" ]
@ -24,8 +24,15 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install -y build-essential libglfw3-dev libglfw3 libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev cmake squashfs-tools
# fix luajit paths
sudo ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua5.1.a
sudo ln -s /usr/include/luajit-2.1 /usr/include/lua
# install EnTT
git clone https://github.com/skypjack/entt.git
cd entt/build
cmake -DCMAKE_BUILD_TYPE=Release ..
sudo make install
cd ../..
- name: configure
run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DVOXELENGINE_BUILD_APPDIR=1
- name: build

View File

@ -36,8 +36,15 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install libglfw3-dev libglfw3 libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev
# fix luajit paths
sudo ln -s /usr/lib/x86_64-linux-gnu/libluajit-5.1.a /usr/lib/x86_64-linux-gnu/liblua-5.1.a
sudo ln -s /usr/include/luajit-2.1 /usr/include/lua
# install EnTT
git clone https://github.com/skypjack/entt.git
cd entt/build
cmake -DCMAKE_BUILD_TYPE=Release ..
sudo make install
cd ../..
- name: Configure CMake
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only

View File

@ -17,7 +17,7 @@ jobs:
- name: Install dependencies from brew
run: |
brew install glfw3 glew libpng openal-soft luajit libvorbis
brew install glfw3 glew libpng openal-soft luajit libvorbis skypjack/entt/entt
- name: Install specific version of GLM
run: |
@ -48,4 +48,4 @@ jobs:
uses: actions/upload-artifact@v4
with:
name: VoxelEngineMacOs
path: VoxelEngineMacApp.dmg
path: VoxelEngineMacApp.dmg

2
.gitignore vendored
View File

@ -13,6 +13,8 @@ Debug/voxel_engine
/worlds/**/*
/settings.toml
/controls.json
/controls.toml
/latest.log
/.idea
.vscode

View File

@ -84,6 +84,9 @@ find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)
find_package(OpenAL REQUIRED)
find_package(ZLIB REQUIRED)
if (NOT APPLE)
find_package(EnTT REQUIRED)
endif()
if (WIN32)
if(VOXELENGINE_BUILD_WINDOWS_VCPKG)
@ -120,7 +123,6 @@ else()
set(LUA_LIBRARIES ${LUAJIT_LIBRARIES})
set(LUA_INCLUDE_DIR ${LUAJIT_INCLUDE_DIRS})
find_package(PNG REQUIRED)
find_package(Lua REQUIRED)
set(PNGLIB PNG::PNG)
set(VORBISLIB ${VORBIS_LDFLAGS})
endif()

View File

@ -29,6 +29,14 @@ cmake --build .
## Install libs:
#### Install EnTT
```sh
git clone https://github.com/skypjack/entt.git
cd entt/build
cmake -DCMAKE_BUILD_TYPE=Release ..
sudo make install
```
#### Debian-based distro:
```sh
sudo apt install libglfw3-dev libglfw3 libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev
@ -59,7 +67,7 @@ sudo pacman -S glfw-wayland glew glm libpng libvorbis openal luajit
#### macOS:
```
brew install glfw3 glew glm libpng libvorbis lua luajit openal-soft
brew install glfw3 glew glm libpng libvorbis lua luajit openal-soft skypjack/entt/entt
```
If homebrew for some reason could not install the necessary packages: ```lua luajit openal-soft```, then download, install and compile them manually (Lua, LuaJIT and OpenAL).

View File

@ -10,4 +10,7 @@
- [Скриптинг](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

@ -0,0 +1,5 @@
{
"steps-sound": "steps/carpet",
"place-sound": "blocks/carpet_place",
"break-sound": "blocks/carpet_break"
}

View File

@ -1,5 +1,5 @@
{
"steps-sound": "steps/wood",
"place-sound": "blocks/wood_place",
"steps-sound": "steps/glass",
"place-sound": "blocks/glass_place",
"break-sound": "blocks/glass_break"
}

View File

@ -0,0 +1,5 @@
{
"steps-sound": "steps/metal",
"place-sound": "blocks/metal_place",
"break-sound": "blocks/metal_break"
}

View File

@ -1,5 +1,5 @@
{
"steps-sound": "steps/sand",
"steps-sound": "blocks/ground_place",
"place-sound": "blocks/ground_place",
"break-sound": "blocks/ground_break"
}

View File

@ -1,4 +1,5 @@
{
"texture": "blue_lamp",
"emission": [0, 0, 15]
}
"emission": [0, 0, 15],
"material": "base:glass"
}

View File

@ -1,4 +1,5 @@
{
"texture": "green_lamp",
"emission": [0, 15, 0]
}
"emission": [0, 15, 0],
"material": "base:glass"
}

View File

@ -6,5 +6,6 @@
"hitbox": [0.25, 0.0, 0.25, 0.5, 0.5, 0.5],
"rotation": "pipe",
"light-passing": true,
"sky-light-passing": true
"sky-light-passing": true,
"material": "base:glass"
}

View File

@ -1,3 +1,4 @@
{
"texture": "metal"
}
"texture": "metal",
"material": "base:metal"
}

View File

@ -10,5 +10,6 @@
"model": "aabb",
"hitbox": [0.25, 0.0, 0.25, 0.5, 1.0, 0.5],
"light-passing": true,
"rotation": "pipe"
"rotation": "pipe",
"material": "base:metal"
}

View File

@ -1,4 +1,5 @@
{
"texture": "red_lamp",
"emission": [15, 0, 0]
}
"emission": [15, 0, 0],
"material": "base:glass"
}

View File

@ -1,3 +1,4 @@
{
"texture": "rust"
}
"texture": "rust",
"material": "base:metal"
}

View File

@ -0,0 +1,17 @@
{
"material": "base:wood",
"texture-faces": [
"wooden_door_side",
"wooden_door_side",
"wooden_door_top",
"wooden_door_top",
"wooden_door",
"wooden_door"
],
"light-passing": true,
"sky-light-passing": true,
"size": [1, 2, 1],
"rotation": "pane",
"model": "aabb",
"hitbox": [0.0, 0.0, 0.8, 1.0, 2.0, 0.2]
}

View File

@ -25,6 +25,7 @@
"pane",
"pipe",
"lightbulb",
"torch"
"torch",
"wooden_door"
]
}

View File

@ -1,6 +1,6 @@
{
"id": "base",
"title": "Base",
"version": "0.21",
"version": "0.22",
"description": "basic content package"
}

View File

@ -0,0 +1,6 @@
{
"sounds": [
"blocks/door_open",
"blocks/door_close"
]
}

View File

@ -0,0 +1,13 @@
function on_interact(x, y, z)
local inc = 1
if block.get_user_bits(x, y, z, 0, 1) > 0 then
inc = 3
block.set_user_bits(x, y, z, 0, 1, 0)
audio.play_sound("blocks/door_close", x+0.5, y+1, z+0.5, 1, 1)
else
block.set_user_bits(x, y, z, 0, 1, 1)
audio.play_sound("blocks/door_open", x+0.5, y+1, z+0.5, 1, 1)
end
block.set_rotation(x, y, z, (block.get_rotation(x, y, z) + inc) % 4)
return true
end

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

View File

@ -38,12 +38,7 @@ function submit(text)
document.log.caret = -1
local status, result = pcall(function() return console.execute(text) end)
if result ~= nil then
local prevtext = document.log.text
if #prevtext == 0 then
document.log:paste(tostring(result))
else
document.log:paste('\n'..tostring(result))
end
console.log(result)
end
document.prompt.text = ""
document.prompt.focused = true

View File

@ -203,6 +203,24 @@ function time.post_runnable(runnable)
table.insert(__post_runnables, runnable)
end
local log_element = Document.new("core:console").log
function console.log(...)
local args = {...}
local text = ''
for i,v in ipairs(args) do
if i ~= 1 then
text = text..' '..v
else
text = text..v
end
end
log_element.caret = -1
if log_element.caret > 0 then
text = '\n'..text
end
log_element:paste(text)
end
function gui.template(name, params)
local text = file.read(file.find("layouts/templates/"..name..".xml"))
for k,v in pairs(params) do

View File

@ -13,58 +13,62 @@ error.dependency-not-found=Käytetty riippuvuutta ei löytynyt
pack.remove-confirm=Poistetaanko kaikki pakettien sisältö maailmasta (peruuttamattomasti)?
# Меню
menu.New World=Uusi Maailma
menu.Quit=Poistu
menu.Continue=Jatka
menu.Save and Quit to Menu=Tallenna ja poistu valikkoon
menu.missing-content=Ei ole sisältöä!
menu.Content Error=Sisältövirhe
menu.Controls=Ohjaus
menu.Back to Main Menu=Takaisin Valikoon
menu.Settings=Asetukset
menu.Apply=Tallenna
menu.Audio=Ääni
menu.Back to Main Menu=Takaisin Valikkoon
menu.Content Error=Virhe Sisällössä
menu.Content=Sisältö
menu.Audio=Audio
menu.Continue=Jatka
menu.Controls=Ohjaus
menu.Graphics=Grafiikka
menu.missing-content=Sisältö Puuttuu!
menu.New World=Uusi Maailma
menu.Page not found=Sivu ei löytynyt!
menu.Quit=Poistu
menu.Save and Quit to Menu=Tallenna ja Takaisin Valikkoon
menu.Settings=Asetukset
world.Seed=Siemen
world.Name=Nimi
world.World generator=Maailman generaattori
world.World generator=Maailma Generaatori
world.generators.default=Tavallinen
world.generators.flat=Tasainen
menu.Create World=Luo Maailma
world.convert-request=Indeksit ovat muuttuneet! Luodaanko maailma uudeleen?
world.delete-confirm=Poistetaanko maailma peruuttamattomasti?
world.Create World=Luo Maailma
world.convert-request=Indekseissä on muutoksia! Kääntää maailman?
world.delete-confirm=Poistetaanko maailma pysyvästi?
# Настройки
settings.Load Distance=Latausalue
settings.Load Speed=Latausnopeus
settings.Fog Curve=Sumun tiheys
settings.Backlight=Taustavalo
settings.V-Sync=Pystytahdistus
settings.Camera Shaking=Kameran tärähdys
settings.Master Volume=Pää-äänekkyys
settings.Regular Sounds=Tavalliset äänet
settings.UI Sounds=Käyttöliittymän äänet
settings.Ambient=Tausta
settings.Music=Musiikki
settings.FOV=Näkökenttä
settings.Mouse Sensitivity=Hiiren nopeus
settings.Backlight=Taustavalo
settings.Camera Shaking=Tärisevä kamera
settings.Fog Curve=Sumukäurä
settings.FOV=Näkokenttä
settings.Fullscreen=Koko näyttö
settings.Gamma=Gamma
settings.Language=Kieli
settings.Load Distance=Latausetäisyys
settings.Load Speed=Latausnopeus
settings.Master Volume=Yleinen äänen voimakkuus
settings.Mouse Sensitivity=Hiiren herkkyys
settings.Music=Musiikki
settings.Regular Sounds=Tavalliset Äänet
settings.UI Sounds=Käyttöliittymän äänet
settings.V-Sync=Pystytahdistus
# Управление
devtools.console=Konsoli
movement.forward=Eteenpäin
movement.back=Taaksepäin
movement.left=Vaseemalle
movement.left=Vaseemmalle
movement.right=Oikealle
movement.jump=Hyppy
movement.sprint=Juoksu
movement.sprint=Kiihtyvyys
movement.crouch=Hiipiä
movement.cheat=Huijata
hud.inventory=Varasto
player.pick=Ottaa lohko
player.pick=Valitse lohko
player.attack=Lyödä / Rikkoa
player.build=Aseta lohko
player.flight=Lento
camera.zoom=Lähentäminen
camera.mode=Vaihda Kameratila
camera.mode=Vaihda kameratilaa

View File

@ -11,59 +11,59 @@
Assets::~Assets() {
}
Texture* Assets::getTexture(std::string name) const {
Texture* Assets::getTexture(const std::string& name) const {
auto found = textures.find(name);
if (found == textures.end())
return nullptr;
return found->second.get();
}
void Assets::store(std::unique_ptr<Texture> texture, std::string name){
void Assets::store(std::unique_ptr<Texture> texture, const std::string& name){
textures.emplace(name, std::move(texture));
}
Shader* Assets::getShader(std::string name) const{
Shader* Assets::getShader(const std::string& name) const{
auto found = shaders.find(name);
if (found == shaders.end())
return nullptr;
return found->second.get();
}
void Assets::store(std::unique_ptr<Shader> shader, std::string name){
void Assets::store(std::unique_ptr<Shader> shader, const std::string& name){
shaders.emplace(name, std::move(shader));
}
Font* Assets::getFont(std::string name) const {
Font* Assets::getFont(const std::string& name) const {
auto found = fonts.find(name);
if (found == fonts.end())
return nullptr;
return found->second.get();
}
void Assets::store(std::unique_ptr<Font> font, std::string name){
void Assets::store(std::unique_ptr<Font> font, const std::string& name){
fonts.emplace(name, std::move(font));
}
Atlas* Assets::getAtlas(std::string name) const {
Atlas* Assets::getAtlas(const std::string& name) const {
auto found = atlases.find(name);
if (found == atlases.end())
return nullptr;
return found->second.get();
}
void Assets::store(std::unique_ptr<Atlas> atlas, std::string name){
void Assets::store(std::unique_ptr<Atlas> atlas, const std::string& name){
atlases.emplace(name, std::move(atlas));
}
audio::Sound* Assets::getSound(std::string name) const {
audio::Sound* Assets::getSound(const std::string& name) const {
auto found = sounds.find(name);
if (found == sounds.end())
return nullptr;
return found->second.get();
}
void Assets::store(std::unique_ptr<audio::Sound> sound, std::string name) {
void Assets::store(std::unique_ptr<audio::Sound> sound, const std::string& name) {
sounds.emplace(name, std::move(sound));
}
@ -75,13 +75,13 @@ void Assets::store(const TextureAnimation& animation) {
animations.emplace_back(animation);
}
UiDocument* Assets::getLayout(std::string name) const {
UiDocument* Assets::getLayout(const std::string& name) const {
auto found = layouts.find(name);
if (found == layouts.end())
return nullptr;
return found->second.get();
}
void Assets::store(std::unique_ptr<UiDocument> layout, std::string name) {
void Assets::store(std::unique_ptr<UiDocument> layout, const std::string& name) {
layouts[name] = std::shared_ptr<UiDocument>(std::move(layout));
}

View File

@ -38,26 +38,26 @@ public:
Assets(const Assets&) = delete;
~Assets();
Texture* getTexture(std::string name) const;
void store(std::unique_ptr<Texture> texture, std::string name);
Texture* getTexture(const std::string& name) const;
void store(std::unique_ptr<Texture> texture, const std::string& name);
Shader* getShader(std::string name) const;
void store(std::unique_ptr<Shader> shader, std::string name);
Shader* getShader(const std::string& name) const;
void store(std::unique_ptr<Shader> shader, const std::string& name);
Font* getFont(std::string name) const;
void store(std::unique_ptr<Font> font, std::string name);
Font* getFont(const std::string& name) const;
void store(std::unique_ptr<Font> font, const std::string& name);
Atlas* getAtlas(std::string name) const;
void store(std::unique_ptr<Atlas> atlas, std::string name);
Atlas* getAtlas(const std::string& name) const;
void store(std::unique_ptr<Atlas> atlas, const std::string& name);
audio::Sound* getSound(std::string name) const;
void store(std::unique_ptr<audio::Sound> sound, std::string name);
audio::Sound* getSound(const std::string& name) const;
void store(std::unique_ptr<audio::Sound> sound, const std::string& name);
const std::vector<TextureAnimation>& getAnimations();
void store(const TextureAnimation& animation);
UiDocument* getLayout(std::string name) const;
void store(std::unique_ptr<UiDocument> layout, std::string name);
UiDocument* getLayout(const std::string& name) const;
void store(std::unique_ptr<UiDocument> layout, const std::string& name);
};
#endif // ASSETS_ASSETS_HPP_

View File

@ -17,6 +17,7 @@
#include <iostream>
#include <memory>
#include <utility>
static debug::Logger logger("assets-loader");
@ -32,11 +33,11 @@ AssetsLoader::AssetsLoader(Assets* assets, const ResPaths* paths)
}
void AssetsLoader::addLoader(AssetType tag, aloader_func func) {
loaders[tag] = func;
loaders[tag] = std::move(func);
}
void AssetsLoader::add(AssetType tag, const std::string filename, const std::string alias, std::shared_ptr<AssetCfg> settings) {
entries.push(aloader_entry{tag, filename, alias, settings});
void AssetsLoader::add(AssetType tag, const std::string& filename, const std::string& alias, std::shared_ptr<AssetCfg> settings) {
entries.push(aloader_entry{tag, filename, alias, std::move(settings)});
}
bool AssetsLoader::hasNext() const {
@ -69,12 +70,12 @@ bool AssetsLoader::loadNext() {
}
}
void addLayouts(scriptenv env, const std::string& prefix, const fs::path& folder, AssetsLoader& loader) {
void addLayouts(const scriptenv& env, const std::string& prefix, const fs::path& folder, AssetsLoader& loader) {
if (!fs::is_directory(folder)) {
return;
}
for (auto& entry : fs::directory_iterator(folder)) {
const fs::path file = entry.path();
const fs::path& file = entry.path();
if (file.extension().u8string() != ".xml")
continue;
std::string name = prefix+":"+file.stem().u8string();
@ -82,7 +83,7 @@ void addLayouts(scriptenv env, const std::string& prefix, const fs::path& folder
}
}
void AssetsLoader::tryAddSound(std::string name) {
void AssetsLoader::tryAddSound(const std::string& name) {
if (name.empty()) {
return;
}
@ -148,7 +149,7 @@ void AssetsLoader::processPreloadList(AssetType tag, dynamic::List* list) {
}
}
void AssetsLoader::processPreloadConfig(fs::path file) {
void AssetsLoader::processPreloadConfig(const fs::path& file) {
auto root = files::read_json(file);
processPreloadList(AssetType::font, root->list("fonts"));
processPreloadList(AssetType::shader, root->list("shaders"));
@ -209,7 +210,7 @@ void AssetsLoader::addDefaults(AssetsLoader& loader, const Content* content) {
bool AssetsLoader::loadExternalTexture(
Assets* assets,
const std::string& name,
std::vector<std::filesystem::path> alternatives
const std::vector<std::filesystem::path>& alternatives
) {
if (assets->getTexture(name) != nullptr) {
return true;
@ -255,7 +256,7 @@ std::shared_ptr<Task> AssetsLoader::startTask(runnable onDone) {
func(assets);
}
);
pool->setOnComplete(onDone);
pool->setOnComplete(std::move(onDone));
while (!entries.empty()) {
const aloader_entry& entry = entries.front();
auto ptr = std::make_shared<aloader_entry>(entry);

View File

@ -12,6 +12,7 @@
#include <functional>
#include <map>
#include <queue>
#include <utility>
namespace dynamic {
class Map;
@ -38,7 +39,7 @@ struct AssetCfg {
struct LayoutCfg : AssetCfg {
scriptenv env;
LayoutCfg(scriptenv env) : env(env) {}
LayoutCfg(scriptenv env) : env(std::move(env)) {}
};
struct SoundCfg : AssetCfg {
@ -68,11 +69,11 @@ class AssetsLoader {
std::queue<aloader_entry> entries;
const ResPaths* paths;
void tryAddSound(std::string name);
void tryAddSound(const std::string& name);
void processPreload(AssetType tag, const std::string& name, dynamic::Map* map);
void processPreloadList(AssetType tag, dynamic::List* list);
void processPreloadConfig(std::filesystem::path file);
void processPreloadConfig(const std::filesystem::path& file);
void processPreloadConfigs(const Content* content);
public:
AssetsLoader(Assets* assets, const ResPaths* paths);
@ -85,8 +86,8 @@ public:
/// @param settings asset loading settings (based on asset type)
void add(
AssetType tag,
const std::string filename,
const std::string alias,
const std::string& filename,
const std::string& alias,
std::shared_ptr<AssetCfg> settings=nullptr
);
@ -106,7 +107,7 @@ public:
static bool loadExternalTexture(
Assets* assets,
const std::string& name,
std::vector<std::filesystem::path> alternatives
const std::vector<std::filesystem::path>& alternatives
);
};

View File

@ -36,9 +36,9 @@ static bool animation(
assetload::postfunc assetload::texture(
AssetsLoader*,
const ResPaths* paths,
const std::string filename,
const std::string name,
std::shared_ptr<AssetCfg>
const std::string& filename,
const std::string& name,
const std::shared_ptr<AssetCfg>&
) {
std::shared_ptr<ImageData> image (
imageio::read(paths->find(filename+".png").u8string()).release()
@ -51,9 +51,9 @@ assetload::postfunc assetload::texture(
assetload::postfunc assetload::shader(
AssetsLoader*,
const ResPaths* paths,
const std::string filename,
const std::string name,
std::shared_ptr<AssetCfg>
const std::string& filename,
const std::string& name,
const std::shared_ptr<AssetCfg>&
) {
fs::path vertexFile = paths->find(filename+".glslv");
fs::path fragmentFile = paths->find(filename+".glslf");
@ -88,9 +88,9 @@ static bool append_atlas(AtlasBuilder& atlas, const fs::path& file) {
assetload::postfunc assetload::atlas(
AssetsLoader*,
const ResPaths* paths,
const std::string directory,
const std::string name,
std::shared_ptr<AssetCfg>
const std::string& directory,
const std::string& name,
const std::shared_ptr<AssetCfg>&
) {
AtlasBuilder builder;
for (const auto& file : paths->listdir(directory)) {
@ -113,9 +113,9 @@ assetload::postfunc assetload::atlas(
assetload::postfunc assetload::font(
AssetsLoader*,
const ResPaths* paths,
const std::string filename,
const std::string name,
std::shared_ptr<AssetCfg>
const std::string& filename,
const std::string& name,
const std::shared_ptr<AssetCfg>&
) {
auto pages = std::make_shared<std::vector<std::unique_ptr<ImageData>>>();
for (size_t i = 0; i <= 4; i++) {
@ -136,9 +136,9 @@ assetload::postfunc assetload::font(
assetload::postfunc assetload::layout(
AssetsLoader*,
const ResPaths* paths,
const std::string file,
const std::string name,
std::shared_ptr<AssetCfg> config
const std::string& file,
const std::string& name,
const std::shared_ptr<AssetCfg>& config
) {
return [=](auto assets) {
try {
@ -154,9 +154,9 @@ assetload::postfunc assetload::layout(
assetload::postfunc assetload::sound(
AssetsLoader*,
const ResPaths* paths,
const std::string file,
const std::string name,
std::shared_ptr<AssetCfg> config
const std::string& file,
const std::string& name,
const std::shared_ptr<AssetCfg>& config
) {
auto cfg = std::dynamic_pointer_cast<SoundCfg>(config);
bool keepPCM = cfg ? cfg->keepPCM : false;

View File

@ -17,45 +17,45 @@ namespace assetload {
postfunc texture(
AssetsLoader*,
const ResPaths* paths,
const std::string filename,
const std::string name,
std::shared_ptr<AssetCfg> settings
const std::string& filename,
const std::string &name,
const std::shared_ptr<AssetCfg>& settings
);
postfunc shader(
AssetsLoader*,
const ResPaths* paths,
const std::string filename,
const std::string name,
std::shared_ptr<AssetCfg> settings
const std::string& filename,
const std::string &name,
const std::shared_ptr<AssetCfg>& settings
);
postfunc atlas(
AssetsLoader*,
const ResPaths* paths,
const std::string directory,
const std::string name,
std::shared_ptr<AssetCfg> settings
const std::string &directory,
const std::string &name,
const std::shared_ptr<AssetCfg>& settings
);
postfunc font(
AssetsLoader*,
const ResPaths* paths,
const std::string filename,
const std::string name,
std::shared_ptr<AssetCfg> settings
const std::string& filename,
const std::string &name,
const std::shared_ptr<AssetCfg>& settings
);
postfunc layout(
AssetsLoader*,
const ResPaths* paths,
const std::string file,
const std::string name,
std::shared_ptr<AssetCfg> settings
const std::string& file,
const std::string &name,
const std::shared_ptr<AssetCfg>& settings
);
postfunc sound(
AssetsLoader*,
const ResPaths* paths,
const std::string file,
const std::string name,
std::shared_ptr<AssetCfg> settings
const std::string& file,
const std::string &name,
const std::shared_ptr<AssetCfg>& settings
);
}

View File

@ -4,12 +4,13 @@
#include "../../debug/Logger.hpp"
#include <string>
#include <utility>
static debug::Logger logger("al-audio");
using namespace audio;
ALSound::ALSound(ALAudio* al, uint buffer, std::shared_ptr<PCM> pcm, bool keepPCM)
ALSound::ALSound(ALAudio* al, uint buffer, const std::shared_ptr<PCM>& pcm, bool keepPCM)
: al(al), buffer(buffer)
{
duration = pcm->getDuration();
@ -36,7 +37,7 @@ std::unique_ptr<Speaker> ALSound::newInstance(int priority, int channel) const {
}
ALStream::ALStream(ALAudio* al, std::shared_ptr<PCMStream> source, bool keepSource)
: al(al), source(source), keepSource(keepSource) {
: al(al), source(std::move(source)), keepSource(keepSource) {
}
ALStream::~ALStream() {
@ -457,7 +458,7 @@ std::vector<std::string> ALAudio::getAvailableDevices() const {
const char* ptr = devices;
do {
devicesVec.push_back(std::string(ptr));
devicesVec.emplace_back(ptr);
ptr += devicesVec.back().size() + 1;
}
while (ptr[0]);

View File

@ -29,7 +29,7 @@ namespace audio {
std::shared_ptr<PCM> pcm;
duration_t duration;
public:
ALSound(ALAudio* al, uint buffer, std::shared_ptr<PCM> pcm, bool keepPCM);
ALSound(ALAudio* al, uint buffer, const std::shared_ptr<PCM>& pcm, bool keepPCM);
~ALSound();
duration_t getDuration() const override {

View File

@ -2,7 +2,7 @@
using namespace audio;
NoSound::NoSound(std::shared_ptr<PCM> pcm, bool keepPCM) {
NoSound::NoSound(const std::shared_ptr<PCM>& pcm, bool keepPCM) {
duration = pcm->getDuration();
if (keepPCM) {
this->pcm = pcm;

View File

@ -8,7 +8,7 @@ namespace audio {
std::shared_ptr<PCM> pcm;
duration_t duration;
public:
NoSound(std::shared_ptr<PCM> pcm, bool keepPCM);
NoSound(const std::shared_ptr<PCM>& pcm, bool keepPCM);
~NoSound() {}
duration_t getDuration() const override {
@ -28,7 +28,7 @@ namespace audio {
std::shared_ptr<PCMStream> source;
duration_t duration;
public:
NoStream(std::shared_ptr<PCMStream> source, bool keepSource) {
NoStream(const std::shared_ptr<PCMStream>& source, bool keepSource) {
duration = source->getTotalDuration();
if (keepSource) {
this->source = source;

View File

@ -8,6 +8,7 @@
#include <iostream>
#include <stdexcept>
#include <utility>
namespace audio {
static speakerid_t nextId = 1;
@ -19,7 +20,7 @@ namespace audio {
using namespace audio;
Channel::Channel(std::string name) : name(name) {
Channel::Channel(std::string name) : name(std::move(name)) {
}
float Channel::getVolume() const {
@ -175,7 +176,7 @@ std::unique_ptr<Sound> audio::load_sound(const fs::path& file, bool keepPCM) {
}
std::unique_ptr<Sound> audio::create_sound(std::shared_ptr<PCM> pcm, bool keepPCM) {
return backend->createSound(pcm, keepPCM);
return backend->createSound(std::move(pcm), keepPCM);
}
std::unique_ptr<PCMStream> audio::open_PCM_stream(const fs::path& file) {
@ -204,7 +205,7 @@ std::unique_ptr<Stream> audio::open_stream(const fs::path& file, bool keepSource
}
std::unique_ptr<Stream> audio::open_stream(std::shared_ptr<PCMStream> stream, bool keepSource) {
return backend->openStream(stream, keepSource);
return backend->openStream(std::move(stream), keepSource);
}
@ -276,7 +277,7 @@ speakerid_t audio::play(
}
speakerid_t audio::play(
std::shared_ptr<Stream> stream,
const std::shared_ptr<Stream>& stream,
glm::vec3 position,
bool relative,
float volume,

View File

@ -437,7 +437,7 @@ namespace audio {
/// @param channel channel index
/// @return speaker id or 0
speakerid_t play(
std::shared_ptr<Stream> stream,
const std::shared_ptr<Stream>& stream,
glm::vec3 position,
bool relative,
float volume,

View File

@ -8,29 +8,30 @@
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <utility>
namespace fs = std::filesystem;
void GLSLExtension::setVersion(std::string version) {
this->version = version;
this->version = std::move(version);
}
void GLSLExtension::setPaths(const ResPaths* paths) {
this->paths = paths;
}
void GLSLExtension::loadHeader(std::string name) {
void GLSLExtension::loadHeader(const std::string& name) {
fs::path file = paths->find("shaders/lib/"+name+".glsl");
std::string source = files::read_string(file);
addHeader(name, source);
}
void GLSLExtension::addHeader(std::string name, std::string source) {
headers[name] = source;
void GLSLExtension::addHeader(const std::string& name, std::string source) {
headers[name] = std::move(source);
}
void GLSLExtension::define(std::string name, std::string value) {
defines[name] = value;
void GLSLExtension::define(const std::string& name, std::string value) {
defines[name] = std::move(value);
}
const std::string& GLSLExtension::getHeader(const std::string& name) const {
@ -41,10 +42,10 @@ const std::string& GLSLExtension::getHeader(const std::string& name) const {
return found->second;
}
const std::string GLSLExtension::getDefine(const std::string& name) const {
const std::string& GLSLExtension::getDefine(const std::string& name) const {
auto found = defines.find(name);
if (found == defines.end()) {
return "";
throw std::runtime_error("name '"+name+"' is not defined");
}
return found->second;
}
@ -57,7 +58,7 @@ bool GLSLExtension::hasHeader(const std::string& name) const {
return headers.find(name) != headers.end();
}
void GLSLExtension::undefine(std::string name) {
void GLSLExtension::undefine(const std::string& name) {
if (hasDefine(name)) {
defines.erase(name);
}
@ -66,7 +67,7 @@ void GLSLExtension::undefine(std::string name) {
inline std::runtime_error parsing_error(
const fs::path& file,
uint linenum,
const std::string message) {
const std::string& message) {
return std::runtime_error("file "+file.string()+": "+message+
" at line "+std::to_string(linenum));
}
@ -74,7 +75,7 @@ inline std::runtime_error parsing_error(
inline void parsing_warning(
const fs::path& file,
uint linenum, const
std::string message) {
std::string& message) {
std::cerr << "file "+file.string()+": warning: "+message+
" at line "+std::to_string(linenum) << std::endl;
}
@ -83,7 +84,7 @@ inline void source_line(std::stringstream& ss, uint linenum) {
ss << "#line " << linenum << "\n";
}
const std::string GLSLExtension::process(const fs::path& file, const std::string& source) {
std::string GLSLExtension::process(const fs::path& file, const std::string& source) {
std::stringstream ss;
size_t pos = 0;
uint linenum = 1;

View File

@ -14,22 +14,22 @@ class GLSLExtension {
std::string version = "330 core";
const ResPaths* paths = nullptr;
void loadHeader(std::string name);
void loadHeader(const std::string& name);
public:
void setPaths(const ResPaths* paths);
void setVersion(std::string version);
void define(std::string name, std::string value);
void undefine(std::string name);
void addHeader(std::string name, std::string source);
void define(const std::string& name, std::string value);
void undefine(const std::string& name);
void addHeader(const std::string& name, std::string source);
const std::string& getHeader(const std::string& name) const;
const std::string getDefine(const std::string& name) const;
const std::string& getDefine(const std::string& name) const;
bool hasHeader(const std::string& name) const;
bool hasDefine(const std::string& name) const;
const std::string process(
std::string process(
const std::filesystem::path& file,
const std::string& source
);

View File

@ -15,7 +15,7 @@ inline double power(double base, int64_t power) {
}
parsing_error::parsing_error(
std::string message,
const std::string& message,
std::string_view filename,
std::string_view source,
uint pos,
@ -332,6 +332,6 @@ std::string BasicParser::parseString(char quote, bool closeRequired) {
return ss.str();
}
parsing_error BasicParser::error(std::string message) {
parsing_error BasicParser::error(const std::string& message) {
return parsing_error(message, filename, source, pos, line, linestart);
}

View File

@ -60,7 +60,7 @@ public:
uint linestart;
parsing_error(
std::string message,
const std::string& message,
std::string_view filename,
std::string_view source,
uint pos,
@ -92,7 +92,7 @@ protected:
dynamic::Value parseNumber(int sign);
std::string parseString(char chr, bool closeRequired=true);
parsing_error error(std::string message);
parsing_error error(const std::string& message);
public:
std::string_view readUntil(char c);

View File

@ -80,7 +80,7 @@ class OggStream : public PCMStream {
size_t totalSamples = 0;
bool seekable;
public:
OggStream(OggVorbis_File vf) : vf(std::move(vf)) {
OggStream(OggVorbis_File vf) : vf(vf) {
vorbis_info* info = ov_info(&vf, -1);
channels = info->channels;
sampleRate = info->rate;
@ -158,5 +158,5 @@ std::unique_ptr<PCMStream> ogg::create_stream(const fs::path& file) {
if ((code = ov_fopen(file.u8string().c_str(), &vf))) {
throw std::runtime_error("vorbis: "+vorbis_error_message(code));
}
return std::make_unique<OggStream>(std::move(vf));
return std::make_unique<OggStream>(vf);
}

View File

@ -5,12 +5,13 @@
#include <charconv>
#include <stdexcept>
#include <sstream>
#include <utility>
using namespace xml;
Attribute::Attribute(std::string name, std::string text)
: name(name),
text(text) {
: name(std::move(name)),
text(std::move(text)) {
}
const std::string& Attribute::getName() const {
@ -104,14 +105,14 @@ glm::vec4 Attribute::asColor() const {
}
}
Node::Node(std::string tag) : tag(tag) {
Node::Node(std::string tag) : tag(std::move(tag)) {
}
void Node::add(xmlelement element) {
void Node::add(const xmlelement& element) {
elements.push_back(element);
}
void Node::set(std::string name, std::string text) {
void Node::set(const std::string& name, const std::string &text) {
attrs[name] = Attribute(name, text);
}
@ -119,7 +120,7 @@ const std::string& Node::getTag() const {
return tag;
}
const xmlattribute Node::attr(const std::string& name) const {
const xmlattribute& Node::attr(const std::string& name) const {
auto found = attrs.find(name);
if (found == attrs.end()) {
throw std::runtime_error("element <"+tag+" ...> missing attribute "+name);
@ -127,7 +128,7 @@ const xmlattribute Node::attr(const std::string& name) const {
return found->second;
}
const xmlattribute Node::attr(const std::string& name, const std::string& def) const {
xmlattribute Node::attr(const std::string& name, const std::string& def) const {
auto found = attrs.find(name);
if (found == attrs.end()) {
return Attribute(name, def);
@ -157,11 +158,11 @@ const xmlelements_map& Node::getAttributes() const {
}
Document::Document(std::string version, std::string encoding)
: version(version),
encoding(encoding) {
: version(std::move(version)),
encoding(std::move(encoding)) {
}
void Document::setRoot(xmlelement element) {
void Document::setRoot(const xmlelement &element) {
this->root = element;
}
@ -336,7 +337,7 @@ xmldocument Parser::parse() {
return document;
}
xmldocument xml::parse(std::string filename, std::string source) {
xmldocument xml::parse(const std::string& filename, const std::string& source) {
Parser parser(filename, source);
return parser.parse();
}
@ -357,7 +358,7 @@ inline void newline(
static void stringifyElement(
std::stringstream& ss,
const xmlelement element,
const xmlelement& element,
bool nice,
const std::string& indentStr,
int indent
@ -414,7 +415,7 @@ static void stringifyElement(
}
std::string xml::stringify(
const xmldocument document,
const xmldocument& document,
bool nice,
const std::string& indentStr
) {

View File

@ -46,12 +46,12 @@ namespace xml {
Node(std::string tag);
/// @brief Add sub-element
void add(xmlelement element);
void add(const xmlelement& element);
/// @brief Set attribute value. Creates attribute if does not exists
/// @param name attribute name
/// @param text attribute value
void set(std::string name, std::string text);
void set(const std::string& name, const std::string &text);
/// @brief Get element tag
const std::string& getTag() const;
@ -68,14 +68,14 @@ namespace xml {
/// @param name attribute name
/// @throws std::runtime_error if element has no attribute
/// @return xmlattribute - {name, value}
const xmlattribute attr(const std::string& name) const;
const xmlattribute& attr(const std::string& name) const;
/// @brief Get attribute by name
/// @param name attribute name
/// @param def default value will be returned wrapped in xmlattribute
/// if element has no attribute
/// @return xmlattribute - {name, value} or {name, def} if not found*/
const xmlattribute attr(const std::string& name, const std::string& def) const;
xmlattribute attr(const std::string& name, const std::string& def) const;
/// @brief Check if element has attribute
/// @param name attribute name
@ -101,7 +101,7 @@ namespace xml {
public:
Document(std::string version, std::string encoding);
void setRoot(xmlelement element);
void setRoot(const xmlelement &element);
xmlelement getRoot() const;
const std::string& getVersion() const;
@ -129,7 +129,7 @@ namespace xml {
/// @param indentStr indentation characters sequence (default - 4 spaces)
/// @return XML string
extern std::string stringify(
const xmldocument document,
const xmldocument& document,
bool nice=true,
const std::string& indentStr=" "
);
@ -138,7 +138,7 @@ namespace xml {
/// @param filename file name will be shown in error messages
/// @param source xml source code string
/// @return xml document
extern xmldocument parse(std::string filename, std::string source);
extern xmldocument parse(const std::string& filename, const std::string& source);
}
#endif // CODERS_XML_HPP_

View File

@ -7,7 +7,7 @@
#include <string>
inline constexpr int ENGINE_VERSION_MAJOR = 0;
inline constexpr int ENGINE_VERSION_MINOR = 21;
inline constexpr int ENGINE_VERSION_MINOR = 22;
#ifdef NDEBUG
inline constexpr bool ENGINE_DEBUG_BUILD = false;
@ -15,7 +15,7 @@ inline constexpr bool ENGINE_DEBUG_BUILD = false;
inline constexpr bool ENGINE_DEBUG_BUILD = true;
#endif // NDEBUG
inline const std::string ENGINE_VERSION_STRING = "0.21";
inline const std::string ENGINE_VERSION_STRING = "0.22";
inline constexpr blockid_t BLOCK_AIR = 0;
inline constexpr itemid_t ITEM_EMPTY = 0;

View File

@ -3,6 +3,7 @@
#include <memory>
#include <stdexcept>
#include <glm/glm.hpp>
#include <utility>
#include "../voxels/Block.hpp"
#include "../items/ItemDef.hpp"
@ -13,8 +14,8 @@
ContentIndices::ContentIndices(
std::vector<Block*> blockDefs,
std::vector<ItemDef*> itemDefs
) : blockDefs(blockDefs),
itemDefs(itemDefs)
) : blockDefs(std::move(blockDefs)),
itemDefs(std::move(itemDefs))
{}
Content::Content(
@ -35,7 +36,7 @@ Content::Content(
Content::~Content() {
}
Block* Content::findBlock(std::string id) const {
Block* Content::findBlock(const std::string& id) const {
auto found = blockDefs.find(id);
if (found == blockDefs.end()) {
return nullptr;
@ -43,7 +44,7 @@ Block* Content::findBlock(std::string id) const {
return found->second.get();
}
Block& Content::requireBlock(std::string id) const {
Block& Content::requireBlock(const std::string& id) const {
auto found = blockDefs.find(id);
if (found == blockDefs.end()) {
throw std::runtime_error("missing block "+id);
@ -51,7 +52,7 @@ Block& Content::requireBlock(std::string id) const {
return *found->second;
}
ItemDef* Content::findItem(std::string id) const {
ItemDef* Content::findItem(const std::string& id) const {
auto found = itemDefs.find(id);
if (found == itemDefs.end()) {
return nullptr;
@ -59,7 +60,7 @@ ItemDef* Content::findItem(std::string id) const {
return found->second.get();
}
ItemDef& Content::requireItem(std::string id) const {
ItemDef& Content::requireItem(const std::string& id) const {
auto found = itemDefs.find(id);
if (found == itemDefs.end()) {
throw std::runtime_error("missing item "+id);
@ -67,7 +68,7 @@ ItemDef& Content::requireItem(std::string id) const {
return *found->second;
}
const BlockMaterial* Content::findBlockMaterial(std::string id) const {
const BlockMaterial* Content::findBlockMaterial(const std::string& id) const {
auto found = blockMaterials.find(id);
if (found == blockMaterials.end()) {
return nullptr;
@ -75,7 +76,7 @@ const BlockMaterial* Content::findBlockMaterial(std::string id) const {
return found->second.get();
}
const ContentPackRuntime* Content::getPackRuntime(std::string id) const {
const ContentPackRuntime* Content::getPackRuntime(const std::string& id) const {
auto found = packs.find(id);
if (found == packs.end()) {
return nullptr;

View File

@ -107,15 +107,15 @@ public:
return indices.get();
}
Block* findBlock(std::string id) const;
Block& requireBlock(std::string id) const;
Block* findBlock(const std::string& id) const;
Block& requireBlock(const std::string& id) const;
ItemDef* findItem(std::string id) const;
ItemDef& requireItem(std::string id) const;
ItemDef* findItem(const std::string& id) const;
ItemDef& requireItem(const std::string& id) const;
const BlockMaterial* findBlockMaterial(std::string id) const;
const BlockMaterial* findBlockMaterial(const std::string& id) const;
const ContentPackRuntime* getPackRuntime(std::string id) const;
const ContentPackRuntime* getPackRuntime(const std::string& id) const;
const std::unordered_map<std::string, std::unique_ptr<BlockMaterial>>& getBlockMaterials() const;
const std::unordered_map<std::string, std::unique_ptr<ContentPackRuntime>>& getPacks() const;

View File

@ -6,7 +6,7 @@ void ContentBuilder::add(std::unique_ptr<ContentPackRuntime> pack) {
packs[pack->getId()] = std::move(pack);
}
Block& ContentBuilder::createBlock(std::string id) {
Block& ContentBuilder::createBlock(const std::string& id) {
auto found = blockDefs.find(id);
if (found != blockDefs.end()) {
return *found->second;
@ -17,7 +17,7 @@ Block& ContentBuilder::createBlock(std::string id) {
return *blockDefs[id];
}
ItemDef& ContentBuilder::createItem(std::string id) {
ItemDef& ContentBuilder::createItem(const std::string& id) {
auto found = itemDefs.find(id);
if (found != itemDefs.end()) {
return *found->second;
@ -28,21 +28,21 @@ ItemDef& ContentBuilder::createItem(std::string id) {
return *itemDefs[id];
}
BlockMaterial& ContentBuilder::createBlockMaterial(std::string id) {
BlockMaterial& ContentBuilder::createBlockMaterial(const std::string& id) {
blockMaterials[id] = std::make_unique<BlockMaterial>();
auto& material = *blockMaterials[id];
material.name = id;
return material;
}
void ContentBuilder::checkIdentifier(std::string id) {
void ContentBuilder::checkIdentifier(const std::string& id) {
contenttype result;
if (((result = checkContentType(id)) != contenttype::none)) {
throw namereuse_error("name "+id+" is already used", result);
}
}
contenttype ContentBuilder::checkContentType(std::string id) {
contenttype ContentBuilder::checkContentType(const std::string& id) {
if (blockDefs.find(id) != blockDefs.end()) {
return contenttype::block;
}
@ -62,6 +62,7 @@ std::unique_ptr<Content> ContentBuilder::build() {
def.rt.id = blockDefsIndices.size();
def.rt.emissive = *reinterpret_cast<uint32_t*>(def.emission);
def.rt.solid = def.model == BlockModel::block;
def.rt.extended = def.size.x > 1 || def.size.y > 1 || def.size.z > 1;
if (def.rotatable) {
for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) {

View File

@ -24,12 +24,12 @@ public:
void add(std::unique_ptr<ContentPackRuntime> pack);
Block& createBlock(std::string id);
ItemDef& createItem(std::string id);
BlockMaterial& createBlockMaterial(std::string id);
Block& createBlock(const std::string& id);
ItemDef& createItem(const std::string& id);
BlockMaterial& createBlockMaterial(const std::string& id);
void checkIdentifier(std::string id);
contenttype checkContentType(std::string id);
void checkIdentifier(const std::string& id);
contenttype checkContentType(const std::string& id);
std::unique_ptr<Content> build();
};

View File

@ -19,7 +19,7 @@ ContentLUT::ContentLUT(const Content* content, size_t blocksCount, size_t itemsC
blockNames.push_back(indices->getBlockDef(i)->name);
}
for (size_t i = indices->countBlockDefs(); i < blocksCount; i++) {
blockNames.push_back("");
blockNames.emplace_back("");
}
for (size_t i = 0; i < itemsCount; i++) {
@ -29,7 +29,7 @@ ContentLUT::ContentLUT(const Content* content, size_t blocksCount, size_t itemsC
itemNames.push_back(indices->getItemDef(i)->name);
}
for (size_t i = indices->countItemDefs(); i < itemsCount; i++) {
itemNames.push_back("");
itemNames.emplace_back();
}
}

View File

@ -7,6 +7,7 @@
#include "../constants.hpp"
#include <string>
#include <utility>
#include <vector>
#include <filesystem>
@ -44,7 +45,7 @@ public:
inline void setBlock(blockid_t index, std::string name, blockid_t id) {
blocks[index] = id;
blockNames[index] = name;
blockNames[index] = std::move(name);
if (id == BLOCK_VOID) {
missingContent = true;
} else if (index != id) {
@ -62,7 +63,7 @@ public:
inline void setItem(itemid_t index, std::string name, itemid_t id) {
items[index] = id;
itemNames[index] = name;
itemNames[index] = std::move(name);
if (id == ITEM_VOID) {
missingContent = true;
} else if (index != id) {

View File

@ -28,15 +28,15 @@ ContentLoader::ContentLoader(ContentPack* pack) : pack(pack) {
}
bool ContentLoader::fixPackIndices(
fs::path folder,
const fs::path& folder,
dynamic::Map* indicesRoot,
std::string contentSection
const std::string& contentSection
) {
std::vector<std::string> detected;
std::vector<std::string> indexed;
if (fs::is_directory(folder)) {
for (auto entry : fs::directory_iterator(folder)) {
fs::path file = entry.path();
for (const auto& entry : fs::directory_iterator(folder)) {
const fs::path& file = entry.path();
if (fs::is_regular_file(file) && file.extension() == ".json") {
std::string name = file.stem().string();
if (name[0] == '_')
@ -46,8 +46,8 @@ bool ContentLoader::fixPackIndices(
std::string space = file.stem().string();
if (space[0] == '_')
continue;
for (auto entry : fs::directory_iterator(file)) {
fs::path file = entry.path();
for (const auto& entry : fs::directory_iterator(file)) {
const fs::path& file = entry.path();
if (fs::is_regular_file(file) && file.extension() == ".json") {
std::string name = file.stem().string();
if (name[0] == '_')
@ -109,7 +109,7 @@ void ContentLoader::fixPackIndices() {
}
}
void ContentLoader::loadBlock(Block& def, std::string name, fs::path file) {
void ContentLoader::loadBlock(Block& def, const std::string& name, const fs::path& file) {
auto root = files::read_json(file);
root->str("caption", def.caption);
@ -137,16 +137,14 @@ void ContentLoader::loadBlock(Block& def, std::string name, fs::path file) {
def.model = BlockModel::custom;
if (root->has("model-primitives")) {
loadCustomBlockModel(def, root->map("model-primitives"));
}
else {
std::cerr << "ERROR occured while block "
<< name << " parsed: no \"model-primitives\" found" << std::endl;
} else {
logger.error() << name << ": no 'model-primitives' found";
}
}
else if (model == "X") def.model = BlockModel::xsprite;
else if (model == "none") def.model = BlockModel::none;
else {
std::cerr << "unknown model " << model << std::endl;
logger.error() << "unknown model " << model;
def.model = BlockModel::none;
}
@ -156,12 +154,12 @@ void ContentLoader::loadBlock(Block& def, std::string name, fs::path file) {
std::string profile = "none";
root->str("rotation", profile);
def.rotatable = profile != "none";
if (profile == "pipe") {
if (profile == BlockRotProfile::PIPE_NAME) {
def.rotations = BlockRotProfile::PIPE;
} else if (profile == "pane") {
} else if (profile == BlockRotProfile::PANE_NAME) {
def.rotations = BlockRotProfile::PANE;
} else if (profile != "none") {
std::cerr << "unknown rotation profile " << profile << std::endl;
logger.error() << "unknown rotation profile " << profile;
def.rotatable = false;
}
@ -175,29 +173,37 @@ void ContentLoader::loadBlock(Block& def, std::string name, fs::path file) {
def.hitboxes[i].b = glm::vec3(box->num(3), box->num(4), box->num(5));
def.hitboxes[i].b += def.hitboxes[i].a;
}
} else if (auto boxarr = root->list("hitbox")){
AABB aabb;
aabb.a = glm::vec3(boxarr->num(0), boxarr->num(1), boxarr->num(2));
aabb.b = glm::vec3(boxarr->num(3), boxarr->num(4), boxarr->num(5));
aabb.b += aabb.a;
def.hitboxes = { aabb };
} else if (!def.modelBoxes.empty()) {
def.hitboxes = def.modelBoxes;
} else {
boxarr = root->list("hitbox");
if (boxarr) {
AABB aabb;
aabb.a = glm::vec3(boxarr->num(0), boxarr->num(1), boxarr->num(2));
aabb.b = glm::vec3(boxarr->num(3), boxarr->num(4), boxarr->num(5));
aabb.b += aabb.a;
def.hitboxes = { aabb };
} else if (!def.modelBoxes.empty()) {
def.hitboxes = def.modelBoxes;
} else {
def.hitboxes = { AABB() };
}
def.hitboxes = { AABB() };
}
// block light emission [r, g, b] where r,g,b in range [0..15]
auto emissionarr = root->list("emission");
if (emissionarr) {
if (auto emissionarr = root->list("emission")) {
def.emission[0] = emissionarr->num(0);
def.emission[1] = emissionarr->num(1);
def.emission[2] = emissionarr->num(2);
}
// block size
if (auto sizearr = root->list("size")) {
def.size.x = sizearr->num(0);
def.size.y = sizearr->num(1);
def.size.z = sizearr->num(2);
if (def.model == BlockModel::block &&
(def.size.x != 1 || def.size.y != 1 || def.size.z != 1)) {
def.model = BlockModel::aabb;
def.hitboxes = {AABB(def.size)};
}
}
// primitive properties
root->flag("obstacle", def.obstacle);
root->flag("replaceable", def.replaceable);
@ -244,7 +250,7 @@ void ContentLoader::loadCustomBlockModel(Block& def, dynamic::Map* primitives) {
}
else
for (uint j = 6; j < 12; j++) {
def.modelTextures.push_back("notfound");
def.modelTextures.emplace_back("notfound");
}
}
}
@ -254,8 +260,8 @@ void ContentLoader::loadCustomBlockModel(Block& def, dynamic::Map* primitives) {
/* Parse tetragon to points */
auto tgonobj = modeltetragons->list(i);
glm::vec3 p1(tgonobj->num(0), tgonobj->num(1), tgonobj->num(2)),
xw(tgonobj->num(3), tgonobj->num(4), tgonobj->num(5)),
yh(tgonobj->num(6), tgonobj->num(7), tgonobj->num(8));
xw(tgonobj->num(3), tgonobj->num(4), tgonobj->num(5)),
yh(tgonobj->num(6), tgonobj->num(7), tgonobj->num(8));
def.modelExtraPoints.push_back(p1);
def.modelExtraPoints.push_back(p1+xw);
def.modelExtraPoints.push_back(p1+xw+yh);
@ -266,7 +272,7 @@ void ContentLoader::loadCustomBlockModel(Block& def, dynamic::Map* primitives) {
}
}
void ContentLoader::loadItem(ItemDef& def, std::string name, fs::path file) {
void ContentLoader::loadItem(ItemDef& def, const std::string& name, const fs::path& file) {
auto root = files::read_json(file);
root->str("caption", def.caption);
@ -279,7 +285,7 @@ void ContentLoader::loadItem(ItemDef& def, std::string name, fs::path file) {
} else if (iconTypeStr == "sprite") {
def.iconType = item_icon_type::sprite;
} else if (iconTypeStr.length()){
std::cerr << "unknown icon type" << iconTypeStr << std::endl;
logger.error() << name << ": unknown icon type" << iconTypeStr;
}
root->str("icon", def.icon);
root->str("placing-block", def.placingBlock);
@ -295,7 +301,7 @@ void ContentLoader::loadItem(ItemDef& def, std::string name, fs::path file) {
}
}
void ContentLoader::loadBlock(Block& def, std::string full, std::string name) {
void ContentLoader::loadBlock(Block& def, const std::string& full, const std::string& name) {
auto folder = pack->folder;
fs::path configFile = folder/fs::path("blocks/"+name+".json");
@ -307,7 +313,7 @@ void ContentLoader::loadBlock(Block& def, std::string full, std::string name) {
}
}
void ContentLoader::loadItem(ItemDef& def, std::string full, std::string name) {
void ContentLoader::loadItem(ItemDef& def, const std::string& full, const std::string& name) {
auto folder = pack->folder;
fs::path configFile = folder/fs::path("items/"+name+".json");
@ -319,7 +325,7 @@ void ContentLoader::loadItem(ItemDef& def, std::string full, std::string name) {
}
}
void ContentLoader::loadBlockMaterial(BlockMaterial& def, fs::path file) {
void ContentLoader::loadBlockMaterial(BlockMaterial& def, const fs::path& file) {
auto root = files::read_json(file);
root->str("steps-sound", def.stepsSound);
root->str("place-sound", def.placeSound);
@ -394,8 +400,8 @@ void ContentLoader::load(ContentBuilder& builder) {
fs::path materialsDir = folder / fs::u8path("block_materials");
if (fs::is_directory(materialsDir)) {
for (auto entry : fs::directory_iterator(materialsDir)) {
fs::path file = entry.path();
for (const auto& entry : fs::directory_iterator(materialsDir)) {
const fs::path& file = entry.path();
std::string name = pack->id+":"+file.stem().u8string();
loadBlockMaterial(builder.createBlockMaterial(name), file);
}

View File

@ -22,21 +22,21 @@ class ContentLoader {
const ContentPack* pack;
scriptenv env;
void loadBlock(Block& def, std::string full, std::string name);
void loadBlock(Block& def, const std::string& full, const std::string& name);
void loadCustomBlockModel(Block& def, dynamic::Map* primitives);
void loadItem(ItemDef& def, std::string full, std::string name);
void loadBlockMaterial(BlockMaterial& def, fs::path file);
void loadItem(ItemDef& def, const std::string& full, const std::string& name);
void loadBlockMaterial(BlockMaterial& def, const fs::path& file);
public:
ContentLoader(ContentPack* pack);
bool fixPackIndices(
fs::path folder,
const fs::path& folder,
dynamic::Map* indicesRoot,
std::string contentSection
const std::string& contentSection
);
void fixPackIndices();
void loadBlock(Block& def, std::string name, fs::path file);
void loadItem(ItemDef& def, std::string name, fs::path file);
void loadBlock(Block& def, const std::string& name, const fs::path& file);
void loadItem(ItemDef& def, const std::string& name, const fs::path& file);
void load(ContentBuilder& builder);
};

View File

@ -2,6 +2,7 @@
#include <iostream>
#include <algorithm>
#include <utility>
#include "../coders/json.hpp"
#include "../files/files.hpp"
@ -21,8 +22,8 @@ const std::vector<std::string> ContentPack::RESERVED_NAMES = {
contentpack_error::contentpack_error(
std::string packId,
fs::path folder,
std::string message)
: std::runtime_error(message), packId(packId), folder(folder) {
const std::string& message)
: std::runtime_error(message), packId(std::move(packId)), folder(std::move(folder)) {
}
std::string contentpack_error::getPackId() const {
@ -36,7 +37,7 @@ fs::path ContentPack::getContentFile() const {
return folder/fs::path(CONTENT_FILENAME);
}
bool ContentPack::is_pack(fs::path folder) {
bool ContentPack::is_pack(const fs::path& folder) {
return fs::is_regular_file(folder/fs::path(PACKAGE_FILENAME));
}
@ -61,7 +62,7 @@ static void checkContentPackId(const std::string& id, const fs::path& folder) {
}
}
ContentPack ContentPack::read(fs::path folder) {
ContentPack ContentPack::read(const fs::path& folder) {
auto root = files::read_json(folder/fs::path(PACKAGE_FILENAME));
ContentPack pack;
root->str("id", pack.id);
@ -89,14 +90,14 @@ ContentPack ContentPack::read(fs::path folder) {
}
void ContentPack::scanFolder(
fs::path folder,
const fs::path& folder,
std::vector<ContentPack>& packs
) {
if (!fs::is_directory(folder)) {
return;
}
for (auto entry : fs::directory_iterator(folder)) {
fs::path folder = entry.path();
for (const auto& entry : fs::directory_iterator(folder)) {
const fs::path& folder = entry.path();
if (!fs::is_directory(folder))
continue;
if (!is_pack(folder))
@ -112,7 +113,7 @@ void ContentPack::scanFolder(
}
}
std::vector<std::string> ContentPack::worldPacksList(fs::path folder) {
std::vector<std::string> ContentPack::worldPacksList(const fs::path& folder) {
fs::path listfile = folder / fs::path("packs.list");
if (!fs::is_regular_file(listfile)) {
std::cerr << "warning: packs.list not found (will be created)";
@ -122,7 +123,7 @@ std::vector<std::string> ContentPack::worldPacksList(fs::path folder) {
return files::read_list(listfile);
}
fs::path ContentPack::findPack(const EnginePaths* paths, fs::path worldDir, std::string name) {
fs::path ContentPack::findPack(const EnginePaths* paths, const fs::path& worldDir, const std::string& name) {
fs::path folder = worldDir / fs::path("content") / fs::path(name);
if (fs::is_directory(folder)) {
return folder;
@ -141,7 +142,7 @@ fs::path ContentPack::findPack(const EnginePaths* paths, fs::path worldDir, std:
ContentPackRuntime::ContentPackRuntime(
ContentPack info,
scriptenv env
) : info(info), env(std::move(env))
) : info(std::move(info)), env(std::move(env))
{
}

View File

@ -16,7 +16,7 @@ class contentpack_error : public std::runtime_error {
std::string packId;
fs::path folder;
public:
contentpack_error(std::string packId, fs::path folder, std::string message);
contentpack_error(std::string packId, fs::path folder, const std::string& message);
std::string getPackId() const;
fs::path getFolder() const;
@ -52,20 +52,20 @@ struct ContentPack {
static const fs::path ITEMS_FOLDER;
static const std::vector<std::string> RESERVED_NAMES;
static bool is_pack(fs::path folder);
static ContentPack read(fs::path folder);
static bool is_pack(const fs::path& folder);
static ContentPack read(const fs::path& folder);
static void scanFolder(
fs::path folder,
const fs::path& folder,
std::vector<ContentPack>& packs
);
static std::vector<std::string> worldPacksList(fs::path folder);
static std::vector<std::string> worldPacksList(const fs::path& folder);
static fs::path findPack(
const EnginePaths* paths,
fs::path worldDir,
std::string name
const fs::path& worldDir,
const std::string& name
);
};

View File

@ -110,7 +110,7 @@ void Map::str(const std::string& key, std::string& dst) const {
dst = get(key, dst);
}
std::string Map::get(const std::string& key, const std::string def) const {
std::string Map::get(const std::string& key, const std::string& def) const {
auto found = values.find(key);
if (found == values.end())
return def;
@ -213,7 +213,7 @@ void Map::flag(const std::string& key, bool& dst) const {
dst = get(key, dst);
}
Map& Map::put(std::string key, const Value& value) {
Map& Map::put(const std::string& key, const Value& value) {
values[key] = value;
return *this;
}
@ -222,13 +222,13 @@ void Map::remove(const std::string& key) {
values.erase(key);
}
List& Map::putList(std::string key) {
List& Map::putList(const std::string& key) {
auto arr = create_list();
put(key, arr);
return *arr;
}
Map& Map::putMap(std::string key) {
Map& Map::putMap(const std::string& key) {
auto obj = create_map();
put(key, obj);
return *obj;

View File

@ -101,7 +101,7 @@ namespace dynamic {
return get(key, T());
}
std::string get(const std::string& key, const std::string def) const;
std::string get(const std::string& key, const std::string& def) const;
number_t get(const std::string& key, double def) const;
integer_t get(const std::string& key, integer_t def) const;
bool get(const std::string& key, bool def) const;
@ -155,12 +155,12 @@ namespace dynamic {
Map& put(std::string key, const char* value) {
return put(key, Value(value));
}
Map& put(std::string key, const Value& value);
Map& put(const std::string& key, const Value& value);
void remove(const std::string& key);
List& putList(std::string key);
Map& putMap(std::string key);
List& putList(const std::string& key);
Map& putMap(const std::string& key);
bool has(const std::string& key) const;
size_t size() const;

View File

@ -4,6 +4,7 @@
#include <iomanip>
#include <chrono>
#include <iostream>
#include <utility>
using namespace debug;
@ -16,10 +17,10 @@ LogMessage::~LogMessage() {
logger->log(level, ss.str());
}
Logger::Logger(std::string name) : name(name) {
Logger::Logger(std::string name) : name(std::move(name)) {
}
void Logger::log(LogLevel level, const std::string& name, std::string message) {
void Logger::log(LogLevel level, const std::string& name, const std::string& message) {
using namespace std::chrono;
std::stringstream ss;
@ -72,5 +73,5 @@ void Logger::flush() {
}
void Logger::log(LogLevel level, std::string message) {
log(level, name, message);
log(level, name, std::move(message));
}

View File

@ -35,7 +35,7 @@ namespace debug {
std::string name;
static void log(LogLevel level, const std::string& name, std::string message);
static void log(LogLevel level, const std::string& name, const std::string& message);
public:
static void init(const std::string& filename);
static void flush();

View File

@ -42,6 +42,7 @@
#include <glm/glm.hpp>
#include <unordered_set>
#include <functional>
#include <utility>
static debug::Logger logger("engine");
@ -65,6 +66,7 @@ Engine::Engine(EngineSettings& settings, SettingsHandler& settingsHandler, Engin
: settings(settings), settingsHandler(settingsHandler), paths(paths),
interpreter(std::make_unique<cmd::CommandsInterpreter>())
{
paths->prepare();
loadSettings();
controller = std::make_unique<EngineController>(this);
@ -115,14 +117,6 @@ void Engine::loadControls() {
logger.info() << "loading controls";
std::string text = files::read_string(controls_file);
Events::loadBindings(controls_file.u8string(), text);
} else {
controls_file = paths->getControlsFileOld();
if (fs::is_regular_file(controls_file)) {
logger.info() << "loading controls (old)";
std::string text = files::read_string(controls_file);
Events::loadBindingsOld(controls_file.u8string(), text);
fs::remove(controls_file);
}
}
}
@ -347,11 +341,11 @@ double Engine::getDelta() const {
void Engine::setScreen(std::shared_ptr<Screen> screen) {
audio::reset_channel(audio::get_channel_index("regular"));
audio::reset_channel(audio::get_channel_index("ambient"));
this->screen = screen;
this->screen = std::move(screen);
}
void Engine::setLanguage(std::string locale) {
langs::setup(paths->getResources(), locale, contentPacks);
langs::setup(paths->getResources(), std::move(locale), contentPacks);
gui->getMenu()->setPageLoader(menus::create_page_loader(this));
}
@ -391,7 +385,7 @@ std::shared_ptr<Screen> Engine::getScreen() {
return screen;
}
void Engine::postRunnable(runnable callback) {
void Engine::postRunnable(const runnable& callback) {
std::lock_guard<std::recursive_mutex> lock(postRunnablesMutex);
postRunnables.push(callback);
}

View File

@ -137,7 +137,7 @@ public:
std::shared_ptr<Screen> getScreen();
/// @brief Enqueue function call to the end of current frame in draw thread
void postRunnable(runnable callback);
void postRunnable(const runnable& callback);
void saveScreenshot();

View File

@ -13,6 +13,7 @@
#include <memory>
#include <iostream>
#include <stdexcept>
#include <utility>
namespace fs = std::filesystem;
@ -22,7 +23,7 @@ class ConverterWorker : public util::Worker<convert_task, int> {
std::shared_ptr<WorldConverter> converter;
public:
ConverterWorker(std::shared_ptr<WorldConverter> converter)
: converter(converter) {}
: converter(std::move(converter)) {}
int operator()(const std::shared_ptr<convert_task>& task) override {
converter->convert(*task);
@ -31,11 +32,11 @@ public:
};
WorldConverter::WorldConverter(
fs::path folder,
const fs::path& folder,
const Content* content,
std::shared_ptr<ContentLUT> lut
) : wfile(std::make_unique<WorldFiles>(folder)),
lut(lut),
lut(std::move(lut)),
content(content)
{
fs::path regionsFolder = wfile->getRegions().getRegionsFolder(REGION_LAYER_VOXELS);
@ -44,7 +45,7 @@ WorldConverter::WorldConverter(
return;
}
tasks.push(convert_task {convert_task_type::player, wfile->getPlayerFile()});
for (auto file : fs::directory_iterator(regionsFolder)) {
for (const auto& file : fs::directory_iterator(regionsFolder)) {
tasks.push(convert_task {convert_task_type::region, file.path()});
}
}
@ -53,10 +54,10 @@ WorldConverter::~WorldConverter() {
}
std::shared_ptr<Task> WorldConverter::startTask(
fs::path folder,
const fs::path& folder,
const Content* content,
std::shared_ptr<ContentLUT> lut,
runnable onDone,
const std::shared_ptr<ContentLUT>& lut,
const runnable& onDone,
bool multithreading
) {
auto converter = std::make_shared<WorldConverter>(folder, content, lut);
@ -85,7 +86,7 @@ std::shared_ptr<Task> WorldConverter::startTask(
return pool;
}
void WorldConverter::convertRegion(fs::path file) const {
void WorldConverter::convertRegion(const fs::path& file) const {
int x, z;
std::string name = file.stem().string();
if (!WorldRegions::parseRegionFilename(name, x, z)) {
@ -101,14 +102,14 @@ void WorldConverter::convertRegion(fs::path file) const {
});
}
void WorldConverter::convertPlayer(fs::path file) const {
void WorldConverter::convertPlayer(const fs::path& file) const {
logger.info() << "converting player " << file.u8string();
auto map = files::read_json(file);
Player::convert(map.get(), lut.get());
files::write_json(file, map.get());
}
void WorldConverter::convert(convert_task task) const {
void WorldConverter::convert(const convert_task& task) const {
if (!fs::is_regular_file(task.file))
return;
@ -134,7 +135,7 @@ void WorldConverter::convertNext() {
}
void WorldConverter::setOnComplete(runnable callback) {
this->onComplete = callback;
this->onComplete = std::move(callback);
}
void WorldConverter::update() {

View File

@ -32,17 +32,17 @@ class WorldConverter : public Task {
runnable onComplete;
uint tasksDone = 0;
void convertPlayer(fs::path file) const;
void convertRegion(fs::path file) const;
void convertPlayer(const fs::path& file) const;
void convertRegion(const fs::path& file) const;
public:
WorldConverter(
fs::path folder,
const fs::path& folder,
const Content* content,
std::shared_ptr<ContentLUT> lut
);
~WorldConverter();
void convert(convert_task task) const;
void convert(const convert_task& task) const;
void convertNext();
void setOnComplete(runnable callback);
void write();
@ -55,10 +55,10 @@ public:
uint getWorkDone() const override;
static std::shared_ptr<Task> startTask(
fs::path folder,
const fs::path& folder,
const Content* content,
std::shared_ptr<ContentLUT> lut,
runnable onDone,
const std::shared_ptr<ContentLUT>& lut,
const runnable& onDone,
bool multithreading
);
};

View File

@ -27,14 +27,15 @@
#include <fstream>
#include <sstream>
#include <cstring>
#include <utility>
#define WORLD_FORMAT_MAGIC ".VOXWLD"
WorldFiles::WorldFiles(fs::path directory) : directory(directory), regions(directory) {
WorldFiles::WorldFiles(const fs::path& directory) : directory(directory), regions(directory) {
}
WorldFiles::WorldFiles(fs::path directory, const DebugSettings& settings)
: WorldFiles(directory)
WorldFiles::WorldFiles(const fs::path& directory, const DebugSettings& settings)
: WorldFiles(directory)
{
generatorTestMode = settings.generatorTestMode.get();
doWriteLights = settings.doWriteLights.get();

View File

@ -41,8 +41,8 @@ class WorldFiles {
void writeWorldInfo(const World* world);
void writeIndices(const ContentIndices* indices);
public:
WorldFiles(fs::path directory);
WorldFiles(fs::path directory, const DebugSettings& settings);
WorldFiles(const fs::path &directory);
WorldFiles(const fs::path &directory, const DebugSettings& settings);
~WorldFiles();
fs::path getPlayerFile() const;

View File

@ -8,10 +8,11 @@
#include "../util/data_io.hpp"
#include <cstring>
#include <utility>
#define REGION_FORMAT_MAGIC ".VOXREG"
regfile::regfile(fs::path filename) : file(filename) {
regfile::regfile(fs::path filename) : file(std::move(filename)) {
if (file.length() < REGION_HEADER_SIZE)
throw std::runtime_error("incomplete region file header");
char header[REGION_HEADER_SIZE];
@ -49,17 +50,12 @@ std::unique_ptr<ubyte[]> regfile::read(int index, uint32_t& length) {
return data;
}
WorldRegion::WorldRegion() {
chunksData = new ubyte*[REGION_CHUNKS_COUNT]{};
sizes = new uint32_t[REGION_CHUNKS_COUNT]{};
}
WorldRegion::WorldRegion()
: chunksData(std::make_unique<std::unique_ptr<ubyte[]>[]>(REGION_CHUNKS_COUNT)),
sizes(std::make_unique<uint32_t[]>(REGION_CHUNKS_COUNT))
{}
WorldRegion::~WorldRegion() {
for (uint i = 0; i < REGION_CHUNKS_COUNT; i++) {
delete[] chunksData[i];
}
delete[] sizes;
delete[] chunksData;
}
void WorldRegion::setUnsaved(bool unsaved) {
@ -69,30 +65,29 @@ bool WorldRegion::isUnsaved() const {
return unsaved;
}
ubyte** WorldRegion::getChunks() const {
return chunksData;
std::unique_ptr<ubyte[]>* WorldRegion::getChunks() const {
return chunksData.get();
}
uint32_t* WorldRegion::getSizes() const {
return sizes;
return sizes.get();
}
void WorldRegion::put(uint x, uint z, ubyte* data, uint32_t size) {
size_t chunk_index = z * REGION_SIZE + x;
delete[] chunksData[chunk_index];
chunksData[chunk_index] = data;
chunksData[chunk_index].reset(data);
sizes[chunk_index] = size;
}
ubyte* WorldRegion::getChunkData(uint x, uint z) {
return chunksData[z * REGION_SIZE + x];
return chunksData[z * REGION_SIZE + x].get();
}
uint WorldRegion::getChunkDataSize(uint x, uint z) {
return sizes[z * REGION_SIZE + x];
}
WorldRegions::WorldRegions(fs::path directory) : directory(directory) {
WorldRegions::WorldRegions(const fs::path& directory) : directory(directory) {
for (uint i = 0; i < sizeof(layers)/sizeof(RegionsLayer); i++) {
layers[i].layer = i;
}
@ -108,19 +103,21 @@ WorldRegion* WorldRegions::getRegion(int x, int z, int layer) {
RegionsLayer& regions = layers[layer];
std::lock_guard lock(regions.mutex);
auto found = regions.regions.find(glm::ivec2(x, z));
if (found == regions.regions.end())
if (found == regions.regions.end()) {
return nullptr;
}
return found->second.get();
}
WorldRegion* WorldRegions::getOrCreateRegion(int x, int z, int layer) {
WorldRegion* region = getRegion(x, z, layer);
if (region == nullptr) {
RegionsLayer& regions = layers[layer];
std::lock_guard lock(regions.mutex);
region = new WorldRegion();
regions.regions[glm::ivec2(x, z)].reset(region);
if (auto region = getRegion(x, z, layer)) {
return region;
}
RegionsLayer& regions = layers[layer];
std::lock_guard lock(regions.mutex);
auto region_ptr = std::make_unique<WorldRegion>();
auto region = region_ptr.get();
regions.regions[{x, z}] = std::move(region_ptr);
return region;
}
@ -152,10 +149,7 @@ inline void calc_reg_coords(
}
std::unique_ptr<ubyte[]> WorldRegions::readChunkData(
int x,
int z,
uint32_t& length,
regfile* rfile
int x, int z, uint32_t& length, regfile* rfile
){
int regionX, regionZ, localX, localZ;
calc_reg_coords(x, z, regionX, regionZ, localX, localZ);
@ -165,14 +159,14 @@ std::unique_ptr<ubyte[]> WorldRegions::readChunkData(
/// @brief Read missing chunks data (null pointers) from region file
void WorldRegions::fetchChunks(WorldRegion* region, int x, int z, regfile* file) {
ubyte** chunks = region->getChunks();
auto* chunks = region->getChunks();
uint32_t* sizes = region->getSizes();
for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) {
int chunk_x = (i % REGION_SIZE) + x * REGION_SIZE;
int chunk_z = (i / REGION_SIZE) + z * REGION_SIZE;
if (chunks[i] == nullptr) {
chunks[i] = readChunkData(chunk_x, chunk_z, sizes[i], file).release();
chunks[i] = readChunkData(chunk_x, chunk_z, sizes[i], file);
}
}
}
@ -205,13 +199,10 @@ ubyte* WorldRegions::getData(
return nullptr;
}
std::shared_ptr<regfile> WorldRegions::useRegFile(glm::ivec3 coord) {
regfile_ptr WorldRegions::useRegFile(glm::ivec3 coord) {
auto* file = openRegFiles[coord].get();
file->inUse = true;
return std::shared_ptr<regfile>(file, [this](regfile* ptr) {
ptr->inUse = false;
regFilesCv.notify_one();
});
return regfile_ptr(file, &regFilesCv);
}
void WorldRegions::closeRegFile(glm::ivec3 coord) {
@ -220,7 +211,7 @@ void WorldRegions::closeRegFile(glm::ivec3 coord) {
}
// Marks regfile as used and unmarks when shared_ptr dies
std::shared_ptr<regfile> WorldRegions::getRegFile(glm::ivec3 coord, bool create) {
regfile_ptr WorldRegions::getRegFile(glm::ivec3 coord, bool create) {
{
std::lock_guard lock(regFilesMutex);
const auto found = openRegFiles.find(coord);
@ -237,7 +228,7 @@ std::shared_ptr<regfile> WorldRegions::getRegFile(glm::ivec3 coord, bool create)
return nullptr;
}
std::shared_ptr<regfile> WorldRegions::createRegFile(glm::ivec3 coord) {
regfile_ptr WorldRegions::createRegFile(glm::ivec3 coord) {
fs::path file = layers[coord[2]].folder/getRegionFilename(coord[0], coord[1]);
if (!fs::exists(file)) {
return nullptr;
@ -281,6 +272,7 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){
fetchChunks(entry, x, z, regfile.get());
std::lock_guard lock(regFilesMutex);
regfile.reset();
closeRegFile(regcoord);
}
@ -294,18 +286,18 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){
char intbuf[4]{};
uint offsets[REGION_CHUNKS_COUNT]{};
ubyte** region = entry->getChunks();
auto* region = entry->getChunks();
uint32_t* sizes = entry->getSizes();
for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) {
ubyte* chunk = region[i];
ubyte* chunk = region[i].get();
if (chunk == nullptr){
offsets[i] = 0;
} else {
offsets[i] = offset;
size_t compressedSize = sizes[i];
dataio::write_int32_big(compressedSize, (ubyte*)intbuf, 0);
dataio::write_int32_big(compressedSize, reinterpret_cast<ubyte*>(intbuf), 0);
offset += 4 + compressedSize;
file.write(intbuf, 4);
@ -313,7 +305,7 @@ void WorldRegions::writeRegion(int x, int z, int layer, WorldRegion* entry){
}
}
for (size_t i = 0; i < REGION_CHUNKS_COUNT; i++) {
dataio::write_int32_big(offsets[i], (ubyte*)intbuf, 0);
dataio::write_int32_big(offsets[i], reinterpret_cast<ubyte*>(intbuf), 0);
file.write(intbuf, 4);
}
}
@ -357,15 +349,20 @@ static std::unique_ptr<ubyte[]> write_inventories(Chunk* chunk, uint& datasize)
auto datavec = builder.data();
datasize = builder.size();
auto data = std::make_unique<ubyte[]>(datasize);
for (uint i = 0; i < datasize; i++) {
data[i] = datavec[i];
}
std::memcpy(data.get(), datavec, datasize);
return data;
}
/// @brief Store chunk (voxels and lights) in region (existing or new)
/// @brief Store chunk data (voxels and lights) in region (existing or new)
void WorldRegions::put(Chunk* chunk){
assert(chunk != nullptr);
if (!chunk->flags.lighted) {
return;
}
bool lightsUnsaved = !chunk->flags.loadedLights && doWriteLights;
if (!chunk->flags.unsaved && !lightsUnsaved) {
return;
}
int regionX, regionZ, localX, localZ;
calc_reg_coords(chunk->x, chunk->z, regionX, regionZ, localX, localZ);
@ -408,11 +405,12 @@ std::unique_ptr<light_t[]> WorldRegions::getLights(int x, int z) {
}
chunk_inventories_map WorldRegions::fetchInventories(int x, int z) {
chunk_inventories_map inventories;
chunk_inventories_map meta;
uint32_t bytesSize;
const ubyte* data = getData(x, z, REGION_LAYER_INVENTORIES, bytesSize);
if (data == nullptr)
return inventories;
if (data == nullptr) {
return meta;
}
ByteReader reader(data, bytesSize);
int count = reader.getInt32();
for (int i = 0; i < count; i++) {
@ -422,12 +420,12 @@ chunk_inventories_map WorldRegions::fetchInventories(int x, int z) {
reader.skip(size);
auto inv = std::make_shared<Inventory>(0, 0);
inv->deserialize(map.get());
inventories[index] = inv;
meta[index] = inv;
}
return inventories;
return meta;
}
void WorldRegions::processRegionVoxels(int x, int z, regionproc func) {
void WorldRegions::processRegionVoxels(int x, int z, const regionproc& func) {
if (getRegion(x, z, REGION_LAYER_VOXELS)) {
throw std::runtime_error("not implemented for in-memory regions");
}
@ -465,8 +463,9 @@ void WorldRegions::write() {
bool WorldRegions::parseRegionFilename(const std::string& name, int& x, int& z) {
size_t sep = name.find('_');
if (sep == std::string::npos || sep == 0 || sep == name.length()-1)
if (sep == std::string::npos || sep == 0 || sep == name.length()-1) {
return false;
}
try {
x = std::stoi(name.substr(0, sep));
z = std::stoi(name.substr(sep+1));

View File

@ -38,8 +38,8 @@ public:
};
class WorldRegion {
ubyte** chunksData;
uint32_t* sizes;
std::unique_ptr<std::unique_ptr<ubyte[]>[]> chunksData;
std::unique_ptr<uint32_t[]> sizes;
bool unsaved = false;
public:
WorldRegion();
@ -52,7 +52,7 @@ public:
void setUnsaved(bool unsaved);
bool isUnsaved() const;
ubyte** getChunks() const;
std::unique_ptr<ubyte[]>* getChunks() const;
uint32_t* getSizes() const;
};
@ -77,6 +77,43 @@ struct RegionsLayer {
std::mutex mutex;
};
class regfile_ptr {
regfile* file;
std::condition_variable* cv;
public:
regfile_ptr(
regfile* file,
std::condition_variable* cv
) : file(file), cv(cv) {}
regfile_ptr(const regfile_ptr&) = delete;
regfile_ptr(std::nullptr_t) : file(nullptr), cv(nullptr) {}
bool operator==(std::nullptr_t) const {
return file == nullptr;
}
bool operator!=(std::nullptr_t) const {
return file != nullptr;
}
operator bool() const {
return file != nullptr;
}
~regfile_ptr() {
reset();
}
regfile* get() {
return file;
}
void reset() {
if (file) {
file->inUse = false;
cv->notify_one();
file = nullptr;
}
}
};
class WorldRegions {
fs::path directory;
std::unordered_map<glm::ivec3, std::unique_ptr<regfile>> openRegFiles;
@ -110,10 +147,10 @@ class WorldRegions {
ubyte* getData(int x, int z, int layer, uint32_t& size);
std::shared_ptr<regfile> getRegFile(glm::ivec3 coord, bool create=true);
regfile_ptr getRegFile(glm::ivec3 coord, bool create=true);
void closeRegFile(glm::ivec3 coord);
std::shared_ptr<regfile> useRegFile(glm::ivec3 coord);
std::shared_ptr<regfile> createRegFile(glm::ivec3 coord);
regfile_ptr useRegFile(glm::ivec3 coord);
regfile_ptr createRegFile(glm::ivec3 coord);
fs::path getRegionFilename(int x, int y) const;
@ -128,7 +165,7 @@ public:
bool generatorTestMode = false;
bool doWriteLights = true;
WorldRegions(fs::path directory);
WorldRegions(const fs::path& directory);
WorldRegions(const WorldRegions&) = delete;
~WorldRegions();
@ -148,7 +185,7 @@ public:
std::unique_ptr<light_t[]> getLights(int x, int z);
chunk_inventories_map fetchInventories(int x, int z);
void processRegionVoxels(int x, int z, regionproc func);
void processRegionVoxels(int x, int z, const regionproc& func);
fs::path getRegionsFolder(int layer) const;

View File

@ -4,15 +4,24 @@
#include <sstream>
#include <filesystem>
#include <algorithm>
#include <utility>
#include "../util/stringutil.hpp"
#include "../typedefs.hpp"
#include "WorldFiles.hpp"
const fs::path SCREENSHOTS_FOLDER {"screenshots"};
const fs::path CONTENT_FOLDER {"content"};
const fs::path CONTROLS_FILE {"controls.toml"};
const fs::path SETTINGS_FILE {"settings.toml"};
void EnginePaths::prepare() {
fs::path contentFolder = userfiles/fs::path(CONTENT_FOLDER);
if (!fs::is_directory(contentFolder)) {
fs::create_directories(contentFolder);
}
}
fs::path EnginePaths::getUserfiles() const {
return userfiles;
}
@ -21,7 +30,7 @@ fs::path EnginePaths::getResources() const {
return resources;
}
fs::path EnginePaths::getScreenshotFile(std::string ext) {
fs::path EnginePaths::getScreenshotFile(const std::string& ext) {
fs::path folder = userfiles/fs::path(SCREENSHOTS_FOLDER);
if (!fs::is_directory(folder)) {
fs::create_directory(folder);
@ -60,10 +69,6 @@ fs::path EnginePaths::getControlsFile() {
return userfiles/fs::path(CONTROLS_FILE);
}
fs::path EnginePaths::getControlsFileOld() {
return userfiles/fs::path("controls.json");
}
fs::path EnginePaths::getSettingsFile() {
return userfiles/fs::path(SETTINGS_FILE);
}
@ -75,11 +80,11 @@ std::vector<fs::path> EnginePaths::scanForWorlds() {
if (!fs::is_directory(folder))
return folders;
for (auto entry : fs::directory_iterator(folder)) {
for (const auto& entry : fs::directory_iterator(folder)) {
if (!entry.is_directory()) {
continue;
}
fs::path worldFolder = entry.path();
const fs::path& worldFolder = entry.path();
fs::path worldFile = worldFolder/fs::u8path(WorldFiles::WORLD_FILE);
if (!fs::is_regular_file(worldFile)) {
continue;
@ -94,20 +99,20 @@ std::vector<fs::path> EnginePaths::scanForWorlds() {
return folders;
}
bool EnginePaths::isWorldNameUsed(std::string name) {
bool EnginePaths::isWorldNameUsed(const std::string& name) {
return fs::exists(EnginePaths::getWorldsFolder()/fs::u8path(name));
}
void EnginePaths::setUserfiles(fs::path folder) {
this->userfiles = folder;
this->userfiles = std::move(folder);
}
void EnginePaths::setResources(fs::path folder) {
this->resources = folder;
this->resources = std::move(folder);
}
void EnginePaths::setWorldFolder(fs::path folder) {
this->worldFolder = folder;
this->worldFolder = std::move(folder);
}
void EnginePaths::setContentPacks(std::vector<ContentPack>* contentPacks) {
@ -139,7 +144,7 @@ static fs::path toCanonic(fs::path path) {
return path;
}
fs::path EnginePaths::resolve(std::string path, bool throwErr) {
fs::path EnginePaths::resolve(const std::string& path, bool throwErr) {
size_t separator = path.find(':');
if (separator == std::string::npos) {
throw files_access_error("no entry point specified");
@ -172,7 +177,7 @@ fs::path EnginePaths::resolve(std::string path, bool throwErr) {
}
ResPaths::ResPaths(fs::path mainRoot, std::vector<PathsRoot> roots)
: mainRoot(mainRoot), roots(roots) {
: mainRoot(std::move(mainRoot)), roots(std::move(roots)) {
}
fs::path ResPaths::find(const std::string& filename) const {

View File

@ -21,17 +21,18 @@ class EnginePaths {
fs::path worldFolder;
std::vector<ContentPack>* contentPacks = nullptr;
public:
void prepare();
fs::path getUserfiles() const;
fs::path getResources() const;
fs::path getScreenshotFile(std::string ext);
fs::path getScreenshotFile(const std::string& ext);
fs::path getWorldsFolder();
fs::path getWorldFolder();
fs::path getWorldFolder(const std::string& name);
fs::path getControlsFile();
fs::path getControlsFileOld(); // TODO: remove in 0.22
fs::path getSettingsFile();
bool isWorldNameUsed(std::string name);
bool isWorldNameUsed(const std::string& name);
void setUserfiles(fs::path folder);
void setResources(fs::path folder);
@ -40,7 +41,7 @@ public:
std::vector<fs::path> scanForWorlds();
fs::path resolve(std::string path, bool throwErr=true);
fs::path resolve(const std::string& path, bool throwErr=true);
};
struct PathsRoot {

View File

@ -15,7 +15,7 @@
namespace fs = std::filesystem;
files::rafile::rafile(fs::path filename)
files::rafile::rafile(const fs::path& filename)
: file(filename, std::ios::binary | std::ios::ate) {
if (!file) {
throw std::runtime_error("could not to open file "+filename.string());
@ -36,7 +36,7 @@ void files::rafile::read(char* buffer, std::streamsize size) {
file.read(buffer, size);
}
bool files::write_bytes(fs::path filename, const ubyte* data, size_t size) {
bool files::write_bytes(const fs::path& filename, const ubyte* data, size_t size) {
std::ofstream output(filename, std::ios::binary);
if (!output.is_open())
return false;
@ -45,7 +45,7 @@ bool files::write_bytes(fs::path filename, const ubyte* data, size_t size) {
return true;
}
uint files::append_bytes(fs::path filename, const ubyte* data, size_t size) {
uint files::append_bytes(const fs::path& filename, const ubyte* data, size_t size) {
std::ofstream output(filename, std::ios::binary | std::ios::app);
if (!output.is_open())
return 0;
@ -55,7 +55,7 @@ uint files::append_bytes(fs::path filename, const ubyte* data, size_t size) {
return position;
}
bool files::read(fs::path filename, char* data, size_t size) {
bool files::read(const fs::path& filename, char* data, size_t size) {
std::ifstream output(filename, std::ios::binary);
if (!output.is_open())
return false;
@ -64,7 +64,7 @@ bool files::read(fs::path filename, char* data, size_t size) {
return true;
}
std::unique_ptr<ubyte[]> files::read_bytes(fs::path filename, size_t& length) {
std::unique_ptr<ubyte[]> files::read_bytes(const fs::path& filename, size_t& length) {
std::ifstream input(filename, std::ios::binary);
if (!input.is_open())
return nullptr;
@ -78,7 +78,7 @@ std::unique_ptr<ubyte[]> files::read_bytes(fs::path filename, size_t& length) {
return data;
}
std::string files::read_string(fs::path filename) {
std::string files::read_string(const fs::path& filename) {
size_t size;
std::unique_ptr<ubyte[]> bytes (read_bytes(filename, size));
if (bytes == nullptr) {
@ -88,7 +88,7 @@ std::string files::read_string(fs::path filename) {
return std::string((const char*)bytes.get(), size);
}
bool files::write_string(fs::path filename, const std::string content) {
bool files::write_string(const fs::path& filename, const std::string content) {
std::ofstream file(filename);
if (!file) {
return false;
@ -97,16 +97,16 @@ bool files::write_string(fs::path filename, const std::string content) {
return true;
}
bool files::write_json(fs::path filename, const dynamic::Map* obj, bool nice) {
bool files::write_json(const fs::path& filename, const dynamic::Map* obj, bool nice) {
return files::write_string(filename, json::stringify(obj, nice, " "));
}
bool files::write_binary_json(fs::path filename, const dynamic::Map* obj, bool compression) {
bool files::write_binary_json(const fs::path& filename, const dynamic::Map* obj, bool compression) {
auto bytes = json::to_binary(obj, compression);
return files::write_bytes(filename, bytes.data(), bytes.size());
}
std::shared_ptr<dynamic::Map> files::read_json(fs::path filename) {
std::shared_ptr<dynamic::Map> files::read_json(const fs::path& filename) {
std::string text = files::read_string(filename);
try {
return json::parse(filename.string(), text);;
@ -116,17 +116,17 @@ std::shared_ptr<dynamic::Map> files::read_json(fs::path filename) {
}
}
std::shared_ptr<dynamic::Map> files::read_binary_json(fs::path file) {
std::shared_ptr<dynamic::Map> files::read_binary_json(const fs::path& file) {
size_t size;
std::unique_ptr<ubyte[]> bytes (files::read_bytes(file, size));
return json::from_binary(bytes.get(), size);
}
std::shared_ptr<dynamic::Map> files::read_toml(fs::path file) {
std::shared_ptr<dynamic::Map> files::read_toml(const fs::path& file) {
return toml::parse(file.u8string(), files::read_string(file));
}
std::vector<std::string> files::read_list(fs::path filename) {
std::vector<std::string> files::read_list(const fs::path& filename) {
std::ifstream file(filename);
if (!file) {
throw std::runtime_error("could not to open file "+filename.u8string());

View File

@ -20,7 +20,7 @@ namespace files {
std::ifstream file;
size_t filelength;
public:
rafile(fs::path filename);
rafile(const fs::path& filename);
void seekg(std::streampos pos);
void read(char* buffer, std::streamsize size);
@ -31,40 +31,40 @@ namespace files {
/// @param file target file
/// @param data data bytes array
/// @param size size of data bytes array
bool write_bytes(fs::path file, const ubyte* data, size_t size);
bool write_bytes(const fs::path& file, const ubyte* data, size_t size);
/// @brief Append bytes array to the file without any extra data
/// @param file target file
/// @param data data bytes array
/// @param size size of data bytes array
uint append_bytes(fs::path file, const ubyte* data, size_t size);
uint append_bytes(const fs::path& file, const ubyte* data, size_t size);
/// @brief Write string to the file
bool write_string(fs::path filename, const std::string content);
bool write_string(const fs::path& filename, const std::string content);
/// @brief Write dynamic data to the JSON file
/// @param nice if true, human readable format will be used, otherwise minimal
bool write_json(fs::path filename, const dynamic::Map* obj, bool nice=true);
bool write_json(const fs::path& filename, const dynamic::Map* obj, bool nice=true);
/// @brief Write dynamic data to the binary JSON file
/// (see src/coders/binary_json_spec.md)
/// @param compressed use gzip compression
bool write_binary_json(
fs::path filename,
const fs::path& filename,
const dynamic::Map* obj,
bool compressed=false
);
bool read(fs::path, char* data, size_t size);
std::unique_ptr<ubyte[]> read_bytes(fs::path, size_t& length);
std::string read_string(fs::path filename);
bool read(const fs::path&, char* data, size_t size);
std::unique_ptr<ubyte[]> read_bytes(const fs::path&, size_t& length);
std::string read_string(const fs::path& filename);
/// @brief Read JSON or BJSON file
/// @param file *.json or *.bjson file
std::shared_ptr<dynamic::Map> read_json(fs::path file);
std::shared_ptr<dynamic::Map> read_binary_json(fs::path file);
std::shared_ptr<dynamic::Map> read_toml(fs::path file);
std::vector<std::string> read_list(fs::path file);
std::shared_ptr<dynamic::Map> read_json(const fs::path& file);
std::shared_ptr<dynamic::Map> read_binary_json(const fs::path& file);
std::shared_ptr<dynamic::Map> read_toml(const fs::path& file);
std::vector<std::string> read_list(const fs::path& file);
}
#endif /* FILES_FILES_HPP_ */

Some files were not shown because too many files have changed in this diff Show More