mirror of
https://github.com/MaSzyna-EU07/maszyna.git
synced 2026-11-19 02:56:01 +01:00
Merge branch 'master' into feat/renderers-cleanup
This commit is contained in:
905
scripting/luaprogram.cpp
Normal file
905
scripting/luaprogram.cpp
Normal file
@@ -0,0 +1,905 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
// the Lua screens: scripts run by LuaJIT, each screen in a state of its own, with the eu07 table of
|
||||
// script_screens_doc.md. the state has no io, os, ffi, debug or require, reads files only through eu07 and below the
|
||||
// script's folder, takes no precompiled code, and runs without the JIT compiler, so that the instruction count hook
|
||||
// can stop a script stuck in a loop (LuaJIT calls no hooks in compiled code)
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "scripting/scriptscreenprogram.h"
|
||||
#include "scripting/scriptscreendrawing.h"
|
||||
#include "scripting/scriptscreenkernels.h"
|
||||
|
||||
#include "utilities/Logs.h"
|
||||
#include "utilities/dictionary.h"
|
||||
#include "utilities/utilities.h"
|
||||
|
||||
#include "stb/stb_image.h"
|
||||
|
||||
#include <lua.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <new>
|
||||
#include <string_view>
|
||||
|
||||
namespace script_screens
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
constexpr int hook_interval{1000};
|
||||
constexpr char const *image_metatable{"eu07.image"};
|
||||
constexpr char const *font_metatable{"eu07.font"};
|
||||
constexpr char const *sprite_metatable{"eu07.sprite"};
|
||||
// the address is the key of the program in the registry of its state
|
||||
constexpr char program_key{0};
|
||||
|
||||
class lua_program final : public program
|
||||
{
|
||||
public:
|
||||
lua_program(std::string const &Script, script_screen_kind const Kind) : kind{Kind}, script{Script}, folder{substr_path(Script)} {}
|
||||
~lua_program() override
|
||||
{
|
||||
if (m_state != nullptr)
|
||||
{
|
||||
lua_close(m_state);
|
||||
}
|
||||
}
|
||||
lua_program(lua_program const &) = delete;
|
||||
lua_program &operator=(lua_program const &) = delete;
|
||||
|
||||
bool start();
|
||||
bool render(render_call &Call) override;
|
||||
|
||||
script_screen_kind const kind;
|
||||
std::string const script;
|
||||
std::string const folder;
|
||||
render_call *call{nullptr}; // the refresh in progress
|
||||
bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged
|
||||
std::int64_t budget{0}; // instructions left to the call in progress
|
||||
|
||||
private:
|
||||
// calls what's on the stack, with the instruction limit. logs a failure
|
||||
bool run(int Arguments, int Results, std::string_view What);
|
||||
void open_libraries();
|
||||
void register_api();
|
||||
|
||||
lua_State *m_state{nullptr};
|
||||
int m_screen{LUA_NOREF}; // the table the script returned
|
||||
};
|
||||
|
||||
lua_program *program_of(lua_State *L)
|
||||
{
|
||||
lua_pushlightuserdata(L, const_cast<char *>(&program_key)); // NOSONAR: the address is only a key
|
||||
lua_rawget(L, LUA_REGISTRYINDEX);
|
||||
auto *self{static_cast<lua_program *>(lua_touserdata(L, -1))};
|
||||
lua_pop(L, 1);
|
||||
return self;
|
||||
}
|
||||
|
||||
void count_hook(lua_State *L, lua_Debug * /*Debug*/)
|
||||
{
|
||||
auto *self{program_of(L)};
|
||||
if (self == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self->budget -= hook_interval;
|
||||
if (self->budget < 0)
|
||||
{
|
||||
luaL_error(L, "instruction limit exceeded");
|
||||
}
|
||||
}
|
||||
|
||||
// objects of the api -------------------------------------------------------------------------------------------------
|
||||
|
||||
template <typename Type_> Type_ *push_object(lua_State *L, Type_ &&Object, char const *Metatable)
|
||||
{
|
||||
auto *memory{lua_newuserdata(L, sizeof(Type_))};
|
||||
auto *object{new (memory) Type_(std::move(Object))};
|
||||
luaL_getmetatable(L, Metatable);
|
||||
lua_setmetatable(L, -2);
|
||||
return object;
|
||||
}
|
||||
|
||||
template <typename Type_> int collect(lua_State *L)
|
||||
{
|
||||
static_cast<Type_ *>(lua_touserdata(L, 1))->~Type_();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// the object at the index when it has the metatable, otherwise nullptr
|
||||
template <typename Type_> Type_ *test_object(lua_State *L, int const Index, char const *Metatable)
|
||||
{
|
||||
auto *object{lua_touserdata(L, Index)};
|
||||
if (object == nullptr || 0 == lua_getmetatable(L, Index))
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
luaL_getmetatable(L, Metatable);
|
||||
auto const matches{lua_rawequal(L, -1, -2) != 0};
|
||||
lua_pop(L, 2);
|
||||
return matches ? static_cast<Type_ *>(object) : nullptr;
|
||||
}
|
||||
|
||||
template <typename Type_> Type_ &check_object(lua_State *L, int const Index, char const *Metatable)
|
||||
{
|
||||
auto *object{test_object<Type_>(L, Index, Metatable)};
|
||||
if (object == nullptr)
|
||||
{
|
||||
luaL_typerror(L, Index, Metatable);
|
||||
}
|
||||
return *object;
|
||||
}
|
||||
|
||||
// an image of a script: what was drawn on it, and the post-processing (image:led_post, image:resize) asked for and not
|
||||
// run yet. the steps of the image render returns run in the queue, on the gpu when the renderer can; the steps of an
|
||||
// image the script goes on to read or draw on (or with) run here, on the cpu, when it does
|
||||
struct lua_image
|
||||
{
|
||||
canvas drawn;
|
||||
std::vector<post_step> steps;
|
||||
|
||||
int width() const
|
||||
{
|
||||
auto result{drawn.width()};
|
||||
for (auto const &step : steps)
|
||||
{
|
||||
result = width_after(step, result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
int height() const
|
||||
{
|
||||
auto result{drawn.height()};
|
||||
for (auto const &step : steps)
|
||||
{
|
||||
result = height_after(step, result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// the image with its post-processing done
|
||||
canvas &done()
|
||||
{
|
||||
if (false == steps.empty())
|
||||
{
|
||||
post_image image{drawn.pixels(), drawn.width(), drawn.height()};
|
||||
// the sizes were checked when the steps were asked for
|
||||
apply_post(image, steps);
|
||||
drawn = canvas{image.width, image.height, std::move(image.pixels)};
|
||||
steps.clear();
|
||||
}
|
||||
return drawn;
|
||||
}
|
||||
// the image, a step further
|
||||
lua_image then(post_step const &Step) const
|
||||
{
|
||||
lua_image result{drawn, steps};
|
||||
result.steps.push_back(Step);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
lua_image &check_lua_image(lua_State *L, int const Index)
|
||||
{
|
||||
return check_object<lua_image>(L, Index, image_metatable);
|
||||
}
|
||||
|
||||
// the image, to read or draw on: its post-processing is done first
|
||||
canvas &check_image(lua_State *L, int const Index)
|
||||
{
|
||||
return check_lua_image(L, Index).done();
|
||||
}
|
||||
|
||||
int check_int(lua_State *L, int const Index)
|
||||
{
|
||||
return static_cast<int>(luaL_checkinteger(L, Index));
|
||||
}
|
||||
|
||||
int optional_int(lua_State *L, int const Index, int const Default)
|
||||
{
|
||||
return static_cast<int>(luaL_optinteger(L, Index, Default));
|
||||
}
|
||||
|
||||
// a colour: { r, g, b }, each 0-255
|
||||
rgb check_color(lua_State *L, int const Index)
|
||||
{
|
||||
luaL_checktype(L, Index, LUA_TTABLE);
|
||||
rgb color{};
|
||||
for (int channel = 0; channel < 3; ++channel)
|
||||
{
|
||||
lua_rawgeti(L, Index, channel + 1);
|
||||
if (0 == lua_isnumber(L, -1))
|
||||
{
|
||||
luaL_argerror(L, Index, "a colour is { r, g, b }");
|
||||
}
|
||||
color[channel] = static_cast<std::uint8_t>(std::clamp<lua_Integer>(lua_tointeger(L, -1), 0, 255));
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
std::string_view check_text(lua_State *L, int const Index)
|
||||
{
|
||||
std::size_t length{0};
|
||||
auto const *text{luaL_checklstring(L, Index, &length)};
|
||||
return {text, length};
|
||||
}
|
||||
|
||||
struct decoded_image
|
||||
{
|
||||
std::vector<std::uint8_t> pixels;
|
||||
int width{0};
|
||||
int height{0};
|
||||
};
|
||||
|
||||
// a .png of the screen's folder or below, as RGBA
|
||||
std::optional<decoded_image> read_png(std::string const &Folder, std::string_view const Path)
|
||||
{
|
||||
auto const file{read_screen_file(Folder, Path)};
|
||||
if (false == file.has_value())
|
||||
{
|
||||
return std::nullopt;
|
||||
}
|
||||
int width{0};
|
||||
int height{0};
|
||||
int channels{0};
|
||||
// the texture loader turns every image bottom row first, for all threads (model/Texture.cpp): fonts and sprites are
|
||||
// read top row first, as led_util reads them
|
||||
stbi_set_flip_vertically_on_load_thread(0);
|
||||
auto *pixels{stbi_load_from_memory(reinterpret_cast<stbi_uc const *>(file->data()), static_cast<int>(file->size()), &width, &height, &channels, 4)};
|
||||
if (pixels == nullptr)
|
||||
{
|
||||
return std::nullopt;
|
||||
}
|
||||
decoded_image result{std::vector<std::uint8_t>(pixels, pixels + image_size(width, height)), width, height};
|
||||
stbi_image_free(pixels);
|
||||
return result;
|
||||
}
|
||||
|
||||
// eu07 ---------------------------------------------------------------------------------------------------------------
|
||||
|
||||
// eu07.image(width, height [, color]): a new image, black or in the colour
|
||||
int api_image(lua_State *L)
|
||||
{
|
||||
auto const width{check_int(L, 1)};
|
||||
auto const height{check_int(L, 2)};
|
||||
luaL_argcheck(L, valid_image_side(width), 1, "between 1 and 4096");
|
||||
luaL_argcheck(L, valid_image_side(height), 2, "between 1 and 4096");
|
||||
auto const color{lua_isnoneornil(L, 3) ? rgb{0, 0, 0} : check_color(L, 3)};
|
||||
push_object(L, lua_image{canvas{width, height, color}, {}}, image_metatable);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// eu07.font(path): the font of path .. ".png" and path .. ".txt", below the script's folder
|
||||
int api_font(lua_State *L)
|
||||
{
|
||||
auto const path{check_text(L, 1)};
|
||||
auto const *self{program_of(L)};
|
||||
auto loaded{false};
|
||||
{
|
||||
auto const image{read_png(self->folder, std::string{path} + ".png")};
|
||||
auto const description{read_screen_file(self->folder, std::string{path} + ".txt")};
|
||||
if (image.has_value() && description.has_value())
|
||||
{
|
||||
if (auto font{bitmap_font::parse(image->pixels, image->width, image->height, *description)}; font.has_value())
|
||||
{
|
||||
push_object(L, std::move(*font), font_metatable);
|
||||
loaded = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (false == loaded)
|
||||
{
|
||||
return luaL_error(L, "font \"%s\" not found below the script's folder", lua_tostring(L, 1));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
// eu07.sprite(path): the sprite of path .. ".png", below the script's folder
|
||||
int api_sprite(lua_State *L)
|
||||
{
|
||||
auto const path{check_text(L, 1)};
|
||||
auto const *self{program_of(L)};
|
||||
auto loaded{false};
|
||||
{
|
||||
if (auto const image{read_png(self->folder, std::string{path} + ".png")}; image.has_value())
|
||||
{
|
||||
push_object(L, bitmap_font::sprite(image->pixels, image->width, image->height), sprite_metatable);
|
||||
loaded = true;
|
||||
}
|
||||
}
|
||||
if (false == loaded)
|
||||
{
|
||||
return luaL_error(L, "sprite \"%s\" not found below the script's folder", lua_tostring(L, 1));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
int api_time(lua_State *L)
|
||||
{
|
||||
lua_pushnumber(L, screen_time());
|
||||
return 1;
|
||||
}
|
||||
|
||||
// eu07.log(...): the values, joined with spaces, as print() does
|
||||
int api_log(lua_State *L)
|
||||
{
|
||||
auto const count{lua_gettop(L)};
|
||||
for (int idx = 1; idx <= count; ++idx)
|
||||
{
|
||||
if (idx > 1)
|
||||
{
|
||||
lua_pushliteral(L, " ");
|
||||
}
|
||||
lua_getglobal(L, "tostring");
|
||||
lua_pushvalue(L, idx);
|
||||
lua_call(L, 1, 1);
|
||||
}
|
||||
if (count == 0)
|
||||
{
|
||||
lua_pushliteral(L, "");
|
||||
}
|
||||
else
|
||||
{
|
||||
lua_concat(L, count * 2 - 1);
|
||||
}
|
||||
auto const *self{program_of(L)};
|
||||
auto const *text{lua_tostring(L, -1)};
|
||||
WriteLog(std::format("Lua screen \"{}\": {}", self->script, text != nullptr ? text : ""));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// eu07.command(name, param1, param2): sends a command to the vehicle of the cab
|
||||
int api_command(lua_State *L)
|
||||
{
|
||||
auto const name{check_text(L, 1)};
|
||||
auto const param1{optional_int(L, 2, 0)};
|
||||
auto const param2{optional_int(L, 3, 0)};
|
||||
auto *self{program_of(L)};
|
||||
if (self->call == nullptr)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
if (self->kind != script_screen_kind::cab)
|
||||
{
|
||||
if (false == self->commands_ignored)
|
||||
{
|
||||
self->commands_ignored = true;
|
||||
WriteLog(std::format("Lua screen \"{}\": commands are only taken from screens in the cab", self->script));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
self->call->commands.emplace_back(std::string{name}, param1, param2, self->call->vehicle);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// eu07.read_file(path): the contents of a file below the script's folder, or nil
|
||||
int api_read_file(lua_State *L)
|
||||
{
|
||||
auto const path{check_text(L, 1)};
|
||||
auto const *self{program_of(L)};
|
||||
if (auto const contents{read_screen_file(self->folder, path)}; contents.has_value())
|
||||
{
|
||||
lua_pushlstring(L, contents->data(), contents->size());
|
||||
}
|
||||
else
|
||||
{
|
||||
lua_pushnil(L);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
// loads a script as text: precompiled code is refused. leaves the chunk, or an error message, on the stack
|
||||
bool load_chunk(lua_State *L, std::string_view const Code, std::string const &Name)
|
||||
{
|
||||
if (false == Code.empty() && Code.front() == '\x1b')
|
||||
{
|
||||
lua_pushfstring(L, "%s: precompiled scripts aren't loaded", Name.c_str());
|
||||
return false;
|
||||
}
|
||||
return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t");
|
||||
}
|
||||
|
||||
// eu07.include(path): runs another script below the script's folder and returns what it returns
|
||||
int api_include(lua_State *L)
|
||||
{
|
||||
auto const path{check_text(L, 1)};
|
||||
auto const *self{program_of(L)};
|
||||
auto loaded{false};
|
||||
{
|
||||
if (auto const code{read_screen_file(self->folder, path)}; code.has_value())
|
||||
{
|
||||
loaded = load_chunk(L, *code, self->folder + std::string{path});
|
||||
}
|
||||
else
|
||||
{
|
||||
lua_pushfstring(L, "script \"%s\" not found below the script's folder", lua_tostring(L, 1));
|
||||
}
|
||||
}
|
||||
if (false == loaded)
|
||||
{
|
||||
return lua_error(L);
|
||||
}
|
||||
lua_call(L, 0, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// eu07.image methods -------------------------------------------------------------------------------------------------
|
||||
|
||||
int image_width(lua_State *L)
|
||||
{
|
||||
lua_pushinteger(L, check_lua_image(L, 1).width());
|
||||
return 1;
|
||||
}
|
||||
|
||||
int image_height(lua_State *L)
|
||||
{
|
||||
lua_pushinteger(L, check_lua_image(L, 1).height());
|
||||
return 1;
|
||||
}
|
||||
|
||||
int image_fill(lua_State *L)
|
||||
{
|
||||
auto &image{check_image(L, 1)};
|
||||
image.fill(check_color(L, 2));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int image_set(lua_State *L)
|
||||
{
|
||||
auto &image{check_image(L, 1)};
|
||||
auto const x{check_int(L, 2)};
|
||||
auto const y{check_int(L, 3)};
|
||||
image.set(x, y, check_color(L, 4));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int image_get(lua_State *L)
|
||||
{
|
||||
auto const &image{check_image(L, 1)};
|
||||
auto const color{image.get(check_int(L, 2), check_int(L, 3))};
|
||||
for (auto const channel : color)
|
||||
{
|
||||
lua_pushinteger(L, channel);
|
||||
}
|
||||
return 3;
|
||||
}
|
||||
|
||||
int image_fill_rect(lua_State *L)
|
||||
{
|
||||
auto &image{check_image(L, 1)};
|
||||
auto const x{check_int(L, 2)};
|
||||
auto const y{check_int(L, 3)};
|
||||
auto const width{check_int(L, 4)};
|
||||
auto const height{check_int(L, 5)};
|
||||
image.fill_rect(x, y, width, height, check_color(L, 6));
|
||||
return 0;
|
||||
}
|
||||
|
||||
enum class alignment
|
||||
{
|
||||
left,
|
||||
right,
|
||||
center
|
||||
};
|
||||
|
||||
// image:draw_text(font, x, y, text, color [, spacing]): returns the x after the text
|
||||
int draw_text_aligned(lua_State *L, alignment const Alignment)
|
||||
{
|
||||
auto &image{check_image(L, 1)};
|
||||
auto const &font{check_object<bitmap_font>(L, 2, font_metatable)};
|
||||
auto x{check_int(L, 3)};
|
||||
auto const y{check_int(L, 4)};
|
||||
auto const text{check_text(L, 5)};
|
||||
auto const color{check_color(L, 6)};
|
||||
auto const spacing{optional_int(L, 7, 1)};
|
||||
if (Alignment == alignment::right)
|
||||
{
|
||||
x -= font.text_width(text, spacing);
|
||||
}
|
||||
else if (Alignment == alignment::center)
|
||||
{
|
||||
x -= font.text_width(text, spacing) / 2;
|
||||
}
|
||||
lua_pushinteger(L, image.draw_text(font, x, y, text, color, spacing));
|
||||
return 1;
|
||||
}
|
||||
|
||||
int image_draw_text(lua_State *L)
|
||||
{
|
||||
return draw_text_aligned(L, alignment::left);
|
||||
}
|
||||
|
||||
int image_draw_text_right(lua_State *L)
|
||||
{
|
||||
return draw_text_aligned(L, alignment::right);
|
||||
}
|
||||
|
||||
int image_draw_text_centered(lua_State *L)
|
||||
{
|
||||
return draw_text_aligned(L, alignment::center);
|
||||
}
|
||||
|
||||
int image_draw_sprite(lua_State *L)
|
||||
{
|
||||
auto &image{check_image(L, 1)};
|
||||
auto const &sprite{check_object<glyph>(L, 2, sprite_metatable)};
|
||||
auto const x{check_int(L, 3)};
|
||||
auto const y{check_int(L, 4)};
|
||||
image.draw_glyph(sprite, x, y, check_color(L, 5));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int image_draw_image(lua_State *L)
|
||||
{
|
||||
auto &image{check_image(L, 1)};
|
||||
auto const &source{check_image(L, 2)};
|
||||
image.draw_image(source, check_int(L, 3), check_int(L, 4));
|
||||
return 0;
|
||||
}
|
||||
|
||||
// image:led_post([bloom]): led_util's render_post, a new image (2w + 2) x (2h + 2). done when the image is shown or used
|
||||
int image_led_post(lua_State *L)
|
||||
{
|
||||
auto const &image{check_lua_image(L, 1)};
|
||||
auto const bloom{lua_isnoneornil(L, 2) || lua_toboolean(L, 2) != 0};
|
||||
luaL_argcheck(L, valid_image_side(image.width() * 2 + 2) && valid_image_side(image.height() * 2 + 2), 1, "too large");
|
||||
post_step step;
|
||||
step.type = post_step::kind::led;
|
||||
step.bloom = bloom;
|
||||
push_object(L, image.then(step), image_metatable);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// image:resize(width, height): scaled as Pillow's resize(..., LANCZOS), a new image. done when the image is shown or used
|
||||
int image_resize(lua_State *L)
|
||||
{
|
||||
auto const &image{check_lua_image(L, 1)};
|
||||
auto const width{check_int(L, 2)};
|
||||
auto const height{check_int(L, 3)};
|
||||
luaL_argcheck(L, valid_image_side(width), 2, "between 1 and 4096");
|
||||
luaL_argcheck(L, valid_image_side(height), 3, "between 1 and 4096");
|
||||
post_step step;
|
||||
step.type = post_step::kind::resize;
|
||||
step.width = width;
|
||||
step.height = height;
|
||||
push_object(L, image.then(step), image_metatable);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int image_copy(lua_State *L)
|
||||
{
|
||||
auto const &image{check_lua_image(L, 1)};
|
||||
push_object(L, lua_image{image}, image_metatable);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// eu07.font and eu07.sprite methods ----------------------------------------------------------------------------------
|
||||
|
||||
int font_height(lua_State *L)
|
||||
{
|
||||
lua_pushinteger(L, check_object<bitmap_font>(L, 1, font_metatable).height());
|
||||
return 1;
|
||||
}
|
||||
|
||||
int font_text_width(lua_State *L)
|
||||
{
|
||||
auto const &font{check_object<bitmap_font>(L, 1, font_metatable)};
|
||||
auto const text{check_text(L, 2)};
|
||||
lua_pushinteger(L, font.text_width(text, optional_int(L, 3, 1)));
|
||||
return 1;
|
||||
}
|
||||
|
||||
int sprite_width(lua_State *L)
|
||||
{
|
||||
lua_pushinteger(L, check_object<glyph>(L, 1, sprite_metatable).width());
|
||||
return 1;
|
||||
}
|
||||
|
||||
int sprite_height(lua_State *L)
|
||||
{
|
||||
lua_pushinteger(L, check_object<glyph>(L, 1, sprite_metatable).height());
|
||||
return 1;
|
||||
}
|
||||
|
||||
constexpr std::array image_methods{
|
||||
luaL_Reg{"width", image_width},
|
||||
luaL_Reg{"height", image_height},
|
||||
luaL_Reg{"fill", image_fill},
|
||||
luaL_Reg{"set", image_set},
|
||||
luaL_Reg{"get", image_get},
|
||||
luaL_Reg{"fill_rect", image_fill_rect},
|
||||
luaL_Reg{"draw_text", image_draw_text},
|
||||
luaL_Reg{"draw_text_right", image_draw_text_right},
|
||||
luaL_Reg{"draw_text_centered", image_draw_text_centered},
|
||||
luaL_Reg{"draw_sprite", image_draw_sprite},
|
||||
luaL_Reg{"draw_image", image_draw_image},
|
||||
luaL_Reg{"led_post", image_led_post},
|
||||
luaL_Reg{"resize", image_resize},
|
||||
luaL_Reg{"copy", image_copy},
|
||||
luaL_Reg{nullptr, nullptr},
|
||||
};
|
||||
|
||||
constexpr std::array font_methods{
|
||||
luaL_Reg{"height", font_height},
|
||||
luaL_Reg{"text_width", font_text_width},
|
||||
luaL_Reg{nullptr, nullptr},
|
||||
};
|
||||
|
||||
constexpr std::array sprite_methods{
|
||||
luaL_Reg{"width", sprite_width},
|
||||
luaL_Reg{"height", sprite_height},
|
||||
luaL_Reg{nullptr, nullptr},
|
||||
};
|
||||
|
||||
constexpr std::array api_functions{
|
||||
luaL_Reg{"image", api_image},
|
||||
luaL_Reg{"font", api_font},
|
||||
luaL_Reg{"sprite", api_sprite},
|
||||
luaL_Reg{"time", api_time},
|
||||
luaL_Reg{"log", api_log},
|
||||
luaL_Reg{"command", api_command},
|
||||
luaL_Reg{"read_file", api_read_file},
|
||||
luaL_Reg{"include", api_include},
|
||||
luaL_Reg{nullptr, nullptr},
|
||||
};
|
||||
|
||||
template <std::size_t Size_> void make_metatable(lua_State *L, char const *Name, std::array<luaL_Reg, Size_> const &Methods, lua_CFunction Collect)
|
||||
{
|
||||
luaL_newmetatable(L, Name);
|
||||
lua_newtable(L);
|
||||
for (auto const &method : Methods)
|
||||
{
|
||||
if (method.name == nullptr)
|
||||
{
|
||||
break;
|
||||
}
|
||||
lua_pushcfunction(L, method.func);
|
||||
lua_setfield(L, -2, method.name);
|
||||
}
|
||||
lua_setfield(L, -2, "__index");
|
||||
lua_pushcfunction(L, Collect);
|
||||
lua_setfield(L, -2, "__gc");
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
|
||||
// the state of a refresh as a table, as the python screens get it in a dictionary; a list of points (touches) is a
|
||||
// list of { x, y }
|
||||
void push_state(lua_State *L, dictionary_source const &Input)
|
||||
{
|
||||
lua_createtable(L, 0, static_cast<int>(Input.floats.size() + Input.integers.size() + Input.bools.size() + Input.strings.size() + Input.vec2_lists.size()));
|
||||
for (auto const &[key, value] : Input.floats)
|
||||
{
|
||||
lua_pushnumber(L, value);
|
||||
lua_setfield(L, -2, key.c_str());
|
||||
}
|
||||
for (auto const &[key, value] : Input.integers)
|
||||
{
|
||||
lua_pushnumber(L, value);
|
||||
lua_setfield(L, -2, key.c_str());
|
||||
}
|
||||
for (auto const &[key, value] : Input.bools)
|
||||
{
|
||||
lua_pushboolean(L, value ? 1 : 0);
|
||||
lua_setfield(L, -2, key.c_str());
|
||||
}
|
||||
for (auto const &[key, value] : Input.strings)
|
||||
{
|
||||
auto const text{utf8_text(value)};
|
||||
lua_pushlstring(L, text.data(), text.size());
|
||||
lua_setfield(L, -2, key.c_str());
|
||||
}
|
||||
for (auto const &[key, points] : Input.vec2_lists)
|
||||
{
|
||||
lua_createtable(L, static_cast<int>(points.size()), 0);
|
||||
for (std::size_t idx = 0; idx < points.size(); ++idx)
|
||||
{
|
||||
lua_createtable(L, 2, 0);
|
||||
lua_pushnumber(L, points[idx].x);
|
||||
lua_rawseti(L, -2, 1);
|
||||
lua_pushnumber(L, points[idx].y);
|
||||
lua_rawseti(L, -2, 2);
|
||||
lua_rawseti(L, -2, static_cast<int>(idx + 1));
|
||||
}
|
||||
lua_setfield(L, -2, key.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void open_library(lua_State *L, lua_CFunction Open, char const *Name)
|
||||
{
|
||||
lua_pushcfunction(L, Open);
|
||||
lua_pushstring(L, Name);
|
||||
lua_call(L, 1, 0);
|
||||
}
|
||||
|
||||
void lua_program::open_libraries()
|
||||
{
|
||||
open_library(m_state, luaopen_base, "");
|
||||
open_library(m_state, luaopen_table, LUA_TABLIBNAME);
|
||||
open_library(m_state, luaopen_string, LUA_STRLIBNAME);
|
||||
open_library(m_state, luaopen_math, LUA_MATHLIBNAME);
|
||||
open_library(m_state, luaopen_bit, LUA_BITLIBNAME);
|
||||
// what reaches files or loads code
|
||||
for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"})
|
||||
{
|
||||
lua_pushnil(m_state);
|
||||
lua_setglobal(m_state, name);
|
||||
}
|
||||
lua_getglobal(m_state, LUA_STRLIBNAME);
|
||||
lua_pushnil(m_state);
|
||||
lua_setfield(m_state, -2, "dump");
|
||||
lua_pop(m_state, 1);
|
||||
}
|
||||
|
||||
void lua_program::register_api()
|
||||
{
|
||||
auto *L{m_state};
|
||||
lua_pushlightuserdata(L, const_cast<char *>(&program_key)); // NOSONAR: the address is only a key
|
||||
lua_pushlightuserdata(L, this);
|
||||
lua_rawset(L, LUA_REGISTRYINDEX);
|
||||
|
||||
make_metatable(L, image_metatable, image_methods, collect<lua_image>);
|
||||
make_metatable(L, font_metatable, font_methods, collect<bitmap_font>);
|
||||
make_metatable(L, sprite_metatable, sprite_methods, collect<glyph>);
|
||||
|
||||
lua_newtable(L);
|
||||
for (auto const &function : api_functions)
|
||||
{
|
||||
if (function.name == nullptr)
|
||||
{
|
||||
break;
|
||||
}
|
||||
lua_pushcfunction(L, function.func);
|
||||
lua_setfield(L, -2, function.name);
|
||||
}
|
||||
lua_setglobal(L, "eu07");
|
||||
// print() writes to the log
|
||||
lua_pushcfunction(L, api_log);
|
||||
lua_setglobal(L, "print");
|
||||
}
|
||||
|
||||
bool lua_program::run(int const Arguments, int const Results, std::string_view const What)
|
||||
{
|
||||
budget = instruction_limit;
|
||||
if (0 == lua_pcall(m_state, Arguments, Results, 0))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
auto const *message{lua_tostring(m_state, -1)};
|
||||
ErrorLog(std::format("Lua screen \"{}\": {} failed: {}", script, What, message != nullptr ? message : "unknown error"));
|
||||
lua_pop(m_state, 1);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool lua_program::start()
|
||||
{
|
||||
m_state = luaL_newstate();
|
||||
if (m_state == nullptr)
|
||||
{
|
||||
ErrorLog(std::format("Lua screen \"{}\": failed to create the state", script));
|
||||
return false;
|
||||
}
|
||||
// no compiled code: LuaJIT calls no hooks in it, and the hook is what stops a script stuck in a loop
|
||||
luaJIT_setmode(m_state, 0, LUAJIT_MODE_ENGINE | LUAJIT_MODE_OFF);
|
||||
open_libraries();
|
||||
register_api();
|
||||
lua_sethook(m_state, count_hook, LUA_MASKCOUNT, hook_interval);
|
||||
|
||||
std::ifstream file{script, std::ios::binary};
|
||||
if (false == file.is_open())
|
||||
{
|
||||
ErrorLog(std::format("Lua screen \"{}\": file not found", script));
|
||||
return false;
|
||||
}
|
||||
std::string const code{std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};
|
||||
if (false == load_chunk(m_state, code, script))
|
||||
{
|
||||
ErrorLog(std::format("Lua screen \"{}\": {}", script, lua_tostring(m_state, -1)));
|
||||
return false;
|
||||
}
|
||||
if (false == run(0, 1, "the script"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (false == lua_istable(m_state, -1))
|
||||
{
|
||||
ErrorLog(std::format("Lua screen \"{}\": the script has to return a table with a render function", script));
|
||||
return false;
|
||||
}
|
||||
lua_getfield(m_state, -1, "render");
|
||||
auto const renders{lua_isfunction(m_state, -1)};
|
||||
lua_pop(m_state, 1);
|
||||
if (false == renders)
|
||||
{
|
||||
ErrorLog(std::format("Lua screen \"{}\": the script has to return a table with a render function", script));
|
||||
return false;
|
||||
}
|
||||
m_screen = luaL_ref(m_state, LUA_REGISTRYINDEX);
|
||||
|
||||
lua_rawgeti(m_state, LUA_REGISTRYINDEX, m_screen);
|
||||
lua_getfield(m_state, -1, "init");
|
||||
lua_remove(m_state, -2);
|
||||
if (lua_isfunction(m_state, -1))
|
||||
{
|
||||
if (false == run(0, 0, "init"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
lua_pop(m_state, 1);
|
||||
}
|
||||
WriteLog(std::format("Lua screen \"{}\": ready", script));
|
||||
return true;
|
||||
}
|
||||
|
||||
bool lua_program::render(render_call &Call)
|
||||
{
|
||||
call = &Call;
|
||||
lua_rawgeti(m_state, LUA_REGISTRYINDEX, m_screen);
|
||||
lua_getfield(m_state, -1, "render");
|
||||
lua_remove(m_state, -2);
|
||||
push_state(m_state, Call.input);
|
||||
auto const rendered{run(1, 1, "render")};
|
||||
call = nullptr;
|
||||
if (false == rendered)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// nil: the screen didn't change, keep the image there is
|
||||
auto succeeded{true};
|
||||
if (auto const *image{test_object<lua_image>(m_state, -1, image_metatable)}; image != nullptr)
|
||||
{
|
||||
Call.pixels = image->drawn.pixels();
|
||||
Call.width = image->drawn.width();
|
||||
Call.height = image->drawn.height();
|
||||
Call.post = image->steps;
|
||||
}
|
||||
else if (false == lua_isnil(m_state, -1))
|
||||
{
|
||||
ErrorLog(std::format("Lua screen \"{}\": render has to return an image or nil", script));
|
||||
succeeded = false;
|
||||
}
|
||||
lua_pop(m_state, 1);
|
||||
// the images the refreshes left behind
|
||||
lua_gc(m_state, LUA_GCSTEP, 0);
|
||||
return succeeded;
|
||||
}
|
||||
|
||||
class lua_runtime_host final : public runtime
|
||||
{
|
||||
public:
|
||||
std::unique_ptr<program> load(std::string const &Script, script_screen_kind const Kind) override
|
||||
{
|
||||
auto loaded{std::make_unique<lua_program>(Script, Kind)};
|
||||
if (false == loaded->start())
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
std::unique_ptr<runtime> make_lua_runtime()
|
||||
{
|
||||
return std::make_unique<lua_runtime_host>();
|
||||
}
|
||||
|
||||
} // namespace script_screens
|
||||
294
scripting/scriptscreendrawing.cpp
Normal file
294
scripting/scriptscreendrawing.cpp
Normal file
@@ -0,0 +1,294 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "scripting/scriptscreendrawing.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <charconv>
|
||||
|
||||
namespace script_screens
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
struct sequence
|
||||
{
|
||||
std::size_t length{1};
|
||||
char32_t first_bits{0};
|
||||
};
|
||||
|
||||
// the length of the UTF-8 sequence starting with the byte and the bits it carries; length 0 for a byte that can't
|
||||
// start one
|
||||
sequence utf8_sequence(std::uint8_t const Lead)
|
||||
{
|
||||
if (Lead < 0x80)
|
||||
{
|
||||
return {1, Lead};
|
||||
}
|
||||
if (Lead >= 0xC2 && Lead <= 0xDF)
|
||||
{
|
||||
return {2, static_cast<char32_t>(Lead & 0x1F)};
|
||||
}
|
||||
if (Lead >= 0xE0 && Lead <= 0xEF)
|
||||
{
|
||||
return {3, static_cast<char32_t>(Lead & 0x0F)};
|
||||
}
|
||||
if (Lead >= 0xF0 && Lead <= 0xF4)
|
||||
{
|
||||
return {4, static_cast<char32_t>(Lead & 0x07)};
|
||||
}
|
||||
return {0, 0};
|
||||
}
|
||||
|
||||
bool continuation(std::uint8_t const Byte)
|
||||
{
|
||||
return (Byte & 0xC0) == 0x80;
|
||||
}
|
||||
|
||||
// a pixel is lit unless it is opaque white, as led_util compares it with (255, 255, 255) and (255, 255, 255, 255)
|
||||
bool lit_pixel(std::span<std::uint8_t const> const Rgba, int const Width, int const X, int const Y)
|
||||
{
|
||||
auto const at{(static_cast<std::size_t>(Y) * Width + X) * 4};
|
||||
return false == (Rgba[at] == 255 && Rgba[at + 1] == 255 && Rgba[at + 2] == 255 && Rgba[at + 3] == 255);
|
||||
}
|
||||
|
||||
// the columns [First, First + Count) of the image as a glyph; columns past the image's edge are unlit
|
||||
glyph cut_glyph(std::span<std::uint8_t const> const Rgba, int const Width, int const Height, int const First, int const Count)
|
||||
{
|
||||
std::vector<bool> lit(static_cast<std::size_t>(Count) * Height, false);
|
||||
for (auto column = 0; column < Count; ++column)
|
||||
{
|
||||
auto const x{First + column};
|
||||
if (x < 0 || x >= Width)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for (auto y = 0; y < Height; ++y)
|
||||
{
|
||||
lit[static_cast<std::size_t>(column) * Height + y] = lit_pixel(Rgba, Width, x, y);
|
||||
}
|
||||
}
|
||||
return {Count, Height, std::move(lit)};
|
||||
}
|
||||
|
||||
// the lines of the text, without the line ends (\n or \r\n, as python's text files read them)
|
||||
std::vector<std::string_view> lines(std::string_view Text)
|
||||
{
|
||||
std::vector<std::string_view> result;
|
||||
while (false == Text.empty())
|
||||
{
|
||||
auto const end{std::min(Text.find('\n'), Text.size())};
|
||||
auto line{Text.substr(0, end)};
|
||||
if (false == line.empty() && line.back() == '\r')
|
||||
{
|
||||
line.remove_suffix(1);
|
||||
}
|
||||
result.push_back(line);
|
||||
Text.remove_prefix(std::min(end + 1, Text.size()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::u32string decode_utf8(std::string_view const Text)
|
||||
{
|
||||
std::u32string result;
|
||||
std::size_t idx{0};
|
||||
while (idx < Text.size())
|
||||
{
|
||||
auto const lead{static_cast<std::uint8_t>(Text[idx])};
|
||||
auto [length, code]{utf8_sequence(lead)};
|
||||
auto valid{length > 0 && idx + length <= Text.size()};
|
||||
for (std::size_t offset = 1; valid && offset < length; ++offset)
|
||||
{
|
||||
auto const byte{static_cast<std::uint8_t>(Text[idx + offset])};
|
||||
valid = continuation(byte);
|
||||
code = (code << 6) | (byte & 0x3F);
|
||||
}
|
||||
if (false == valid)
|
||||
{
|
||||
result.push_back(lead);
|
||||
++idx;
|
||||
continue;
|
||||
}
|
||||
result.push_back(code);
|
||||
idx += length;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<bitmap_font> bitmap_font::parse(std::span<std::uint8_t const> const Rgba, int const Width, int const Height, std::string_view const Description)
|
||||
{
|
||||
if (Width <= 0 || Height <= 0 || Rgba.size() < static_cast<std::size_t>(Width) * Height * 4)
|
||||
{
|
||||
return std::nullopt;
|
||||
}
|
||||
bitmap_font font;
|
||||
font.m_height = Height;
|
||||
auto const all{lines(Description)};
|
||||
auto x{0};
|
||||
// the first line is a comment
|
||||
for (std::size_t line = 1; line < all.size(); ++line)
|
||||
{
|
||||
auto const characters{decode_utf8(all[line])};
|
||||
if (characters.empty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// the character, then its width in digits
|
||||
auto const lead{utf8_sequence(static_cast<std::uint8_t>(all[line][0])).length};
|
||||
auto digits{all[line].substr(std::max<std::size_t>(lead, 1))};
|
||||
// int() of python lets spaces around the number through
|
||||
while (false == digits.empty() && (digits.front() == ' ' || digits.front() == ' '))
|
||||
{
|
||||
digits.remove_prefix(1);
|
||||
}
|
||||
while (false == digits.empty() && (digits.back() == ' ' || digits.back() == ' '))
|
||||
{
|
||||
digits.remove_suffix(1);
|
||||
}
|
||||
auto width{0};
|
||||
if (std::from_chars(digits.data(), digits.data() + digits.size(), width).ec != std::errc{} || width < 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
auto cut{cut_glyph(Rgba, Width, Height, x, width)};
|
||||
if (font.m_glyphs.empty())
|
||||
{
|
||||
font.m_fallback = cut;
|
||||
}
|
||||
font.m_glyphs.insert_or_assign(characters.front(), std::move(cut));
|
||||
x += width + 1;
|
||||
}
|
||||
if (font.m_glyphs.empty())
|
||||
{
|
||||
return std::nullopt;
|
||||
}
|
||||
return font;
|
||||
}
|
||||
|
||||
glyph bitmap_font::sprite(std::span<std::uint8_t const> const Rgba, int const Width, int const Height)
|
||||
{
|
||||
if (Width <= 0 || Height <= 0 || Rgba.size() < static_cast<std::size_t>(Width) * Height * 4)
|
||||
{
|
||||
return {};
|
||||
}
|
||||
return cut_glyph(Rgba, Width, Height, 0, Width);
|
||||
}
|
||||
|
||||
glyph const &bitmap_font::find(char32_t const Character) const
|
||||
{
|
||||
if (auto const lookup{m_glyphs.find(Character)}; lookup != m_glyphs.end())
|
||||
{
|
||||
return lookup->second;
|
||||
}
|
||||
return m_fallback;
|
||||
}
|
||||
|
||||
int bitmap_font::text_width(std::string_view const Text, int const Spacing) const
|
||||
{
|
||||
auto width{0};
|
||||
for (auto const character : decode_utf8(Text))
|
||||
{
|
||||
width += find(character).width() + Spacing;
|
||||
}
|
||||
return width;
|
||||
}
|
||||
|
||||
canvas::canvas(int const Width, int const Height, rgb const Color)
|
||||
: m_width{std::max(Width, 0)}, m_height{std::max(Height, 0)}, m_pixels(static_cast<std::size_t>(m_width) * m_height * 4, 255)
|
||||
{
|
||||
fill(Color);
|
||||
}
|
||||
|
||||
canvas::canvas(int const Width, int const Height, std::vector<std::uint8_t> Pixels) : m_width{Width}, m_height{Height}, m_pixels{std::move(Pixels)}
|
||||
{
|
||||
m_pixels.resize(static_cast<std::size_t>(std::max(Width, 0)) * std::max(Height, 0) * 4, 255);
|
||||
}
|
||||
|
||||
void canvas::fill(rgb const Color)
|
||||
{
|
||||
for (std::size_t at = 0; at < m_pixels.size(); at += 4)
|
||||
{
|
||||
std::ranges::copy(Color, m_pixels.begin() + static_cast<std::ptrdiff_t>(at));
|
||||
m_pixels[at + 3] = 255;
|
||||
}
|
||||
}
|
||||
|
||||
void canvas::set(int const X, int const Y, rgb const Color)
|
||||
{
|
||||
if (X < 0 || Y < 0 || X >= m_width || Y >= m_height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
auto const at{(static_cast<std::size_t>(Y) * m_width + X) * 4};
|
||||
std::ranges::copy(Color, m_pixels.begin() + static_cast<std::ptrdiff_t>(at));
|
||||
}
|
||||
|
||||
rgb canvas::get(int const X, int const Y) const
|
||||
{
|
||||
if (X < 0 || Y < 0 || X >= m_width || Y >= m_height)
|
||||
{
|
||||
return {0, 0, 0};
|
||||
}
|
||||
auto const at{(static_cast<std::size_t>(Y) * m_width + X) * 4};
|
||||
return {m_pixels[at], m_pixels[at + 1], m_pixels[at + 2]};
|
||||
}
|
||||
|
||||
void canvas::fill_rect(int const X, int const Y, int const Width, int const Height, rgb const Color)
|
||||
{
|
||||
for (auto y = std::max(Y, 0); y < std::min(Y + Height, m_height); ++y)
|
||||
{
|
||||
for (auto x = std::max(X, 0); x < std::min(X + Width, m_width); ++x)
|
||||
{
|
||||
set(x, y, Color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void canvas::draw_glyph(glyph const &Glyph, int const X, int const Y, rgb const Color)
|
||||
{
|
||||
for (auto column = 0; column < Glyph.width(); ++column)
|
||||
{
|
||||
for (auto row = 0; row < Glyph.height(); ++row)
|
||||
{
|
||||
if (Glyph.lit(column, row))
|
||||
{
|
||||
set(X + column, Y + row, Color);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int canvas::draw_text(bitmap_font const &Font, int X, int const Y, std::string_view const Text, rgb const Color, int const Spacing)
|
||||
{
|
||||
for (auto const character : decode_utf8(Text))
|
||||
{
|
||||
auto const &shape{Font.find(character)};
|
||||
draw_glyph(shape, X, Y, Color);
|
||||
X += shape.width() + Spacing;
|
||||
}
|
||||
return X;
|
||||
}
|
||||
|
||||
void canvas::draw_image(canvas const &Image, int const X, int const Y)
|
||||
{
|
||||
for (auto y = 0; y < Image.height(); ++y)
|
||||
{
|
||||
for (auto x = 0; x < Image.width(); ++x)
|
||||
{
|
||||
set(X + x, Y + y, Image.get(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace script_screens
|
||||
126
scripting/scriptscreendrawing.h
Normal file
126
scripting/scriptscreendrawing.h
Normal file
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// the drawing the Lua screens get from the game (eu07.image, eu07.font, eu07.sprite): bitmap fonts and sprites in the
|
||||
// format of the python LED screens (scripts/led_util.py: a .png with the glyphs side by side and a .txt with their
|
||||
// widths), and RGBA images to draw them on. drawn natively, the script only says what goes where
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace script_screens
|
||||
{
|
||||
|
||||
using rgb = std::array<std::uint8_t, 3>;
|
||||
|
||||
// the code points of UTF-8 text; a byte that doesn't start a valid sequence stands for itself
|
||||
std::u32string decode_utf8(std::string_view Text);
|
||||
|
||||
// a character or a sprite: its lit pixels, column by column
|
||||
class glyph
|
||||
{
|
||||
public:
|
||||
glyph() = default;
|
||||
glyph(int Width, int Height, std::vector<bool> Lit) : m_width{Width}, m_height{Height}, m_lit{std::move(Lit)} {}
|
||||
|
||||
int width() const
|
||||
{
|
||||
return m_width;
|
||||
}
|
||||
int height() const
|
||||
{
|
||||
return m_height;
|
||||
}
|
||||
bool lit(int const X, int const Y) const
|
||||
{
|
||||
return m_lit[static_cast<std::size_t>(X) * m_height + Y];
|
||||
}
|
||||
|
||||
private:
|
||||
int m_width{0};
|
||||
int m_height{0};
|
||||
std::vector<bool> m_lit;
|
||||
};
|
||||
|
||||
class bitmap_font
|
||||
{
|
||||
public:
|
||||
// a font as led_util.load_font() reads it: Rgba (Width x Height) has the glyphs side by side, a column apart;
|
||||
// Description has a comment line, then a line per glyph: the character and its width. a pixel is lit unless it is
|
||||
// opaque white. nothing for a description without glyphs
|
||||
static std::optional<bitmap_font> parse(std::span<std::uint8_t const> Rgba, int Width, int Height, std::string_view Description);
|
||||
// a sprite as led_util.load_spr() reads it: the whole image as one glyph
|
||||
static glyph sprite(std::span<std::uint8_t const> Rgba, int Width, int Height);
|
||||
|
||||
int height() const
|
||||
{
|
||||
return m_height;
|
||||
}
|
||||
// the glyph of the character. a character the font lacks gets the font's first glyph (led_util picks a random one;
|
||||
// here every refresh draws the same)
|
||||
glyph const &find(char32_t Character) const;
|
||||
// the width of the text, a column of Spacing after every character (led_util's get_str_len)
|
||||
int text_width(std::string_view Text, int Spacing) const;
|
||||
|
||||
private:
|
||||
int m_height{0};
|
||||
std::unordered_map<char32_t, glyph> m_glyphs;
|
||||
glyph m_fallback;
|
||||
};
|
||||
|
||||
// an RGBA image, from the top row down
|
||||
class canvas
|
||||
{
|
||||
public:
|
||||
canvas(int Width, int Height, rgb Color);
|
||||
canvas(int Width, int Height, std::vector<std::uint8_t> Pixels);
|
||||
|
||||
int width() const
|
||||
{
|
||||
return m_width;
|
||||
}
|
||||
int height() const
|
||||
{
|
||||
return m_height;
|
||||
}
|
||||
std::vector<std::uint8_t> const &pixels() const
|
||||
{
|
||||
return m_pixels;
|
||||
}
|
||||
|
||||
void fill(rgb Color);
|
||||
// a pixel outside the image is skipped
|
||||
void set(int X, int Y, rgb Color);
|
||||
// black outside the image
|
||||
rgb get(int X, int Y) const;
|
||||
// clipped to the image
|
||||
void fill_rect(int X, int Y, int Width, int Height, rgb Color);
|
||||
// the lit pixels of the glyph, its top left corner at (X, Y)
|
||||
void draw_glyph(glyph const &Glyph, int X, int Y, rgb Color);
|
||||
// text from X rightwards, Spacing columns between the characters (led_util's draw_str). returns the X after it
|
||||
int draw_text(bitmap_font const &Font, int X, int Y, std::string_view Text, rgb Color, int Spacing);
|
||||
// another image, its top left corner at (X, Y), clipped
|
||||
void draw_image(canvas const &Image, int X, int Y);
|
||||
|
||||
private:
|
||||
int m_width;
|
||||
int m_height;
|
||||
std::vector<std::uint8_t> m_pixels;
|
||||
};
|
||||
|
||||
} // namespace script_screens
|
||||
281
scripting/scriptscreenkernels.cpp
Normal file
281
scripting/scriptscreenkernels.cpp
Normal file
@@ -0,0 +1,281 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "scripting/scriptscreenkernels.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <numbers>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace script_screens
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
constexpr int glow_radius{6};
|
||||
constexpr double glow_factor{0.08};
|
||||
|
||||
using light = std::array<std::int64_t, 3>;
|
||||
|
||||
// led_util's get_px_str: the light gathered from the diodes around, weighted 1 / (0.08 + distance squared), the sums
|
||||
// taken in the same order as there to get the very same numbers
|
||||
light glow_at(std::span<std::uint8_t const> const Source, int const Width, int const Height, int const X, int const Y)
|
||||
{
|
||||
std::array<double, 3> sum{};
|
||||
auto const left{std::max(X - glow_radius, 0)};
|
||||
auto const right{std::min(X + glow_radius + 1, Width)};
|
||||
auto const top{std::max(Y - glow_radius, 0)};
|
||||
auto const bottom{std::min(Y + glow_radius + 1, Height)};
|
||||
for (auto i = left; i < right; ++i)
|
||||
{
|
||||
auto const m{glow_factor + static_cast<double>((i - X) * (i - X))};
|
||||
if (m > 20.0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for (auto j = top; j < bottom; ++j)
|
||||
{
|
||||
auto const s{m + static_cast<double>((j - Y) * (j - Y))};
|
||||
if (s > 20.0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
auto const *pixel{&Source[(static_cast<std::size_t>(j) * Width + i) * 4]};
|
||||
for (std::size_t channel = 0; channel < 3; ++channel)
|
||||
{
|
||||
sum[channel] += static_cast<double>(pixel[channel]) / s;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {static_cast<std::int64_t>(sum[0] * glow_factor), static_cast<std::int64_t>(sum[1] * glow_factor), static_cast<std::int64_t>(sum[2] * glow_factor)};
|
||||
}
|
||||
|
||||
double sinc(double X)
|
||||
{
|
||||
if (X == 0.0)
|
||||
{
|
||||
return 1.0;
|
||||
}
|
||||
X *= std::numbers::pi;
|
||||
return std::sin(X) / X;
|
||||
}
|
||||
|
||||
double lanczos(double const X)
|
||||
{
|
||||
if (X >= -3.0 && X < 3.0)
|
||||
{
|
||||
return sinc(X) * sinc(X / 3.0);
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
constexpr int precision_bits{32 - 8 - 2};
|
||||
|
||||
// the fixed-point weights of one pass, as Pillow's Resample.c (precompute_coeffs, normalize_coeffs_8bpc) makes them
|
||||
struct coefficients
|
||||
{
|
||||
int size{0};
|
||||
std::vector<std::pair<int, int>> bounds; // first input sample and the number of samples, per output sample
|
||||
std::vector<std::int64_t> weights;
|
||||
|
||||
coefficients(int const Input, int const Output)
|
||||
{
|
||||
auto const scale{static_cast<double>(Input) / static_cast<double>(Output)};
|
||||
auto const filterscale{std::max(scale, 1.0)};
|
||||
auto const support{3.0 * filterscale};
|
||||
size = static_cast<int>(std::ceil(support)) * 2 + 1;
|
||||
bounds.reserve(Output);
|
||||
weights.assign(static_cast<std::size_t>(Output) * size, 0);
|
||||
std::vector<double> prepared(size);
|
||||
for (auto xx = 0; xx < Output; ++xx)
|
||||
{
|
||||
auto const center{(xx + 0.5) * scale};
|
||||
auto const ss{1.0 / filterscale};
|
||||
auto const xmin{std::max(static_cast<int>(center - support + 0.5), 0)};
|
||||
auto const xmax{std::min(static_cast<int>(center + support + 0.5), Input) - xmin};
|
||||
auto total{0.0};
|
||||
for (auto x = 0; x < xmax; ++x)
|
||||
{
|
||||
prepared[x] = lanczos((x + xmin - center + 0.5) * ss);
|
||||
total += prepared[x];
|
||||
}
|
||||
for (auto x = 0; x < xmax; ++x)
|
||||
{
|
||||
if (total != 0.0)
|
||||
{
|
||||
prepared[x] /= total;
|
||||
}
|
||||
auto const fixed{prepared[x] * static_cast<double>(1 << precision_bits)};
|
||||
weights[static_cast<std::size_t>(xx) * size + x] = static_cast<std::int64_t>(prepared[x] < 0.0 ? -0.5 + fixed : 0.5 + fixed);
|
||||
}
|
||||
bounds.emplace_back(xmin, xmax);
|
||||
}
|
||||
}
|
||||
|
||||
static std::uint8_t clip(std::int64_t const Sum)
|
||||
{
|
||||
if (Sum >= (std::int64_t{1} << (precision_bits + 8)))
|
||||
{
|
||||
return 255;
|
||||
}
|
||||
if (Sum <= 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return static_cast<std::uint8_t>(Sum >> precision_bits);
|
||||
}
|
||||
};
|
||||
|
||||
constexpr std::int64_t rounding{std::int64_t{1} << (precision_bits - 1)};
|
||||
|
||||
// one pass of the resampling, along rows (Step 4: neighbouring pixels) or along columns (Step: a row)
|
||||
struct pass
|
||||
{
|
||||
coefficients const &weights;
|
||||
std::size_t step; // bytes between the samples the pass mixes
|
||||
};
|
||||
|
||||
std::uint8_t mix(std::uint8_t const *First, pass const &Pass, std::size_t const Index)
|
||||
{
|
||||
auto const count{Pass.weights.bounds[Index].second};
|
||||
auto const offset{Index * static_cast<std::size_t>(Pass.weights.size)};
|
||||
auto sum{rounding};
|
||||
for (auto sample = 0; sample < count; ++sample)
|
||||
{
|
||||
sum += static_cast<std::int64_t>(First[sample * Pass.step]) * Pass.weights.weights[offset + sample];
|
||||
}
|
||||
return coefficients::clip(sum);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool led_post(std::span<std::uint8_t const> const Source, int const Width, int const Height, std::span<std::uint8_t> const Target, bool const Bloom)
|
||||
{
|
||||
auto const targetwidth{Width * 2 + 2};
|
||||
auto const targetheight{Height * 2 + 2};
|
||||
if (Width <= 0 || Height <= 0 || Source.size() < image_size(Width, Height) || Target.size() < image_size(targetwidth, targetheight))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// the light of every diode; above 255 it is clamped only in the final pixels, as led_util (Pillow) does
|
||||
std::vector<light> diodes(static_cast<std::size_t>(Width) * Height);
|
||||
for (auto y = 0; y < Height; ++y)
|
||||
{
|
||||
for (auto x = 0; x < Width; ++x)
|
||||
{
|
||||
auto const at{(static_cast<std::size_t>(y) * Width + x) * 4};
|
||||
diodes[static_cast<std::size_t>(y) * Width + x] = Bloom ? glow_at(Source, Width, Height, x, y) : light{Source[at], Source[at + 1], Source[at + 2]};
|
||||
}
|
||||
}
|
||||
// a black frame, then the diodes
|
||||
for (std::size_t idx = 0; idx < image_size(targetwidth, targetheight); ++idx)
|
||||
{
|
||||
Target[idx] = idx % 4 == 3 ? 255 : 0;
|
||||
}
|
||||
for (auto i = 0; i < Width * 2; ++i)
|
||||
{
|
||||
for (auto j = 0; j < Height * 2; ++j)
|
||||
{
|
||||
auto const &diode{diodes[static_cast<std::size_t>(j / 2) * Width + i / 2]};
|
||||
auto const shade{1.0 - static_cast<double>(i % 2 + j % 2) * 0.15};
|
||||
auto *pixel{&Target[(static_cast<std::size_t>(j + 1) * targetwidth + (i + 1)) * 4]};
|
||||
for (std::size_t channel = 0; channel < 3; ++channel)
|
||||
{
|
||||
pixel[channel] = static_cast<std::uint8_t>(std::clamp<std::int64_t>(static_cast<std::int64_t>(static_cast<double>(diode[channel]) * shade), 0, 255));
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool resize_lanczos(std::span<std::uint8_t const> const Source, int const Width, int const Height, std::span<std::uint8_t> const Target, int const TargetWidth,
|
||||
int const TargetHeight)
|
||||
{
|
||||
if (Width <= 0 || Height <= 0 || TargetWidth <= 0 || TargetHeight <= 0 || Source.size() < image_size(Width, Height) ||
|
||||
Target.size() < image_size(TargetWidth, TargetHeight))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
coefficients const horizontal{Width, TargetWidth};
|
||||
coefficients const vertical{Height, TargetHeight};
|
||||
|
||||
std::vector<std::uint8_t> temporary(image_size(TargetWidth, Height));
|
||||
pass const along_row{horizontal, 4};
|
||||
for (auto y = 0; y < Height; ++y)
|
||||
{
|
||||
for (auto x = 0; x < TargetWidth; ++x)
|
||||
{
|
||||
auto const *first{&Source[(static_cast<std::size_t>(y) * Width + horizontal.bounds[x].first) * 4]};
|
||||
for (std::size_t channel = 0; channel < 3; ++channel)
|
||||
{
|
||||
temporary[(static_cast<std::size_t>(y) * TargetWidth + x) * 4 + channel] = mix(first + channel, along_row, x);
|
||||
}
|
||||
}
|
||||
}
|
||||
pass const along_column{vertical, static_cast<std::size_t>(TargetWidth) * 4};
|
||||
for (auto y = 0; y < TargetHeight; ++y)
|
||||
{
|
||||
for (auto x = 0; x < TargetWidth; ++x)
|
||||
{
|
||||
auto const *first{&temporary[(static_cast<std::size_t>(vertical.bounds[y].first) * TargetWidth + x) * 4]};
|
||||
auto *pixel{&Target[(static_cast<std::size_t>(y) * TargetWidth + x) * 4]};
|
||||
for (std::size_t channel = 0; channel < 3; ++channel)
|
||||
{
|
||||
pixel[channel] = mix(first + channel, along_column, y);
|
||||
}
|
||||
pixel[3] = 255;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int width_after(post_step const &Step, int const Width)
|
||||
{
|
||||
return Step.type == post_step::kind::led ? Width * 2 + 2 : Step.width;
|
||||
}
|
||||
|
||||
int height_after(post_step const &Step, int const Height)
|
||||
{
|
||||
return Step.type == post_step::kind::led ? Height * 2 + 2 : Step.height;
|
||||
}
|
||||
|
||||
bool apply_post(post_image &Image, std::span<post_step const> const Steps)
|
||||
{
|
||||
if (Steps.empty())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
auto result{Image};
|
||||
for (auto const &step : Steps)
|
||||
{
|
||||
auto const width{width_after(step, result.width)};
|
||||
auto const height{height_after(step, result.height)};
|
||||
if (width <= 0 || height <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
std::vector<std::uint8_t> pixels(image_size(width, height));
|
||||
auto const done{step.type == post_step::kind::led ? led_post(result.pixels, result.width, result.height, pixels, step.bloom)
|
||||
: resize_lanczos(result.pixels, result.width, result.height, pixels, width, height)};
|
||||
if (false == done)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
result = post_image{std::move(pixels), width, height};
|
||||
}
|
||||
Image = std::move(result);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace script_screens
|
||||
66
scripting/scriptscreenkernels.h
Normal file
66
scripting/scriptscreenkernels.h
Normal file
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
// image filters the script screens call through the host (led_post, resize_lanczos), run natively rather than
|
||||
// in the interpreter. they give the very pixels of the Python screens: led_util.render_post() and Pillow's
|
||||
// resize(..., Image.LANCZOS). the images are RGBA, 4 bytes a pixel, row by row; alpha is ignored and written as 255
|
||||
namespace script_screens
|
||||
{
|
||||
|
||||
// the size in bytes of an RGBA image
|
||||
constexpr std::size_t image_size(int const Width, int const Height)
|
||||
{
|
||||
return static_cast<std::size_t>(Width) * static_cast<std::size_t>(Height) * 4;
|
||||
}
|
||||
|
||||
// led_util's render_post: every diode becomes 2x2 pixels with a darker grid between them, glowing into its neighbours
|
||||
// (Bloom), in a 1 pixel black frame. Target takes (2 Width + 2) x (2 Height + 2) pixels. returns false for sizes that
|
||||
// don't fit the spans
|
||||
bool led_post(std::span<std::uint8_t const> Source, int Width, int Height, std::span<std::uint8_t> Target, bool Bloom);
|
||||
|
||||
// Pillow's resize with the Lanczos filter, horizontally then vertically, each pass rounded to 8 bits. returns false
|
||||
// for sizes that don't fit the spans
|
||||
bool resize_lanczos(std::span<std::uint8_t const> Source, int Width, int Height, std::span<std::uint8_t> Target, int TargetWidth, int TargetHeight);
|
||||
|
||||
// one step of the post-processing a script asks for on its image (image:led_post, image:resize). the steps of the image
|
||||
// render returns run on the gpu when the renderer can (script_screens::post_processor), otherwise on the cpu
|
||||
struct post_step
|
||||
{
|
||||
enum class kind
|
||||
{
|
||||
led, // led_post
|
||||
resize // resize_lanczos
|
||||
};
|
||||
kind type{kind::led};
|
||||
bool bloom{true}; // led: with the glow
|
||||
int width{0}; // resize: the size it gives
|
||||
int height{0};
|
||||
};
|
||||
|
||||
struct post_image
|
||||
{
|
||||
std::vector<std::uint8_t> pixels; // RGBA, from the top row down
|
||||
int width{0};
|
||||
int height{0};
|
||||
};
|
||||
|
||||
// the size of an image Width wide, or Height high, after the step
|
||||
int width_after(post_step const &Step, int Width);
|
||||
int height_after(post_step const &Step, int Height);
|
||||
// runs the steps on the cpu, one after another. false for sizes the kernels refuse; the image is then as it was
|
||||
bool apply_post(post_image &Image, std::span<post_step const> Steps);
|
||||
|
||||
} // namespace script_screens
|
||||
94
scripting/scriptscreenprogram.h
Normal file
94
scripting/scriptscreenprogram.h
Normal file
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// the inside of the script screens: what the queue (scripting/scriptscreens.cpp) asks of a language runtime
|
||||
// (scripting/luaprogram.cpp, scripting/wasmprogram.cpp), and the helpers they share
|
||||
|
||||
#include "scripting/scriptscreens.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace script_screens
|
||||
{
|
||||
|
||||
// the largest side of a screen image, in pixels
|
||||
constexpr int max_image_side{4096};
|
||||
// the most instructions one call into a screen may run, so that a script stuck in a loop can't hang the worker
|
||||
constexpr std::int64_t instruction_limit{200'000'000};
|
||||
|
||||
struct pending_command
|
||||
{
|
||||
std::string name;
|
||||
std::int32_t param1{0};
|
||||
std::int32_t param2{0};
|
||||
std::uint32_t vehicle{0};
|
||||
};
|
||||
|
||||
// one refresh of a screen: what it gets and what it gives back
|
||||
struct render_call
|
||||
{
|
||||
dictionary_source const &input;
|
||||
std::uint32_t vehicle{0}; // the target of the commands
|
||||
std::vector<pending_command> commands; // sent during the call
|
||||
// the image drawn, RGBA, from the top row down; empty when the screen didn't change
|
||||
std::vector<std::uint8_t> pixels;
|
||||
int width{0};
|
||||
int height{0};
|
||||
// the post-processing still to run on the image (image:led_post, image:resize of the Lua screens)
|
||||
std::vector<post_step> post;
|
||||
};
|
||||
|
||||
// a running script: a Lua state, a WebAssembly instance. made, called and destroyed on the worker thread, or by the
|
||||
// queue once the worker stopped
|
||||
class program
|
||||
{
|
||||
public:
|
||||
program() = default;
|
||||
virtual ~program() = default;
|
||||
program(program const &) = delete;
|
||||
program &operator=(program const &) = delete;
|
||||
// runs a refresh. false when the screen can't run (any more); the reason is in the log
|
||||
virtual bool render(render_call &Call) = 0;
|
||||
};
|
||||
|
||||
// a language: started and stopped with the queue
|
||||
class runtime
|
||||
{
|
||||
public:
|
||||
runtime() = default;
|
||||
virtual ~runtime() = default;
|
||||
runtime(runtime const &) = delete;
|
||||
runtime &operator=(runtime const &) = delete;
|
||||
// loads the script of a screen and runs its setup. nullptr when it fails; the reason is in the log
|
||||
virtual std::unique_ptr<program> load(std::string const &Script, script_screen_kind Kind) = 0;
|
||||
// called on the worker thread when it starts and before it ends
|
||||
virtual void attach_thread() {}
|
||||
virtual void detach_thread() {}
|
||||
};
|
||||
|
||||
std::unique_ptr<runtime> make_lua_runtime();
|
||||
std::unique_ptr<runtime> make_wasm_runtime();
|
||||
|
||||
// the text as UTF-8: names of sceneries and vehicles may come in windows-1250
|
||||
std::string utf8_text(std::string const &Text);
|
||||
// a file of the screen's folder or below; nothing for a path leading outside, or no such file
|
||||
std::optional<std::string> read_screen_file(std::string const &Folder, std::string_view Path);
|
||||
// seconds of a steady clock, the same for every screen, for animations that don't depend on how often the screen is
|
||||
// refreshed
|
||||
double screen_time();
|
||||
bool valid_image_side(int Side);
|
||||
|
||||
} // namespace script_screens
|
||||
126
scripting/scriptscreenrules.cpp
Normal file
126
scripting/scriptscreenrules.cpp
Normal file
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "scripting/scriptscreenrules.h"
|
||||
|
||||
#include "utilities/parser.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace script_screens
|
||||
{
|
||||
|
||||
void screen_config::deserialize(cParser &Input)
|
||||
{
|
||||
while (deserialize_mapping(Input))
|
||||
{
|
||||
// all work done by while()
|
||||
}
|
||||
}
|
||||
|
||||
bool screen_config::deserialize_mapping(cParser &Input)
|
||||
{
|
||||
// token can be a key or block end
|
||||
auto const key{Input.getToken<std::string>(true, "\n\r\t ,;[]")};
|
||||
|
||||
if (key.empty() || key == "}")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (key == "{")
|
||||
{
|
||||
script = Input.getToken<std::string>();
|
||||
}
|
||||
else if (key == "target:")
|
||||
{
|
||||
target = Input.getToken<std::string>();
|
||||
}
|
||||
else if (key == "frames:")
|
||||
{
|
||||
frames = Input.getToken<int>();
|
||||
}
|
||||
else if (key == "parameters:")
|
||||
{
|
||||
parameters = Input.getToken<std::string>();
|
||||
}
|
||||
else if (key == "instance:")
|
||||
{
|
||||
instancing = Input.getToken<std::string>();
|
||||
}
|
||||
else if (key == "background:")
|
||||
{
|
||||
background = Input.getToken<std::string>();
|
||||
}
|
||||
else
|
||||
{
|
||||
// a key of a later version: skip its value
|
||||
Input.getToken<std::string>();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
frame_schedule::frame_schedule(std::uint64_t const Start, int const Interval, int const Phase)
|
||||
: m_interval{std::max(Interval, 1)}, m_next{Start + static_cast<std::uint64_t>(std::max(Phase, 0))}
|
||||
{
|
||||
}
|
||||
|
||||
int frame_schedule::effective_interval(int const Configured, int const Requested)
|
||||
{
|
||||
return std::max({Configured, Requested, 1});
|
||||
}
|
||||
|
||||
int frame_schedule::phase(std::string_view const Key, int const Interval)
|
||||
{
|
||||
if (Interval <= 1)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
// FNV-1a: the same offset for the same name on every compiler
|
||||
std::uint32_t hash{2166136261u};
|
||||
for (auto const character : Key)
|
||||
{
|
||||
hash ^= static_cast<std::uint8_t>(character);
|
||||
hash *= 16777619u;
|
||||
}
|
||||
return static_cast<int>(hash % static_cast<std::uint32_t>(Interval));
|
||||
}
|
||||
|
||||
bool frame_schedule::poll(std::uint64_t const Frame)
|
||||
{
|
||||
if (Frame < m_next)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
m_next = Frame + static_cast<std::uint64_t>(m_interval);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool is_safe_relative_path(std::string_view const Path)
|
||||
{
|
||||
if (Path.empty() || Path.front() == '/' || Path.front() == '\\' || Path.find(':') != std::string_view::npos)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
std::size_t start{0};
|
||||
while (start <= Path.size())
|
||||
{
|
||||
auto const end{std::min(Path.find_first_of("/\\", start), Path.size())};
|
||||
if (Path.substr(start, end - start) == "..")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
start = end + 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace script_screens
|
||||
75
scripting/scriptscreenrules.h
Normal file
75
scripting/scriptscreenrules.h
Normal file
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
class cParser;
|
||||
|
||||
// the parts of the script screens (Lua, WebAssembly) that don't need a runtime: the .mmd entries, the frame
|
||||
// schedule and the file access rules. kept apart from scripting/scriptscreens.cpp so the unit tests can check them
|
||||
namespace script_screens
|
||||
{
|
||||
|
||||
// a script screen as the .mmd file describes it:
|
||||
// luascreen: { script.lua target: submodel frames: 4 parameters: key=value&key=value }
|
||||
// luadestinationsign: { script.lua frames: 30 instance: name parameters: ... background: texture }
|
||||
// and the same with wasmscreen:, wasmdestinationsign: and a .wasm module
|
||||
// every key but the script is optional, and an unknown key is skipped along with its value
|
||||
struct screen_config
|
||||
{
|
||||
std::string script; // the .lua script or .wasm module, relative to the vehicle folder when it has no path of its own
|
||||
std::string target{"none"}; // cab screens: the submodel the screen is drawn on
|
||||
std::string parameters; // extra key=value pairs passed to the screen with the simulation state
|
||||
std::string instancing; // destination signs: "name" or "type", one sign per vehicle or per vehicle type
|
||||
std::string background; // destination signs: the texture shown while the sign is off
|
||||
int frames{0}; // the screen's own refresh interval in frames, used when longer than the one set in eu07.ini
|
||||
|
||||
void deserialize(cParser &Input);
|
||||
|
||||
private:
|
||||
bool deserialize_mapping(cParser &Input);
|
||||
};
|
||||
|
||||
// how often a screen gets fresh data, counted in rendered frames
|
||||
class frame_schedule
|
||||
{
|
||||
public:
|
||||
frame_schedule() = default;
|
||||
// Start: the frame the screen was created on. the first refresh comes Phase frames later
|
||||
frame_schedule(std::uint64_t Start, int Interval, int Phase);
|
||||
|
||||
// the interval of a screen: the one set in eu07.ini, or the screen's own one when that is longer. at least 1
|
||||
static int effective_interval(int Configured, int Requested);
|
||||
// a fixed offset in [0, Interval) taken from the screen's name, so that the screens sharing an interval
|
||||
// don't all refresh on the same frame
|
||||
static int phase(std::string_view Key, int Interval);
|
||||
|
||||
// true when the screen is due on Frame, and then not again until Interval frames later. a screen that
|
||||
// wasn't asked for a while (a vehicle out of sight) is due on the first frame it is asked again
|
||||
bool poll(std::uint64_t Frame);
|
||||
|
||||
int interval() const
|
||||
{
|
||||
return m_interval;
|
||||
}
|
||||
|
||||
private:
|
||||
int m_interval{1};
|
||||
std::uint64_t m_next{0};
|
||||
};
|
||||
|
||||
// true for a file a screen may read: a relative path inside the screen's folder, without '..', without a
|
||||
// drive or a leading separator
|
||||
bool is_safe_relative_path(std::string_view Path);
|
||||
|
||||
} // namespace script_screens
|
||||
592
scripting/scriptscreens.cpp
Normal file
592
scripting/scriptscreens.cpp
Normal file
@@ -0,0 +1,592 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "scripting/scriptscreens.h"
|
||||
#include "scripting/scriptscreenprogram.h"
|
||||
#include "scripting/scriptscreenkernels.h"
|
||||
|
||||
#include "input/command.h"
|
||||
#include "interfaces/ITexture.h"
|
||||
#include "utilities/Globals.h"
|
||||
#include "utilities/Logs.h"
|
||||
#include "utilities/dictionary.h"
|
||||
#include "utilities/utilities.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace script_screens
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
// the length of the UTF-8 sequence starting with the byte, 0 for a byte that can't start one
|
||||
std::size_t utf8_length(std::uint8_t const Lead)
|
||||
{
|
||||
if (Lead < 0x80)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
if (Lead >= 0xC2 && Lead <= 0xDF)
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
if (Lead >= 0xE0 && Lead <= 0xEF)
|
||||
{
|
||||
return 3;
|
||||
}
|
||||
if (Lead >= 0xF0 && Lead <= 0xF4)
|
||||
{
|
||||
return 4;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool is_utf8(std::string_view const Text)
|
||||
{
|
||||
std::size_t idx{0};
|
||||
while (idx < Text.size())
|
||||
{
|
||||
auto const length{utf8_length(static_cast<std::uint8_t>(Text[idx]))};
|
||||
if (length == 0 || idx + length > Text.size())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
auto const sequence{Text.substr(idx + 1, length - 1)};
|
||||
if (false == std::ranges::all_of(sequence, [](char const Byte) { return (static_cast<std::uint8_t>(Byte) & 0xC0) == 0x80; }))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
idx += length;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string utf8_text(std::string const &Text)
|
||||
{
|
||||
return is_utf8(Text) ? Text : win1250_to_utf8(Text);
|
||||
}
|
||||
|
||||
std::optional<std::string> read_screen_file(std::string const &Folder, std::string_view const Path)
|
||||
{
|
||||
if (false == is_safe_relative_path(Path))
|
||||
{
|
||||
return std::nullopt;
|
||||
}
|
||||
std::ifstream file{Folder + std::string{Path}, std::ios::binary};
|
||||
if (false == file.is_open())
|
||||
{
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::string{std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{}};
|
||||
}
|
||||
|
||||
double screen_time()
|
||||
{
|
||||
static auto const start{std::chrono::steady_clock::now()};
|
||||
return std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
|
||||
}
|
||||
|
||||
bool valid_image_side(int const Side)
|
||||
{
|
||||
return Side > 0 && Side <= max_image_side;
|
||||
}
|
||||
|
||||
} // namespace script_screens
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
constexpr std::size_t no_texture{std::numeric_limits<std::size_t>::max()};
|
||||
|
||||
std::string_view language_name(script_language const Language)
|
||||
{
|
||||
return Language == script_language::lua ? "Lua" : "WASM";
|
||||
}
|
||||
|
||||
// the rows of the image the other way round. the script draws from the top row down; the texture takes the bottom row
|
||||
// first, as the python screens give it (abstractscreenrenderer flips the image before handing it over)
|
||||
std::vector<std::uint8_t> flipped(std::span<std::uint8_t const> const Pixels, int const Width, int const Height)
|
||||
{
|
||||
auto const row{static_cast<std::size_t>(Width) * 4};
|
||||
auto const height{static_cast<std::size_t>(Height)};
|
||||
std::vector<std::uint8_t> result(Pixels.size());
|
||||
for (std::size_t y = 0; y < height; ++y)
|
||||
{
|
||||
std::memcpy(result.data() + (height - 1 - y) * row, Pixels.data() + y * row, row);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// the post-processing of the image done on the cpu. false when the kernels refused a size
|
||||
bool post_on_cpu(std::vector<std::uint8_t> &Pixels, int &Width, int &Height, std::vector<script_screens::post_step> &Steps)
|
||||
{
|
||||
script_screens::post_image image{std::move(Pixels), Width, Height};
|
||||
auto const done{script_screens::apply_post(image, Steps)};
|
||||
Pixels = std::move(image.pixels);
|
||||
Width = image.width;
|
||||
Height = image.height;
|
||||
Steps.clear();
|
||||
return done;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
class script_screen
|
||||
{
|
||||
public:
|
||||
script_screen(script_screen_queue::screen_request const &Request, script_screens::frame_schedule const &Schedule)
|
||||
: kind{Request.kind}, language{Request.language}, script{Request.script}, texture{Request.texture}, m_schedule{Schedule}
|
||||
{
|
||||
}
|
||||
~script_screen() = default;
|
||||
script_screen(script_screen const &) = delete;
|
||||
script_screen &operator=(script_screen const &) = delete;
|
||||
|
||||
bool poll(std::uint64_t const Frame)
|
||||
{
|
||||
std::scoped_lock lock{m_schedule_mutex};
|
||||
return m_schedule.poll(Frame);
|
||||
}
|
||||
|
||||
// set when made, read-only afterwards
|
||||
script_screen_kind const kind;
|
||||
script_language const language;
|
||||
std::string const script;
|
||||
ITexture *const texture;
|
||||
|
||||
// set by the worker when the screen can't run (any more); a failed screen isn't refreshed
|
||||
std::atomic<bool> failed{false};
|
||||
// the worker's, and the queue's once the worker stopped
|
||||
std::unique_ptr<script_screens::program> program;
|
||||
|
||||
// the image, handed from the worker to the main thread: bottom row first as the texture takes it, or, while it has
|
||||
// post-processing to run on the gpu, from the top row down as the script drew it
|
||||
std::mutex image_mutex;
|
||||
std::vector<std::uint8_t> image;
|
||||
int image_width{0};
|
||||
int image_height{0};
|
||||
std::vector<script_screens::post_step> post;
|
||||
bool image_pending{false}; // drawn and not yet uploaded
|
||||
std::size_t uploaded_texture{no_texture}; // the gl texture the image went to, to upload it again when it's made anew
|
||||
|
||||
private:
|
||||
std::mutex m_schedule_mutex;
|
||||
script_screens::frame_schedule m_schedule;
|
||||
};
|
||||
|
||||
struct script_screen_queue::implementation
|
||||
{
|
||||
struct task
|
||||
{
|
||||
std::shared_ptr<script_screen> screen;
|
||||
std::shared_ptr<dictionary_source> input;
|
||||
std::uint32_t vehicle{0};
|
||||
};
|
||||
|
||||
void run(std::stop_token const &Stop);
|
||||
void process(task const &Task);
|
||||
script_screens::runtime *runtime_of(script_language const Language) const
|
||||
{
|
||||
return Language == script_language::lua ? lua.get() : wasm.get();
|
||||
}
|
||||
static void present(script_screen &Screen, script_screens::render_call &Call);
|
||||
void upload(script_screen &Screen);
|
||||
// the post-processing of the image the gpu couldn't do, done on the cpu. false when it failed too
|
||||
static bool finish_on_cpu(script_screen &Screen);
|
||||
static void execute(script_screens::pending_command const &Command);
|
||||
|
||||
std::unique_ptr<script_screens::runtime> lua;
|
||||
std::unique_ptr<script_screens::runtime> wasm;
|
||||
bool initialized{false};
|
||||
std::atomic<std::uint64_t> frame{0};
|
||||
|
||||
// the main thread's: the gpu post-processing, none when the renderer has none, or it failed
|
||||
script_screens::post_processor *post_processor{nullptr};
|
||||
// read by the worker: the post-processing is left to the main thread, for the gpu
|
||||
std::atomic<bool> post_on_gpu{false};
|
||||
|
||||
std::mutex screens_mutex;
|
||||
std::unordered_map<std::string, std::weak_ptr<script_screen>> screens;
|
||||
|
||||
std::mutex tasks_mutex;
|
||||
std::condition_variable_any tasks_condition;
|
||||
std::deque<task> tasks;
|
||||
std::jthread worker;
|
||||
|
||||
std::mutex commands_mutex;
|
||||
std::vector<script_screens::pending_command> commands;
|
||||
};
|
||||
|
||||
void script_screen_queue::implementation::run(std::stop_token const &Stop)
|
||||
{
|
||||
for (auto *runtime : {lua.get(), wasm.get()})
|
||||
{
|
||||
if (runtime != nullptr)
|
||||
{
|
||||
runtime->attach_thread();
|
||||
}
|
||||
}
|
||||
while (false == Stop.stop_requested())
|
||||
{
|
||||
task next;
|
||||
{
|
||||
std::unique_lock lock{tasks_mutex};
|
||||
if (false == tasks_condition.wait(lock, Stop, [this] { return false == tasks.empty(); }))
|
||||
{
|
||||
break;
|
||||
}
|
||||
next = std::move(tasks.front());
|
||||
tasks.pop_front();
|
||||
}
|
||||
process(next);
|
||||
}
|
||||
for (auto *runtime : {lua.get(), wasm.get()})
|
||||
{
|
||||
if (runtime != nullptr)
|
||||
{
|
||||
runtime->detach_thread();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void script_screen_queue::implementation::process(task const &Task)
|
||||
{
|
||||
auto &screen{*Task.screen};
|
||||
if (screen.failed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (screen.program == nullptr)
|
||||
{
|
||||
auto *runtime{runtime_of(screen.language)};
|
||||
screen.program = runtime != nullptr ? runtime->load(screen.script, screen.kind) : nullptr;
|
||||
if (screen.program == nullptr)
|
||||
{
|
||||
screen.failed = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
script_screens::render_call call{*Task.input, Task.vehicle};
|
||||
if (false == screen.program->render(call))
|
||||
{
|
||||
screen.failed = true;
|
||||
return;
|
||||
}
|
||||
if (false == call.pixels.empty())
|
||||
{
|
||||
if (false == script_screens::valid_image_side(call.width) || false == script_screens::valid_image_side(call.height) ||
|
||||
call.pixels.size() != script_screens::image_size(call.width, call.height))
|
||||
{
|
||||
ErrorLog(std::format("{} screen \"{}\": invalid image size {}x{}", language_name(screen.language), screen.script, call.width, call.height));
|
||||
screen.failed = true;
|
||||
return;
|
||||
}
|
||||
if (false == call.post.empty() && false == post_on_gpu && false == post_on_cpu(call.pixels, call.width, call.height, call.post))
|
||||
{
|
||||
ErrorLog(std::format("{} screen \"{}\": the post-processing of the image failed", language_name(screen.language), screen.script));
|
||||
screen.failed = true;
|
||||
return;
|
||||
}
|
||||
present(screen, call);
|
||||
}
|
||||
if (false == call.commands.empty())
|
||||
{
|
||||
std::scoped_lock lock{commands_mutex};
|
||||
commands.insert(commands.end(), std::make_move_iterator(call.commands.begin()), std::make_move_iterator(call.commands.end()));
|
||||
}
|
||||
}
|
||||
|
||||
// keeps the image the screen drew, turned bottom row first for the texture; with post-processing left for the gpu, as
|
||||
// it was drawn
|
||||
void script_screen_queue::implementation::present(script_screen &Screen, script_screens::render_call &Call)
|
||||
{
|
||||
std::scoped_lock lock{Screen.image_mutex};
|
||||
if (Call.post.empty())
|
||||
{
|
||||
Screen.image = flipped(Call.pixels, Call.width, Call.height);
|
||||
}
|
||||
else
|
||||
{
|
||||
Screen.image = std::move(Call.pixels);
|
||||
}
|
||||
Screen.post = std::move(Call.post);
|
||||
Screen.image_width = Call.width;
|
||||
Screen.image_height = Call.height;
|
||||
Screen.image_pending = true;
|
||||
}
|
||||
|
||||
bool script_screen_queue::implementation::finish_on_cpu(script_screen &Screen)
|
||||
{
|
||||
if (false == post_on_cpu(Screen.image, Screen.image_width, Screen.image_height, Screen.post))
|
||||
{
|
||||
ErrorLog(std::format("{} screen \"{}\": the post-processing of the image failed", language_name(Screen.language), Screen.script));
|
||||
Screen.image.clear();
|
||||
return false;
|
||||
}
|
||||
Screen.image = flipped(Screen.image, Screen.image_width, Screen.image_height);
|
||||
return true;
|
||||
}
|
||||
|
||||
void script_screen_queue::implementation::upload(script_screen &Screen)
|
||||
{
|
||||
if (Screen.texture == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
std::scoped_lock lock{Screen.image_mutex};
|
||||
if (Screen.image.empty() || false == Screen.texture->get_is_ready())
|
||||
{
|
||||
// nothing drawn yet, or the texture isn't made yet or was released: the image goes up once it's there
|
||||
return;
|
||||
}
|
||||
if (false == Screen.image_pending && Screen.texture->get_id() == Screen.uploaded_texture)
|
||||
{
|
||||
return;
|
||||
}
|
||||
auto const on_gpu{false == Screen.post.empty() && post_processor != nullptr &&
|
||||
post_processor->apply(*Screen.texture, Screen.image, Screen.image_width, Screen.image_height, Screen.post)};
|
||||
if (false == on_gpu)
|
||||
{
|
||||
if (false == Screen.post.empty())
|
||||
{
|
||||
// the gpu can't do it: the cpu does, here this time, and on the worker from now on
|
||||
if (post_processor != nullptr)
|
||||
{
|
||||
WriteLog("Script screens: the post-processing of the images goes to the cpu");
|
||||
}
|
||||
post_processor = nullptr;
|
||||
post_on_gpu = false;
|
||||
if (false == finish_on_cpu(Screen))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
Screen.texture->update_from_memory(Screen.image_width, Screen.image_height, Screen.image.data());
|
||||
}
|
||||
Screen.uploaded_texture = Screen.texture->get_id();
|
||||
Screen.image_pending = false;
|
||||
}
|
||||
|
||||
void script_screen_queue::implementation::execute(script_screens::pending_command const &Command)
|
||||
{
|
||||
auto const lookup{simulation::commandMap.find(Command.name)};
|
||||
if (lookup == simulation::commandMap.end())
|
||||
{
|
||||
ErrorLog(std::format("Script screen: command [{}] not found", Command.name));
|
||||
return;
|
||||
}
|
||||
command_data data{};
|
||||
data.command = lookup->second;
|
||||
data.action = GLFW_PRESS;
|
||||
data.param1 = Command.param1;
|
||||
data.param2 = Command.param2;
|
||||
WriteLog(std::format("Script screen: executing command [{}] with params: P1={} P2={} Target ID={}", Command.name, Command.param1, Command.param2, Command.vehicle));
|
||||
simulation::Commands.push(data, static_cast<std::uint32_t>(command_target::vehicle) | Command.vehicle);
|
||||
}
|
||||
|
||||
script_screen_queue::script_screen_queue() : m_impl{std::make_unique<implementation>()} {}
|
||||
|
||||
script_screen_queue::~script_screen_queue()
|
||||
{
|
||||
exit();
|
||||
}
|
||||
|
||||
bool script_screen_queue::init()
|
||||
{
|
||||
if (m_impl->initialized)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (Global.luascreens_enabled)
|
||||
{
|
||||
m_impl->lua = script_screens::make_lua_runtime();
|
||||
}
|
||||
if (Global.wasm_enabled)
|
||||
{
|
||||
m_impl->wasm = script_screens::make_wasm_runtime();
|
||||
}
|
||||
if (m_impl->lua == nullptr && m_impl->wasm == nullptr)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
m_impl->initialized = true;
|
||||
auto *impl{m_impl.get()};
|
||||
m_impl->worker = std::jthread([impl](std::stop_token const &Stop) { impl->run(Stop); });
|
||||
WriteLog(std::format("Script screens: setup complete (lua: {}, wasm: {}), refreshed every {} frames in the cab and every {} frames outside", m_impl->lua != nullptr ? "yes" : "no",
|
||||
m_impl->wasm != nullptr ? "yes" : "no", Global.screens_cabframes, Global.screens_externalframes));
|
||||
return true;
|
||||
}
|
||||
|
||||
void script_screen_queue::exit()
|
||||
{
|
||||
if (false == m_impl->initialized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (m_impl->worker.joinable())
|
||||
{
|
||||
m_impl->worker.request_stop();
|
||||
m_impl->worker.join();
|
||||
}
|
||||
{
|
||||
std::scoped_lock lock{m_impl->tasks_mutex};
|
||||
m_impl->tasks.clear();
|
||||
}
|
||||
{
|
||||
std::scoped_lock lock{m_impl->commands_mutex};
|
||||
m_impl->commands.clear();
|
||||
}
|
||||
{
|
||||
// the vehicles may hold their screens past this point, but the runtimes go now
|
||||
std::scoped_lock lock{m_impl->screens_mutex};
|
||||
for (auto const &[key, screen] : m_impl->screens)
|
||||
{
|
||||
if (auto const live{screen.lock()}; live != nullptr)
|
||||
{
|
||||
live->program.reset();
|
||||
live->failed = true;
|
||||
}
|
||||
}
|
||||
m_impl->screens.clear();
|
||||
}
|
||||
m_impl->lua.reset();
|
||||
m_impl->wasm.reset();
|
||||
m_impl->initialized = false;
|
||||
}
|
||||
|
||||
bool script_screen_queue::runs(script_language const Language) const
|
||||
{
|
||||
return m_impl->initialized && m_impl->runtime_of(Language) != nullptr;
|
||||
}
|
||||
|
||||
std::shared_ptr<script_screen> script_screen_queue::acquire(screen_request const &Request)
|
||||
{
|
||||
if (false == runs(Request.language) || Request.script.empty())
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
auto const key{Request.key.empty() ? Request.script : Request.key};
|
||||
std::scoped_lock lock{m_impl->screens_mutex};
|
||||
if (auto const lookup{m_impl->screens.find(key)}; lookup != m_impl->screens.end())
|
||||
{
|
||||
if (auto existing{lookup->second.lock()}; existing != nullptr)
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
auto const configured{Request.kind == script_screen_kind::cab ? Global.screens_cabframes : Global.screens_externalframes};
|
||||
auto const interval{script_screens::frame_schedule::effective_interval(configured, Request.frames)};
|
||||
auto screen{std::make_shared<script_screen>(Request, script_screens::frame_schedule{m_impl->frame.load(), interval, script_screens::frame_schedule::phase(key, interval)})};
|
||||
m_impl->screens.insert_or_assign(key, screen);
|
||||
WriteLog(std::format("{} screen \"{}\": refreshed every {} frames", language_name(Request.language), Request.script, interval));
|
||||
return screen;
|
||||
}
|
||||
|
||||
bool script_screen_queue::due(script_screen &Screen) const
|
||||
{
|
||||
if (false == m_impl->initialized || Screen.failed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return Screen.poll(m_impl->frame.load());
|
||||
}
|
||||
|
||||
void script_screen_queue::submit(std::shared_ptr<script_screen> const &Screen, std::shared_ptr<dictionary_source> Input, std::uint32_t const Vehicle)
|
||||
{
|
||||
if (false == m_impl->initialized || Screen == nullptr || Input == nullptr || Screen->failed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
{
|
||||
std::scoped_lock lock{m_impl->tasks_mutex};
|
||||
auto const pending{std::ranges::find(m_impl->tasks, Screen, &implementation::task::screen)};
|
||||
if (pending != m_impl->tasks.end())
|
||||
{
|
||||
// the refresh still waiting gets the newer input
|
||||
pending->input = std::move(Input);
|
||||
pending->vehicle = Vehicle;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_impl->tasks.emplace_back(Screen, std::move(Input), Vehicle);
|
||||
}
|
||||
}
|
||||
m_impl->tasks_condition.notify_one();
|
||||
}
|
||||
|
||||
void script_screen_queue::update()
|
||||
{
|
||||
if (false == m_impl->initialized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
++m_impl->frame;
|
||||
{
|
||||
std::scoped_lock lock{m_impl->screens_mutex};
|
||||
std::erase_if(m_impl->screens, [](auto const &Entry) { return Entry.second.expired(); });
|
||||
for (auto const &[key, screen] : m_impl->screens)
|
||||
{
|
||||
if (auto const live{screen.lock()}; live != nullptr)
|
||||
{
|
||||
m_impl->upload(*live);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<script_screens::pending_command> sent;
|
||||
{
|
||||
std::scoped_lock lock{m_impl->commands_mutex};
|
||||
sent.swap(m_impl->commands);
|
||||
}
|
||||
for (auto const &command : sent)
|
||||
{
|
||||
implementation::execute(command);
|
||||
}
|
||||
}
|
||||
|
||||
void script_screen_queue::set_post_processor(script_screens::post_processor *Processor)
|
||||
{
|
||||
m_impl->post_processor = Processor;
|
||||
m_impl->post_on_gpu = Processor != nullptr;
|
||||
}
|
||||
|
||||
#ifndef WITH_LUA
|
||||
std::unique_ptr<script_screens::runtime> script_screens::make_lua_runtime()
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef WITH_WASM
|
||||
std::unique_ptr<script_screens::runtime> script_screens::make_wasm_runtime()
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
#endif
|
||||
122
scripting/scriptscreens.h
Normal file
122
scripting/scriptscreens.h
Normal file
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "scripting/scriptscreenrules.h"
|
||||
#include "scripting/scriptscreenkernels.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
struct ITexture;
|
||||
struct dictionary_source;
|
||||
|
||||
namespace script_screens
|
||||
{
|
||||
|
||||
// runs the post-processing of a screen's image (image:led_post, image:resize) on the gpu, into the screen's texture.
|
||||
// given by the renderer that can (gfx_renderer::Screen_post_processor); used on the main thread
|
||||
class post_processor
|
||||
{
|
||||
public:
|
||||
post_processor() = default;
|
||||
virtual ~post_processor() = default;
|
||||
post_processor(post_processor const &) = delete;
|
||||
post_processor &operator=(post_processor const &) = delete;
|
||||
// Pixels: the image drawn, Width x Height, RGBA from the top row down. the texture gets the result bottom row first,
|
||||
// as update_from_memory takes it, with its mipmaps. false when it can't; the screen then does the steps on the cpu
|
||||
virtual bool apply(ITexture &Target, std::span<std::uint8_t const> Pixels, int Width, int Height, std::span<post_step const> Steps) = 0;
|
||||
};
|
||||
|
||||
} // namespace script_screens
|
||||
|
||||
// screens drawn by scripts, the counterpart of the python screens (scripting/PyInt.h): Lua scripts run by LuaJIT
|
||||
// (luascreen:, luadestinationsign:) and WebAssembly modules run by WAMR (wasmscreen:, wasmdestinationsign:). a script
|
||||
// gets the state a python screen gets, returns an RGBA image and, in the cab, may send commands. the interface is
|
||||
// described in script_screens_doc.md.
|
||||
// unlike the python screens, which refresh after a time, a script screen refreshes every so many rendered frames:
|
||||
// screens.cabframes in eu07.ini for the screens in the cab, screens.externalframes for the screens outside
|
||||
// (destination signs)
|
||||
|
||||
enum class script_screen_kind
|
||||
{
|
||||
cab, // in the cab of the driven vehicle: may send commands to it
|
||||
external // on the outside of a vehicle, such as a destination sign: shows only
|
||||
};
|
||||
|
||||
enum class script_language
|
||||
{
|
||||
lua,
|
||||
wasm
|
||||
};
|
||||
|
||||
// the language of a script, by its extension: .lua or .wasm
|
||||
inline std::optional<script_language> script_language_of(std::string_view const Script)
|
||||
{
|
||||
if (Script.ends_with(".lua"))
|
||||
{
|
||||
return script_language::lua;
|
||||
}
|
||||
if (Script.ends_with(".wasm"))
|
||||
{
|
||||
return script_language::wasm;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// one screen: a running script with its own state, and the image it drew last
|
||||
class script_screen;
|
||||
|
||||
class script_screen_queue
|
||||
{
|
||||
public:
|
||||
struct screen_request
|
||||
{
|
||||
script_screen_kind kind{script_screen_kind::cab};
|
||||
script_language language{script_language::lua};
|
||||
std::string script; // the .lua script or .wasm module
|
||||
std::string key; // requests with the same key get the same screen, e.g. the destination signs of one train
|
||||
ITexture *texture{nullptr}; // where the screen is drawn; none for a screen that only sends commands
|
||||
int frames{0}; // the screen's own refresh interval from the .mmd, used when longer than the eu07.ini one
|
||||
};
|
||||
|
||||
script_screen_queue();
|
||||
~script_screen_queue();
|
||||
script_screen_queue(script_screen_queue const &) = delete;
|
||||
script_screen_queue &operator=(script_screen_queue const &) = delete;
|
||||
|
||||
// starts the runtimes switched on in eu07.ini and the worker thread. returns true when any runtime started
|
||||
bool init();
|
||||
// stops the worker and releases every screen, also the ones still held by vehicles
|
||||
void exit();
|
||||
// true when screens in the language can run
|
||||
bool runs(script_language Language) const;
|
||||
// the screen for the request, made on the first request with its key. nullptr when its language doesn't run
|
||||
std::shared_ptr<script_screen> acquire(screen_request const &Request);
|
||||
// true once per refresh interval of the screen. the caller then gathers the screen's input and submit()s it
|
||||
bool due(script_screen &Screen) const;
|
||||
// queues a refresh of the screen with the given input, replacing a refresh of it still waiting.
|
||||
// Vehicle: the vehicle that gets the commands the screen sends; cab screens only
|
||||
void submit(std::shared_ptr<script_screen> const &Screen, std::shared_ptr<dictionary_source> Input, std::uint32_t Vehicle);
|
||||
// main thread, once per rendered frame: uploads the finished images, runs the commands the screens sent and
|
||||
// counts the frame
|
||||
void update();
|
||||
// main thread: the post-processing of the images goes to the gpu through the processor; with none (the default) it
|
||||
// runs on the worker, on the cpu
|
||||
void set_post_processor(script_screens::post_processor *Processor);
|
||||
|
||||
private:
|
||||
struct implementation;
|
||||
std::unique_ptr<implementation> m_impl;
|
||||
};
|
||||
630
scripting/wasmprogram.cpp
Normal file
630
scripting/wasmprogram.cpp
Normal file
@@ -0,0 +1,630 @@
|
||||
/*
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
// the WebAssembly screens: modules run by the WAMR interpreter (ref/wamr), with the "eu07" import module of
|
||||
// script_screens_doc.md
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "scripting/scriptscreenprogram.h"
|
||||
#include "scripting/scriptscreenkernels.h"
|
||||
|
||||
#include "utilities/Logs.h"
|
||||
#include "utilities/dictionary.h"
|
||||
#include "utilities/utilities.h"
|
||||
|
||||
#include <wasm_export.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace script_screens
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
// the wasm stack of a screen, in bytes
|
||||
constexpr std::uint32_t stack_size{64 * 1024};
|
||||
|
||||
// the type of a value in the input of a screen, as eu07.value_type() reports it
|
||||
enum class value_type : std::int32_t
|
||||
{
|
||||
none = 0,
|
||||
floating = 1,
|
||||
integer = 2,
|
||||
boolean = 3,
|
||||
string = 4,
|
||||
vec2_list = 5
|
||||
};
|
||||
|
||||
// the input of one refresh, indexed by key. when two values share a key the later one counts, as it does for the
|
||||
// python screens, which get the values in the same order
|
||||
class input_view
|
||||
{
|
||||
public:
|
||||
struct entry
|
||||
{
|
||||
value_type type{value_type::none};
|
||||
std::size_t index{0};
|
||||
};
|
||||
|
||||
explicit input_view(dictionary_source const &Source) : m_source{Source}
|
||||
{
|
||||
index(Source.floats, value_type::floating);
|
||||
index(Source.integers, value_type::integer);
|
||||
index(Source.bools, value_type::boolean);
|
||||
index(Source.strings, value_type::string);
|
||||
index(Source.vec2_lists, value_type::vec2_list);
|
||||
}
|
||||
|
||||
entry find(std::string_view const Key) const
|
||||
{
|
||||
if (auto const lookup{m_entries.find(Key)}; lookup != m_entries.end())
|
||||
{
|
||||
return lookup->second;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
dictionary_source const &source() const
|
||||
{
|
||||
return m_source;
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename Sequence_> void index(Sequence_ const &Values, value_type const Type)
|
||||
{
|
||||
for (std::size_t idx = 0; idx < Values.size(); ++idx)
|
||||
{
|
||||
m_entries.insert_or_assign(std::string_view{Values[idx].first}, entry{Type, idx});
|
||||
}
|
||||
}
|
||||
|
||||
dictionary_source const &m_source;
|
||||
std::unordered_map<std::string_view, entry> m_entries;
|
||||
};
|
||||
|
||||
std::int32_t to_int32(double const Value)
|
||||
{
|
||||
if (std::isnan(Value))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return static_cast<std::int32_t>(std::clamp(Value, static_cast<double>(std::numeric_limits<std::int32_t>::min()), static_cast<double>(std::numeric_limits<std::int32_t>::max())));
|
||||
}
|
||||
|
||||
std::int32_t to_int32(std::size_t const Value)
|
||||
{
|
||||
return static_cast<std::int32_t>(std::min<std::size_t>(Value, std::numeric_limits<std::int32_t>::max()));
|
||||
}
|
||||
|
||||
class wasm_program final : public program
|
||||
{
|
||||
public:
|
||||
wasm_program(std::string const &Script, script_screen_kind const Kind) : kind{Kind}, script{Script}, folder{substr_path(Script)} {}
|
||||
~wasm_program() override
|
||||
{
|
||||
if (exec_env != nullptr)
|
||||
{
|
||||
wasm_runtime_destroy_exec_env(exec_env);
|
||||
}
|
||||
if (instance != nullptr)
|
||||
{
|
||||
wasm_runtime_deinstantiate(instance);
|
||||
}
|
||||
}
|
||||
wasm_program(wasm_program const &) = delete;
|
||||
wasm_program &operator=(wasm_program const &) = delete;
|
||||
|
||||
bool instantiate(wasm_module_t Module);
|
||||
bool render(render_call &Call) override;
|
||||
|
||||
script_screen_kind const kind;
|
||||
std::string const script;
|
||||
std::string const folder;
|
||||
// the call in progress
|
||||
input_view const *input{nullptr};
|
||||
render_call *call{nullptr};
|
||||
bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged
|
||||
|
||||
private:
|
||||
bool call_i32(wasm_function_inst_t Function, std::string_view Name, std::int32_t &Result);
|
||||
bool present(std::uint32_t Pixels, render_call &Call);
|
||||
|
||||
wasm_module_inst_t instance{nullptr};
|
||||
wasm_exec_env_t exec_env{nullptr};
|
||||
wasm_function_inst_t m_render{nullptr};
|
||||
wasm_function_inst_t m_width{nullptr};
|
||||
wasm_function_inst_t m_height{nullptr};
|
||||
};
|
||||
|
||||
wasm_program *program_of(wasm_exec_env_t Env)
|
||||
{
|
||||
return static_cast<wasm_program *>(wasm_runtime_get_custom_data(wasm_runtime_get_module_inst(Env)));
|
||||
}
|
||||
|
||||
struct lookup_result
|
||||
{
|
||||
input_view const *view{nullptr};
|
||||
input_view::entry entry;
|
||||
};
|
||||
|
||||
lookup_result lookup(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length)
|
||||
{
|
||||
auto const *screen{program_of(Env)};
|
||||
if (screen == nullptr || screen->input == nullptr || Key == nullptr)
|
||||
{
|
||||
return {};
|
||||
}
|
||||
return {screen->input, screen->input->find(std::string_view{Key, Length})};
|
||||
}
|
||||
|
||||
// the natives of the "eu07" module, which a screen imports. see script_screens_doc.md
|
||||
|
||||
std::int32_t native_value_type(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length)
|
||||
{
|
||||
return static_cast<std::int32_t>(lookup(Env, Key, Length).entry.type);
|
||||
}
|
||||
|
||||
double native_get_float(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length)
|
||||
{
|
||||
auto const [view, entry]{lookup(Env, Key, Length)};
|
||||
using enum value_type;
|
||||
switch (entry.type)
|
||||
{
|
||||
case floating:
|
||||
return view->source().floats[entry.index].second;
|
||||
case integer:
|
||||
return view->source().integers[entry.index].second;
|
||||
case boolean:
|
||||
return view->source().bools[entry.index].second ? 1.0 : 0.0;
|
||||
default:
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
std::int32_t native_get_int(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length)
|
||||
{
|
||||
auto const [view, entry]{lookup(Env, Key, Length)};
|
||||
using enum value_type;
|
||||
switch (entry.type)
|
||||
{
|
||||
case floating:
|
||||
return to_int32(view->source().floats[entry.index].second);
|
||||
case integer:
|
||||
return view->source().integers[entry.index].second;
|
||||
case boolean:
|
||||
return view->source().bools[entry.index].second ? 1 : 0;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
std::int32_t native_get_bool(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length)
|
||||
{
|
||||
auto const [view, entry]{lookup(Env, Key, Length)};
|
||||
using enum value_type;
|
||||
switch (entry.type)
|
||||
{
|
||||
case floating:
|
||||
return view->source().floats[entry.index].second != 0.0 ? 1 : 0;
|
||||
case integer:
|
||||
return view->source().integers[entry.index].second != 0 ? 1 : 0;
|
||||
case boolean:
|
||||
return view->source().bools[entry.index].second ? 1 : 0;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// copies the string into the buffer, as UTF-8. returns the length of the whole string, which may be more than the
|
||||
// buffer took, or -1 when there is no such string
|
||||
std::int32_t native_get_string(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length, char *Buffer, std::uint32_t const Capacity)
|
||||
{
|
||||
auto const [view, entry]{lookup(Env, Key, Length)};
|
||||
if (entry.type != value_type::string)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
auto const text{utf8_text(view->source().strings[entry.index].second)};
|
||||
if (Buffer != nullptr)
|
||||
{
|
||||
std::memcpy(Buffer, text.data(), std::min<std::size_t>(text.size(), Capacity));
|
||||
}
|
||||
return to_int32(text.size());
|
||||
}
|
||||
|
||||
std::int32_t native_get_vec2_count(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length)
|
||||
{
|
||||
auto const [view, entry]{lookup(Env, Key, Length)};
|
||||
if (entry.type != value_type::vec2_list)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return to_int32(view->source().vec2_lists[entry.index].second.size());
|
||||
}
|
||||
|
||||
// writes the point as two f32 at Output. returns 1 on success, 0 when there is no such point
|
||||
std::int32_t native_get_vec2(wasm_exec_env_t Env, char const *Key, std::uint32_t const Length, std::int32_t const Index, std::uint32_t const Output)
|
||||
{
|
||||
auto const [view, entry]{lookup(Env, Key, Length)};
|
||||
if (entry.type != value_type::vec2_list || Index < 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
auto const &points{view->source().vec2_lists[entry.index].second};
|
||||
if (static_cast<std::size_t>(Index) >= points.size())
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
auto *instance{wasm_runtime_get_module_inst(Env)};
|
||||
std::array<float, 2> const point{points[Index].x, points[Index].y};
|
||||
if (false == wasm_runtime_validate_app_addr(instance, Output, sizeof(point)))
|
||||
{
|
||||
// the runtime has raised an exception, which ends the call
|
||||
return 0;
|
||||
}
|
||||
std::memcpy(wasm_runtime_addr_app_to_native(instance, Output), point.data(), sizeof(point));
|
||||
return 1;
|
||||
}
|
||||
|
||||
void native_command(wasm_exec_env_t Env, char const *Name, std::uint32_t const Length, std::int32_t const Param1, std::int32_t const Param2)
|
||||
{
|
||||
auto *screen{program_of(Env)};
|
||||
if (screen == nullptr || screen->call == nullptr || Name == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (screen->kind != script_screen_kind::cab)
|
||||
{
|
||||
if (false == screen->commands_ignored)
|
||||
{
|
||||
screen->commands_ignored = true;
|
||||
WriteLog(std::format("WASM screen \"{}\": commands are only taken from screens in the cab", screen->script));
|
||||
}
|
||||
return;
|
||||
}
|
||||
screen->call->commands.emplace_back(std::string{Name, Length}, Param1, Param2, screen->call->vehicle);
|
||||
}
|
||||
|
||||
void native_log(wasm_exec_env_t Env, char const *Text, std::uint32_t const Length)
|
||||
{
|
||||
auto const *screen{program_of(Env)};
|
||||
if (screen == nullptr || Text == nullptr)
|
||||
{
|
||||
return;
|
||||
}
|
||||
WriteLog(std::format("WASM screen \"{}\": {}", screen->script, std::string_view{Text, Length}));
|
||||
}
|
||||
|
||||
// reads a file from the screen's folder into the buffer. returns the size of the whole file, which may be more
|
||||
// than the buffer took, or -1 when there is no such file or the path leads outside the folder
|
||||
std::int32_t native_file_read(wasm_exec_env_t Env, char const *Path, std::uint32_t const Length, char *Buffer, std::uint32_t const Capacity)
|
||||
{
|
||||
auto const *screen{program_of(Env)};
|
||||
if (screen == nullptr || Path == nullptr)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
auto const contents{read_screen_file(screen->folder, std::string_view{Path, Length})};
|
||||
if (false == contents.has_value())
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
if (Buffer != nullptr)
|
||||
{
|
||||
std::memcpy(Buffer, contents->data(), std::min<std::size_t>(contents->size(), Capacity));
|
||||
}
|
||||
return to_int32(contents->size());
|
||||
}
|
||||
|
||||
double native_time(wasm_exec_env_t /*Env*/)
|
||||
{
|
||||
return screen_time();
|
||||
}
|
||||
|
||||
// the bytes of an image in the module's memory; an empty span for one that lies outside (the runtime then raises an
|
||||
// exception, which ends the call)
|
||||
std::span<std::uint8_t> module_image(wasm_exec_env_t Env, std::uint32_t const Offset, int const Width, int const Height)
|
||||
{
|
||||
auto *instance{wasm_runtime_get_module_inst(Env)};
|
||||
auto const size{image_size(Width, Height)};
|
||||
if (false == wasm_runtime_validate_app_addr(instance, Offset, size))
|
||||
{
|
||||
return {};
|
||||
}
|
||||
return {static_cast<std::uint8_t *>(wasm_runtime_addr_app_to_native(instance, Offset)), size};
|
||||
}
|
||||
|
||||
// led_util's render_post, natively: Target takes (2 Width + 2) x (2 Height + 2) pixels. returns 1, or 0 for an image
|
||||
// that doesn't fit
|
||||
std::int32_t native_led_post(wasm_exec_env_t Env, std::uint32_t const Source, std::int32_t const Width, std::int32_t const Height, std::uint32_t const Target, std::int32_t const Bloom)
|
||||
{
|
||||
if (false == valid_image_side(Width) || false == valid_image_side(Height))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
auto const source{module_image(Env, Source, Width, Height)};
|
||||
auto const target{module_image(Env, Target, Width * 2 + 2, Height * 2 + 2)};
|
||||
if (source.empty() || target.empty())
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return led_post(source, Width, Height, target, Bloom != 0) ? 1 : 0;
|
||||
}
|
||||
|
||||
// Pillow's resize(..., LANCZOS), natively. returns 1, or 0 for an image that doesn't fit
|
||||
std::int32_t native_resize_lanczos(wasm_exec_env_t Env, std::uint32_t const Source, std::int32_t const Width, std::int32_t const Height, std::uint32_t const Target,
|
||||
std::int32_t const TargetWidth, std::int32_t const TargetHeight)
|
||||
{
|
||||
if (false == valid_image_side(Width) || false == valid_image_side(Height) || false == valid_image_side(TargetWidth) || false == valid_image_side(TargetHeight))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
auto const source{module_image(Env, Source, Width, Height)};
|
||||
auto const target{module_image(Env, Target, TargetWidth, TargetHeight)};
|
||||
if (source.empty() || target.empty())
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
return resize_lanczos(source, Width, Height, target, TargetWidth, TargetHeight) ? 1 : 0;
|
||||
}
|
||||
|
||||
template <typename Function_> NativeSymbol native(char const *Name, Function_ *Function, char const *Signature)
|
||||
{
|
||||
return NativeSymbol{Name, reinterpret_cast<void *>(Function), Signature, nullptr};
|
||||
}
|
||||
|
||||
bool wasm_program::instantiate(wasm_module_t const Module)
|
||||
{
|
||||
std::array<char, 256> error{};
|
||||
instance = wasm_runtime_instantiate(Module, stack_size, 0, error.data(), static_cast<std::uint32_t>(error.size()));
|
||||
if (instance == nullptr)
|
||||
{
|
||||
ErrorLog(std::format("WASM screen \"{}\": instantiation failed: {}", script, error.data()));
|
||||
return false;
|
||||
}
|
||||
wasm_runtime_set_custom_data(instance, this);
|
||||
exec_env = wasm_runtime_create_exec_env(instance, stack_size);
|
||||
if (exec_env == nullptr)
|
||||
{
|
||||
ErrorLog(std::format("WASM screen \"{}\": failed to create the execution environment", script));
|
||||
return false;
|
||||
}
|
||||
m_render = wasm_runtime_lookup_function(instance, "screen_render");
|
||||
m_width = wasm_runtime_lookup_function(instance, "screen_width");
|
||||
m_height = wasm_runtime_lookup_function(instance, "screen_height");
|
||||
if (m_render == nullptr || m_width == nullptr || m_height == nullptr)
|
||||
{
|
||||
ErrorLog(std::format("WASM screen \"{}\": the module has to export screen_render, screen_width and screen_height", script));
|
||||
return false;
|
||||
}
|
||||
if (auto *init{wasm_runtime_lookup_function(instance, "screen_init")}; init != nullptr)
|
||||
{
|
||||
std::int32_t result{0};
|
||||
if (false == call_i32(init, "screen_init", result))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (result != 0)
|
||||
{
|
||||
ErrorLog(std::format("WASM screen \"{}\": screen_init returned {}", script, result));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
WriteLog(std::format("WASM screen \"{}\": ready", script));
|
||||
return true;
|
||||
}
|
||||
|
||||
// calls a function of the screen that takes nothing and returns an i32
|
||||
bool wasm_program::call_i32(wasm_function_inst_t Function, std::string_view const Name, std::int32_t &Result)
|
||||
{
|
||||
wasm_runtime_set_instruction_count_limit(exec_env, static_cast<int>(instruction_limit));
|
||||
std::array<std::uint32_t, 1> cells{};
|
||||
if (false == wasm_runtime_call_wasm(exec_env, Function, 0, cells.data()))
|
||||
{
|
||||
auto const *exception{wasm_runtime_get_exception(instance)};
|
||||
ErrorLog(std::format("WASM screen \"{}\": {} failed: {}", script, Name, exception != nullptr ? exception : "unknown error"));
|
||||
return false;
|
||||
}
|
||||
Result = static_cast<std::int32_t>(cells[0]);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool wasm_program::render(render_call &Call)
|
||||
{
|
||||
input_view const view{Call.input};
|
||||
input = &view;
|
||||
call = &Call;
|
||||
std::int32_t pixels{0};
|
||||
auto const rendered{call_i32(m_render, "screen_render", pixels)};
|
||||
input = nullptr;
|
||||
call = nullptr;
|
||||
if (false == rendered)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// 0: the screen didn't change, keep the image there is
|
||||
return pixels == 0 || present(static_cast<std::uint32_t>(pixels), Call);
|
||||
}
|
||||
|
||||
// copies the image the screen drew, Pixels being its address in the module's memory
|
||||
bool wasm_program::present(std::uint32_t const Pixels, render_call &Call)
|
||||
{
|
||||
std::int32_t width{0};
|
||||
std::int32_t height{0};
|
||||
if (false == call_i32(m_width, "screen_width", width) || false == call_i32(m_height, "screen_height", height))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (false == valid_image_side(width) || false == valid_image_side(height))
|
||||
{
|
||||
ErrorLog(std::format("WASM screen \"{}\": invalid image size {}x{}", script, width, height));
|
||||
return false;
|
||||
}
|
||||
auto const size{image_size(width, height)};
|
||||
if (false == wasm_runtime_validate_app_addr(instance, Pixels, size))
|
||||
{
|
||||
ErrorLog(std::format("WASM screen \"{}\": the image lies outside the module's memory", script));
|
||||
return false;
|
||||
}
|
||||
auto const *pixels{static_cast<std::uint8_t const *>(wasm_runtime_addr_app_to_native(instance, Pixels))};
|
||||
Call.pixels.assign(pixels, pixels + size);
|
||||
Call.width = width;
|
||||
Call.height = height;
|
||||
return true;
|
||||
}
|
||||
|
||||
class wasm_runtime_host final : public runtime
|
||||
{
|
||||
public:
|
||||
wasm_runtime_host()
|
||||
: m_natives{native("value_type", &native_value_type, "(*~)i"),
|
||||
native("get_float", &native_get_float, "(*~)F"),
|
||||
native("get_int", &native_get_int, "(*~)i"),
|
||||
native("get_bool", &native_get_bool, "(*~)i"),
|
||||
native("get_string", &native_get_string, "(*~*~)i"),
|
||||
native("get_vec2_count", &native_get_vec2_count, "(*~)i"),
|
||||
native("get_vec2", &native_get_vec2, "(*~ii)i"),
|
||||
native("command", &native_command, "(*~ii)"),
|
||||
native("log", &native_log, "(*~)"),
|
||||
native("file_read", &native_file_read, "(*~*~)i"),
|
||||
native("time", &native_time, "()F"),
|
||||
native("led_post", &native_led_post, "(iiiii)i"),
|
||||
native("resize_lanczos", &native_resize_lanczos, "(iiiiii)i")}
|
||||
{
|
||||
}
|
||||
~wasm_runtime_host() override
|
||||
{
|
||||
for (auto const &[script, entry] : m_modules)
|
||||
{
|
||||
if (entry.module != nullptr)
|
||||
{
|
||||
wasm_runtime_unload(entry.module);
|
||||
}
|
||||
}
|
||||
if (m_started)
|
||||
{
|
||||
wasm_runtime_destroy();
|
||||
}
|
||||
}
|
||||
wasm_runtime_host(wasm_runtime_host const &) = delete;
|
||||
wasm_runtime_host &operator=(wasm_runtime_host const &) = delete;
|
||||
|
||||
bool start();
|
||||
std::unique_ptr<program> load(std::string const &Script, script_screen_kind Kind) override;
|
||||
void attach_thread() override
|
||||
{
|
||||
wasm_runtime_init_thread_env();
|
||||
}
|
||||
void detach_thread() override
|
||||
{
|
||||
wasm_runtime_destroy_thread_env();
|
||||
}
|
||||
|
||||
private:
|
||||
struct module_entry
|
||||
{
|
||||
std::vector<std::uint8_t> bytes; // the runtime reads the module from here as long as it is loaded
|
||||
wasm_module_t module{nullptr};
|
||||
};
|
||||
|
||||
wasm_module_t load_module(std::string const &Script);
|
||||
|
||||
// the runtime keeps the array and sorts it, so it lives as long as the runtime
|
||||
std::array<NativeSymbol, 13> m_natives;
|
||||
bool m_started{false};
|
||||
std::unordered_map<std::string, module_entry> m_modules; // the worker's
|
||||
};
|
||||
|
||||
bool wasm_runtime_host::start()
|
||||
{
|
||||
RuntimeInitArgs arguments{};
|
||||
arguments.mem_alloc_type = Alloc_With_System_Allocator;
|
||||
arguments.native_module_name = "eu07";
|
||||
arguments.native_symbols = m_natives.data();
|
||||
arguments.n_native_symbols = static_cast<std::uint32_t>(m_natives.size());
|
||||
arguments.running_mode = Mode_Interp;
|
||||
if (false == wasm_runtime_full_init(&arguments))
|
||||
{
|
||||
ErrorLog("WASM screens: failed to initialize the runtime");
|
||||
return false;
|
||||
}
|
||||
wasm_runtime_set_log_level(WASM_LOG_LEVEL_ERROR);
|
||||
m_started = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
wasm_module_t wasm_runtime_host::load_module(std::string const &Script)
|
||||
{
|
||||
if (auto const lookup{m_modules.find(Script)}; lookup != m_modules.end())
|
||||
{
|
||||
return lookup->second.module;
|
||||
}
|
||||
// a failure is kept as well, so the module isn't tried again for every screen using it
|
||||
auto &entry{m_modules[Script]};
|
||||
std::ifstream file{Script, std::ios::binary};
|
||||
if (false == file.is_open())
|
||||
{
|
||||
ErrorLog(std::format("WASM screen \"{}\": file not found", Script));
|
||||
return nullptr;
|
||||
}
|
||||
entry.bytes.assign(std::istreambuf_iterator<char>{file}, std::istreambuf_iterator<char>{});
|
||||
if (entry.bytes.empty() || entry.bytes.size() > std::numeric_limits<std::uint32_t>::max())
|
||||
{
|
||||
ErrorLog(std::format("WASM screen \"{}\": invalid module size", Script));
|
||||
return nullptr;
|
||||
}
|
||||
std::array<char, 256> error{};
|
||||
entry.module = wasm_runtime_load(entry.bytes.data(), static_cast<std::uint32_t>(entry.bytes.size()), error.data(), static_cast<std::uint32_t>(error.size()));
|
||||
if (entry.module == nullptr)
|
||||
{
|
||||
ErrorLog(std::format("WASM screen \"{}\": failed to load the module: {}", Script, error.data()));
|
||||
}
|
||||
return entry.module;
|
||||
}
|
||||
|
||||
std::unique_ptr<program> wasm_runtime_host::load(std::string const &Script, script_screen_kind const Kind)
|
||||
{
|
||||
auto *module{load_module(Script)};
|
||||
if (module == nullptr)
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
auto loaded{std::make_unique<wasm_program>(Script, Kind)};
|
||||
if (false == loaded->instantiate(module))
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::unique_ptr<runtime> make_wasm_runtime()
|
||||
{
|
||||
auto started{std::make_unique<wasm_runtime_host>()};
|
||||
if (false == started->start())
|
||||
{
|
||||
return nullptr;
|
||||
}
|
||||
return started;
|
||||
}
|
||||
|
||||
} // namespace script_screens
|
||||
Reference in New Issue
Block a user