Add ruby bindings for internal structures, allow better controlled localization

This commit is contained in:
2026-05-06 22:01:48 +01:00
parent 3894b90398
commit 65109cc3c4
8 changed files with 1047 additions and 114 deletions
+33 -12
View File
@@ -16,6 +16,7 @@ struct Element {
Vec2<float> position = {0, 0};
float rotation = 0;
Vec2<float> scale = {1, 1};
float alpha = 1.0f;
float z = 0;
bool click_through = false;
Ruby::Block on_click;
@@ -56,28 +57,38 @@ struct EImage : Element {
return;
int frame_index = (int)((abs_time * animation.frame_rate) / 1000) % animation.frames.size();
window.draw(animation.frames[frame_index], position, z, rotation, scale);
window.draw(animation.frames[frame_index], position, z, rotation, scale, alpha);
}
};
struct EText : Element {
Localization::Key key;
uint64_t font_id = UINT64_MAX;
Color color = {255, 255, 255};
mrb_value params = mrb_nil_value();
~EText() {
if (text_id != UINT64_MAX)
text_pool.release(text_id);
if (font_id != UINT64_MAX)
font_pool.release(font_id);
if (!mrb_nil_p(params))
mrb_gc_unregister(Ruby::mrb, params);
}
Color color = {255, 255, 255, 255};
EText(Localization::Key key, uint64_t font_id, Color color)
: Element(Type::TEXT), key(key), font_id(font_id), color(color) {
EText(Localization::Key key, uint64_t font_id, Color color, mrb_value params)
: Element(Type::TEXT), key(key), font_id(font_id), color(color), params(params) {
if (!mrb_nil_p(params))
mrb_gc_protect(Ruby::mrb, params);
font_pool.use(font_id);
}
void reload_params() {
// Force re-render by resetting last_key (without affecting this frame)
// this can be changed to use a dirty flag or version counter if needed
last_key = UINT16_MAX;
}
Vec2<float> size(Window *window) override {
if (text_id == UINT64_MAX)
return {0, 0};
@@ -85,26 +96,32 @@ struct EText : Element {
};
void render(Window &window, uint64_t) override {
if (last_language != Localization::current_language || last_key != key || text_id == UINT64_MAX) {
std::string localized_str = Localization::get(key);
if (
last_language != Localization::current_language
|| last_key != key || text_id == UINT64_MAX
|| last_color != color
) {
std::string localized_str = Localization::get(Ruby::mrb, key, params);
if (text_id != UINT64_MAX)
text_pool.release(text_id);
text_id = window.create_text(font_id, localized_str.c_str(), localized_str.size(), color);
last_language = Localization::current_language;
last_key = key;
last_color = color;
}
window.write(text_id, position, z, rotation, scale);
window.write(text_id, position, z, rotation, scale, alpha);
}
private:
uint64_t text_id = UINT64_MAX;
Localization::LanguageCode last_language = UINT_MAX;
Localization::Key last_key = UINT_MAX;
Color last_color = color;
Localization::LanguageCode last_language = UINT32_MAX;
Localization::Key last_key = UINT16_MAX;
};
struct ERect : Element {
Vec2<float> shape = {0, 0};
Color color = {255, 255, 255, 255};
Color color = {255, 255, 255};
Vec2<float> size(Window *) override {
return shape;
};
@@ -112,7 +129,7 @@ struct ERect : Element {
ERect(Vec2<float> shape, Color color) : Element(Type::RECT), shape(shape), color(color) {}
void render(Window &window, uint64_t) override {
window.draw_rect(Rect::from_size(position, shape), color, z, rotation);
window.draw_rect(Rect::from_size(position, shape), color, z, rotation, scale, alpha);
}
};
@@ -195,6 +212,10 @@ struct App {
bool running = true;
Vec2<float> mouse_position = {-1, -1};
void exit() {
running = false;
}
void switch_to_scene(uint64_t scene_id) {
scene_pool.release(current_scene_id);
scene_pool.use(scene_id);
File diff suppressed because it is too large Load Diff
+2
View File
@@ -94,6 +94,8 @@ DEF_SYM(bold)
DEF_SYM(italic)
DEF_SYM(underline)
DEF_SYM(position)
DEF_SYM(rotation)
DEF_SYM(scale)
DEF_SYM(alpha)
DEF_SYM(fps)
DEF_SYM(click_through)
+83 -9
View File
@@ -17,20 +17,87 @@ inline JoinedKey join_keys(LanguageCode lang_code, Key loc_key) {
return (static_cast<JoinedKey>(lang_code) << 16) | loc_key;
}
inline std::unordered_map<JoinedKey, std::string> localized_strings;
struct Segment {
bool is_var;
std::string text;
};
inline std::string get(Key key) {
auto it = localized_strings.find(join_keys(current_language, key));
if (it != localized_strings.end())
inline std::unordered_map<JoinedKey, std::vector<Segment>> localized_strings;
inline std::unordered_map<std::string, mrb_sym> var_sym_cache;
inline mrb_sym get_var_sym(mrb_state *mrb, const std::string &name) {
auto it = var_sym_cache.find(name);
if (it != var_sym_cache.end())
return it->second;
for (const auto &[joined, value] : localized_strings) {
Key k = (Key)(joined & 0xFFFF);
if (k == key)
return value;
mrb_sym sym = mrb_intern_cstr(mrb, name.c_str());
var_sym_cache[name] = sym;
return sym;
}
inline std::vector<Segment> parse_localized(const std::string &input) {
std::vector<Segment> out;
size_t i = 0;
while (i < input.size()) {
size_t start = input.find("%{", i);
if (start == std::string::npos) {
out.push_back({false, input.substr(i)});
break;
}
if (start > i) {
out.push_back({false, input.substr(i, start - i)});
}
size_t end = input.find("}", start);
if (end == std::string::npos) {
// malformed fallback
out.push_back({false, input.substr(start)});
break;
}
std::string var = input.substr(start + 2, end - (start + 2));
out.push_back({true, var});
i = end + 1;
}
return "Localization not set!";
return out;
}
inline void set(LanguageCode lang_code, Key key, const std::string &text) {
localized_strings[join_keys(lang_code, key)] = parse_localized(text);
}
inline std::string get(mrb_state *mrb, Key key, mrb_value hash) {
auto it = localized_strings.find(join_keys(current_language, key));
if (it == localized_strings.end())
return "Localization not set!";
const auto &entry = it->second;
std::string result;
result.reserve(10);
for (const auto &seg : entry) {
if (!seg.is_var) {
result += seg.text;
} else {
mrb_sym sym = get_var_sym(mrb, seg.text);
if (mrb_nil_p(hash) || mrb_nil_p(mrb_hash_get(mrb, hash, mrb_symbol_value(sym)))) {
result += "%{" + seg.text + "}";
continue;
}
mrb_value val = mrb_hash_get(mrb, hash, mrb_symbol_value(sym));
if (mrb_nil_p(val))
continue;
result += mrb_str_to_cstr(mrb, val);
}
}
return result;
}
inline LanguageCode lang_from_sym(mrb_state *mrb, mrb_sym sym) {
@@ -49,6 +116,13 @@ inline LanguageCode lang_from_sym(mrb_state *mrb, mrb_sym sym) {
return code;
}
inline mrb_sym lang_to_sym(mrb_state *mrb, LanguageCode code) {
char s[5] = {0};
for (int i = 0; i < 4; ++i)
s[i] = (code >> (8 * (3 - i))) & 0xFF;
return mrb_intern_cstr(mrb, s);
}
inline Key key_from_sym(mrb_state *mrb, mrb_sym sym) {
const char *key_name = mrb_sym2name(mrb, sym);
+5 -1
View File
@@ -9,7 +9,11 @@
#define UNUSED(x) (void)(x)
struct Color {
uint8_t r, g, b = 0, a = 255;
uint8_t r, g, b = 0;
bool operator!=(const Color &other) const {
return r != other.r || g != other.g || b != other.b;
}
};
template <typename T>
+6 -7
View File
@@ -83,8 +83,6 @@ struct Event {
struct Animation {
std::vector<uint64_t> frames;
float frame_rate;
bool loop;
int reference_count = 0;
~Animation() {
for (uint64_t frame_id : frames)
@@ -104,20 +102,20 @@ public:
~Window();
// Rendering functions
uint64_t load_image(const char *path, float alpha = 1.0f, bool pixel_art = false);
uint64_t load_image(const char *path, bool pixel_art);
Vec2<float> get_image_size(uint64_t image_id);
uint64_t load_font(const char *path, int font_size, bool bold = false, bool italic = false, bool underline = false, bool pixel_art = false);
uint64_t load_font(const char *path, int font_size, bool bold, bool italic, bool underline, bool pixel_art);
// text is copied internally, so it can be free'd by the caller after the text is created.
uint64_t create_text(uint64_t font_id, const char *text, uint32_t length, Color color);
Vec2<float> get_text_size(uint64_t text_id);
bool write(uint64_t text_id, Vec2<float> position, float z, float angle = 0.0f, Vec2<float> scale = {1.0f, 1.0f});
bool write(uint64_t text_id, Vec2<float> position, float z, float angle, Vec2<float> scale, float alpha);
bool draw(uint64_t image_id, Vec2<float> position, float z, float angle = 0.0f, Vec2<float> scale = {1.0f, 1.0f});
bool draw(uint64_t image_id, Vec2<float> position, float z, float angle, Vec2<float> scale, float alpha);
bool draw_rect(Rect rect, Color color, float z, float angle = 0.0f);
bool draw_rect(Rect rect, Color color, float z, float angle, Vec2<float> scale, float alpha);
void render(); // the rest of the calls only build the instruction list, this actually renders everything added to the screen (following z order)
@@ -170,6 +168,7 @@ private:
float z;
float angle;
Vec2<float> scale;
float alpha;
union {
struct {
+17 -22
View File
@@ -4,33 +4,35 @@ main_scene = Scene.new
default_font = Font.new "assets/fonts/charybdis.ttf", 24, pixel_art: true
bg_image1 = Image.new "assets/images/menu_bg.png", alpha: 0.7, pixel_art: true
bg_image2 = Image.new "assets/images/game_over_dead_bg.png", alpha: 1, pixel_art: true
bg_image1 = Image.new "assets/images/menu_bg.png", pixel_art: true
bg_image2 = Image.new "assets/images/game_over_dead_bg.png", pixel_art: true
bg_animation = Animation.new [bg_image1, bg_image2], fps: 5
App.language = :en
App.localize(:en, :btn_text, "Click me!")
App.localize(:en, :btn_text, "Click %{name}!")
text = ElementText.new :btn_text, default_font, position: {x: 50, y: 50}, z: 1, click_through: true
text = ElementText.new :btn_text, default_font, 0xFFFFFF, {name: "Me"}, position: {x: 50, y: 50}, z: 1, click_through: true, alpha: 1
rect = ElementRect.new({x: 50, y: 50, w: 100, h: 25}, 0xFF0000FF, z: 0)
rect = ElementRect.new 100, 25, 0xFF0000, position: {x: 50, y: 50}, z: 0, rotation: 60, scale: { x: 1.5, y: 1 }, alpha: 0.4
image_element = ElementImage.new bg_animation, position: {x: 0, y: 0}, z: -1, click_through: true
image_element = ElementImage.new bg_animation, position: {x: 0, y: 0}, z: -1, click_through: true, alpha: 1
rect.on_click do
rect.color = rect.color == 0xFF0000FF ?
0x00FF00FF
:
0xFF0000FF
rect.color = rect.color == 0xFF0000 ?
0x00FF00 :
0xFF0000
text.params[:name] = text.params[:name] == "Me" ?
"You" :
"Me"
text.params!
end
=begin
input handling:
on_click - exists to simplify on elements, not the standard way.
App.map_key(:space, :jump) # maps the space key to a :jump action (multiple keys can be mapped to the same action)
# all events here are in english ones, (so need to find which english key corresponds to the key in the current language of the keyboard)
key can be one of [:a..:z, :0..:9, :space, :enter, :shift, :ctrl, :alt, :tab, :backspace, :escape, :up, :down, :left, :right, :middle]
@@ -58,16 +60,9 @@ App.text_input # returns the text typed this frame as a string (useful for text
App.stop_text_input!
####
also in a scene you can use (with click_though semantics):
main_scene.elements_at(x, y)
=end
main_scene.on_update do |delta_time|
# puts "Delta time: #{delta_time}ms"
# commented out to avoid spamming the console, but you can uncomment to see the delta time being printed every frame
@@ -76,11 +71,11 @@ main_scene.on_update do |delta_time|
el = main_scene.elements_at(App.mouse_position)
for elem in el
if elem == image_element
puts "Hovering over image element"
#puts "Hovering over image element"
elsif elem == rect
puts "Hovering over rect element"
#puts "Hovering over rect element"
elsif elem == text
puts "Hovering over text element"
#puts "Hovering over text element"
end
end
+16 -11
View File
@@ -56,7 +56,7 @@ Window::~Window() {
SDL_Quit();
}
uint64_t Window::load_image(const char *path, float alpha, bool pixel_art) {
uint64_t Window::load_image(const char *path, bool pixel_art) {
SDL_Texture *texture = IMG_LoadTexture(renderer, path);
if (pixel_art) {
@@ -68,8 +68,6 @@ uint64_t Window::load_image(const char *path, float alpha, bool pixel_art) {
return UINT64_MAX;
}
SDL_SetTextureAlphaMod(texture, (uint8_t)(alpha * 255));
float w, h;
SDL_GetTextureSize(texture, &w, &h);
@@ -119,7 +117,7 @@ uint64_t Window::create_text(uint64_t font_id, const char *text, uint32_t length
return UINT64_MAX;
}
SDL_Color sdl_color = {color.r, color.g, color.b, color.a};
SDL_Color sdl_color = {color.r, color.g, color.b, 255};
SDL_Surface *surface = TTF_RenderText_Solid(font_pool[font_id]->font, text, length, sdl_color);
if (surface == nullptr) {
@@ -157,7 +155,7 @@ Vec2<float> Window::get_text_size(uint64_t text_id) {
return text_pool[text_id]->size;
}
bool Window::write(uint64_t text_id, Vec2<float> position, float z, float angle, Vec2<float> scale) {
bool Window::write(uint64_t text_id, Vec2<float> position, float z, float angle, Vec2<float> scale, float alpha) {
if (!text_pool.is_valid(text_id)) {
fprintf(stderr, "(Write) Invalid text ID: %llu\n", (unsigned long long)text_id);
return false;
@@ -168,6 +166,7 @@ bool Window::write(uint64_t text_id, Vec2<float> position, float z, float angle,
.z = z,
.angle = angle,
.scale = scale,
.alpha = alpha,
.draw_text = {
.text_id = text_id,
.position = position,
@@ -177,7 +176,7 @@ bool Window::write(uint64_t text_id, Vec2<float> position, float z, float angle,
return true;
};
bool Window::draw(uint64_t image_id, Vec2<float> position, float z, float angle, Vec2<float> scale) {
bool Window::draw(uint64_t image_id, Vec2<float> position, float z, float angle, Vec2<float> scale, float alpha) {
if (!image_pool.is_valid(image_id)) {
fprintf(stderr, "Invalid image ID: %llu\n", (unsigned long long)image_id);
return false;
@@ -188,6 +187,7 @@ bool Window::draw(uint64_t image_id, Vec2<float> position, float z, float angle,
.z = z,
.angle = angle,
.scale = scale,
.alpha = alpha,
.draw_image = {
.image_id = image_id,
.position = position,
@@ -197,12 +197,13 @@ bool Window::draw(uint64_t image_id, Vec2<float> position, float z, float angle,
return true;
};
bool Window::draw_rect(Rect rect, Color color, float z, float angle) {
bool Window::draw_rect(Rect rect, Color color, float z, float angle, Vec2<float> scale, float alpha) {
render_instructions.push_back(
{.type = RenderInstruction::DRAW_RECT,
.z = z,
.angle = angle,
.scale = {1.0f, 1.0f},
.scale = scale,
.alpha = alpha,
.draw_rect = {
.rect = rect,
.color = color,
@@ -276,6 +277,8 @@ void Window::render() {
dst_rect.w = scale_x * text->size.x;
dst_rect.h = scale_y * text->size.y;
SDL_SetTextureAlphaModFloat(texture, instruction.alpha);
SDL_RenderTextureRotated(
renderer,
texture,
@@ -306,6 +309,8 @@ void Window::render() {
dst_rect.w = scale_x * image->size.x;
dst_rect.h = scale_y * image->size.y;
SDL_SetTextureAlphaModFloat(image->texture, instruction.alpha);
SDL_RenderTextureRotated(
renderer,
image->texture,
@@ -321,8 +326,8 @@ void Window::render() {
SDL_FRect dst_rect;
dst_rect.x = instruction.draw_rect.rect.x() * scale + offset.x;
dst_rect.y = instruction.draw_rect.rect.y() * scale + offset.y;
dst_rect.w = instruction.draw_rect.rect.w() * scale;
dst_rect.h = instruction.draw_rect.rect.h() * scale;
dst_rect.w = instruction.draw_rect.rect.w() * scale * instruction.scale.x;
dst_rect.h = instruction.draw_rect.rect.h() * scale * instruction.scale.y;
SDL_SetTextureColorMod(
white_tex,
@@ -331,7 +336,7 @@ void Window::render() {
instruction.draw_rect.color.b
);
SDL_SetTextureAlphaMod(white_tex, instruction.draw_rect.color.a);
SDL_SetTextureAlphaModFloat(white_tex, instruction.alpha);
SDL_RenderTextureRotated(
renderer,