aboutsummaryrefslogtreecommitdiff
path: root/advtrains/tracks.lua
blob: 39592321c40e0920aa7f9b68b2e1268c4acb9b02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
--advtrains by orwell96, see readme.txt

--dev-time settings:
--EDIT HERE
--If the old non-model rails on straight tracks should be replaced by the new...
--false: no
--true: yes
advtrains.register_replacement_lbms=false

--[[TracksDefinition
nodename_prefix
texture_prefix
description
common={}
straight={}
straight45={}
curve={}
curve45={}
lswitchst={}
lswitchst45={}
rswitchst={}
rswitchst45={}
lswitchcr={}
lswitchcr45={}
rswitchcr={}
rswitchcr45={}
vert1={
	--you'll probably want to override mesh here
}
vert2={
	--you'll probably want to override mesh here
}
]]--
advtrains.all_tracktypes={}

--definition preparation
local function conns(c1, c2, r1, r2) return {{c=c1, y=r1}, {c=c2, y=r2}} end
local function conns3(c1, c2, c3, r1, r2, r3) return {{c=c1, y=r1}, {c=c2, y=r2}, {c=c3, y=r3}} end

advtrains.ap={}
advtrains.ap.t_30deg_flat={
	regstep=1,
	variant={
		st={
			conns = conns(0,8),
			desc = "straight",
			tpdouble = true,
			tpsingle = true,
			trackworker = "cr",
		},
		cr={
			conns = conns(0,7),
			desc = "curve",
			tpdouble = true,
			trackworker = "swlst",
		},
		swlst={
			conns = conns3(0,8,7),
			desc = "left switch (straight)",
			trackworker = "swrst",
			switchalt = "cr",
			switchmc = "on",
			switchst = "st",
			switchprefix = "swl",
		},
		swlcr={
			conns = conns3(0,7,8),
			desc = "left switch (curve)",
			trackworker = "swrcr",
			switchalt = "st",
			switchmc = "off",
			switchst = "cr",
			switchprefix = "swl",
		},
		swrst={
			conns = conns3(0,8,9),
			desc = "right switch (straight)",
			trackworker = "st",
			switchalt = "cr",
			switchmc = "on",
			switchst = "st",
			switchprefix = "swr",
		},
		swrcr={
			conns = conns3(0,9,8),
			desc = "right switch (curve)",
			trackworker = "st",
			switchalt = "st",
			switchmc = "off",
			switchst = "cr",
			switchprefix = "swr",
		},
	},
	regtp=true,
	tpdefault="st",
	trackworker={
		["swrcr"]="st",
		["swrst"]="st",
		["cr"]="swlst",
		["swlcr"]="swrcr",
		["swlst"]="swrst",
	},
	rotation={"", "_30", "_45", "_60"},
}
advtrains.ap.t_yturnout={
	regstep=1,
	variant={
		l={
			conns = conns3(0,7,9),
			desc = "Y-turnout (left)",
			switchalt = "r",
			switchmc = "off",
			switchst = "l",
			switchprefix = "",
		},
		r={
			conns = conns3(0,9,7),
			desc = "Y-turnout (right)",
			switchalt = "l",
			switchmc = "on",
			switchst = "r",
			switchprefix = "",
		}
	},
	regtp=true,
	tpdefault="l",
	rotation={"", "_30", "_45", "_60"},
}
advtrains.ap.t_s3way={
	regstep=1,
	variant={
		l={
			conns = { {c=0}, {c=7}, {c=8}, {c=9}, {c=0} },
			desc = "3-way turnout (left)",
			switchalt = "s",
			switchst="l",
			switchprefix = "",
		},
		s={
			conns = { {c=0}, {c=8}, {c=7}, {c=9}, {c=0} },
			desc = "3-way turnout (straight)",
			switchalt ="r",
			switchst = "s",
			switchprefix = "",
		},
		r={
			conns = { {c=0}, {c=9}, {c=8}, {c=7}, {c=0} },
			desc = "3-way turnout (right)",
			switchalt = "l",
			switchst="r",
			switchprefix = "",
		}
	},
	regtp=true,
	tpdefault="l",
	rotation={"", "_30", "_45", "_60"},
}
advtrains.ap.t_30deg_slope={
	regstep=1,
	variant={
		vst1={conns = conns(8,0,0,0.5), rail_y = 0.25, desc = "steep uphill 1/2", slope=true},
		vst2={conns = conns(8,0,0.5,1), rail_y = 0.75, desc = "steep uphill 2/2", slope=true},
		vst31={conns = conns(8,0,0,0.33), rail_y = 0.16, desc = "uphill 1/3", slope=true},
		vst32={conns = conns(8,0,0.33,0.66), rail_y = 0.5, desc = "uphill 2/3", slope=true},
		vst33={conns = conns(8,0,0.66,1), rail_y = 0.83, desc = "uphill 3/3", slope=true},
	},
	regsp=true,
	slopeplacer={
		[2]={"vst1", "vst2"},
		[3]={"vst31", "vst32", "vst33"},
		max=3,--highest entry
	},
	slopeplacer_45={
		[2]={"vst1_45", "vst2_45"},
		max=2,
	},
	rotation={"", "_30", "_45", "_60"},
	trackworker={},
	increativeinv={},
}
advtrains.ap.t_30deg_straightonly={
	regstep=1,
	variant={
		st={
			conns = conns(0,8),
			desc = "straight",
			tpdouble = true,
			tpsingle = true,
			trackworker = "st",
		},
	},
	regtp=true,
	tpdefault="st",
	rotation={"", "_30", "_45", "_60"},
}
advtrains.ap.t_30deg_straightonly_noplacer={
	regstep=1,
	variant={
		st={
			conns = conns(0,8),
			desc = "straight",
			tpdouble = true,
			tpsingle = true,
			trackworker = "st",
		},
	},
	tpdefault="st",
	rotation={"", "_30", "_45", "_60"},
}
advtrains.ap.t_45deg={
	regstep=2,
	variant={
		st={
			conns = conns(0,8),
			desc = "straight",
			tpdouble = true,
			tpsingle = true,
			trackworker = "cr",
		},
		cr={
			conns = conns(0,6),
			desc = "curve",
			tpdouble = true,
			trackworker = "swlst",
		},
		swlst={
			conns = conns3(0,8,6),
			desc = "left switch (straight)",
			trackworker = "swrst",
			switchalt = "cr",
			switchmc = "on",
			switchst = "st",
		},
		swlcr={
			conns = conns3(0,6,8),
			desc = "left switch (curve)",
			trackworker = "swrcr",
			switchalt = "st",
			switchmc = "off",
			switchst = "cr",
		},
		swrst={
			conns = conns3(0,8,10),
			desc = "right switch (straight)",
			trackworker = "st",
			switchalt = "cr",
			switchmc = "on",
			switchst = "st",
		},
		swrcr={
			conns = conns3(0,10,8),
			desc = "right switch (curve)",
			trackworker = "st",
			switchalt = "st",
			switchmc = "off",
			switchst = "cr",
		},
	},
	regtp=true,
	tpdefault="st",
	trackworker={
		["swrcr"]="st",
		["swrst"]="st",
		["cr"]="swlst",
		["swlcr"]="swrcr",
		["swlst"]="swrst",
	},
	rotation={"", "_30", "_45", "_60"},
}
advtrains.ap.t_perpcrossing={
	regstep = 1,
	variant={
		st={
			conns = { {c=0}, {c=8}, {c=4}, {c=12} },
			desc = "perpendicular crossing",
			tpdouble = true,
			tpsingle = true,
			trackworker = "st",
		},
	},
	regtp=true,
	tpdefault="st",
	rotation={"", "_30", "_45", "_60"},
}
advtrains.ap.t_90plusx_crossing={
	regstep = 1,
	variant={
		["30l"]={
			conns = { {c=0}, {c=8}, {c=1}, {c=9} },
			desc = "30/90 degree crossing (left)",
			tpdouble = true,
			tpsingle = true,
			trackworker = "45l"
		},
		["45l"]={
			conns = { {c=0}, {c=8}, {c=2}, {c=10} },
			desc = "45/90 degree crossing (left)",
			tpdouble = true,
			tpsingle = true,
			trackworker = "60l",
		},
		["60l"]={
			conns = { {c=0}, {c=8}, {c=3}, {c=11}},
			desc = "60/90 degree crossing (left)",
			tpdouble = true,
			tpsingle = true,
			trackworker = "60r",
		},
		["60r"]={
			conns = { {c=0}, {c=8}, {c=5}, {c=13} },
			desc = "60/90 degree crossing (right)",
			tpdouble = true,
			tpsingle = true,
			trackworker = "45r"
		},
		["45r"]={
			conns = { {c=0}, {c=8}, {c=6}, {c=14} },
			desc = "45/90 degree crossing (right)",
			tpdouble = true,
			tpsingle = true,span class="hl kwb">char **lasts)
{
	char *t;

	if (!s)
		s = *lasts;

	while (*s && strchr(sep, *s))
		s++;

	if (!*s)
		return nullptr;

	t = s;
	while (*t) {
		if (strchr(sep, *t)) {
			*t++ = '\0';
			break;
		}
		t++;
	}

	*lasts = t;
	return s;
}

u64 read_seed(const char *str)
{
	char *endptr;
	u64 num;

	if (str[0] == '0' && str[1] == 'x')
		num = strtoull(str, &endptr, 16);
	else
		num = strtoull(str, &endptr, 10);

	if (*endptr)
		num = murmur_hash_64_ua(str, (int)strlen(str), 0x1337);

	return num;
}

static bool parseHexColorString(const std::string &value, video::SColor &color,
		unsigned char default_alpha)
{
	u8 components[] = {0x00, 0x00, 0x00, default_alpha}; // R,G,B,A

	size_t len = value.size();
	bool short_form;

	if (len == 9 || len == 7) // #RRGGBBAA or #RRGGBB
		short_form = false;
	else if (len == 5 || len == 4) // #RGBA or #RGB
		short_form = true;
	else
		return false;

	for (size_t pos = 1, cc = 0; pos < len; pos++, cc++) {
		if (short_form) {
			u8 d;
			if (!hex_digit_decode(value[pos], d))
				return false;

			components[cc] = (d & 0xf) << 4 | (d & 0xf);
		} else {
			u8 d1, d2;
			if (!hex_digit_decode(value[pos], d1) ||
					!hex_digit_decode(value[pos+1], d2))
				return false;

			components[cc] = (d1 & 0xf) << 4 | (d2 & 0xf);
			pos++; // skip the second digit -- it's already used
		}
	}

	color.setRed(components[0]);
	color.setGreen(components[1]);
	color.setBlue(components[2]);
	color.setAlpha(components[3]);

	return true;
}

const static std::unordered_map<std::string, u32> s_named_colors = {
	{"aliceblue",            0xf0f8ff},
	{"antiquewhite",         0xfaebd7},
	{"aqua",                 0x00ffff},
	{"aquamarine",           0x7fffd4},
	{"azure",                0xf0ffff},
	{"beige",                0xf5f5dc},
	{"bisque",               0xffe4c4},
	{"black",                00000000},
	{"blanchedalmond",       0xffebcd},
	{"blue",                 0x0000ff},
	{"blueviolet",           0x8a2be2},
	{"brown",                0xa52a2a},
	{"burlywood",            0xdeb887},
	{"cadetblue",            0x5f9ea0},
	{"chartreuse",           0x7fff00},
	{"chocolate",            0xd2691e},
	{"coral",                0xff7f50},
	{"cornflowerblue",       0x6495ed},
	{"cornsilk",             0xfff8dc},
	{"crimson",              0xdc143c},
	{"cyan",                 0x00ffff},
	{"darkblue",             0x00008b},
	{"darkcyan",             0x008b8b},
	{"darkgoldenrod",        0xb8860b},
	{"darkgray",             0xa9a9a9},
	{"darkgreen",            0x006400},
	{"darkgrey",             0xa9a9a9},
	{"darkkhaki",            0xbdb76b},
	{"darkmagenta",          0x8b008b},
	{"darkolivegreen",       0x556b2f},
	{"darkorange",           0xff8c00},
	{"darkorchid",           0x9932cc},
	{"darkred",              0x8b0000},
	{"darksalmon",           0xe9967a},
	{"darkseagreen",         0x8fbc8f},
	{"darkslateblue",        0x483d8b},
	{"darkslategray",        0x2f4f4f},
	{"darkslategrey",        0x2f4f4f},
	{"darkturquoise",        0x00ced1},
	{"darkviolet",           0x9400d3},
	{"deeppink",             0xff1493},
	{"deepskyblue",          0x00bfff},
	{"dimgray",              0x696969},
	{"dimgrey",              0x696969},
	{"dodgerblue",           0x1e90ff},
	{"firebrick",            0xb22222},
	{"floralwhite",          0xfffaf0},
	{"forestgreen",          0x228b22},
	{"fuchsia",              0xff00ff},
	{"gainsboro",            0xdcdcdc},
	{"ghostwhite",           0xf8f8ff},
	{"gold",                 0xffd700},
	{"goldenrod",            0xdaa520},
	{"gray",                 0x808080},
	{"green",                0x008000},
	{"greenyellow",          0xadff2f},
	{"grey",                 0x808080},
	{"honeydew",             0xf0fff0},
	{"hotpink",              0xff69b4},
	{"indianred",            0xcd5c5c},
	{"indigo",               0x4b0082},
	{"ivory",                0xfffff0},
	{"khaki",                0xf0e68c},
	{"lavender",             0xe6e6fa},
	{"lavenderblush",        0xfff0f5},
	{"lawngreen",            0x7cfc00},
	{"lemonchiffon",         0xfffacd},
	{"lightblue",            0xadd8e6},
	{"lightcoral",           0xf08080},
	{"lightcyan",            0xe0ffff},
	{"lightgoldenrodyellow", 0xfafad2},
	{"lightgray",            0xd3d3d3},
	{"lightgreen",           0x90ee90},
	{"lightgrey",            0xd3d3d3},
	{"lightpink",            0xffb6c1},
	{"lightsalmon",          0xffa07a},
	{"lightseagreen",        0x20b2aa},
	{"lightskyblue",         0x87cefa},
	{"lightslategray",       0x778899},
	{"lightslategrey",       0x778899},
	{"lightsteelblue",       0xb0c4de},
	{"lightyellow",          0xffffe0},
	{"lime",                 0x00ff00},
	{"limegreen",            0x32cd32},
	{"linen",                0xfaf0e6},
	{"magenta",              0xff00ff},
	{"maroon",               0x800000},
	{"mediumaquamarine",     0x66cdaa},
	{"mediumblue",           0x0000cd},
	{"mediumorchid",         0xba55d3},
	{"mediumpurple",         0x9370db},
	{"mediumseagreen",       0x3cb371},
	{"mediumslateblue",      0x7b68ee},
	{"mediumspringgreen",    0x00fa9a},
	{"mediumturquoise",      0x48d1cc},
	{"mediumvioletred",      0xc71585},
	{"midnightblue",         0x191970},
	{"mintcream",            0xf5fffa},
	{"mistyrose",            0xffe4e1},
	{"moccasin",             0xffe4b5},
	{"navajowhite",          0xffdead},
	{"navy",                 0x000080},
	{"oldlace",              0xfdf5e6},
	{"olive",                0x808000},
	{"olivedrab",            0x6b8e23},
	{"orange",               0xffa500},
	{"orangered",            0xff4500},
	{"orchid",               0xda70d6},
	{"palegoldenrod",        0xeee8aa},
	{"palegreen",            0x98fb98},
	{"paleturquoise",        0xafeeee},
	{"palevioletred",        0xdb7093},
	{"papayawhip",           0xffefd5},
	{"peachpuff",            0xffdab9},
	{"peru",                 0xcd853f},
	{"pink",                 0xffc0cb},
	{"plum",                 0xdda0dd},
	{"powderblue",           0xb0e0e6},
	{"purple",               0x800080},
	{"red",                  0xff0000},
	{"rosybrown",            0xbc8f8f},
	{"royalblue",            0x4169e1},
	{"saddlebrown",          0x8b4513},
	{"salmon",               0xfa8072},
	{"sandybrown",           0xf4a460},
	{"seagreen",             0x2e8b57},
	{"seashell",             0xfff5ee},
	{"sienna",               0xa0522d},
	{"silver",               0xc0c0c0},
	{"skyblue",              0x87ceeb},
	{"slateblue",            0x6a5acd},
	{"slategray",            0x708090},
	{"slategrey",            0x708090},
	{"snow",                 0xfffafa},
	{"springgreen",          0x00ff7f},
	{"steelblue",            0x4682b4},
	{"tan",                  0xd2b48c},
	{"teal",                 0x008080},
	{"thistle",              0xd8bfd8},
	{"tomato",               0xff6347},
	{"turquoise",            0x40e0d0},
	{"violet",               0xee82ee},
	{"wheat",                0xf5deb3},
	{"white",                0xffffff},
	{"whitesmoke",           0xf5f5f5},
	{"yellow",               0xffff00},
	{"yellowgreen",          0x9acd32}
};

static bool parseNamedColorString(const std::string &value, video::SColor &color)
{
	std::string color_name;
	std::string alpha_string;

	/* If the string has a # in it, assume this is the start of a specified
	 * alpha value (if it isn't the string is invalid and the error will be
	 * caught later on, either because the color name won't be found or the
	 * alpha value will fail conversion)
	 */
	size_t alpha_pos = value.find('#');
	if (alpha_pos != std::string::npos) {
		color_name = value.substr(0, alpha_pos);
		alpha_string = value.substr(alpha_pos + 1);
	} else {
		color_name = value;
	}

	color_name = lowercase(color_name);

	auto it = s_named_colors.find(color_name);
	if (it == s_named_colors.end())
		return false;

	u32 color_temp = it->second;

	/* An empty string for alpha is ok (none of the color table entries
	 * have an alpha value either). Color strings without an alpha specified
	 * are interpreted as fully opaque
	 */
	if (!alpha_string.empty()) {
		if (alpha_string.size() == 1) {
			u8 d;
			if (!hex_digit_decode(alpha_string[0], d))
				return false;

			color_temp |= ((d & 0xf) << 4 | (d & 0xf)) << 24;
		} else if (alpha_string.size() == 2) {
			u8 d1, d2;
			if (!hex_digit_decode(alpha_string[0], d1)
					|| !hex_digit_decode(alpha_string[1], d2))
				return false;

			color_temp |= ((d1 & 0xf) << 4 | (d2 & 0xf)) << 24;
		} else {
			return false;
		}
	} else {
		color_temp |= 0xff << 24; // Fully opaque
	}

	color = video::SColor(color_temp);

	return true;
}

bool parseColorString(const std::string &value, video::SColor &color, bool quiet,
		unsigned char default_alpha)
{
	bool success;

	if (value[0] == '#')
		success = parseHexColorString(value, color, default_alpha);
	else
		success = parseNamedColorString(value, color);

	if (!success && !quiet)
		errorstream << "Invalid color: \"" << value << "\"" << std::endl;

	return success;
}

void str_replace(std::string &str, char from, char to)
{
	std::replace(str.begin(), str.end(), from, to);
}

/* Translated strings have the following format:
 * \x1bT marks the beginning of a translated string
 * \x1bE marks its end
 *
 * \x1bF marks the beginning of an argument, and \x1bE its end.
 *
 * Arguments are *not* translated, as they may contain escape codes.
 * Thus, if you want a translated argument, it should be inside \x1bT/\x1bE tags as well.
 *
 * This representation is chosen so that clients ignoring escape codes will
 * see untranslated strings.
 *
 * For instance, suppose we have a string such as "@1 Wool" with the argument "White"
 * The string will be sent as "\x1bT\x1bF\x1bTWhite\x1bE\x1bE Wool\x1bE"
 * To translate this string, we extract what is inside \x1bT/\x1bE tags.
 * When we notice the \x1bF tag, we recursively extract what is there up to the \x1bE end tag,
 * translating it as well.
 * We get the argument "White", translated, and create a template string with "@1" instead of it.
 * We finally get the template "@1 Wool" that was used in the beginning, which we translate
 * before filling it again.
 */

void translate_all(const std::wstring &s, size_t &i,
		Translations *translations, std::wstring &res);

void translate_string(const std::wstring &s, Translations *translations,
		const std::wstring &textdomain, size_t &i, std::wstring &res)
{
	std::wostringstream output;
	std::vector<std::wstring> args;
	int arg_number = 1;
	while (i < s.length()) {
		// Not an escape sequence: just add the character.
		if (s[i] != '\x1b') {
			output.put(s[i]);
			// The character is a literal '@'; add it twice
			// so that it is not mistaken for an argument.
			if (s[i] == L'@')
				output.put(L'@');
			++i;
			continue;
		}

		// We have an escape sequence: locate it and its data
		// It is either a single character, or it begins with '('
		// and extends up to the following ')', with '\' as an escape character.
		++i;
		size_t start_index = i;
		size_t length;
		if (i == s.length()) {
			length = 0;
		} else if (s[i] == L'(') {
			++i;
			++start_index;
			while (i < s.length() && s[i] != L')') {
				if (s[i] == L'\\')
					++i;
				++i;
			}
			length = i - start_index;
			++i;
			if (i > s.length())
				i = s.length();
		} else {
			++i;
			length = 1;
		}
		std::wstring escape_sequence(s, start_index, length);

		// The escape sequence is now reconstructed.
		std::vector<std::wstring> parts = split(escape_sequence, L'@');
		if (parts[0] == L"E") {
			// "End of translation" escape sequence. We are done locating the string to translate.
			break;
		} else if (parts[0] == L"F") {
			// "Start of argument" escape sequence.
			// Recursively translate the argument, and add it to the argument list.
			// Add an "@n" instead of the argument to the template to translate.
			if (arg_number >= 10) {
				errorstream << "Ignoring too many arguments to translation" << std::endl;
				std::wstring arg;
				translate_all(s, i, translations, arg);
				args.push_back(arg);
				continue;
			}
			output.put(L'@');
			output << arg_number;
			++arg_number;
			std::wstring arg;
			translate_all(s, i, translations, arg);
			args.push_back(arg);
		} else {
			// This is an escape sequence *inside* the template string to translate itself.
			// This should not happen, show an error message.
			errorstream << "Ignoring escape sequence '"
				<< wide_to_utf8(escape_sequence) << "' in translation" << std::endl;
		}
	}

	std::wstring toutput;
	// Translate the template.
	if (translations != nullptr)
		toutput = translations->getTranslation(
				textdomain, output.str());
	else
		toutput = output.str();

	// Put back the arguments in the translated template.
	std::wostringstream result;
	size_t j = 0;
	while (j < toutput.length()) {
		// Normal character, add it to output and continue.
		if (toutput[j] != L'@' || j == toutput.length() - 1) {
			result.put(toutput[j]);
			++j;
			continue;
		}

		++j;
		// Literal escape for '@'.
		if (toutput[j] == L'@') {
			result.put(L'@');
			++j;
			continue;
		}

		// Here we have an argument; get its index and add the translated argument to the output.
		int arg_index = toutput[j] - L'1';
		++j;
		if (0 <= arg_index && (size_t)arg_index < args.size()) {
			result << args[arg_index];
		} else {
			// This is not allowed: show an error message
			errorstream << "Ignoring out-of-bounds argument escape sequence in translation" << std::endl;
		}
	}
	res = result.str();
}

void translate_all(const std::wstring &s, size_t &i,
		Translations *translations, std::wstring &res)
{
	std::wostringstream output;
	while (i < s.length()) {
		// Not an escape sequence: just add the character.
		if (s[i] != '\x1b') {
			output.put(s[i]);
			++i;
			continue;
		}

		// We have an escape sequence: locate it and its data
		// It is either a single character, or it begins with '('
		// and extends up to the following ')', with '\' as an escape character.
		size_t escape_start = i;
		++i;
		size_t start_index = i;
		size_t length;
		if (i == s.length()) {
			length = 0;
		} else if (s[i] == L'(') {
			++i;
			++start_index;
			while (i < s.length() && s[i] != L')') {
				if (s[i] == L'\\') {
					++i;
				}
				++i;
			}
			length = i - start_index;
			++i;
			if (i > s.length())
				i = s.length();
		} else {
			++i;
			length = 1;
		}
		std::wstring escape_sequence(s, start_index, length);

		// The escape sequence is now reconstructed.
		std::vector<std::wstring> parts = split(escape_sequence, L'@');
		if (parts[0] == L"E") {
			// "End of argument" escape sequence. Exit.
			break;
		} else if (parts[0] == L"T") {
			// Beginning of translated string.
			std::wstring textdomain;
			if (parts.size() > 1)
				textdomain = parts[1];
			std::wstring translated;
			translate_string(s, translations, textdomain, i, translated);
			output << translated;
		} else {
			// Another escape sequence, such as colors. Preserve it.
			output << std::wstring(s, escape_start, i - escape_start);
		}
	}

	res = output.str();
}

// Translate string server side
std::wstring translate_string(const std::wstring &s, Translations *translations)
{
	size_t i = 0;
	std::wstring res;
	translate_all(s, i, translations, res);
	return res;
}

// Translate string client side
std::wstring translate_string(const std::wstring &s)
{
#ifdef SERVER
	return translate_string(s, nullptr);
#else
	return translate_string(s, g_client_translations);
#endif
}

static const std::array<std::wstring, 22> disallowed_dir_names = {
	// Problematic filenames from here:
	// https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#file-and-directory-names
	L"CON",
	L"PRN",
	L"AUX",
	L"NUL",
	L"COM1",
	L"COM2",
	L"COM3",
	L"COM4",
	L"COM5",
	L"COM6",
	L"COM7",
	L"COM8",
	L"COM9",
	L"LPT1",
	L"LPT2",
	L"LPT3",
	L"LPT4",
	L"LPT5",
	L"LPT6",
	L"LPT7",
	L"LPT8",
	L"LPT9",
};

/**
 * List of characters that are blacklisted from created directories
 */
static const std::wstring disallowed_path_chars = L"<>:\"/\\|?*.";

/**
 * Sanitize the name of a new directory. This consists of two stages:
 * 1. Check for 'reserved filenames' that can't be used on some filesystems
 *	and add a prefix to them
 * 2. Remove 'unsafe' characters from the name by replacing them with '_'
 */
std::string sanitizeDirName(const std::string &str, const std::string &optional_prefix)
{
	std::wstring safe_name = utf8_to_wide(str);

	for (std::wstring disallowed_name : disallowed_dir_names) {
		if (str_equal(safe_name, disallowed_name, true)) {
			safe_name = utf8_to_wide(optional_prefix) + safe_name;
			break;
		}
	}

	for (unsigned long i = 0; i < safe_name.length(); i++) {
		bool is_valid = true;

		// Unlikely, but control characters should always be blacklisted
		if (safe_name[i] < 32) {
			is_valid = false;
		} else if (safe_name[i] < 128) {
			is_valid = disallowed_path_chars.find_first_of(safe_name[i])
					== std::wstring::npos;
		}

		if (!is_valid)
			safe_name[i] = '_';
	}

	return wide_to_utf8(safe_name);
}


void safe_print_string(std::ostream &os, const std::string &str)
{
	std::ostream::fmtflags flags = os.flags();
	os << std::hex;
	for (const char c : str) {
		if (IS_ASCII_PRINTABLE_CHAR(c) || IS_UTF8_MULTB_START(c) ||
				IS_UTF8_MULTB_INNER(c) || c == '\n' || c == '\t') {
			os << c;
		} else {
			os << '<' << std::setw(2) << (int)c << '>';
		}
	}
	os.setf(flags);
}