-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutil.nut
More file actions
536 lines (449 loc) · 12.3 KB
/
Copy pathutil.nut
File metadata and controls
536 lines (449 loc) · 12.3 KB
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
function Debug(...) {
local s = "";
for(local i = 0; i< vargc; i++) {
s = s + " " + vargv[i];
}
AILog.Info(GetDate() + ":" + s);
}
function Warning(...) {
local s = "";
for(local i = 0; i< vargc; i++) {
s = s + " " + vargv[i];
}
AILog.Warning(GetDate() + ":" + s);
}
function Error(...) {
local s = "";
for(local i = 0; i< vargc; i++) {
s = s + " " + vargv[i];
}
AILog.Error(GetDate() + ":" + s);
}
/**
* Print a stack trace.
*
* Unfortunately, getstackinfos() does not appear to be available
*/
// function PrintStack() {
// local i = 2; // 0 is getstackinfos, 1 is PrintStack()
// while (true) {
// local stack = getstackinfos(i);
// if (stack == null) break;
// AILog.Error("*FUNCTION [" + stack.func + "()] " + stack.src + " [" + stack.line + "]");
// foreach(idx, val in stack.locals) {
// AILog.Error("[" + idx + "] " + val);
// }
// i = i + 1;
// }
// }
function GetDate() {
local date = AIDate.GetCurrentDate();
return "" + AIDate.GetYear(date) + "-" + ZeroPad(AIDate.GetMonth(date)) + "-" + ZeroPad(AIDate.GetDayOfMonth(date));
}
function PrintError() {
Error(AIError.GetLastErrorString());
}
function Sign(x) {
if (x < 0) return -1;
if (x > 0) return 1;
return 0;
}
/**
* Calculates an integer square root.
*/
function Sqrt(i) {
if (i == 0)
return 0; // Avoid divide by zero
local n = (i / 2) + 1; // Initial estimate, never low
local n1 = (n + (i / n)) / 2;
while (n1 < n) {
n = n1;
n1 = (n + (i / n)) / 2;
}
return n;
}
function Min(a, b) {
return a < b ? a : b;
}
function Range(from, to) {
local range = [];
for (local i=from; i<to; i++) {
range.append(i);
}
return range;
}
/**
* Return the closest integer equal to or greater than x.
*/
function Ceiling(x) {
if (x.tointeger().tofloat() == x) return x.tointeger();
return x.tointeger() + 1;
}
function RandomTile() {
return abs(RANDOM.Rand()) % AIMap.GetMapSize();
}
/**
* Sum up the values of an AIList.
*/
function Sum(list) {
local sum = 0;
for (local item = list.Begin(); list.HasNext(); item = list.Next()) {
sum += list.GetValue(item);
}
return sum;
}
/**
* Shuffle the items in an array.
*/
function Shuffle(a) {
local n = a.len();
for (local i = 0; i < n; i++) {
local j = AIBase.RandRange(n);
local temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
/**
* Create a string of all elements of an array, separated by a comma.
*/
function ArrayToString(a) {
if (a == null) return "";
local s = "";
foreach (index, item in a) {
if (index > 0) s += ", ";
s += item;
}
return s;
}
/**
* Turn a tile index into an "x, y" string.
*/
function TileToString(tile) {
return "(" + AIMap.GetTileX(tile) + ", " + AIMap.GetTileY(tile) + ")";
}
/**
* Concatenate the same string, n times.
*/
function StringN(s, n) {
local r = "";
for (local i=0; i<n; i++) {
r += s;
}
return r;
}
function Join(...) {
local s = "";
for(local i = 0; i< vargc; i++) {
s = s + " " + vargv[i];
}
return s;
}
function ZeroPad(i) {
return i < 10 ? "0" + i : "" + i;
}
function StartsWith(a, b) {
return a.find(b) == 0;
}
function EndsWith(a, b) {
return a.find(b) == a.len() - b.len();
}
/**
* Swap two tiles - used for swapping entrance/exit tile strips.
*/
function Swap(tiles) {
return [tiles[1], tiles[0]];
}
/**
* Create an array from an AIList.
*/
function ListToArray(l) {
local a = [];
for (local item = l.Begin(); l.HasNext(); item = l.Next()) a.append(item);
return a;
}
/**
* Create an AIList from an array.
*/
function ArrayToList(a) {
local l = AIList();
foreach (item in a) l.AddItem(item, 0);
return l;
}
function ArrayContains(a, item) {
foreach (item in a) {
if (item == item) return true;
}
return false;
}
/**
* Return an array that contains all elements of a and b.
*/
function Concat(a, b) {
local r = [];
r.extend(a);
r.extend(b);
return r;
}
/**
* Add a rectangular area to an AITileList containing tiles that are within /radius/
* tiles from the center tile, taking the edges of the map into account.
*/
function SafeAddRectangle(list, tile, radius) {
local x1 = max(1, AIMap.GetTileX(tile) - radius);
local y1 = max(1, AIMap.GetTileY(tile) - radius);
local x2 = min(AIMap.GetMapSizeX() - 2, AIMap.GetTileX(tile) + radius);
local y2 = min(AIMap.GetMapSizeY() - 2, AIMap.GetTileY(tile) + radius);
list.AddRectangle(AIMap.GetTileIndex(x1, y1),AIMap.GetTileIndex(x2, y2));
}
/**
* Filter an AITileList for AITile.IsBuildable tiles.
*/
function KeepBuildableArea(area) {
area.Valuate(AITile.IsBuildable);
area.KeepValue(1);
return area;
}
function InverseDirection(direction) {
switch (direction) {
case Direction.N: return Direction.S;
case Direction.E: return Direction.W;
case Direction.S: return Direction.N;
case Direction.W: return Direction.E;
case Direction.NE: return Direction.SW;
case Direction.SE: return Direction.NW;
case Direction.SW: return Direction.NE;
case Direction.NW: return Direction.SE;
default: throw "invalid direction";
}
}
function DirectionName(direction) {
switch (direction) {
case Direction.N: return "N";
case Direction.E: return "E";
case Direction.S: return "S";
case Direction.W: return "W";
case Direction.NE: return "NE";
case Direction.SE: return "SE";
case Direction.SW: return "SW";
case Direction.NW: return "NW";
default: throw "invalid direction";
}
}
/**
* Find the cargo ID for passengers.
* Otto: newgrf can have tourist (TOUR) which qualify as passengers but townfolk won't enter the touristbus...
* hence this rewrite; you can check for PASS as string, but this is discouraged on the wiki
*/
function GetPassengerCargoID() {
return GetCargoID(AICargo.CC_PASSENGERS);
}
function GetMailCargoID() {
return GetCargoID(AICargo.CC_MAIL);
}
function GetCargoID(cargoClass) {
local list = AICargoList();
for (local i = list.Begin(); list.HasNext(); i = list.Next()) {
if (AICargo.HasCargoClass(i, cargoClass)) {
return i;
}
}
return null;
}
function IsRightHandTraffic() {
local roadVehicleSide = AIGameSettings.GetValue("vehicle.road_side");
switch (AIController.GetSetting("TrainTrafficSide")) {
case 1: return false;
case 2: return true;
default: return roadVehicleSide == 1;
}
}
function GetMaxBridgeLength() {
local length = AIController.GetSetting("MaxBridgeLength");
while (length > 0 && AIBridgeList_Length(length).IsEmpty()) {
length--;
}
return length;
}
function GetMaxBridgeCost(length) {
local bridges = AIBridgeList_Length(length);
if (bridges.IsEmpty()) throw "Cannot build " + length + " tile bridges!";
bridges.Valuate(AIBridge.GetMaxSpeed);
bridges.KeepTop(1);
local bridge = bridges.Begin();
return AIBridge.GetPrice(bridge, length);
}
function TrainLength(train) {
// train length in tiles
return (AIVehicle.GetLength(train) + 15) / 16;
}
function HaveHQ() {
return AICompany.GetCompanyHQ(COMPANY) != AIMap.TILE_INVALID;
}
function GetRailType(cargo, cheap, bannedCargo, bannedEngines) {
// select a rail type for which we can build a locomotive that can pull wagons for the desired cargo
local railTypes = AIRailTypeList();
railTypes.Valuate(HasEngine, cargo, bannedEngines);
railTypes.KeepValue(1);
railTypes.Valuate(AIRail.GetBuildCost, AIRail.BT_TRACK);
railTypes.KeepAboveValue(0); // filter out NuTracks planning tracks, which are free
if (cheap) {
railTypes.KeepBottom(1); // we use the cheap stuff for cargo
} else {
railTypes.KeepTop(1); // use the fastest one for passengers
}
if (railTypes.IsEmpty()) {
bannedCargo.append(cargo);
throw TaskFailedException("no rail type for " + AICargo.GetCargoLabel(cargo));
} else {
return railTypes.Begin();
}
}
function HasEngine(railType, cargo, bannedEngines) {
// check if we have an engine that can pull the desired cargo on this rail type
try {
GetEngine(cargo, railType, bannedEngines, false)
return true;
} catch (e) {
return false;
}
}
function GetEngine(cargo, railType, bannedEngines, cheap) {
local engineList = AIEngineList(AIVehicle.VT_RAIL);
engineList.Valuate(AIEngine.IsWagon);
engineList.KeepValue(0);
engineList.Valuate(AIEngine.CanRunOnRail, railType);
engineList.KeepValue(1);
engineList.Valuate(AIEngine.HasPowerOnRail, railType);
engineList.KeepValue(1);
engineList.Valuate(AIEngine.CanPullCargo, cargo);
engineList.KeepValue(1);
engineList.RemoveList(ArrayToList(bannedEngines));
engineList.Valuate(AIEngine.GetPrice);
if (cheap) {
// go for the cheapest
engineList.KeepBottom(1);
} else {
// pick something middle of the range, by removing the top half
// this will hopefully give us something decent, even when faced with newgrf train sets
engineList.Sort(AIList.SORT_BY_VALUE, true);
engineList.RemoveTop(engineList.Count() / 2);
}
if (engineList.IsEmpty()) throw TaskFailedException("no suitable engine for " + AICargo.GetCargoLabel(cargo) + " on " + AIRail.GetName(railType));
return engineList.Begin();
}
function GetWagon(cargo, railType) {
// select the largest appropriate wagon type
local engineList = AIEngineList(AIVehicle.VT_RAIL);
engineList.Valuate(AIEngine.CanRefitCargo, cargo);
engineList.KeepValue(1);
engineList.Valuate(AIEngine.IsWagon);
engineList.KeepValue(1);
engineList.Valuate(AIEngine.CanRunOnRail, railType);
engineList.KeepValue(1);
// prefer engines that can carry this cargo without a refit,
// because their refitted capacity may be different from
// their "native" capacity - for example, NARS Ore Hoppers
local native = AIList();
native.AddList(engineList);
native.Valuate(AIEngine.GetCargoType);
native.KeepValue(cargo);
if (!native.IsEmpty()) {
engineList = native;
}
engineList.Valuate(AIEngine.GetCapacity)
engineList.KeepTop(1);
if (engineList.IsEmpty()) throw TaskFailedException("no suitable wagon");
return engineList.Begin();
}
function MaxDistance(cargo, trainLength) {
// maximum safe rail distance we can expect to build with our starting loan
local rail = AIRail.GetCurrentRailType();
local engine = GetEngine(cargo, rail, [], true);
local wagon = GetWagon(cargo, rail);
local trainCost = AIEngine.GetPrice(engine) + AIEngine.GetPrice(wagon) * (trainLength-1) * 2;
local bridgeCost = GetMaxBridgeCost(GetMaxBridgeLength());
local tileCost = AIRail.GetBuildCost(rail, AIRail.BT_TRACK);
return (AICompany.GetMaxLoanAmount() - trainCost - bridgeCost) / tileCost;
}
function GetGameSetting(setting, defaultValue) {
if (!AIGameSettings.IsValid(setting)) {
Warning("Invalid game setting:", setting);
Warning("Using default value", defaultValue);
return defaultValue;
}
return AIGameSettings.GetValue(setting);
}
class Counter {
count = 0;
constructor() {
count = 0;
}
function Get() {
return count;
}
function Inc() {
count++;
}
}
/**
* A boolean flag, usable as a static field.
*/
class Flag {
value = null;
constructor() {
value = false;
}
function Set(value) {
this.value = value;
}
function Get() {
return value;
}
}
class Random {
seed = 0;
constructor(seed) {
this.seed = seed;
}
function Rand() {
// linear congruential generator
seed = (1103515245 * seed + 12345) % 0x80000000;
return seed;
}
function RandItem(unused) {
return this.Rand();
}
}
function GenerateCircle(centerTile, radius)
{
local tiles = [];
local cx = AIMap.GetTileX(centerTile);
local cy = AIMap.GetTileY(centerTile);
local dx = 0;
local dy = radius;
local d = 1 - radius;
while (dx <= dy)
{
// 8-way symmetry
tiles.append(AIMap.GetTileIndex(cx + dx, cy + dy));
tiles.append(AIMap.GetTileIndex(cx - dx, cy + dy));
tiles.append(AIMap.GetTileIndex(cx + dx, cy - dy));
tiles.append(AIMap.GetTileIndex(cx - dx, cy - dy));
tiles.append(AIMap.GetTileIndex(cx + dy, cy + dx));
tiles.append(AIMap.GetTileIndex(cx - dy, cy + dx));
tiles.append(AIMap.GetTileIndex(cx + dy, cy - dx));
tiles.append(AIMap.GetTileIndex(cx - dy, cy - dx));
dx = dx + 1;
if (d < 0)
{
d = d + 2 * dx + 1;
}
else
{
dy = dy - 1;
d = d + 2 * (dx - dy) + 1;
}
}
return tiles;
}