TrinityCore
Loading...
Searching...
No Matches
LanguageMgr.cpp
Go to the documentation of this file.
1/*
2 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 * more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "LanguageMgr.h"
19#include "DB2Stores.h"
20#include "Log.h"
21#include "MapUtils.h"
22#include "SpellMgr.h"
23#include "Timer.h"
24#include "Util.h"
25
26LanguageMgr::LanguageMgr() : _langsMap(), _wordsMap() { }
27
29{
30 _langsMap.clear();
31 _wordsMap.clear();
32}
33
39
41{
42 ASSERT(spellEffect && spellEffect->Effect == SPELL_EFFECT_LANGUAGE);
43
44 uint32 languageId = uint32(spellEffect->EffectMiscValue[0]);
45
46 _langsMap.emplace(languageId, LanguageDesc{ spellEffect->SpellID, 0 }); // register without a skill id for now
47}
48
50{
51 uint32 oldMSTime = getMSTime();
52
53 // Load languages from Languages.db2. Just the id, we don't need the name
54 for (LanguagesEntry const* langEntry : sLanguagesStore)
55 {
56 auto spellsRange = Trinity::Containers::MapEqualRange(_langsMap, langEntry->ID);
57 if (spellsRange.begin() == spellsRange.end())
58 _langsMap.emplace(langEntry->ID, LanguageDesc());
59 else
60 {
61 std::vector<LanguageDesc> langsWithSkill;
62 for (LanguagesMap::value_type const& spellItr : spellsRange)
63 for (SkillLineAbilityMap::value_type const& skillPair : Trinity::Containers::MakeIteratorPair(sSpellMgr->GetSkillLineAbilityMapBounds(spellItr.second.SpellId)))
64 langsWithSkill.emplace_back(LanguageDesc{ spellItr.second.SpellId, uint32(skillPair.second->SkillLine) });
65
66 for (LanguageDesc const& langDesc : langsWithSkill)
67 {
68 // erase temporary assignment that lacked skill
69 Trinity::Containers::MultimapErasePair(_langsMap, langEntry->ID, { langDesc.SpellId, 0 });
70 _langsMap.emplace(langEntry->ID, langDesc);
71 }
72 }
73 }
74
75 // Add the languages used in code in case they don't exist
76 _langsMap.emplace(LANG_UNIVERSAL, LanguageDesc());
77 _langsMap.emplace(LANG_ADDON, LanguageDesc());
78 _langsMap.emplace(LANG_ADDON_LOGGED, LanguageDesc());
79
80 // Log load time
81 TC_LOG_INFO("server.loading", ">> Loaded {} languages in {} ms", uint32(_langsMap.size()), GetMSTimeDiffToNow(oldMSTime));
82}
83
85{
86 uint32 oldMSTime = getMSTime();
87
88 uint32 wordsNum = 0;
89 for (LanguageWordsEntry const* wordEntry : sLanguageWordsStore)
90 {
91 uint8 length = std::min(18U, uint32(strlen(wordEntry->Word)));
92
93 WordKey key = WordKey(wordEntry->LanguageID, length);
94
95 _wordsMap[key].push_back(wordEntry->Word);
96 ++wordsNum;
97 }
98
99 // log load time
100 TC_LOG_INFO("server.loading", ">> Loaded {} word groups from {} words in {} ms", uint32(_wordsMap.size()), wordsNum, GetMSTimeDiffToNow(oldMSTime));
101}
102
104{
105 return Trinity::Containers::MapGetValuePtr(_wordsMap, WordKey(language, wordLen));
106}
107
108namespace
109{
110 void StripHyperlinks(std::string const& source, std::string& dest)
111 {
112 dest.resize(source.length());
113 size_t destSize = 0;
114 bool skipSquareBrackets = false;
115 for (size_t i = 0; i < source.length(); ++i)
116 {
117 char c = source[i];
118 if (c != '|')
119 {
120 if (!skipSquareBrackets || (c != '[' && c != ']'))
121 dest[destSize++] = source[i];
122
123 continue;
124 }
125
126 if (i + 1 >= source.length())
127 break;
128
129 switch (source[i + 1])
130 {
131 case 'c':
132 case 'C':
133 // skip color
134 if (i + 2 >= source.length())
135 break;
136
137 if (source[i + 2] == 'n')
138 i = source.find(':', i); // numeric color id
139 else
140 i += 9;
141 break;
142 case 'r':
143 ++i;
144 break;
145 case 'H':
146 // skip just past first |h
147 i = source.find("|h", i);
148 if (i != std::string::npos)
149 i += 2;
150 skipSquareBrackets = true;
151 break;
152 case 'h':
153 ++i;
154 skipSquareBrackets = false;
155 break;
156 case 'T':
157 // skip just past closing |t
158 i = source.find("|t", i);
159 if (i != std::string::npos)
160 i += 2;
161 break;
162 default:
163 break;
164 }
165 }
166
167 dest.resize(destSize);
168 }
169
170 void ReplaceUntranslatableCharactersWithSpace(std::string& text)
171 {
172 std::wstring wstrText;
173 if (!Utf8toWStr(text, wstrText))
174 return;
175
176 for (wchar_t& w : wstrText)
177 if (!isLatin1Character(w) && !isNumeric(w) && w <= 0xFF && w != L'\'')
178 w = L' ';
179
180 WStrToUtf8(wstrText, text);
181 }
182
183 constexpr char upper_backslash(char c)
184 {
185 if (c == '/')
186 return '\\';
187 if (c >= 'a' && c <= 'z')
188 return char('A' + char(c - 'a'));
189 else
190 return c;
191 }
192
193 constexpr std::array<uint32, 16> sstr_hashtable =
194 {
195 0x486E26EE, 0xDCAA16B3, 0xE1918EEF, 0x202DAFDB,
196 0x341C7DC7, 0x1C365303, 0x40EF2D37, 0x65FD5E49,
197 0xD6057177, 0x904ECE93, 0x1C38024F, 0x98FD323B,
198 0xE3061AE7, 0xA39B0FA1, 0x9797F25F, 0xE4444563,
199 };
200
201 constexpr uint32 SStrHash(std::string_view string, bool caseInsensitive, uint32 seed = 0x7FED7FED)
202 {
203 uint32 shift = 0xEEEEEEEE;
204 for (char c : string)
205 {
206 if (caseInsensitive)
207 c = upper_backslash(c);
208
209 seed = (sstr_hashtable[c >> 4] - sstr_hashtable[c & 0xF]) ^ (shift + seed);
210 shift = c + seed + 33 * shift + 3;
211 }
212
213 return seed ? seed : 1;
214 }
215}
216
217std::string LanguageMgr::Translate(std::string const& msg, uint32 language, LocaleConstant locale) const
218{
219 std::string textToTranslate;
220 StripHyperlinks(msg, textToTranslate);
221 ReplaceUntranslatableCharactersWithSpace(textToTranslate);
222
223 std::string result;
224 result.reserve(textToTranslate.length());
225 for (std::string_view str : Trinity::Tokenize(textToTranslate, ' ', false))
226 {
227 uint32 wordLen = std::min(18u, uint32(str.length()));
228 if (LanguageMgr::WordList const* wordGroup = FindWordGroup(language, wordLen))
229 {
230 uint32 wordHash = SStrHash(str, true);
231 uint8 idxInsideGroup = language * wordHash % wordGroup->size();
232
233 char const* replacementWord = (*wordGroup)[idxInsideGroup];
234
235 switch (locale)
236 {
237 case LOCALE_koKR:
238 case LOCALE_zhCN:
239 case LOCALE_zhTW:
240 {
241 size_t length = std::min(str.length(), strlen(replacementWord));
242 for (size_t i = 0; i < length; ++i)
243 {
244 if (str[i] >= 'A' && str[i] <= 'Z')
245 result += charToUpper(replacementWord[i]);
246 else
247 result += replacementWord[i];
248 }
249 break;
250 }
251 default:
252 {
253 std::wstring wstrSourceWord;
254 if (Utf8toWStr(str, wstrSourceWord))
255 {
256 size_t length = std::min(wstrSourceWord.length(), strlen(replacementWord));
257 for (size_t i = 0; i < length; ++i)
258 {
259 if (wstrSourceWord[i] != L'\'' && isUpper(wstrSourceWord[i]))
260 result += charToUpper(replacementWord[i]);
261 else
262 result += charToLower(replacementWord[i]);
263 }
264 }
265 break;
266 }
267 }
268 }
269
270 result += ' ';
271 }
272
273 if (!result.empty())
274 result.pop_back();
275
276 return result;
277}
278
280{
281 return sLanguagesStore.HasRecord(languageId);
282}
283
LocaleConstant
Definition Common.h:51
@ LOCALE_zhCN
Definition Common.h:56
@ LOCALE_zhTW
Definition Common.h:57
@ LOCALE_koKR
Definition Common.h:53
DB2Storage< LanguageWordsEntry > sLanguageWordsStore("LanguageWords.db2", &LanguageWordsLoadInfo::Instance)
DB2Storage< LanguagesEntry > sLanguagesStore("Languages.db2", &LanguagesLoadInfo::Instance)
uint8_t uint8
Definition Define.h:156
uint32_t uint32
Definition Define.h:154
#define ASSERT
Definition Errors.h:80
#define TC_LOG_INFO(filterType__, message__,...)
Definition Log.h:184
Language
@ LANG_ADDON_LOGGED
@ LANG_UNIVERSAL
@ LANG_ADDON
@ SPELL_EFFECT_LANGUAGE
#define sSpellMgr
Definition SpellMgr.h:812
uint32 GetMSTimeDiffToNow(uint32 oldMSTime)
Definition Timer.h:57
uint32 getMSTime()
Definition Timer.h:33
bool WStrToUtf8(wchar_t const *wstr, size_t size, std::string &utf8str)
Definition Util.cpp:386
bool Utf8toWStr(char const *utf8str, size_t csize, wchar_t *wstr, size_t &wsize)
Definition Util.cpp:336
bool isNumeric(wchar_t wchar)
Definition Util.h:207
bool isLatin1Character(wchar_t wchar)
Definition Util.h:151
struct CharToUpper charToUpper
struct CharToLower charToLower
bool isUpper(wchar_t wchar)
Definition Util.h:352
std::pair< uint32, uint8 > WordKey
Definition LanguageMgr.h:43
WordList const * FindWordGroup(uint32 language, uint32 wordLen) const
WordsMap _wordsMap
Definition LanguageMgr.h:94
void LoadSpellEffectLanguage(SpellEffectEntry const *spellEffect)
void LoadLanguages()
Trinity::IteratorPair< LanguagesMap::const_iterator > GetLanguageDescById(Language languageId) const
LanguagesMap _langsMap
Definition LanguageMgr.h:93
std::string Translate(std::string const &msg, uint32 language, LocaleConstant locale) const
static LanguageMgr * instance()
void LoadLanguagesWords()
bool IsLanguageExist(uint32 languageId) const
std::vector< char const * > WordList
Definition LanguageMgr.h:44
Utility class to enable range for loop syntax for multimap.equal_range uses.
auto MapEqualRange(M &map, typename M::key_type const &key)
constexpr IteratorPair< iterator, end_iterator > MakeIteratorPair(iterator first, end_iterator second)
auto MapGetValuePtr(M &map, typename M::key_type const &key)
Definition MapUtils.h:37
void MultimapErasePair(M &multimap, typename M::key_type const &key, typename M::mapped_type const &value)
Definition MapUtils.h:57
TC_COMMON_API std::vector< std::string_view > Tokenize(std::string_view str, char sep, bool keepEmpty)
Definition Util.cpp:57
uint32 SpellId
Definition LanguageMgr.h:30
std::array< int32, 2 > EffectMiscValue