63 lines
1.7 KiB
C++
63 lines
1.7 KiB
C++
#include "pch.h"
|
|
#include "utils.h"
|
|
|
|
namespace Localization {
|
|
using Key = uint16_t;
|
|
|
|
// Maps localization keys to their string identifiers. This is used for text elements to look up the correct localized string.
|
|
inline std::unordered_map<std::string, Key> localization_key_map;
|
|
|
|
using LanguageCode = uint32_t; // 32-bit integer to store the language code (e.g., "en", "fr", "es")
|
|
|
|
inline LanguageCode current_language = 'e' << 24 | 'n' << 16;
|
|
|
|
using JoinedKey = uint64_t; // 64-bit integer to store the joined language code and key
|
|
|
|
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;
|
|
|
|
inline std::string get(Key key) {
|
|
auto it = localized_strings.find(join_keys(current_language, key));
|
|
if (it != localized_strings.end())
|
|
return it->second;
|
|
|
|
for (const auto &[joined, value] : localized_strings) {
|
|
Key k = (Key)(joined & 0xFFFF);
|
|
if (k == key)
|
|
return value;
|
|
}
|
|
|
|
return "Localization not set!";
|
|
}
|
|
|
|
inline LanguageCode lang_from_sym(mrb_state *mrb, mrb_sym sym) {
|
|
const char *s = mrb_sym2name(mrb, sym);
|
|
size_t len = strlen(s);
|
|
|
|
if (len == 0 || len > 4)
|
|
return 0;
|
|
|
|
LanguageCode code = 0;
|
|
|
|
for (size_t i = 0; i < len; ++i) {
|
|
code |= (static_cast<LanguageCode>(s[i]) << (8 * (3 - i)));
|
|
}
|
|
|
|
return code;
|
|
}
|
|
|
|
inline Key key_from_sym(mrb_state *mrb, mrb_sym sym) {
|
|
const char *key_name = mrb_sym2name(mrb, sym);
|
|
|
|
auto it = localization_key_map.find(key_name);
|
|
if (it != localization_key_map.end())
|
|
return it->second;
|
|
|
|
Key new_id = (Key)localization_key_map.size();
|
|
localization_key_map[key_name] = new_id;
|
|
return new_id;
|
|
}
|
|
} // namespace Localization
|