wangguan
2020-11-11 6f32c1848f141eb7c4b2fe32875b2dfde5f5226c
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
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
using System.Globalization;
using Core.Health;
using Core.Input;
using Core.Utilities;
using DG.Tweening;
using JetBrains.Annotations;
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using TowerDefense.Level;
using TowerDefense.Towers;
using TowerDefense.Towers.Placement;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using TowerDefense.Nodes;
using TowerDefense.Affectors;
using KTGMGemClient;
 
namespace TowerDefense.UI.HUD
{
    /// <summary>
    /// An object that manages user interaction with the game. Its responsibilities deal with
    /// <list type="bullet">
    ///     <item>
    ///         <description>Building towers</description>
    ///     </item>
    ///     <item>
    ///         <description>Selecting towers and units</description>
    ///     </item>
    /// </list>
    /// </summary>
    [RequireComponent(typeof(Camera))]
    public class EndlessGameUI : Singleton<EndlessGameUI>
    {
        /// <summary>
        /// The states the UI can be in
        /// </summary>
        public enum State
        {
            /// <summary>
            /// The game is in its normal state. Here the player can pan the camera, select units and towers
            /// </summary>
            Normal,
 
            /// <summary>
            /// The game is in 'build mode'. Here the player can pan the camera, confirm or deny placement
            /// </summary>
            Building,
 
            /// <summary>
            /// The game is Paused. Here, the player can restart the level, or quit to the main menu
            /// </summary>
            Paused,
 
            /// <summary>
            /// The game is over and the level was failed/completed
            /// </summary>
            GameOver,
 
            /// <summary>
            /// The game is in 'build mode' and the player is dragging the ghost tower
            /// </summary>
            BuildingWithDrag
        }
 
        /// <summary>
        /// Gets the current UI state
        /// </summary>
        public State state { get; private set; }
 
        /// <summary>
        /// The currently selected tower
        /// </summary>
        public LayerMask placementAreaMask;
 
        /// <summary>
        /// 兵线层对应的Mask.
        /// </summary>
        public LayerMask waveLineMask;
 
        /// <summary>
        /// 战场区域Mask.
        /// </summary>
        public LayerMask battleAreaMask;
 
        /// <summary>
        /// The layer for tower selection
        /// </summary>
        public LayerMask towerSelectionLayer;
 
        /// <summary>
        /// The physics layer for moving the ghost around the world
        /// when the placement is not valid
        /// </summary>
        public LayerMask ghostWorldPlacementMask;
 
        public readonly int MAX_TOWERNUM = 20;
 
        /// <summary>
        /// The radius of the sphere cast 
        /// for checking ghost placement
        /// </summary>
        public float sphereCastRadius = 1;
 
        /// <summary>
        /// 随机购买塔防的按钮.
        /// </summary>
        public Button randomTowerBtn;
 
        /// <summary>
        /// 飘血数字对应的prefab.
        /// </summary>
        public TextMoveDoTween bloodText;
 
        /// <summary>
        /// 中毒飘字.
        /// </summary>
        public TextMoveDoTween bloodPoison;
 
        /// <summary>
        /// 暴击飘字.
        /// </summary>
        public TextMoveDoTween bloodCrit;
 
        /// <summary>
        /// 购买塔防按钮上的Text.
        /// </summary>
        protected TextMeshProUGUI towerPriceText;
 
        protected bool tdBuyDisable = false;
 
        /// <summary>
        /// 鼠标在移动一个Tower之前,要隐藏的Tower数据和指针。
        /// </summary>
        protected Tower towerToMove = null;
 
        /// <summary>
        /// Fires when the <see cref="State"/> changes
        /// should only allow firing when TouchUI is used
        /// </summary>
        public event Action<State, State> stateChanged;
 
        /// <summary>
        /// Fires off when the ghost was previously not valid but now is due to currency amount change
        /// </summary>
        public event Action ghostBecameValid;
 
        /// <summary>
        /// Fires when a tower is selected/deselected
        /// </summary>
        public event Action<Tower> selectionChanged;
 
        /// <summary>
        /// 成长骰子对应的Timer.
        /// </summary>
        protected List<Timer> listTowerTimer = new List<Timer>();
 
        protected Dictionary<int, Tower> towerTimeDic = new Dictionary<int, Tower>();
 
        /// <summary>
        /// Placement area ghost tower is currently on
        /// </summary>
        IPlacementArea m_CurrentArea;
 
        /// <summary>
        /// Grid position ghost tower in on
        /// </summary>
        IntVector2 m_GridPosition;
 
        /// <summary>
        /// Our cached camera reference
        /// </summary>
        Camera m_Camera;
 
        /// <summary>
        /// Current tower placeholder. Will be null if not in the <see cref="State.Building" /> state.
        /// </summary>
        TowerPlacementGhost m_CurrentTower;
 
        public bool HasTower{
            get{
                return m_CurrentTower!=null;
            }
        }
 
        // TowerList用于简单记录相关的数据
        protected List<Tower> m_listTower = new List<Tower>();
 
        /// <summary>
        /// Tracks if the ghost is in a valid location and the player can afford it
        /// </summary>
        bool m_GhostPlacementPossible;
 
        /// <summary>
        /// Gets the current selected tower
        /// </summary>
        public Tower currentSelectedTower { get; private set; }
 
        /// <summary>
        /// 拖动塔防时,原塔防的等级。
        /// </summary>
        protected int dragTowerLevel = 0;
 
        /// <summary>
        /// 选中Tower时候的鼠标点击坐标与Tower中心所在的屏幕坐标之间的偏移值.
        /// </summary>
        protected Vector2 selTowerOffset = new Vector2();
 
        // 测试屏幕显示相关的倒计时.
        protected bool bLoaded = false;
 
        private Timer overTimer;
 
        /// <summary>
        /// 总兵线数
        /// </summary>
        public int TotalWaveLines { get; } = 5;
 
        public IntVector2 currentGrid
        {
            get { return m_GridPosition; }
        }
 
        /// <summary>
        /// Gets whether a tower has been selected
        /// </summary>
        public bool isTowerSelected
        {
            get { return currentSelectedTower != null; }
        }
 
        /// <summary>
        /// 攻击塔位占的行数
        /// </summary>
        public int AttackRowNumbers { get; set; } = 2;
 
        /// <summary>
        /// 所有攻击塔位的摧毁信息,是否被摧毁,默认全部没有被摧毁
        /// </summary>
        private bool[,] TowerDestroyArr;
 
        public event Action GameOverEvent;
 
        /// <summary>
        /// 塔升级特效预制体
        /// </summary>
        public GameObject TowerUpgradeEffectPrefab;
 
        /// <summary>
        /// 宝石出现特效预制体
        /// </summary>
        public GameObject TowerAppearEffectPrefab;
 
        /// <summary>
        /// 保存所有生成或合成的塔的最小等级,索引0 -> 火木水塔 索引1 -> 技能塔
        /// </summary>
        /// <value></value>
        public int MinLevel;
 
        public IPlacementArea selfTowerPlaceArea
        {
            get
            {
                if (m_CurrentArea == null)
                {
                    GameObject placeObj = GameObject.FindGameObjectWithTag("PlaceTower");
                    if (placeObj != null)
                        m_CurrentArea = placeObj.GetComponent<IPlacementArea>();
                }
                return m_CurrentArea;
            }
        }
 
        private void UpdateMinLevelArr()
        {
            int min = -1;
 
            for (int i = 0; i < m_listTower.Count; ++i)
            {
                if (min == -1 || m_listTower[i].currentLevel < min)
                    min = m_listTower[i].currentLevel;
            }
 
            MinLevel = Mathf.Max(min, 0);
        }
 
        /// <summary>
        /// 增加一个防塔的数据结构,测试数据
        /// </summary>
        /// <param name="t"></param>
        public void addTower(Tower t)
        {
            m_listTower.Add(t);
            UpdateMinLevelArr();
 
            // 当前所在的位置是否攻击位置,随手瞎写:2 或者 3也就是前两排是上阵的
            if (t.gridPosition.y >= 2)
                t.bInAttackMode = true;
 
            // ATTENTION TO FIX: 先写死,有一个简单的逻辑再说:
            if (m_listTower.Count >= MAX_TOWERNUM)
                disableRandomTowerBtn();
        }
 
        /// <summary>
        /// 根据塔位索引位置,查找位置上是否有对应的塔防数据。
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public Tower FindTowerWithGridIdx(int x, int y)
        {
            foreach (Tower lt in m_listTower)
            {
                if ((lt.gridPosition.x == x) && (lt.gridPosition.y == y))
                    return lt;
            }
            return null;
        }
 
        public bool towerInList(Tower t)
        {
            return m_listTower.Contains(t);
        }
 
        /// <summary>
        /// 设置已经上阵的所有塔的攻击状态,是否可以攻击
        /// </summary>
        /// <param name="canAttack"></param>
        public void SetAttackingTowerState(bool canAttack)
        {
            foreach (Tower tower in m_listTower)
            {
                tower.bInAttackMode = canAttack;
            }
        }
 
        public void delTower(Tower t)
        {
            // 删除Tower有可能对应的Timer.
            foreach (var tdata in towerTimeDic)
            {
                if (tdata.Value == t)
                {
                    // 先删除对应的timer数据:
                    foreach (var timer in listTowerTimer)
                    {
                        if (tdata.Key == timer.timerID)
                        {
                            listTowerTimer.Remove(timer);
                            break;
                        }
                    }
 
                    // 删除字典并退出:
                    towerTimeDic.Remove(tdata.Key);
                    break;
                }
            }
 
 
            int tcnt = m_listTower.Count;
            m_listTower.Remove(t);
            if (tcnt == MAX_TOWERNUM)
                enableRandomTowerBtn();
        }
 
        /// <summary>
        /// 清空缓存数据
        /// </summary>
        public void restartLevel()
        {
            m_listTower.Clear();
            listTowerTimer.Clear();
            towerTimeDic.Clear();
        }
 
        /// <summary>
        /// 查找相同类型,相同段位的Tower
        /// </summary>
        /// <param name="t"></param>
        public Tower findSameLvlTower(Tower t)
        {
            Tower rest = null;
 
            foreach (Tower lt in m_listTower)
            {
                if (lt == t) continue;
                if ((lt.currentLevel == t.currentLevel) &&
                    (lt.towerName == t.towerName))
                {
                    return lt;
                }
            }
            return rest;
        }
 
        /// <summary>
        /// Gets whether certain build operations are valid
        /// </summary>
        public bool isBuilding
        {
            get
            {
                return state == State.Building || state == State.BuildingWithDrag;
            }
        }
 
        /// <summary>
        /// Cancel placing the ghost
        /// </summary>
        public void CancelGhostPlacement()
        {
            if (m_CurrentTower)
                Destroy(m_CurrentTower.gameObject);
            m_CurrentTower = null;
            SetState(State.Normal);
            DeselectTower();
        }
 
        /// <summary>
        /// Returns the GameUI to dragging mode with the curent tower
        /// </summary>
        /// /// <exception cref="InvalidOperationException">
        /// Throws exception when not in build mode
        /// </exception>
        public void ChangeToDragMode()
        {
            if (!isBuilding)
            {
                throw new InvalidOperationException("Trying to return to Build With Dragging Mode when not in Build Mode");
            }
            SetState(State.BuildingWithDrag);
        }
 
        /// <summary>
        /// Returns the GameUI to BuildMode with the current tower
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Throws exception when not in Drag mode
        /// </exception>
        public void ReturnToBuildMode()
        {
            if (!isBuilding)
            {
                throw new InvalidOperationException("Trying to return to Build Mode when not in Drag Mode");
            }
            SetState(State.Building);
        }
 
        /// <summary>
        /// Changes the state and fires <see cref="stateChanged"/>
        /// </summary>
        /// <param name="newState">The state to change to</param>
        /// <exception cref="ArgumentOutOfRangeException">thrown on an invalid state</exception>
        void SetState(State newState)
        {
            if (state == newState)
            {
                return;
            }
            State oldState = state;
            if (oldState == State.Paused || oldState == State.GameOver)
            {
                Time.timeScale = 1f;
            }
 
            switch (newState)
            {
                case State.Normal:
                    break;
                case State.Building:
                    break;
                case State.BuildingWithDrag:
                    break;
                case State.Paused:
                case State.GameOver:
                    if (oldState == State.Building)
                        CancelGhostPlacement();
                    Time.timeScale = 1f;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("newState", newState, null);
            }
            state = newState;
            if (stateChanged != null)
            {
                stateChanged(oldState, state);
            }
        }
 
        /// <summary>
        /// Called when the game is over
        /// </summary>
        public void GameOver()
        {
            SetState(State.GameOver);
        }
 
        /// <summary>
        /// Pause the game and display the pause menu
        /// </summary>
        public void Pause()
        {
            SetState(State.Paused);
        }
 
        /// <summary>
        /// Resume the game and close the pause menu
        /// </summary>
        public void Unpause()
        {
            SetState(State.Normal);
        }
 
        /// <summary>
        /// Changes the mode to drag
        /// </summary>
        /// <param name="towerToBuild">
        /// The tower to build
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// Throws exception when trying to change to Drag mode when not in Normal Mode
        /// </exception>
        public void SetToDragMode([NotNull] Tower towerToBuild)
        {
            if (state != State.Normal)
            {
                throw new InvalidOperationException("Trying to enter drag mode when not in Normal mode");
            }
 
            if (m_CurrentTower != null)
            {
                // Destroy current ghost
                CancelGhostPlacement();
            }
            SetUpGhostTower(towerToBuild);
            SetState(State.BuildingWithDrag);
        }
 
        /// <summary>
        /// 点击某一个塔防之后,开启拖动塔防的模式。
        /// River: 修改为暂不删除原来的Tower,把原来的Tower隐藏掉.
        /// </summary>
        /// <param name="towerOld"></param>
        public void startDragTower(Tower towerOld)
        {
            Tower newT = null;
            foreach (Tower tower in EndlessLevelManager.instance.TowerLibrary)
            {
                if (tower.towerName != towerOld.towerName)
                    continue;
 
                newT = Instantiate(tower, transform);
                break;
            }
 
            // 从列表中删除Tower.并破坏Tower的外形。
            dragTowerLevel = towerOld.currentLevel;
            // 尝试不再删除原来的Tower,而是尝试在合成成功后再删除原来的Tower
            towerOld.showTower(false);
            towerToMove = towerOld;
 
            // 先删除,再设置移动相关。
            SetToDragMode(newT);
 
            if (towerOld.towerFeature == EFeatureTower.Skill_Bomb)
                m_CurrentTower.SetAttackArea(dragTowerLevel, towerOld.attributeId);
        }
 
        /// <summary>
        /// Sets the UI into a build state for a given tower
        /// River: 当界面上某一个塔防的按钮被按下后,需要调用的这个函数进入建造模式。
        /// </summary>
        /// <param name="towerToBuild">
        /// The tower to build
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// Throws exception trying to enter Build Mode when not in Normal Mode
        /// </exception>
        public void SetToBuildMode([NotNull] Tower towerToBuild)
        {
            if (state != State.Normal)
            {
                throw new InvalidOperationException("Trying to enter Build mode when not in Normal mode");
            }
 
            if (m_CurrentTower != null)
            {
                // Destroy current ghost
                CancelGhostPlacement();
            }
            SetUpGhostTower(towerToBuild);
            SetState(State.Building);
        }
 
        /// <summary>
        /// 目标位置是否是可攻击属性的空塔位
        /// </summary>
        /// <param name="pinfo"></param>
        /// <returns></returns>
        protected bool isFreeAttackGrid(PointerInfo pinfo)
        {
            // 判断格子上的塔防:
            UIPointer pointer = WrapPointer(pinfo);
            Tower sTower = PickTowerInGrid(pointer);
            if (sTower != null)
            {
                return false;
            }
 
            if ((m_GridPosition.x >= 0) && (m_GridPosition.y >= 0))
            {
                if (m_CurrentArea.isFreeAtackPos(m_GridPosition.x, m_GridPosition.y))
                {
                    return true;
                }
            }
 
            return false;
        }
 
        /// <summary>
        /// 是否是可开启的AttackGrid塔位.
        /// </summary>
        /// <param name="pinfo"></param>
        /// <returns></returns>
        protected bool isWaitBuyAttackGrid(PointerInfo pinfo)
        {
            // 判断格子上的塔防:
            UIPointer pointer = WrapPointer(pinfo);
            Tower sTower = PickTowerInGrid(pointer);
            if (sTower != null)
                return false;
 
            if ((m_GridPosition.x >= 0) && (m_GridPosition.y >= 0))
            {
                if (m_CurrentArea.isWaitBuyGrid(m_GridPosition.x, m_GridPosition.y))
                    return true;
            }
 
            return false;
        }
 
        /// <summary>
        /// 目标位置是否有同等级同类型的Tower.
        /// </summary>
        /// <param name="pinfo"></param>
        /// <returns></returns>
        protected bool isValidateCombineTarget(PointerInfo pinfo)
        {
            // 判断是否格子上重复放置塔防
            if (!m_CurrentTower || !IsGhostAtValidPosition())
            {
                // 最大级别的Tower不能再合并了.
                if (towerToMove.isAtMaxLevel)
                    return false;
 
                // 判断格子上的塔防:
                UIPointer pointer = WrapPointer(pinfo);
                Tower sTower = PickTowerInGrid(pointer);
                if (sTower && sTower != towerToMove)
                {
                    int testLvl = dragTowerLevel;
 
                    if (towerToMove && sTower.currentLevel == testLvl && sTower.towerName == towerToMove.towerName)
                        return true;
                }
            }
            return false;
        }
 
        /// <summary>
        /// 判断是否有不同类型的Tower,可以发生置换,仅限于火木水之间发生
        /// </summary>
        /// <param name="pinfo"></param>
        /// <returns></returns>
        protected bool IsSubstitute(PointerInfo pinfo)
        {
            if (!m_CurrentTower || !IsGhostAtValidPosition())
            {
                // 判断格子上的塔防:
                UIPointer pointer = WrapPointer(pinfo);
                Tower sTower = PickTowerInGrid(pointer);
 
                if (sTower && sTower != towerToMove)
                {
                    if (towerToMove && sTower.towerFeature == EFeatureTower.NULL && towerToMove.towerFeature == EFeatureTower.NULL && sTower.bInAttackMode == towerToMove.bInAttackMode)
                        return true;
                }
            }
 
            return false;
        }
 
        /// <summary>
        /// 获取目标格子上的塔防的名字数据
        /// </summary>
        /// <param name="pinfo"></param>
        /// <returns></returns>
        protected string getTargetTowerName(PointerInfo pinfo)
        {
            if (m_CurrentTower == null || !IsGhostAtValidPosition())
            {
                // 获取目标格子上的塔防指针:
                UIPointer pointer = WrapPointer(pinfo);
                Tower sTower = PickTowerInGrid(pointer);
                if ((sTower != null) && (sTower != towerToMove))
                {
                    return sTower.towerName;
                }
            }
            return "";
        }
 
        /// <summary>
        /// 成长骰子升级为高一级别的随机骰子.
        /// </summary>
        /// <param name="tower"></param>
        protected void growUpTower(Tower tower)
        {
            Tower newTower = EndlessRandomTower.instance.GetRandomTower(false);
 
            // 所有的Tower不能升级成为FeatureTower.
            int maxLoop = 20;
            while (newTower.towerFeature != EFeatureTower.NULL)
            {
                newTower = EndlessRandomTower.instance.GetRandomTower(false);
                maxLoop--;
                if (maxLoop <= 0)
                {
                    newTower = EndlessRandomTower.instance.getRTower();
                    Debug.LogError("超级循环发生了.");
                    break;
                }
            }
 
            // 成长为高一级别的骰子
            DisplaceTower(newTower, tower, 1);
        }
 
        /// <summary>
        /// 破坏某一列的塔位数据
        /// </summary>
        /// <param name="yidx"></param>
        /// <param name="opponent"></param>
        public void DestroyTowerGrid(int xidx)
        {
            // 这里的逻辑已经不走了
            for (int i = 0; i < AttackRowNumbers; ++i)
            {
                if (TowerDestroyArr[xidx, i]) continue;
 
                Node newNode = EndlessLevelManager.instance.SwitchHomeBase(xidx);
                WaveLineAgentInsMgr[] agentInsMgrs = AgentInsManager.instance.GetWaveLineList();
 
                for (int j = 0; j < agentInsMgrs[xidx].listAgent.Count; ++j)
                {
                    agentInsMgrs[xidx].listAgent[j].ChangeNextNode(newNode);
                }
 
                TowerDestroyArr[xidx, i] = true;
                Tower tower = FindTowerWithGridIdx(xidx, 3 - i);
 
                if (tower)
                {
                    delTower(tower);
                    tower.Sell();
                }
 
                if (m_CurrentArea != null)
                    // 3 -> dimensions.y - 1
                    m_CurrentArea.SetDestroyedGrid(xidx, 3 - i);
 
                break;
            }
 
            bool isAllDestroyed = true;
 
            for (int i = 0; i < AttackRowNumbers; ++i)
            {
                if (!TowerDestroyArr[xidx, i])
                {
                    isAllDestroyed = false;
                    break;
                }
            }
 
            // 该兵线的所有基地都被摧毁完毕,目前的逻辑只要有一条兵线两个基地都被摧毁就算游戏结束
            if (isAllDestroyed)
            {
                // 停止所有兵线的出兵
                for (int i = 0; i < TotalWaveLines; ++i)
                {
                    EndlessLevelManager.instance.StopWaveLine(i);
                }
 
                // 让所有兵线上已经生成的所有agent播放一个死亡动画然后销毁
                WaveLineAgentInsMgr[] waveLineAgentIns = AgentInsManager.instance.GetWaveLineList();
 
                for (int i = 0; i < waveLineAgentIns.Length; ++i)
                {
                    while (waveLineAgentIns[i].listAgent.Count > 0)
                    {
                        waveLineAgentIns[i].listAgent[0].PlayDeath();
                    }
                }
 
                GameOver();
                overTimer = new Timer(1.2f, SafelyCallGameOverEvent);
            }
        }
 
        /// <summary>
        /// 爱心数量为0,游戏结束
        /// </summary>
        private void AllHeartLose()
        {
            // 清理技能
            EndlessBossSkillManager.instance.ClearSkillList();
            EndlessBossHPManager.instance.SwitchHP(true);
            EndlessBossHPManager.instance.SetCurrentHP(0);
 
            // 停止所有兵线的出兵
            for (int i = 0; i < TotalWaveLines; ++i)
            {
                EndlessLevelManager.instance.StopWaveLine(i);
            }
 
            // 让所有兵线上已经生成的所有agent播放一个死亡动画然后销毁
            WaveLineAgentInsMgr[] waveLineAgentIns = AgentInsManager.instance.GetWaveLineList();
 
            for (int i = 0; i < waveLineAgentIns.Length; ++i)
            {
                while (waveLineAgentIns[i].listAgent.Count > 0)
                {
                    waveLineAgentIns[i].listAgent[0].PlayDeath();
                }
            }
 
            GameOver();
            overTimer = new Timer(1.2f, SafelyCallGameOverEvent);
        }
 
        private void SafelyCallGameOverEvent()
        {
            if (GameOverEvent != null)
                GameOverEvent();
            overTimer = null;
        }
 
        #region 拖动时候给塔位一个标识
 
        public MeshRenderer temporaryMat;//移动时候的虚像材质
 
        /// <summary>
        /// 查找可以合成的塔
        /// </summary>
        public void CheckAllCanPlace()
        {
            if (m_CurrentTower != null)
            {
                if (m_CurrentTower.controller.towerFeature == EFeatureTower.NULL)
                {
                    List<IntVector2> allTowerP = new List<IntVector2>();
                    List<IntVector2> allPSTowerP = new List<IntVector2>();//需要播放升级动画的
 
                    for (int i = 0; i < m_listTower.Count; i++)
                    {
                        if (m_listTower[i].bInAttackMode && towerToMove && m_listTower[i].currentLevel == dragTowerLevel && m_listTower[i].towerName == towerToMove.towerName)
                        {
                            if (towerToMove.gridPosition != m_listTower[i].gridPosition)
                                //说明可以合成
                                allPSTowerP.Add(m_listTower[i].gridPosition);
                        }
                        else
                        {
                            //把不符合条件的传进去
                            allTowerP.Add(m_listTower[i].gridPosition);
                        }
                    }
 
                (m_CurrentArea as TowerPlacementGridEndless).CheckAllCanPlace(allTowerP);
                    (m_CurrentArea as TowerPlacementGridEndless).PlayPS(allPSTowerP);
                }
                else if (m_CurrentTower.controller.towerFeature == EFeatureTower.Skill_Fire || m_CurrentTower.controller.towerFeature == EFeatureTower.Skill_Bomb)
                {
                    //Debug.Log("需要激活兵线下方绿色标识");
                    EventCenter.Ins.BroadCast((int)KTGMGemClient.EventType.EndlessStartDragSkill, true);
                }
            }
        }
 
        /// <summary>
        /// 关闭所有标识
        /// </summary>
        public void CloseCanPlaceRenderer()
        {
            if (m_CurrentTower && m_CurrentTower.controller && m_CurrentTower.controller.towerFeature == EFeatureTower.Skill_Fire || m_CurrentTower.controller.towerFeature == EFeatureTower.Skill_Bomb)
            {
                EventCenter.Ins.BroadCast((int)KTGMGemClient.EventType.EndlessStartDragSkill, false);
            }
 
            if (m_CurrentArea != null)
                (m_CurrentArea as TowerPlacementGridEndless).CloseCanPlaceRenderer();
            else
            {
                GameObject placeObj = GameObject.FindGameObjectWithTag("PlaceTower");
                if (placeObj != null)
                    (placeObj.GetComponent<IPlacementArea>() as TowerPlacementGridEndless).CloseCanPlaceRenderer();
            }
        }
 
        /// <summary>
        /// 检查符合条件的塔
        /// </summary>
        /// <param name="pointerInfo"></param>
        public void CheckTowerPlace(PointerInfo pointerInfo)
        {
            //return;
            if (m_CurrentArea != null && m_CurrentArea is TowerPlacementGridEndless)
            {
                //下面是为了设置一个虚拟的塔
                if (isFreeAttackGridOnDrag(pointerInfo) && m_CurrentTower.controller.towerFeature == EFeatureTower.NULL)
                {
                    //Debug.Log("得到了一个空的塔位");
 
                    (m_CurrentArea as TowerPlacementGridEndless).CheckCanPlaceUpdate(m_GridPosition.x, m_GridPosition.y, false, "");
                    //if(temporaryMat)
                }
                else if ((m_GridPosition.x >= 0) && (m_GridPosition.y >= 0))
                {
                    if (m_CurrentArea.isFreeAtackPos(m_GridPosition.x, m_GridPosition.y))
                    {
                        (m_CurrentArea as TowerPlacementGridEndless).CheckCanPlaceUpdate(m_GridPosition.x, m_GridPosition.y, true, towerToMove.towerName);
                    }
                    else
                    {
                        (m_CurrentArea as TowerPlacementGridEndless).CloseCanPlace();
                    }
                }
                else
                {
                    (m_CurrentArea as TowerPlacementGridEndless).CloseCanPlace();
                }
            }
            else
            {
                //Debug.Log("什么情况");
                if (m_CurrentTower.controller.towerFeature == EFeatureTower.NULL)
                {
                    dragTowerPlacement.CloseCanPlace();
                }
            }
        }
 
        TowerPlacementGridEndless dragTowerPlacement;
 
        /// <summary>
        /// 目标位置是否是可攻击属性的空塔位
        /// </summary>
        /// <param name="pinfo"></param>
        /// <returns></returns>
        protected bool isFreeAttackGridOnDrag(PointerInfo pinfo)
        {
            // 判断格子上的塔防:
            UIPointer pointer = WrapPointer(pinfo);
            Tower sTower = PickTowerInGrid(pointer);
            if (sTower != null)
            {
                if (sTower.bInAttackMode && towerToMove && sTower.currentLevel == dragTowerLevel && sTower.towerName == towerToMove.towerName)
                {
                    //说明可以合成
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }
 
        #endregion
 
        /// <summary>
        /// 拖动一个Tower之后,松开鼠标或者EndDrag.
        /// 1: 目标点可合成,则直接合成。
        /// 2: 目标点不管是空白,还是不能放置Tower,都要让当前的Tower返回到原来的TowerPlace
        /// </summary>
        /// <param name="pointerInfo"></param>
        public void onEndTowerDrag(PointerInfo pointerInfo)
        {
            bool bSkill = false;
            if (temporaryMat != null)
            {
                //移动虚像隐藏
                temporaryMat.material = null;
            }
 
            if (!m_CurrentTower || !m_CurrentTower.controller)
            {
                CancelPlaceTower(pointerInfo);
                return;
            }
 
            if (m_CurrentTower.controller.towerFeature != EFeatureTower.NULL)
                bSkill = true;
 
            // 判断目标位置是否有Tower且类型和等级一致,如果没有,则GhostTower删除,原Tower显示。
            if (isValidateCombineTarget(pointerInfo))
                TryPlaceTower(pointerInfo);
            else if (isFreeAttackGrid(pointerInfo) && !bSkill)
            {
                if (!TryPlaceTower(pointerInfo, false, true)) return;
 
                // 删除towerToMove,确保塔防数据不再出现多个
                if (towerToMove != null)
                {
                    delTower(towerToMove);
                    towerToMove.showTower(true);
                    towerToMove.Sell();
                    towerToMove = null;
                }
            }
            else if (EndlessLevelManager.instanceExists && IsSubstitute(pointerInfo))
            {
                // 可以发生置换
                UIPointer pointer = WrapPointer(pointerInfo);
                // 格子上的塔
                Tower sTower = PickTowerInGrid(pointer);
 
                if (sTower.bInAttackMode == towerToMove.bInAttackMode)
                {
                    IntVector2 v1 = new IntVector2(towerToMove.gridPosition.x, towerToMove.gridPosition.y);
                    IntVector2 v2 = new IntVector2(sTower.gridPosition.x, sTower.gridPosition.y);
 
                    Tower newTower1 = PlaceTowerForce(EndlessRandomTower.instance.getTowerByName(sTower.towerName), v1, sTower.currentLevel + 1, false);
                    Tower newTower2 = PlaceTowerForce(m_CurrentTower.controller, v2, towerToMove.currentLevel + 1, false);
 
                    if (towerToMove != null)
                    {
                        delTower(towerToMove);
                        towerToMove.showTower(true);
                        towerToMove.Sell();
                        towerToMove = null;
                    }
 
                    delTower(sTower);
                    sTower.showTower(true);
                    sTower.Sell();
                    sTower = null;
 
                    CancelGhostPlacement();
 
                    newTower1.placementArea.Occupy(newTower1.gridPosition, newTower1.dimensions);
                    newTower2.placementArea.Occupy(newTower2.gridPosition, newTower2.dimensions);
                }
            }
            // 当前是Skill塔位的状态.
            else if (bSkill)
            {
                if (SkillPlayEndDrag(pointerInfo))
                {
                    // 先释放掉当前的Ghost塔防.
                    CancelGhostPlacement();
 
                    // 删除towerToMove,确保塔防数据不再出现多个
                    if (towerToMove != null)
                    {
                        delTower(towerToMove);
                        towerToMove.showTower(true);
                        towerToMove.Sell();
                        towerToMove = null;
                    }
                }
                else
                    CancelPlaceTower(pointerInfo);
            }
            else
                CancelPlaceTower(pointerInfo);
        }
 
        /// <summary>
        /// 强制放置塔,主要是用于新手
        /// </summary>
        /// <param name="newTower"></param>
        /// <param name="pos"></param>
        /// <param name="level">塔的等级</param>
        public Tower PlaceTowerForce(Tower newTower, IntVector2 pos, int level, bool playEffect = true)
        {
            TowerPlacementGhost currentTower = Instantiate(newTower.towerGhostPrefab);
            currentTower.Initialize(newTower);
            Tower controller = currentTower.controller;
            Tower createdTower = Instantiate(controller);
            createdTower.PlayWaveLineFlash = playEffect;
            createdTower.Initialize(m_CurrentArea, pos);
            createdTower.SetLevel(level - 1);
 
            if (playEffect)
                PlayUpgradeEffect(createdTower);
 
            addTower(createdTower);
            Destroy(currentTower.gameObject);
 
            return createdTower;
        }
 
        protected bool SkillPlayEndDrag(PointerInfo pointer)
        {
            // 我操,终于可以了!ATTENTION TO OPP:
            PointerInfo tp = new PointerActionInfo();
            tp.currentPosition = pointer.currentPosition;
            tp.previousPosition = pointer.previousPosition;
            tp.delta = pointer.delta;
            tp.startedOverUI = pointer.startedOverUI;
            // River: 调整偏移值,用于鼠标移动塔防的时候,更加平滑。
            tp.currentPosition.x += selTowerOffset.x;
            tp.currentPosition.y += selTowerOffset.y;
            UIPointer npt = new UIPointer
            {
                overUI = false,
                pointer = tp,
                overWaveLine = false,
                ray = m_Camera.ScreenPointToRay(tp.currentPosition)
            };
 
            int sId = towerToMove.attributeId;
            int sLevel = towerToMove.currentLevel;
 
            // 火是列攻击:
            if (m_CurrentTower.controller.towerFeature == EFeatureTower.Skill_Fire)
            {
                WavelineAreaRaycast(ref npt);
                if (npt.overWaveLine)
                {
                    WaveLineSelEffect selEff = npt.wavelineHit.Value.collider.GetComponent<WaveLineSelEffect>();
                    if (selEff)
                    {
                        // 播放特效,并处理伤害.
                        EndlessWaveLineManager.instance.PlayWaveLineEffect(selEff.waveLineId);
                        AgentInsManager.instance.ExecWavelineAttack(selEff.waveLineId, sId, sLevel, false);
                        ++GameConfig.EndlessPortUseSkillTowerCount;
                        return true;
                    }
                }
            }
            // 炸弹是区域攻击显示:
            if (m_CurrentTower.controller.towerFeature == EFeatureTower.Skill_Bomb)
            {
                // 测试代码与战场区域碰撞,碰撞后显示攻击区域:
                BattleAreaRaycast(ref npt);
                if (npt.overWaveLine)
                {
                    EndlessWaveLineManager.instance.PlayBattleAreaBombEffect(npt.wavelineHit.Value.point);
                    AgentInsManager.instance.ExecBombAttack(npt.wavelineHit.Value.point, sId, sLevel, false);
                    return true;
                }
            }
 
            return false;
        }
 
        protected void CancelPlaceTower(PointerInfo pointerInfo)
        {
            CancelGhostPlacement();
 
            if (towerToMove)
            {
                towerToMove.showTower(true);
 
                // 处理复制骰子:
                if (towerToMove.towerFeature == EFeatureTower.CopyCat)
                {
                    CopyTargetTower(pointerInfo);
                }
                else
                {
                    // 升级目标位置的塔防.
                    currentSelectedTower = towerToMove;
                }
                towerToMove = null;
            }
            SetState(State.Normal);
        }
 
        /// <summary>
        /// 处理复制宝石塔防
        /// </summary>
        /// <param name="pointerInfo"></param>
        protected void CopyTargetTower(PointerInfo pointerInfo)
        {
            string tstr = getTargetTowerName(pointerInfo);
            Tower targetTower = null;
            if (tstr.Length > 0)
                targetTower = EndlessRandomTower.instance.getTowerByName(tstr);
 
            currentSelectedTower = towerToMove;
            if (targetTower)
            {
                // 1:记录当前Tower的Level,删除当前的Tower. 
                int towerLvl = currentSelectedTower.currentLevel + 1;
                int posx = currentSelectedTower.gridPosition.x;
                int posy = currentSelectedTower.gridPosition.y;
                currentSelectedTower.Sell();
                delTower(currentSelectedTower);
 
                // 在目标位置放置新的Tower类型,只有零级。
                RandomPlaceTower(targetTower, posx, posy, 0);
            }
        }
 
        /// <summary>
        /// Attempt to position a tower at the given location
        /// </summary>
        /// <param name="pointerInfo">The pointer we're using to position the tower</param>
        public bool TryPlaceTower(PointerInfo pointerInfo, bool force = false, bool zeroCost = false)
        {
            UIPointer pointer = WrapPointer(pointerInfo);
 
            // Do nothing if we're over UI
            if (pointer.overUI && !force)
            {
                Debug.Log("在UI上了,直接返回");
                return false;
            }
 
            BuyTower(pointer, force, zeroCost);
 
            return true;
        }
 
        /// <summary>
        /// 根据鼠标的点击信息来确认当前点击的位置是否有塔防模型。
        /// </summary>
        /// <param name="pointer"></param>
        /// <returns></returns>
        protected Tower PickTowerInGrid(UIPointer pointer)
        {
            RaycastHit output;
            bool hasHit = Physics.Raycast(pointer.ray, out output, float.MaxValue, towerSelectionLayer);
            if (!hasHit || pointer.overUI)
            {
                return null;
            }
            var controller = output.collider.GetComponent<Tower>();
 
            return controller;
        }
 
        /// <summary>
        /// Position the ghost tower at the given pointer
        /// </summary>
        /// <param name="pointerInfo">The pointer we're using to position the tower</param>
        /// <param name="hideWhenInvalid">Optional parameter for configuring if the ghost is hidden when in an invalid location</param>
        public void TryMoveGhost(PointerInfo pointerInfo, bool hideWhenInvalid = true)
        {
            if (m_CurrentTower == null)
            {
                return;
                //throw new InvalidOperationException("Trying to move the tower ghost when we don't have one");
            }
 
            UIPointer pointer = WrapPointer(pointerInfo);
            // Do nothing if we're over UI
            if (pointer.overUI && hideWhenInvalid)
            {
                m_CurrentTower.Hide();
                return;
            }
            MoveGhost(pointer, hideWhenInvalid);
        }
 
        /// <summary>
        /// Activates the tower controller UI with the specific information
        /// </summary>
        /// <param name="tower">
        /// The tower controller information to use
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// Throws exception when selecting tower when <see cref="State" /> does not equal <see cref="State.Normal" />
        /// </exception>
        public void SelectTower(Tower tower)
        {
            if (state != State.Normal)
            {
                throw new InvalidOperationException("Trying to select whilst not in a normal state");
            }
            DeselectTower();
            currentSelectedTower = tower;
            if (currentSelectedTower != null)
            {
                currentSelectedTower.removed += OnTowerDied;
            }
            startDragTower(tower);
        }
 
        /// <summary>
        /// 在当前的PlaceArea内删除有相同LvL相同类型的防塔.
        /// </summary>
        /// <param name="tower"></param>
        public bool deleteSameLvlTower(Tower tower)
        {
            Tower delTower = findSameLvlTower(tower);
            if (delTower == null) return false;
            Tower backT = currentSelectedTower;
            currentSelectedTower = delTower;
            SellSelectedTower();
            currentSelectedTower = backT;
            return true;
        }
 
        /// <summary>
        /// Upgrades <see cref="currentSelectedTower" />, if possible
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Throws exception when selecting tower when <see cref="State" /> does not equal <see cref="State.Normal" />
        /// or <see cref="currentSelectedTower" /> is null
        /// </exception>
        public void UpgradeSelectedTower()
        {
            if (state != State.Normal)
            {
                throw new InvalidOperationException("Trying to upgrade whilst not in Normal state");
            }
            if (currentSelectedTower == null)
            {
                throw new InvalidOperationException("Selected Tower is null");
            }
            if (currentSelectedTower.isAtMaxLevel)
            {
                return;
            }
            int upgradeCost = currentSelectedTower.GetCostForNextLevel();
            bool successfulUpgrade = EndlessLevelManager.instance.Currency.TryPurchase(upgradeCost);
            if (successfulUpgrade)
            {
                currentSelectedTower.UpgradeTower();
            }
            DeselectTower();
        }
 
        /// <summary>
        /// 当前的塔防随机升级为另一种塔防的种类。
        /// </summary>
        protected bool randomUpgradeTower()
        {
            if (state != State.Normal)
            {
                throw new InvalidOperationException("Trying to upgrade whilst not in Normal state");
            }
            if (currentSelectedTower == null)
            {
                throw new InvalidOperationException("Selected Tower is null");
            }
            if (currentSelectedTower.isAtMaxLevel)
                return false;
 
            // 直接随机升级,零成本。
            // 1:记录当前Tower的Level,删除当前的Tower. 2:从TowerLib中随机找一个高一级别的Tower.
            string towerName = currentSelectedTower.towerName;
            if (currentSelectedTower.towerFeature == EFeatureTower.NULL)
                towerName = "";
            int towerLvl = currentSelectedTower.currentLevel + 1;
            int posx = currentSelectedTower.gridPosition.x;
            int posy = currentSelectedTower.gridPosition.y;
            currentSelectedTower.Sell();
            delTower(currentSelectedTower);
 
            // 随机放置一个新的Tower
            EndlessRandomTower.instance.randomTower(posx, posy, towerLvl, towerName);
 
            DeselectTower();
 
            return true;
        }
 
        /// <summary>
        /// Sells <see cref="currentSelectedTower" /> if possible
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Throws exception when selecting tower when <see cref="State" /> does not equal <see cref="State.Normal" />
        /// or <see cref="currentSelectedTower" /> is null
        /// </exception>
        public void SellSelectedTower()
        {
            if (state != State.Normal)
            {
                throw new InvalidOperationException("Trying to sell tower whilst not in Normal state");
            }
            if (currentSelectedTower == null)
            {
                throw new InvalidOperationException("Selected Tower is null");
            }
            int sellValue = currentSelectedTower.GetSellLevel();
            if (EndlessLevelManager.instanceExists && sellValue > 0)
            {
                EndlessLevelManager.instance.Currency.AddCurrency(sellValue);
                currentSelectedTower.Sell();
 
                // 从列表中删除Tower.
                delTower(currentSelectedTower);
            }
            DeselectTower();
        }
 
        /// <summary>
        /// Buys the tower and places it in the place that it currently is
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Throws exception if trying to buy towers in Build Mode
        /// </exception>
        public void BuyTower()
        {
            if (!isBuilding)
            {
                throw new InvalidOperationException("Trying to buy towers when not in Build Mode");
            }
            if (m_CurrentTower == null || !IsGhostAtValidPosition())
            {
                return;
            }
            int cost = m_CurrentTower.controller.purchaseCost;
            bool successfulPurchase = EndlessLevelManager.instance.Currency.TryPurchase(cost);
            if (successfulPurchase)
            {
                PlaceTower();
            }
        }
 
        /// <summary>
        /// Used to buy the tower during the build phase
        /// Checks currency and calls <see cref="PlaceGhost" />
        /// <exception cref="InvalidOperationException">
        /// Throws exception when not in a build mode or when tower is not a valid position
        /// </exception>
        /// </summary>
        public void BuyTower(UIPointer pointer, bool force = false, bool zeroCost = false)
        {
            if (!isBuilding) return;
 
            // 判断是否格子上重复放置塔防
            if (!m_CurrentTower || !IsGhostAtValidPosition())
            {
                // 判断格子上的塔防:
                Tower sTower = PickTowerInGrid(pointer);
 
                if (sTower)
                {
                    Tower curTower = m_CurrentTower.controller;
                    int testLvl = dragTowerLevel;
                    if ((sTower.currentLevel == testLvl) &&
                        (sTower.towerName == curTower.towerName))
                    {
                        // 先释放掉当前的Ghost塔防.
                        CancelGhostPlacement();
 
                        // 升级目标位置的塔防.
                        currentSelectedTower = sTower;
                        SetState(State.Normal);
                        // 新的代码,合并升级为随机塔防类型.
                        randomUpgradeTower();
                    }
                }
                else
                {
                    // 放置攻击塔位
                    PlacementAreaRaycast(ref pointer);
                    if (!pointer.raycast.HasValue || pointer.raycast.Value.collider == null)
                    {
                        CancelGhostPlacement();
                        return;
                    }
                    PlaceGhost(pointer);
                }
                return;
            }
 
            // 这是判断是否超出了格子
            PlacementAreaRaycast(ref pointer, force);
            if (!pointer.raycast.HasValue || pointer.raycast.Value.collider == null)
            {
                CancelGhostPlacement();
                return;
            }
 
            int cost = m_CurrentTower.controller.purchaseCost;
            if (zeroCost)
                cost = 0;
            bool successfulPurchase = EndlessLevelManager.instance.Currency.TryPurchase(cost);
            if (successfulPurchase)
            {
                PlaceGhost(pointer);
            }
        }
 
        /// <summary>
        /// 播放升级特效
        /// </summary>
        /// <param name="worldPos"></param>
        public void PlayUpgradeEffect(Tower newTower)
        {
            GameObject effect = TowerUpgradeEffectPrefab;
 
            if (newTower.towerFeature == EFeatureTower.NULL)
            {
                string path = $"UI/ToBattle_{newTower.attributeId}";
                GameObject prefab = Resources.Load<GameObject>(path);
                effect = Instantiate(prefab);
            }
 
            // 在sTower的位置播放升级特效
            GameObject obj = Instantiate(effect);
            obj.transform.position = newTower.transform.position;
            Vector3 pos = obj.transform.position;
            pos.y += 5f;
            obj.transform.position = pos;
            ParticleSystem ps = obj.GetComponent<ParticleSystem>();
 
            if (ps == null)
                ps = obj.transform.GetChild(0).GetComponent<ParticleSystem>();
            ps.Play();
            Destroy(obj, ps.main.duration);
        }
 
        /// <summary>
        /// Deselect the current tower and hides the UI
        /// </summary>
        public void DeselectTower()
        {
            if (currentSelectedTower != null)
            {
                currentSelectedTower.removed -= OnTowerDied;
            }
 
            currentSelectedTower = null;
 
            if (selectionChanged != null)
            {
                selectionChanged(null);
            }
        }
 
        /// <summary>
        /// Checks the position of the <see cref="m_CurrentTower"/> 
        /// on the <see cref="m_CurrentArea"/>
        /// </summary>
        /// <returns>
        /// True if the placement is valid
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// Throws exception if the check is done in <see cref="State.Normal"/> state
        /// </exception>
        public bool IsGhostAtValidPosition(bool opponent = false)
        {
            if (m_CurrentTower == null || m_CurrentArea == null)
                return false;
 
            TowerFitStatus fits = m_CurrentArea.Fits(m_GridPosition, m_CurrentTower.controller.dimensions);
            return fits == TowerFitStatus.Fits;
        }
 
        /// <summary>
        /// Checks if buying the ghost tower is possible
        /// </summary>
        /// <returns>
        /// True if can purchase
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// Throws exception if not in Build Mode or Build With Dragging mode
        /// </exception>
        public bool IsValidPurchase()
        {
            if (!isBuilding)
            {
                throw new InvalidOperationException("Trying to check ghost position when not in a build mode");
            }
 
            if (m_CurrentTower == null || m_CurrentArea == null)
                return false;
 
            return EndlessLevelManager.instance.Currency.CanAfford(m_CurrentTower.controller.purchaseCost);
        }
 
        /// <summary>
        /// Places a tower where the ghost tower is
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Throws exception if not in Build State or <see cref="m_CurrentTower"/> is not at a valid position
        /// </exception>
        public void PlaceTower(int lvl = 0, bool isUpgrade = false, bool opponent = false)
        {
            if (!isBuilding)
                throw new InvalidOperationException("Trying to place tower when not in a Build Mode");
 
            if (lvl <= 0)
            {
                if (!IsGhostAtValidPosition(opponent))
                    throw new InvalidOperationException("Trying to place tower on an invalid area");
            }
 
            if (m_CurrentArea == null)
                return;
 
            Tower createdTower = Instantiate(m_CurrentTower.controller);
            createdTower.opponentSide = opponent;
            createdTower.Initialize(m_CurrentArea, m_GridPosition, lvl);
 
            // River: 内部缓存数据,用于后期容易找到数据.
            addTower(createdTower);
            CancelGhostPlacement();
            if (!isUpgrade)
                PlayAppearEffect(createdTower.transform.position);
            else
                PlayUpgradeEffect(createdTower);
 
            // 处理成长骰子,复制骰子等等功能.
            if (lvl == 0)
            {
                ProcessFeatureTower(createdTower);
            }
        }
 
        /// <summary>
        /// 播放宝石出现特效
        /// </summary>
        public void PlayAppearEffect(Vector3 worldPos)
        {
            GameObject obj = Instantiate(TowerAppearEffectPrefab);
            obj.transform.position = worldPos;
            Vector3 pos = obj.transform.position;
            pos.y += 5f;
            obj.transform.position = pos;
 
            ParticleSystem ps = obj.GetComponent<ParticleSystem>();
 
            if (ps == null)
                ps = obj.transform.GetChild(0).GetComponent<ParticleSystem>();
 
            ps.Play();
            Destroy(obj, ps.main.duration);
        }
 
        /// <summary>
        /// 播放升级特效
        /// </summary>
        /// <param name="worldPos"></param>
        public void GuidePlayUpgradeEffect(Vector3 position)
        {
            GameObject effect = TowerUpgradeEffectPrefab;
 
            // 在sTower的位置播放升级特效
            GameObject obj = Instantiate(effect);
            obj.transform.position = position;
            Vector3 pos = obj.transform.position;
            pos.y += 5f;
            obj.transform.position = pos;
            ParticleSystem ps = obj.GetComponent<ParticleSystem>();
 
            if (ps == null)
                ps = obj.transform.GetChild(0).GetComponent<ParticleSystem>();
            ps.Play();
            Destroy(obj, ps.main.duration);
        }
 
        protected void ProcessFeatureTower(Tower ctower)
        {
            if (ctower.towerFeature == EFeatureTower.GrowUp)
            {
                Timer timer = new Timer(10.0f, () => { growUpTower(ctower); });
                listTowerTimer.Add(timer);
 
                towerTimeDic.Add(timer.timerID, ctower);
            }
            else if (ctower.towerFeature == EFeatureTower.CopyCat)
            {
 
            }
            return;
        }
 
        /// <summary>
        /// 成功购买塔防后,更新价格,更新按钮,更新按钮上的塔防价格等等.
        /// </summary>
        protected void OnSuccessBuyTower()
        {
            var tpMgr = TowerPrice.instance;
            if (!tpMgr) return;
 
            // 价格更新
            tpMgr.onTowerBuySuccess();
 
            if (!towerPriceText)
            {
                towerPriceText = randomTowerBtn.transform.Find("cashText").GetComponent<TextMeshProUGUI>();
                if (towerPriceText)
                    towerPriceText.text = tpMgr.currentTowerPrice.ToString();
            }
            else
            {
                towerPriceText.text = tpMgr.currentTowerPrice.ToString();
            }
 
            // 无法支付新的塔防价格,按钮变灰.
            if (tpMgr.currentTowerPrice > EndlessLevelManager.instance.Currency.currentCurrency)
            {
                disableRandomTowerBtn();
            }
        }
 
        /// <summary>
        /// 随机放置Tower按钮禁止使用,灰掉.
        /// </summary>
        protected void disableRandomTowerBtn()
        {
            randomTowerBtn.GetComponent<EndlessRandomTower>().ChangeBtnClick();
            //randomTowerBtn.interactable = false;
            if (towerPriceText)
            {
                towerPriceText.color = new Color(0.5f, 0.5f, 0.5f);
            }
            tdBuyDisable = true;
        }
 
        /// <summary>
        /// 随机购买Tower的按钮重设置为有效.
        /// </summary>
        protected void enableRandomTowerBtn()
        {
            // ATTENTION TO FIX: 再次判断是因为有的地方是直接调用
            if ((TowerPrice.instance.currentTowerPrice > EndlessLevelManager.instance.Currency.currentCurrency) ||
                 (m_listTower.Count >= MAX_TOWERNUM))
                return;
 
            if (towerPriceText)
                towerPriceText.color = new Color(1.0f, 1.0f, 1.0f);
 
            if (randomTowerBtn)
            {
                randomTowerBtn.GetComponent<EndlessRandomTower>().ChangeBtnClickNormal();
                //randomTowerBtn.interactable = true;
            }
            tdBuyDisable = false;
        }
 
        /// <summary>
        /// 游戏内向上飘血
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="val"></param>
        public void generateBloodText(Vector3 wpos, float val, bool crit = false, bool doubleHit = false, bool poison = false)
        {
            Vector3 spos = m_Camera.WorldToScreenPoint(wpos);
            TextMoveDoTween tm;
            if (crit)
            {
                tm = Poolable.TryGetPoolable<TextMoveDoTween>(bloodCrit.gameObject);
            }
            else if (poison)
            {
                tm = Poolable.TryGetPoolable<TextMoveDoTween>(bloodPoison.gameObject);
            }
            else
            {
                tm = Poolable.TryGetPoolable<TextMoveDoTween>(bloodText.gameObject);
            }
            if (tm)
            {
                tm.GetComponent<Transform>().SetParent(GameObject.Find("MainUI").GetComponent<Transform>(), true);
                string bloodStr = "";
                if (doubleHit)
                    bloodStr += "Dble!";
                if (crit)
                    bloodStr += "Crt!";
                bloodStr += "-";
                bloodStr += ((Int64)val).ToString();
 
                tm.moveBloodText(spos.x, spos.y, bloodStr, crit);
            }
        }
 
        private void Start()
        {
            // 获取相应的放置区域。
            GameObject placeObj = GameObject.FindGameObjectWithTag("PlaceTower");
            if (placeObj != null)
            {
                m_CurrentArea = placeObj.GetComponent<IPlacementArea>();
                dragTowerPlacement = placeObj.GetComponent<IPlacementArea>() as TowerPlacementGridEndless; 
            }
            placeObj = GameObject.FindGameObjectWithTag("PlaceTowerOpponent");
            EventCenter.Ins.Add((int)KTGMGemClient.EventType.EndlessHeartAllLose, AllHeartLose);
        }
 
        /// <summary>
        /// 替换towerToMove的目标Tower,如果是使用towerToMove,则必须提前处理相应的指针。
        /// </summary>
        /// <param name="tow"></param>
        public void DisplaceTower(Tower newTower, Tower oldTower, int lvl = 0)
        {
            // 先记录oldTower的位置信息:
            int posx = oldTower.gridPosition.x;
            int posy = oldTower.gridPosition.y;
            bool opponent = oldTower.opponentSide;
 
            int newLvl = oldTower.currentLevel + 1;
            if (newLvl > 4) newLvl = 4;
 
            delTower(oldTower);
            oldTower.showTower(true);
            oldTower.Sell();
 
            // 减化成长塔位对应的代码,用于不再影响目前正处于建设状态的塔位.
            if (m_CurrentArea == null)
                return;
 
            IntVector2 ivec;
            ivec.x = posx;
            ivec.y = posy;
 
            Tower createdTower = Instantiate(newTower);
            createdTower.opponentSide = opponent;
 
            createdTower.Initialize(m_CurrentArea, ivec, newLvl);
 
            // River: 内部缓存数据,用于后期容易找到数据.
            addTower(createdTower);
        }
 
        /// <summary>
        /// 直接在IPlaceArea上随机放置一个Tower。这是随机放置塔防的入口类。这是入口的塔防类。
        /// </summary>
        /// <param name="tow"></param>
        public bool RandomPlaceTower(Tower tow, int posx = -1, int posy = -1, int lvl = 0, int forceCost = -1, bool isUpgrade = false)
        {
            // 获取IPlaceArea.
            if (m_CurrentArea == null)
            {
                GameObject placeObj = GameObject.FindGameObjectWithTag("PlaceTower");
                if (placeObj == null) return false;
                // 获取相应的放置区域。
                m_CurrentArea = placeObj.GetComponent<IPlacementArea>();
                if (m_CurrentArea == null) return false;
            }
 
            bool zeroCost = false;
            if (posx < 0 && posy < 0)
            {
                IntVector2 tvec = m_CurrentArea.getFreePos(1, 1);
                if (tvec.x < 0 && tvec.y < 0)
                    return false;
                m_GridPosition.x = tvec.x;
                m_GridPosition.y = tvec.y;
            }
            else
            {
                m_GridPosition.x = posx;
                m_GridPosition.y = posy;
                zeroCost = true;
            }
 
            // 购买成功,才会继续放置塔防:
            if (tow.towerGhostPrefab == null)
            {
                return false;
            }
            // River: 修改Cost为全局统一维护的数据
            int cost = TowerPrice.instance.currentTowerPrice;
            if (zeroCost)
                cost = 0;
 
            if (forceCost != -1)
                cost = forceCost;
 
            bool successfulPurchase = EndlessLevelManager.instance.Currency.TryPurchase(cost);
            if (!successfulPurchase) return false;
 
            SetUpGhostTower(tow);
            //Debug.Log("设置影子塔防.");
            m_CurrentTower.Show();
            if (successfulPurchase)
            {
                ++GameConfig.EndlessBuyTowerCount;
                // 删除towerToMove,确保塔防数据不再出现多个
                if (zeroCost && (towerToMove != null))
                {
                    delTower(towerToMove);
                    towerToMove.showTower(true);
                    towerToMove.Sell();
                    towerToMove = null;
                }
 
                // 塔防购买成功后的相关更新:
                if (!zeroCost)
                    OnSuccessBuyTower();
                SetState(State.Building);
 
                PlaceTower(lvl, isUpgrade);
            }
 
            return true;
        }
 
        /// <summary>
        /// Calculates whether the given pointer is over the current tower ghost
        /// </summary>
        /// <param name="pointerInfo">
        /// The information used to check against the <see cref="m_CurrentTower"/>
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// Throws an exception if not in Build Mode
        /// </exception>
        public bool IsPointerOverGhost(PointerInfo pointerInfo)
        {
            if (state != State.Building)
            {
                throw new InvalidOperationException("Trying to tap on ghost tower when not in Build Mode");
            }
            UIPointer uiPointer = WrapPointer(pointerInfo);
            RaycastHit hit;
            return m_CurrentTower.ghostCollider.Raycast(uiPointer.ray, out hit, float.MaxValue);
        }
 
        /// <summary>
        /// Selects a tower beneath the given pointer if there is one
        /// 选择塔防
        /// </summary>
        /// <param name="info">
        /// The pointer information concerning the selector of the pointer
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// Throws an exception when not in <see cref="State.Normal"/>
        /// </exception>
        public void TrySelectTower(PointerInfo info)
        {
            if (state != State.Normal)
            {
                //throw new InvalidOperationException("Trying to select towers outside of Normal state");
                return;
            }
            UIPointer uiPointer = WrapPointer(info);
            RaycastHit output;
            // River: Raycast的碰撞是游戏内物品的Collider进行碰撞检测的
            bool hasHit = Physics.Raycast(uiPointer.ray, out output, float.MaxValue, towerSelectionLayer);
            if (!hasHit)//|| uiPointer.overUI)
            {
                //Debug.Log("没有点中或者点中了UI:" + hasHit.ToString() + "," + uiPointer.overUI.ToString());
                return;
            }
            var controller = output.collider.GetComponent<Tower>();
            if (controller != null)
            {
                SelectTower(controller);
            }
 
            // 计算偏移值.
            CalSelTowerScreenOffset(info, controller);
        }
 
 
 
        /// <summary>
        /// 鼠标选中一个Tower的时候,计算当前鼠标位置与当前Tower位置在屏幕上坐标位置的偏移量。
        /// </summary>
        /// <param name="info"></param>
        /// <param name="tower"></param>
        protected void CalSelTowerScreenOffset(PointerInfo info, Tower tower)
        {
            Vector3 towerCentPos = m_Camera.WorldToScreenPoint(tower.transform.position);
            selTowerOffset.x = towerCentPos.x - info.currentPosition.x;
            selTowerOffset.y = towerCentPos.y - info.currentPosition.y;
        }
 
        /// <summary>
        /// Gets the world position of the ghost tower
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Throws an exception when not in the Build Mode or
        /// When a ghost tower does not exist
        /// </exception>
        public Vector3 GetGhostPosition()
        {
            if (!isBuilding)
            {
                throw new InvalidOperationException("Trying to get ghost position when not in a Build Mode");
            }
            if (m_CurrentTower == null)
            {
                throw new InvalidOperationException("Trying to get ghost position for an object that does not exist");
            }
            return m_CurrentTower.transform.position;
        }
 
        /// <summary>
        /// Moves the ghost to the center of the screen
        /// </summary>
        /// <exception cref="InvalidOperationException">
        /// Throws exception when not in build mode
        /// </exception>
        public void MoveGhostToCenter()
        {
            if (state != State.Building)
            {
                throw new InvalidOperationException("Trying to move ghost when not in Build Mode");
            }
            // try to find a valid placement 
            Ray ray = m_Camera.ScreenPointToRay(new Vector2(Screen.width * 0.5f, Screen.height * 0.5f));
            RaycastHit placementHit;
 
            if (Physics.SphereCast(ray, sphereCastRadius, out placementHit, float.MaxValue, placementAreaMask))
            {
                MoveGhostWithRaycastHit(placementHit);
            }
            else
            {
                MoveGhostOntoWorld(ray, false);
            }
        }
 
        /// <summary>
        /// Set initial values, cache attached components
        /// and configure the controls
        /// </summary>
        protected override void Awake()
        {
            base.Awake();
 
            DOTween.Init(true, true, LogBehaviour.Verbose).SetCapacity(200, 10);
 
            state = State.Normal;
            m_Camera = GetComponent<Camera>();
            TowerDestroyArr = new bool[5, AttackRowNumbers];
        }
 
        /// <summary>
        /// 战场内所有的Tower实例都需要升级相关的数据.
        /// 找到相同类型的所有Tower,然后进行局内升级的修改。
        /// </summary>
        /// <param name="td"></param>
        protected void towerUpgradeInBattle(TowerLevelUp tlu)
        {
            foreach (Tower tower in m_listTower)
            {
                if (tlu.towerName != tower.towerName)
                    continue;
                tower.upGradeInSceneTL();
            }
            return;
        }
 
        /// <summary>
        /// Reset TimeScale if game is paused
        /// </summary>
        protected override void OnDestroy()
        {
            base.OnDestroy();
            Time.timeScale = 1f;
        }
 
        /// <summary>
        /// Subscribe to the level manager
        /// </summary>
        protected virtual void OnEnable()
        {
            if (EndlessLevelManager.instanceExists)
                EndlessLevelManager.instance.Currency.currencyChanged += OnCurrencyChanged;
        }
 
        /// <summary>
        /// Unsubscribe from the level manager
        /// </summary>
        protected virtual void OnDisable()
        {
            if (EndlessLevelManager.instanceExists)
                EndlessLevelManager.instance.Currency.currencyChanged -= OnCurrencyChanged;
        }
 
        /// <summary>
        /// Creates a new UIPointer holding data object for the given pointer position
        /// </summary>
        protected UIPointer WrapPointer(PointerInfo pointerInfo)
        {
            return new UIPointer
            {
                overUI = IsOverUI(pointerInfo),
                pointer = pointerInfo,
                overWaveLine = false,
                ray = m_Camera.ScreenPointToRay(pointerInfo.currentPosition)
            };
        }
 
        /// <summary>
        /// Checks whether a given pointer is over any UI
        /// </summary>
        /// <param name="pointerInfo">The pointer to test</param>
        /// <returns>True if the event system reports pointer being over UI</returns>
        protected bool IsOverUI(PointerInfo pointerInfo)
        {
            int pointerId;
            EventSystem currentEventSystem = EventSystem.current;
 
            // Pointer id is negative for mouse, positive for touch
            var cursorInfo = pointerInfo as MouseCursorInfo;
            var mbInfo = pointerInfo as MouseButtonInfo;
            var touchInfo = pointerInfo as TouchInfo;
 
            if (cursorInfo != null)
            {
                pointerId = PointerInputModule.kMouseLeftId;
            }
            else if (mbInfo != null)
            {
                // LMB is 0, but kMouseLeftID = -1;
                pointerId = -mbInfo.mouseButtonId - 1;
            }
            else if (touchInfo != null)
            {
                pointerId = touchInfo.touchId;
            }
            else
            {
                throw new ArgumentException("Passed pointerInfo is not a TouchInfo or MouseCursorInfo", "pointerInfo");
            }
 
            return currentEventSystem.IsPointerOverGameObject(pointerId);
        }
 
        WaveLineSelEffect currentEffect;
        /// <summary>
        /// Move the ghost to the pointer's position
        /// </summary>
        /// <param name="pointer">The pointer to place the ghost at</param>
        /// <param name="hideWhenInvalid">Optional parameter for whether the ghost should be hidden or not</param>
        /// <exception cref="InvalidOperationException">If we're not in the correct state</exception>
        protected void MoveGhost(UIPointer pointer, bool hideWhenInvalid = true)
        {
            // 我操,终于可以了!ATTENTION TO OPP:
            PointerInfo tp = new PointerActionInfo();
            tp.currentPosition = pointer.pointer.currentPosition;
            tp.previousPosition = pointer.pointer.previousPosition;
            tp.delta = pointer.pointer.delta;
            tp.startedOverUI = pointer.pointer.startedOverUI;
            // River: 调整偏移值,用于鼠标移动塔防的时候,更加平滑。
            tp.currentPosition.x += selTowerOffset.x;
            tp.currentPosition.y += selTowerOffset.y;
            UIPointer npt = new UIPointer
            {
                overUI = false,
                pointer = tp,
                overWaveLine = false,
                ray = m_Camera.ScreenPointToRay(tp.currentPosition)
            };
 
 
            m_GridPosition.x = -1;
            m_GridPosition.y = -1;
 
            // 
            // WORK START: 从这里开始,移动的时候与场景内的WaveSelEffect射线做碰撞。  
            // Raycast onto placement layer
            PlacementAreaRaycast(ref npt);
 
            if (npt.raycast != null)
            {
                MoveGhostWithRaycastHit(npt.raycast.Value);
            }
            else
            {
                // 根据技能塔的类型,来碰撞不同的数据:
                // 火是列攻击:
                if (m_CurrentTower.controller.towerFeature == EFeatureTower.Skill_Fire)
                {
                    WavelineAreaRaycast(ref npt);
                    if (npt.overWaveLine)
                    {
                        WaveLineSelEffect selEff = npt.wavelineHit.Value.collider.GetComponent<WaveLineSelEffect>();
                        if (selEff != currentEffect)
                        {
                            if (currentEffect != null)
                            {
                                currentEffect.SetParticleSystem(false);
                            }
                            currentEffect = selEff;
                            currentEffect.SetParticleSystem(true);
                        }
                        //selEff.SetWaveLineSel(true);
                    }
                }
                // 炸弹是区域攻击显示:
                else if (m_CurrentTower.controller.towerFeature == EFeatureTower.Skill_Bomb)
                {
                    // 测试代码与战场区域碰撞,碰撞后显示攻击区域:
                    BattleAreaRaycast(ref npt);
                    if (npt.overWaveLine)
                        m_CurrentTower.fadeOutAttackArea();
                }
 
                MoveGhostOntoWorld(npt.ray, hideWhenInvalid);
            }
        }
 
        /// <summary>
        /// Move ghost with successful raycastHit onto m_PlacementAreaMask
        /// </summary>
        protected virtual void MoveGhostWithRaycastHit(RaycastHit raycast)
        {
            // We successfully hit one of our placement areas
            // Try and get a placement area on the object we hit
            m_CurrentArea = raycast.collider.GetComponent<IPlacementArea>();
            if (m_CurrentArea == null)
            {
                Debug.LogError("There is not an IPlacementArea attached to the collider found on the m_PlacementAreaMask");
                return;
            }
            m_GridPosition = m_CurrentArea.WorldToGrid(raycast.point, m_CurrentTower.controller.dimensions);
            TowerFitStatus fits = m_CurrentArea.Fits(m_GridPosition, m_CurrentTower.controller.dimensions);
 
            m_CurrentTower.Show();
            m_GhostPlacementPossible = fits == TowerFitStatus.Fits && IsValidPurchase();
            m_CurrentTower.Move(raycast.point,
                                 //m_CurrentArea.GridToWorld(m_GridPosition, m_CurrentTower.controller.dimensions),
                                 m_CurrentArea.transform.rotation,
                                 m_GhostPlacementPossible);
        }
 
        /// <summary>
        /// Move ghost with the given ray
        /// </summary>
        protected virtual void MoveGhostOntoWorld(Ray ray, bool hideWhenInvalid)
        {
            m_CurrentArea = null;
 
            if (!hideWhenInvalid)
            {
                RaycastHit hit;
 
                // check against all layers that the ghost can be on
                Physics.SphereCast(ray, sphereCastRadius, out hit, float.MaxValue, ghostWorldPlacementMask);
                if (hit.collider == null)
                {
                    return;
                }
                m_CurrentTower.Show();
 
                // ATTENTION TO FIX:什么情况下会导致Y值过高,然后闪烁出现?
                Vector3 tvec3 = hit.point;
                tvec3.y = 0.0f;
                hit.point = tvec3;
 
                m_CurrentTower.Move(hit.point, hit.collider.transform.rotation, false);
            }
            else
            {
                m_CurrentTower.Hide();
            }
        }
 
        /// <summary>
        /// Place the ghost at the pointer's position
        /// </summary>
        /// <param name="pointer">The pointer to place the ghost at</param>
        /// <exception cref="InvalidOperationException">If we're not in the correct state</exception>
        protected void PlaceGhost(UIPointer pointer)
        {
            MoveGhost(pointer);
 
            if (m_CurrentArea != null)
            {
                TowerFitStatus fits = m_CurrentArea.Fits(m_GridPosition, m_CurrentTower.controller.dimensions);
 
                if (fits == TowerFitStatus.Fits)
                {
                    // Place the ghost
                    Tower controller = m_CurrentTower.controller;
                    Tower createdTower = Instantiate(controller);
                    createdTower.Initialize(m_CurrentArea, m_GridPosition);
                    createdTower.SetLevel(dragTowerLevel);
 
                    // ATTENTION TO FIX:是否应该加入List:
                    addTower(createdTower);
                    PlayToAttackEffect(createdTower.attributeId, createdTower.transform.position);
                    dragTowerLevel = 0;
                    CancelGhostPlacement();
                }
            }
        }
 
        /// <summary>
        /// 播放宝石上阵特效
        /// </summary>
        /// <param name="attributeId">101 火,105 水,109 木</param>
        /// <param name="worldPos">世界坐标</param>
        public void PlayToAttackEffect(int attributeId, Vector3 worldPos)
        {
            string path = $"UI/ToBattle_{attributeId}";
            GameObject prefab = Resources.Load<GameObject>(path);
            GameObject obj = Instantiate(prefab);
            obj.transform.position = worldPos;
            Vector3 pos = obj.transform.position;
            pos.y += 5f;
            obj.transform.position = pos;
 
            ParticleSystem ps = obj.GetComponent<ParticleSystem>();
 
            if (ps == null)
                ps = obj.transform.GetChild(0).GetComponent<ParticleSystem>();
 
            ps.Play();
            Destroy(obj, ps.main.duration);
        }
 
        /// <summary>
        /// Raycast onto tower placement areas
        /// </summary>
        /// <param name="pointer">The pointer we're testing</param>
        protected void PlacementAreaRaycast(ref UIPointer pointer, bool force = false)
        {
            pointer.raycast = null;
 
            if (pointer.overUI && (!force))
            {
                // Pointer is over UI, so no valid position
                return;
            }
 
            // Raycast onto placement area layer
            RaycastHit hit;
            if (Physics.Raycast(pointer.ray, out hit, float.MaxValue, placementAreaMask))
            {
                pointer.raycast = hit;
            }
        }
 
        /// <summary>
        /// 是否会跟兵线层数据有碰撞发生.
        /// </summary>
        /// <param name="point"></param>
        protected void WavelineAreaRaycast(ref UIPointer pointer)
        {
            RaycastHit hit;
            if (Physics.Raycast(pointer.ray, out hit, float.MaxValue, waveLineMask))
            {
                pointer.wavelineHit = hit;
                pointer.overWaveLine = true;
            }
            return;
        }
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pointer"></param>
        protected void BattleAreaRaycast(ref UIPointer pointer)
        {
            RaycastHit hit;
            if (Physics.Raycast(pointer.ray, out hit, float.MaxValue, battleAreaMask))
            {
                pointer.wavelineHit = hit;
                pointer.overWaveLine = true;
            }
 
            return;
        }
 
        /// <summary>
        /// 更新每一个
        /// </summary>
        protected void updateSceneTowerUpgradeStatus()
        {
            bool zeroTower = m_listTower.Count == 0;
        }
 
        /// <summary>
        /// Modifies the valid rendering of the ghost tower once there is enough currency
        /// </summary>
        protected virtual void OnCurrencyChanged()
        {
            // 如果当前处于TowerBuy Disable的状态,根据Currency的值来判断是否应该重新开启RandomTowerBuy按钮.
            if (tdBuyDisable)
            {
                enableRandomTowerBtn();
            }
 
            // 无法支付新的塔防价格,按钮变灰.
            var tpMgr = TowerPrice.instance;
            if (tpMgr.currentTowerPrice > EndlessLevelManager.instance.Currency.currentCurrency)
                disableRandomTowerBtn();
 
            // 处理场景内升级相关的内容
            updateSceneTowerUpgradeStatus();
 
            if (!isBuilding || m_CurrentTower == null || m_CurrentArea == null)
            {
                return;
            }
            TowerFitStatus fits = m_CurrentArea.Fits(m_GridPosition, m_CurrentTower.controller.dimensions);
            bool valid = fits == TowerFitStatus.Fits && IsValidPurchase();
            m_CurrentTower.Move(m_CurrentArea.GridToWorld(m_GridPosition, m_CurrentTower.controller.dimensions),
                                m_CurrentArea.transform.rotation,
                                valid);
            if (valid && !m_GhostPlacementPossible && ghostBecameValid != null)
            {
                m_GhostPlacementPossible = true;
                ghostBecameValid();
            }
        }
 
        /// <summary>
        /// Closes the Tower UI on death of tower
        /// </summary>
        protected void OnTowerDied(DamageableBehaviour targetable)
        {
            DeselectTower();
        }
 
        /// <summary>
        /// Creates and hides the tower and shows the buildInfoUI
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// Throws exception if the <paramref name="towerToBuild"/> is null
        /// </exception>
        void SetUpGhostTower([NotNull] Tower towerToBuild)
        {
            if (towerToBuild == null)
            {
                throw new ArgumentNullException("towerToBuild");
            }
 
            m_CurrentTower = Instantiate(towerToBuild.towerGhostPrefab);
            m_CurrentTower.Initialize(towerToBuild);
        }
 
        /// <summary>
        /// 处理GameUI的Update相关内容,目前的主要工作是处理成长骰子.
        /// </summary>
        private void Update()
        {
            if (overTimer != null)
                overTimer.Tick(Time.deltaTime);
 
            for (int ti = listTowerTimer.Count - 1; ti >= 0; ti--)
            {
                // 如果执行到,会在DelTower函数内删除对应的listTowerTimer.
                listTowerTimer[ti].Tick(Time.deltaTime);
            }
 
            // 更新处理自己方光塔对应的攻击增加.
            updateLightTowerAttRise();
        }
 
        /// <summary>
        /// 更新火属性Tower对左右塔的攻击增加.
        /// </summary>
        protected void updateLightTowerAttRise()
        {
            int yRow = 2;
            int maxTower = MAX_TOWERNUM / 3;
 
            for (int ti = 0; ti < maxTower; ti++)
            {
                Tower tw = FindTowerWithGridIdx(ti, yRow);
                if (tw)
                    tw.attackRise = 0.0f;
            }
 
            for (int ti = 0; ti < maxTower; ti++)
            {
                Tower tw = FindTowerWithGridIdx(ti, yRow);
                if (tw == null) continue;
                if (tw.towerFeature == EFeatureTower.LightTower)
                {
                    int nidx = ti - 1;
                    if (nidx >= 0)
                    {
                        tw = FindTowerWithGridIdx(nidx, yRow);
                        if (tw)
                            tw.attackRise = 0.1f;
                    }
                    nidx = ti + 1;
                    if (nidx < maxTower)
                    {
                        tw = FindTowerWithGridIdx(nidx, yRow);
                        if (tw)
                            tw.attackRise = 0.1f;
                    }
                }
            }
        }
    }
}