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
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945

#include "gfCParkLevelComponent.h"

#include <algorithm>
#include <cmath>
#include <numeric>
#include <utility>
#include <vector>

#include <fsCore/src/fsCUniqueId.h>
#include <fsCore/src/fsCResourceName.h>
#include <fsCore/src/fsCAppSettings.h>

#include <fsAppCore/fsIDisplay.h>
#include <fsAppCore/fsIInputManager.h>
#include <fsAppCore/src/fsCAppCoreMain.h>
#include <fsAppCore/src/fsCEntity.h>
#include <fsAppCore/src/fsCEntityFactory.h>
#include <fsAppCore/src/fsCProfileManager.h>
#include <fsAppCore/src/fsILevelBasedAppCoreMain.h>
#include <fsAppCore/src/components/gui/fsIGuiComponent.h>

#include <fsCore/src/fsCVariableTable.h>
#include <fsCore/fsSColour.h>
#include <fsCore/fsIFile.h>
#include <fsCore/src/debug/fsLog.h>

#include <fsRenderer/src/fsCBrushManager.h>
#include <fsRenderer/src/components/fsCSpriteComponent.h>

#include <fsTileMap/fsITileMap.h>
#include <fsTileMap/fsITile.h>
#include <fsTileMap/fsIObject.h>
#include <fsTileMap/fsILayer.h>
#include <fsTileMap/src/fsCView.h>
#include <fsTileMap/src/fsCBoundryScroller.h>

#include <gfCatalogue/src/gfCCatalogueParserYaml.h>
#include <gfCatalogue/src/gfCCatalogueCatalogue.h>
#include <gfCatalogue/src/gfCCatalogueItem.h>

#include "gfCParkGuestViewComponent.h"
#include "gfCParkStaffViewComponent.h"
#include "gfCParkOfficeTapComponent.h"
#include "gfCParkSlotStaffComponent.h"
#include "gfCParkLensComponent.h"
#include "gfCParkLayoutManager.h"
#include "gfCPurchaseActionSlotFill.h"
#include "gfCTimeUserSavedData.h"
#include "sim/gfCParkDaySim.h"

const fsCUniqueId gfCParkLevelComponent::mTypeId("gfCParkLevelComponent");

// Placeholder day-loop values, tuned by feel.
const fsS32 gfCParkLevelComponent::mDayDurationMs = 5 * 60 * 1000;

namespace
{
std::vector<fsStr> guestNeedsParse(fsStr pNeeds)
{
	std::vector<fsStr> needs;
	while (!pNeeds.emptyGet())
	{
		fsStr need = pNeeds.chomp(",");
		need.leadingWhitespaceTrim();
		need.trailingWhitespaceTrim();
		if (!need.emptyGet())
		{
			needs.push_back(need);
		}
	}
	return needs;
}

// One visitor every 2.5s. The fixed scenery gate admits up to 60 per day;
// asset-defined entrance buildings can raise that quota.
const fsS32 gSpawnIntervalMs = 2500;
const fsS32 gBaseVisitorQuota = 60;

// Natural scenery and free walking access draw a small audience before the
// player builds anything. Buildings and decorations add authored appeal.
const fsS32 gBaseVisitorDemand = 30;

// A walk is inherently worthwhile; suitable park furniture can lift its visit
// quality by up to 20 points without replacing optional services.
const fsS32 gBaseWalkingSatisfaction = 60;
const fsS32 gMaxDecorationComfortBonus = 20;

// How far a decoration's comfort reaches for walkingSatisfactionNearGet - a
// bench helps the guests near it, not the whole park. Tuned loosely against
// gServiceBuildingDefaultWidth (128px): a couple of building-widths.
const fsF32 gComfortRadiusPx = 220.0f;

// Each extra decoration sharing the same catalogue art counts for less -
// otherwise spamming one cheap decoration beats placing a variety of them.
// 1st copy: 100%, 2nd: 50%, 3rd: 25%, ... (halved per repeat, floored).
const fsS32 gDecorationDuplicateDecayPercent = 50;

// weightPercent for the (pCopyIndex+1)-th decoration of one catalogue art
// (pCopyIndex is 0 for the first). Shared by both appeal (park-wide) and
// comfort (nearby-only) aggregation - "duplicate" means same art, in
// whichever scope is being summed.
fsS32 decorationDuplicateWeightPercentGet(fsS32 pCopyIndex)
{
	fsS32 weightPercent = 100;
	for (fsS32 i = 0; i < pCopyIndex; ++i)
	{
		weightPercent = weightPercent * gDecorationDuplicateDecayPercent / 100;
	}
	return weightPercent;
}

// Sums pValueGet(item) across pItems with decorationDuplicateWeightPercentGet
// applied per repeat of pImageGet(item) - used for both appeal and comfort.
template <typename T, typename ImageGetter, typename ValueGetter>
fsS32 decorationDiminishingSumGet(const std::vector<T>& pItems, ImageGetter pImageGet, ValueGetter pValueGet)
{
	std::vector<std::pair<fsStr, fsS32>> copiesSeen; // image -> copies counted so far
	fsS32 total = 0;
	for (const T& item : pItems)
	{
		fsS32 copyIndex = 0;
		fsBool found = false;
		for (auto& seen : copiesSeen)
		{
			if (seen.first == pImageGet(item))
			{<--- Consider using std::find_if algorithm instead of a raw loop.
				copyIndex = seen.second++;
				found = true;
				break;
			}
		}
		if (!found)
		{
			copiesSeen.push_back(std::make_pair(pImageGet(item), 1));
		}
		total += pValueGet(item) * decorationDuplicateWeightPercentGet(copyIndex) / 100;
	}
	return total;
}

// Reputation provides a deliberately modest return-visitor effect: every five
// points above/below neutral changes demand by one, capped naturally by 0-100.
fsS32 reputationDemandModifier(fsS32 pReputation)
{
	if (pReputation >= 50)
	{
		return (pReputation - 50) / 5;
	}
	return -((50 - pReputation) / 5);
}

// Per-day coin goal (placeholder ramp).
const fsS32 gCoinGoalByDay[gfCParkLevelComponent::mNumDays] = {100, 150, 200, 250, 300};

// TEMPORARY testing float - far more than content costs so nothing is gated.
// Can't be 0: staffing costs coins and coins only come from serving, so an
// empty purse deadlocks the park. Drop to ~one staff hire once proven.
const fsS32 gStartingCoins = 20000;

// Walk time from gate to slot (patience doesn't run while walking).
const fsS32 gGuestTravelMs = 4000;

// A building breaks after this many services or this long staffed-open,
// whichever first (age-wear only accrues while staffed - see
// gfCSlotSim::tick - so an idle, unstaffed building no longer wears at all).
// Raised from 8/120000 - breaking was too frequent even for a busy building.
const fsS32 gServicesBeforeBreak = 20;
const fsS32 gOpenMsBeforeBreak = 300000;
const fsS32 gRepairTimeMs = 8000;

// How often, during play, progress is flushed to disk (see progressPersist).
const fsS32 gAutosaveIntervalMs = 5000;

// Map furniture: fixed scenery with no catalogue entry, art living with the
// scene. Office is a landmark, gate is a wide low fence.
const fsStr gStaffDepotObjectName("staffDepot");
const fsStr gStaffDepotImage("parkscenes/pinecreekhillspark/staffDepot.png");
const fsF32 gStaffDepotDrawScale = 2.5f;

const fsStr gParkGateObjectName("parkGate");
const fsStr gParkGateImage("parkscenes/pinecreekhillspark/parkGate.png");
const fsF32 gParkGateDrawScale = 1.6f;

// Translucent per-type tints for the greybox slot markers.
fsSColour4B slotTypeColour(const fsStr& pType)
{
	if (pType == "tickets") return fsSColour4B(235, 205, 70, 140);
	if (pType == "food")    return fsSColour4B(235, 140, 55, 140);
	if (pType == "rides")   return fsSColour4B(70, 185, 225, 150);
	if (pType == "staff")   return fsSColour4B(205, 95, 205, 140);
	return fsSColour4B(210, 210, 210, 140);
}

// Per-index saved-data keys for the ownership collections (the flat saved-data
// table has no list type). Built in one place so save and restore can't drift.
fsStr ownedSlotKey(fsS32 pIndex, const char* pField)
{
	return fsStr("parkOwnedSlot") + fsStr(pIndex) + pField;
}
fsStr hiredStaffKey(fsS32 pIndex, const char* pField)
{
	return fsStr("parkHiredStaff") + fsStr(pIndex) + pField;
}
fsStr deployedSlotKey(fsS32 pIndex)
{
	return fsStr("parkDeployedSlot") + fsStr(pIndex);
}
fsStr decorationKey(fsS32 pIndex, const char* pField)
{
	return fsStr("parkDecoration") + fsStr(pIndex) + pField;
}
fsStr clearedCellKey(fsS32 pIndex, const char* pField)
{
	return fsStr("parkClearedCell") + fsStr(pIndex) + pField;
}

// Placeholder size for a decoration with no art yet (the same green as the
// guest-view stand-in, so a missing PNG reads as "placed" rather than invisible).
const fsS32 gDecorationPlaceholderSize = 40;

// Used when an older/hand-authored catalogue omits placementwidth.
const fsS32 gServiceBuildingDefaultWidth = 64;

struct SGridRect
{
	fsS32 mLeft;
	fsS32 mTop;
	fsS32 mRight;
	fsS32 mBottom;
};

fsBool gridRectsOverlap(const SGridRect& pLhs, const SGridRect& pRhs)
{
	return pLhs.mLeft < pRhs.mRight && pLhs.mRight > pRhs.mLeft &&
	       pLhs.mTop < pRhs.mBottom && pLhs.mBottom > pRhs.mTop;
}

SGridRect gridRectFromAnchor(fsNTileMap::fsCView* const pView,
	fsS32 pLocalX, fsS32 pLocalY, fsS32 pColumns, fsS32 pRows)
{
	const fsPoint mapTopLeft = pView->mapPixelToLocal(fsPoint(0, 0));
	const fsPoint firstTileBottomRight = pView->mapPixelToLocal(
		fsPoint(pView->mMap->tileWidthGet(), pView->mMap->tileHeightGet()));
	const fsF32 tileLocalWidth = static_cast<fsF32>(firstTileBottomRight.x - mapTopLeft.x);
	const fsF32 tileLocalHeight = static_cast<fsF32>(firstTileBottomRight.y - mapTopLeft.y);

	SGridRect rect;
	rect.mLeft = static_cast<fsS32>(std::floor(
		(pLocalX - mapTopLeft.x) / tileLocalWidth - pColumns * 0.5f + 0.5f));
	rect.mTop = static_cast<fsS32>(std::floor(
		(pLocalY - mapTopLeft.y) / tileLocalHeight - pRows + 0.5f));
	rect.mRight = rect.mLeft + pColumns;
	rect.mBottom = rect.mTop + pRows;
	return rect;
}
}

void gfCParkLevelComponent::levelCreate(const fsStr& pLevelName, fsBool pResume)
{
	// Not gfCTileMapLevelLoaderComponent: that spawns a walker-avatar and
	// coords.txt pipeline (torsion machinery) a tap park doesn't want. Just the
	// fsCView the loader would build, minus the baggage.
	const fsCVariableTable* const levelSettings = fsILevelBasedAppCoreMain::instanceGet()->levelSettingsGet();
	auto* const map = fsNTileMap::fsITileMap::create(fsCResourceName(levelSettings->strGet("mapFile"),
	                                                                 fsCResourceName::eRES_LOCATION_ASSETS));

	const fsS32 canvasW = fsIDisplay::instanceGet()->designCanvasWidthGet();
	const fsS32 canvasH = fsIDisplay::instanceGet()->designCanvasHeightGet();

	// A map that fits one screen keeps the original view=whole-map behaviour.
	// A bigger one gets a scrollable window (+ a tile margin) at native
	// scale, so fsCView recycles tiles instead of sprite count growing with
	// the map (see gfCParkLensComponent).
	const fsS32 mapPixelWidth = map->widthGet() * map->tileWidthGet();
	const fsF32 fillWidthScale = static_cast<fsF32>(canvasW) / static_cast<fsF32>(mapPixelWidth);
	const fsS32 kViewMarginTiles = 2;
	const fsS32 viewTileW = std::min(canvasW / map->tileWidthGet() + kViewMarginTiles, map->widthGet());
	const fsS32 viewTileH = std::min(canvasH / map->tileHeightGet() + kViewMarginTiles, map->heightGet());
	const fsBool scrollable = (viewTileW < map->widthGet()) || (viewTileH < map->heightGet());
	const fsF32 viewScale = scrollable ? 1.0f : fillWidthScale;

	auto* const view = fsNTileMap::fsCView::create(
		map,
		new fsNTileMap::fsCBoundryScroller(),
		viewTileW, viewTileH, viewScale);
	mView = view;

	// The view renders centred at its own origin, so a plain container holding
	// it at (0,0) has its origin on the park centre. The lens transforms this
	// container (see gfCParkLensComponent::targetGetDo), so zoom scales about the
	// centre and pan moves the whole park. Everything else still finds the view
	// by name ("tilemapView") - childFind is recursive.
	fsCEntity* const camera = parentGet()->entityFactoryGet()->emptyEntityCreate("parkCamera");
	camera->childAdd(view);
	parentGet()->childAdd(camera);

	// Find the clearable "forest" tile layer once; clearing, building placement
	// and guest routing all read walkability off it.
	forestLayerResolve(view);

	// Before the markers and moving layers, so everything draws in front of it.
	mapFurnitureCreate(view, gStaffDepotObjectName, gStaffDepotImage, gStaffDepotDrawScale,
	                   /*pRepairDispatchTap*/ true);
	mapFurnitureCreate(view, gParkGateObjectName, gParkGateImage, gParkGateDrawScale);

	slotMarkersCreate(view);

	// Draws the sim's guests (on this entity so it can reach the sim).
	parentGet()->componentAdd<gfCParkGuestViewComponent>();

	// After the guest view, so the guest layer it shares exists.
	parentGet()->componentAdd<gfCParkStaffViewComponent>();

	// Pan/zoom lens (Phase 1). Its own full-canvas, brushless sprite catches
	// drag/pinch anywhere on screen; the lens then scrolls the view's tile
	// window (gfCParkLensComponent::updateDo) and scales the camera for zoom.
	// Added after the view so viewSet()/targetGetDo's lookups resolve.
	fsCEntity* const lensEnt = parentGet()->entityFactoryGet()->emptyEntityCreate("parkLens");
	lensEnt->componentAdd(fsCSpriteComponent::mTypeId);
	if (auto* const lensHit = lensEnt->spriteComponentGet())
	{
		// Hit-test bounds only. The false = pModifyRenderData: set the size for
		// hit testing but build no render quad, so this brushless sprite is not
		// drawn (a drawn brushless sprite is an opaque white rectangle - it was
		// covering the whole screen). Same pattern as HOG's map hit sprite.
		lensHit->widthSet(canvasW, false);
		lensHit->heightSet(canvasH, false);
	}
	parentGet()->childAdd(lensEnt);

	// Content = the map's full on-screen size at min zoom.
	const fsS32 contentWidth = static_cast<fsS32>(map->widthGet() * map->tileWidthGet() * viewScale);
	const fsS32 contentHeight = static_cast<fsS32>(map->heightGet() * map->tileHeightGet() * viewScale);
	auto* const lens = lensEnt->componentAdd<gfCParkLensComponent>();
	lens->configure(
		fsPoint(canvasW, canvasH),
		fsPoint(contentWidth, contentHeight),
		/*minZoom*/ 1.0f, /*maxZoom*/ 2.5f);
	lens->viewSet(view);
	lens->levelSet(this);

	mDayIndex = 1;

	if (pResume)
	{
		progressRestore();

		// The sim state was restored above, but building sprites are only ever
		// created at purchase time - re-place them here so a resumed park shows
		// its bought buildings (and their staff-tap components) instead of empty
		// slots. Staff/guests draw themselves off the restored sim.
		for (const SOwnedSlot& purchasedSlot : mPurchasedSlots)
		{
			if (purchasedSlot.mRuntime)
			{
				scrollTrackedAdd(serviceBuildingPresentationPlace(view, purchasedSlot.mName,
					purchasedSlot.mBuildingImage, purchasedSlot.mDrawWidth,
					purchasedSlot.mLocalX, purchasedSlot.mLocalY), view);
			}
			else
			{
				gfCPurchaseActionSlotFill::buildingPresentationPlace(
					view, purchasedSlot.mName, purchasedSlot.mBuildingImage, this);
			}
		}

		// Cosmetic decorations restore the same way - re-dropped at their saved
		// view-local position.
		for (const SOwnedDecoration& decoration : mOwnedDecorations)
		{
			scrollTrackedAdd(decorationPresentationPlace(view, decoration.mImage, decoration.mDrawWidth,
			                            decoration.mLocalX, decoration.mLocalY), view);
		}

		// Re-hide every previously cleared forest tile so a resumed park shows the
		// land the player already opened up (walkability is data-driven, so the
		// grid is already open - this only re-syncs what's drawn).
		for (const fsPoint& cell : mClearedCells)
		{
			clearedCellApply(view, cell.x, cell.y);
		}
	}
	else
	{
		// New Game: ignore any saved keys and start a clean day 1. The persist
		// below then overwrites the save (counts back to 0, day 1) so a later
		// Continue can't resume a previous game's park.
		daySimBegin();
	}

	// Optional authored starting landmark. Apply after restoring presentations so
	// the normal scroll refresh moves buildings, decorations and walkers together.
	const fsStr startFocusObject = levelSettings->strGet("startFocusObject");
	if (!startFocusObject.emptyGet())
	{
		fsBool focused = false;
		for (fsS32 layer = 0; layer < map->layerCountGet() && !focused; ++layer)
		{
			if (map->layerTypeGet(layer) != fsNTileMap::fsILayer::eType::OBJECT)
			{
				continue;
			}
			for (fsNTileMap::fsIObjectRef const& obj : map->triggersGet(layer))
			{
				if (obj->nameGet() != startFocusObject)
				{
					continue;
				}
				const fsPoint centre = view->mapPixelToLocal(fsPoint(
					obj->posGet().x + obj->widthGet() / 2,
					obj->posGet().y + obj->heightGet() / 2));
				fsS32 dx = static_cast<fsS32>(-(centre.x + view->posGet().x) / viewScale);
				fsS32 dy = static_cast<fsS32>(-(centre.y + view->posGet().y) / viewScale);
				view->scroll(dx, dy);
				scrollRefresh(view);
				focused = true;
				break;
			}
		}
	}

	// Flush immediately, so a save exists (with mCurrentLocation) the moment the
	// park opens - Continue then works even if the player quits within seconds,
	// before the first autosave tick.
	progressPersist();
}

void gfCParkLevelComponent::mapFurnitureCreate(fsNTileMap::fsCView* const pView, const fsStr& pObjectName,
                                               const fsStr& pImagePath, fsF32 pDrawScale,
                                               fsBool pRepairDispatchTap)
{
	fsNTileMap::fsITileMap* const map = pView->mMap;
	for (fsS32 layer = 0; layer < map->layerCountGet(); ++layer)
	{
		if (fsNTileMap::fsILayer::eType::OBJECT != map->layerTypeGet(layer))
		{
			continue;
		}

		for (fsNTileMap::fsIObjectRef const& obj : map->triggersGet(layer))
		{
			if (obj->nameGet() != pObjectName)
			{
				continue;
			}

			const fsCResourceName furnitureRes(pImagePath, fsCResourceName::eRES_LOCATION_ASSETS);
			if (!fsIFile::fileExistsGet(furnitureRes))
			{
				fsLogError("Map furniture image not found: %s", pImagePath.utf8Get());
				return;
			}

			// Sized and stood on its footprint exactly like a purchased building
			// (see gfCPurchaseActionSlotFill) so it sits in the scene the same way.
			const fsPoint pos = obj->posGet();
			const fsPoint topLeft = pView->mapPixelToLocal(pos);
			const fsPoint botRight = pView->mapPixelToLocal(
				fsPoint(pos.x + obj->widthGet(), pos.y + obj->heightGet()));

			fsCEntity* const furniture = pView->entityFactoryGet()->emptyEntityCreate(pObjectName);
			furniture->componentAdd(fsCSpriteComponent::mTypeId);
			auto* const sprt = furniture->spriteComponentGet();
			sprt->brushSet(fsCBrushManager::instanceGet()->get(furnitureRes, false));

			const fsS32 nativeW = sprt->widthGet();
			const fsS32 nativeH = sprt->heightGet();
			const fsS32 drawW = static_cast<fsS32>((botRight.x - topLeft.x) * pDrawScale);
			fsS32 drawH = static_cast<fsS32>((botRight.y - topLeft.y) * pDrawScale);
			if (nativeW > 0 && nativeH > 0)
			{
				drawH = static_cast<fsS32>(drawW * (static_cast<fsF32>(nativeH) / static_cast<fsF32>(nativeW)));
			}
			sprt->widthSet(drawW);
			sprt->heightSet(drawH);
			furniture->posSet(fsPoint((topLeft.x + botRight.x) / 2, botRight.y - drawH / 2));

			// Added before the guest layer exists, so staff and guests walk in
			// front of it rather than disappearing behind.
			pView->childAdd(furniture);
			scrollTrackedAdd(furniture, pView);

			// Tappable to arm a repair dispatch. Added after childAdd so its input
			// listener registers with the entity in the scene.
			if (pRepairDispatchTap)
			{
				furniture->componentAdd<gfCParkOfficeTapComponent>();
			}
			return;
		}
	}
}

void gfCParkLevelComponent::slotMarkersCreate(fsNTileMap::fsCView* const pView)
{
	fsNTileMap::fsITileMap* const map = pView->mMap;
	for (fsS32 layer = 0; layer < map->layerCountGet(); ++layer)
	{
		if (fsNTileMap::fsILayer::eType::OBJECT != map->layerTypeGet(layer))
		{
			continue;
		}

		for (fsNTileMap::fsIObjectRef const& obj : map->triggersGet(layer))
		{
			// Only typed objects are slots; untyped ones are anchors.
			if (obj->typeGet().emptyGet())
			{
				continue;
			}

			// Slot footprint -> view-local via the backdrop's transform.
			const fsPoint pos = obj->posGet();
			const fsPoint topLeft = pView->mapPixelToLocal(pos);
			const fsPoint botRight = pView->mapPixelToLocal(
				fsPoint(pos.x + obj->widthGet(), pos.y + obj->heightGet()));

			fsCEntity* const marker = pView->entityFactoryGet()->emptyEntityCreate(obj->nameGet() + "Marker");
			marker->componentAdd(fsCSpriteComponent::mTypeId);
			// No brush: a sized, coloured sprite is a solid quad (as the screen fade).
			auto* const sprt = marker->spriteComponentGet();
			sprt->widthSet(botRight.x - topLeft.x);
			sprt->heightSet(botRight.y - topLeft.y);
			sprt->colourSet(slotTypeColour(obj->typeGet()));
			marker->posSet(fsPoint((topLeft.x + botRight.x) / 2, (topLeft.y + botRight.y) / 2));
			pView->childAdd(marker);
			scrollTrackedAdd(marker, pView);
		}
	}
}

fsCEntity* gfCParkLevelComponent::decorationPresentationPlace(
	fsNTileMap::fsCView* pView, const fsStr& pImage, fsS32 pDrawWidth,
	fsS32 pLocalX, fsS32 pLocalY)
{
	if (!pView)
	{
		return nullptr;
	}

	// Ever-increasing so names never collide (decorations are never looked up by
	// name, but a duplicate would still confuse a recursive childFind elsewhere).
	static fsS32 sDecorationSeq = 0;
	fsCEntity* const ent =
		pView->entityFactoryGet()->emptyEntityCreate(fsStr("decoration") + fsStr(sDecorationSeq++));
	ent->componentAdd(fsCSpriteComponent::mTypeId);
	auto* const sprt = ent->spriteComponentGet();

	// Same existence-check-before-brushSet discipline as a placed building: a
	// missing file would crash brushSet, so fall back to a small solid block.
	const fsCResourceName decorationRes(pImage, fsCResourceName::eRES_LOCATION_ASSETS);
	fsS32 nativeW = 0;
	fsS32 nativeH = 0;
	if (!pImage.emptyGet() && fsIFile::fileExistsGet(decorationRes))
	{
		// No hit map needed - decorations aren't tappable, they're pure scenery.
		sprt->brushSet(fsCBrushManager::instanceGet()->get(decorationRes, false));
		nativeW = sprt->widthGet();
		nativeH = sprt->heightGet();
	}
	else
	{
		sprt->colourSet(fsSColour4B(120, 200, 120, 255));
	}

	const fsS32 drawW = pDrawWidth > 0
		? pDrawWidth
		: (nativeW > 0 ? nativeW : gDecorationPlaceholderSize);
	fsS32 drawH = drawW;
	if (nativeW > 0 && nativeH > 0)
	{
		drawH = static_cast<fsS32>(drawW *
			(static_cast<fsF32>(nativeH) / static_cast<fsF32>(nativeW)));
	}
	sprt->widthSet(drawW);
	sprt->heightSet(drawH);

	// New grid-aware records are bottom-centred exactly like the live preview.
	// A zero width identifies an older save, whose coordinates were centre-based.
	ent->posSet(fsPoint(pLocalX, pDrawWidth > 0 ? pLocalY - drawH / 2 : pLocalY));
	pView->childAdd(ent);

	// Children render in insertion order, so keep guests drawn above a decoration
	// dropped mid-day.
	if (fsCEntity* const guestLayer = pView->childFind(gfCParkGuestViewComponent::mGuestLayerName))
	{
		guestLayer->bringToFrontOfSiblings();
	}

	return ent;
}

void gfCParkLevelComponent::decorationPlacedRecord(
	fsNTileMap::fsCView* pView, const fsStr& pImage, fsS32 pDrawWidth,
	fsS32 pFootprintColumns, fsS32 pFootprintRows,
	fsS32 pLocalX, fsS32 pLocalY, fsS32 pVisitorAppeal, fsS32 pVisitorComfort)
{
	SOwnedDecoration owned;
	owned.mImage = pImage;
	owned.mDrawWidth = pDrawWidth;
	owned.mFootprintColumns = pFootprintColumns > 0 ? pFootprintColumns : 1;
	owned.mFootprintRows = pFootprintRows > 0 ? pFootprintRows : 1;
	// Zero-scroll, like serviceBuildingPlace - see decorationComfortSourcesGet
	// and parkPlacementValid for where the current scroll is added back on.
	{
		const fsPoint placementScroll = pView ? pView->scrollPixelGet() : fsPoint(0, 0);
		owned.mLocalX = pLocalX - placementScroll.x;
		owned.mLocalY = pLocalY - placementScroll.y;
	}
	owned.mVisitorAppeal = pVisitorAppeal > 0 ? pVisitorAppeal : 0;
	owned.mVisitorComfort = pVisitorComfort > 0 ? pVisitorComfort : 0;
	mOwnedDecorations.push_back(owned);
	visitorNumbersRefresh();
}

std::vector<gfCParkLevelComponent::SDecorationComfortSource>
gfCParkLevelComponent::decorationComfortSourcesGet(fsNTileMap::fsCView* pView) const
{
	std::vector<SDecorationComfortSource> sources;
	sources.reserve(mOwnedDecorations.size());
	const fsPoint scrollPixel = pView ? pView->scrollPixelGet() : fsPoint(0, 0);
	for (const SOwnedDecoration& decoration : mOwnedDecorations)
	{
		if (decoration.mVisitorComfort <= 0)
		{
			continue;
		}
		SDecorationComfortSource source;
		source.mPos = fsVec2d(static_cast<fsF32>(decoration.mLocalX + scrollPixel.x),
		                      static_cast<fsF32>(decoration.mLocalY + scrollPixel.y));
		source.mComfort = decoration.mVisitorComfort;
		source.mImage = decoration.mImage;
		sources.push_back(source);
	}
	return sources;
}

fsCEntity* gfCParkLevelComponent::serviceBuildingPresentationPlace(
	fsNTileMap::fsCView* pView, const fsStr& pSlotName, const fsStr& pImage,
	fsS32 pDrawWidth, fsS32 pLocalX, fsS32 pLocalY)
{
	if (!pView)
	{
		return nullptr;
	}

	fsCEntity* const ent = pView->entityFactoryGet()->emptyEntityCreate(pSlotName + "Building");
	ent->componentAdd(fsCSpriteComponent::mTypeId);
	auto* const sprt = ent->spriteComponentGet();

	const fsCResourceName buildingRes(pImage, fsCResourceName::eRES_LOCATION_ASSETS);
	if (!pImage.emptyGet() && fsIFile::fileExistsGet(buildingRes))
	{
		sprt->brushSet(fsCBrushManager::instanceGet()->get(buildingRes, false));
	}
	else
	{
		sprt->colourSet(fsSColour4B(228, 216, 194, 255));
	}

	const fsS32 nativeW = sprt->widthGet();
	const fsS32 nativeH = sprt->heightGet();
	const fsS32 drawW = pDrawWidth > 0 ? pDrawWidth : gServiceBuildingDefaultWidth;
	fsS32 drawH = drawW;
	if (nativeW > 0 && nativeH > 0)
	{
		drawH = static_cast<fsS32>(drawW *
			(static_cast<fsF32>(nativeH) / static_cast<fsF32>(nativeW)));
	}
	sprt->widthSet(drawW);
	sprt->heightSet(drawH);
	ent->posSet(fsPoint(pLocalX, pLocalY - drawH / 2));
	pView->childAdd(ent);

	if (fsCEntity* const guestLayer = pView->childFind(gfCParkGuestViewComponent::mGuestLayerName))
	{
		guestLayer->bringToFrontOfSiblings();
	}

	gfCParkSlotStaffComponent* const staffComponent = ent->componentAdd<gfCParkSlotStaffComponent>();
	staffComponent->slotNameSet(pSlotName);
	staffComponent->buildingImageSet(pImage);
	return ent;
}

fsBool gfCParkLevelComponent::serviceBuildingPlace(
	fsNTileMap::fsCView* pView, const fsStr& pImage, const fsStr& pServiceType,
	fsS32 pServiceTimeMs, fsS32 pMaxQueueLength, fsS32 pVisitorQuota,
	fsS32 pVisitorAppeal, fsS32 pDrawWidth,
	fsS32 pFootprintColumns, fsS32 pFootprintRows,
	fsS32 pLocalX, fsS32 pLocalY, fsS32 pPurchaseCost)
{
	if (!pView || !mSim || pServiceType.emptyGet() || pServiceTimeMs <= 0 || pMaxQueueLength <= 0)
	{
		return false;
	}
	if (!parkPlacementValid(
		pView, pLocalX, pLocalY, pFootprintColumns, pFootprintRows))
	{
		return false;
	}

	const fsStr slotName = fsStr("runtimeBuildingSlot") + fsStr(mRuntimeSlotSequence++);
	fsCEntity* const placed =
		serviceBuildingPresentationPlace(pView, slotName, pImage, pDrawWidth, pLocalX, pLocalY);
	if (!placed)
	{
		return false;
	}
	scrollTrackedAdd(placed, pView);

	mSim->slotAdd(slotName, pServiceType, pServiceTimeMs, pMaxQueueLength, true);
	mSim->slotWearLimitsSetAll(gServicesBeforeBreak, gOpenMsBeforeBreak);

	SOwnedSlot owned;
	owned.mName = slotName;
	owned.mServiceTimeMs = pServiceTimeMs;
	owned.mMaxQueueLength = pMaxQueueLength;
	owned.mBuildingImage = pImage;
	owned.mRuntime = true;
	owned.mServiceType = pServiceType;
	// Stored zero-scroll, like scrollTrackedAdd's mZeroScrollPos for the sprite
	// itself - pLocalX/Y is wherever the player tapped under *today's* scroll,
	// and runtimeSlotPositionGet/runtimeSlotGetByIndex add the *current* scroll
	// back on. Without this, staff/guests pathing to a free-placed building
	// (every building, now that fixed slots are gone) would keep targeting
	// where it was on screen at purchase time rather than where it is now.
	{
		const fsPoint placementScroll = pView->scrollPixelGet();
		owned.mLocalX = pLocalX - placementScroll.x;
		owned.mLocalY = pLocalY - placementScroll.y;
	}
	owned.mDrawWidth = pDrawWidth > 0 ? pDrawWidth : gServiceBuildingDefaultWidth;
	owned.mFootprintColumns = pFootprintColumns > 0 ? pFootprintColumns : 1;
	owned.mFootprintRows = pFootprintRows > 0 ? pFootprintRows : 1;
	owned.mVisitorQuota = pVisitorQuota > 0 ? pVisitorQuota : 0;
	owned.mVisitorAppeal = pVisitorAppeal > 0 ? pVisitorAppeal : 0;
	owned.mPurchaseCost = pPurchaseCost;
	mPurchasedSlots.push_back(owned);
	visitorNumbersRefresh();
	return true;
}

fsS32 gfCParkLevelComponent::buildingPurchaseCostGet(const fsStr& pSlotName) const
{
	for (const SOwnedSlot& slot : mPurchasedSlots)
		if (slot.mName == pSlotName) return slot.mPurchaseCost;<--- Consider using std::find_if algorithm instead of a raw loop.
	return -1;
}

fsBool gfCParkLevelComponent::runtimeSlotPositionGet(const fsStr& pSlotName, fsVec2d& pOut) const
{
	auto slot = std::find_if(mPurchasedSlots.begin(), mPurchasedSlots.end(),
	                        [&pSlotName](SOwnedSlot const& slot)
	                        {
		                        return slot.mRuntime && slot.mName == pSlotName;
	                        });
	if (slot != mPurchasedSlots.end())
	{
		// mLocalX/Y is stored zero-scroll (see serviceBuildingPlace) - add the
		// current scroll back on so callers get where the building actually is
		// on screen right now, not where it was when purchased.
		const fsPoint scrollPixel = mView ? mView->scrollPixelGet() : fsPoint(0, 0);
		pOut = fsVec2d(static_cast<fsF32>(slot->mLocalX + scrollPixel.x),
		              static_cast<fsF32>(slot->mLocalY + scrollPixel.y));
		return true;
	}
	return false;
}

fsBool gfCParkLevelComponent::runtimeSlotGetByIndex(fsS32 pIndex, fsStr& pNameOut,
                                                    fsVec2d& pPositionOut) const
{
	if (pIndex < 0)
	{
		return false;
	}

	const fsPoint scrollPixel = mView ? mView->scrollPixelGet() : fsPoint(0, 0);
	fsS32 runtimeIndex = 0;
	for (const SOwnedSlot& slot : mPurchasedSlots)
	{
		if (!slot.mRuntime)
		{
			continue;
		}
		if (runtimeIndex++ == pIndex)
		{
			pNameOut = slot.mName;
			// See runtimeSlotPositionGet - mLocalX/Y is a zero-scroll anchor.
			pPositionOut = fsVec2d(static_cast<fsF32>(slot.mLocalX + scrollPixel.x),
			                       static_cast<fsF32>(slot.mLocalY + scrollPixel.y));
			return true;
		}
	}
	return false;
}

fsBool gfCParkLevelComponent::parkPlacementValid(
	fsNTileMap::fsCView* pView, fsS32 pLocalX, fsS32 pLocalY,
	fsS32 pFootprintColumns, fsS32 pFootprintRows) const
{
	if (!pView || pFootprintColumns <= 0 || pFootprintRows <= 0)
	{
		return false;
	}

	const SGridRect candidate = gridRectFromAnchor(
		pView, pLocalX, pLocalY, pFootprintColumns, pFootprintRows);
	if (candidate.mLeft < 0 || candidate.mTop < 0 ||
		candidate.mRight > pView->mMap->widthGet() ||
		candidate.mBottom > pView->mMap->heightGet())
	{
		return false;
	}

	// slot.mLocalX/Y is stored zero-scroll (see serviceBuildingPlace); candidate
	// above was built from pLocalX/Y, which is current-scroll (a live tap) -
	// both sides of gridRectFromAnchor's subtraction need the same frame, so
	// add the current scroll back on here too.
	const fsPoint scrollPixel = pView->scrollPixelGet();
	for (const SOwnedSlot& slot : mPurchasedSlots)
	{
		if (!slot.mRuntime)
		{
			continue;
		}
		const SGridRect occupied = gridRectFromAnchor(
			pView, slot.mLocalX + scrollPixel.x, slot.mLocalY + scrollPixel.y,
			slot.mFootprintColumns > 0 ? slot.mFootprintColumns : 1,
			slot.mFootprintRows > 0 ? slot.mFootprintRows : 1);
		if (gridRectsOverlap(candidate, occupied))
		{
			return false;
		}
	}

	// Decorations share the same grid and reserve their asset-defined footprint,
	// so buildings and later decorations cannot overlap them. mLocalX/Y is
	// zero-scroll (see decorationPlacedRecord) - same current-scroll
	// correction as the buildings loop above.
	for (const SOwnedDecoration& decoration : mOwnedDecorations)
	{
		const SGridRect occupied = gridRectFromAnchor(
			pView, decoration.mLocalX + scrollPixel.x, decoration.mLocalY + scrollPixel.y,
			decoration.mFootprintColumns > 0 ? decoration.mFootprintColumns : 1,
			decoration.mFootprintRows > 0 ? decoration.mFootprintRows : 1);
		if (gridRectsOverlap(candidate, occupied))
		{
			return false;
		}
	}

	// Every authored object reserves its footprint. That protects fixed slots,
	// the gate and staff office, while still allowing free placement elsewhere.
	fsNTileMap::fsITileMap* const map = pView->mMap;
	for (fsS32 layer = 0; layer < map->layerCountGet(); ++layer)
	{
		if (fsNTileMap::fsILayer::eType::OBJECT != map->layerTypeGet(layer))
		{
			continue;
		}
		for (fsNTileMap::fsIObjectRef const& obj : map->triggersGet(layer))
		{
			const fsPoint pos = obj->posGet();
			const fsS32 width = obj->widthGet() > 0 ? obj->widthGet() : 1;
			const fsS32 height = obj->heightGet() > 0 ? obj->heightGet() : 1;
			SGridRect occupied;
			occupied.mLeft = pos.x / map->tileWidthGet();
			occupied.mTop = pos.y / map->tileHeightGet();
			occupied.mRight =
				(pos.x + width + map->tileWidthGet() - 1) / map->tileWidthGet();
			occupied.mBottom =
				(pos.y + height + map->tileHeightGet() - 1) / map->tileHeightGet();
			if (gridRectsOverlap(candidate, occupied))
			{
				return false;
			}
		}
	}

	// Uncleared forest is not buildable - the footprint must sit entirely on open
	// (cleared or never-forested) ground.
	for (fsS32 row = candidate.mTop; row < candidate.mBottom; ++row)
	{
		for (fsS32 col = candidate.mLeft; col < candidate.mRight; ++col)
		{
			if (cellForestGet(pView, col, row))
			{
				return false;
			}
		}
	}

	return true;
}

fsBool gfCParkLevelComponent::cellClearedGet(fsS32 pCol, fsS32 pRow) const
{
	return std::any_of(mClearedCells.begin(), mClearedCells.end(),
	                   [pCol, pRow](fsPoint const& cell)
	                   {
		                   return cell.x == pCol && cell.y == pRow;
	                   });
}

void gfCParkLevelComponent::forestLayerResolve(fsNTileMap::fsCView* const pView)
{
	mForestLayerId = -1;
	if (!pView || !pView->mMap)
	{
		return;
	}
	fsNTileMap::fsITileMap* const map = pView->mMap;
	for (fsS32 layer = 0; layer < map->layerCountGet(); ++layer)
	{
		if (fsNTileMap::fsILayer::eType::TILE == map->layerTypeGet(layer) &&
			map->layerNameGet(layer) == "forest")
		{
			mForestLayerId = layer;
			return;
		}
	}
}

fsBool gfCParkLevelComponent::cellForestGet(fsNTileMap::fsCView* pView, fsS32 pCol, fsS32 pRow) const
{
	if (!pView || !pView->mMap || mForestLayerId < 0)
	{
		return false;
	}
	fsNTileMap::fsITileMap* const map = pView->mMap;
	if (pCol < 0 || pRow < 0 || pCol >= map->widthGet() || pRow >= map->heightGet())
	{
		return false;
	}
	if (cellClearedGet(pCol, pRow))
	{
		return false;
	}
	const fsNTileMap::fsITileRef tile = map->tileGet(mForestLayerId, pCol, pRow);
	return tile && tile->tileSetIdGet() != -1;
}

fsBool gfCParkLevelComponent::cellWalkableGet(fsNTileMap::fsCView* pView, fsS32 pCol, fsS32 pRow) const
{
	if (!pView || !pView->mMap)
	{
		return false;
	}
	fsNTileMap::fsITileMap* const map = pView->mMap;
	if (pCol < 0 || pRow < 0 || pCol >= map->widthGet() || pRow >= map->heightGet())
	{
		return false;
	}
	return !cellForestGet(pView, pCol, pRow);
}

fsPoint gfCParkLevelComponent::cellFromLocal(fsNTileMap::fsCView* pView, const fsVec2d& pLocal) const
{
	fsNTileMap::fsITileMap* const map = pView->mMap;
	const fsPoint mapTopLeft = pView->mapPixelToLocal(fsPoint(0, 0));
	const fsPoint firstTileBottomRight = pView->mapPixelToLocal(
		fsPoint(map->tileWidthGet(), map->tileHeightGet()));
	const fsF32 tileLocalWidth = static_cast<fsF32>(firstTileBottomRight.x - mapTopLeft.x);
	const fsF32 tileLocalHeight = static_cast<fsF32>(firstTileBottomRight.y - mapTopLeft.y);
	if (tileLocalWidth <= 0.0f || tileLocalHeight <= 0.0f)
	{
		return fsPoint(0, 0);
	}
	const fsS32 col = static_cast<fsS32>(std::floor((pLocal.x - mapTopLeft.x) / tileLocalWidth));
	const fsS32 row = static_cast<fsS32>(std::floor((pLocal.y - mapTopLeft.y) / tileLocalHeight));
	return fsPoint(col, row);
}

fsVec2d gfCParkLevelComponent::cellCentreLocal(fsNTileMap::fsCView* pView, fsS32 pCol, fsS32 pRow) const
{
	fsNTileMap::fsITileMap* const map = pView->mMap;
	// fsCView's own tile layer (see fsCView.cpp) positions each tile sprite at
	// col*tileWidth directly - since sprites are centre-anchored, that point IS
	// the tile's visual centre. Adding an extra half-tile here (as the corner-
	// based mapPixelToLocal convention used elsewhere would suggest) instead
	// lands on the boundary between this cell and the next.
	const fsPoint centre = pView->mapPixelToLocal(fsPoint(
		pCol * map->tileWidthGet(),
		pRow * map->tileHeightGet()));
	return fsVec2d(static_cast<fsF32>(centre.x), static_cast<fsF32>(centre.y));
}

std::vector<fsPoint> gfCParkLevelComponent::pathFindCells(fsNTileMap::fsCView* pView,
                                                          const fsPoint& pFrom, const fsPoint& pTo) const
{
	std::vector<fsPoint> path;
	if (!pView || !pView->mMap)
	{
		return path;
	}
	fsNTileMap::fsITileMap* const map = pView->mMap;
	const fsS32 width = map->widthGet();
	const fsS32 height = map->heightGet();
	if (!cellWalkableGet(pView, pFrom.x, pFrom.y) || !cellWalkableGet(pView, pTo.x, pTo.y))
	{
		return path;
	}
	if (pFrom.x == pTo.x && pFrom.y == pTo.y)
	{
		path.push_back(pFrom);
		return path;
	}

	// Grid BFS. cameFrom holds each visited cell's predecessor index (-1 = unset,
	// -2 = the start), so the route can be walked back once the target is found.
	const fsS32 cellCount = width * height;
	std::vector<fsS32> cameFrom(cellCount, -1);
	std::vector<fsS32> queue;
	queue.reserve(cellCount);
	const fsS32 startIndex = pFrom.y * width + pFrom.x;
	const fsS32 targetIndex = pTo.y * width + pTo.x;
	cameFrom[startIndex] = -2;
	queue.push_back(startIndex);

	const fsS32 stepX[4] = {1, -1, 0, 0};
	const fsS32 stepY[4] = {0, 0, 1, -1};
	fsBool found = false;
	for (fsS32 head = 0; head < static_cast<fsS32>(queue.size()) && !found; ++head)
	{
		const fsS32 current = queue[head];
		const fsS32 cx = current % width;
		const fsS32 cy = current / width;
		for (fsS32 dir = 0; dir < 4; ++dir)
		{
			const fsS32 nx = cx + stepX[dir];
			const fsS32 ny = cy + stepY[dir];
			if (nx < 0 || ny < 0 || nx >= width || ny >= height)
			{
				continue;
			}
			const fsS32 neighbour = ny * width + nx;
			if (cameFrom[neighbour] != -1 || !cellWalkableGet(pView, nx, ny))
			{
				continue;
			}
			cameFrom[neighbour] = current;
			if (neighbour == targetIndex)
			{
				found = true;
				break;
			}
			queue.push_back(neighbour);
		}
	}

	if (!found)
	{
		return path;
	}
	for (fsS32 at = targetIndex; at != -2; at = cameFrom[at])
	{
		path.push_back(fsPoint(at % width, at / width));
	}
	// Walked target -> start; flip so callers get start -> target.
	for (fsS32 i = 0, j = static_cast<fsS32>(path.size()) - 1; i < j; ++i, --j)
	{
		const fsPoint tmp = path[i];
		path[i] = path[j];
		path[j] = tmp;
	}
	return path;
}

fsPoint gfCParkLevelComponent::nearestWalkableCell(fsNTileMap::fsCView* pView, const fsPoint& pCell) const
{
	if (cellWalkableGet(pView, pCell.x, pCell.y))
	{
		return pCell;
	}
	if (!pView || !pView->mMap)
	{
		return pCell;
	}
	const fsS32 maxRadius = pView->mMap->widthGet() + pView->mMap->heightGet();
	for (fsS32 radius = 1; radius <= maxRadius; ++radius)
	{
		for (fsS32 dy = -radius; dy <= radius; ++dy)
		{
			for (fsS32 dx = -radius; dx <= radius; ++dx)
			{
				// Only the ring at this radius (its interior was tested already).
				if (dx > -radius && dx < radius && dy > -radius && dy < radius)
				{
					continue;
				}
				const fsS32 cx = pCell.x + dx;
				const fsS32 cy = pCell.y + dy;
				if (cellWalkableGet(pView, cx, cy))
				{
					return fsPoint(cx, cy);
				}
			}
		}
	}
	return pCell;
}

fsPoint gfCParkLevelComponent::nearestReachableCell(fsNTileMap::fsCView* pView,
                                                    const fsPoint& pFrom, const fsPoint& pDesired) const
{
	if (!pView || !pView->mMap || !cellWalkableGet(pView, pFrom.x, pFrom.y))
	{
		return pFrom;
	}
	fsNTileMap::fsITileMap* const map = pView->mMap;
	const fsS32 width = map->widthGet();
	const fsS32 height = map->heightGet();

	std::vector<bool> visited(width * height, false);
	std::vector<fsS32> queue;
	queue.reserve(width * height);
	const fsS32 startIndex = pFrom.y * width + pFrom.x;
	visited[startIndex] = true;
	queue.push_back(startIndex);

	fsPoint best = pFrom;
	auto sqDist = [&](fsS32 cx, fsS32 cy)
	{
		const fsS32 dx = cx - pDesired.x;
		const fsS32 dy = cy - pDesired.y;
		return dx * dx + dy * dy;
	};
	fsS32 bestDist = sqDist(pFrom.x, pFrom.y);

	const fsS32 stepX[4] = {1, -1, 0, 0};
	const fsS32 stepY[4] = {0, 0, 1, -1};
	for (fsS32 head = 0; head < static_cast<fsS32>(queue.size()); ++head)
	{
		const fsS32 current = queue[head];
		const fsS32 cx = current % width;
		const fsS32 cy = current / width;
		const fsS32 d = sqDist(cx, cy);
		if (d < bestDist)
		{
			bestDist = d;
			best = fsPoint(cx, cy);
			if (0 == bestDist)
			{
				break;   // reached the desired cell exactly
			}
		}
		for (fsS32 dir = 0; dir < 4; ++dir)
		{
			const fsS32 nx = cx + stepX[dir];
			const fsS32 ny = cy + stepY[dir];
			if (nx < 0 || ny < 0 || nx >= width || ny >= height)
			{
				continue;
			}
			const fsS32 neighbour = ny * width + nx;
			if (visited[neighbour] || !cellWalkableGet(pView, nx, ny))
			{
				continue;
			}
			visited[neighbour] = true;
			queue.push_back(neighbour);
		}
	}
	return best;
}

fsS32 gfCParkLevelComponent::forestClearCostGet() const
{
	return fsCAppCoreMain::instanceGet()->settingsGet()->s32GetWithDefault(
		"forestClearCostCoins", 25);
}

void gfCParkLevelComponent::clearedCellApply(fsNTileMap::fsCView* const pView, fsS32 pCol, fsS32 pRow)
{
	if (pView && mForestLayerId >= 0)
	{
		pView->tileHide(mForestLayerId, pCol, pRow);
	}
}

void gfCParkLevelComponent::scrollTrackedAdd(fsCEntity* const pEntity, fsNTileMap::fsCView* const pView)
{
	if (!pEntity || !pView)
	{
		return;
	}
	SScrollTracked tracked;
	tracked.mEntity = pEntity;
	// Where this would sit at scroll (0,0) - scrollTrackedRefresh adds the
	// current scroll back on.
	tracked.mZeroScrollPos = fsPoint(pEntity->posGet()) - pView->scrollPixelGet();
	mScrollTracked.push_back(tracked);
}

void gfCParkLevelComponent::scrollTrackedRemove(fsCEntity* const pEntity)
{
	std::erase_if(mScrollTracked, [pEntity](const SScrollTracked& tracked)
	{
		return tracked.mEntity == pEntity;
	});
}

void gfCParkLevelComponent::scrollTrackedRefresh(fsNTileMap::fsCView* const pView) const
{
	if (!pView)
	{
		return;
	}
	const fsPoint scrollPixel = pView->scrollPixelGet();
	for (const SScrollTracked& tracked : mScrollTracked)
	{
		if (tracked.mEntity)
		{
			tracked.mEntity->posSet(tracked.mZeroScrollPos + scrollPixel);
		}
	}
}

fsS32 gfCParkLevelComponent::forestClearBrushSizeGet() const
{
	return std::clamp(fsCAppCoreMain::instanceGet()->settingsGet()->s32GetWithDefault(
		"forestClearBrushSize", 1), 1, 2);
}

std::vector<fsPoint> gfCParkLevelComponent::forestClearTargetsGet(
	fsNTileMap::fsCView* pView, fsS32 pCol, fsS32 pRow) const
{
	std::vector<fsPoint> targets;
	if (!cellForestGet(pView, pCol, pRow))
	{
		return targets;
	}

	const fsS32 side = forestClearBrushSizeGet();
	const fsS32 costPerTile = forestClearCostGet();
	const fsS32 limit = mSim && costPerTile > 0
		? std::clamp(mSim->economyGet().coinsGet() / costPerTile, 0, side * side)
		: side * side;
	if (limit == 0)
	{
		return targets;
	}

	// Grow inward from open land. A cell can touch existing open ground or
	// another forest cell selected in this tap.
	size_t previousCount;
	do
	{
		previousCount = targets.size();
		for (fsS32 row = pRow; row < pRow + side; ++row)
		{
			for (fsS32 col = pCol; col < pCol + side; ++col)
			{
				if (!cellForestGet(pView, col, row) ||
					std::find(targets.begin(), targets.end(), fsPoint(col, row)) != targets.end())
				{
					continue;
				}
				const fsBool touchesOpen =
					cellWalkableGet(pView, col + 1, row) || cellWalkableGet(pView, col - 1, row) ||
					cellWalkableGet(pView, col, row + 1) || cellWalkableGet(pView, col, row - 1);
				const fsBool touchesTarget = std::any_of(targets.begin(), targets.end(),
					[col, row](const fsPoint& cell)
					{
						return std::abs(cell.x - col) + std::abs(cell.y - row) == 1;
					});
				if (touchesOpen || touchesTarget)
				{
					targets.emplace_back(col, row);
					if (targets.size() == static_cast<size_t>(limit))
					{
						return targets;
					}
				}
			}
		}
	} while (targets.size() != previousCount);

	return targets;
}

fsBool gfCParkLevelComponent::forestClearAt(fsNTileMap::fsCView* pView, fsS32 pCol, fsS32 pRow)
{
	const auto targets = forestClearTargetsGet(pView, pCol, pRow);
	if (targets.empty())
	{
		return false;
	}

	const fsS32 costPerTile = forestClearCostGet();
	if (mSim && costPerTile > 0)
	{
		const fsS32 cost = costPerTile * static_cast<fsS32>(targets.size());
		mSim->economyGet().coinsSet(mSim->economyGet().coinsGet() - cost);
	}

	for (const fsPoint& cell : targets)
	{
		mClearedCells.push_back(cell);
		clearedCellApply(pView, cell.x, cell.y);
	}
	// New land can raise appeal-independent walking access; keep sim numbers fresh
	// and persist so the clear survives a quit exactly like a purchase.
	visitorNumbersRefresh();
	progressPersist();
	return true;
}

void gfCParkLevelComponent::daySimBegin()
{
	mDayRemainingMs = mDayDurationMs;
	mDayEndShown = false;

	mSim = std::make_unique<gfCParkDaySim>(
		gSpawnIntervalMs, visitorQuotaHighestOwnedGet(), gCoinGoalByDay[mDayIndex - 1]);
	mSim->visitorDemandSet(visitorDemandFromParkGet());
	mSim->walkingSatisfactionPercentSet(walkingSatisfactionFromParkGet());
	// Re-granted per day (fresh sim); progressRestore overwrites it when resuming.
	mSim->economyGet().coinsSet(gStartingCoins);
	// Presentation paces guest sprites to this same walk time.
	mSim->guestTravelMsSet(gGuestTravelMs);
	mSim->unstaffedVisitHappyChancePercentSet(
		fsCAppCoreMain::instanceGet()->settingsGet()->s32GetWithDefault(
			"unstaffedGuestHappyChancePercent", 50));

	guestTemplatesLoad();

	// Clear last day's guests so the new day starts empty rather than yesterday's
	// crowd walking out at once. A no-op on the first day (view exists, empty).
	if (gfCParkGuestViewComponent* const guestView =
		parentGet()->firstComponentOfFamilyType<gfCParkGuestViewComponent>())
	{
		guestView->reset();
		mSim->waitForServiceArrivalSet(true);
	}

	if (auto* const view = dynamic_cast<fsNTileMap::fsCView*>(
		fsCAppCoreMain::instanceGet()->sceneGet()->childFind("tilemapView")))
	{
		gfCParkLayoutManager::slotsRegister(view->mMap, *mSim);
	}

	for (const SOwnedSlot& purchasedSlot : mPurchasedSlots)
	{
		if (purchasedSlot.mRuntime && !purchasedSlot.mServiceType.emptyGet())
		{
			mSim->slotAdd(purchasedSlot.mName, purchasedSlot.mServiceType,
				purchasedSlot.mServiceTimeMs, purchasedSlot.mMaxQueueLength, true);
		}
	}

	// A fresh sim re-registers slots locked with an empty staff pool, but the
	// player's buildings persist on the map - re-apply ownership or the park
	// looks built yet serves nobody.
	for (const SOwnedSlot& purchasedSlot : mPurchasedSlots)
	{
		mSim->slotUnlock(purchasedSlot.mName);
		if (purchasedSlot.mServiceTimeMs > 0)
		{
			mSim->slotServiceTimeMsSet(purchasedSlot.mName, purchasedSlot.mServiceTimeMs);
		}
		if (purchasedSlot.mMaxQueueLength > 0)
		{
			mSim->slotMaxQueueLengthSet(purchasedSlot.mName, purchasedSlot.mMaxQueueLength);
		}
	}
	for (const SHiredStaff& hired : mHiredStaff)
	{
		mSim->staffPoolGrow(hired.mType, 1);
	}

	// Re-deploy after the pool exists, or staffDeploy() finds nobody available.
	for (const SDeployedStaff& deployed : mDeployedSlots)
	{
		mSim->staffDeploy(deployed.mSlotName, deployed.mType);
	}

	// After registration (touches every slot). Buildings start each day repaired,
	// so wear is within-day pressure.
	mSim->slotWearLimitsSetAll(gServicesBeforeBreak, gOpenMsBeforeBreak);
	mSim->repairTimeMsSet(gRepairTimeMs);
}

void gfCParkLevelComponent::slotPurchasedRecord(const fsStr& pSlotName, fsS32 pServiceTimeMs,
	                                            fsS32 pMaxQueueLength, const fsStr& pBuildingImage,
	                                            fsS32 pVisitorQuota, fsS32 pVisitorAppeal)
{
	auto purchasedSlot = std::find_if(mPurchasedSlots.begin(), mPurchasedSlots.end(),
	                                 [&pSlotName](SOwnedSlot const& purchasedSlot)
	                                 {
		                                 return purchasedSlot.mName == pSlotName;
	                                 });
	if (purchasedSlot != mPurchasedSlots.end())
	{
		purchasedSlot->mServiceTimeMs = pServiceTimeMs;
		purchasedSlot->mMaxQueueLength = pMaxQueueLength;
		purchasedSlot->mBuildingImage = pBuildingImage;
		purchasedSlot->mRuntime = false;
		purchasedSlot->mServiceType = fsStr();
		purchasedSlot->mLocalX = 0;
		purchasedSlot->mLocalY = 0;
		purchasedSlot->mDrawWidth = 0;
		purchasedSlot->mFootprintColumns = 0;
		purchasedSlot->mFootprintRows = 0;
		purchasedSlot->mVisitorQuota = pVisitorQuota > 0 ? pVisitorQuota : 0;
		purchasedSlot->mVisitorAppeal = pVisitorAppeal > 0 ? pVisitorAppeal : 0;
		visitorNumbersRefresh();
		return;
	}

	SOwnedSlot owned;
	owned.mName = pSlotName;
	owned.mServiceTimeMs = pServiceTimeMs;
	owned.mMaxQueueLength = pMaxQueueLength;
	owned.mBuildingImage = pBuildingImage;
	owned.mRuntime = false;
	owned.mVisitorQuota = pVisitorQuota > 0 ? pVisitorQuota : 0;
	owned.mVisitorAppeal = pVisitorAppeal > 0 ? pVisitorAppeal : 0;
	mPurchasedSlots.push_back(owned);
	visitorNumbersRefresh();
}

fsS32 gfCParkLevelComponent::visitorQuotaHighestOwnedGet() const
{
	return std::accumulate(mPurchasedSlots.begin(), mPurchasedSlots.end(), gBaseVisitorQuota,
	                       [](fsS32 visitorQuota, SOwnedSlot const& slot)
	                       {
		                       return std::max(visitorQuota, slot.mVisitorQuota);
	                       });
}

fsS32 gfCParkLevelComponent::visitorDemandFromParkGet() const
{
	fsS32 visitorDemand = gBaseVisitorDemand + reputationDemandModifier(mParkReputation);
	visitorDemand = std::accumulate(mPurchasedSlots.begin(), mPurchasedSlots.end(), visitorDemand,
	                                [](fsS32 sum, SOwnedSlot const& slot)
	                                {
		                                return sum + slot.mVisitorAppeal;
	                                });
	// Diminishing returns per repeated decoration art - see
	// decorationDuplicateWeightPercentGet. Buildings aren't included: they're
	// expensive and footprint-limited, not spammable the same way.
	visitorDemand += decorationDiminishingSumGet(mOwnedDecorations,
		[](SOwnedDecoration const& decoration) -> const fsStr& { return decoration.mImage; },
		[](SOwnedDecoration const& decoration) { return decoration.mVisitorAppeal; });
	return visitorDemand;
}

fsS32 gfCParkLevelComponent::walkingSatisfactionFromParkGet() const
{
	fsS32 comfortBonus = decorationDiminishingSumGet(mOwnedDecorations,
		[](SOwnedDecoration const& decoration) -> const fsStr& { return decoration.mImage; },
		[](SOwnedDecoration const& decoration) { return decoration.mVisitorComfort; });
	if (comfortBonus > gMaxDecorationComfortBonus)
	{
		comfortBonus = gMaxDecorationComfortBonus;
	}
	return gBaseWalkingSatisfaction + comfortBonus;
}

fsS32 gfCParkLevelComponent::walkingSatisfactionNearGet(
	fsNTileMap::fsCView* pView, const fsVec2d& pScreenPos) const
{
	// Filter to what's actually in range first, then apply diminishing returns
	// within that nearby set - five identical benches clustered on top of the
	// guest shouldn't add up to five times the comfort of one.
	std::vector<SDecorationComfortSource> nearby;
	for (const SDecorationComfortSource& source : decorationComfortSourcesGet(pView))
	{
		const fsVec2d offset = source.mPos - pScreenPos;
		const fsF32 distSq = offset.x * offset.x + offset.y * offset.y;
		if (distSq <= gComfortRadiusPx * gComfortRadiusPx)
		{
			nearby.push_back(source);
		}
	}
	fsS32 comfortBonus = decorationDiminishingSumGet(nearby,
		[](SDecorationComfortSource const& source) -> const fsStr& { return source.mImage; },
		[](SDecorationComfortSource const& source) { return source.mComfort; });
	if (comfortBonus > gMaxDecorationComfortBonus)
	{
		comfortBonus = gMaxDecorationComfortBonus;
	}
	return gBaseWalkingSatisfaction + comfortBonus;
}

void gfCParkLevelComponent::reputationSettle()
{
	if (!mSim || mReputationSettledDay >= mDayIndex)
	{
		return;
	}
	mParkReputation = mSim->economyGet().reputationAfterDayGet(mParkReputation);
	mReputationSettledDay = mDayIndex;
}

void gfCParkLevelComponent::visitorNumbersRefresh()
{
	if (!mSim)
	{
		return;
	}
	mSim->visitorQuotaSet(visitorQuotaHighestOwnedGet());
	mSim->visitorDemandSet(visitorDemandFromParkGet());
	mSim->walkingSatisfactionPercentSet(walkingSatisfactionFromParkGet());
}

void gfCParkLevelComponent::staffHiredRecord(const fsStr& pStaffType, fsS32 pWage)
{
	SHiredStaff hired;
	hired.mType = pStaffType;
	hired.mWage = pWage;
	mHiredStaff.push_back(hired);
}

fsS32 gfCParkLevelComponent::dailyWagesGet() const
{
	return std::accumulate(mHiredStaff.begin(), mHiredStaff.end(), 0,
	                       [](fsS32 wages, SHiredStaff const& hired)
	                       {
		                       return wages + hired.mWage;
	                       });
}

void gfCParkLevelComponent::staffDeployedRecord(const fsStr& pSlotName)
{
	staffRecalledRecord(pSlotName);
	mDeployedSlots.push_back({pSlotName, mSim->slotStaffTypeGet(pSlotName)});
}

void gfCParkLevelComponent::staffRecalledRecord(const fsStr& pSlotName)
{
	std::erase_if(mDeployedSlots, [&pSlotName](const SDeployedStaff& deployed)
	{
		return deployed.mSlotName == pSlotName;
	});
}

void gfCParkLevelComponent::guestTemplatesLoad()
{
	// Its own catalogue root (guests aren't shop items) - just reuses the
	// catalogue format for its per-entry params.
	gfCCatalogueParserYaml parser;
	std::unique_ptr<gfCCatalogueCatalogue> catalogue(parser.catalogueLoad("catalogue/guests.yml"));

	for (fsS32 i = 0; i < catalogue->numChildrenGet(); ++i)
	{
		if (const auto* const item = dynamic_cast<const gfCCatalogueItem*>(catalogue->childGetByIndex(i)))
		{
			std::vector<fsStr> needs = guestNeedsParse(item->paramGet("needs"));
			if (needs.empty())
			{
				// Backward-compatible content fallback while catalogues migrate.
				needs = guestNeedsParse(item->paramGet("needslottype"));
			}
			fsS32 visitMs = item->paramGet("visitms").toS32();
			fsS32 needIntervalMs = item->paramGet("needintervalms").toS32();
			if (visitMs <= 0)
			{
				visitMs = 45000;
			}
			if (needIntervalMs <= 0)
			{
				needIntervalMs = 8000;
			}
			const fsS32 arrivalWeight = item->paramGet("arrivalweight").toS32();
			const fsS32 partySize = item->paramGet("partysize").toS32();
			mSim->guestTemplateAdd(item->nameGet(), needs,
			                       item->paramGet("spend").toS32(),
			                       item->paramGet("patiencems").toS32(),
			                       visitMs, needIntervalMs,
			                       arrivalWeight > 0 ? arrivalWeight : 1,
			                       partySize > 0 ? partySize : 1);
		}
	}
}

void gfCParkLevelComponent::dayAdvance()
{
	if (mDayIndex < mNumDays)
	{
		++mDayIndex;
		daySimBegin();
		// New day rolled in - persist so Continue resumes on the right day.
		progressPersist();
	}
}

void gfCParkLevelComponent::scrollRefresh(fsNTileMap::fsCView* const pView)
{
	if (!pView)
	{
		return;
	}
	const fsPoint scrollPixel = pView->scrollPixelGet();
	if (scrollPixel == mLastScrollPixel)
	{
		return;
	}

	// Guests/staff keep walking on their own, so shift by the delta rather
	// than recompute from a fixed anchor like scrollTrackedRefresh does.
	const fsVec2d delta(static_cast<fsF32>(scrollPixel.x - mLastScrollPixel.x),
	                    static_cast<fsF32>(scrollPixel.y - mLastScrollPixel.y));
	mLastScrollPixel = scrollPixel;

	scrollTrackedRefresh(pView);
	for (const fsPoint& cell : mClearedCells)
	{
		clearedCellApply(pView, cell.x, cell.y);
	}
	if (auto* const guests = parentGet()->firstComponentOfFamilyType<gfCParkGuestViewComponent>())
	{
		guests->scrollShift(delta);
	}
	if (auto* const staff = parentGet()->firstComponentOfFamilyType<gfCParkStaffViewComponent>())
	{
		staff->scrollShift(delta);
	}
}

void gfCParkLevelComponent::updateDo(fsS32 pDeltaMs)
{
	// Fallback poll - the lens calls scrollRefresh directly, same tick.
	scrollRefresh(mView);

	// Day over and summary up - freeze the sim rather than running it on behind
	// the summary (which drove the timer negative).
	if (mDayEndShown)
	{
		return;
	}

	mSim->tick(pDeltaMs);

	// Periodic autosave so a mid-day quit resumes where it left off (desktop
	// window-close fires no save hook at all).
	mAutosaveTimerMs += pDeltaMs;
	if (mAutosaveTimerMs >= gAutosaveIntervalMs)
	{
		mAutosaveTimerMs = 0;
		progressPersist();
	}

	mDayRemainingMs -= pDeltaMs;
	if (mDayRemainingMs <= 0)
	{
		// Clamped so the HUD reads 0 rather than a growing negative.
		mDayRemainingMs = 0;
		mDayEndShown = true;

		// Payroll off the day's takings before scoring, shown on the summary.
		// Clamped at zero - no debt.
		mLastDayWages = dailyWagesGet();
		if (mLastDayWages > 0)
		{
			const fsS32 remaining = mSim->economyGet().coinsGet() - mLastDayWages;
			mSim->economyGet().coinsSet(remaining > 0 ? remaining : 0);
		}
		reputationSettle();
		parentGet()->childAdd(fsIGuiComponent::guiCreateFromFile(fsCResourceName(
			fsCAppCoreMain::instanceGet()->settingsGet()->strGet("endOfDaySummary"),
			fsCResourceName::eRES_LOCATION_ASSETS)));

		// Day's final coins/wages are now settled - persist the end-of-day state.
		progressPersist();
	}
}

void gfCParkLevelComponent::listenersRegisterDo()
{
	fsIMessageListener::listenersRegisterDo();
	fsIInputManager::instanceGet()->listenerRegister(fsIInputManager::mTypedCharMsg, this);
}

void gfCParkLevelComponent::listenersDeregisterDo()
{
	fsIMessageListener::listenersDeregisterDo();
	fsIInputManager::instanceGet()->listenerDeregister(fsIInputManager::mTypedCharMsg, this);
}

fsBool gfCParkLevelComponent::messageProcessDo(const fsCUniqueId& pMessageType,
                                               const fsIMessageDispatcher::sMessageParameters& pParam)
{
	if (pMessageType != fsIInputManager::mTypedCharMsg)
	{
		return false;
	}

	// Same keys/multipliers as gfCHogLevelComponent. timeStepSet() drives both
	// the app timer and the hardware scale, so sim and animation stay in sync.
	const fsS32 typedChar = static_cast<const fsIInputManager::sKeyboardMsgParam&>(pParam).mKey;
	if ('1' == typedChar)
	{
		fsCAppCoreMain::instanceGet()->timeStepSet(1.0f);
		return true;
	}
	if ('2' == typedChar)
	{
		fsCAppCoreMain::instanceGet()->timeStepSet(4.0f);
		return true;
	}
	if ('3' == typedChar)
	{
		fsCAppCoreMain::instanceGet()->timeStepSet(8.0f);
		return true;
	}

	return false;
}

void gfCParkLevelComponent::progressSave() const
{
	fsCUserSavedData* const userData = fsCProfileManager::instanceGet()->userSavedDataGet();
	userData->s32Set(gfCTimeUserSavedData::mParkDayIndex, mDayIndex);
	userData->s32Set(gfCTimeUserSavedData::mDayRemainingMs, mDayRemainingMs);
	userData->s32Set(gfCTimeUserSavedData::mDayCoins, mSim->economyGet().coinsGet());
	userData->s32Set(gfCTimeUserSavedData::mDayHappyVisitors,
	                 mSim->economyGet().happyCountGet());
	userData->s32Set(gfCTimeUserSavedData::mDayUnhappyVisitors,
	                 mSim->economyGet().unhappyCountGet());
	userData->s32Set(gfCTimeUserSavedData::mDayServicesPurchased,
	                 mSim->economyGet().servicesPurchasedCountGet());
	userData->s32Set(gfCTimeUserSavedData::mDaySatisfactionTotal,
	                 mSim->economyGet().satisfactionTotalGet());
	userData->s32Set(gfCTimeUserSavedData::mParkReputation, mParkReputation);
	userData->s32Set(gfCTimeUserSavedData::mParkReputationSettledDay,
	                 mReputationSettledDay);

	// Ownership (kept outside the per-day sim) - persist it too, else Continue
	// rebuilds the day but the park is empty of everything the player bought.
	userData->s32Set(gfCTimeUserSavedData::mParkOwnedSlotCount, static_cast<fsS32>(mPurchasedSlots.size()));
	for (fsS32 i = 0; i < static_cast<fsS32>(mPurchasedSlots.size()); ++i)
	{
		const SOwnedSlot& slot = mPurchasedSlots[i];
		userData->strSet(ownedSlotKey(i, "Name"), slot.mName);
		userData->s32Set(ownedSlotKey(i, "ServiceMs"), slot.mServiceTimeMs);
		userData->s32Set(ownedSlotKey(i, "QueueLen"), slot.mMaxQueueLength);
		userData->strSet(ownedSlotKey(i, "Image"), slot.mBuildingImage);
		userData->s32Set(ownedSlotKey(i, "Runtime"), slot.mRuntime ? 1 : 0);
		userData->strSet(ownedSlotKey(i, "ServiceType"), slot.mServiceType);
		userData->s32Set(ownedSlotKey(i, "X"), slot.mLocalX);
		userData->s32Set(ownedSlotKey(i, "Y"), slot.mLocalY);
		userData->s32Set(ownedSlotKey(i, "DrawWidth"), slot.mDrawWidth);
		userData->s32Set(ownedSlotKey(i, "FootprintColumns"), slot.mFootprintColumns);
		userData->s32Set(ownedSlotKey(i, "FootprintRows"), slot.mFootprintRows);
		userData->s32Set(ownedSlotKey(i, "VisitorQuota"), slot.mVisitorQuota);
		userData->s32Set(ownedSlotKey(i, "VisitorAppeal"), slot.mVisitorAppeal);
		userData->s32Set(ownedSlotKey(i, "PurchaseCost"), slot.mPurchaseCost);
	}

	userData->s32Set(gfCTimeUserSavedData::mParkHiredStaffCount, static_cast<fsS32>(mHiredStaff.size()));
	for (fsS32 i = 0; i < static_cast<fsS32>(mHiredStaff.size()); ++i)
	{
		const SHiredStaff& hired = mHiredStaff[i];
		userData->strSet(hiredStaffKey(i, "Type"), hired.mType);
		userData->s32Set(hiredStaffKey(i, "Wage"), hired.mWage);
	}

	userData->s32Set(gfCTimeUserSavedData::mParkDeployedSlotCount, static_cast<fsS32>(mDeployedSlots.size()));
	for (fsS32 i = 0; i < static_cast<fsS32>(mDeployedSlots.size()); ++i)
	{
		userData->strSet(deployedSlotKey(i), mDeployedSlots[i].mSlotName);
		userData->strSet(deployedSlotKey(i) + "Type", mDeployedSlots[i].mType);
	}

	userData->s32Set(gfCTimeUserSavedData::mParkDecorationCount, static_cast<fsS32>(mOwnedDecorations.size()));
	for (fsS32 i = 0; i < static_cast<fsS32>(mOwnedDecorations.size()); ++i)
	{
		const SOwnedDecoration& decoration = mOwnedDecorations[i];
		userData->strSet(decorationKey(i, "Image"), decoration.mImage);
		userData->s32Set(decorationKey(i, "DrawWidth"), decoration.mDrawWidth);
		userData->s32Set(decorationKey(i, "FootprintColumns"), decoration.mFootprintColumns);
		userData->s32Set(decorationKey(i, "FootprintRows"), decoration.mFootprintRows);
		userData->s32Set(decorationKey(i, "X"), decoration.mLocalX);
		userData->s32Set(decorationKey(i, "Y"), decoration.mLocalY);
		userData->s32Set(decorationKey(i, "VisitorAppeal"), decoration.mVisitorAppeal);
		userData->s32Set(decorationKey(i, "VisitorComfort"), decoration.mVisitorComfort);
	}

	userData->s32Set(gfCTimeUserSavedData::mParkClearedCellCount,
	                 static_cast<fsS32>(mClearedCells.size()));
	for (fsS32 i = 0; i < static_cast<fsS32>(mClearedCells.size()); ++i)
	{
		userData->s32Set(clearedCellKey(i, "Col"), mClearedCells[i].x);
		userData->s32Set(clearedCellKey(i, "Row"), mClearedCells[i].y);
	}
}

void gfCParkLevelComponent::progressPersist()
{
	progressSave();
	// Actually write the profile file - progressSave only touched the in-memory
	// table. mCurrentLocation (set when the level loaded) rides along in the same
	// table, so this is also what makes Continue find a level to load at all.
	fsCProfileManager::instanceGet()->allDataSave(/*pIsAutoSave*/ true);
}

void gfCParkLevelComponent::ownershipRestore(fsCUserSavedData* const pUserData)
{
	// Rebuilt from disk, so start clean rather than appending to whatever a
	// prior in-session state left behind.
	mPurchasedSlots.clear();
	mHiredStaff.clear();
	mDeployedSlots.clear();
	mOwnedDecorations.clear();
	mClearedCells.clear();
	mRuntimeSlotSequence = 0;
	mParkReputation = pUserData->s32GetWithDefault(
		gfCTimeUserSavedData::mParkReputation, 50);
	mReputationSettledDay = pUserData->s32GetWithDefault(
		gfCTimeUserSavedData::mParkReputationSettledDay, 0);

	const fsS32 slotCount = pUserData->s32GetWithDefault(gfCTimeUserSavedData::mParkOwnedSlotCount, 0);
	for (fsS32 i = 0; i < slotCount; ++i)
	{
		SOwnedSlot owned;
		owned.mName = pUserData->strGet(ownedSlotKey(i, "Name"));
		owned.mServiceTimeMs = pUserData->s32Get(ownedSlotKey(i, "ServiceMs"));
		owned.mMaxQueueLength = pUserData->s32Get(ownedSlotKey(i, "QueueLen"));
		owned.mBuildingImage = pUserData->strGet(ownedSlotKey(i, "Image"));
		owned.mRuntime = 0 != pUserData->s32GetWithDefault(ownedSlotKey(i, "Runtime"), 0);
		owned.mServiceType = pUserData->strGet(ownedSlotKey(i, "ServiceType"));
		owned.mLocalX = pUserData->s32GetWithDefault(ownedSlotKey(i, "X"), 0);
		owned.mLocalY = pUserData->s32GetWithDefault(ownedSlotKey(i, "Y"), 0);
		owned.mDrawWidth = pUserData->s32GetWithDefault(
			ownedSlotKey(i, "DrawWidth"), gServiceBuildingDefaultWidth);
		owned.mFootprintColumns = pUserData->s32GetWithDefault(
			ownedSlotKey(i, "FootprintColumns"), 1);
		owned.mFootprintRows = pUserData->s32GetWithDefault(
			ownedSlotKey(i, "FootprintRows"), 1);
		owned.mVisitorQuota = pUserData->s32GetWithDefault(
			ownedSlotKey(i, "VisitorQuota"), 0);
		owned.mVisitorAppeal = pUserData->s32GetWithDefault(
			ownedSlotKey(i, "VisitorAppeal"), 0);
		owned.mPurchaseCost = pUserData->s32GetWithDefault(ownedSlotKey(i, "PurchaseCost"), -1);
		if (owned.mRuntime)
		{
			++mRuntimeSlotSequence;
		}
		mPurchasedSlots.push_back(owned);
	}

	const fsS32 staffCount = pUserData->s32GetWithDefault(gfCTimeUserSavedData::mParkHiredStaffCount, 0);
	for (fsS32 i = 0; i < staffCount; ++i)
	{
		SHiredStaff hired;
		hired.mType = pUserData->strGet(hiredStaffKey(i, "Type"));
		hired.mWage = pUserData->s32Get(hiredStaffKey(i, "Wage"));
		mHiredStaff.push_back(hired);
	}

	const fsS32 deployedCount = pUserData->s32GetWithDefault(gfCTimeUserSavedData::mParkDeployedSlotCount, 0);
	for (fsS32 i = 0; i < deployedCount; ++i)
	{
		const fsStr type = pUserData->strGet(deployedSlotKey(i) + "Type");
		mDeployedSlots.push_back({pUserData->strGet(deployedSlotKey(i)),
			type.emptyGet() ? gfCParkDaySim::mStaffTypeKiosk : type});
	}

	const fsS32 decorationCount = pUserData->s32GetWithDefault(gfCTimeUserSavedData::mParkDecorationCount, 0);
	for (fsS32 i = 0; i < decorationCount; ++i)
	{
		SOwnedDecoration owned;
		owned.mImage = pUserData->strGet(decorationKey(i, "Image"));
		owned.mDrawWidth = pUserData->s32GetWithDefault(
			decorationKey(i, "DrawWidth"), 0);
		owned.mFootprintColumns = pUserData->s32GetWithDefault(
			decorationKey(i, "FootprintColumns"), 1);
		owned.mFootprintRows = pUserData->s32GetWithDefault(
			decorationKey(i, "FootprintRows"), 1);
		owned.mLocalX = pUserData->s32Get(decorationKey(i, "X"));
		owned.mLocalY = pUserData->s32Get(decorationKey(i, "Y"));
		owned.mVisitorAppeal = pUserData->s32GetWithDefault(
			decorationKey(i, "VisitorAppeal"), 0);
		owned.mVisitorComfort = pUserData->s32GetWithDefault(
			decorationKey(i, "VisitorComfort"), 0);
		mOwnedDecorations.push_back(owned);
	}

	const fsS32 clearedCount = pUserData->s32GetWithDefault(
		gfCTimeUserSavedData::mParkClearedCellCount, 0);
	for (fsS32 i = 0; i < clearedCount; ++i)
	{
		mClearedCells.push_back(fsPoint(
			pUserData->s32Get(clearedCellKey(i, "Col")),
			pUserData->s32Get(clearedCellKey(i, "Row"))));
	}
}

void gfCParkLevelComponent::progressRestore()
{
	fsCUserSavedData* const userData = fsCProfileManager::instanceGet()->userSavedDataGet();
	if (userData->keyExistsGet(gfCTimeUserSavedData::mParkDayIndex))
	{
		mDayIndex = userData->s32Get(gfCTimeUserSavedData::mParkDayIndex);
	}

	// Must precede daySimBegin(): its re-apply loops unlock/staff the fresh sim
	// from exactly these three collections, so they have to be populated first.
	ownershipRestore(userData);

	daySimBegin();

	if (userData->keyExistsGet(gfCTimeUserSavedData::mDayRemainingMs))
	{
		mDayRemainingMs = userData->s32Get(gfCTimeUserSavedData::mDayRemainingMs);
	}
	mSim->economyGet().progressSet(
		userData->s32GetWithDefault(gfCTimeUserSavedData::mDayCoins,
		                            mSim->economyGet().coinsGet()),
		userData->s32GetWithDefault(gfCTimeUserSavedData::mDayHappyVisitors, 0),
		userData->s32GetWithDefault(gfCTimeUserSavedData::mDayUnhappyVisitors, 0),
		userData->s32GetWithDefault(gfCTimeUserSavedData::mDayServicesPurchased, 0),
		userData->s32GetWithDefault(gfCTimeUserSavedData::mDaySatisfactionTotal, 0));
}

fsIComponent* const gfCParkLevelComponent::create(fsCEntity* const pParent)
{
	return new gfCParkLevelComponent(pParent);
}

gfCParkLevelComponent::gfCParkLevelComponent(fsCEntity* const pParent):
fsIMessageListenerComponent(pParent),
mDayIndex(1),
mDayRemainingMs(0),
mDayEndShown(false),
mAutosaveTimerMs(0),
mForestLayerId(-1),
mLastDayWages(0),
mParkReputation(50),
mReputationSettledDay(0),
mRepairArmed(false),
mRuntimeSlotSequence(0),
mView(nullptr),
mLastScrollPixel(0, 0)
{
}

gfCParkLevelComponent::~gfCParkLevelComponent()
{
}