Maintain a circular buffer of recent commands, add to crashlog.
[openttd-joker.git] / src / newgrf_text.cpp
blob943e236ef645aeac889f4b5d305c1e1e38f67dc9
1 /* $Id: newgrf_text.cpp 26244 2014-01-12 18:01:33Z frosch $ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /**
11 * @file newgrf_text.cpp
12 * Implementation of Action 04 "universal holder" structure and functions.
13 * This file implements a linked-lists of strings,
14 * holding everything that the newgrf action 04 will send over to OpenTTD.
15 * One of the biggest problems is that Dynamic lang Array uses ISO codes
16 * as way to identifying current user lang, while newgrf uses bit shift codes
17 * not related to ISO. So equivalence functionnality had to be set.
20 #include "stdafx.h"
21 #include "newgrf.h"
22 #include "strings_func.h"
23 #include "newgrf_storage.h"
24 #include "newgrf_text.h"
25 #include "newgrf_cargo.h"
26 #include "newgrf_config.h"
27 #include "string_func.h"
28 #include "date_type.h"
29 #include "debug.h"
30 #include "core/alloc_type.hpp"
31 #include "core/smallmap_type.hpp"
32 #include "language.h"
34 #include "table/strings.h"
35 #include "table/control_codes.h"
37 #include "safeguards.h"
39 /**
40 * Explains the newgrf shift bit positioning.
41 * the grf base will not be used in order to find the string, but rather for
42 * jumping from standard langID scheme to the new one.
44 enum GRFBaseLanguages {
45 GRFLB_AMERICAN = 0x01,
46 GRFLB_ENGLISH = 0x02,
47 GRFLB_GERMAN = 0x04,
48 GRFLB_FRENCH = 0x08,
49 GRFLB_SPANISH = 0x10,
50 GRFLB_GENERIC = 0x80,
53 enum GRFExtendedLanguages {
54 GRFLX_AMERICAN = 0x00,
55 GRFLX_ENGLISH = 0x01,
56 GRFLX_GERMAN = 0x02,
57 GRFLX_FRENCH = 0x03,
58 GRFLX_SPANISH = 0x04,
59 GRFLX_UNSPECIFIED = 0x7F,
62 /**
63 * Element of the linked list.
64 * Each of those elements represent the string,
65 * but according to a different lang.
67 struct GRFText {
68 public:
69 /**
70 * Allocate, and assign a new GRFText with the given text.
71 * As these strings can have string terminations in them, e.g.
72 * due to "choice lists" we (sometimes) cannot rely on detecting
73 * the length by means of strlen. Also, if the length of already
74 * known not scanning the whole string is more efficient.
75 * @param langid The language of the text.
76 * @param text The text to store in the new GRFText.
77 * @param len The length of the text.
79 static GRFText *New(byte langid, const char *text, size_t len)
81 return new (len) GRFText(langid, text, len);
84 /**
85 * Create a copy of this GRFText.
86 * @param orig the grftext to copy.
87 * @return an exact copy of the given text.
89 static GRFText *Copy(GRFText *orig)
91 return GRFText::New(orig->langid, orig->text, orig->len);
94 /**
95 * Helper allocation function to disallow something.
96 * Don't allow simple 'news'; they wouldn't have enough memory.
97 * @param size the amount of space not to allocate.
99 void *operator new(size_t size)
101 NOT_REACHED();
105 * Free the memory we allocated.
106 * @param p memory to free.
108 void operator delete(void *p)
110 free(p);
112 private:
114 * Actually construct the GRFText.
115 * @param langid_ The language of the text.
116 * @param text_ The text to store in this GRFText.
117 * @param len_ The length of the text to store.
119 GRFText(byte langid_, const char *text_, size_t len_) : next(NULL), len(len_), langid(langid_)
121 /* We need to use memcpy instead of strcpy due to
122 * the possibility of "choice lists" and therefore
123 * intermediate string terminators. */
124 memcpy(this->text, text_, len);
128 * Allocate memory for this class.
129 * @param size the size of the instance
130 * @param extra the extra memory for the text
131 * @return the requested amount of memory for both the instance and the text
133 void *operator new(size_t size, size_t extra)
135 return MallocT<byte>(size + extra);
138 public:
139 GRFText *next; ///< The next GRFText in this chain.
140 size_t len; ///< The length of the stored string, used for copying.
141 byte langid; ///< The language associated with this GRFText.
142 char text[]; ///< The actual (translated) text.
147 * Holder of the above structure.
148 * Putting both grfid and stringid together allows us to avoid duplicates,
149 * since it is NOT SUPPOSED to happen.
151 struct GRFTextEntry {
152 uint32 grfid;
153 uint16 stringid;
154 StringID def_string;
155 GRFText *textholder;
159 static uint _num_grf_texts = 0;
160 static GRFTextEntry _grf_text[TAB_SIZE_NEWGRF];
161 static byte _currentLangID = GRFLX_ENGLISH; ///< by default, english is used.
164 * Get the mapping from the NewGRF supplied ID to OpenTTD's internal ID.
165 * @param newgrf_id The NewGRF ID to map.
166 * @param gender Whether to map genders or cases.
167 * @return The, to OpenTTD's internal ID, mapped index, or -1 if there is no mapping.
169 int LanguageMap::GetMapping(int newgrf_id, bool gender) const
171 const SmallVector<Mapping, 1> &map = gender ? this->gender_map : this->case_map;
172 for (const Mapping *m = map.Begin(); m != map.End(); m++) {
173 if (m->newgrf_id == newgrf_id) return m->openttd_id;
175 return -1;
179 * Get the mapping from OpenTTD's internal ID to the NewGRF supplied ID.
180 * @param openttd_id The OpenTTD ID to map.
181 * @param gender Whether to map genders or cases.
182 * @return The, to the NewGRF supplied ID, mapped index, or -1 if there is no mapping.
184 int LanguageMap::GetReverseMapping(int openttd_id, bool gender) const
186 const SmallVector<Mapping, 1> &map = gender ? this->gender_map : this->case_map;
187 for (const Mapping *m = map.Begin(); m != map.End(); m++) {
188 if (m->openttd_id == openttd_id) return m->newgrf_id;
190 return -1;
193 /** Helper structure for mapping choice lists. */
194 struct UnmappedChoiceList : ZeroedMemoryAllocator {
195 /** Clean everything up. */
196 ~UnmappedChoiceList()
198 for (SmallPair<byte, char *> *p = this->strings.Begin(); p < this->strings.End(); p++) {
199 free(p->second);
204 * Initialise the mapping.
205 * @param type The type of mapping.
206 * @param old_d The old begin of the string, i.e. from where to start writing again.
207 * @param offset The offset to get the plural/gender from.
209 UnmappedChoiceList(StringControlCode type, char *old_d, int offset) :
210 type(type), old_d(old_d), offset(offset)
214 StringControlCode type; ///< The type of choice list.
215 char *old_d; ///< The old/original location of the "d" local variable.
216 int offset; ///< The offset for the plural/gender form.
218 /** Mapping of NewGRF supplied ID to the different strings in the choice list. */
219 SmallMap<byte, char *> strings;
222 * Flush this choice list into the old d variable.
223 * @param lm The current language mapping.
224 * @return The new location of the output string.
226 char *Flush(const LanguageMap *lm)
228 if (!this->strings.Contains(0)) {
229 /* In case of a (broken) NewGRF without a default,
230 * assume an empty string. */
231 grfmsg(1, "choice list misses default value");
232 this->strings[0] = stredup("");
235 char *d = old_d;
236 if (lm == NULL) {
237 /* In case there is no mapping, just ignore everything but the default.
238 * A probable cause for this happening is when the language file has
239 * been removed by the user and as such no mapping could be made. */
240 size_t len = strlen(this->strings[0]);
241 memcpy(d, this->strings[0], len);
242 return d + len;
245 d += Utf8Encode(d, this->type);
247 if (this->type == SCC_SWITCH_CASE) {
249 * Format for case switch:
250 * <NUM CASES> <CASE1> <LEN1> <STRING1> <CASE2> <LEN2> <STRING2> <CASE3> <LEN3> <STRING3> <STRINGDEFAULT>
251 * Each LEN is printed using 2 bytes in big endian order.
254 /* "<NUM CASES>" */
255 int count = 0;
256 for (uint8 i = 0; i < _current_language->num_cases; i++) {
257 /* Count the ones we have a mapped string for. */
258 if (this->strings.Contains(lm->GetReverseMapping(i, false))) count++;
260 *d++ = count;
262 for (uint8 i = 0; i < _current_language->num_cases; i++) {
263 /* Resolve the string we're looking for. */
264 int idx = lm->GetReverseMapping(i, false);
265 if (!this->strings.Contains(idx)) continue;
266 char *str = this->strings[idx];
268 /* "<CASEn>" */
269 *d++ = i + 1;
271 /* "<LENn>" */
272 size_t len = strlen(str) + 1;
273 *d++ = GB(len, 8, 8);
274 *d++ = GB(len, 0, 8);
276 /* "<STRINGn>" */
277 memcpy(d, str, len);
278 d += len;
281 /* "<STRINGDEFAULT>" */
282 size_t len = strlen(this->strings[0]) + 1;
283 memcpy(d, this->strings[0], len);
284 d += len;
285 } else {
286 if (this->type == SCC_PLURAL_LIST) {
287 *d++ = lm->plural_form;
291 * Format for choice list:
292 * <OFFSET> <NUM CHOICES> <LENs> <STRINGs>
295 /* "<OFFSET>" */
296 *d++ = this->offset - 0x80;
298 /* "<NUM CHOICES>" */
299 int count = (this->type == SCC_GENDER_LIST ? _current_language->num_genders : LANGUAGE_MAX_PLURAL_FORMS);
300 *d++ = count;
302 /* "<LENs>" */
303 for (int i = 0; i < count; i++) {
304 int idx = (this->type == SCC_GENDER_LIST ? lm->GetReverseMapping(i, true) : i + 1);
305 const char *str = this->strings[this->strings.Contains(idx) ? idx : 0];
306 size_t len = strlen(str) + 1;
307 if (len > 0xFF) grfmsg(1, "choice list string is too long");
308 *d++ = GB(len, 0, 8);
311 /* "<STRINGs>" */
312 for (int i = 0; i < count; i++) {
313 int idx = (this->type == SCC_GENDER_LIST ? lm->GetReverseMapping(i, true) : i + 1);
314 const char *str = this->strings[this->strings.Contains(idx) ? idx : 0];
315 /* Limit the length of the string we copy to 0xFE. The length is written above
316 * as a byte and we need room for the final '\0'. */
317 size_t len = min<size_t>(0xFE, strlen(str));
318 memcpy(d, str, len);
319 d += len;
320 *d++ = '\0';
323 return d;
328 * Translate TTDPatch string codes into something OpenTTD can handle (better).
329 * @param grfid The (NewGRF) ID associated with this string
330 * @param language_id The (NewGRF) language ID associated with this string.
331 * @param allow_newlines Whether newlines are allowed in the string or not.
332 * @param str The string to translate.
333 * @param [out] olen The length of the final string.
334 * @param byte80 The control code to use as replacement for the 0x80-value.
335 * @return The translated string.
337 char *TranslateTTDPatchCodes(uint32 grfid, uint8 language_id, bool allow_newlines, const char *str, int *olen, StringControlCode byte80)
339 char *tmp = MallocT<char>(strlen(str) * 10 + 1); // Allocate space to allow for expansion
340 char *d = tmp;
341 bool unicode = false;
342 WChar c;
343 size_t len = Utf8Decode(&c, str);
345 /* Helper variable for a possible (string) mapping. */
346 UnmappedChoiceList *mapping = NULL;
348 if (c == NFO_UTF8_IDENTIFIER) {
349 unicode = true;
350 str += len;
353 for (;;) {
354 if (unicode && Utf8EncodedCharLen(*str) != 0) {
355 c = Utf8Consume(&str);
356 /* 'Magic' range of control codes. */
357 if (GB(c, 8, 8) == 0xE0) {
358 c = GB(c, 0, 8);
359 } else if (c >= 0x20) {
360 if (!IsValidChar(c, CS_ALPHANUMERAL)) c = '?';
361 d += Utf8Encode(d, c);
362 continue;
364 } else {
365 c = (byte)*str++;
367 if (c == '\0') break;
369 switch (c) {
370 case 0x01:
371 if (str[0] == '\0') goto string_end;
372 d += Utf8Encode(d, ' ');
373 str++;
374 break;
375 case 0x0A: break;
376 case 0x0D:
377 if (allow_newlines) {
378 *d++ = 0x0A;
379 } else {
380 grfmsg(1, "Detected newline in string that does not allow one");
382 break;
383 case 0x0E: d += Utf8Encode(d, SCC_TINYFONT); break;
384 case 0x0F: d += Utf8Encode(d, SCC_BIGFONT); break;
385 case 0x1F:
386 if (str[0] == '\0' || str[1] == '\0') goto string_end;
387 d += Utf8Encode(d, ' ');
388 str += 2;
389 break;
390 case 0x7B:
391 case 0x7C:
392 case 0x7D:
393 case 0x7E:
394 case 0x7F: d += Utf8Encode(d, SCC_NEWGRF_PRINT_DWORD_SIGNED + c - 0x7B); break;
395 case 0x80: d += Utf8Encode(d, byte80); break;
396 case 0x81: {
397 if (str[0] == '\0' || str[1] == '\0') goto string_end;
398 StringID string;
399 string = ((uint8)*str++);
400 string |= ((uint8)*str++) << 8;
401 d += Utf8Encode(d, SCC_NEWGRF_STRINL);
402 d += Utf8Encode(d, MapGRFStringID(grfid, string));
403 break;
405 case 0x82:
406 case 0x83:
407 case 0x84: d += Utf8Encode(d, SCC_NEWGRF_PRINT_WORD_DATE_LONG + c - 0x82); break;
408 case 0x85: d += Utf8Encode(d, SCC_NEWGRF_DISCARD_WORD); break;
409 case 0x86: d += Utf8Encode(d, SCC_NEWGRF_ROTATE_TOP_4_WORDS); break;
410 case 0x87: d += Utf8Encode(d, SCC_NEWGRF_PRINT_WORD_VOLUME_LONG); break;
411 case 0x88: d += Utf8Encode(d, SCC_BLUE); break;
412 case 0x89: d += Utf8Encode(d, SCC_SILVER); break;
413 case 0x8A: d += Utf8Encode(d, SCC_GOLD); break;
414 case 0x8B: d += Utf8Encode(d, SCC_RED); break;
415 case 0x8C: d += Utf8Encode(d, SCC_PURPLE); break;
416 case 0x8D: d += Utf8Encode(d, SCC_LTBROWN); break;
417 case 0x8E: d += Utf8Encode(d, SCC_ORANGE); break;
418 case 0x8F: d += Utf8Encode(d, SCC_GREEN); break;
419 case 0x90: d += Utf8Encode(d, SCC_YELLOW); break;
420 case 0x91: d += Utf8Encode(d, SCC_DKGREEN); break;
421 case 0x92: d += Utf8Encode(d, SCC_CREAM); break;
422 case 0x93: d += Utf8Encode(d, SCC_BROWN); break;
423 case 0x94: d += Utf8Encode(d, SCC_WHITE); break;
424 case 0x95: d += Utf8Encode(d, SCC_LTBLUE); break;
425 case 0x96: d += Utf8Encode(d, SCC_GRAY); break;
426 case 0x97: d += Utf8Encode(d, SCC_DKBLUE); break;
427 case 0x98: d += Utf8Encode(d, SCC_BLACK); break;
428 case 0x9A: {
429 int code = *str++;
430 switch (code) {
431 case 0x00: goto string_end;
432 case 0x01: d += Utf8Encode(d, SCC_NEWGRF_PRINT_QWORD_CURRENCY); break;
433 /* 0x02: ignore next colour byte is not supported. It works on the final
434 * string and as such hooks into the string drawing routine. At that
435 * point many things already happened, such as splitting up of strings
436 * when drawn over multiple lines or right-to-left translations, which
437 * make the behaviour peculiar, e.g. only happening at specific width
438 * of windows. Or we need to add another pass over the string to just
439 * support this. As such it is not implemented in OpenTTD. */
440 case 0x03: {
441 if (str[0] == '\0' || str[1] == '\0') goto string_end;
442 uint16 tmp = ((uint8)*str++);
443 tmp |= ((uint8)*str++) << 8;
444 d += Utf8Encode(d, SCC_NEWGRF_PUSH_WORD);
445 d += Utf8Encode(d, tmp);
446 break;
448 case 0x04:
449 if (str[0] == '\0') goto string_end;
450 d += Utf8Encode(d, SCC_NEWGRF_UNPRINT);
451 d += Utf8Encode(d, *str++);
452 break;
453 case 0x06: d += Utf8Encode(d, SCC_NEWGRF_PRINT_BYTE_HEX); break;
454 case 0x07: d += Utf8Encode(d, SCC_NEWGRF_PRINT_WORD_HEX); break;
455 case 0x08: d += Utf8Encode(d, SCC_NEWGRF_PRINT_DWORD_HEX); break;
456 /* 0x09, 0x0A are TTDPatch internal use only string codes. */
457 case 0x0B: d += Utf8Encode(d, SCC_NEWGRF_PRINT_QWORD_HEX); break;
458 case 0x0C: d += Utf8Encode(d, SCC_NEWGRF_PRINT_WORD_STATION_NAME); break;
459 case 0x0D: d += Utf8Encode(d, SCC_NEWGRF_PRINT_WORD_WEIGHT_LONG); break;
460 case 0x0E:
461 case 0x0F: {
462 if (str[0] == '\0') goto string_end;
463 const LanguageMap *lm = LanguageMap::GetLanguageMap(grfid, language_id);
464 int index = *str++;
465 int mapped = lm != NULL ? lm->GetMapping(index, code == 0x0E) : -1;
466 if (mapped >= 0) {
467 d += Utf8Encode(d, code == 0x0E ? SCC_GENDER_INDEX : SCC_SET_CASE);
468 d += Utf8Encode(d, code == 0x0E ? mapped : mapped + 1);
470 break;
473 case 0x10:
474 case 0x11:
475 if (str[0] == '\0') goto string_end;
476 if (mapping == NULL) {
477 if (code == 0x10) str++; // Skip the index
478 grfmsg(1, "choice list %s marker found when not expected", code == 0x10 ? "next" : "default");
479 break;
480 } else {
481 /* Terminate the previous string. */
482 *d = '\0';
483 int index = (code == 0x10 ? *str++ : 0);
484 if (mapping->strings.Contains(index)) {
485 grfmsg(1, "duplicate choice list string, ignoring");
486 d++;
487 } else {
488 d = mapping->strings[index] = MallocT<char>(strlen(str) * 10 + 1);
491 break;
493 case 0x12:
494 if (mapping == NULL) {
495 grfmsg(1, "choice list end marker found when not expected");
496 } else {
497 /* Terminate the previous string. */
498 *d = '\0';
500 /* Now we can start flushing everything and clean everything up. */
501 d = mapping->Flush(LanguageMap::GetLanguageMap(grfid, language_id));
502 delete mapping;
503 mapping = NULL;
505 break;
507 case 0x13:
508 case 0x14:
509 case 0x15:
510 if (str[0] == '\0') goto string_end;
511 if (mapping != NULL) {
512 grfmsg(1, "choice lists can't be stacked, it's going to get messy now...");
513 if (code != 0x14) str++;
514 } else {
515 static const StringControlCode mp[] = { SCC_GENDER_LIST, SCC_SWITCH_CASE, SCC_PLURAL_LIST };
516 mapping = new UnmappedChoiceList(mp[code - 0x13], d, code == 0x14 ? 0 : *str++);
518 break;
520 case 0x16:
521 case 0x17:
522 case 0x18:
523 case 0x19:
524 case 0x1A:
525 case 0x1B:
526 case 0x1C:
527 case 0x1D:
528 case 0x1E:
529 d += Utf8Encode(d, SCC_NEWGRF_PRINT_DWORD_DATE_LONG + code - 0x16);
530 break;
532 default:
533 grfmsg(1, "missing handler for extended format code");
534 break;
536 break;
539 case 0x9E: d += Utf8Encode(d, 0x20AC); break; // Euro
540 case 0x9F: d += Utf8Encode(d, 0x0178); break; // Y with diaeresis
541 case 0xA0: d += Utf8Encode(d, SCC_UP_ARROW); break;
542 case 0xAA: d += Utf8Encode(d, SCC_DOWN_ARROW); break;
543 case 0xAC: d += Utf8Encode(d, SCC_CHECKMARK); break;
544 case 0xAD: d += Utf8Encode(d, SCC_CROSS); break;
545 case 0xAF: d += Utf8Encode(d, SCC_RIGHT_ARROW); break;
546 case 0xB4: d += Utf8Encode(d, SCC_TRAIN); break;
547 case 0xB5: d += Utf8Encode(d, SCC_LORRY); break;
548 case 0xB6: d += Utf8Encode(d, SCC_BUS); break;
549 case 0xB7: d += Utf8Encode(d, SCC_PLANE); break;
550 case 0xB8: d += Utf8Encode(d, SCC_SHIP); break;
551 case 0xB9: d += Utf8Encode(d, SCC_SUPERSCRIPT_M1); break;
552 case 0xBC: d += Utf8Encode(d, SCC_SMALL_UP_ARROW); break;
553 case 0xBD: d += Utf8Encode(d, SCC_SMALL_DOWN_ARROW); break;
554 default:
555 /* Validate any unhandled character */
556 if (!IsValidChar(c, CS_ALPHANUMERAL)) c = '?';
557 d += Utf8Encode(d, c);
558 break;
562 string_end:
563 if (mapping != NULL) {
564 grfmsg(1, "choice list was incomplete, the whole list is ignored");
565 delete mapping;
568 *d = '\0';
569 if (olen != NULL) *olen = d - tmp + 1;
570 tmp = ReallocT(tmp, d - tmp + 1);
571 return tmp;
575 * Add a GRFText to a GRFText list.
576 * @param list The list where the text should be added to.
577 * @param text_to_add The GRFText to add to the list.
579 void AddGRFTextToList(GRFText **list, GRFText *text_to_add)
581 GRFText **ptext, *text;
583 /* Loop through all languages and see if we can replace a string */
584 for (ptext = list; (text = *ptext) != NULL; ptext = &text->next) {
585 if (text->langid == text_to_add->langid) {
586 text_to_add->next = text->next;
587 *ptext = text_to_add;
588 delete text;
589 return;
593 /* If a string wasn't replaced, then we must append the new string */
594 *ptext = text_to_add;
598 * Add a string to a GRFText list.
599 * @param list The list where the text should be added to.
600 * @param langid The language of the new text.
601 * @param grfid The grfid where this string is defined.
602 * @param allow_newlines Whether newlines are allowed in this string.
603 * @param text_to_add The text to add to the list.
604 * @note All text-codes will be translated.
606 void AddGRFTextToList(struct GRFText **list, byte langid, uint32 grfid, bool allow_newlines, const char *text_to_add)
608 int len;
609 char *translatedtext = TranslateTTDPatchCodes(grfid, langid, allow_newlines, text_to_add, &len);
610 GRFText *newtext = GRFText::New(langid, translatedtext, len);
611 free(translatedtext);
613 AddGRFTextToList(list, newtext);
617 * Add a GRFText to a GRFText list. The text should not contain any text-codes.
618 * The text will be added as a 'default language'-text.
619 * @param list The list where the text should be added to.
620 * @param text_to_add The text to add to the list.
622 void AddGRFTextToList(struct GRFText **list, const char *text_to_add)
624 AddGRFTextToList(list, GRFText::New(0x7F, text_to_add, strlen(text_to_add) + 1));
628 * Create a copy of this GRFText list.
629 * @param orig The GRFText list to copy.
630 * @return A duplicate of the given GRFText.
632 GRFText *DuplicateGRFText(GRFText *orig)
634 GRFText *newtext = NULL;
635 GRFText **ptext = &newtext;
636 for (; orig != NULL; orig = orig->next) {
637 *ptext = GRFText::Copy(orig);
638 ptext = &(*ptext)->next;
640 return newtext;
644 * Add the new read string into our structure.
646 StringID AddGRFString(uint32 grfid, uint16 stringid, byte langid_to_add, bool new_scheme, bool allow_newlines, const char *text_to_add, StringID def_string)
648 char *translatedtext;
649 uint id;
651 /* When working with the old language scheme (grf_version is less than 7) and
652 * English or American is among the set bits, simply add it as English in
653 * the new scheme, i.e. as langid = 1.
654 * If English is set, it is pretty safe to assume the translations are not
655 * actually translated.
657 if (!new_scheme) {
658 if (langid_to_add & (GRFLB_AMERICAN | GRFLB_ENGLISH)) {
659 langid_to_add = GRFLX_ENGLISH;
660 } else {
661 StringID ret = STR_EMPTY;
662 if (langid_to_add & GRFLB_GERMAN) ret = AddGRFString(grfid, stringid, GRFLX_GERMAN, true, allow_newlines, text_to_add, def_string);
663 if (langid_to_add & GRFLB_FRENCH) ret = AddGRFString(grfid, stringid, GRFLX_FRENCH, true, allow_newlines, text_to_add, def_string);
664 if (langid_to_add & GRFLB_SPANISH) ret = AddGRFString(grfid, stringid, GRFLX_SPANISH, true, allow_newlines, text_to_add, def_string);
665 return ret;
669 for (id = 0; id < _num_grf_texts; id++) {
670 if (_grf_text[id].grfid == grfid && _grf_text[id].stringid == stringid) {
671 break;
675 /* Too many strings allocated, return empty */
676 if (id == lengthof(_grf_text)) {
677 _grf_bug_too_many_strings = true;
678 return STR_EMPTY;
681 int len;
682 translatedtext = TranslateTTDPatchCodes(grfid, langid_to_add, allow_newlines, text_to_add, &len);
684 GRFText *newtext = GRFText::New(langid_to_add, translatedtext, len);
686 free(translatedtext);
688 /* If we didn't find our stringid and grfid in the list, allocate a new id */
689 if (id == _num_grf_texts) _num_grf_texts++;
691 if (_grf_text[id].textholder == NULL) {
692 _grf_text[id].grfid = grfid;
693 _grf_text[id].stringid = stringid;
694 _grf_text[id].def_string = def_string;
696 AddGRFTextToList(&_grf_text[id].textholder, newtext);
698 grfmsg(3, "Added 0x%X: grfid %08X string 0x%X lang 0x%X string '%s' (%X)", id, grfid, stringid, newtext->langid, newtext->text, MakeStringID(TEXT_TAB_NEWGRF_START, id));
700 return MakeStringID(TEXT_TAB_NEWGRF_START, id);
704 * Returns the index for this stringid associated with its grfID
706 StringID GetGRFStringID(uint32 grfid, StringID stringid)
708 for (uint id = 0; id < _num_grf_texts; id++) {
709 if (_grf_text[id].grfid == grfid && _grf_text[id].stringid == stringid) {
710 return MakeStringID(TEXT_TAB_NEWGRF_START, id);
714 return STR_UNDEFINED;
719 * Get a C-string from a GRFText-list. If there is a translation for the
720 * current language it is returned, otherwise the default translation
721 * is returned. If there is neither a default nor a translation for the
722 * current language NULL is returned.
723 * @param text The GRFText to get the string from.
725 const char *GetGRFStringFromGRFText(const GRFText *text)
727 const char *default_text = NULL;
729 /* Search the list of lang-strings of this stringid for current lang */
730 for (; text != NULL; text = text->next) {
731 if (text->langid == _currentLangID) return text->text;
733 /* If the current string is English or American, set it as the
734 * fallback language if the specific language isn't available. */
735 if (text->langid == GRFLX_UNSPECIFIED || (default_text == NULL && (text->langid == GRFLX_ENGLISH || text->langid == GRFLX_AMERICAN))) {
736 default_text = text->text;
740 return default_text;
744 * Get a C-string from a stringid set by a newgrf.
746 const char *GetGRFStringPtr(uint16 stringid)
748 assert(_grf_text[stringid].grfid != 0);
750 const char *str = GetGRFStringFromGRFText(_grf_text[stringid].textholder);
751 if (str != NULL) return str;
753 /* Use the default string ID if the fallback string isn't available */
754 return GetStringPtr(_grf_text[stringid].def_string);
758 * Equivalence Setter function between game and newgrf langID.
759 * This function will adjust _currentLangID as to what is the LangID
760 * of the current language set by the user.
761 * This function is called after the user changed language,
762 * from strings.cpp:ReadLanguagePack
763 * @param language_id iso code of current selection
765 void SetCurrentGrfLangID(byte language_id)
767 _currentLangID = language_id;
770 bool CheckGrfLangID(byte lang_id, byte grf_version)
772 if (grf_version < 7) {
773 switch (_currentLangID) {
774 case GRFLX_GERMAN: return (lang_id & GRFLB_GERMAN) != 0;
775 case GRFLX_FRENCH: return (lang_id & GRFLB_FRENCH) != 0;
776 case GRFLX_SPANISH: return (lang_id & GRFLB_SPANISH) != 0;
777 default: return (lang_id & (GRFLB_ENGLISH | GRFLB_AMERICAN)) != 0;
781 return (lang_id == _currentLangID || lang_id == GRFLX_UNSPECIFIED);
785 * Delete all items of a linked GRFText list.
786 * @param grftext the head of the list to delete
788 void CleanUpGRFText(GRFText *grftext)
790 while (grftext != NULL) {
791 GRFText *grftext2 = grftext->next;
792 delete grftext;
793 grftext = grftext2;
798 * House cleaning.
799 * Remove all strings and reset the text counter.
801 void CleanUpStrings()
803 uint id;
805 for (id = 0; id < _num_grf_texts; id++) {
806 CleanUpGRFText(_grf_text[id].textholder);
807 _grf_text[id].grfid = 0;
808 _grf_text[id].stringid = 0;
809 _grf_text[id].textholder = NULL;
812 _num_grf_texts = 0;
815 struct TextRefStack {
816 byte stack[0x30];
817 byte position;
818 const GRFFile *grffile;
819 bool used;
821 TextRefStack() : position(0), grffile(NULL), used(false) {}
823 TextRefStack(const TextRefStack &stack) :
824 position(stack.position),
825 grffile(stack.grffile),
826 used(stack.used)
828 memcpy(this->stack, stack.stack, sizeof(this->stack));
831 uint8 PopUnsignedByte() { assert(this->position < lengthof(this->stack)); return this->stack[this->position++]; }
832 int8 PopSignedByte() { return (int8)this->PopUnsignedByte(); }
834 uint16 PopUnsignedWord()
836 uint16 val = this->PopUnsignedByte();
837 return val | (this->PopUnsignedByte() << 8);
839 int16 PopSignedWord() { return (int32)this->PopUnsignedWord(); }
841 uint32 PopUnsignedDWord()
843 uint32 val = this->PopUnsignedWord();
844 return val | (this->PopUnsignedWord() << 16);
846 int32 PopSignedDWord() { return (int32)this->PopUnsignedDWord(); }
848 uint64 PopUnsignedQWord()
850 uint64 val = this->PopUnsignedDWord();
851 return val | (((uint64)this->PopUnsignedDWord()) << 32);
853 int64 PopSignedQWord() { return (int64)this->PopUnsignedQWord(); }
855 /** Rotate the top four words down: W1, W2, W3, W4 -> W4, W1, W2, W3 */
856 void RotateTop4Words()
858 byte tmp[2];
859 for (int i = 0; i < 2; i++) tmp[i] = this->stack[this->position + i + 6];
860 for (int i = 5; i >= 0; i--) this->stack[this->position + i + 2] = this->stack[this->position + i];
861 for (int i = 0; i < 2; i++) this->stack[this->position + i] = tmp[i];
864 void PushWord(uint16 word)
866 if (this->position >= 2) {
867 this->position -= 2;
868 } else {
869 for (int i = lengthof(stack) - 1; i >= this->position + 2; i--) {
870 this->stack[i] = this->stack[i - 2];
873 this->stack[this->position] = GB(word, 0, 8);
874 this->stack[this->position + 1] = GB(word, 8, 8);
877 void ResetStack(const GRFFile *grffile)
879 assert(grffile != NULL);
880 this->position = 0;
881 this->grffile = grffile;
882 this->used = true;
885 void RewindStack() { this->position = 0; }
888 /** The stack that is used for TTDP compatible string code parsing */
889 static TextRefStack _newgrf_textrefstack;
892 * Check whether the NewGRF text stack is in use.
893 * @return True iff the NewGRF text stack is used.
895 bool UsingNewGRFTextStack()
897 return _newgrf_textrefstack.used;
901 * Create a backup of the current NewGRF text stack.
902 * @return A copy of the current text stack.
904 struct TextRefStack *CreateTextRefStackBackup()
906 return new TextRefStack(_newgrf_textrefstack);
910 * Restore a copy of the text stack to the used stack.
911 * @param backup The copy to restore.
913 void RestoreTextRefStackBackup(struct TextRefStack *backup)
915 _newgrf_textrefstack = *backup;
916 delete backup;
920 * Start using the TTDP compatible string code parsing.
922 * On start a number of values is copied on the #TextRefStack.
923 * You can then use #GetString() and the normal string drawing functions,
924 * and they will use the #TextRefStack for NewGRF string codes.
926 * However, when you want to draw a string multiple times using the same stack,
927 * you have to call #RewindTextRefStack() between draws.
929 * After you are done with drawing, you must disable usage of the #TextRefStack
930 * by calling #StopTextRefStackUsage(), so NewGRF string codes operate on the
931 * normal string parameters again.
933 * @param grffile the NewGRF providing the stack data
934 * @param numEntries number of entries to copy from the registers
935 * @param values values to copy onto the stack; if NULL the temporary NewGRF registers will be used instead
937 void StartTextRefStackUsage(const GRFFile *grffile, byte numEntries, const uint32 *values)
939 extern TemporaryStorageArray<int32, 0x110> _temp_store;
941 _newgrf_textrefstack.ResetStack(grffile);
943 byte *p = _newgrf_textrefstack.stack;
944 for (uint i = 0; i < numEntries; i++) {
945 uint32 value = values != NULL ? values[i] : _temp_store.GetValue(0x100 + i);
946 for (uint j = 0; j < 32; j += 8) {
947 *p = GB(value, j, 8);
948 p++;
953 /** Stop using the TTDP compatible string code parsing */
954 void StopTextRefStackUsage()
956 _newgrf_textrefstack.used = false;
959 void RewindTextRefStack()
961 _newgrf_textrefstack.RewindStack();
965 * FormatString for NewGRF specific "magic" string control codes
966 * @param scc the string control code that has been read
967 * @param buff the buffer we're writing to
968 * @param str the string that we need to write
969 * @param argv the OpenTTD stack of values
970 * @param argv_size space on the stack \a argv
971 * @param modify_argv When true, modify the OpenTTD stack.
972 * @return the string control code to "execute" now
974 uint RemapNewGRFStringControlCode(uint scc, char *buf_start, char **buff, const char **str, int64 *argv, uint argv_size, bool modify_argv)
976 switch (scc) {
977 default: break;
979 case SCC_NEWGRF_PRINT_DWORD_SIGNED:
980 case SCC_NEWGRF_PRINT_WORD_SIGNED:
981 case SCC_NEWGRF_PRINT_BYTE_SIGNED:
982 case SCC_NEWGRF_PRINT_WORD_UNSIGNED:
983 case SCC_NEWGRF_PRINT_BYTE_HEX:
984 case SCC_NEWGRF_PRINT_WORD_HEX:
985 case SCC_NEWGRF_PRINT_DWORD_HEX:
986 case SCC_NEWGRF_PRINT_QWORD_HEX:
987 case SCC_NEWGRF_PRINT_DWORD_CURRENCY:
988 case SCC_NEWGRF_PRINT_QWORD_CURRENCY:
989 case SCC_NEWGRF_PRINT_WORD_STRING_ID:
990 case SCC_NEWGRF_PRINT_WORD_DATE_LONG:
991 case SCC_NEWGRF_PRINT_DWORD_DATE_LONG:
992 case SCC_NEWGRF_PRINT_WORD_DATE_SHORT:
993 case SCC_NEWGRF_PRINT_DWORD_DATE_SHORT:
994 case SCC_NEWGRF_PRINT_WORD_SPEED:
995 case SCC_NEWGRF_PRINT_WORD_VOLUME_LONG:
996 case SCC_NEWGRF_PRINT_WORD_VOLUME_SHORT:
997 case SCC_NEWGRF_PRINT_WORD_WEIGHT_LONG:
998 case SCC_NEWGRF_PRINT_WORD_WEIGHT_SHORT:
999 case SCC_NEWGRF_PRINT_WORD_POWER:
1000 case SCC_NEWGRF_PRINT_WORD_STATION_NAME:
1001 case SCC_NEWGRF_PRINT_WORD_CARGO_NAME:
1002 if (argv_size < 1) {
1003 DEBUG(misc, 0, "Too many NewGRF string parameters.");
1004 return 0;
1006 break;
1008 case SCC_NEWGRF_PRINT_WORD_CARGO_LONG:
1009 case SCC_NEWGRF_PRINT_WORD_CARGO_SHORT:
1010 case SCC_NEWGRF_PRINT_WORD_CARGO_TINY:
1011 if (argv_size < 2) {
1012 DEBUG(misc, 0, "Too many NewGRF string parameters.");
1013 return 0;
1015 break;
1018 if (_newgrf_textrefstack.used && modify_argv) {
1019 switch (scc) {
1020 default: NOT_REACHED();
1021 case SCC_NEWGRF_PRINT_BYTE_SIGNED: *argv = _newgrf_textrefstack.PopSignedByte(); break;
1022 case SCC_NEWGRF_PRINT_QWORD_CURRENCY: *argv = _newgrf_textrefstack.PopSignedQWord(); break;
1024 case SCC_NEWGRF_PRINT_DWORD_CURRENCY:
1025 case SCC_NEWGRF_PRINT_DWORD_SIGNED: *argv = _newgrf_textrefstack.PopSignedDWord(); break;
1027 case SCC_NEWGRF_PRINT_BYTE_HEX: *argv = _newgrf_textrefstack.PopUnsignedByte(); break;
1028 case SCC_NEWGRF_PRINT_QWORD_HEX: *argv = _newgrf_textrefstack.PopUnsignedQWord(); break;
1030 case SCC_NEWGRF_PRINT_WORD_SPEED:
1031 case SCC_NEWGRF_PRINT_WORD_VOLUME_LONG:
1032 case SCC_NEWGRF_PRINT_WORD_VOLUME_SHORT:
1033 case SCC_NEWGRF_PRINT_WORD_SIGNED: *argv = _newgrf_textrefstack.PopSignedWord(); break;
1035 case SCC_NEWGRF_PRINT_WORD_HEX:
1036 case SCC_NEWGRF_PRINT_WORD_WEIGHT_LONG:
1037 case SCC_NEWGRF_PRINT_WORD_WEIGHT_SHORT:
1038 case SCC_NEWGRF_PRINT_WORD_POWER:
1039 case SCC_NEWGRF_PRINT_WORD_STATION_NAME:
1040 case SCC_NEWGRF_PRINT_WORD_UNSIGNED: *argv = _newgrf_textrefstack.PopUnsignedWord(); break;
1042 case SCC_NEWGRF_PRINT_DWORD_DATE_LONG:
1043 case SCC_NEWGRF_PRINT_DWORD_DATE_SHORT:
1044 case SCC_NEWGRF_PRINT_DWORD_HEX: *argv = _newgrf_textrefstack.PopUnsignedDWord(); break;
1046 case SCC_NEWGRF_PRINT_WORD_DATE_LONG:
1047 case SCC_NEWGRF_PRINT_WORD_DATE_SHORT: *argv = _newgrf_textrefstack.PopUnsignedWord() + DAYS_TILL_ORIGINAL_BASE_YEAR; break;
1049 case SCC_NEWGRF_DISCARD_WORD: _newgrf_textrefstack.PopUnsignedWord(); break;
1051 case SCC_NEWGRF_ROTATE_TOP_4_WORDS: _newgrf_textrefstack.RotateTop4Words(); break;
1052 case SCC_NEWGRF_PUSH_WORD: _newgrf_textrefstack.PushWord(Utf8Consume(str)); break;
1053 case SCC_NEWGRF_UNPRINT: *buff = max(*buff - Utf8Consume(str), buf_start); break;
1055 case SCC_NEWGRF_PRINT_WORD_CARGO_LONG:
1056 case SCC_NEWGRF_PRINT_WORD_CARGO_SHORT:
1057 case SCC_NEWGRF_PRINT_WORD_CARGO_TINY:
1058 argv[0] = GetCargoTranslation(_newgrf_textrefstack.PopUnsignedWord(), _newgrf_textrefstack.grffile);
1059 argv[1] = _newgrf_textrefstack.PopUnsignedWord();
1060 break;
1062 case SCC_NEWGRF_PRINT_WORD_STRING_ID:
1063 *argv = MapGRFStringID(_newgrf_textrefstack.grffile->grfid, _newgrf_textrefstack.PopUnsignedWord());
1064 break;
1066 case SCC_NEWGRF_PRINT_WORD_CARGO_NAME: {
1067 CargoID cargo = GetCargoTranslation(_newgrf_textrefstack.PopUnsignedWord(), _newgrf_textrefstack.grffile);
1068 *argv = cargo < NUM_CARGO ? 1 << cargo : 0;
1069 break;
1072 } else {
1073 /* Consume additional parameter characters */
1074 switch (scc) {
1075 default: break;
1077 case SCC_NEWGRF_PUSH_WORD:
1078 case SCC_NEWGRF_UNPRINT:
1079 Utf8Consume(str);
1080 break;
1084 switch (scc) {
1085 default: NOT_REACHED();
1086 case SCC_NEWGRF_PRINT_DWORD_SIGNED:
1087 case SCC_NEWGRF_PRINT_WORD_SIGNED:
1088 case SCC_NEWGRF_PRINT_BYTE_SIGNED:
1089 case SCC_NEWGRF_PRINT_WORD_UNSIGNED:
1090 return SCC_COMMA;
1092 case SCC_NEWGRF_PRINT_BYTE_HEX:
1093 case SCC_NEWGRF_PRINT_WORD_HEX:
1094 case SCC_NEWGRF_PRINT_DWORD_HEX:
1095 case SCC_NEWGRF_PRINT_QWORD_HEX:
1096 return SCC_HEX;
1098 case SCC_NEWGRF_PRINT_DWORD_CURRENCY:
1099 case SCC_NEWGRF_PRINT_QWORD_CURRENCY:
1100 return SCC_CURRENCY_LONG;
1102 case SCC_NEWGRF_PRINT_WORD_STRING_ID:
1103 return SCC_NEWGRF_PRINT_WORD_STRING_ID;
1105 case SCC_NEWGRF_PRINT_WORD_DATE_LONG:
1106 case SCC_NEWGRF_PRINT_DWORD_DATE_LONG:
1107 return SCC_DATE_LONG;
1109 case SCC_NEWGRF_PRINT_WORD_DATE_SHORT:
1110 case SCC_NEWGRF_PRINT_DWORD_DATE_SHORT:
1111 return SCC_DATE_SHORT;
1113 case SCC_NEWGRF_PRINT_WORD_SPEED:
1114 return SCC_VELOCITY;
1116 case SCC_NEWGRF_PRINT_WORD_VOLUME_LONG:
1117 return SCC_VOLUME_LONG;
1119 case SCC_NEWGRF_PRINT_WORD_VOLUME_SHORT:
1120 return SCC_VOLUME_SHORT;
1122 case SCC_NEWGRF_PRINT_WORD_WEIGHT_LONG:
1123 return SCC_WEIGHT_LONG;
1125 case SCC_NEWGRF_PRINT_WORD_WEIGHT_SHORT:
1126 return SCC_WEIGHT_SHORT;
1128 case SCC_NEWGRF_PRINT_WORD_POWER:
1129 return SCC_POWER;
1131 case SCC_NEWGRF_PRINT_WORD_CARGO_LONG:
1132 return SCC_CARGO_LONG;
1134 case SCC_NEWGRF_PRINT_WORD_CARGO_SHORT:
1135 return SCC_CARGO_SHORT;
1137 case SCC_NEWGRF_PRINT_WORD_CARGO_TINY:
1138 return SCC_CARGO_TINY;
1140 case SCC_NEWGRF_PRINT_WORD_CARGO_NAME:
1141 return SCC_CARGO_LIST;
1143 case SCC_NEWGRF_PRINT_WORD_STATION_NAME:
1144 return SCC_STATION_NAME;
1146 case SCC_NEWGRF_DISCARD_WORD:
1147 case SCC_NEWGRF_ROTATE_TOP_4_WORDS:
1148 case SCC_NEWGRF_PUSH_WORD:
1149 case SCC_NEWGRF_UNPRINT:
1150 return 0;