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
|
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#include "System/mmgr.h"
#include "GroundMoveType.h"
#include "ExternalAI/EngineOutHandler.h"
#include "Game/Camera.h"
#include "Game/GameHelper.h"
#include "Game/GlobalUnsynced.h"
#include "Game/Player.h"
#include "Game/SelectedUnits.h"
#include "Map/Ground.h"
#include "Map/MapInfo.h"
#include "Map/ReadMap.h"
#include "MoveMath/MoveMath.h"
#include "Sim/Features/Feature.h"
#include "Sim/Features/FeatureHandler.h"
#include "Sim/Misc/GeometricObjects.h"
#include "Sim/Misc/ModInfo.h"
#include "Sim/Misc/QuadField.h"
#include "Sim/Misc/TeamHandler.h"
#include "Sim/Path/IPathManager.h"
#include "Sim/Units/Scripts/CobInstance.h"
#include "Sim/Units/CommandAI/CommandAI.h"
#include "Sim/Units/UnitDef.h"
#include "Sim/Units/UnitHandler.h"
#include "Sim/Weapons/WeaponDefHandler.h"
#include "Sim/Weapons/Weapon.h"
#include "System/EventHandler.h"
#include "System/Log/ILog.h"
#include "System/FastMath.h"
#include "System/myMath.h"
#include "System/Vec2.h"
#include "System/Sound/SoundChannels.h"
#include "System/Sync/SyncTracer.h"
#define LOG_SECTION_GMT "GroundMoveType"
LOG_REGISTER_SECTION_GLOBAL(LOG_SECTION_GMT)
// use the specific section for all LOG*() calls in this source file
#ifdef LOG_SECTION_CURRENT
#undef LOG_SECTION_CURRENT
#endif
#define LOG_SECTION_CURRENT LOG_SECTION_GMT
// speeds near (MAX_UNIT_SPEED * 1e1) elmos / frame can be caused by explosion impulses
// CUnitHandler removes units with speeds > MAX_UNIT_SPEED as soon as they exit the map,
// so the assertion can be less strict
#define ASSERT_SANE_OWNER_SPEED(v) assert(v.SqLength() < (MAX_UNIT_SPEED * MAX_UNIT_SPEED * 1e2));
#define RAD2DEG (180.0f / PI)
#define MIN_WAYPOINT_DISTANCE SQUARE_SIZE
#define MAX_IDLING_SLOWUPDATES 16
#define DEBUG_OUTPUT 0
#define WAIT_FOR_PATH 1
#define IGNORE_OBSTACLES 0
#define PLAY_SOUNDS 1
#define OWNER_CMD_QUE owner->commandAI->commandQue
#define OWNER_MOVE_CMD() (OWNER_CMD_QUE.empty() || OWNER_CMD_QUE[0].GetID() == CMD_MOVE)
#define FOOTPRINT_RADIUS(xs, zs, s) ((math::sqrt((xs * xs + zs * zs)) * 0.5f * SQUARE_SIZE) * s)
CR_BIND_DERIVED(CGroundMoveType, AMoveType, (NULL));
CR_REG_METADATA(CGroundMoveType, (
CR_MEMBER(turnRate),
CR_MEMBER(accRate),
CR_MEMBER(decRate),
CR_MEMBER(maxReverseSpeed),
CR_MEMBER(wantedSpeed),
CR_MEMBER(currentSpeed),
CR_MEMBER(requestedSpeed),
CR_MEMBER(deltaSpeed),
CR_MEMBER(pathId),
CR_MEMBER(goalRadius),
CR_MEMBER(currWayPoint),
CR_MEMBER(nextWayPoint),
CR_MEMBER(atGoal),
CR_MEMBER(haveFinalWaypoint),
CR_MEMBER(currWayPointDist),
CR_MEMBER(prevWayPointDist),
CR_MEMBER(pathRequestDelay),
CR_MEMBER(numIdlingUpdates),
CR_MEMBER(numIdlingSlowUpdates),
CR_MEMBER(wantedHeading),
CR_MEMBER(moveSquareX),
CR_MEMBER(moveSquareY),
CR_MEMBER(nextObstacleAvoidanceUpdate),
CR_MEMBER(skidding),
CR_MEMBER(flying),
CR_MEMBER(reversing),
CR_MEMBER(idling),
CR_MEMBER(canReverse),
CR_MEMBER(useMainHeading),
CR_MEMBER(waypointDir),
CR_MEMBER(flatFrontDir),
CR_MEMBER(lastAvoidanceDir),
CR_MEMBER(mainHeadingPos),
CR_MEMBER(skidRotVector),
CR_MEMBER(skidRotSpeed),
CR_MEMBER(skidRotAccel),
CR_ENUM_MEMBER(oldPhysState),
CR_RESERVED(64),
CR_POSTLOAD(PostLoad)
));
std::vector<int2> CGroundMoveType::lineTable[LINETABLE_SIZE][LINETABLE_SIZE];
CGroundMoveType::CGroundMoveType(CUnit* owner):
AMoveType(owner),
turnRate(0.1f),
accRate(0.01f),
decRate(0.01f),
maxReverseSpeed(0.0f),
wantedSpeed(0.0f),
currentSpeed(0.0f),
requestedSpeed(0.0f),
deltaSpeed(0.0f),
pathId(0),
goalRadius(0),
currWayPoint(ZeroVector),
nextWayPoint(ZeroVector),
atGoal(false),
haveFinalWaypoint(false),
currWayPointDist(0.0f),
prevWayPointDist(0.0f),
skidding(false),
flying(false),
reversing(false),
idling(false),
canReverse(owner->unitDef->rSpeed > 0.0f),
useMainHeading(false),
skidRotVector(UpVector),
skidRotSpeed(0.0f),
skidRotAccel(0.0f),
oldPhysState(CSolidObject::OnGround),
flatFrontDir(0.0f, 0.0, 1.0f),
lastAvoidanceDir(ZeroVector),
mainHeadingPos(ZeroVector),
nextObstacleAvoidanceUpdate(0),
pathRequestDelay(0),
numIdlingUpdates(0),
numIdlingSlowUpdates(0),
wantedHeading(0)
{
assert(owner != NULL);
assert(owner->unitDef != NULL);
moveSquareX = owner->pos.x / MIN_WAYPOINT_DISTANCE;
moveSquareY = owner->pos.z / MIN_WAYPOINT_DISTANCE;
maxReverseSpeed = owner->unitDef->rSpeed / GAME_SPEED;
turnRate = owner->unitDef->turnRate;
accRate = std::max(0.01f, owner->unitDef->maxAcc);
decRate = std::max(0.01f, owner->unitDef->maxDec);
}
CGroundMoveType::~CGroundMoveType()
{
if (pathId != 0) {
pathManager->DeletePath(pathId);
}
}
void CGroundMoveType::PostLoad()
{
// HACK: re-initialize path after load
if (pathId != 0) {
pathId = pathManager->RequestPath(owner->mobility, owner->pos, goalPos, goalRadius, owner);
}
}
bool CGroundMoveType::Update()
{
ASSERT_SYNCED(owner->pos);
if (owner->GetTransporter() != NULL) {
return false;
}
if (OnSlope(1.0f)) {
skidding = true;
}
if (skidding) {
UpdateSkid();
HandleObjectCollisions();
return false;
}
ASSERT_SYNCED(owner->pos);
// set drop height when we start to drop
if (owner->falling) {
UpdateControlledDrop();
return false;
}
ASSERT_SYNCED(owner->pos);
bool hasMoved = false;
bool wantReverse = false;
const short heading = owner->heading;
if (owner->stunned || owner->beingBuilt) {
owner->script->StopMoving();
SetDeltaSpeed(0.0f, false);
} else {
if (owner->fpsControlPlayer != NULL) {
wantReverse = UpdateDirectControl();
} else {
wantReverse = FollowPath();
}
}
// these must be executed even when stunned (so
// units do not get buried by restoring terrain)
UpdateOwnerPos(wantReverse);
AdjustPosToWaterLine();
HandleObjectCollisions();
ASSERT_SANE_OWNER_SPEED(owner->speed);
// <dif> is normally equal to owner->speed (if no collisions)
// we need more precision (less tolerance) in the y-dimension
// for all-terrain units that are slowed down a lot on cliffs
const float3 posDif = owner->pos - oldPos;
const float3 cmpEps = float3(float3::CMP_EPS, float3::CMP_EPS * 1e-2f, float3::CMP_EPS);
if (posDif.equals(ZeroVector, cmpEps)) {
// note: the float3::== test is not exact, so even if this
// evaluates to true the unit might still have an epsilon
// speed vector --> nullify it to prevent apparent visual
// micro-stuttering (speed is used to extrapolate drawPos)
owner->speed = ZeroVector;
// negative y-coordinates indicate temporary waypoints that
// only exist while we are still waiting for the pathfinder
// (so we want to avoid being considered "idle", since that
// will cause our path to be re-requested and again give us
// a temporary waypoint, etc.)
// NOTE: this is only relevant for QTPFS
// if the unit is just turning in-place over several frames
// (eg. to maneuver around an obstacle), do not consider it
// as "idling"
idling = (currWayPoint.y != -1.0f && nextWayPoint.y != -1.0f);
idling &= (std::abs(owner->heading - heading) < turnRate);
hasMoved = false;
} else {
TestNewTerrainSquare();
// note: HandleObjectCollisions() may have negated the position set
// by UpdateOwnerPos() (so that owner->pos is again equal to oldPos)
oldPos = owner->pos;
// too many false negatives: speed is unreliable if stuck behind an obstacle
// idling = (owner->speed.SqLength() < (accRate * accRate));
// too many false positives: waypoint-distance delta and speed vary too much
// idling = (Square(currWayPointDist - prevWayPointDist) < owner->speed.SqLength());
// too many false positives: many slow units cannot even manage 1 elmo/frame
// idling = (Square(currWayPointDist - prevWayPointDist) < 1.0f);
idling = true;
idling &= (math::fabs(posDif.y) < math::fabs(cmpEps.y * owner->pos.y));
idling &= (Square(currWayPointDist - prevWayPointDist) <= (posDif.SqLength() * 0.5f));
hasMoved = true;
}
return hasMoved;
}
void CGroundMoveType::SlowUpdate()
{
if (owner->GetTransporter() != NULL) {
if (progressState == Active)
StopEngine();
return;
}
if (progressState == Active) {
if (pathId != 0) {
if (idling) {
numIdlingSlowUpdates = std::min(MAX_IDLING_SLOWUPDATES, int(numIdlingSlowUpdates + 1));
} else {
numIdlingSlowUpdates = std::max(0, int(numIdlingSlowUpdates - 1));
}
if (numIdlingUpdates > (SHORTINT_MAXVALUE / turnRate)) {
// case A: we have a path but are not moving
LOG_L(L_DEBUG,
"SlowUpdate: unit %i has pathID %i but %i ETA failures",
owner->id, pathId, numIdlingUpdates);
if (numIdlingSlowUpdates < MAX_IDLING_SLOWUPDATES) {
StopEngine();
StartEngine();
} else {
// unit probably ended up on a non-traversable
// square, or got stuck in a non-moving crowd
Fail();
}
}
} else {
if (gs->frameNum > pathRequestDelay) {
// case B: we want to be moving but don't have a path
LOG_L(L_DEBUG, "SlowUpdate: unit %i has no path", owner->id);
StopEngine();
StartEngine();
}
}
}
if (!flying) {
// move us into the map, and update <oldPos>
// to prevent any extreme changes in <speed>
if (!owner->pos.IsInBounds()) {
owner->pos.ClampInBounds();
oldPos = owner->pos;
}
}
AMoveType::SlowUpdate();
}
/*
Sets unit to start moving against given position with max speed.
*/
void CGroundMoveType::StartMoving(float3 pos, float goalRadius) {
StartMoving(pos, goalRadius, (reversing? maxReverseSpeed: maxSpeed));
}
/*
Sets owner unit to start moving against given position with requested speed.
*/
void CGroundMoveType::StartMoving(float3 moveGoalPos, float _goalRadius, float speed)
{
#ifdef TRACE_SYNC
tracefile << "[" << __FUNCTION__ << "] ";
tracefile << owner->pos.x << " " << owner->pos.y << " " << owner->pos.z << " " << owner->id << "\n";
#endif
if (progressState == Active) {
StopEngine();
}
// set the new goal
goalPos.x = moveGoalPos.x;
goalPos.z = moveGoalPos.z;
goalPos.y = 0.0f;
goalRadius = _goalRadius;
requestedSpeed = speed;
atGoal = false;
useMainHeading = false;
progressState = Active;
numIdlingUpdates = 0;
numIdlingSlowUpdates = 0;
currWayPointDist = 0.0f;
prevWayPointDist = 0.0f;
LOG_L(L_DEBUG, "StartMoving: starting engine for unit %i", owner->id);
StartEngine();
#if (PLAY_SOUNDS == 1)
if (owner->team == gu->myTeam) {
Channels::General.PlayRandomSample(owner->unitDef->sounds.activate, owner);
}
#endif
}
void CGroundMoveType::StopMoving() {
#ifdef TRACE_SYNC
tracefile << "[" << __FUNCTION__ << "] ";
tracefile << owner->pos.x << " " << owner->pos.y << " " << owner->pos.z << " " << owner->id << "\n";
#endif
LOG_L(L_DEBUG, "StopMoving: stopping engine for unit %i", owner->id);
StopEngine();
useMainHeading = false;
progressState = Done;
}
bool CGroundMoveType::FollowPath()
{
bool wantReverse = false;
if (pathId == 0) {
SetDeltaSpeed(0.0f, false);
SetMainHeading();
} else {
ASSERT_SYNCED(currWayPoint);
ASSERT_SYNCED(nextWayPoint);
ASSERT_SYNCED(owner->pos);
prevWayPointDist = currWayPointDist;
currWayPointDist = owner->pos.distance2D(currWayPoint);
{
// NOTE:
// uses owner->pos instead of currWayPoint (ie. not the same as haveFinalWaypoint)
//
// if our first command is a build-order, then goalRadius is set to our build-range
// and we cannot increase tolerance safely (otherwise the unit might stop when still
// outside its range and fail to start construction)
const float curGoalDistSq = (owner->pos - goalPos).SqLength2D();
const float minGoalDistSq = (OWNER_MOVE_CMD())?
Square(goalRadius * (numIdlingSlowUpdates + 1)):
Square(goalRadius );
atGoal |= (curGoalDistSq < minGoalDistSq);
}
if (!atGoal) {
if (!idling) {
numIdlingUpdates = std::max(0, int(numIdlingUpdates - 1));
} else {
numIdlingUpdates = std::min(SHORTINT_MAXVALUE, int(numIdlingUpdates + 1));
}
}
if (!haveFinalWaypoint) {
GetNextWayPoint();
} else {
if (atGoal) {
Arrived();
}
}
// set direction to waypoint AFTER requesting it
waypointDir.x = currWayPoint.x - owner->pos.x;
waypointDir.z = currWayPoint.z - owner->pos.z;
waypointDir.y = 0.0f;
waypointDir.SafeNormalize();
ASSERT_SYNCED(waypointDir);
const float3 wpDirInv = -waypointDir;
// const float3 wpPosTmp = owner->pos.xz + wpDirInv;
const bool wpBehind = (waypointDir.dot(flatFrontDir) < 0.0f);
if (wpBehind) {
wantReverse = WantReverse(waypointDir);
}
// apply obstacle avoidance (steering)
const float3 avoidVec = ObstacleAvoidance(waypointDir);
ASSERT_SYNCED(avoidVec);
if (avoidVec != ZeroVector) {
if (wantReverse) {
ChangeHeading(GetHeadingFromVector(wpDirInv.x, wpDirInv.z));
} else {
// should be waypointDir + avoidanceDir
ChangeHeading(GetHeadingFromVector(avoidVec.x, avoidVec.z));
}
} else {
SetMainHeading();
}
SetDeltaSpeed(requestedSpeed, wantReverse);
}
pathManager->UpdatePath(owner, pathId);
return wantReverse;
}
void CGroundMoveType::SetDeltaSpeed(float newWantedSpeed, bool wantReverse, bool fpsMode)
{
wantedSpeed = newWantedSpeed;
// round low speeds to zero
if (wantedSpeed == 0.0f && currentSpeed < 0.01f) {
currentSpeed = 0.0f;
deltaSpeed = 0.0f;
return;
}
// wanted speed and acceleration
float targetSpeed = wantReverse? maxReverseSpeed: maxSpeed;
#if (WAIT_FOR_PATH == 1)
// don't move until we have an actual path, trying to hide queuing
// lag is too dangerous since units can blindly drive into objects,
// cliffs, etc. (requires the QTPFS idle-check in Update)
if (currWayPoint.y == -1.0f && nextWayPoint.y == -1.0f) {
targetSpeed = 0.0f;
} else
#endif
{
if (wantedSpeed > 0.0f) {
const UnitDef* ud = owner->unitDef;
const float groundMod = ud->movedata->moveMath->GetPosSpeedMod(*ud->movedata, owner->pos, flatFrontDir);
const float curGoalDistSq = (owner->pos - goalPos).SqLength2D();
const float minGoalDistSq = Square(BreakingDistance(currentSpeed));
const float3& goalDifFwd = waypointDir;
const float3 goalDifRev = -goalDifFwd;
const float3 goalDif = reversing? goalDifRev: goalDifFwd;
const short turnDeltaHeading = owner->heading - GetHeadingFromVector(goalDif.x, goalDif.z);
// NOTE: <= 2 because every CMD_MOVE has a trailing CMD_SET_WANTED_MAX_SPEED
const bool startBreaking = (OWNER_CMD_QUE.size() <= 2 && curGoalDistSq <= minGoalDistSq);
if (!fpsMode && turnDeltaHeading != 0) {
// only auto-adjust speed for turns when not in FPS mode
const float reqTurnAngle = math::fabs(180.0f * (owner->heading - wantedHeading) / SHORTINT_MAXVALUE);
const float maxTurnAngle = (turnRate / SPRING_CIRCLE_DIVS) * 360.0f;
float reducedSpeed = (reversing)? maxReverseSpeed: maxSpeed;
if (reqTurnAngle != 0.0f) {
reducedSpeed *= (maxTurnAngle / reqTurnAngle);
}
if (haveFinalWaypoint && !atGoal) {
// at this point, Update() will no longer call GetNextWayPoint()
// and we must slow down to prevent entering an infinite circle
targetSpeed = fastmath::apxsqrt(currWayPointDist * (reversing? accRate: decRate));
}
if (waypointDir.SqLength() > 0.1f) {
if (!ud->turnInPlace) {
targetSpeed = std::max(ud->turnInPlaceSpeedLimit, reducedSpeed);
} else {
if (reqTurnAngle > ud->turnInPlaceAngleLimit) {
targetSpeed = reducedSpeed;
}
}
}
}
targetSpeed *= groundMod;
targetSpeed *= ((startBreaking)? 0.0f: 1.0f);
targetSpeed = std::min(targetSpeed, wantedSpeed);
} else {
targetSpeed = 0.0f;
}
}
const int targetSpeedSign = int(!wantReverse) * 2 - 1;
const int currentSpeedSign = int(!reversing) * 2 - 1;
const float rawSpeedDiff = (targetSpeed * targetSpeedSign) - (currentSpeed * currentSpeedSign);
const float absSpeedDiff = math::fabs(rawSpeedDiff);
// need to clamp, game-supplied values can be much larger than |speedDiff|
const float modAccRate = std::min(absSpeedDiff, accRate);
const float modDecRate = std::min(absSpeedDiff, decRate);
if (reversing) {
// speed-sign in UpdateOwnerPos is negative
// --> to go faster in reverse gear, we need to add +decRate
// --> to go slower in reverse gear, we need to add -accRate
deltaSpeed = (rawSpeedDiff < 0.0f)? modDecRate: -modAccRate;
} else {
// speed-sign in UpdateOwnerPos is positive
// --> to go faster in forward gear, we need to add +accRate
// --> to go slower in forward gear, we need to add -decRate
deltaSpeed = (rawSpeedDiff < 0.0f)? -modDecRate: modAccRate;
}
}
/*
* Changes the heading of the owner.
* FIXME near-duplicate of HoverAirMoveType::UpdateHeading
*/
void CGroundMoveType::ChangeHeading(short newHeading) {
if (flying) return;
if (owner->GetTransporter() != NULL) return;
wantedHeading = newHeading;
SyncedSshort& heading = owner->heading;
const short deltaHeading = wantedHeading - heading;
ASSERT_SYNCED(deltaHeading);
ASSERT_SYNCED(turnRate);
if (deltaHeading > 0) {
heading += std::min(deltaHeading, short(turnRate));
} else {
heading += std::max(deltaHeading, short(-turnRate));
}
owner->UpdateDirVectors(!owner->upright && maxSpeed > 0.0f);
owner->UpdateMidPos();
flatFrontDir = owner->frontdir;
flatFrontDir.y = 0.0f;
flatFrontDir.Normalize();
}
void CGroundMoveType::ImpulseAdded(const float3&)
{
// NOTE: ships must be able to receive impulse too (for collision handling)
if (owner->beingBuilt)
return;
float3& impulse = owner->residualImpulse;
float3& speed = owner->speed;
if (skidding) {
speed += impulse;
impulse = ZeroVector;
}
const float3& groundNormal = ground->GetNormal(owner->pos.x, owner->pos.z);
const float groundImpulseScale = impulse.dot(groundNormal);
if (groundImpulseScale < 0.0f)
impulse -= (groundNormal * groundImpulseScale);
if (impulse.SqLength() <= 9.0f && groundImpulseScale <= 0.3f)
return;
skidding = true;
useHeading = false;
speed += impulse;
impulse = ZeroVector;
skidRotSpeed = 0.0f;
skidRotAccel = 0.0f;
float3 skidDir = owner->frontdir;
if (speed.SqLength2D() >= 0.01f) {
skidDir = speed;
skidDir.y = 0.0f;
skidDir.Normalize();
}
skidRotVector = skidDir.cross(UpVector);
oldPhysState = owner->physicalState;
owner->physicalState = CSolidObject::Flying;
if (speed.dot(groundNormal) > 0.2f) {
skidRotAccel = (gs->randFloat() - 0.5f) * 0.04f;
flying = true;
}
ASSERT_SANE_OWNER_SPEED(speed);
}
void CGroundMoveType::UpdateSkid()
{
ASSERT_SYNCED(owner->midPos);
const float3& pos = owner->pos;
float3& speed = owner->speed;
const UnitDef* ud = owner->unitDef;
const float groundHeight = GetGroundHeight(pos);
if (flying) {
// water drag
if (pos.y < 0.0f)
speed *= 0.95f;
const float impactSpeed = pos.IsInBounds()?
-speed.dot(ground->GetNormal(pos.x, pos.z)):
-speed.dot(UpVector);
const float impactDamageMult = impactSpeed * owner->mass * 0.02f;
const bool doColliderDamage = (modInfo.allowUnitCollisionDamage && impactSpeed > ud->minCollisionSpeed && ud->minCollisionSpeed >= 0.0f);
if (groundHeight > pos.y) {
// ground impact, stop flying
flying = false;
owner->Move1D(groundHeight, 1, false);
// deal ground impact damage
// TODO:
// bouncing behaves too much like a rubber-ball,
// most impact energy needs to go into the ground
if (doColliderDamage) {
owner->DoDamage(DamageArray(impactDamageMult), ZeroVector, NULL, -CSolidObject::DAMAGE_COLLISION_GROUND);
}
skidRotSpeed = 0.0f;
// skidRotAccel = 0.0f;
} else {
speed.y += mapInfo->map.gravity;
}
} else {
float speedf = speed.Length();
float skidRotSpd = 0.0f;
const bool onSlope = OnSlope(-1.0f);
const float speedReduction = 0.35f;
if (speedf < speedReduction && !onSlope) {
// stop skidding
speed = ZeroVector;
skidding = false;
useHeading = true;
owner->physicalState = oldPhysState;
skidRotSpd = math::floor(skidRotSpeed + skidRotAccel + 0.5f);
skidRotAccel = (skidRotSpd - skidRotSpeed) * 0.5f;
skidRotAccel *= (PI / 180.0f);
ChangeHeading(owner->heading);
} else {
if (onSlope) {
const float3 normal = ground->GetNormal(pos.x, pos.z);
const float3 normalForce = normal * normal.dot(UpVector * mapInfo->map.gravity);
const float3 newForce = UpVector * mapInfo->map.gravity - normalForce;
speed += newForce;
speedf = speed.Length();
speed *= (1.0f - (0.1f * normal.y));
} else {
speed *= (1.0f - std::min(1.0f, speedReduction / speedf)); // clamped 0..1
}
// number of frames until rotational speed would drop to 0
const float remTime = std::max(1.0f, speedf / speedReduction);
skidRotSpd = math::floor(skidRotSpeed + skidRotAccel * (remTime - 1.0f) + 0.5f);
skidRotAccel = (skidRotSpd - skidRotSpeed) / remTime;
skidRotAccel *= (PI / 180.0f);
if (math::floor(skidRotSpeed) != math::floor(skidRotSpeed + skidRotAccel)) {
skidRotSpeed = 0.0f;
skidRotAccel = 0.0f;
}
}
if ((groundHeight - pos.y) < (speed.y + mapInfo->map.gravity)) {
speed.y += mapInfo->map.gravity;
flying = true;
skidding = true; // flying requires skidding
useHeading = false; // and relies on CalcSkidRot
} else if ((groundHeight - pos.y) > speed.y) {
const float3& normal = (pos.IsInBounds())? ground->GetNormal(pos.x, pos.z): UpVector;
const float dot = speed.dot(normal);
if (dot > 0.0f) {
speed *= 0.95f;
} else {
speed += (normal * (math::fabs(speed.dot(normal)) + 0.1f)) * 1.9f;
speed *= 0.8f;
}
}
}
// translate before rotate
owner->Move3D(speed, true);
// NOTE: only needed to match terrain normal
if ((pos.y - groundHeight) <= SQUARE_SIZE)
owner->UpdateDirVectors(true);
if (skidding) {
CalcSkidRot();
CheckCollisionSkid();
}
// always update <oldPos> here so that <speed> does not make
// extreme jumps when the unit transitions from skidding back
// to non-skidding
oldPos = owner->pos;
ASSERT_SANE_OWNER_SPEED(speed);
ASSERT_SYNCED(owner->midPos);
}
void CGroundMoveType::UpdateControlledDrop()
{
if (!owner->falling)
return;
const float3& pos = owner->pos;
float3& speed = owner->speed;
speed.y += (mapInfo->map.gravity * owner->fallSpeed);
speed.y = std::min(speed.y, 0.0f);
owner->Move3D(speed, true);
// water drag
if (pos.y < 0.0f)
speed *= 0.90;
const float wh = GetGroundHeight(pos);
if (wh > pos.y) {
// ground impact
owner->falling = false;
owner->Move1D(wh, 1, false);
owner->script->Landed(); //stop parachute animation
}
}
void CGroundMoveType::CheckCollisionSkid()
{
CUnit* collider = owner;
// NOTE:
// the QuadField::Get* functions check o->midPos,
// but the quad(s) that objects are stored in are
// derived from o->pos (!)
const float3& pos = collider->pos;
const UnitDef* colliderUD = collider->unitDef;
const vector<CUnit*>& nearUnits = qf->GetUnitsExact(pos, collider->radius);
const vector<CFeature*>& nearFeatures = qf->GetFeaturesExact(pos, collider->radius);
// magic number to reduce damage taken from collisions
// between a very heavy and a very light CSolidObject
static const float MASS_MULT = 0.02f;
vector<CUnit*>::const_iterator ui;
vector<CFeature*>::const_iterator fi;
for (ui = nearUnits.begin(); ui != nearUnits.end(); ++ui) {
CUnit* collidee = *ui;
const UnitDef* collideeUD = collider->unitDef;
const float sqDist = (pos - collidee->pos).SqLength();
const float totRad = collider->radius + collidee->radius;
if ((sqDist >= totRad * totRad) || (sqDist <= 0.01f)) {
continue;
}
// stop units from reaching escape velocity
const float3 dif = (pos - collidee->pos).SafeNormalize();
if (collidee->mobility == NULL) {
const float impactSpeed = -collider->speed.dot(dif);
const float impactDamageMult = std::min(impactSpeed * collider->mass * MASS_MULT, MAX_UNIT_SPEED);
const bool doColliderDamage = (modInfo.allowUnitCollisionDamage && impactSpeed > colliderUD->minCollisionSpeed && colliderUD->minCollisionSpeed >= 0.0f);
const bool doCollideeDamage = (modInfo.allowUnitCollisionDamage && impactSpeed > collideeUD->minCollisionSpeed && collideeUD->minCollisionSpeed >= 0.0f);
if (impactSpeed <= 0.0f)
continue;
collider->Move3D(dif * impactSpeed, true);
collider->speed += ((dif * impactSpeed) * 1.8f);
// damage the collider, no added impulse
if (doColliderDamage) {
collider->DoDamage(DamageArray(impactDamageMult), ZeroVector, NULL, -CSolidObject::DAMAGE_COLLISION_OBJECT);
}
// damage the (static) collidee based on collider's mass, no added impulse
if (doCollideeDamage) {
collidee->DoDamage(DamageArray(impactDamageMult), ZeroVector, NULL, -CSolidObject::DAMAGE_COLLISION_OBJECT);
}
} else {
// don't conserve momentum
assert(collider->mass > 0.0f && collidee->mass > 0.0f);
const float impactSpeed = (collidee->speed - collider->speed).dot(dif) * 0.5f;
const float colliderRelMass = (collider->mass / (collider->mass + collidee->mass));
const float colliderRelImpactSpeed = impactSpeed * (1.0f - colliderRelMass);
const float collideeRelImpactSpeed = impactSpeed * ( colliderRelMass);
const float colliderImpactDmgMult = std::min(colliderRelImpactSpeed * collider->mass * MASS_MULT, MAX_UNIT_SPEED);
const float collideeImpactDmgMult = std::min(collideeRelImpactSpeed * collider->mass * MASS_MULT, MAX_UNIT_SPEED);
const float3 colliderImpactImpulse = dif * colliderRelImpactSpeed;
const float3 collideeImpactImpulse = dif * collideeRelImpactSpeed;
const bool doColliderDamage = (modInfo.allowUnitCollisionDamage && impactSpeed > colliderUD->minCollisionSpeed && colliderUD->minCollisionSpeed >= 0.0f);
const bool doCollideeDamage = (modInfo.allowUnitCollisionDamage && impactSpeed > collideeUD->minCollisionSpeed && collideeUD->minCollisionSpeed >= 0.0f);
if (impactSpeed <= 0.0f)
continue;
collider->Move3D(colliderImpactImpulse, true);
collidee->Move3D(-collideeImpactImpulse, true);
// damage the collider
if (doColliderDamage) {
collider->DoDamage(DamageArray(colliderImpactDmgMult), dif * colliderImpactDmgMult, NULL, -CSolidObject::DAMAGE_COLLISION_OBJECT);
}
// damage the collidee
if (doCollideeDamage) {
collidee->DoDamage(DamageArray(collideeImpactDmgMult), dif * -collideeImpactDmgMult, NULL, -CSolidObject::DAMAGE_COLLISION_OBJECT);
}
collider->speed += colliderImpactImpulse;
collider->speed *= 0.9f;
collidee->speed -= collideeImpactImpulse;
collidee->speed *= 0.9f;
}
}
for (fi = nearFeatures.begin(); fi != nearFeatures.end(); ++fi) {
CFeature* f = *fi;
if (!f->blocking)
continue;
const float sqDist = (pos - f->pos).SqLength();
const float totRad = collider->radius + f->radius;
if ((sqDist >= totRad * totRad) || (sqDist <= 0.01f))
continue;
const float3 dif = (pos - f->pos).SafeNormalize();
const float impactSpeed = -collider->speed.dot(dif);
const float impactDamageMult = std::min(impactSpeed * collider->mass * MASS_MULT, MAX_UNIT_SPEED);
const float3 impactImpulse = dif * impactSpeed;
const bool doColliderDamage = (modInfo.allowUnitCollisionDamage && impactSpeed > colliderUD->minCollisionSpeed && colliderUD->minCollisionSpeed >= 0.0f);
if (impactSpeed <= 0.0f)
continue;
collider->Move3D(impactImpulse, true);
collider->speed += (impactImpulse * 1.8f);
// damage the collider, no added impulse (!)
if (doColliderDamage) {
collider->DoDamage(DamageArray(impactDamageMult), ZeroVector, NULL, -CSolidObject::DAMAGE_COLLISION_OBJECT);
}
// damage the collidee feature based on collider's mass
f->DoDamage(DamageArray(impactDamageMult), -impactImpulse, NULL, -CSolidObject::DAMAGE_COLLISION_OBJECT);
}
ASSERT_SANE_OWNER_SPEED(collider->speed);
}
void CGroundMoveType::CalcSkidRot()
{
skidRotSpeed += skidRotAccel;
skidRotSpeed *= 0.999f;
skidRotAccel *= 0.95f;
const float angle = (skidRotSpeed / GAME_SPEED) * (PI * 2.0f);
const float cosp = math::cos(angle);
const float sinp = math::sin(angle);
float3 f1 = skidRotVector * skidRotVector.dot(owner->frontdir);
float3 f2 = owner->frontdir - f1;
float3 r1 = skidRotVector * skidRotVector.dot(owner->rightdir);
float3 r2 = owner->rightdir - r1;
float3 u1 = skidRotVector * skidRotVector.dot(owner->updir);
float3 u2 = owner->updir - u1;
f2 = f2 * cosp + f2.cross(skidRotVector) * sinp;
r2 = r2 * cosp + r2.cross(skidRotVector) * sinp;
u2 = u2 * cosp + u2.cross(skidRotVector) * sinp;
owner->frontdir = f1 + f2;
owner->rightdir = r1 + r2;
owner->updir = u1 + u2;
owner->UpdateMidPos();
}
/*
* Dynamic obstacle avoidance, helps the unit to
* follow the path even when it's not perfect.
*/
float3 CGroundMoveType::ObstacleAvoidance(const float3& desiredDir) {
#if (IGNORE_OBSTACLES == 1)
return desiredDir;
#endif
// multiplier for how strongly an object should be avoided
static const float AVOIDANCE_STRENGTH = 8000.0f;
// Obstacle-avoidance-system only needs to be run if the unit wants to move
if (pathId == 0)
return ZeroVector;
float3 avoidanceVec = ZeroVector;
float3 avoidanceDir = desiredDir;
// Speed-optimizer. Reduces the times this system is run.
if (gs->frameNum < nextObstacleAvoidanceUpdate)
return lastAvoidanceDir;
lastAvoidanceDir = desiredDir;
nextObstacleAvoidanceUpdate = gs->frameNum + 4;
CUnit* avoider = owner;
MoveData* avoiderMD = avoider->mobility;
CMoveMath* avoiderMM = avoiderMD->moveMath;
avoiderMD->tempOwner = avoider;
// now we do the obstacle avoidance proper
// avoider always uses its never-rotated MoveDef footprint
const float avoidanceRadius = std::max(currentSpeed, 1.0f) * (avoider->radius * 2.0f);
const float avoiderRadius = FOOTPRINT_RADIUS(avoiderMD->xsize, avoiderMD->zsize, 1.0f);
const float3 rightOfPath = desiredDir.cross(UpVector);
float avoidLeft = 0.0f;
float avoidRight = 0.0f;
const vector<CSolidObject*>& nearbyObjects = qf->GetSolidsExact(avoider->pos, avoidanceRadius);
for (vector<CSolidObject*>::const_iterator oi = nearbyObjects.begin(); oi != nearbyObjects.end(); ++oi) {
CSolidObject* avoidee = *oi;
MoveData* avoideeMD = avoidee->mobility;
// cases in which there is no need to avoid this obstacle
if (avoidee == owner)
continue;
if (avoiderMM->IsNonBlocking(*avoiderMD, avoidee))
continue;
if (!avoiderMM->CrushResistant(*avoiderMD, avoidee))
continue;
// ignore objects that are slightly behind us
if ((desiredDir.dot(avoidee->pos - avoider->pos) + 0.25f) <= 0.0f)
continue;
const bool avoideeMobile = (avoideeMD != NULL);
const float3 avoideeVector = (avoider->pos - avoidee->pos - avoidee->speed * GAME_SPEED);
const float avoideeDistSq = avoideeVector.SqLength();
// use the avoidee's MoveDef footprint if it is mobile
// use the avoidee's Unit (not UnitDef) footprint otherwise
const float avoideeRadius = avoideeMobile?
FOOTPRINT_RADIUS(avoideeMD->xsize, avoideeMD->zsize, 1.0f):
FOOTPRINT_RADIUS(avoidee ->xsize, avoidee ->zsize, 1.0f);
const float avoidanceRadiusSum = avoiderRadius + avoideeRadius;
const float avoidanceMassSum = avoider->mass + avoidee->mass;
const float avoideeMassScale = (avoideeMobile)? (avoidee->mass / avoidanceMassSum): 1.0f;
if (avoideeMobile && !avoiderMD->avoidMobilesOnPath)
continue;
if (avoideeDistSq >= Square(currentSpeed * GAME_SPEED + avoidanceRadiusSum))
continue;
if (avoideeDistSq >= avoider->pos.SqDistance2D(goalPos))
continue;
// note: positive angle cosines mean object is to our right
const float avoideeDistToAvoidDirCenter = avoideeVector.dot(rightOfPath);
if (avoideeVector.dot(avoidanceDir) >= avoidanceRadiusSum)
continue;
if (math::fabs(avoideeDistToAvoidDirCenter) >= avoidanceRadiusSum)
continue;
// do not bother steering around idling objects
// (collision handling will push them aside, or
// us in case of "allied" features)
if (!avoidee->isMoving && avoidee->allyteam == avoider->allyteam)
continue;
// if object and unit in relative motion are closing in on one another
// (or not yet fully apart), then the object is on the path of the unit
// and they are not collided
if (avoideeMobile || (Distance2D(owner, avoidee, SQUARE_SIZE) >= 0.0f)) {
#if (DEBUG_OUTPUT == 1)
{
GML_RECMUTEX_LOCK(sel); // ObstacleAvoidance
if (selectedUnits.selectedUnits.find(owner) != selectedUnits.selectedUnits.end()) {
geometricObjects->AddLine(avoider->pos + UpVector * 20, object->pos + UpVector * 20, 3, 1, 4);
}
}
#endif
const float iSqrtDist = (avoideeDistSq <= 1e-4f)? 1e-2f: math::isqrt2(avoideeDistSq);
const float avoidScale = (AVOIDANCE_STRENGTH * iSqrtDist * iSqrtDist * iSqrtDist) * avoideeMassScale;
// avoid collision by turning either left or right
// using the direction thats needs most adjustment
if (avoideeDistToAvoidDirCenter > 0.0f) {
avoidRight += ((avoidanceRadiusSum - avoideeDistToAvoidDirCenter) * avoidScale);
} else {
avoidLeft += ((avoidanceRadiusSum + avoideeDistToAvoidDirCenter) * avoidScale);
}
}
}
avoiderMD->tempOwner = NULL;
// Sum up avoidance.
avoidanceVec = (desiredDir.cross(UpVector) * (avoidRight - avoidLeft));
#if (DEBUG_OUTPUT == 1)
{
GML_RECMUTEX_LOCK(sel); // ObstacleAvoidance
if (selectedUnits.selectedUnits.find(owner) != selectedUnits.selectedUnits.end()) {
int a = geometricObjects->AddLine(avoider->pos + UpVector * 20, avoider->pos + UpVector * 20 + avoidanceVec * 40, 7, 1, 4);
geometricObjects->SetColor(a, 1, 0.3f, 0.3f, 0.6f);
a = geometricObjects->AddLine(avoider->pos + UpVector * 20, avoider->pos + UpVector * 20 + desiredDir * 40, 7, 1, 4);
geometricObjects->SetColor(a, 0.3f, 0.3f, 1, 0.6f);
}
}
#endif
// Return the resulting recommended velocity.
avoidanceDir = (desiredDir + avoidanceVec).SafeNormalize();
#ifdef TRACE_SYNC
tracefile << "[" << __FUNCTION__ << "] ";
tracefile << "avoidanceVec = <" << avoidanceVec.x << " " << avoidanceVec.y << " " << avoidanceVec.z << ">\n";
#endif
return (lastAvoidanceDir = avoidanceDir);
}
// Calculates an aproximation of the physical 2D-distance between given two objects.
float CGroundMoveType::Distance2D(CSolidObject* object1, CSolidObject* object2, float marginal)
{
// calculate the distance in (x,z) depending
// on the shape of the object footprints
float dist2D;
if (object1->xsize == object1->zsize || object2->xsize == object2->zsize) {
// use xsize as a cylindrical radius.
float3 distVec = (object1->midPos - object2->midPos);
dist2D = distVec.Length2D() - (object1->xsize + object2->xsize) * SQUARE_SIZE / 2 + 2 * marginal;
} else {
// Pytagorean sum of the x and z distance.
float3 distVec;
const float xdiff = math::fabs(object1->midPos.x - object2->midPos.x);
const float zdiff = math::fabs(object1->midPos.z - object2->midPos.z);
distVec.x = xdiff - (object1->xsize + object2->xsize) * SQUARE_SIZE / 2 + 2 * marginal;
distVec.z = zdiff - (object1->zsize + object2->zsize) * SQUARE_SIZE / 2 + 2 * marginal;
if (distVec.x > 0.0f && distVec.z > 0.0f) {
dist2D = distVec.Length2D();
} else if (distVec.x < 0.0f && distVec.z < 0.0f) {
dist2D = -distVec.Length2D();
} else if (distVec.x > 0.0f) {
dist2D = distVec.x;
} else {
dist2D = distVec.z;
}
}
return dist2D;
}
// Creates a path to the goal.
void CGroundMoveType::GetNewPath()
{
assert(pathId == 0);
pathId = pathManager->RequestPath(owner->mobility, owner->pos, goalPos, goalRadius, owner);
// if new path received, can't be at waypoint
if (pathId != 0) {
atGoal = false;
haveFinalWaypoint = false;
currWayPoint = pathManager->NextWayPoint(pathId, owner->pos, 1.25f * SQUARE_SIZE, 0, owner->id);
nextWayPoint = pathManager->NextWayPoint(pathId, currWayPoint, 1.25f * SQUARE_SIZE, 0, owner->id);
} else {
Fail();
}
// limit frequency of (case B) path-requests from SlowUpdate's
pathRequestDelay = gs->frameNum + (UNIT_SLOWUPDATE_RATE << 1);
}
/*
Sets waypoint to next in path.
*/
void CGroundMoveType::GetNextWayPoint()
{
if (pathId == 0) {
return;
}
if (currWayPoint.y != -1.0f && nextWayPoint.y != -1.0f) {
#if (DEBUG_OUTPUT == 1)
// plot the vectors to {curr, next}WayPoint
const float3& pos = owner->pos;
const float3& cwp = currWayPoint;
const float3& nwp = nextWayPoint;
const int cwpFigGroupID = geometricObjects->AddLine(pos + (UpVector * 20.0f), cwp + (UpVector * (pos.y + 20.0f)), 8.0f, 1, 4);
const int nwpFigGroupID = geometricObjects->AddLine(pos + (UpVector * 20.0f), nwp + (UpVector * (pos.y + 20.0f)), 8.0f, 1, 4);
geometricObjects->SetColor(cwpFigGroupID, 1, 0.3f, 0.3f, 0.6f);
geometricObjects->SetColor(nwpFigGroupID, 1, 0.3f, 0.3f, 0.6f);
#endif
// perform a turn-radius check: if the waypoint
// lies outside our turning circle, don't skip
// it (since we can steer toward this waypoint
// and pass it without slowing down)
// note that we take the DIAMETER of the circle
// to prevent sine-like "snaking" trajectories
const float turnFrames = SPRING_CIRCLE_DIVS / turnRate;
const float turnRadius = (owner->speed.Length() * turnFrames) / (PI + PI);
const int dirSign = int(!reversing) * 2 - 1;
if (currWayPointDist > (turnRadius * 2.0f)) {
return;
}
if (currWayPointDist > MIN_WAYPOINT_DISTANCE && waypointDir.dot(flatFrontDir * dirSign) >= 0.995f) {
return;
}
{
const float curGoalDistSq = (currWayPoint - goalPos).SqLength2D();
const float minGoalDistSq = (OWNER_MOVE_CMD())?
Square(goalRadius * (numIdlingSlowUpdates + 1)):
Square(goalRadius );
// trigger Arrived on the next Update (but
// only if we have non-temporary waypoints)
haveFinalWaypoint |= (curGoalDistSq < minGoalDistSq);
}
if (haveFinalWaypoint) {
currWayPoint = goalPos;
nextWayPoint = goalPos;
return;
}
}
// TODO-QTPFS:
// regularly check if a terrain-change modified our path by comparing
// NextWayPoint(pathId, owner->pos, 1.25f * SQUARE_SIZE, 0, owner->id)
// and waypoint, eg. every 15 frames
// if we do not and a terrain-change area happened to contain <waypoint>
// (the immediate next destination), then the unit will keep heading for
// it and might possibly get stuck
//
if ((nextWayPoint - currWayPoint).SqLength2D() > 0.01f) {
currWayPoint = nextWayPoint;
nextWayPoint = pathManager->NextWayPoint(pathId, currWayPoint, 1.25f * SQUARE_SIZE, 0, owner->id);
if (nextWayPoint.x == -1.0f && nextWayPoint.z == -1.0f) {
Fail();
}
}
}
/*
The distance the unit will move at max breaking before stopping,
starting from given speed.
*/
float CGroundMoveType::BreakingDistance(float speed) const
{
const float rate = reversing? accRate: decRate;
const float time = speed / std::max(rate, 0.001f);
const float dist = 0.5f * rate * time * time;
return dist;
}
/*
Gives the position this unit will end up at with full breaking
from current velocity.
*/
float3 CGroundMoveType::Here()
{
const float dist = BreakingDistance(currentSpeed);
const int sign = int(!reversing) * 2 - 1;
const float3 pos2D = float3(owner->pos.x, 0.0f, owner->pos.z);
const float3 dir2D = flatFrontDir * dist * sign;
return (pos2D + dir2D);
}
void CGroundMoveType::StartEngine() {
// ran only if the unit has no path and is not already at goal
if (pathId == 0 && !atGoal) {
GetNewPath();
// activate "engine" only if a path was found
if (pathId != 0) {
pathManager->UpdatePath(owner, pathId);
owner->isMoving = true;
owner->script->StartMoving();
}
}
nextObstacleAvoidanceUpdate = gs->frameNum;
}
void CGroundMoveType::StopEngine() {
if (pathId != 0) {
pathManager->DeletePath(pathId);
pathId = 0;
if (!atGoal) {
currWayPoint = Here();
}
// Stop animation.
owner->script->StopMoving();
LOG_L(L_DEBUG, "StopEngine: engine stopped for unit %i", owner->id);
}
owner->isMoving = false;
wantedSpeed = 0.0f;
}
/* Called when the unit arrives at its goal. */
void CGroundMoveType::Arrived()
{
// can only "arrive" if the engine is active
if (progressState == Active) {
// we have reached our goal
StopEngine();
#if (PLAY_SOUNDS == 1)
if (owner->team == gu->myTeam) {
Channels::General.PlayRandomSample(owner->unitDef->sounds.arrived, owner);
}
#endif
// and the action is done
progressState = Done;
owner->commandAI->SlowUpdate();
LOG_L(L_DEBUG, "Arrived: unit %i arrived", owner->id);
}
}
/*
Makes the unit fail this action.
No more trials will be done before a new goal is given.
*/
void CGroundMoveType::Fail()
{
LOG_L(L_DEBUG, "Fail: unit %i failed", owner->id);
StopEngine();
// failure of finding a path means that
// this action has failed to reach its goal.
progressState = Failed;
eventHandler.UnitMoveFailed(owner);
eoh->UnitMoveFailed(*owner);
}
void CGroundMoveType::HandleObjectCollisions()
{
static const float3 sepDirMask = float3(1.0f, 0.0f, 1.0f);
CUnit* collider = owner;
collider->mobility->tempOwner = collider;
{
const UnitDef* colliderUD = collider->unitDef;
const MoveData* colliderMD = collider->mobility;
const CMoveMath* colliderMM = colliderMD->moveMath;
// collider always uses its never-rotated MoveDef footprint
//
// allow some degree of inter-penetration (1 - 0.75)
// between objects to avoid sudden extreme responses
const float colliderSpeed = collider->speed.Length();
const float colliderRadius = FOOTPRINT_RADIUS(colliderMD->xsize, colliderMD->zsize, 0.75f);
HandleUnitCollisions(collider, colliderSpeed, colliderRadius, sepDirMask, colliderUD, colliderMD, colliderMM);
HandleFeatureCollisions(collider, colliderSpeed, colliderRadius, sepDirMask, colliderUD, colliderMD, colliderMM);
}
collider->mobility->tempOwner = NULL;
collider->Block();
}
void CGroundMoveType::HandleUnitCollisions(
CUnit* collider,
const float colliderSpeed,
const float colliderRadius,
const float3& sepDirMask,
const UnitDef* colliderUD,
const MoveData* colliderMD,
const CMoveMath* colliderMM
) {
const float searchRadius = std::max(colliderSpeed, 1.0f) * (colliderRadius * 2.0f);
const std::vector<CUnit*>& nearUnits = qf->GetUnitsExact(collider->pos, searchRadius);
std::vector<CUnit*>::const_iterator uit;
// NOTE: probably too large for most units (eg. causes tree falling animations to be skipped)
const int dirSign = int(!reversing) * 2 - 1;
const float3 crushImpulse = collider->speed * collider->mass * dirSign;
for (uit = nearUnits.begin(); uit != nearUnits.end(); ++uit) {
CUnit* collidee = const_cast<CUnit*>(*uit);
if (collidee == collider) { continue; }
if (collidee->moveType->IsSkidding()) { continue; }
if (collidee->moveType->IsFlying()) { continue; }
const bool colliderMobile = (collider->mobility != NULL);
const bool collideeMobile = (collidee->mobility != NULL);
const UnitDef* collideeUD = collidee->unitDef;
const MoveData* collideeMD = collidee->mobility;
const CMoveMath* collideeMM = (collideeMobile)? collideeMD->moveMath: NULL;
// use the collidee's MoveDef footprint if it is mobile
// use the collidee's Unit (not UnitDef) footprint otherwise
const float collideeSpeed = collidee->speed.Length();
const float collideeRadius = collideeMobile?
FOOTPRINT_RADIUS(collideeMD->xsize, collideeMD->zsize, 0.75f):
FOOTPRINT_RADIUS(collidee ->xsize, collidee ->zsize, 0.75f);
const float3 separationVector = collider->pos - collidee->pos;
const float separationMinDistSq = (colliderRadius + collideeRadius) * (colliderRadius + collideeRadius);
if ((separationVector.SqLength() - separationMinDistSq) > 0.01f)
continue;
// NOTE:
// we exclude aircraft (which have NULL mobility) landed
// on the ground, since they would just stack when pushed
bool pushCollider = colliderMobile;
bool pushCollidee = collideeMobile;
bool crushCollidee = false;
// if not an allied collision, neither party is allowed to be pushed (bi-directional) and both stop
// if an allied collision, only the collidee is allowed to be crushed (uni-directional) and neither stop
//
// first rule can be ignored at will by either party (only through Lua) such that it is not stopped
// however neither party can override its pushResistant gene: the party that has it set will ignore
// pushing contributions from the other WITHOUT being forcibly stopped, unless *both* happen to be
// push-resistant (then both are stopped)
const bool alliedCollision =
teamHandler->Ally(collider->allyteam, collidee->allyteam) &&
teamHandler->Ally(collidee->allyteam, collider->allyteam);
const bool collideeYields = (collider->isMoving && !collidee->isMoving);
const bool ignoreCollidee = ((collideeYields && alliedCollision) || colliderUD->pushResistant);
const bool disablePushing =
(colliderUD->pushResistant && !collider->beingBuilt) &&
(collideeUD->pushResistant && !collidee->beingBuilt);
pushCollider &= (alliedCollision || modInfo.allowPushingEnemyUnits || !collider->blockEnemyPushing);
pushCollidee &= (alliedCollision || modInfo.allowPushingEnemyUnits || !collidee->blockEnemyPushing);
pushCollider &= (!disablePushing && !collidee->usingScriptMoveType);
pushCollidee &= (!disablePushing && !collider->usingScriptMoveType);
crushCollidee |= (!alliedCollision || modInfo.allowCrushingAlliedUnits);
crushCollidee &= (collider->speed != ZeroVector);
// don't push/crush either party if the collidee does not block the collider
if (colliderMM->IsNonBlocking(*colliderMD, collidee)) { continue; }
if (crushCollidee && !colliderMM->CrushResistant(*colliderMD, collidee)) { collidee->Kill(crushImpulse, true); }
eventHandler.UnitUnitCollision(collider, collidee);
const float colliderRelRadius = colliderRadius / (colliderRadius + collideeRadius);
const float collideeRelRadius = collideeRadius / (colliderRadius + collideeRadius);
const float collisionRadiusSum = (colliderRadius * colliderRelRadius + collideeRadius * collideeRelRadius);
const float sepDistance = separationVector.Length() + 0.01f;
const float penDistance = std::max(collisionRadiusSum - sepDistance, 1.0f);
const float sepResponse = std::min(SQUARE_SIZE * 2.0f, penDistance * 0.5f);
const float3 sepDirection = (separationVector / sepDistance);
const float3 colResponseVec = sepDirection * sepDirMask * sepResponse;
const float
m1 = collider->mass,
m2 = collidee->mass,
v1 = std::max(1.0f, colliderSpeed), // TODO: precalculate
v2 = std::max(1.0f, collideeSpeed), // TODO: precalculate
c1 = 1.0f + (1.0f - math::fabs(collider->frontdir.dot(-sepDirection))) * 5.0f,
c2 = 1.0f + (1.0f - math::fabs(collidee->frontdir.dot( sepDirection))) * 5.0f,
s1 = m1 * v1 * c1,
s2 = m2 * v2 * c2,
r1 = s1 / (s1 + s2 + 1.0f),
r2 = s2 / (s1 + s2 + 1.0f);
// far from a realistic treatment, but works
float colliderMassScale = std::max(0.01f, std::min(0.99f, 1.0f - r1));
float collideeMassScale = std::max(0.01f, std::min(0.99f, 1.0f - r2));
if (collider->isMoving && collidee->isMoving) {
#define SIGN(v) ((int(v >= 0.0f) * 2) - 1)
// push collider and collidee laterally in opposite directions
const int colliderSign = SIGN( separationVector.dot(collider->rightdir));
const int collideeSign = SIGN(-separationVector.dot(collidee->rightdir));
const float3 colliderSlideVec = collider->rightdir * colliderSign * (1.0f / penDistance);
const float3 collideeSlideVec = collidee->rightdir * collideeSign * (1.0f / penDistance);
if (pushCollider) { collider->Move3D(colliderSlideVec * r2, true); }
if (pushCollidee) { collidee->Move3D(collideeSlideVec * r1, true); }
#undef SIGN
}
if (!collideeMobile) {
CMoveMath::BlockType posBits;
if (collider->speed == ZeroVector)
continue;
posBits = colliderMM->IsBlocked(*colliderMD, collider->pos);
if ((posBits & CMoveMath::BLOCK_STRUCTURE) == 0)
continue;
posBits = colliderMM->IsBlocked(*colliderMD, collider->pos + collider->speed);
if ((posBits & CMoveMath::BLOCK_STRUCTURE) != 0) {
// applied every frame objects are colliding, so be careful
collider->AddImpulse(sepDirection * sepDirMask);
currentSpeed = 0.0f;
deltaSpeed = 0.0f;
if ((gs->frameNum > pathRequestDelay) && ((-sepDirection).dot(owner->frontdir * dirSign) >= 0.5f)) {
// repath iff obstacle is within 60-degree cone; we do this
// because the GNWP lookahead (for non-TIP units) can cause
// corners to be cut across statically blocked squares
//
// NOTE:
// we want an initial speed of 0 to avoid ramming into the
// obstacle again right after the push, but if our leading
// command is not a CMD_MOVE then SetMaxSpeed will not get
// called later and 0 will immobilize us
//
if (OWNER_MOVE_CMD()) {
StartMoving(goalPos, goalRadius, 0.0f);
} else {
StartMoving(goalPos, goalRadius);
}
}
}
}
const float3 colliderPushPos = collider->pos + (colResponseVec * colliderMassScale);
const float3 collideePushPos = collidee->pos - (colResponseVec * collideeMassScale);
const bool cancelColliderPush =
((colliderMM->IsBlocked(*colliderMD, colliderPushPos) & CMoveMath::BLOCK_STRUCTURE) != 0) ||
((colliderMM->GetPosSpeedMod(*colliderMD, colliderPushPos) <= 0.01f));
const bool cancelCollideePush =
(collideeMobile && (collideeMM->IsBlocked(*collideeMD, collideePushPos) & CMoveMath::BLOCK_STRUCTURE) != 0) ||
(collideeMobile && (collideeMM->GetPosSpeedMod(*collideeMD, collideePushPos) <= 0.01f));
// try to prevent both parties from being pushed onto non-traversable
// squares (without stopping them dead in their tracks, which is worse)
if (cancelColliderPush) { colliderMassScale = 0.0f; }
if (cancelCollideePush) { collideeMassScale = 0.0f; }
// ignore pushing contributions from idling friendly collidee's
// (or if we are resistant to them) without stopping; this will
// ONLY take effect if pushCollider is still true
if (ignoreCollidee) {
colliderMassScale *= ((collideeMobile)? 0.0f: 1.0f);
}
// either both parties are pushed, or only one party is pushed and the other is stopped, or both are stopped
if ( pushCollider) { collider->Move3D( colResponseVec * colliderMassScale, true); }
else if (colliderMobile) { collider->Move3D(collider->moveType->oldPos, false); }
if ( pushCollidee) { collidee->Move3D(-colResponseVec * collideeMassScale, true); }
else if (collideeMobile) { collidee->Move3D(collidee->moveType->oldPos, false); }
#if 0
if (!((gs->frameNum + collider->id) & 31) && !colliderCAI->unimportantMove) {
// if we do not have an internal move order, tell units around us to bugger off
// note: this causes too much chaos among the ranks when groups get large
helper->BuggerOff(collider->pos + collider->frontdir * colliderRadius, colliderRadius, true, false, collider->team, collider);
}
#endif
}
}
void CGroundMoveType::HandleFeatureCollisions(
CUnit* collider,
const float colliderSpeed,
const float colliderRadius,
const float3& sepDirMask,
const UnitDef* colliderUD,
const MoveData* colliderMD,
const CMoveMath* colliderMM
) {
const float searchRadius = std::max(colliderSpeed, 1.0f) * (colliderRadius * 2.0f);
const std::vector<CFeature*>& nearFeatures = qf->GetFeaturesExact(collider->pos, searchRadius);
std::vector<CFeature*>::const_iterator fit;
const int dirSign = int(!reversing) * 2 - 1;
const float3 crushImpulse = collider->speed * collider->mass * dirSign;
for (fit = nearFeatures.begin(); fit != nearFeatures.end(); ++fit) {
CFeature* collidee = const_cast<CFeature*>(*fit);
// const FeatureDef* collideeFD = collidee->def;
// use the collidee's Feature (not FeatureDef) footprint
// const float collideeRadius = FOOTPRINT_RADIUS(collideeFD->xsize, collideeFD->zsize, 0.75f);
const float collideeRadius = FOOTPRINT_RADIUS(collidee->xsize, collidee->zsize, 0.75f);
const float3 separationVector = collider->pos - collidee->pos;
const float separationMinDistSq = (colliderRadius + collideeRadius) * (colliderRadius + collideeRadius);
if ((separationVector.SqLength() - separationMinDistSq) > 0.01f)
continue;
if (colliderMM->IsNonBlocking(*colliderMD, collidee)) { continue; }
if (!colliderMM->CrushResistant(*colliderMD, collidee)) { collidee->Kill(crushImpulse, true); }
eventHandler.UnitFeatureCollision(collider, collidee);
const float sepDistance = separationVector.Length() + 0.01f;
const float penDistance = std::max((colliderRadius + collideeRadius) - sepDistance, 1.0f);
const float sepResponse = std::min(SQUARE_SIZE * 2.0f, penDistance * 0.5f);
const float3 sepDirection = (separationVector / sepDistance);
const float3 colResponseVec = sepDirection * sepDirMask * sepResponse;
// multiply the collider's mass by a large constant (so that heavy
// features do not bounce light units away like jittering pinballs;
// collideeMassScale ~= 0.01 suppresses large responses)
const float
m1 = collider->mass,
m2 = collidee->mass * 10000.0f,
v1 = std::max(1.0f, colliderSpeed),
v2 = 1.0f,
c1 = (1.0f - math::fabs( collider->frontdir.dot(-sepDirection))) * 5.0f,
c2 = (1.0f - math::fabs(-collider->frontdir.dot( sepDirection))) * 5.0f,
s1 = m1 * v1 * c1,
s2 = m2 * v2 * c2,
r1 = s1 / (s1 + s2 + 1.0f),
r2 = s2 / (s1 + s2 + 1.0f);
const float colliderMassScale = std::max(0.01f, std::min(0.99f, 1.0f - r1));
// const float collideeMassScale = std::max(0.01f, std::min(0.99f, 1.0f - r2));
if (collidee->reachedFinalPos) {
CMoveMath::BlockType posBits;
if (collider->speed == ZeroVector)
continue;
posBits = colliderMM->IsBlocked(*colliderMD, collider->pos);
if ((posBits & CMoveMath::BLOCK_STRUCTURE) == 0)
continue;
posBits = colliderMM->IsBlocked(*colliderMD, collider->pos + collider->speed);
if ((posBits & CMoveMath::BLOCK_STRUCTURE) != 0) {
// applied every frame objects are colliding, so be careful
collider->AddImpulse(sepDirection * sepDirMask);
currentSpeed = 0.0f;
deltaSpeed = 0.0f;
if ((gs->frameNum > pathRequestDelay) && ((-sepDirection).dot(owner->frontdir * dirSign) >= 0.5f)) {
if (OWNER_MOVE_CMD()) {
StartMoving(goalPos, goalRadius, 0.0f);
} else {
StartMoving(goalPos, goalRadius);
}
}
}
}
collider->Move3D(colResponseVec * colliderMassScale, true);
}
}
void CGroundMoveType::CreateLineTable()
{
// for every <xt, zt> pair, computes a set of regularly spaced
// grid sample-points (int2 offsets) along the line from <start>
// to <to>; <to> ranges from [x=-4.5, z=-4.5] to [x=+5.5, z=+5.5]
//
// TestNewTerrainSquare() and ObstacleAvoidance() check whether
// squares are blocked at these offsets to get a fast estimate
// of terrain passability
for (int yt = 0; yt < LINETABLE_SIZE; ++yt) {
for (int xt = 0; xt < LINETABLE_SIZE; ++xt) {
// center-point of grid-center cell
const float3 start(0.5f, 0.0f, 0.5f);
// center-point of target cell
const float3 to((xt - (LINETABLE_SIZE / 2)) + 0.5f, 0.0f, (yt - (LINETABLE_SIZE / 2)) + 0.5f);
const float dx = to.x - start.x;
const float dz = to.z - start.z;
float xp = start.x;
float zp = start.z;
if (floor(start.x) == floor(to.x)) {
if (dz > 0.0f) {
for (int a = 1; a <= floor(to.z); ++a)
lineTable[yt][xt].push_back(int2(0, a));
} else {
for (int a = -1; a >= floor(to.z); --a)
lineTable[yt][xt].push_back(int2(0, a));
}
} else if (floor(start.z) == floor(to.z)) {
if (dx > 0.0f) {
for (int a = 1; a <= floor(to.x); ++a)
lineTable[yt][xt].push_back(int2(a, 0));
} else {
for (int a = -1; a >= floor(to.x); --a)
lineTable[yt][xt].push_back(int2(a, 0));
}
} else {
float xn, zn;
bool keepgoing = true;
while (keepgoing) {
if (dx > 0.0f) {
xn = (floor(xp) + 1.0f - xp) / dx;
} else {
xn = (floor(xp) - xp) / dx;
}
if (dz > 0.0f) {
zn = (floor(zp) + 1.0f - zp) / dz;
} else {
zn = (floor(zp) - zp) / dz;
}
if (xn < zn) {
xp += (xn + 0.0001f) * dx;
zp += (xn + 0.0001f) * dz;
} else {
xp += (zn + 0.0001f) * dx;
zp += (zn + 0.0001f) * dz;
}
keepgoing =
math::fabs(xp - start.x) <= math::fabs(to.x - start.x) &&
math::fabs(zp - start.z) <= math::fabs(to.z - start.z);
int2 pt(int(floor(xp)), int(floor(zp)));
static const int MIN_IDX = -int(LINETABLE_SIZE / 2);
static const int MAX_IDX = -MIN_IDX;
if (MIN_IDX > pt.x || pt.x > MAX_IDX) continue;
if (MIN_IDX > pt.y || pt.y > MAX_IDX) continue;
lineTable[yt][xt].push_back(pt);
}
}
}
}
}
void CGroundMoveType::DeleteLineTable()
{
for (int yt = 0; yt < LINETABLE_SIZE; ++yt) {
for (int xt = 0; xt < LINETABLE_SIZE; ++xt) {
lineTable[yt][xt].clear();
}
}
}
void CGroundMoveType::TestNewTerrainSquare()
{
// first make sure we don't go into any terrain we cant get out of
int newMoveSquareX = owner->pos.x / (MIN_WAYPOINT_DISTANCE);
int newMoveSquareY = owner->pos.z / (MIN_WAYPOINT_DISTANCE);
float3 newpos = owner->pos;
if (newMoveSquareX != moveSquareX || newMoveSquareY != moveSquareY) {
const CMoveMath* movemath = owner->unitDef->movedata->moveMath;
const MoveData& md = *(owner->unitDef->movedata);
const float cmod = movemath->GetPosSpeedMod(md, moveSquareX, moveSquareY);
if (math::fabs(owner->frontdir.x) < math::fabs(owner->frontdir.z)) {
if (newMoveSquareX > moveSquareX) {
const float nmod = movemath->GetPosSpeedMod(md, newMoveSquareX, newMoveSquareY);
if (cmod > 0.01f && nmod <= 0.01f) {
newpos.x = moveSquareX * MIN_WAYPOINT_DISTANCE + (MIN_WAYPOINT_DISTANCE - 0.01f);
newMoveSquareX = moveSquareX;
}
} else if (newMoveSquareX < moveSquareX) {
const float nmod = movemath->GetPosSpeedMod(md, newMoveSquareX, newMoveSquareY);
if (cmod > 0.01f && nmod <= 0.01f) {
newpos.x = moveSquareX * MIN_WAYPOINT_DISTANCE + 0.01f;
newMoveSquareX = moveSquareX;
}
}
if (newMoveSquareY > moveSquareY) {
const float nmod = movemath->GetPosSpeedMod(md, newMoveSquareX, newMoveSquareY);
if (cmod > 0.01f && nmod <= 0.01f) {
newpos.z = moveSquareY * MIN_WAYPOINT_DISTANCE + (MIN_WAYPOINT_DISTANCE - 0.01f);
newMoveSquareY = moveSquareY;
}
} else if (newMoveSquareY < moveSquareY) {
const float nmod = movemath->GetPosSpeedMod(md, newMoveSquareX, newMoveSquareY);
if (cmod > 0.01f && nmod <= 0.01f) {
newpos.z = moveSquareY * MIN_WAYPOINT_DISTANCE + 0.01f;
newMoveSquareY = moveSquareY;
}
}
} else {
if (newMoveSquareY > moveSquareY) {
const float nmod = movemath->GetPosSpeedMod(md, newMoveSquareX, newMoveSquareY);
if (cmod > 0.01f && nmod <= 0.01f) {
newpos.z = moveSquareY * MIN_WAYPOINT_DISTANCE + (MIN_WAYPOINT_DISTANCE - 0.01f);
newMoveSquareY = moveSquareY;
}
} else if (newMoveSquareY < moveSquareY) {
const float nmod = movemath->GetPosSpeedMod(md, newMoveSquareX, newMoveSquareY);
if (cmod > 0.01f && nmod <= 0.01f) {
newpos.z = moveSquareY * MIN_WAYPOINT_DISTANCE + 0.01f;
newMoveSquareY = moveSquareY;
}
}
if (newMoveSquareX > moveSquareX) {
const float nmod = movemath->GetPosSpeedMod(md, newMoveSquareX, newMoveSquareY);
if (cmod > 0.01f && nmod <= 0.01f) {
newpos.x = moveSquareX * MIN_WAYPOINT_DISTANCE + (MIN_WAYPOINT_DISTANCE - 0.01f);
newMoveSquareX = moveSquareX;
}
} else if (newMoveSquareX < moveSquareX) {
const float nmod = movemath->GetPosSpeedMod(md, newMoveSquareX, newMoveSquareY);
if (cmod > 0.01f && nmod <= 0.01f) {
newpos.x = moveSquareX * MIN_WAYPOINT_DISTANCE + 0.01f;
newMoveSquareX = moveSquareX;
}
}
}
// do not teleport units. if the unit is too far away from old position,
// reset the pathfinder instead of teleporting it.
if (newpos.SqDistance2D(owner->pos) > (MIN_WAYPOINT_DISTANCE * MIN_WAYPOINT_DISTANCE)) {
newMoveSquareX = (int) owner->pos.x / (MIN_WAYPOINT_DISTANCE);
newMoveSquareY = (int) owner->pos.z / (MIN_WAYPOINT_DISTANCE);
} else {
owner->Move3D(newpos, false);
}
if (newMoveSquareX != moveSquareX || newMoveSquareY != moveSquareY) {
moveSquareX = newMoveSquareX;
moveSquareY = newMoveSquareY;
// if we have moved, check if we can get to the next waypoint
int nwsx = (int) nextWayPoint.x / (MIN_WAYPOINT_DISTANCE) - moveSquareX;
int nwsy = (int) nextWayPoint.z / (MIN_WAYPOINT_DISTANCE) - moveSquareY;
int numIter = 0;
static const unsigned int blockBits =
CMoveMath::BLOCK_STRUCTURE |
CMoveMath::BLOCK_MOBILE |
CMoveMath::BLOCK_MOBILE_BUSY;
while ((nwsx * nwsx + nwsy * nwsy) < LINETABLE_SIZE && !haveFinalWaypoint && pathId != 0) {
const int ltx = nwsx + LINETABLE_SIZE / 2;
const int lty = nwsy + LINETABLE_SIZE / 2;
bool wpOk = true;
if (ltx >= 0 && ltx < LINETABLE_SIZE && lty >= 0 && lty < LINETABLE_SIZE) {
for (std::vector<int2>::iterator li = lineTable[lty][ltx].begin(); li != lineTable[lty][ltx].end(); ++li) {
const int x = (moveSquareX + li->x);
const int y = (moveSquareY + li->y);
if ((movemath->IsBlocked(md, x, y) & blockBits) ||
movemath->GetPosSpeedMod(md, x, y) <= 0.01f) {
wpOk = false;
break;
}
}
}
if (!wpOk || numIter > 6) {
break;
}
GetNextWayPoint();
nwsx = (int) nextWayPoint.x / (MIN_WAYPOINT_DISTANCE) - moveSquareX;
nwsy = (int) nextWayPoint.z / (MIN_WAYPOINT_DISTANCE) - moveSquareY;
++numIter;
}
}
}
}
void CGroundMoveType::LeaveTransport()
{
oldPos = owner->pos + UpVector * 0.001f;
}
void CGroundMoveType::KeepPointingTo(float3 pos, float distance, bool aggressive) {
mainHeadingPos = pos;
useMainHeading = aggressive;
if (!useMainHeading) return;
if (owner->weapons.empty()) return;
CWeapon* frontWeapon = owner->weapons.front();
if (!frontWeapon->weaponDef->waterweapon && mainHeadingPos.y <= 1.0f) {
mainHeadingPos.y = 1.0f;
}
float3 dir1 = frontWeapon->mainDir;
float3 dir2 = mainHeadingPos - owner->pos;
dir1.y = 0.0f;
dir1.Normalize();
dir2.y = 0.0f;
dir2.SafeNormalize();
if (dir2 == ZeroVector)
return;
short heading =
GetHeadingFromVector(dir2.x, dir2.z) -
GetHeadingFromVector(dir1.x, dir1.z);
if (owner->heading == heading)
return;
if (!frontWeapon->TryTarget(mainHeadingPos, true, 0)) {
progressState = Active;
}
}
void CGroundMoveType::KeepPointingTo(CUnit* unit, float distance, bool aggressive) {
//! wrapper
KeepPointingTo(unit->pos, distance, aggressive);
}
/**
* @brief Orients owner so that weapon[0]'s arc includes mainHeadingPos
*/
void CGroundMoveType::SetMainHeading() {
if (!useMainHeading) return;
if (owner->weapons.empty()) return;
CWeapon* frontWeapon = owner->weapons.front();
float3 dir1 = frontWeapon->mainDir;
float3 dir2 = mainHeadingPos - owner->pos;
dir1.y = 0.0f;
dir1.Normalize();
dir2.y = 0.0f;
dir2.SafeNormalize();
ASSERT_SYNCED(dir1);
ASSERT_SYNCED(dir2);
if (dir2 == ZeroVector)
return;
short heading =
GetHeadingFromVector(dir2.x, dir2.z) -
GetHeadingFromVector(dir1.x, dir1.z);
ASSERT_SYNCED(heading);
if (progressState == Active) {
if (owner->heading == heading) {
// stop turning
owner->script->StopMoving();
progressState = Done;
} else {
ChangeHeading(heading);
}
} else {
if (owner->heading != heading) {
if (!frontWeapon->TryTarget(mainHeadingPos, true, 0)) {
// start moving
progressState = Active;
owner->script->StartMoving();
ChangeHeading(heading);
}
}
}
}
void CGroundMoveType::SetMaxSpeed(float speed)
{
maxSpeed = std::min(speed, maxSpeedDef);
maxReverseSpeed = std::min(speed, maxReverseSpeed);
requestedSpeed = speed;
}
bool CGroundMoveType::OnSlope(float minSlideTolerance) {
const UnitDef* ud = owner->unitDef;
const float3& pos = owner->pos;
if (ud->slideTolerance < minSlideTolerance) { return false; }
if (owner->unitDef->floatOnWater && owner->inWater) { return false; }
if (!pos.IsInBounds()) { return false; }
// if minSlideTolerance is zero, do not multiply maxSlope by ud->slideTolerance
// (otherwise the unit could stop on an invalid path location, and be teleported
// back)
const float gSlope = ground->GetSlope(pos.x, pos.z);
const float uSlope = ud->movedata->maxSlope * ((minSlideTolerance <= 0.0f)? 1.0f: ud->slideTolerance);
return (gSlope > uSlope);
}
float CGroundMoveType::GetGroundHeight(const float3& p) const
{
float h = 0.0f;
if (owner->unitDef->floatOnWater) {
// in [0, maxHeight]
h = ground->GetHeightAboveWater(p.x, p.z);
} else {
// in [minHeight, maxHeight]
h = ground->GetHeightReal(p.x, p.z);
}
return h;
}
void CGroundMoveType::AdjustPosToWaterLine()
{
if (!(owner->falling || flying)) {
float groundHeight = GetGroundHeight(owner->pos);
if (owner->unitDef->floatOnWater && owner->inWater && groundHeight <= 0.0f) {
groundHeight = -owner->unitDef->waterline;
}
owner->Move1D(groundHeight, 1, false);
/*
const UnitDef* ud = owner->unitDef;
const MoveData* md = ud->movedata;
const CMoveMath* mm = md->moveMath;
y = mm->yLevel(owner->pos.x, owner->pos.z);
if (owner->unitDef->floatOnWater && owner->inWater) {
y -= owner->unitDef->waterline;
}
owner->Move1D(y, 1, false);
*/
}
}
bool CGroundMoveType::UpdateDirectControl()
{
const CPlayer* myPlayer = gu->GetMyPlayer();
const FPSUnitController& selfCon = myPlayer->fpsController;
const FPSUnitController& unitCon = owner->fpsControlPlayer->fpsController;
const bool wantReverse = (unitCon.back && !unitCon.forward);
float turnSign = 0.0f;
currWayPoint.x = owner->pos.x + owner->frontdir.x * (wantReverse)? -100.0f: 100.0f;
currWayPoint.z = owner->pos.z + owner->frontdir.z * (wantReverse)? -100.0f: 100.0f;
currWayPoint.ClampInBounds();
if (unitCon.forward) {
SetDeltaSpeed(maxSpeed, wantReverse, true);
owner->isMoving = true;
owner->script->StartMoving();
} else if (unitCon.back) {
SetDeltaSpeed(maxReverseSpeed, wantReverse, true);
owner->isMoving = true;
owner->script->StartMoving();
} else {
// not moving forward or backward, stop
SetDeltaSpeed(0.0f, false, true);
owner->isMoving = false;
owner->script->StopMoving();
}
if (unitCon.left ) { ChangeHeading(owner->heading + turnRate); turnSign = 1.0f; }
if (unitCon.right) { ChangeHeading(owner->heading - turnRate); turnSign = -1.0f; }
if (selfCon.GetControllee() == owner) {
camera->rot.y += (turnRate * turnSign * TAANG2RAD);
}
return wantReverse;
}
void CGroundMoveType::UpdateOwnerPos(bool wantReverse)
{
if (wantedSpeed > 0.0f || currentSpeed != 0.0f) {
if (wantReverse) {
if (!reversing) {
reversing = (currentSpeed <= accRate);
}
} else {
if (reversing) {
reversing = (currentSpeed > accRate);
}
}
const UnitDef* ud = owner->unitDef;
const MoveData* md = ud->movedata;
const CMoveMath* mm = md->moveMath;
const int speedSign = int(!reversing) * 2 - 1;
const float speedScale = std::min(currentSpeed + deltaSpeed, (reversing? maxReverseSpeed: maxSpeed));
const float3 speedVector = owner->frontdir * speedScale * speedSign;
owner->speed = speedVector;
if (mm->GetPosSpeedMod(*md, owner->pos + owner->speed) <= 0.01f) {
// never move onto an impassable square (units
// can still tunnel across them at high enough
// speeds however)
owner->speed = ZeroVector;
} else {
// use the simplest possible Euler integration
owner->Move3D(owner->speed, true);
}
currentSpeed = (owner->speed != ZeroVector)? speedScale: 0.0f;
deltaSpeed = 0.0f;
assert(math::fabs(currentSpeed) < 1e6f);
}
if (!wantReverse && currentSpeed == 0.0f) {
reversing = false;
}
}
bool CGroundMoveType::WantReverse(const float3& waypointDir2D) const
{
if (!canReverse)
return false;
// these values are normally non-0, but LuaMoveCtrl
// can override them and we do not want any div0's
if (maxReverseSpeed <= 0.0f) return false;
if (maxSpeed <= 0.0f) return true;
if (accRate <= 0.0f) return false;
if (decRate <= 0.0f) return false;
if (turnRate <= 0.0f) return false;
const float3 waypointDif = float3(goalPos.x - owner->pos.x, 0.0f, goalPos.z - owner->pos.z); // use final WP for ETA
const float waypointDist = waypointDif.Length(); // in elmos
const float waypointFETA = (waypointDist / maxSpeed); // in frames (simplistic)
const float waypointRETA = (waypointDist / maxReverseSpeed); // in frames (simplistic)
const float waypointDirDP = waypointDir2D.dot(owner->frontdir);
const float waypointAngle = Clamp(waypointDirDP, -1.0f, 1.0f); // prevent NaN's
const float turnAngleDeg = math::acosf(waypointAngle) * RAD2DEG; // in degrees
const float turnAngleSpr = (turnAngleDeg / 360.0f) * SPRING_CIRCLE_DIVS; // in "headings"
const float revAngleSpr = SHORTINT_MAXVALUE - turnAngleSpr; // 180 deg - angle
// units start accelerating before finishing the turn, so subtract something
const float turnTimeMod = 5.0f;
const float turnAngleTime = std::max(0.0f, (turnAngleSpr / turnRate) - turnTimeMod); // in frames
const float revAngleTime = std::max(0.0f, (revAngleSpr / turnRate) - turnTimeMod);
const float apxSpeedAfterTurn = std::max(0.f, currentSpeed - 0.125f * (turnAngleTime * decRate));
const float apxRevSpdAfterTurn = std::max(0.f, currentSpeed - 0.125f * (revAngleTime * decRate));
const float decTime = ( reversing * apxSpeedAfterTurn) / decRate;
const float revDecTime = (!reversing * apxRevSpdAfterTurn) / decRate;
const float accTime = (maxSpeed - !reversing * apxSpeedAfterTurn) / accRate;
const float revAccTime = (maxReverseSpeed - reversing * apxRevSpdAfterTurn) / accRate;
const float revAccDecTime = revDecTime + revAccTime;
const float fwdETA = waypointFETA + turnAngleTime + accTime + decTime;
const float revETA = waypointRETA + revAngleTime + revAccDecTime;
return (fwdETA > revETA);
}
|