add 'config' entry point, pack.shared_file(...) & refactor engine_paths.cpp

This commit is contained in:
MihailRis 2024-10-04 22:40:05 +03:00
parent 85bea6f17d
commit 15342c2df2
7 changed files with 102 additions and 42 deletions

View File

@ -19,7 +19,8 @@ Content pack identifier requirements:
### Content packs data ### Content packs data
Settings and other state that supposed to be saved with a world, must be stored in `world:data/pack_id/`. The path should be retrieved by calling a function: State that supposed to be saved with a world, must be stored in `world:data/pack_id/`. The path should be retrieved by calling a function:
```lua ```lua
local path = pack.data_file(PACK_ID, "file_name") local path = pack.data_file(PACK_ID, "file_name")
file.write(path, some_data) file.write(path, some_data)
@ -29,3 +30,13 @@ PACK_ID is an existing variable containing current content-pack name.
Directory `world:data/PACK_ID` will be created on call `pack.data_file(...)`. Directory `world:data/PACK_ID` will be created on call `pack.data_file(...)`.
#### Shared data
Settings and other data that should be accessible from all worlds where the pack is used should be in
`config:pack_id/`. You can use a special function:
```lua
local path = pack.shared_file(PACK_ID, "file_name")
file.write(path, data)
-- writes data to the file config:PACK_ID/file_name
```

View File

@ -47,14 +47,38 @@ pack.is_installed(packid: str) -> bool
Check if specified pack is installed in the world Check if specified pack is installed in the world
```python ```lua
pack.data_file(packid: str, filename: str) -> str pack.data_file(packid: str, filename: str) -> str
-- and
pack.shared_file(packid: str, filename: str) -> str
``` ```
Returns data file path like `world:data/packid/filename` Returns the path to the data file
and creates missing directories. and creates missing directories in the path.
Use this function when saving pack settings or other data to the world. - The first option returns: `world:data/packid/filename`
- The second option returns: `config:packid/filename`
Examples:
```lua
file.write(pack.data_file(PACK_ID, "example.txt"), text)
```
For a *containermod* pack, write text to `world:data/containermod/example.txt`.
Use this to store in-world data.
```lua
file.write(pack.shared_file(PACK_ID, "example.txt"), text)
```
For a *containermod* pack, write text to `config:containermod/example.txt`
Use this to store shared data for all worlds.
```python
pack.get_folder(packid: str) -> str
```
Returns the path to the folder of the installed content pack.
Example: Example:
```lua ```lua

View File

@ -19,7 +19,9 @@
### Данные контент-паков ### Данные контент-паков
Настройки, состояние, которое нужно сохранять в мире, должны находиться в `world:data/id_пака/`. Путь следует получать через специальную функцию: #### Данные в мире
Состояние, которое нужно сохранять в мире, должны находиться в `world:data/id_пака/`. Путь следует получать через специальную функцию:
```lua ```lua
local path = pack.data_file(PACK_ID, "имя_файла") local path = pack.data_file(PACK_ID, "имя_файла")
file.write(path, данные) file.write(path, данные)
@ -27,4 +29,15 @@ file.write(path, данные)
``` ```
Здесь PACK_ID является доступной константой, т.е не нужно вписывать имя пака самостоятельно. Здесь PACK_ID является доступной константой, т.е не нужно вписывать имя пака самостоятельно.
Папка `world:data/PACK_ID` будет создана при вызове `pack.data_file`. Папка `world:data/PACK_ID` будет создана при вызове `pack.data_file`.
#### Общие данные
Настройки и иные данные, что должны быть доступны из всех миров, где используется пак, должны находиться в
`config:id_пака/`. Можно использовать специальную функцию:
```lua
local path = pack.shared_file(PACK_ID, "имя_файла")
file.write(path, данные)
-- запишет данные в файл config:PACK_ID/имя_файла
```

View File

@ -44,20 +44,32 @@ pack.is_installed(packid: str) -> bool
Проверяет наличие установленного пака в мире Проверяет наличие установленного пака в мире
```python ```lua
pack.data_file(packid: str, filename: str) -> str pack.data_file(packid: str, filename: str) -> str
-- и
pack.shared_file(packid: str, filename: str) -> str
``` ```
Возвращает путь к файлу данных по типу: `world:data/packid/filename` Возвращает путь к файлу данных
и создает недостающие директории в пути. и создает недостающие директории в пути.
Используйте эту функцию при сохранении настроек пака или иных данных в мире. - Первый вариант возвращает: `world:data/packid/filename`
- Второй вариант возвращает: `config:packid/filename`
Пример: Примеры:
```lua ```lua
file.write(pack.data_file(PACK_ID, "example.txt"), text) file.write(pack.data_file(PACK_ID, "example.txt"), text)
``` ```
Для пака *containermod* запишет текст в файл `world:data/containermod/example.txt` Для пака *containermod* запишет текст в файл `world:data/containermod/example.txt`.
Используйте для хранения данных в мире.
```lua
file.write(pack.shared_file(PACK_ID, "example.txt"), text)
```
Для пака *containermod* запишет текст в файл `config:containermod/example.txt`
Используйте для хранения данныхm общих для всех миров.
```python ```python
pack.get_folder(packid: str) -> str pack.get_folder(packid: str) -> str

View File

@ -101,6 +101,11 @@ function pack.data_file(packid, name)
return "world:data/"..packid.."/"..name return "world:data/"..packid.."/"..name
end end
function pack.shared_file(packid, name)
file.mkdirs("config:"..packid)
return "config:"..packid.."/"..name
end
-- events -- events
events = { events = {
handlers = {} handlers = {}

View File

@ -11,23 +11,12 @@
#include "WorldFiles.hpp" #include "WorldFiles.hpp"
static inline auto SCREENSHOTS_FOLDER = std::filesystem::u8path("screenshots");
/// @brief ENUM for accessing folder and file names static inline auto CONTENT_FOLDER = std::filesystem::u8path("content");
enum F_F_NAME { static inline auto WORLDS_FOLDER = std::filesystem::u8path("worlds");
SCREENSHOTS_FOLDER, static inline auto CONFIG_FOLDER = std::filesystem::u8path("config");
CONTENT_FOLDER, static inline auto CONTROLS_FILE = std::filesystem::u8path("controls.toml");
CONTROLS_FILE, static inline auto SETTINGS_FILE = std::filesystem::u8path("settings.toml");
SETTINGS_FILE,
COUNT
};
/// @brief array for get file or folder name by enum `F_F_NAME`
///
/// example:
/// `std::filesystem::path settings = f_f_names[SETTINGS_FILE];`
static std::array<std::string, F_F_NAME::COUNT> f_f_names {
"screenshots", "content", "controls.toml", "settings.toml"};
static std::filesystem::path toCanonic(std::filesystem::path path) { static std::filesystem::path toCanonic(std::filesystem::path path) {
std::stack<std::string> parts; std::stack<std::string> parts;
@ -55,8 +44,7 @@ static std::filesystem::path toCanonic(std::filesystem::path path) {
} }
void EnginePaths::prepare() { void EnginePaths::prepare() {
auto contentFolder = auto contentFolder = userFilesFolder / CONTENT_FOLDER;
userFilesFolder / std::filesystem::path(f_f_names[CONTENT_FOLDER]);
if (!fs::is_directory(contentFolder)) { if (!fs::is_directory(contentFolder)) {
fs::create_directories(contentFolder); fs::create_directories(contentFolder);
} }
@ -71,8 +59,7 @@ std::filesystem::path EnginePaths::getResourcesFolder() const {
} }
std::filesystem::path EnginePaths::getNewScreenshotFile(const std::string& ext) { std::filesystem::path EnginePaths::getNewScreenshotFile(const std::string& ext) {
auto folder = auto folder = userFilesFolder / SCREENSHOTS_FOLDER;
userFilesFolder / std::filesystem::path(f_f_names[SCREENSHOTS_FOLDER]);
if (!fs::is_directory(folder)) { if (!fs::is_directory(folder)) {
fs::create_directory(folder); fs::create_directory(folder);
} }
@ -97,8 +84,12 @@ std::filesystem::path EnginePaths::getNewScreenshotFile(const std::string& ext)
return filename; return filename;
} }
std::filesystem::path EnginePaths::getWorldsFolder() { std::filesystem::path EnginePaths::getWorldsFolder() const {
return userFilesFolder / std::filesystem::path("worlds"); return userFilesFolder / WORLDS_FOLDER;
}
std::filesystem::path EnginePaths::getConfigFolder() const {
return userFilesFolder / CONFIG_FOLDER;
} }
std::filesystem::path EnginePaths::getCurrentWorldFolder() { std::filesystem::path EnginePaths::getCurrentWorldFolder() {
@ -109,12 +100,12 @@ std::filesystem::path EnginePaths::getWorldFolderByName(const std::string& name)
return getWorldsFolder() / std::filesystem::path(name); return getWorldsFolder() / std::filesystem::path(name);
} }
std::filesystem::path EnginePaths::getControlsFile() { std::filesystem::path EnginePaths::getControlsFile() const {
return userFilesFolder / std::filesystem::path(f_f_names[CONTROLS_FILE]); return userFilesFolder / CONTROLS_FILE;
} }
std::filesystem::path EnginePaths::getSettingsFile() { std::filesystem::path EnginePaths::getSettingsFile() const {
return userFilesFolder / std::filesystem::path(f_f_names[SETTINGS_FILE]); return userFilesFolder / SETTINGS_FILE;
} }
std::vector<std::filesystem::path> EnginePaths::scanForWorlds() { std::vector<std::filesystem::path> EnginePaths::scanForWorlds() {
@ -179,6 +170,9 @@ std::filesystem::path EnginePaths::resolve(
if (prefix == "user") { if (prefix == "user") {
return userFilesFolder / fs::u8path(filename); return userFilesFolder / fs::u8path(filename);
} }
if (prefix == "config") {
return getConfigFolder() / fs::u8path(filename);
}
if (prefix == "world") { if (prefix == "world") {
return currentWorldFolder / fs::u8path(filename); return currentWorldFolder / fs::u8path(filename);
} }

View File

@ -24,15 +24,16 @@ public:
void setResourcesFolder(std::filesystem::path folder); void setResourcesFolder(std::filesystem::path folder);
std::filesystem::path getResourcesFolder() const; std::filesystem::path getResourcesFolder() const;
std::filesystem::path getWorldsFolder();
std::filesystem::path getWorldFolderByName(const std::string& name); std::filesystem::path getWorldFolderByName(const std::string& name);
std::filesystem::path getWorldsFolder() const;
std::filesystem::path getConfigFolder() const;
void setCurrentWorldFolder(std::filesystem::path folder); void setCurrentWorldFolder(std::filesystem::path folder);
std::filesystem::path getCurrentWorldFolder(); std::filesystem::path getCurrentWorldFolder();
std::filesystem::path getNewScreenshotFile(const std::string& ext); std::filesystem::path getNewScreenshotFile(const std::string& ext);
std::filesystem::path getControlsFile(); std::filesystem::path getControlsFile() const;
std::filesystem::path getSettingsFile(); std::filesystem::path getSettingsFile() const;
void setContentPacks(std::vector<ContentPack>* contentPacks); void setContentPacks(std::vector<ContentPack>* contentPacks);