OpenTTD Source 20261112-master-gbcbec5e63f
strings.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "currency_func.h"
12#include "station_base.h"
13#include "town.h"
14#include "waypoint_base.h"
15#include "depot_base.h"
16#include "industry.h"
17#include "newgrf_text.h"
18#include "fileio_func.h"
19#include "signs_base.h"
20#include "error.h"
21#include "error_func.h"
22#include "strings_func.h"
23#include "rev.h"
24#include "core/endian_func.hpp"
26#include "vehicle_base.h"
27#include "engine_base.h"
28#include "language.h"
29#include "string_func.h"
30#include "company_base.h"
31#include "smallmap_gui.h"
32#include "window_func.h"
33#include "debug.h"
34#include "game/game_text.hpp"
36#include "newgrf_engine.h"
37#include "core/backup_type.hpp"
38#include "gfx_layout.h"
39#include "core/utf8.hpp"
41#include <stack>
42
43#include "table/strings.h"
44#include "table/control_codes.h"
45#include "3rdparty/fmt/std.h"
46
47#include "strings_internal.h"
48
49#include "safeguards.h"
50
54
56
57#ifdef WITH_ICU_I18N
58std::unique_ptr<icu::Collator> _current_collator;
59#endif /* WITH_ICU_I18N */
60
68{
69 assert(this->next_type == 0 || (SCC_CONTROL_START <= this->next_type && this->next_type <= SCC_CONTROL_END));
70 if (this->offset >= this->parameters.size()) {
71 throw std::out_of_range("Trying to read invalid string parameter");
72 }
73
74 auto &param = this->parameters[this->offset++];
75 if (param.type != 0 && param.type != this->next_type) {
76 this->next_type = 0;
77 throw std::out_of_range("Trying to read string parameter with wrong type");
78 }
79 param.type = this->next_type;
80 this->next_type = 0;
81 return param;
82}
83
93
101EncodedString GetEncodedStringWithArgs(StringID str, std::span<const StringParameter> params)
102{
103 std::string result;
104 StringBuilder builder(result);
106 builder.PutIntegerBase(str.base(), 16);
107
108 struct visitor {
109 StringBuilder &builder;
110
111 void operator()(const std::monostate &) {}
112
113 void operator()(const uint64_t &arg)
114 {
115 this->builder.PutUtf8(SCC_ENCODED_NUMERIC);
116 this->builder.PutIntegerBase(arg, 16);
117 }
118
119 void operator()(const std::string &value)
120 {
121#ifdef WITH_ASSERT
122 /* Don't allow an encoded string to contain another encoded string. */
123 {
124 auto [len, c] = DecodeUtf8(value);
125 assert(len == 0 || (c != SCC_ENCODED && c != SCC_ENCODED_INTERNAL && c != SCC_RECORD_SEPARATOR));
126 }
127#endif /* WITH_ASSERT */
128 this->builder.PutUtf8(SCC_ENCODED_STRING);
129 this->builder += value;
130 }
131 };
132
133 visitor v{builder};
134 for (const auto &param : params) {
135 builder.PutUtf8(SCC_RECORD_SEPARATOR);
136 std::visit(v, param.data);
137 }
138
139 return EncodedString{std::move(result)};
140}
141
149EncodedString EncodedString::ReplaceParam(size_t param, StringParameter &&data) const
150{
151 if (this->empty()) return {};
152
153 std::vector<StringParameter> params;
154 StringConsumer consumer(this->string);
155
156 if (!consumer.ReadUtf8If(SCC_ENCODED_INTERNAL)) return {};
157
158 StringID str;
159 if (auto r = consumer.TryReadIntegerBase<uint32_t>(16); r.has_value()) {
160 str = static_cast<StringID>(*r);
161 } else {
162 return {};
163 }
164 if (consumer.AnyBytesLeft() && !consumer.ReadUtf8If(SCC_RECORD_SEPARATOR)) return {};
165
166 while (consumer.AnyBytesLeft()) {
167 StringConsumer record(consumer.ReadUntilUtf8(SCC_RECORD_SEPARATOR, StringConsumer::SKIP_ONE_SEPARATOR));
168
169 if (!record.AnyBytesLeft()) {
170 /* This is an empty parameter. */
171 params.emplace_back(std::monostate{});
172 continue;
173 }
174
175 /* Get the parameter type. */
176 char32_t parameter_type = record.ReadUtf8();
177 switch (parameter_type) {
178 case SCC_ENCODED_NUMERIC: {
179 uint64_t value = record.ReadIntegerBase<uint64_t>(16);
180 assert(!record.AnyBytesLeft());
181 params.emplace_back(value);
182 break;
183 }
184
185 case SCC_ENCODED_STRING: {
186 params.emplace_back(record.Read(StringConsumer::npos));
187 break;
188 }
189
190 default:
191 /* Unknown parameter, make it blank. */
192 params.emplace_back(std::monostate{});
193 break;
194 }
195 }
196
197 if (param >= std::size(params)) return {};
198 params[param] = data;
199 return GetEncodedStringWithArgs(str, params);
200}
201
207{
208 return GetString(STR_JUST_RAW_STRING, this->string);
209}
210
217uint64_t GetParamMaxDigits(uint count, FontSize size)
218{
219 auto [front, next] = GetBroadestDigit(size);
220 uint64_t val = count > 1 ? front : next;
221 for (; count > 1; count--) {
222 val = 10 * val + next;
223 }
224 return val;
225}
226
235uint64_t GetParamMaxValue(uint64_t max_value, uint min_count, FontSize size)
236{
237 uint num_digits = 1;
238 while (max_value >= 10) {
239 num_digits++;
240 max_value /= 10;
241 }
242 return GetParamMaxDigits(std::max(min_count, num_digits), size);
243}
244
245static void StationGetSpecialString(StringBuilder &builder, StationFacilities x);
246static bool GetSpecialNameString(StringBuilder &builder, StringID string, StringParameters &args);
247
248static void FormatString(StringBuilder &builder, std::string_view str, StringParameters &args, uint case_index = 0, bool game_script = false, bool dry_run = false);
249
260static void FormatString(StringBuilder &builder, std::string_view str, std::span<StringParameter> params, uint case_index = 0, bool game_script = false, bool dry_run = false)
261{
262 StringParameters tmp_params{params};
263 FormatString(builder, str, tmp_params, case_index, game_script, dry_run);
264}
265
267 char data[];
268};
269
271 void operator()(LanguagePack *langpack)
272 {
273 /* LanguagePack is in fact reinterpreted char[], we need to reinterpret it back to free it properly. */
274 delete[] reinterpret_cast<char *>(langpack);
275 }
276};
277
279 std::unique_ptr<LanguagePack, LanguagePackDeleter> langpack;
280
281 std::vector<std::string_view> strings;
282
283 std::array<uint, TEXT_TAB_END> langtab_num;
284 std::array<uint, TEXT_TAB_END> langtab_start;
285
286 std::string list_separator;
287 std::string ellipsis;
288};
289
290static LoadedLanguagePack _langpack;
291
292static bool _scan_for_gender_data = false;
293
298std::string_view GetListSeparator()
299{
300 return _langpack.list_separator;
301}
302
307std::string_view GetEllipsis()
308{
309 return _langpack.ellipsis;
310}
311
312std::string_view GetStringPtr(StringID string)
313{
314 switch (GetStringTab(string)) {
316 /* 0xD0xx and 0xD4xx IDs have been converted earlier. */
317 case TEXT_TAB_OLD_NEWGRF: NOT_REACHED();
319 default: {
320 const size_t offset = _langpack.langtab_start[GetStringTab(string)] + GetStringIndex(string).base();
321 if (offset < _langpack.strings.size()) return _langpack.strings[offset];
322 return "(undefined string)";
323 }
324 }
325}
326
335void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index, bool game_script)
336{
337 if (string == 0) {
338 GetStringWithArgs(builder, STR_UNDEFINED, args);
339 return;
340 }
341
342 StringIndexInTab index = GetStringIndex(string);
343 StringTab tab = GetStringTab(string);
344
345 switch (tab) {
346 case TEXT_TAB_TOWN:
347 if (IsInsideMM(string, SPECSTR_TOWNNAME_START, SPECSTR_TOWNNAME_END) && !game_script) {
348 try {
349 GenerateTownNameString(builder, (string - SPECSTR_TOWNNAME_START).base(), args.GetNextParameter<uint32_t>());
350 } catch (const std::runtime_error &e) {
351 Debug(Facility::Misc, Severity::Critical, "GetStringWithArgs: {}", e.what());
352 builder += "(invalid string parameter)";
353 }
354 return;
355 }
356 break;
357
358 case TEXT_TAB_SPECIAL:
359 if (!game_script) {
360 try {
361 if (GetSpecialNameString(builder, string, args)) return;
362 } catch (const std::runtime_error &e) {
363 Debug(Facility::Misc, Severity::Critical, "GetStringWithArgs: {}", e.what());
364 builder += "(invalid string parameter)";
365 return;
366 }
367 }
368 break;
369
370 case TEXT_TAB_OLD_CUSTOM:
371 /* Old table for custom names. This is no longer used */
372 if (!game_script) {
373 FatalError("Incorrect conversion of custom name string.");
374 }
375 break;
376
378 FormatString(builder, GetGameStringPtr(index), args, case_index, true);
379 return;
380 }
381
382 case TEXT_TAB_OLD_NEWGRF:
383 NOT_REACHED();
384
386 FormatString(builder, GetGRFStringPtr(index), args, case_index);
387 return;
388 }
389
390 default:
391 break;
392 }
393
394 if (index >= _langpack.langtab_num[tab]) {
395 if (game_script) {
396 return GetStringWithArgs(builder, STR_UNDEFINED, args);
397 }
398 FatalError("String 0x{:X} is invalid. You are probably using an old version of the .lng file.\n", string);
399 }
400
401 FormatString(builder, GetStringPtr(string), args, case_index);
402}
403
412void GetStringWithArgs(StringBuilder &builder, StringID string, std::span<StringParameter> params, uint case_index, bool game_script)
413{
414 StringParameters tmp_params{params};
415 GetStringWithArgs(builder, string, tmp_params, case_index, game_script);
416}
417
423std::string GetString(StringID string)
424{
425 return GetStringWithArgs(string, {});
426}
427
433void AppendStringInPlace(std::string &result, StringID string)
434{
435 StringBuilder builder(result);
436 GetStringWithArgs(builder, string, {});
437}
438
439void AppendStringWithArgsInPlace(std::string &result, StringID string, std::span<StringParameter> params)
440{
441 StringParameters tmp_params{params};
442 StringBuilder builder(result);
443 GetStringWithArgs(builder, string, tmp_params);
444}
445
453{
454 std::string result;
455 StringBuilder builder(result);
456 GetStringWithArgs(builder, string, args);
457 return result;
458}
459
460std::string GetStringWithArgs(StringID string, std::span<StringParameter> args)
461{
462 std::string result;
463 StringBuilder builder(result);
464 GetStringWithArgs(builder, string, args);
465 return result;
466}
467
468static std::string_view GetDecimalSeparator()
469{
470 std::string_view decimal_separator = _settings_game.locale.digit_decimal_separator;
471 if (decimal_separator.empty()) decimal_separator = _langpack.langpack->digit_decimal_separator;
472 return decimal_separator;
473}
474
481static void FormatNumber(StringBuilder &builder, int64_t number, std::string_view separator)
482{
483 static const int max_digits = 20;
484 uint64_t divisor = 10000000000000000000ULL;
485 int thousands_offset = (max_digits - 1) % 3;
486
487 if (number < 0) {
488 builder.PutChar('-');
489 number = -number;
490 }
491
492 uint64_t num = number;
493 uint64_t tot = 0;
494 for (int i = 0; i < max_digits; i++) {
495 uint64_t quot = 0;
496 if (num >= divisor) {
497 quot = num / divisor;
498 num = num % divisor;
499 }
500 if ((tot |= quot) || i == max_digits - 1) {
501 builder.PutChar('0' + quot); // quot is a single digit
502 if ((i % 3) == thousands_offset && i < max_digits - 1) builder += separator;
503 }
504
505 divisor /= 10;
506 }
507}
508
509static void FormatCommaNumber(StringBuilder &builder, int64_t number)
510{
511 std::string_view separator = _settings_game.locale.digit_group_separator;
512 if (separator.empty()) separator = _langpack.langpack->digit_group_separator;
513 FormatNumber(builder, number, separator);
514}
515
516static void FormatNoCommaNumber(StringBuilder &builder, int64_t number)
517{
518 fmt::format_to(builder.back_inserter(), "{}", number);
519}
520
521static void FormatZerofillNumber(StringBuilder &builder, int64_t number, int count)
522{
523 fmt::format_to(builder.back_inserter(), "{:0{}d}", number, count);
524}
525
526static void FormatHexNumber(StringBuilder &builder, uint64_t number)
527{
528 fmt::format_to(builder.back_inserter(), "0x{:X}", number);
529}
530
536static void FormatBytes(StringBuilder &builder, int64_t number)
537{
538 assert(number >= 0);
539
540 /* 1 2^10 2^20 2^30 2^40 2^50 2^60 */
541 static const std::string_view iec_prefixes[] = {"", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei"};
542 uint id = 1;
543 while (number >= 1024 * 1024) {
544 number /= 1024;
545 id++;
546 }
547
548 if (number < 1024) {
549 id = 0;
550 fmt::format_to(builder.back_inserter(), "{}", number);
551 } else if (number < 1024 * 10) {
552 fmt::format_to(builder.back_inserter(), "{}{}{:02}", number / 1024, GetDecimalSeparator(), (number % 1024) * 100 / 1024);
553 } else if (number < 1024 * 100) {
554 fmt::format_to(builder.back_inserter(), "{}{}{:01}", number / 1024, GetDecimalSeparator(), (number % 1024) * 10 / 1024);
555 } else {
556 assert(number < 1024 * 1024);
557 fmt::format_to(builder.back_inserter(), "{}", number / 1024);
558 }
559
560 assert(id < lengthof(iec_prefixes));
561 fmt::format_to(builder.back_inserter(), NBSP "{}B", iec_prefixes[id]);
562}
563
564static void FormatYmdString(StringBuilder &builder, TimerGameCalendar::Date date, uint case_index)
565{
566 TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(date);
567
568 auto tmp_params = MakeParameters(STR_DAY_NUMBER_1ST + ymd.day - 1, STR_MONTH_ABBREV_JAN + ymd.month, ymd.year);
569 FormatString(builder, GetStringPtr(STR_FORMAT_DATE_LONG), tmp_params, case_index);
570}
571
572static void FormatMonthAndYear(StringBuilder &builder, TimerGameCalendar::Date date, uint case_index)
573{
574 TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(date);
575
576 auto tmp_params = MakeParameters(STR_MONTH_JAN + ymd.month, ymd.year);
577 FormatString(builder, GetStringPtr(STR_FORMAT_DATE_SHORT), tmp_params, case_index);
578}
579
580static void FormatTinyOrISODate(StringBuilder &builder, TimerGameCalendar::Date date, StringID str)
581{
582 TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(date);
583
584 /* Day and month are zero-padded with ZEROFILL_NUM, hence the two 2s. */
585 auto tmp_params = MakeParameters(ymd.day, 2, ymd.month + 1, 2, ymd.year);
586 FormatString(builder, GetStringPtr(str), tmp_params);
587}
588
589static void FormatGenericCurrency(StringBuilder &builder, const CurrencySpec *spec, Money number, bool compact)
590{
591 /* We are going to make number absolute for printing, so
592 * keep this piece of data as we need it later on */
593 bool negative = number < 0;
594
595 number *= spec->rate;
596
597 /* convert from negative */
598 if (number < 0) {
599 builder.PutUtf8(SCC_PUSH_COLOUR);
600 builder.PutUtf8(SCC_RED);
601 builder.PutChar('-');
602 number = -number;
603 }
604
605 /* Add prefix part, following symbol_pos specification. */
606 if (spec->symbol_pos.Test(CurrencySymbolPosition::Prefix)) builder += spec->prefix;
607
608 StringID number_str = STR_NULL;
609
610 /* For huge numbers, compact the number. */
611 if (compact) {
612 /* Take care of the thousand rounding. Having 1 000 000 k
613 * and 1 000 M is inconsistent, so always use 1 000 M. */
614 if (number >= Money(1'000'000'000'000'000) - 500'000'000) {
615 number = (number + Money(500'000'000'000)) / Money(1'000'000'000'000);
616 number_str = STR_CURRENCY_SHORT_TERA;
617 } else if (number >= Money(1'000'000'000'000) - 500'000) {
618 number = (number + 500'000'000) / 1'000'000'000;
619 number_str = STR_CURRENCY_SHORT_GIGA;
620 } else if (number >= 1'000'000'000 - 500) {
621 number = (number + 500'000) / 1'000'000;
622 number_str = STR_CURRENCY_SHORT_MEGA;
623 } else if (number >= 1'000'000) {
624 number = (number + 500) / 1'000;
625 number_str = STR_CURRENCY_SHORT_KILO;
626 }
627 }
628
629 std::string_view separator = _settings_game.locale.digit_group_separator_currency;
630 if (separator.empty()) separator = GetCurrency().separator;
631 if (separator.empty()) separator = _langpack.langpack->digit_group_separator_currency;
632 FormatNumber(builder, number, separator);
633 if (number_str != STR_NULL) {
634 FormatString(builder, GetStringPtr(number_str), {});
635 }
636
637 /* Add suffix part, following symbol_pos specification. */
638 if (spec->symbol_pos.Test(CurrencySymbolPosition::Suffix)) builder += spec->suffix;
639
640 if (negative) {
641 builder.PutUtf8(SCC_POP_COLOUR);
642 }
643}
644
651static int DeterminePluralForm(int64_t count, uint plural_form)
652{
653 /* The absolute value determines plurality */
654 uint64_t n = abs(count);
655
656 switch (plural_form) {
657 default:
658 NOT_REACHED();
659
660 /* Two forms: singular used for one only.
661 * Used in:
662 * Danish, Dutch, English, German, Norwegian, Swedish, Estonian, Finnish,
663 * Greek, Hebrew, Italian, Portuguese, Spanish, Esperanto */
664 case 0:
665 return n != 1 ? 1 : 0;
666
667 /* Only one form.
668 * Used in:
669 * Hungarian, Japanese, Turkish */
670 case 1:
671 return 0;
672
673 /* Two forms: singular used for 0 and 1.
674 * Used in:
675 * French, Brazilian Portuguese */
676 case 2:
677 return n > 1 ? 1 : 0;
678
679 /* Three forms: special cases for 0, and numbers ending in 1 except when ending in 11.
680 * Note: Cases are out of order for hysterical reasons. '0' is last.
681 * Used in:
682 * Latvian */
683 case 3:
684 return n % 10 == 1 && n % 100 != 11 ? 0 : n != 0 ? 1 : 2;
685
686 /* Five forms: special cases for 1, 2, 3 to 6, and 7 to 10.
687 * Used in:
688 * Gaelige (Irish) */
689 case 4:
690 return n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4;
691
692 /* Three forms: special cases for numbers ending in 1 except when ending in 11, and 2 to 9 except when ending in 12 to 19.
693 * Used in:
694 * Lithuanian */
695 case 5:
696 return n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2;
697
698 /* Three forms: special cases for numbers ending in 1 except when ending in 11, and 2 to 4 except when ending in 12 to 14.
699 * Used in:
700 * Croatian, Russian, Ukrainian */
701 case 6:
702 return n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2;
703
704 /* Three forms: special cases for 1, and numbers ending in 2 to 4 except when ending in 12 to 14.
705 * Used in:
706 * Polish */
707 case 7:
708 return n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2;
709
710 /* Four forms: special cases for numbers ending in 01, 02, and 03 to 04.
711 * Used in:
712 * Slovenian */
713 case 8:
714 return n % 100 == 1 ? 0 : n % 100 == 2 ? 1 : n % 100 == 3 || n % 100 == 4 ? 2 : 3;
715
716 /* Two forms: singular used for numbers ending in 1 except when ending in 11.
717 * Used in:
718 * Icelandic */
719 case 9:
720 return n % 10 == 1 && n % 100 != 11 ? 0 : 1;
721
722 /* Three forms: special cases for 1, and 2 to 4
723 * Used in:
724 * Czech, Slovak */
725 case 10:
726 return n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2;
727
728 /* Two forms: cases for numbers ending with a consonant, and with a vowel.
729 * Korean doesn't have the concept of plural, but depending on how a
730 * number is pronounced it needs another version of a particle.
731 * As such the plural system is misused to give this distinction.
732 */
733 case 11:
734 switch (n % 10) {
735 case 0: // yeong
736 case 1: // il
737 case 3: // sam
738 case 6: // yuk
739 case 7: // chil
740 case 8: // pal
741 return 0;
742
743 case 2: // i
744 case 4: // sa
745 case 5: // o
746 case 9: // gu
747 return 1;
748
749 default:
750 NOT_REACHED();
751 }
752
753 /* Four forms: special cases for 1, 0 and numbers ending in 02 to 10, and numbers ending in 11 to 19.
754 * Used in:
755 * Maltese */
756 case 12:
757 return (n == 1 ? 0 : n == 0 || (n % 100 > 1 && n % 100 < 11) ? 1 : (n % 100 > 10 && n % 100 < 20) ? 2 : 3);
758 /* Four forms: special cases for 1 and 11, 2 and 12, 3 .. 10 and 13 .. 19, other
759 * Used in:
760 * Scottish Gaelic */
761 case 13:
762 return ((n == 1 || n == 11) ? 0 : (n == 2 || n == 12) ? 1 : ((n > 2 && n < 11) || (n > 12 && n < 20)) ? 2 : 3);
763
764 /* Three forms: special cases for 1, 0 and numbers ending in 01 to 19.
765 * Used in:
766 * Romanian */
767 case 14:
768 return n == 1 ? 0 : (n == 0 || (n % 100 > 0 && n % 100 < 20)) ? 1 : 2;
769 }
770}
771
772static void SkipStringChoice(StringConsumer &consumer)
773{
774 uint n = consumer.ReadUint8();
775 uint len = 0;
776 for (uint i = 0; i != n; i++) {
777 len += consumer.ReadUint8();
778 }
779 consumer.Skip(len);
780}
781
782static void ParseStringChoice(StringConsumer &consumer, uint form, StringBuilder &builder)
783{
784 /* <NUM> {Length of each string} {each string} */
785 uint n = consumer.ReadUint8();
786 size_t form_pre = 0, form_len = 0, form_post = 0;
787 for (uint i = 0; i != n; i++) {
788 uint len = consumer.ReadUint8();
789 if (i < form) {
790 form_pre += len;
791 } else if (i > form) {
792 form_post += len;
793 } else {
794 form_len = len;
795 }
796 }
797
798 consumer.Skip(form_pre);
799 builder += consumer.Read(form_len);
800 consumer.Skip(form_post);
801}
802
805 double factor;
806
813 int64_t ToDisplay(int64_t input, bool round = true) const
814 {
815 return round
816 ? (int64_t)std::round(input * this->factor)
817 : (int64_t)(input * this->factor);
818 }
819
827 int64_t FromDisplay(int64_t input, bool round = true, int64_t divider = 1) const
828 {
829 return round
830 ? (int64_t)std::round(input / this->factor / divider)
831 : (int64_t)(input / this->factor / divider);
832 }
833};
834
841
849
852 { { 1.0 }, STR_UNITS_VELOCITY_IMPERIAL, 0 },
853 { { 1.609344 }, STR_UNITS_VELOCITY_METRIC, 0 },
854 { { 0.44704 }, STR_UNITS_VELOCITY_SI, 0 },
855 { { 0.578125 }, STR_UNITS_VELOCITY_GAMEUNITS_DAY, 1 },
856 { { 0.868976 }, STR_UNITS_VELOCITY_KNOTS, 0 },
857};
858
861 { { 1.0 }, STR_UNITS_VELOCITY_IMPERIAL, 0 },
862 { { 1.609344 }, STR_UNITS_VELOCITY_METRIC, 0 },
863 { { 0.44704 }, STR_UNITS_VELOCITY_SI, 0 },
864 { { 0.289352 }, STR_UNITS_VELOCITY_GAMEUNITS_SEC, 1 },
865 { { 0.868976 }, STR_UNITS_VELOCITY_KNOTS, 0 },
866};
867
869static const Units _units_power[] = {
870 { { 1.0 }, STR_UNITS_POWER_IMPERIAL, 0 },
871 { { 1.01387 }, STR_UNITS_POWER_METRIC, 0 },
872 { { 0.745699 }, STR_UNITS_POWER_SI, 0 },
873};
874
877 { { 0.907185 }, STR_UNITS_POWER_IMPERIAL_TO_WEIGHT_IMPERIAL, 1 },
878 { { 1.0 }, STR_UNITS_POWER_IMPERIAL_TO_WEIGHT_METRIC, 1 },
879 { { 1.0 }, STR_UNITS_POWER_IMPERIAL_TO_WEIGHT_SI, 1 },
880 { { 0.919768 }, STR_UNITS_POWER_METRIC_TO_WEIGHT_IMPERIAL, 1 },
881 { { 1.01387 }, STR_UNITS_POWER_METRIC_TO_WEIGHT_METRIC, 1 },
882 { { 1.01387 }, STR_UNITS_POWER_METRIC_TO_WEIGHT_SI, 1 },
883 { { 0.676487 }, STR_UNITS_POWER_SI_TO_WEIGHT_IMPERIAL, 1 },
884 { { 0.745699 }, STR_UNITS_POWER_SI_TO_WEIGHT_METRIC, 1 },
885 { { 0.745699 }, STR_UNITS_POWER_SI_TO_WEIGHT_SI, 1 },
886};
887
889static const UnitsLong _units_weight[] = {
890 { { 1.102311 }, STR_UNITS_WEIGHT_SHORT_IMPERIAL, STR_UNITS_WEIGHT_LONG_IMPERIAL, 0 },
891 { { 1.0 }, STR_UNITS_WEIGHT_SHORT_METRIC, STR_UNITS_WEIGHT_LONG_METRIC, 0 },
892 { { 1000.0 }, STR_UNITS_WEIGHT_SHORT_SI, STR_UNITS_WEIGHT_LONG_SI, 0 },
893};
894
896static const UnitsLong _units_volume[] = {
897 { { 264.172 }, STR_UNITS_VOLUME_SHORT_IMPERIAL, STR_UNITS_VOLUME_LONG_IMPERIAL, 0 },
898 { { 1000.0 }, STR_UNITS_VOLUME_SHORT_METRIC, STR_UNITS_VOLUME_LONG_METRIC, 0 },
899 { { 1.0 }, STR_UNITS_VOLUME_SHORT_SI, STR_UNITS_VOLUME_LONG_SI, 0 },
900};
901
903static const Units _units_force[] = {
904 { { 0.224809 }, STR_UNITS_FORCE_IMPERIAL, 0 },
905 { { 0.101972 }, STR_UNITS_FORCE_METRIC, 0 },
906 { { 0.001 }, STR_UNITS_FORCE_SI, 0 },
907};
908
910static const Units _units_height[] = {
911 { { 3.0 }, STR_UNITS_HEIGHT_IMPERIAL, 0 }, // "Wrong" conversion factor for more nicer GUI values
912 { { 1.0 }, STR_UNITS_HEIGHT_METRIC, 0 },
913 { { 1.0 }, STR_UNITS_HEIGHT_SI, 0 },
914 { { .02 }, STR_UNITS_HEIGHT_GAMEUNITS,0 },
915};
916
919 { { 1 }, STR_UNITS_DAYS, 0 },
920 { { 2 }, STR_UNITS_SECONDS, 0 },
921};
922
925 { { 1 }, STR_UNITS_MONTHS, 0 },
926 { { 1 }, STR_UNITS_MINUTES, 0 },
927};
928
931 { { 1 }, STR_UNITS_YEARS, 0 },
932 { { 1 }, STR_UNITS_PERIODS, 0 },
933};
934
937 { { 1 }, STR_UNITS_YEARS, 0 },
938 { { 12 }, STR_UNITS_MINUTES, 0 },
939};
940
947{
948 uint8_t setting = (type == VehicleType::Ship || type == VehicleType::Aircraft) ? _settings_game.locale.units_velocity_nautical : _settings_game.locale.units_velocity;
949
950 assert(setting < lengthof(_units_velocity_calendar));
951 assert(setting < lengthof(_units_velocity_realtime));
952
954
955 return _units_velocity_calendar[setting];
956}
957
965{
966 /* For historical reasons we don't want to mess with the
967 * conversion for speed. So, don't round it and keep the
968 * original conversion factors instead of the real ones. */
969 return GetVelocityUnits(type).c.ToDisplay(speed, false);
970}
971
979{
980 return GetVelocityUnits(type).c.FromDisplay(speed);
981}
982
990{
991 return GetVelocityUnits(type).c.ToDisplay(speed * 10, false) / 16;
992}
993
1001{
1002 return GetVelocityUnits(type).c.FromDisplay(speed * 16, true, 10);
1003}
1004
1011static void DecodeEncodedString(StringConsumer &consumer, bool game_script, StringBuilder &builder)
1012{
1013 std::vector<StringParameter> sub_args;
1014
1015 StringIndexInTab id(consumer.ReadIntegerBase<uint32_t>(16));
1016 if (consumer.AnyBytesLeft() && !consumer.PeekUtf8If(SCC_RECORD_SEPARATOR)) {
1017 consumer.SkipAll();
1018 builder += "(invalid SCC_ENCODED)";
1019 return;
1020 }
1021 if (game_script && id >= TAB_SIZE_GAMESCRIPT) {
1022 consumer.SkipAll();
1023 builder += "(invalid StringID)";
1024 return;
1025 }
1026
1027 while (consumer.AnyBytesLeft()) {
1028 consumer.SkipUtf8If(SCC_RECORD_SEPARATOR);
1029 StringConsumer record(consumer.ReadUntilUtf8(SCC_RECORD_SEPARATOR, StringConsumer::KEEP_SEPARATOR));
1030
1031 if (!record.AnyBytesLeft()) {
1032 /* This is an empty parameter. */
1033 sub_args.emplace_back(std::monostate{});
1034 continue;
1035 }
1036
1037 /* Get the parameter type. */
1038 char32_t parameter_type = record.ReadUtf8();
1039 switch (parameter_type) {
1040 case SCC_ENCODED: {
1041 uint64_t param = record.ReadIntegerBase<uint64_t>(16);
1042 if (param >= TAB_SIZE_GAMESCRIPT) {
1043 builder += "(invalid sub-StringID)";
1044 return;
1045 }
1046 assert(!record.AnyBytesLeft());
1048 sub_args.emplace_back(param);
1049 break;
1050 }
1051
1052 case SCC_ENCODED_NUMERIC: {
1053 uint64_t param = record.ReadIntegerBase<uint64_t>(16);
1054 assert(!record.AnyBytesLeft());
1055 sub_args.emplace_back(param);
1056 break;
1057 }
1058
1059 case SCC_ENCODED_STRING: {
1060 sub_args.emplace_back(record.Read(StringConsumer::npos));
1061 break;
1062 }
1063
1064 default:
1065 /* Unknown parameter, make it blank. */
1066 sub_args.emplace_back(std::monostate{});
1067 break;
1068 }
1069 }
1070
1071 StringID stringid = game_script ? MakeStringID(TEXT_TAB_GAMESCRIPT_START, id) : StringID{id.base()};
1072 GetStringWithArgs(builder, stringid, sub_args, true);
1073}
1074
1080static bool IsColourSafe(std::string_view buffer)
1081{
1082 int safety = 0;
1083 for (char32_t ch : Utf8View(buffer)) {
1084 if (ch == SCC_PUSH_COLOUR) {
1085 ++safety;
1086 } else if (ch == SCC_POP_COLOUR) {
1087 --safety;
1088 if (safety < 0) return false;
1089 } else if ((ch >= SCC_BLUE && ch <= SCC_BLACK) || ch == SCC_COLOUR) {
1090 if (safety == 0) return false;
1091 }
1092 }
1093 return true;
1094}
1095
1105static void FormatString(StringBuilder &builder, std::string_view str_arg, StringParameters &args, uint orig_case_index, bool game_script, bool dry_run)
1106{
1107 size_t orig_first_param_offset = args.GetOffset();
1108 bool emit_automatic_push_pop = false;
1109
1110 if (!dry_run) {
1111 /*
1112 * This function is normally called with `dry_run` false, then we call this function again
1113 * with `dry_run` being true. The dry run is required for the gender formatting. For the
1114 * gender determination we need to format a sub string to get the gender, but for that we
1115 * need to know as what string control code type the specific parameter is encoded. Since
1116 * gendered words can be before the "parameter" words, this needs to be determined before
1117 * the actual formatting.
1118 */
1119 std::string buffer;
1120 StringBuilder dry_run_builder(buffer);
1121 FormatString(dry_run_builder, str_arg, args, orig_case_index, game_script, true);
1122 emit_automatic_push_pop = !IsColourSafe(buffer);
1123 /* We have to restore the original offset here to to read the correct values. */
1124 args.SetOffset(orig_first_param_offset);
1125 }
1126 uint next_substr_case_index = 0;
1127 struct StrStackItem {
1128 StringConsumer consumer;
1129 size_t first_param_offset;
1130 uint case_index;
1131
1132 StrStackItem(std::string_view view, size_t first_param_offset, uint case_index)
1133 : consumer(view), first_param_offset(first_param_offset), case_index(case_index)
1134 {}
1135 };
1136 std::stack<StrStackItem, std::vector<StrStackItem>> str_stack;
1137 str_stack.emplace(str_arg, orig_first_param_offset, orig_case_index);
1138
1139 if (emit_automatic_push_pop) builder.PutUtf8(SCC_PUSH_COLOUR);
1140
1141 for (;;) {
1142 try {
1143 while (!str_stack.empty() && !str_stack.top().consumer.AnyBytesLeft()) {
1144 str_stack.pop();
1145 }
1146 if (str_stack.empty()) break;
1147 StringConsumer &consumer = str_stack.top().consumer;
1148 const size_t ref_param_offset = str_stack.top().first_param_offset;
1149 const uint case_index = str_stack.top().case_index;
1150 char32_t b = consumer.ReadUtf8();
1151 assert(b != 0);
1152 if (b == 0) {
1153 /* A NUL character should never be encountered, but for non-debug builds handle it gracefully. */
1154 builder += "(unexpected NUL)";
1155 continue;
1156 }
1157
1158 if (SCC_NEWGRF_FIRST <= b && b <= SCC_NEWGRF_LAST) {
1159 /* We need to pass some stuff as it might be modified. */
1160 b = RemapNewGRFStringControlCode(b, consumer);
1161 if (b == 0) continue;
1162 }
1163
1164 if (b < SCC_CONTROL_START || b > SCC_CONTROL_END) {
1165 builder.PutUtf8(b);
1166 continue;
1167 }
1168
1169 args.SetTypeOfNextParameter(b);
1170 switch (b) {
1171 case SCC_ENCODED:
1173 DecodeEncodedString(consumer, b == SCC_ENCODED, builder);
1174 break;
1175
1176 case SCC_NEWGRF_STRINL: {
1177 StringID substr{consumer.ReadUtf8(STR_NULL.base())};
1178 std::string_view ptr = GetStringPtr(substr);
1179 str_stack.emplace(ptr, args.GetOffset(), next_substr_case_index); // this may invalidate "consumer"
1180 next_substr_case_index = 0;
1181 break;
1182 }
1183
1185 StringID substr = args.GetNextParameter<StringID>();
1186 std::string_view ptr = GetStringPtr(substr);
1187 str_stack.emplace(ptr, args.GetOffset(), next_substr_case_index); // this may invalidate "consumer"
1188 next_substr_case_index = 0;
1189 break;
1190 }
1191
1192 case SCC_GENDER_LIST: { // {G 0 Der Die Das}
1193 /* First read the meta data from the language file. */
1194 size_t offset = ref_param_offset + consumer.ReadUint8();
1195 uint8_t gender = 0;
1196 if (offset >= args.GetNumParameters()) {
1197 /* The offset may come from an external NewGRF, and be invalid. */
1198 builder += "(invalid GENDER parameter)";
1199 } else if (!dry_run && args.GetTypeAtOffset(offset) != 0) {
1200 /* Now we need to figure out what text to resolve, i.e.
1201 * what do we need to draw? So get the actual raw string
1202 * first using the control code to get said string. */
1203 std::string input;
1204 {
1205 StringBuilder tmp_builder(input);
1206 tmp_builder.PutUtf8(args.GetTypeAtOffset(offset));
1207 }
1208
1209 std::string buffer;
1210 {
1211 AutoRestoreBackup sgd_backup(_scan_for_gender_data, true);
1212 StringBuilder tmp_builder(buffer);
1213 StringParameters tmp_params = args.GetRemainingParameters(offset);
1214 FormatString(tmp_builder, input, tmp_params);
1215 }
1216
1217 /* The gender is stored at the start of the formatted string.
1218 * Does this string have a gender, if so, set it. */
1219 StringConsumer gender_consumer(buffer);
1220 if (gender_consumer.ReadUtf8If(SCC_GENDER_INDEX)) {
1221 gender = gender_consumer.ReadUint8();
1222 }
1223 }
1224 ParseStringChoice(consumer, gender, builder);
1225 break;
1226 }
1227
1228 /* This sets up the gender for the string.
1229 * We just ignore this one. It's used in {G 0 Der Die Das} to determine the case. */
1230 case SCC_GENDER_INDEX: { // {GENDER 0}
1231 uint8_t gender = consumer.ReadUint8();
1233 builder.PutUtf8(SCC_GENDER_INDEX);
1234 builder.PutUint8(gender);
1235 }
1236 break;
1237 }
1238
1239 case SCC_PLURAL_LIST: { // {P}
1240 uint8_t plural_form = consumer.ReadUint8(); // contains the plural form for this string
1241 size_t offset = ref_param_offset + consumer.ReadUint8();
1242 const uint64_t *v = nullptr;
1243 /* The offset may come from an external NewGRF, and be invalid. */
1244 if (offset < args.GetNumParameters()) {
1245 v = std::get_if<uint64_t>(&args.GetParam(offset)); // contains the number that determines plural
1246 }
1247 if (v != nullptr) {
1248 ParseStringChoice(consumer, DeterminePluralForm(static_cast<int64_t>(*v), plural_form), builder);
1249 } else {
1250 SkipStringChoice(consumer);
1251 builder += "(invalid PLURAL parameter)";
1252 }
1253 break;
1254 }
1255
1256 case SCC_ARG_INDEX: { // Move argument pointer
1257 args.SetOffset(ref_param_offset + consumer.ReadUint8());
1258 break;
1259 }
1260
1261 case SCC_SET_CASE: { // {SET_CASE}
1262 /* This is a pseudo command, it's outputted when someone does {STRING.ack}
1263 * The modifier is added to all subsequent GetStringWithArgs that accept the modifier. */
1264 next_substr_case_index = consumer.ReadUint8();
1265 break;
1266 }
1267
1268 case SCC_SWITCH_CASE: { // {Used to implement case switching}
1269 /* <0x9E> <NUM CASES> <CASE1> <LEN1> <STRING1> <CASE2> <LEN2> <STRING2> <CASE3> <LEN3> <STRING3> <LENDEFAULT> <STRINGDEFAULT>
1270 * Each LEN is printed using 2 bytes in little endian order. */
1271 uint num = consumer.ReadUint8();
1272 std::optional<std::string_view> found;
1273 for (; num > 0; --num) {
1274 uint8_t index = consumer.ReadUint8();
1275 uint16_t len = consumer.ReadUint16LE();
1276 auto case_str = consumer.Read(len);
1277 if (index == case_index) {
1278 /* Found the case */
1279 found = case_str;
1280 }
1281 }
1282 uint16_t default_len = consumer.ReadUint16LE();
1283 auto default_str = consumer.Read(default_len);
1284 if (!found.has_value()) found = default_str;
1285 str_stack.emplace(*found, ref_param_offset, case_index); // this may invalidate "consumer"
1286 break;
1287 }
1288
1289 case SCC_REVISION: // {REV}
1290 builder += _openttd_revision;
1291 break;
1292
1293 case SCC_RAW_STRING_POINTER: // {RAW_STRING}
1294 FormatString(builder, args.GetNextParameterString(), args);
1295 break;
1296
1297 case SCC_STRING: {// {STRING}
1298 StringID string_id = args.GetNextParameter<StringID>();
1299 if (game_script && GetStringTab(string_id) != TEXT_TAB_GAMESCRIPT_START) break;
1300 /* It's prohibited for the included string to consume any arguments. */
1301 StringParameters tmp_params(args, game_script ? args.GetDataLeft() : 0);
1302 GetStringWithArgs(builder, string_id, tmp_params, next_substr_case_index, game_script);
1303 next_substr_case_index = 0;
1304 break;
1305 }
1306
1307 case SCC_STRING1:
1308 case SCC_STRING2:
1309 case SCC_STRING3:
1310 case SCC_STRING4:
1311 case SCC_STRING5:
1312 case SCC_STRING6:
1313 case SCC_STRING7: { // {STRING1..7}
1314 /* Strings that consume arguments */
1315 StringID string_id = args.GetNextParameter<StringID>();
1316 if (game_script && GetStringTab(string_id) != TEXT_TAB_GAMESCRIPT_START) break;
1317 uint size = b - SCC_STRING1 + 1;
1318 if (size > args.GetDataLeft()) {
1319 builder += "(consumed too many parameters)";
1320 } else {
1321 StringParameters sub_args(args, game_script ? args.GetDataLeft() : size);
1322 GetStringWithArgs(builder, string_id, sub_args, next_substr_case_index, game_script);
1323 args.AdvanceOffset(size);
1324 }
1325 next_substr_case_index = 0;
1326 break;
1327 }
1328
1329 case SCC_COMMA: // {COMMA}
1330 FormatCommaNumber(builder, args.GetNextParameter<int64_t>());
1331 break;
1332
1333 case SCC_DECIMAL: { // {DECIMAL}
1334 int64_t number = args.GetNextParameter<int64_t>();
1335 int digits = args.GetNextParameter<int>();
1336 if (digits == 0) {
1337 FormatCommaNumber(builder, number);
1338 break;
1339 }
1340
1341 int64_t divisor = PowerOfTen(digits);
1342 int64_t fractional = number % divisor;
1343 number /= divisor;
1344 FormatCommaNumber(builder, number);
1345 fmt::format_to(builder.back_inserter(), "{}{:0{}d}", GetDecimalSeparator(), fractional, digits);
1346 break;
1347 }
1348
1349 case SCC_NUM: // {NUM}
1350 FormatNoCommaNumber(builder, args.GetNextParameter<int64_t>());
1351 break;
1352
1353 case SCC_ZEROFILL_NUM: { // {ZEROFILL_NUM}
1354 int64_t num = args.GetNextParameter<int64_t>();
1355 FormatZerofillNumber(builder, num, args.GetNextParameter<int>());
1356 break;
1357 }
1358
1359 case SCC_HEX: // {HEX}
1360 FormatHexNumber(builder, args.GetNextParameter<uint64_t>());
1361 break;
1362
1363 case SCC_BYTES: // {BYTES}
1364 FormatBytes(builder, args.GetNextParameter<int64_t>());
1365 break;
1366
1367 case SCC_CARGO_TINY: { // {CARGO_TINY}
1368 /* Tiny description of cargotypes. Layout:
1369 * param 1: cargo type
1370 * param 2: cargo count */
1371 CargoType cargo = args.GetNextParameter<CargoType>();
1372 int64_t amount = args.GetNextParameter<int64_t>();
1373
1374 if (cargo >= CargoSpec::GetArraySize()) {
1375 builder += "(invalid cargo type)";
1376 break;
1377 }
1378
1379 switch (CargoSpec::Get(cargo)->units_volume.base()) {
1380 case STR_TONS.base():
1381 amount = _units_weight[_settings_game.locale.units_weight].c.ToDisplay(amount);
1382 break;
1383
1384 case STR_LITERS.base():
1385 amount = _units_volume[_settings_game.locale.units_volume].c.ToDisplay(amount);
1386 break;
1387
1388 default:
1389 break;
1390 }
1391
1392 FormatCommaNumber(builder, amount);
1393 break;
1394 }
1395
1396 case SCC_CARGO_SHORT: { // {CARGO_SHORT}
1397 /* Short description of cargotypes. Layout:
1398 * param 1: cargo type
1399 * param 2: cargo count */
1400 CargoType cargo = args.GetNextParameter<CargoType>();
1401 int64_t amount = args.GetNextParameter<int64_t>();
1402
1403 if (cargo >= CargoSpec::GetArraySize()) {
1404 builder += "(invalid cargo type)";
1405 break;
1406 }
1407
1408 StringID cargo_str = CargoSpec::Get(cargo)->units_volume;
1409 switch (cargo_str.base()) {
1410 case STR_TONS.base(): {
1411 assert(_settings_game.locale.units_weight < lengthof(_units_weight));
1412 const auto &x = _units_weight[_settings_game.locale.units_weight];
1413 auto tmp_params = MakeParameters(x.c.ToDisplay(amount), x.decimal_places);
1414 FormatString(builder, GetStringPtr(x.l), tmp_params);
1415 break;
1416 }
1417
1418 case STR_LITERS.base(): {
1419 assert(_settings_game.locale.units_volume < lengthof(_units_volume));
1420 const auto &x = _units_volume[_settings_game.locale.units_volume];
1421 auto tmp_params = MakeParameters(x.c.ToDisplay(amount), x.decimal_places);
1422 FormatString(builder, GetStringPtr(x.l), tmp_params);
1423 break;
1424 }
1425
1426 default: {
1427 auto tmp_params = MakeParameters(amount);
1428 GetStringWithArgs(builder, cargo_str, tmp_params);
1429 break;
1430 }
1431 }
1432 break;
1433 }
1434
1435 case SCC_CARGO_LONG: { // {CARGO_LONG}
1436 /* First parameter is cargo type, second parameter is cargo count */
1437 CargoType cargo = args.GetNextParameter<CargoType>();
1438 int64_t amount = args.GetNextParameter<int64_t>();
1439 if (cargo < CargoSpec::GetArraySize()) {
1440 auto tmp_args = MakeParameters(amount);
1441 GetStringWithArgs(builder, CargoSpec::Get(cargo)->quantifier, tmp_args);
1442 } else if (!IsValidCargoType(cargo)) {
1443 GetStringWithArgs(builder, STR_QUANTITY_N_A, {});
1444 } else {
1445 builder += "(invalid cargo type)";
1446 }
1447 break;
1448 }
1449
1450 case SCC_CARGO_LIST: { // {CARGO_LIST}
1451 CargoTypes cmask = args.GetNextParameter<CargoTypes>();
1452 bool first = true;
1453
1454 std::string_view list_separator = GetListSeparator();
1455 for (const auto &cs : _sorted_cargo_specs) {
1456 if (!cmask.Test(cs->Index())) continue;
1457
1458 if (first) {
1459 first = false;
1460 } else {
1461 /* Add a comma if this is not the first item */
1462 builder += list_separator;
1463 }
1464
1465 GetStringWithArgs(builder, cs->name, args, next_substr_case_index, game_script);
1466 }
1467
1468 /* If first is still true then no cargo is accepted */
1469 if (first) GetStringWithArgs(builder, STR_JUST_NOTHING, args, next_substr_case_index, game_script);
1470
1471 next_substr_case_index = 0;
1472 break;
1473 }
1474
1475 case SCC_CURRENCY_SHORT: // {CURRENCY_SHORT}
1476 FormatGenericCurrency(builder, &GetCurrency(), args.GetNextParameter<int64_t>(), true);
1477 break;
1478
1479 case SCC_CURRENCY_LONG: // {CURRENCY_LONG}
1480 FormatGenericCurrency(builder, &GetCurrency(), args.GetNextParameter<int64_t>(), false);
1481 break;
1482
1483 case SCC_DATE_TINY: // {DATE_TINY}
1484 FormatTinyOrISODate(builder, args.GetNextParameter<TimerGameCalendar::Date>(), STR_FORMAT_DATE_TINY);
1485 break;
1486
1487 case SCC_DATE_SHORT: // {DATE_SHORT}
1488 FormatMonthAndYear(builder, args.GetNextParameter<TimerGameCalendar::Date>(), next_substr_case_index);
1489 next_substr_case_index = 0;
1490 break;
1491
1492 case SCC_DATE_LONG: // {DATE_LONG}
1493 FormatYmdString(builder, args.GetNextParameter<TimerGameCalendar::Date>(), next_substr_case_index);
1494 next_substr_case_index = 0;
1495 break;
1496
1497 case SCC_DATE_ISO: // {DATE_ISO}
1498 FormatTinyOrISODate(builder, args.GetNextParameter<TimerGameCalendar::Date>(), STR_FORMAT_DATE_ISO);
1499 break;
1500
1501 case SCC_FORCE: { // {FORCE}
1502 assert(_settings_game.locale.units_force < lengthof(_units_force));
1503 const auto &x = _units_force[_settings_game.locale.units_force];
1504 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1505 FormatString(builder, GetStringPtr(x.s), tmp_params);
1506 break;
1507 }
1508
1509 case SCC_HEIGHT: { // {HEIGHT}
1510 assert(_settings_game.locale.units_height < lengthof(_units_height));
1511 const auto &x = _units_height[_settings_game.locale.units_height];
1512 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1513 FormatString(builder, GetStringPtr(x.s), tmp_params);
1514 break;
1515 }
1516
1517 case SCC_POWER: { // {POWER}
1518 assert(_settings_game.locale.units_power < lengthof(_units_power));
1519 const auto &x = _units_power[_settings_game.locale.units_power];
1520 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1521 FormatString(builder, GetStringPtr(x.s), tmp_params);
1522 break;
1523 }
1524
1525 case SCC_POWER_TO_WEIGHT: { // {POWER_TO_WEIGHT}
1526 auto setting = _settings_game.locale.units_power * 3u + _settings_game.locale.units_weight;
1527 assert(setting < lengthof(_units_power_to_weight));
1528 const auto &x = _units_power_to_weight[setting];
1529 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1530 FormatString(builder, GetStringPtr(x.s), tmp_params);
1531 break;
1532 }
1533
1534 case SCC_VELOCITY: { // {VELOCITY}
1535 int64_t arg = args.GetNextParameter<int64_t>();
1536 /* Unpack vehicle type from packed argument to get desired units. */
1537 VehicleType vt = static_cast<VehicleType>(GB(arg, 56, 8));
1538 const auto &x = GetVelocityUnits(vt);
1539 auto tmp_params = MakeParameters(ConvertKmhishSpeedToDisplaySpeed(GB(arg, 0, 56), vt), x.decimal_places);
1540 FormatString(builder, GetStringPtr(x.s), tmp_params);
1541 break;
1542 }
1543
1544 case SCC_VOLUME_SHORT: { // {VOLUME_SHORT}
1545 assert(_settings_game.locale.units_volume < lengthof(_units_volume));
1546 const auto &x = _units_volume[_settings_game.locale.units_volume];
1547 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1548 FormatString(builder, GetStringPtr(x.s), tmp_params);
1549 break;
1550 }
1551
1552 case SCC_VOLUME_LONG: { // {VOLUME_LONG}
1553 assert(_settings_game.locale.units_volume < lengthof(_units_volume));
1554 const auto &x = _units_volume[_settings_game.locale.units_volume];
1555 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1556 FormatString(builder, GetStringPtr(x.l), tmp_params);
1557 break;
1558 }
1559
1560 case SCC_WEIGHT_SHORT: { // {WEIGHT_SHORT}
1561 assert(_settings_game.locale.units_weight < lengthof(_units_weight));
1562 const auto &x = _units_weight[_settings_game.locale.units_weight];
1563 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1564 FormatString(builder, GetStringPtr(x.s), tmp_params);
1565 break;
1566 }
1567
1568 case SCC_WEIGHT_LONG: { // {WEIGHT_LONG}
1569 assert(_settings_game.locale.units_weight < lengthof(_units_weight));
1570 const auto &x = _units_weight[_settings_game.locale.units_weight];
1571 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1572 FormatString(builder, GetStringPtr(x.l), tmp_params);
1573 break;
1574 }
1575
1576 case SCC_UNITS_DAYS_OR_SECONDS: { // {UNITS_DAYS_OR_SECONDS}
1577 uint8_t realtime = TimerGameEconomy::UsingWallclockUnits(_game_mode == GameMode::Menu);
1578 const auto &x = _units_time_days_or_seconds[realtime];
1579 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1580 FormatString(builder, GetStringPtr(x.s), tmp_params);
1581 break;
1582 }
1583
1584 case SCC_UNITS_MONTHS_OR_MINUTES: { // {UNITS_MONTHS_OR_MINUTES}
1585 uint8_t realtime = TimerGameEconomy::UsingWallclockUnits(_game_mode == GameMode::Menu);
1586 const auto &x = _units_time_months_or_minutes[realtime];
1587 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1588 FormatString(builder, GetStringPtr(x.s), tmp_params);
1589 break;
1590 }
1591
1592 case SCC_UNITS_YEARS_OR_PERIODS: { // {UNITS_YEARS_OR_PERIODS}
1593 uint8_t realtime = TimerGameEconomy::UsingWallclockUnits(_game_mode == GameMode::Menu);
1594 const auto &x = _units_time_years_or_periods[realtime];
1595 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1596 FormatString(builder, GetStringPtr(x.s), tmp_params);
1597 break;
1598 }
1599
1600 case SCC_UNITS_YEARS_OR_MINUTES: { // {UNITS_YEARS_OR_MINUTES}
1601 uint8_t realtime = TimerGameEconomy::UsingWallclockUnits(_game_mode == GameMode::Menu);
1602 const auto &x = _units_time_years_or_minutes[realtime];
1603 auto tmp_params = MakeParameters(x.c.ToDisplay(args.GetNextParameter<int64_t>()), x.decimal_places);
1604 FormatString(builder, GetStringPtr(x.s), tmp_params);
1605 break;
1606 }
1607
1608 case SCC_COMPANY_NAME: { // {COMPANY}
1609 const Company *c = Company::GetIfValid(args.GetNextParameter<CompanyID>());
1610 if (c == nullptr) break;
1611
1612 if (!c->name.empty()) {
1613 auto tmp_params = MakeParameters(c->name);
1614 GetStringWithArgs(builder, STR_JUST_RAW_STRING, tmp_params);
1615 } else {
1616 auto tmp_params = MakeParameters(c->name_2);
1617 GetStringWithArgs(builder, c->name_1, tmp_params);
1618 }
1619 break;
1620 }
1621
1622 case SCC_COMPANY_NUM: { // {COMPANY_NUM}
1623 CompanyID company = args.GetNextParameter<CompanyID>();
1624
1625 /* Nothing is added for AI or inactive companies */
1626 if (Company::IsValidHumanID(company)) {
1627 auto tmp_params = MakeParameters(company + 1);
1628 GetStringWithArgs(builder, STR_FORMAT_COMPANY_NUM, tmp_params);
1629 }
1630 break;
1631 }
1632
1633 case SCC_DEPOT_NAME: { // {DEPOT}
1635 if (vt == VehicleType::Aircraft) {
1636 auto tmp_params = MakeParameters(args.GetNextParameter<StationID>());
1637 GetStringWithArgs(builder, STR_FORMAT_DEPOT_NAME_AIRCRAFT, tmp_params);
1638 break;
1639 }
1640
1641 const Depot *d = Depot::Get(args.GetNextParameter<DepotID>());
1642 if (!d->name.empty()) {
1643 auto tmp_params = MakeParameters(d->name);
1644 GetStringWithArgs(builder, STR_JUST_RAW_STRING, tmp_params);
1645 } else {
1646 auto tmp_params = MakeParameters(d->town->index, d->town_cn + 1);
1647 GetStringWithArgs(builder, STR_FORMAT_DEPOT_NAME_TRAIN + 2 * to_underlying(vt) + (d->town_cn == 0 ? 0 : 1), tmp_params);
1648 }
1649 break;
1650 }
1651
1652 case SCC_ENGINE_NAME: { // {ENGINE}
1653 int64_t arg = args.GetNextParameter<int64_t>();
1654 const Engine *e = Engine::GetIfValid(static_cast<EngineID>(arg));
1655 if (e == nullptr) break;
1656
1657 if (!e->name.empty() && e->IsEnabled()) {
1658 auto tmp_params = MakeParameters(e->name);
1659 GetStringWithArgs(builder, STR_JUST_RAW_STRING, tmp_params);
1660 break;
1661 }
1662
1663 if (e->info.callback_mask.Test(VehicleCallbackMask::Name)) {
1664 std::array<int32_t, 16> regs100;
1665 uint16_t callback = GetVehicleCallback(CBID_VEHICLE_NAME, static_cast<uint32_t>(arg >> 32), 0, e->index, nullptr, regs100);
1666 /* Not calling ErrorUnknownCallbackResult due to being inside string processing. */
1667 if (callback == 0x40F) {
1668 const GRFFile *grffile = e->GetGRF();
1669 assert(grffile != nullptr);
1670
1671 builder += GetGRFStringWithTextStack(grffile, static_cast<GRFStringID>(regs100[0]), std::span{regs100}.subspan(1));
1672 break;
1673 } else if (callback < 0x400) {
1674 const GRFFile *grffile = e->GetGRF();
1675 assert(grffile != nullptr);
1676
1677 builder += GetGRFStringWithTextStack(grffile, GRFSTR_MISC_GRF_TEXT + callback, regs100);
1678 break;
1679 }
1680 }
1681
1682 GetStringWithArgs(builder, e->info.string_id, {});
1683 break;
1684 }
1685
1686 case SCC_GROUP_NAME: { // {GROUP}
1687 const Group *g = Group::GetIfValid(args.GetNextParameter<GroupID>());
1688 if (g == nullptr) break;
1689
1690 if (!g->name.empty()) {
1691 auto tmp_params = MakeParameters(g->name);
1692 GetStringWithArgs(builder, STR_JUST_RAW_STRING, tmp_params);
1693 } else {
1694 auto tmp_params = MakeParameters(g->number);
1695 GetStringWithArgs(builder, STR_FORMAT_GROUP_NAME, tmp_params);
1696 }
1697 break;
1698 }
1699
1700 case SCC_INDUSTRY_NAME: { // {INDUSTRY}
1701 const Industry *i = Industry::GetIfValid(args.GetNextParameter<IndustryID>());
1702 if (i == nullptr) break;
1703
1704 static bool use_cache = true;
1706 /* Gender is defined by the industry type.
1707 * STR_FORMAT_INDUSTRY_NAME may have the town first, so it would result in the gender of the town name */
1708 FormatString(builder, GetStringPtr(GetIndustrySpec(i->type)->name), {}, next_substr_case_index);
1709 } else if (use_cache) { // Use cached version if first call
1710 AutoRestoreBackup cache_backup(use_cache, false);
1711 builder += i->GetCachedName();
1712 } else {
1713 /* First print the town name and the industry type name. */
1714 auto tmp_params = MakeParameters(i->town->index, GetIndustrySpec(i->type)->name);
1715 FormatString(builder, GetStringPtr(STR_FORMAT_INDUSTRY_NAME), tmp_params, next_substr_case_index);
1716 }
1717 next_substr_case_index = 0;
1718 break;
1719 }
1720
1721 case SCC_PRESIDENT_NAME: { // {PRESIDENT_NAME}
1722 const Company *c = Company::GetIfValid(args.GetNextParameter<CompanyID>());
1723 if (c == nullptr) break;
1724
1725 if (!c->president_name.empty()) {
1726 auto tmp_params = MakeParameters(c->president_name);
1727 GetStringWithArgs(builder, STR_JUST_RAW_STRING, tmp_params);
1728 } else {
1729 auto tmp_params = MakeParameters(c->president_name_2);
1730 GetStringWithArgs(builder, c->president_name_1, tmp_params);
1731 }
1732 break;
1733 }
1734
1735 case SCC_STATION_NAME: { // {STATION}
1736 StationID sid = args.GetNextParameter<StationID>();
1737 const Station *st = Station::GetIfValid(sid);
1738
1739 if (st == nullptr) {
1740 /* The station doesn't exist anymore. The only place where we might
1741 * be "drawing" an invalid station is in the case of cargo that is
1742 * in transit. */
1743 GetStringWithArgs(builder, STR_UNKNOWN_STATION, {});
1744 break;
1745 }
1746
1747 static bool use_cache = true;
1748 if (use_cache) { // Use cached version if first call
1749 AutoRestoreBackup cache_backup(use_cache, false);
1750 builder += st->GetCachedName();
1751 } else if (!st->name.empty()) {
1752 auto tmp_params = MakeParameters(st->name);
1753 GetStringWithArgs(builder, STR_JUST_RAW_STRING, tmp_params);
1754 } else {
1755 StringID string_id = st->string_id;
1756 if (st->indtype != IT_INVALID) {
1757 /* Special case where the industry provides the name for the station */
1758 const IndustrySpec *indsp = GetIndustrySpec(st->indtype);
1759
1760 /* Industry GRFs can change which might remove the station name and
1761 * thus cause very strange things. Here we check for that before we
1762 * actually set the station name. */
1763 if (indsp->station_name != STR_NULL && indsp->station_name != STR_UNDEFINED) {
1764 string_id = indsp->station_name;
1765 }
1766 }
1767
1768 auto tmp_params = MakeParameters(STR_TOWN_NAME, st->town->index, st->index);
1769 GetStringWithArgs(builder, string_id, tmp_params);
1770 }
1771 break;
1772 }
1773
1774 case SCC_TOWN_NAME: { // {TOWN}
1775 const Town *t = Town::GetIfValid(args.GetNextParameter<TownID>());
1776 if (t == nullptr) break;
1777
1778 static bool use_cache = true;
1779 if (use_cache) { // Use cached version if first call
1780 AutoRestoreBackup cache_backup(use_cache, false);
1781 builder += t->GetCachedName();
1782 } else if (!t->name.empty()) {
1783 auto tmp_params = MakeParameters(t->name);
1784 GetStringWithArgs(builder, STR_JUST_RAW_STRING, tmp_params);
1785 } else {
1786 GetTownName(builder, t);
1787 }
1788 break;
1789 }
1790
1791 case SCC_WAYPOINT_NAME: { // {WAYPOINT}
1792 Waypoint *wp = Waypoint::GetIfValid(args.GetNextParameter<StationID>());
1793 if (wp == nullptr) break;
1794
1795 if (!wp->name.empty()) {
1796 auto tmp_params = MakeParameters(wp->name);
1797 GetStringWithArgs(builder, STR_JUST_RAW_STRING, tmp_params);
1798 } else {
1799 auto tmp_params = MakeParameters(wp->town->index, wp->town_cn + 1);
1800 StringID string_id = ((wp->string_id == STR_SV_STNAME_BUOY) ? STR_FORMAT_BUOY_NAME : STR_FORMAT_WAYPOINT_NAME);
1801 if (wp->town_cn != 0) string_id++;
1802 GetStringWithArgs(builder, string_id, tmp_params);
1803 }
1804 break;
1805 }
1806
1807 case SCC_VEHICLE_NAME: { // {VEHICLE}
1809 if (v == nullptr) break;
1810
1811 if (!v->name.empty()) {
1812 auto tmp_params = MakeParameters(v->name);
1813 GetStringWithArgs(builder, STR_JUST_RAW_STRING, tmp_params);
1814 } else if (v->group_id != DEFAULT_GROUP) {
1815 /* The vehicle has no name, but is member of a group, so print group name */
1816 auto tmp_params = MakeParameters(v->group_id, v->unitnumber);
1817 GetStringWithArgs(builder, STR_FORMAT_GROUP_VEHICLE_NAME, tmp_params);
1818 } else {
1819 auto tmp_params = MakeParameters(v->unitnumber);
1820
1821 StringID string_id;
1822 switch (v->type) {
1823 default: string_id = STR_INVALID_VEHICLE; break;
1824 case VehicleType::Train: string_id = STR_SV_TRAIN_NAME; break;
1825 case VehicleType::Road: string_id = STR_SV_ROAD_VEHICLE_NAME; break;
1826 case VehicleType::Ship: string_id = STR_SV_SHIP_NAME; break;
1827 case VehicleType::Aircraft: string_id = STR_SV_AIRCRAFT_NAME; break;
1828 }
1829
1830 GetStringWithArgs(builder, string_id, tmp_params);
1831 }
1832 break;
1833 }
1834
1835 case SCC_SIGN_NAME: { // {SIGN}
1836 const Sign *si = Sign::GetIfValid(args.GetNextParameter<SignID>());
1837 if (si == nullptr) break;
1838
1839 if (!si->name.empty()) {
1840 auto tmp_params = MakeParameters(si->name);
1841 GetStringWithArgs(builder, STR_JUST_RAW_STRING, tmp_params);
1842 } else {
1843 GetStringWithArgs(builder, STR_DEFAULT_SIGN_NAME, {});
1844 }
1845 break;
1846 }
1847
1848 case SCC_STATION_FEATURES: { // {STATIONFEATURES}
1849 StationGetSpecialString(builder, args.GetNextParameter<StationFacilities>());
1850 break;
1851 }
1852
1853 case SCC_COLOUR: { // {COLOUR}
1854 StringControlCode scc = static_cast<StringControlCode>(SCC_BLUE + to_underlying(args.GetNextParameter<Colours>()));
1855 if (IsInsideMM(scc, SCC_BLUE, SCC_COLOUR)) builder.PutUtf8(scc);
1856 break;
1857 }
1858
1859 default:
1860 builder.PutUtf8(b);
1861 break;
1862 }
1863 } catch (std::out_of_range &e) {
1864 Debug(Facility::Misc, Severity::Critical, "FormatString: {}", e.what());
1865 builder += "(invalid parameter)";
1866 }
1867 }
1868
1869 if (emit_automatic_push_pop) builder.PutUtf8(SCC_POP_COLOUR);
1870}
1871
1872
1873static void StationGetSpecialString(StringBuilder &builder, StationFacilities x)
1874{
1875 if (x.Test(StationFacility::Train)) builder.PutUtf8(SCC_TRAIN);
1876 if (x.Test(StationFacility::TruckStop)) builder.PutUtf8(SCC_LORRY);
1877 if (x.Test(StationFacility::BusStop)) builder.PutUtf8(SCC_BUS);
1878 if (x.Test(StationFacility::Dock)) builder.PutUtf8(SCC_SHIP);
1879 if (x.Test(StationFacility::Airport)) builder.PutUtf8(SCC_PLANE);
1880}
1881
1882static const std::string_view _silly_company_names[] = {
1883 "Bloggs Brothers",
1884 "Tiny Transport Ltd.",
1885 "Express Travel",
1886 "Comfy-Coach & Co.",
1887 "Crush & Bump Ltd.",
1888 "Broken & Late Ltd.",
1889 "Sam Speedy & Son",
1890 "Supersonic Travel",
1891 "Mike's Motors",
1892 "Lightning International",
1893 "Pannik & Loozit Ltd.",
1894 "Inter-City Transport",
1895 "Getout & Pushit Ltd."
1896};
1897
1898static const std::string_view _surname_list[] = {
1899 "Adams",
1900 "Allan",
1901 "Baker",
1902 "Bigwig",
1903 "Black",
1904 "Bloggs",
1905 "Brown",
1906 "Campbell",
1907 "Gordon",
1908 "Hamilton",
1909 "Hawthorn",
1910 "Higgins",
1911 "Green",
1912 "Gribble",
1913 "Jones",
1914 "McAlpine",
1915 "MacDonald",
1916 "McIntosh",
1917 "Muir",
1918 "Murphy",
1919 "Nelson",
1920 "O'Donnell",
1921 "Parker",
1922 "Phillips",
1923 "Pilkington",
1924 "Quigley",
1925 "Sharkey",
1926 "Thomson",
1927 "Watkins"
1928};
1929
1930static const std::string_view _silly_surname_list[] = {
1931 "Grumpy",
1932 "Dozy",
1933 "Speedy",
1934 "Nosey",
1935 "Dribble",
1936 "Mushroom",
1937 "Cabbage",
1938 "Sniffle",
1939 "Fishy",
1940 "Swindle",
1941 "Sneaky",
1942 "Nutkins"
1943};
1944
1945static const char _initial_name_letters[] = {
1946 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
1947 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W',
1948};
1949
1950static std::span<const std::string_view> GetSurnameOptions()
1951{
1952 if (_settings_game.game_creation.landscape == LandscapeType::Toyland) return _silly_surname_list;
1953 return _surname_list;
1954}
1955
1961static std::string_view GetSurname(uint32_t seed)
1962{
1963 auto surname_options = GetSurnameOptions();
1964 return surname_options[surname_options.size() * GB(seed, 16, 8) >> 8];
1965}
1966
1967static void GenAndCoName(StringBuilder &builder, uint32_t seed)
1968{
1969 builder += GetSurname(seed);
1970 builder += " & Co.";
1971}
1972
1973static void GenPresidentName(StringBuilder &builder, uint32_t seed)
1974{
1975 builder.PutChar(_initial_name_letters[std::size(_initial_name_letters) * GB(seed, 0, 8) >> 8]);
1976 builder += ". ";
1977
1978 /* The second initial is optional. */
1979 size_t index = (std::size(_initial_name_letters) + 35) * GB(seed, 8, 8) >> 8;
1980 if (index < std::size(_initial_name_letters)) {
1981 builder.PutChar(_initial_name_letters[index]);
1982 builder += ". ";
1983 }
1984
1985 builder += GetSurname(seed);
1986}
1987
1988static bool GetSpecialNameString(StringBuilder &builder, StringID string, StringParameters &args)
1989{
1990 switch (string.base()) {
1991 case SPECSTR_SILLY_NAME.base(): // Not used in new companies, but retained for old-loader savegames
1992 builder += _silly_company_names[std::min<size_t>(args.GetNextParameter<uint16_t>(), std::size(_silly_company_names) - 1)];
1993 return true;
1994
1995 case SPECSTR_ANDCO_NAME.base(): // used for Foobar & Co company names
1996 GenAndCoName(builder, args.GetNextParameter<uint32_t>());
1997 return true;
1998
1999 case SPECSTR_PRESIDENT_NAME.base(): // President name
2000 GenPresidentName(builder, args.GetNextParameter<uint32_t>());
2001 return true;
2002 }
2003
2004 /* TownName Transport company names, with the appropriate town name. */
2005 if (IsInsideMM(string, SPECSTR_COMPANY_NAME_START, SPECSTR_COMPANY_NAME_END)) {
2006 GenerateTownNameString(builder, (string - SPECSTR_COMPANY_NAME_START).base(), args.GetNextParameter<uint32_t>());
2007 builder += " Transport";
2008 return true;
2009 }
2010
2011 return false;
2012}
2013
2019{
2020 return this->ident == TO_LE32(LanguagePackHeader::IDENT) &&
2021 this->version == TO_LE32(LANGUAGE_PACK_VERSION) &&
2022 this->plural_form < LANGUAGE_MAX_PLURAL &&
2023 this->text_dir <= 1 &&
2025 this->num_genders < MAX_NUM_GENDERS &&
2026 this->num_cases < MAX_NUM_CASES &&
2027 StrValid(this->name) &&
2028 StrValid(this->own_name) &&
2029 StrValid(this->isocode) &&
2033}
2034
2040{
2041 /* "Less than 25% missing" is "sufficiently finished". */
2042 return 4 * this->missing < LANGUAGE_TOTAL_STRINGS;
2043}
2044
2051{
2052 /* Current language pack */
2053 size_t total_len = 0;
2054 std::unique_ptr<LanguagePack, LanguagePackDeleter> lang_pack(reinterpret_cast<LanguagePack *>(ReadFileToMem(FS2OTTD(lang->file.native()), total_len, 1U << 20).release()));
2055 if (!lang_pack) return false;
2056
2057 /* End of read data (+ terminating zero added in ReadFileToMem()) */
2058 const char *end = (char *)lang_pack.get() + total_len + 1;
2059
2060 /* We need at least one byte of lang_pack->data */
2061 if (end <= lang_pack->data || !lang_pack->IsValid()) {
2062 return false;
2063 }
2064
2065 std::array<uint, TEXT_TAB_END> tab_start, tab_num;
2066
2067 uint count = 0;
2068 for (StringTab i : EnumRange(TEXT_TAB_END)) {
2069 uint16_t num = FROM_LE16(lang_pack->offsets[i]);
2070 if (num > TAB_SIZE) return false;
2071
2072 tab_start[i] = count;
2073 tab_num[i] = num;
2074 count += num;
2075 }
2076
2077 /* Allocate offsets */
2078 std::vector<std::string_view> strings;
2079
2080 /* Fill offsets */
2081 char *s = lang_pack->data;
2082 for (uint i = 0; i < count; i++) {
2083 size_t len = static_cast<uint8_t>(*s++);
2084 if (s + len >= end) return false;
2085
2086 if (len >= 0xC0) {
2087 len = ((len & 0x3F) << 8) + static_cast<uint8_t>(*s++);
2088 if (s + len >= end) return false;
2089 }
2090 strings.emplace_back(s, len);
2091 s += len;
2092 }
2093 assert(strings.size() == count);
2094
2095 _langpack.langpack = std::move(lang_pack);
2096 _langpack.strings = std::move(strings);
2097 _langpack.langtab_num = tab_num;
2098 _langpack.langtab_start = tab_start;
2099
2100 _current_language = lang;
2102 _config_language_file = FS2OTTD(_current_language->file.filename().native());
2103 _langpack.list_separator = GetString(STR_LIST_SEPARATOR);
2104 _langpack.ellipsis = GetString(STR_TRUNCATION_ELLIPSIS);
2105
2106#ifdef _WIN32
2107 extern void Win32SetCurrentLocaleName(std::string iso_code);
2108 Win32SetCurrentLocaleName(_current_language->isocode);
2109#endif
2110
2111#ifdef WITH_COCOA
2112 extern void MacOSSetCurrentLocaleName(std::string_view iso_code);
2114#endif
2115
2116#ifdef WITH_ICU_I18N
2117 /* Create a collator instance for our current locale. */
2118 UErrorCode status = U_ZERO_ERROR;
2119 _current_collator.reset(icu::Collator::createInstance(icu::Locale(_current_language->isocode), status));
2120 /* Sort number substrings by their numerical value. */
2121 if (_current_collator) _current_collator->setAttribute(UCOL_NUMERIC_COLLATION, UCOL_ON, status);
2122 /* Avoid using the collator if it is not correctly set. */
2123 if (U_FAILURE(status)) {
2124 _current_collator.reset();
2125 }
2126#endif /* WITH_ICU_I18N */
2127
2129
2130 /* Some lists need to be sorted again after a language change. */
2136 InvalidateWindowClassesData(WindowClass::BuildVehicle); // Build vehicle window.
2137 InvalidateWindowClassesData(WindowClass::TrainList); // Train group window.
2138 InvalidateWindowClassesData(WindowClass::RoadVehicleList); // Road vehicle group window.
2139 InvalidateWindowClassesData(WindowClass::ShipList); // Ship group window.
2140 InvalidateWindowClassesData(WindowClass::AircraftList); // Aircraft group window.
2141 InvalidateWindowClassesData(WindowClass::IndustryDirectory); // Industry directory window.
2142 InvalidateWindowClassesData(WindowClass::StationList); // Station list window.
2143
2144 return true;
2145}
2146
2147/* Win32 implementation in win32.cpp.
2148 * OS X implementation in os/macosx/macos.mm. */
2149#if !(defined(_WIN32) || defined(__APPLE__))
2158std::optional<std::string> GetCurrentLocale(const char *param)
2159{
2160 auto env = GetEnv("LANGUAGE");
2161 if (env.has_value()) return std::string{*env};
2162
2163 env = GetEnv("LC_ALL");
2164 if (env.has_value()) return std::string{*env};
2165
2166 if (param != nullptr) {
2167 env = GetEnv(param);
2168 if (env.has_value()) return std::string{*env};
2169 }
2170
2171 env = GetEnv("LANG");
2172 if (env.has_value()) return std::string{*env};
2173
2174 return std::nullopt;
2175}
2176#else
2177std::optional<std::string> GetCurrentLocale(const char *param);
2178#endif /* !(defined(_WIN32) || defined(__APPLE__)) */
2179
2186{
2187 for (const LanguageMetadata &lang : _languages) {
2188 if (newgrflangid == lang.newgrflangid) return &lang;
2189 }
2190
2191 return nullptr;
2192}
2193
2200static bool GetLanguageFileHeader(const std::string &file, LanguagePackHeader *hdr)
2201{
2202 auto f = FileHandle::Open(file, "rb");
2203 if (!f.has_value()) return false;
2204
2205 size_t read = fread(hdr, sizeof(*hdr), 1, *f);
2206
2207 bool ret = read == 1 && hdr->IsValid();
2208
2209 /* Convert endianness for the windows language ID */
2210 if (ret) {
2211 hdr->missing = FROM_LE16(hdr->missing);
2212 hdr->winlangid = FROM_LE16(hdr->winlangid);
2213 }
2214 return ret;
2215}
2216
2221static void FillLanguageList(const std::string &path)
2222{
2223 std::error_code error_code;
2224 for (const auto &dir_entry : std::filesystem::directory_iterator(OTTD2FS(path), error_code)) {
2225 if (!dir_entry.is_regular_file()) continue;
2226 if (dir_entry.path().extension() != ".lng") continue;
2227
2228 LanguageMetadata lmd;
2229 lmd.file = dir_entry.path();
2230
2231 /* Check whether the file is of the correct version */
2232 std::string file = FS2OTTD(lmd.file.native());
2233 if (!GetLanguageFileHeader(file, &lmd)) {
2234 Debug(Facility::Misc, Severity::Notice, "{} is not a valid language file", file);
2235 } else if (GetLanguage(lmd.newgrflangid) != nullptr) {
2236 Debug(Facility::Misc, Severity::Notice, "{}'s language ID is already known", file);
2237 } else {
2238 _languages.push_back(std::move(lmd));
2239 }
2240 }
2241 if (error_code) {
2242 Debug(Facility::Misc, Severity::Trace3, "Unable to open directory {}: {}", path, error_code.message());
2243 }
2244}
2245
2251{
2252 for (Searchpath sp : _valid_searchpaths) {
2253 FillLanguageList(FioGetDirectory(sp, Subdirectory::Lang));
2254 }
2255 if (_languages.empty()) UserError("No available language packs (invalid versions?)");
2256
2257 /* Acquire the locale of the current system */
2258 auto str_lang = GetCurrentLocale("LC_MESSAGES");
2259 std::string_view lang = str_lang.has_value() ? std::string_view{*str_lang} : "en_GB";
2260
2261 const LanguageMetadata *chosen_language = nullptr;
2262 const LanguageMetadata *language_fallback = nullptr;
2263 const LanguageMetadata *en_GB_fallback = _languages.data();
2264
2265 /* Find a proper language. */
2266 for (const LanguageMetadata &lng : _languages) {
2267 /* We are trying to find a default language. The priority is by
2268 * configuration file, local environment and last, if nothing found,
2269 * English. */
2270 if (_config_language_file == FS2OTTD(lng.file.filename().native())) {
2271 chosen_language = &lng;
2272 break;
2273 }
2274
2275 std::string_view iso_code = lng.isocode;
2276 if (iso_code == "en_GB") en_GB_fallback = &lng;
2277
2278 /* Only auto-pick finished translations */
2279 if (!lng.IsReasonablyFinished()) continue;
2280
2281 if (iso_code.starts_with(lang.substr(0, 5))) chosen_language = &lng;
2282 if (iso_code.starts_with(lang.substr(0, 2))) language_fallback = &lng;
2283 }
2284
2285 /* We haven't found the language in the config nor the one in the locale.
2286 * Now we set it to one of the fallback languages */
2287 if (chosen_language == nullptr) {
2288 chosen_language = (language_fallback != nullptr) ? language_fallback : en_GB_fallback;
2289 }
2290
2291 if (!ReadLanguagePack(chosen_language)) UserError("Can't read language pack '{}'", FS2OTTD(chosen_language->file.native()));
2292}
2293
2299{
2300 return _langpack.langpack->isocode;
2301}
2302
2304{
2305 this->missing_fontsizes.Reset();
2306 this->missing_glyphs.clear();
2307 this->required_glyphs.clear();
2308
2309 this->Reset();
2310 for (auto text = this->NextString(); text.has_value(); text = this->NextString()) {
2311 FontSize fs = this->DefaultSize();
2312 FontCache *fc = FontCache::Get(fs);
2313 for (char32_t c : Utf8View(*text)) {
2314 if (c >= SCC_FIRST_FONT && c <= SCC_LAST_FONT) {
2315 fs = (FontSize)(c - SCC_FIRST_FONT);
2316 fc = FontCache::Get(fs);
2317 continue;
2318 }
2319
2320 if (!fontsizes.Test(fs)) continue;
2321 if (!IsPrintable(c) || IsTextDirectionChar(c)) continue;
2322 if (c != ' ' && (IsWhitespace(c) || IsNonbreakingWhitespace(c))) continue;
2323 if (IsInsideMM(c, SCC_SPRITE_START, SCC_SPRITE_END)) continue;
2324
2325 this->required_glyphs.insert(c);
2326
2327 if (fc->MapCharToGlyph(c, false) != 0) continue;
2328
2329 this->missing_fontsizes.Set(fs);
2330 this->missing_glyphs.insert(c);
2331 }
2332 }
2333}
2334
2337private:
2338 uint i;
2339 uint j;
2340
2341 void Reset() override
2342 {
2343 this->i = 0;
2344 this->j = 0;
2345 }
2346
2348 {
2349 return FontSize::Normal;
2350 }
2351
2352 std::optional<std::string_view> NextString() override
2353 {
2354 if (this->i >= TEXT_TAB_END) return std::nullopt;
2355
2356 std::string_view ret = _langpack.strings[_langpack.langtab_start[this->i] + this->j];
2357
2358 this->j++;
2359 while (this->i < TEXT_TAB_END && this->j >= _langpack.langtab_num[this->i]) {
2360 this->i++;
2361 this->j = 0;
2362 }
2363
2364 return ret;
2365 }
2366};
2367
2382{
2383 static LanguagePackGlyphSearcher pack_searcher;
2384 if (searcher == nullptr) searcher = &pack_searcher;
2385
2386 FontCache::LoadFontCaches(fontsizes);
2387
2388 searcher->DetermineRequiredGlyphs(fontsizes);
2389 bool bad_font = searcher->missing_fontsizes.Any();
2390
2391 if (bad_font) {
2392 Debug(Facility::Fontcache, Severity::Error, "Missing {} glyph(s) in requested fonts", searcher->missing_glyphs.size());
2394 for (char32_t c : searcher->missing_glyphs) {
2395 Debug(Facility::Fontcache, Severity::Notice, " U+{:04X}", static_cast<uint32_t>(c));
2396 }
2397 }
2398 }
2399
2400#if defined(WITH_FREETYPE) || defined(_WIN32) || defined(WITH_COCOA)
2401 if (bad_font) {
2402 /* We found an unprintable character... lets try whether we can find
2403 * a fallback font that can print the characters in the current language. */
2404 bool any_font_configured = !_fcsettings.medium.font.empty();
2405 FontCacheSettings backup = _fcsettings;
2406
2407 /* All systems expect a hyphen not an underscore in the isocode. */
2408 std::string isocode = _langpack.langpack->isocode;
2409 std::ranges::replace(isocode, '_', '-');
2410
2411 bad_font = !FontProviderManager::FindFallbackFont(isocode, searcher);
2412 if (!bad_font) {
2414 }
2415
2416 _fcsettings = std::move(backup);
2417
2418 if (!bad_font && any_font_configured) {
2419 /* If the user configured a bad font, and we found a better one,
2420 * show that we loaded the better font instead of the configured one.
2421 */
2422 std::string err_str;
2423 StringBuilder builder(err_str);
2424 builder.PutUtf8(SCC_YELLOW);
2425 builder.Put("The current font is missing some of the characters used in the texts for this language. Using system fallback font instead.");
2426 ShowErrorMessage(GetEncodedString(STR_JUST_RAW_STRING, std::move(err_str)), {}, WarningLevel::Warning);
2427 }
2428 }
2429#endif
2430
2431 /* Update the font width cache */
2432 LoadStringWidthTable(fontsizes);
2433
2434 if (bad_font) {
2435 /* All attempts have failed. Display an error. As we do not want the string to be translated by
2436 * the translators, we 'force' it into the binary and 'load' it via a BindCString. To do this
2437 * properly we have to set the colour of the string, otherwise we end up with a lot of artifacts.
2438 */
2439 std::string err_str;
2440 StringBuilder builder(err_str);
2441 builder.PutUtf8(SCC_YELLOW);
2442 builder.Put("The current font is missing some of the characters used in the texts for this language. Go to Help & Manuals > Fonts, or read the file docs/fonts.md in your OpenTTD directory, to see how to solve this.");
2443 ShowErrorMessage(GetEncodedString(STR_JUST_RAW_STRING, std::move(err_str)), {}, WarningLevel::Warning);
2444 return;
2445 }
2446
2447#if !(defined(WITH_ICU_I18N) && defined(WITH_HARFBUZZ)) && !defined(WITH_UNISCRIBE) && !defined(WITH_COCOA)
2448 /*
2449 * For right-to-left languages we need the ICU library. If
2450 * we do not have support for that library we warn the user
2451 * about it with a message. As we do not want the string to
2452 * be translated by the translators, we 'force' it into the
2453 * binary and 'load' it via a BindCString. To do this
2454 * properly we have to set the colour of the string,
2455 * otherwise we end up with a lot of artifacts.
2456 */
2457 if (_current_text_dir != TD_LTR) {
2458 std::string err_str;
2459 StringBuilder builder(err_str);
2460 builder.PutUtf8(SCC_YELLOW);
2461 builder.Put("This version of OpenTTD does not support right-to-left languages. Recompile with ICU + Harfbuzz enabled.");
2462 ShowErrorMessage(GetEncodedString(STR_JUST_RAW_STRING, std::move(err_str)), {}, WarningLevel::Error);
2463 }
2464#endif /* !(WITH_ICU_I18N && WITH_HARFBUZZ) && !WITH_UNISCRIBE && !WITH_COCOA */
2465}
Class for backupping variables and making sure they are restored later.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:112
EnumBitSet< CargoType, uint64_t > CargoTypes
Bitset of CargoType elements.
Definition cargo_type.h:115
CargoType
Cargo slots to indicate a cargo type within a game.
Definition cargo_type.h:22
std::vector< const CargoSpec * > _sorted_cargo_specs
Cargo specifications sorted alphabetically by name.
void InitializeSortedCargoSpecs()
Initialize the list of sorted cargo specifications.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
void PutUtf8(char32_t c)
Append UTF-8 char.
void Put(std::string_view str)
Append string.
void PutIntegerBase(T value, int base)
Append integer 'value' in given number 'base'.
void PutChar(char c)
Append 8-bit char.
void PutUint8(uint8_t value)
Append binary uint8.
Base for missing glyph searchers that look for missing glyphs in strings.
virtual FontSize DefaultSize()=0
Get the default (font) size of the string.
virtual void Reset()=0
Reset the search, i.e.
virtual std::optional< std::string_view > NextString()=0
Get the next string to search through.
void DetermineRequiredGlyphs(FontSizes fontsizes) override
Determine set of glyphs required for the current language.
Definition strings.cpp:2303
Container for an encoded string, created by GetEncodedString.
friend EncodedString GetEncodedStringWithArgs(StringID str, std::span< const StringParameter > params)
Encode a string with its parameters into an encoded string.
Definition strings.cpp:101
std::string GetDecodedString() const
Decode the encoded string.
Definition strings.cpp:206
EncodedString ReplaceParam(size_t param, StringParameter &&value) const
Replace a parameter of this EncodedString.
Definition strings.cpp:149
Iterate a range of enum values.
static std::optional< FileHandle > Open(const std::string &filename, std::string_view mode)
Open an RAII file handle if possible.
Definition fileio.cpp:1218
Font cache for basic fonts.
Definition fontcache.h:23
virtual GlyphID MapCharToGlyph(char32_t key, bool fallback=true)=0
Map a character into a glyph.
static void LoadFontCaches(FontSizes fontsizes)
(Re)initialize the font cache related things, i.e.
static FontCache * Get(FontSize fs)
Get the font cache of a given font size.
Definition fontcache.h:136
static bool FindFallbackFont(const std::string &language_isocode, MissingGlyphSearcher *callback)
We would like to have a fallback font as the current one doesn't contain all characters we need.
Definition fontcache.cpp:56
Helper for searching through the language pack.
Definition strings.cpp:2336
uint j
Iterator for the secondary language tables.
Definition strings.cpp:2339
std::optional< std::string_view > NextString() override
Get the next string to search through.
Definition strings.cpp:2352
FontSize DefaultSize() override
Get the default (font) size of the string.
Definition strings.cpp:2347
uint i
Iterator for the primary language tables.
Definition strings.cpp:2338
void Reset() override
Reset the search, i.e.
Definition strings.cpp:2341
static void Initialize()
Perform initialization of layout engine.
A searcher for missing glyphs.
virtual void DetermineRequiredGlyphs(FontSizes fontsizes)=0
Determine set of glyphs required for the current language.
std::set< char32_t > missing_glyphs
Glyphs that are missing in the current font.
FontSizes missing_fontsizes
Font sizes to actually search for.
std::set< char32_t > required_glyphs
Glyphs that are required.
Compose data into a growing std::string.
back_insert_iterator back_inserter()
Create a back-insert-iterator.
Parse data from a string / buffer.
std::optional< T > TryReadIntegerBase(int base, bool clamp=false)
Try to read and parse an integer in number 'base', and then advance the reader.
bool PeekUtf8If(char32_t c) const
Check whether the next UTF-8 char matches 'c'.
char32_t ReadUtf8(char32_t def='?')
Read UTF-8 character, and advance reader.
@ SKIP_ONE_SEPARATOR
Read and discard one separator, do not include it in the result.
@ KEEP_SEPARATOR
Keep the separator in the data as next value to be read.
bool AnyBytesLeft() const noexcept
Check whether any bytes left to read.
uint8_t ReadUint8(uint8_t def=0)
Read binary uint8, and advance reader.
uint16_t ReadUint16LE(uint16_t def=0)
Read binary uint16 using little endian, and advance reader.
void SkipAll()
Discard all remaining data.
T ReadIntegerBase(int base, T def=0, bool clamp=false)
Read and parse an integer in number 'base', and advance the reader.
std::string_view Read(size_type len)
Read the next 'len' bytes, and advance reader.
bool ReadUtf8If(char32_t c)
Check whether the next UTF-8 char matches 'c', and skip it.
static constexpr size_type npos
Special value for "end of data".
void Skip(size_type len)
Discard some bytes.
void SkipUtf8If(char32_t c)
If the next data matches the UTF-8 char 'c', then skip it.
std::string_view ReadUntilUtf8(char32_t c, SeparatorUsage sep)
Read data until the first occurrence of UTF-8 char 'c', and advance reader.
void SetOffset(size_t offset)
Set the offset within the string from where to return the next result of GetInt64 or GetInt32.
std::string_view GetNextParameterString()
Get the next string parameter from our parameters.
StringParameters GetRemainingParameters()
Get a new instance of StringParameters that is a "range" into the remaining existing parameters.
std::span< StringParameter > parameters
Array with the actual parameters.
const StringParameter & GetNextParameterReference()
Get the next parameter from our parameters.
Definition strings.cpp:67
void AdvanceOffset(size_t advance)
Advance the offset within the string from where to return the next result of GetInt64 or GetInt32.
uint64_t GetNextParameter()
Get the next parameter from our parameters.
size_t offset
Current offset in the parameters span.
char32_t next_type
The type of the next data that is retrieved.
size_t GetOffset()
Get the current offset, so it can be backed up for certain processing steps, or be used to offset the...
size_t GetNumParameters() const
Return the number of parameters.
size_t GetDataLeft() const
Return the amount of elements which can still be read.
char32_t GetTypeAtOffset(size_t offset) const
Get the type of a specific element.
static YearMonthDay ConvertDateToYMD(Date date)
Converts a Date to a Year, Month & Day.
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
StrongType::Typedef< int32_t, DateTag< struct Calendar >, StrongType::Compare, StrongType::Integer > Date
Constant span of UTF-8 encoded data.
Definition utf8.hpp:28
Definition of stuff that is very close to a company, like the company struct itself.
Control codes that are embedded in the translation strings.
StringControlCode
List of string control codes used for string formatting, displaying, and by strgen to generate the la...
@ SCC_ENCODED
Encoded string marker and sub-string parameter.
@ SCC_ENCODED_NUMERIC
Encoded numeric parameter.
@ SCC_ENCODED_STRING
Encoded string parameter.
@ SCC_NEWGRF_STRINL
Inline another string at the current position, StringID is encoded in the string.
@ SCC_NEWGRF_FIRST
The next variables are part of a NewGRF subsystem for creating text strings.
@ SCC_NEWGRF_PRINT_WORD_STRING_ID
81: Read 2 bytes from the stack as String ID
@ SCC_ENCODED_INTERNAL
Encoded text from OpenTTD.
Functions to handle different currencies.
const CurrencySpec & GetCurrency()
Get the currently selected currency.
@ Suffix
Show the suffix value.
@ Prefix
Show the prefix value.
Functions related to debugging.
bool IsVisibleSeverity(Facility facility, Severity severity)
Test if debug severity is visible for the given facility.
Definition debug.h:24
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Fontcache
Fontcache message facility.
Definition debug_type.h:37
@ Notice
Notice.
Definition debug_type.h:18
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Error
Error, but we are recovering.
Definition debug_type.h:16
@ Trace3
Trace information #3.
Definition debug_type.h:24
Base for all depots (except hangars).
PoolID< uint16_t, struct DepotIDTag, 64000, 0xFFFF > DepotID
Type for the unique identifier of depots.
Definition depot_type.h:15
Function to handling different endian machines.
Base class for engines.
PoolID< uint16_t, struct EngineIDTag, 64000, 0xFFFF > EngineID
Unique identification number of an engine.
Definition engine_type.h:25
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
Functions related to errors.
@ Warning
Other information.
Definition error.h:23
@ Error
Errors (eg. saving/loading failed).
Definition error.h:24
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
Error reporting related functions.
std::unique_ptr< char[]> ReadFileToMem(const std::string &filename, size_t &lenp, size_t maxsize)
Load a file into memory.
Definition fileio.cpp:1078
Functions for standard in/out file operations.
Searchpath
Types of searchpaths OpenTTD might use.
@ Lang
Subdirectory for all translation files.
Definition fileio_type.h:97
void ReconsiderGameScriptLanguage()
Reconsider the game script language, so we use the right one.
std::string_view GetGameStringPtr(StringIndexInTab id)
Get the string pointer of a particular game string.
Base functions regarding game texts.
std::pair< uint8_t, uint8_t > GetBroadestDigit(FontSize size)
Determine the broadest digits for guessing the maximum width of a n-digit number.
Definition gfx.cpp:1301
void LoadStringWidthTable(FontSizes fontsizes)
Initialize _stringwidth_table cache for the specified font sizes.
Definition gfx.cpp:1255
Functions related to laying out the texts.
FontSize
Available font sizes.
Definition gfx_type.h:248
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
Colours
One of 16 base colours used for companies and windows/widgets.
Definition gfx_type.h:283
EnumBitSet< FontSize, uint8_t > FontSizes
Bitset of FontSize elements.
Definition gfx_type.h:259
static constexpr GroupID DEFAULT_GROUP
Ungrouped vehicles are in this group.
Definition group_type.h:18
Base of all industries.
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
void SortIndustryTypes()
Initialize the list of sorted industry types.
@ Toyland
Landscape with funky industries and vehicles.
Information about languages and their files.
LanguageList _languages
The actual list of language meta data.
Definition strings.cpp:52
const LanguageMetadata * _current_language
The currently loaded language.
Definition strings.cpp:53
static const uint8_t MAX_NUM_GENDERS
Maximum number of supported genders.
Definition language.h:21
std::unique_ptr< icu::Collator > _current_collator
Collator for the language currently in use.
Definition strings.cpp:58
std::vector< LanguageMetadata > LanguageList
Type for the list of language meta data.
Definition language.h:95
static const uint8_t MAX_NUM_CASES
Maximum number of supported cases.
Definition language.h:22
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
constexpr uint64_t PowerOfTen(int power)
Computes ten to the given power.
void BuildContentTypeStringList()
Build array of all strings corresponding to the content types.
User interface for downloading files.
@ CBID_VEHICLE_NAME
Called to determine the engine name to show.
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v, std::span< int32_t > regs100)
Evaluate a newgrf callback for vehicles.
Functions for NewGRF engines.
std::string_view GetGRFStringPtr(StringIndexInTab stringid)
Get a C-string from a stringid set by a newgrf.
std::string GetGRFStringWithTextStack(const struct GRFFile *grffile, GRFStringID grfstringid, std::span< const int32_t > textstack)
Format a GRF string using the text ref stack for parameters.
char32_t RemapNewGRFStringControlCode(char32_t scc, StringConsumer &consumer)
Emit OpenTTD's internal string code for the different NewGRF string codes.
Header of Action 04 "universal holder" structure and functions.
GRFLanguage
Incomplete enumeration of the (New)GRF languages.
@ End
End marker of the valid languages.
StrongType::Typedef< uint32_t, struct GRFStringIDTag, StrongType::Compare, StrongType::Integer > GRFStringID
Type for GRF-internal string IDs.
static constexpr GRFStringID GRFSTR_MISC_GRF_TEXT
Miscellaneous GRF text range.
@ Menu
In the main menu.
Definition openttd.h:19
Declaration of OTTD revision dependent variables.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
Base class for signs.
PoolID< uint16_t, struct SignIDTag, 64000, 0xFFFF > SignID
The type of the IDs of signs.
Definition signs_type.h:16
void BuildIndustriesLegend()
Fills an array for the industries legends.
Smallmap GUI functions.
Base classes/functions for stations.
@ Dock
Station with a dock.
@ TruckStop
Station with truck stops.
@ Train
Station with train station.
@ Airport
Station with an airport.
@ BusStop
Station with bus stops.
EnumBitSet< StationFacility, uint8_t > StationFacilities
Bitset of StationFacility elements.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:261
std::optional< std::string_view > GetEnv(const char *variable)
Get the environment variable using std::getenv and when it is an empty string (or nullptr),...
Definition string.cpp:855
bool StrValid(std::span< const char > str)
Checks whether the given string is valid, i.e.
Definition string.cpp:206
Parse strings.
Functions related to low-level strings.
bool IsWhitespace(char32_t c)
Check whether UNICODE character is whitespace or not, i.e.
bool IsNonbreakingWhitespace(char32_t c)
Check wheather a character is non-breaking whitespace.
bool IsTextDirectionChar(char32_t c)
Is the given character a text direction character.
void MacOSSetCurrentLocaleName(std::string_view iso_code)
Store current language locale as a CoreFoundation locale.
#define NBSP
A non-breaking space.
Definition string_type.h:16
uint64_t GetParamMaxValue(uint64_t max_value, uint min_count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:235
void CheckForMissingGlyphs(FontSizes fontsizes, MissingGlyphSearcher *searcher)
Check whether the currently loaded language pack uses characters that the currently loaded font does ...
Definition strings.cpp:2381
static void FormatNumber(StringBuilder &builder, int64_t number, std::string_view separator)
Format a number into a string.
Definition strings.cpp:481
EncodedString GetEncodedStringWithArgs(StringID str, std::span< const StringParameter > params)
Encode a string with its parameters into an encoded string.
Definition strings.cpp:101
void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index, bool game_script)
Get a parsed string with most special stringcodes replaced by the string parameters.
Definition strings.cpp:335
std::optional< std::string > GetCurrentLocale(const char *param)
Determine the current charset based on the environment First check some default values,...
Definition strings.cpp:2158
std::string_view GetListSeparator()
Get the list separator string for the current language.
Definition strings.cpp:298
static const Units _units_height[]
Unit conversions for height.
Definition strings.cpp:910
static void FormatBytes(StringBuilder &builder, int64_t number)
Format a given number as a number of bytes with the SI prefix.
Definition strings.cpp:536
void AppendStringInPlace(std::string &result, StringID string)
Resolve the given StringID and append in place into an existing std::string with formatting but no pa...
Definition strings.cpp:433
uint ConvertSpeedToDisplaySpeed(uint speed, VehicleType type)
Convert the given (internal) speed to the display speed.
Definition strings.cpp:964
std::string _config_language_file
The file (name) stored in the configuration.
Definition strings.cpp:51
static const Units GetVelocityUnits(VehicleType type)
Get the correct velocity units depending on the vehicle type and whether we're using real-time units.
Definition strings.cpp:946
static int DeterminePluralForm(int64_t count, uint plural_form)
Determine the "plural" index given a plural form and a number.
Definition strings.cpp:651
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
uint ConvertDisplaySpeedToKmhishSpeed(uint speed, VehicleType type)
Convert the given display speed to the km/h-ish speed.
Definition strings.cpp:1000
static const Units _units_power[]
Unit conversions for power.
Definition strings.cpp:869
static std::string_view GetSurname(uint32_t seed)
Get the surname of the president with the given seed.
Definition strings.cpp:1961
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
std::string_view GetCurrentLanguageIsoCode()
Get the ISO language code of the currently loaded language.
Definition strings.cpp:2298
static bool _scan_for_gender_data
Are we scanning for the gender of the current string? (instead of formatting it).
Definition strings.cpp:292
static const UnitsLong _units_volume[]
Unit conversions for volume.
Definition strings.cpp:896
static void DecodeEncodedString(StringConsumer &consumer, bool game_script, StringBuilder &builder)
Decodes an encoded string during FormatString.
Definition strings.cpp:1011
static const UnitsLong _units_weight[]
Unit conversions for weight.
Definition strings.cpp:889
static const Units _units_velocity_calendar[]
Unit conversions for velocity.
Definition strings.cpp:851
static void FillLanguageList(const std::string &path)
Search for the languages in the given directory and add them to the _languages list.
Definition strings.cpp:2221
uint ConvertKmhishSpeedToDisplaySpeed(uint speed, VehicleType type)
Convert the given km/h-ish speed to the display speed.
Definition strings.cpp:989
static const Units _units_force[]
Unit conversions for force.
Definition strings.cpp:903
void InitializeLanguagePacks()
Make a list of the available language packs.
Definition strings.cpp:2250
static bool IsColourSafe(std::string_view buffer)
Test if a string contains colour codes, and is not wrapped by push/pop codes.
Definition strings.cpp:1080
static const Units _units_time_days_or_seconds[]
Unit conversions for time in calendar days or wallclock seconds.
Definition strings.cpp:918
uint ConvertDisplaySpeedToSpeed(uint speed, VehicleType type)
Convert the given display speed to the (internal) speed.
Definition strings.cpp:978
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
static const Units _units_velocity_realtime[]
Unit conversions for velocity.
Definition strings.cpp:860
bool ReadLanguagePack(const LanguageMetadata *lang)
Read a particular language.
Definition strings.cpp:2050
static bool GetLanguageFileHeader(const std::string &file, LanguagePackHeader *hdr)
Reads the language file header and checks compatibility.
Definition strings.cpp:2200
static const Units _units_time_months_or_minutes[]
Unit conversions for time in calendar months or wallclock minutes.
Definition strings.cpp:924
static void FormatString(StringBuilder &builder, std::string_view str, StringParameters &args, uint case_index=0, bool game_script=false, bool dry_run=false)
Parse most format codes within a string and write the result to a buffer.
Definition strings.cpp:1105
static const Units _units_time_years_or_minutes[]
Unit conversions for time in calendar years or wallclock minutes.
Definition strings.cpp:936
static const Units _units_power_to_weight[]
Unit conversions for power to weight.
Definition strings.cpp:876
uint64_t GetParamMaxDigits(uint count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:217
const LanguageMetadata * GetLanguage(GRFLanguage newgrflangid)
Get the language with the given NewGRF language ID.
Definition strings.cpp:2185
std::string_view GetEllipsis()
Get the ellipsis string for the current language.
Definition strings.cpp:307
static const Units _units_time_years_or_periods[]
Unit conversions for time in calendar years or economic periods.
Definition strings.cpp:930
Functions related to OTTD's strings.
StringTab GetStringTab(StringID str)
Extract the StringTab from a StringID.
auto MakeParameters(Args &&... args)
Helper to create the StringParameters with its own buffer with the given parameter values.
StringID MakeStringID(StringTab tab, StringIndexInTab index)
Create a StringID.
StringIndexInTab GetStringIndex(StringID str)
Extract the StringIndex from a StringID.
Types and functions related to the internal workings of formatting OpenTTD's strings.
void GenerateTownNameString(StringBuilder &builder, size_t lang, uint32_t seed)
Generates town name from given seed.
Definition townname.cpp:973
StrongType::Typedef< uint32_t, struct StringIndexInTabTag, StrongType::Compare, StrongType::Integer > StringIndexInTab
The index/offset of a string within a StringTab.
static constexpr StringID SPECSTR_COMPANY_NAME_START
Special strings for company names on the form "TownName transport".
static constexpr StringID SPECSTR_SILLY_NAME
Special string for silly company names.
static const uint TAB_SIZE_GAMESCRIPT
Number of strings for GameScripts.
static constexpr uint16_t SPECSTR_TOWNNAME_START
Special strings for town names.
static constexpr StringID SPECSTR_ANDCO_NAME
Special string for Surname & Co company names.
static constexpr StringID SPECSTR_PRESIDENT_NAME
Special string for the president's name.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
static const uint TAB_SIZE
Number of strings per StringTab.
StringTab
StringTabs to group StringIDs.
@ TEXT_TAB_NEWGRF_START
Start of NewGRF supplied strings.
@ TEXT_TAB_GAMESCRIPT_START
Start of GameScript supplied strings.
@ TEXT_TAB_END
End of language files.
TextDirection
Directions a text can go to.
@ TD_LTR
Text is written left-to-right by default.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
std::string name
Name of vehicle.
StringID string_id
Default name (town area) of station.
Town * town
The town this station is associated with.
std::string name
Custom name.
VehicleType type
Type of vehicle.
StringID units_volume
Name of a single unit of cargo of this type.
Definition cargotype.h:95
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:140
static size_t GetArraySize()
Total number of cargospecs, both valid and invalid.
Definition cargotype.h:129
std::string president_name
Name of the president if the user changed it.
uint32_t name_2
Parameter of name_1.
uint32_t president_name_2
Parameter of president_name_1.
StringID name_1
Name of the company if the user did not change it.
StringID president_name_1
Name of the president if the user did not change it.
std::string name
Name of the company if the user changed it.
static bool IsValidHumanID(auto index)
Is this company a valid company, not controlled by a NoAI program?
Specification of a currency.
std::string separator
The thousands separator for this currency.
CurrencySymbolPositions symbol_pos
Which currency symbols should we show?
std::string prefix
Prefix to apply when formatting money in this currency.
std::string suffix
Suffix to apply when formatting money in this currency.
uint16_t rate
The conversion rate compared to the base currency.
uint16_t town_cn
The N-1th depot for this town (consecutive number).
Definition depot_base.h:22
Settings for the four different fonts.
Definition fontcache.h:198
Dynamic data of a loaded NewGRF.
Definition newgrf.h:126
Group data.
Definition group.h:76
std::string name
Group Name.
Definition group.h:77
uint16_t number
Per-company group number.
Definition group.h:89
Defines the data structure for constructing industry.
StringID name
Displayed name of the industry.
StringID station_name
Default name for nearby station.
Defines the internal data of a functional industry.
Definition industry.h:64
IndustryType type
type of industry.
Definition industry.h:117
Town * town
Nearest town.
Definition industry.h:109
Make sure the size is right.
Definition language.h:90
std::filesystem::path file
Name of the file we read this data from.
Definition language.h:91
Header of a language file.
Definition language.h:25
uint8_t plural_form
plural form index
Definition language.h:42
bool IsValid() const
Check whether the header is a valid header for OpenTTD.
Definition strings.cpp:2018
bool IsReasonablyFinished() const
Check whether a translation is sufficiently finished to offer it to the public.
Definition strings.cpp:2039
uint32_t version
32-bits of auto generated version info which is basically a hash of strings.h
Definition language.h:29
char isocode[16]
the ISO code for the language (not country code)
Definition language.h:32
char own_name[32]
the localized name of this language
Definition language.h:31
char name[32]
the international name of this language
Definition language.h:30
uint16_t winlangid
Windows language ID: Windows cannot and will not convert isocodes to something it can use to determin...
Definition language.h:52
uint8_t num_genders
the number of genders of this language
Definition language.h:54
uint16_t missing
number of missing strings.
Definition language.h:41
char digit_group_separator[8]
Thousand separator used for anything not currencies.
Definition language.h:36
GRFLanguage newgrflangid
newgrf language id
Definition language.h:53
uint8_t text_dir
default direction of the text
Definition language.h:43
uint8_t num_cases
the number of cases of this language
Definition language.h:55
uint32_t ident
32-bits identifier
Definition language.h:28
char digit_decimal_separator[8]
Decimal separator.
Definition language.h:40
char digit_group_separator_currency[8]
Thousand separator used for currencies.
Definition language.h:38
static const uint32_t IDENT
Identifier for OpenTTD language files, big endian for "LANG".
Definition language.h:26
char data[]
List of strings.
Definition strings.cpp:267
std::string list_separator
Current list separator string.
Definition strings.cpp:286
std::string ellipsis
Current ellipsis string.
Definition strings.cpp:287
std::array< uint, TEXT_TAB_END > langtab_num
Offset into langpack offs.
Definition strings.cpp:283
std::array< uint, TEXT_TAB_END > langtab_start
Offset into langpack offs.
Definition strings.cpp:284
static Depot * Get(auto index)
static Company * GetIfValid(auto index)
static Station * GetIfValid(auto index)
Station data structure.
The data required to format and validate a single parameter of a string.
Town data structure.
Definition town.h:64
std::string name
Custom town name. If empty, the town was not renamed and uses the generated name.
Definition town.h:74
Helper for unit conversion.
Definition strings.cpp:804
double factor
Amount to multiply or divide upon conversion.
Definition strings.cpp:805
int64_t ToDisplay(int64_t input, bool round=true) const
Convert value from OpenTTD's internal unit into the displayed value.
Definition strings.cpp:813
int64_t FromDisplay(int64_t input, bool round=true, int64_t divider=1) const
Convert the displayed value back into a value of OpenTTD's internal unit.
Definition strings.cpp:827
Information about a specific unit system with a long variant.
Definition strings.cpp:843
StringID s
String for the short variant of the unit.
Definition strings.cpp:845
StringID l
String for the long variant of the unit.
Definition strings.cpp:846
unsigned int decimal_places
Number of decimal places embedded in the value. For example, 1 if the value is in tenths,...
Definition strings.cpp:847
UnitConversion c
Conversion.
Definition strings.cpp:844
Information about a specific unit system.
Definition strings.cpp:836
StringID s
String for the unit.
Definition strings.cpp:838
unsigned int decimal_places
Number of decimal places embedded in the value. For example, 1 if the value is in tenths,...
Definition strings.cpp:839
UnitConversion c
Conversion.
Definition strings.cpp:837
Vehicle data structure.
GroupID group_id
Index of group Pool array.
UnitID unitnumber
unit number, for display purposes only
Representation of a waypoint.
uint16_t town_cn
The N-1th waypoint for this town (consecutive number).
Definition of the game-calendar-timer.
Base of the town class.
std::pair< size_t, char32_t > DecodeUtf8(std::string_view buf)
Decode a character from UTF-8.
Definition utf8.cpp:46
Handling of UTF-8 encoded data.
Base class for all vehicles.
PoolID< uint32_t, struct VehicleIDTag, 0xFF000, 0xFFFFF > VehicleID
The type all our vehicle IDs have.
VehicleType
Available vehicle types.
@ Ship
Ship vehicle type.
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Train
Train vehicle type.
Base of waypoints.
std::wstring OTTD2FS(std::string_view name)
Convert from OpenTTD's encoding to a wide string.
Definition win32.cpp:389
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.
Definition win32.cpp:373
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3395
Window functions not directly related to making/drawing windows.