bevy_input/gamepad.rs
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 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763
//! The gamepad input functionality.
use crate::{Axis, ButtonInput, ButtonState};
use bevy_core::Name;
use bevy_ecs::{
change_detection::DetectChangesMut,
component::Component,
entity::Entity,
event::{Event, EventReader, EventWriter},
system::{Commands, Query},
};
use bevy_math::Vec2;
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::{std_traits::ReflectDefault, Reflect};
#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
use bevy_utils::{
tracing::{info, warn},
Duration, HashMap,
};
use derive_more::derive::{Display, Error, From};
/// A gamepad event.
///
/// This event type is used over the [`GamepadConnectionEvent`],
/// [`GamepadButtonChangedEvent`] and [`GamepadAxisChangedEvent`] when
/// the in-frame relative ordering of events is important.
///
/// This event is produced by `bevy_input`
#[derive(Event, Debug, Clone, PartialEq, From)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq))]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub enum GamepadEvent {
/// A gamepad has been connected or disconnected.
Connection(GamepadConnectionEvent),
/// A button of the gamepad has been triggered.
Button(GamepadButtonChangedEvent),
/// An axis of the gamepad has been triggered.
Axis(GamepadAxisChangedEvent),
}
/// A raw gamepad event.
///
/// This event type is used over the [`GamepadConnectionEvent`],
/// [`RawGamepadButtonChangedEvent`] and [`RawGamepadAxisChangedEvent`] when
/// the in-frame relative ordering of events is important.
///
/// This event type is used by `bevy_input` to feed its components.
#[derive(Event, Debug, Clone, PartialEq, Reflect, From)]
#[reflect(Debug, PartialEq)]
#[cfg_attr(
feature = "serialize",
derive(serde::Serialize, serde::Deserialize),
reflect(Serialize, Deserialize)
)]
pub enum RawGamepadEvent {
/// A gamepad has been connected or disconnected.
Connection(GamepadConnectionEvent),
/// A button of the gamepad has been triggered.
Button(RawGamepadButtonChangedEvent),
/// An axis of the gamepad has been triggered.
Axis(RawGamepadAxisChangedEvent),
}
/// [`GamepadButton`] changed event unfiltered by [`GamepadSettings`]
#[derive(Event, Debug, Copy, Clone, PartialEq, Reflect)]
#[reflect(Debug, PartialEq)]
#[cfg_attr(
feature = "serialize",
derive(serde::Serialize, serde::Deserialize),
reflect(Serialize, Deserialize)
)]
pub struct RawGamepadButtonChangedEvent {
/// The gamepad on which the button is triggered.
pub gamepad: Entity,
/// The type of the triggered button.
pub button: GamepadButton,
/// The value of the button.
pub value: f32,
}
impl RawGamepadButtonChangedEvent {
/// Creates a [`RawGamepadButtonChangedEvent`].
pub fn new(gamepad: Entity, button_type: GamepadButton, value: f32) -> Self {
Self {
gamepad,
button: button_type,
value,
}
}
}
/// [`GamepadAxis`] changed event unfiltered by [`GamepadSettings`]
#[derive(Event, Debug, Copy, Clone, PartialEq, Reflect)]
#[reflect(Debug, PartialEq)]
#[cfg_attr(
feature = "serialize",
derive(serde::Serialize, serde::Deserialize),
reflect(Serialize, Deserialize)
)]
pub struct RawGamepadAxisChangedEvent {
/// The gamepad on which the axis is triggered.
pub gamepad: Entity,
/// The type of the triggered axis.
pub axis: GamepadAxis,
/// The value of the axis.
pub value: f32,
}
impl RawGamepadAxisChangedEvent {
/// Creates a [`RawGamepadAxisChangedEvent`].
pub fn new(gamepad: Entity, axis_type: GamepadAxis, value: f32) -> Self {
Self {
gamepad,
axis: axis_type,
value,
}
}
}
/// A Gamepad connection event. Created when a connection to a gamepad
/// is established and when a gamepad is disconnected.
#[derive(Event, Debug, Clone, PartialEq, Reflect)]
#[reflect(Debug, PartialEq)]
#[cfg_attr(
feature = "serialize",
derive(serde::Serialize, serde::Deserialize),
reflect(Serialize, Deserialize)
)]
pub struct GamepadConnectionEvent {
/// The gamepad whose connection status changed.
pub gamepad: Entity,
/// The change in the gamepads connection.
pub connection: GamepadConnection,
}
impl GamepadConnectionEvent {
/// Creates a [`GamepadConnectionEvent`].
pub fn new(gamepad: Entity, connection: GamepadConnection) -> Self {
Self {
gamepad,
connection,
}
}
/// Is the gamepad connected?
pub fn connected(&self) -> bool {
matches!(self.connection, GamepadConnection::Connected { .. })
}
/// Is the gamepad disconnected?
pub fn disconnected(&self) -> bool {
!self.connected()
}
}
/// [`GamepadButton`] event triggered by a digital state change
#[derive(Event, Debug, Clone, Copy, PartialEq, Eq, Reflect)]
#[reflect(Debug, PartialEq)]
#[cfg_attr(
feature = "serialize",
derive(serde::Serialize, serde::Deserialize),
reflect(Serialize, Deserialize)
)]
pub struct GamepadButtonStateChangedEvent {
/// The entity that represents this gamepad.
pub entity: Entity,
/// The gamepad button assigned to the event.
pub button: GamepadButton,
/// The pressed state of the button.
pub state: ButtonState,
}
impl GamepadButtonStateChangedEvent {
/// Creates a new [`GamepadButtonStateChangedEvent`]
pub fn new(entity: Entity, button: GamepadButton, state: ButtonState) -> Self {
Self {
entity,
button,
state,
}
}
}
/// [`GamepadButton`] event triggered by an analog state change
#[derive(Event, Debug, Clone, Copy, PartialEq, Reflect)]
#[reflect(Debug, PartialEq)]
#[cfg_attr(
feature = "serialize",
derive(serde::Serialize, serde::Deserialize),
reflect(Serialize, Deserialize)
)]
pub struct GamepadButtonChangedEvent {
/// The entity that represents this gamepad.
pub entity: Entity,
/// The gamepad button assigned to the event.
pub button: GamepadButton,
/// The pressed state of the button.
pub state: ButtonState,
/// The analog value of the button.
pub value: f32,
}
impl GamepadButtonChangedEvent {
/// Creates a new [`GamepadButtonChangedEvent`]
pub fn new(entity: Entity, button: GamepadButton, state: ButtonState, value: f32) -> Self {
Self {
entity,
button,
state,
value,
}
}
}
/// [`GamepadAxis`] event triggered by an analog state change
#[derive(Event, Debug, Clone, Copy, PartialEq, Reflect)]
#[reflect(Debug, PartialEq)]
#[cfg_attr(
feature = "serialize",
derive(serde::Serialize, serde::Deserialize),
reflect(Serialize, Deserialize)
)]
pub struct GamepadAxisChangedEvent {
/// The entity that represents this gamepad.
pub entity: Entity,
/// The gamepad axis assigned to the event.
pub axis: GamepadAxis,
/// The value of this axis.
pub value: f32,
}
impl GamepadAxisChangedEvent {
/// Creates a new [`GamepadAxisChangedEvent`]
pub fn new(entity: Entity, axis: GamepadAxis, value: f32) -> Self {
Self {
entity,
axis,
value,
}
}
}
/// Errors that occur when setting axis settings for gamepad input.
#[derive(Error, Display, Debug, PartialEq)]
pub enum AxisSettingsError {
/// The given parameter `livezone_lowerbound` was not in range -1.0..=0.0.
#[display("invalid livezone_lowerbound {_0}, expected value [-1.0..=0.0]")]
#[error(ignore)]
LiveZoneLowerBoundOutOfRange(f32),
/// The given parameter `deadzone_lowerbound` was not in range -1.0..=0.0.
#[display("invalid deadzone_lowerbound {_0}, expected value [-1.0..=0.0]")]
#[error(ignore)]
DeadZoneLowerBoundOutOfRange(f32),
/// The given parameter `deadzone_lowerbound` was not in range -1.0..=0.0.
#[display("invalid deadzone_upperbound {_0}, expected value [0.0..=1.0]")]
#[error(ignore)]
DeadZoneUpperBoundOutOfRange(f32),
/// The given parameter `deadzone_lowerbound` was not in range -1.0..=0.0.
#[display("invalid livezone_upperbound {_0}, expected value [0.0..=1.0]")]
#[error(ignore)]
LiveZoneUpperBoundOutOfRange(f32),
/// Parameter `livezone_lowerbound` was not less than or equal to parameter `deadzone_lowerbound`.
#[display("invalid parameter values livezone_lowerbound {} deadzone_lowerbound {}, expected livezone_lowerbound <= deadzone_lowerbound", livezone_lowerbound, deadzone_lowerbound)]
LiveZoneLowerBoundGreaterThanDeadZoneLowerBound {
/// The value of the `livezone_lowerbound` parameter.
livezone_lowerbound: f32,
/// The value of the `deadzone_lowerbound` parameter.
deadzone_lowerbound: f32,
},
/// Parameter `deadzone_upperbound` was not less than or equal to parameter `livezone_upperbound`.
#[display("invalid parameter values livezone_upperbound {} deadzone_upperbound {}, expected deadzone_upperbound <= livezone_upperbound", livezone_upperbound, deadzone_upperbound)]
DeadZoneUpperBoundGreaterThanLiveZoneUpperBound {
/// The value of the `livezone_upperbound` parameter.
livezone_upperbound: f32,
/// The value of the `deadzone_upperbound` parameter.
deadzone_upperbound: f32,
},
/// The given parameter was not in range 0.0..=2.0.
#[display("invalid threshold {_0}, expected 0.0 <= threshold <= 2.0")]
#[error(ignore)]
Threshold(f32),
}
/// Errors that occur when setting button settings for gamepad input.
#[derive(Error, Display, Debug, PartialEq)]
pub enum ButtonSettingsError {
/// The given parameter was not in range 0.0..=1.0.
#[display("invalid release_threshold {_0}, expected value [0.0..=1.0]")]
#[error(ignore)]
ReleaseThresholdOutOfRange(f32),
/// The given parameter was not in range 0.0..=1.0.
#[display("invalid press_threshold {_0}, expected [0.0..=1.0]")]
#[error(ignore)]
PressThresholdOutOfRange(f32),
/// Parameter `release_threshold` was not less than or equal to `press_threshold`.
#[display("invalid parameter values release_threshold {} press_threshold {}, expected release_threshold <= press_threshold", release_threshold, press_threshold)]
ReleaseThresholdGreaterThanPressThreshold {
/// The value of the `press_threshold` parameter.
press_threshold: f32,
/// The value of the `release_threshold` parameter.
release_threshold: f32,
},
}
/// Stores a connected gamepad's metadata such as the name and its [`GamepadButton`] and [`GamepadAxis`].
///
/// An entity with this component is spawned automatically after [`GamepadConnectionEvent`]
/// and updated by [`gamepad_event_processing_system`].
///
/// See also [`GamepadSettings`] for configuration.
///
/// # Examples
///
/// ```
/// # use bevy_input::gamepad::{Gamepad, GamepadAxis, GamepadButton};
/// # use bevy_ecs::system::Query;
/// # use bevy_core::Name;
/// #
/// fn gamepad_usage_system(gamepads: Query<(&Name, &Gamepad)>) {
/// for (name, gamepad) in &gamepads {
/// println!("{name}");
///
/// if gamepad.just_pressed(GamepadButton::North) {
/// println!("{} just pressed North", name)
/// }
///
/// if let Some(left_stick_x) = gamepad.get(GamepadAxis::LeftStickX) {
/// println!("left stick X: {}", left_stick_x)
/// }
/// }
/// }
/// ```
#[derive(Component, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug))]
#[require(GamepadSettings)]
pub struct Gamepad {
/// The USB vendor ID as assigned by the USB-IF, if available.
pub(crate) vendor_id: Option<u16>,
/// The USB product ID as assigned by the [vendor], if available.
///
/// [vendor]: Self::vendor_id
pub(crate) product_id: Option<u16>,
/// [`ButtonInput`] of [`GamepadButton`] representing their digital state
pub(crate) digital: ButtonInput<GamepadButton>,
/// [`Axis`] of [`GamepadButton`] representing their analog state.
pub(crate) analog: Axis<GamepadInput>,
}
impl Gamepad {
/// Returns the USB vendor ID as assigned by the USB-IF, if available.
pub fn vendor_id(&self) -> Option<u16> {
self.vendor_id
}
/// Returns the USB product ID as assigned by the [vendor], if available.
///
/// [vendor]: Self::vendor_id
pub fn product_id(&self) -> Option<u16> {
self.product_id
}
/// Returns the analog data of the provided [`GamepadAxis`] or [`GamepadButton`].
///
/// This will be clamped between [[`Axis::MIN`],[`Axis::MAX`]].
pub fn get(&self, input: impl Into<GamepadInput>) -> Option<f32> {
self.analog.get(input.into())
}
/// Returns the unclamped analog data of the provided [`GamepadAxis`] or [`GamepadButton`].
///
/// This value may be outside the [`Axis::MIN`] and [`Axis::MAX`] range.
pub fn get_unclamped(&self, input: impl Into<GamepadInput>) -> Option<f32> {
self.analog.get_unclamped(input.into())
}
/// Returns the left stick as a [`Vec2`]
pub fn left_stick(&self) -> Vec2 {
Vec2 {
x: self.get(GamepadAxis::LeftStickX).unwrap_or(0.0),
y: self.get(GamepadAxis::LeftStickY).unwrap_or(0.0),
}
}
/// Returns the right stick as a [`Vec2`]
pub fn right_stick(&self) -> Vec2 {
Vec2 {
x: self.get(GamepadAxis::RightStickX).unwrap_or(0.0),
y: self.get(GamepadAxis::RightStickY).unwrap_or(0.0),
}
}
/// Returns the directional pad as a [`Vec2`]
pub fn dpad(&self) -> Vec2 {
Vec2 {
x: self.get(GamepadButton::DPadRight).unwrap_or(0.0)
- self.get(GamepadButton::DPadLeft).unwrap_or(0.0),
y: self.get(GamepadButton::DPadUp).unwrap_or(0.0)
- self.get(GamepadButton::DPadDown).unwrap_or(0.0),
}
}
/// Returns `true` if the [`GamepadButton`] has been pressed.
pub fn pressed(&self, button_type: GamepadButton) -> bool {
self.digital.pressed(button_type)
}
/// Returns `true` if any item in the [`GamepadButton`] iterator has been pressed.
pub fn any_pressed(&self, button_inputs: impl IntoIterator<Item = GamepadButton>) -> bool {
self.digital.any_pressed(button_inputs)
}
/// Returns `true` if all items in the [`GamepadButton`] iterator have been pressed.
pub fn all_pressed(&self, button_inputs: impl IntoIterator<Item = GamepadButton>) -> bool {
self.digital.all_pressed(button_inputs)
}
/// Returns `true` if the [`GamepadButton`] has been pressed during the current frame.
///
/// Note: This function does not imply information regarding the current state of [`ButtonInput::pressed`] or [`ButtonInput::just_released`].
pub fn just_pressed(&self, button_type: GamepadButton) -> bool {
self.digital.just_pressed(button_type)
}
/// Returns `true` if any item in the [`GamepadButton`] iterator has been pressed during the current frame.
pub fn any_just_pressed(&self, button_inputs: impl IntoIterator<Item = GamepadButton>) -> bool {
self.digital.any_just_pressed(button_inputs)
}
/// Returns `true` if all items in the [`GamepadButton`] iterator have been just pressed.
pub fn all_just_pressed(&self, button_inputs: impl IntoIterator<Item = GamepadButton>) -> bool {
self.digital.all_just_pressed(button_inputs)
}
/// Returns `true` if the [`GamepadButton`] has been released during the current frame.
///
/// Note: This function does not imply information regarding the current state of [`ButtonInput::pressed`] or [`ButtonInput::just_pressed`].
pub fn just_released(&self, button_type: GamepadButton) -> bool {
self.digital.just_released(button_type)
}
/// Returns `true` if any item in the [`GamepadButton`] iterator has just been released.
pub fn any_just_released(
&self,
button_inputs: impl IntoIterator<Item = GamepadButton>,
) -> bool {
self.digital.any_just_released(button_inputs)
}
/// Returns `true` if all items in the [`GamepadButton`] iterator have just been released.
pub fn all_just_released(
&self,
button_inputs: impl IntoIterator<Item = GamepadButton>,
) -> bool {
self.digital.all_just_released(button_inputs)
}
/// Returns an iterator over all digital [button]s that are pressed.
///
/// [button]: GamepadButton
pub fn get_pressed(&self) -> impl Iterator<Item = &GamepadButton> {
self.digital.get_pressed()
}
/// Returns an iterator over all digital [button]s that were just pressed.
///
/// [button]: GamepadButton
pub fn get_just_pressed(&self) -> impl Iterator<Item = &GamepadButton> {
self.digital.get_just_pressed()
}
/// Returns an iterator over all digital [button]s that were just released.
///
/// [button]: GamepadButton
pub fn get_just_released(&self) -> impl Iterator<Item = &GamepadButton> {
self.digital.get_just_released()
}
/// Returns an iterator over all analog [axes].
///
/// [axes]: GamepadInput
pub fn get_analog_axes(&self) -> impl Iterator<Item = &GamepadInput> {
self.analog.all_axes()
}
/// [`ButtonInput`] of [`GamepadButton`] representing their digital state
pub fn digital(&self) -> &ButtonInput<GamepadButton> {
&self.digital
}
/// Mutable [`ButtonInput`] of [`GamepadButton`] representing their digital state. Useful for mocking inputs.
pub fn digital_mut(&mut self) -> &mut ButtonInput<GamepadButton> {
&mut self.digital
}
/// [`Axis`] of [`GamepadButton`] representing their analog state.
pub fn analog(&self) -> &Axis<GamepadInput> {
&self.analog
}
/// Mutable [`Axis`] of [`GamepadButton`] representing their analog state. Useful for mocking inputs.
pub fn analog_mut(&mut self) -> &mut Axis<GamepadInput> {
&mut self.analog
}
}
impl Default for Gamepad {
fn default() -> Self {
let mut analog = Axis::default();
for button in GamepadButton::all().iter().copied() {
analog.set(button, 0.0);
}
for axis_type in GamepadAxis::all().iter().copied() {
analog.set(axis_type, 0.0);
}
Self {
vendor_id: None,
product_id: None,
digital: Default::default(),
analog,
}
}
}
/// Represents gamepad input types that are mapped in the range [0.0, 1.0].
///
/// ## Usage
///
/// This is used to determine which button has changed its value when receiving gamepad button events
/// It is also used in the [`Gamepad`] component.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(
feature = "bevy_reflect",
derive(Reflect),
reflect(Debug, Hash, PartialEq)
)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub enum GamepadButton {
/// The bottom action button of the action pad (i.e. PS: Cross, Xbox: A).
South,
/// The right action button of the action pad (i.e. PS: Circle, Xbox: B).
East,
/// The upper action button of the action pad (i.e. PS: Triangle, Xbox: Y).
North,
/// The left action button of the action pad (i.e. PS: Square, Xbox: X).
West,
/// The C button.
C,
/// The Z button.
Z,
/// The first left trigger.
LeftTrigger,
/// The second left trigger.
LeftTrigger2,
/// The first right trigger.
RightTrigger,
/// The second right trigger.
RightTrigger2,
/// The select button.
Select,
/// The start button.
Start,
/// The mode button.
Mode,
/// The left thumb stick button.
LeftThumb,
/// The right thumb stick button.
RightThumb,
/// The up button of the D-Pad.
DPadUp,
/// The down button of the D-Pad.
DPadDown,
/// The left button of the D-Pad.
DPadLeft,
/// The right button of the D-Pad.
DPadRight,
/// Miscellaneous buttons, considered non-standard (i.e. Extra buttons on a flight stick that do not have a gamepad equivalent).
Other(u8),
}
impl GamepadButton {
/// Returns an array of all the standard [`GamepadButton`]
pub const fn all() -> [GamepadButton; 19] {
[
GamepadButton::South,
GamepadButton::East,
GamepadButton::North,
GamepadButton::West,
GamepadButton::C,
GamepadButton::Z,
GamepadButton::LeftTrigger,
GamepadButton::LeftTrigger2,
GamepadButton::RightTrigger,
GamepadButton::RightTrigger2,
GamepadButton::Select,
GamepadButton::Start,
GamepadButton::Mode,
GamepadButton::LeftThumb,
GamepadButton::RightThumb,
GamepadButton::DPadUp,
GamepadButton::DPadDown,
GamepadButton::DPadLeft,
GamepadButton::DPadRight,
]
}
}
/// Represents gamepad input types that are mapped in the range [-1.0, 1.0]
///
/// ## Usage
///
/// This is used to determine which axis has changed its value when receiving a
/// gamepad axis event. It is also used in the [`Gamepad`] component.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq))]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub enum GamepadAxis {
/// The horizontal value of the left stick.
LeftStickX,
/// The vertical value of the left stick.
LeftStickY,
/// The value of the left `Z` button.
LeftZ,
/// The horizontal value of the right stick.
RightStickX,
/// The vertical value of the right stick.
RightStickY,
/// The value of the right `Z` button.
RightZ,
/// Non-standard support for other axis types (i.e. HOTAS sliders, potentiometers, etc).
Other(u8),
}
impl GamepadAxis {
/// Returns an array of all the standard [`GamepadAxis`].
pub const fn all() -> [GamepadAxis; 6] {
[
GamepadAxis::LeftStickX,
GamepadAxis::LeftStickY,
GamepadAxis::LeftZ,
GamepadAxis::RightStickX,
GamepadAxis::RightStickY,
GamepadAxis::RightZ,
]
}
}
/// Encapsulation over [`GamepadAxis`] and [`GamepadButton`]
// This is done so Gamepad can share a single Axis<T> and simplifies the API by having only one get/get_unclamped method
#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, From)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq))]
pub enum GamepadInput {
/// A [`GamepadAxis`]
Axis(GamepadAxis),
/// A [`GamepadButton`]
Button(GamepadButton),
}
/// Gamepad settings component.
///
/// ## Usage
///
/// It is used to create a `bevy` component that stores the settings of [`GamepadButton`] and [`GamepadAxis`] in [`Gamepad`].
/// If no user defined [`ButtonSettings`], [`AxisSettings`], or [`ButtonAxisSettings`]
/// are defined, the default settings of each are used as a fallback accordingly.
///
/// ## Note
///
/// The [`GamepadSettings`] are used to determine when raw gamepad events
/// should register. Events that don't meet the change thresholds defined in [`GamepadSettings`]
/// will not register. To modify these settings, mutate the corresponding component.
#[derive(Component, Clone, Default, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Default))]
pub struct GamepadSettings {
/// The default button settings.
pub default_button_settings: ButtonSettings,
/// The default axis settings.
pub default_axis_settings: AxisSettings,
/// The default button axis settings.
pub default_button_axis_settings: ButtonAxisSettings,
/// The user defined button settings.
pub button_settings: HashMap<GamepadButton, ButtonSettings>,
/// The user defined axis settings.
pub axis_settings: HashMap<GamepadAxis, AxisSettings>,
/// The user defined button axis settings.
pub button_axis_settings: HashMap<GamepadButton, ButtonAxisSettings>,
}
impl GamepadSettings {
/// Returns the [`ButtonSettings`] of the [`GamepadButton`].
///
/// If no user defined [`ButtonSettings`] are specified the default [`ButtonSettings`] get returned.
///
/// # Examples
///
/// ```
/// # use bevy_input::gamepad::{GamepadSettings, GamepadButton};
/// #
/// # let settings = GamepadSettings::default();
/// let button_settings = settings.get_button_settings(GamepadButton::South);
/// ```
pub fn get_button_settings(&self, button: GamepadButton) -> &ButtonSettings {
self.button_settings
.get(&button)
.unwrap_or(&self.default_button_settings)
}
/// Returns the [`AxisSettings`] of the [`GamepadAxis`].
///
/// If no user defined [`AxisSettings`] are specified the default [`AxisSettings`] get returned.
///
/// # Examples
///
/// ```
/// # use bevy_input::gamepad::{GamepadSettings, GamepadAxis};
/// #
/// # let settings = GamepadSettings::default();
/// let axis_settings = settings.get_axis_settings(GamepadAxis::LeftStickX);
/// ```
pub fn get_axis_settings(&self, axis: GamepadAxis) -> &AxisSettings {
self.axis_settings
.get(&axis)
.unwrap_or(&self.default_axis_settings)
}
/// Returns the [`ButtonAxisSettings`] of the [`GamepadButton`].
///
/// If no user defined [`ButtonAxisSettings`] are specified the default [`ButtonAxisSettings`] get returned.
///
/// # Examples
///
/// ```
/// # use bevy_input::gamepad::{GamepadSettings, GamepadButton};
/// #
/// # let settings = GamepadSettings::default();
/// let button_axis_settings = settings.get_button_axis_settings(GamepadButton::South);
/// ```
pub fn get_button_axis_settings(&self, button: GamepadButton) -> &ButtonAxisSettings {
self.button_axis_settings
.get(&button)
.unwrap_or(&self.default_button_axis_settings)
}
}
/// Manages settings for gamepad buttons.
///
/// It is used inside [`GamepadSettings`] to define the threshold for a [`GamepadButton`]
/// to be considered pressed or released. A button is considered pressed if the `press_threshold`
/// value is surpassed and released if the `release_threshold` value is undercut.
///
/// Allowed values: `0.0 <= ``release_threshold`` <= ``press_threshold`` <= 1.0`
#[derive(Debug, PartialEq, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Default))]
pub struct ButtonSettings {
press_threshold: f32,
release_threshold: f32,
}
impl Default for ButtonSettings {
fn default() -> Self {
ButtonSettings {
press_threshold: 0.75,
release_threshold: 0.65,
}
}
}
impl ButtonSettings {
/// Creates a new [`ButtonSettings`] instance.
///
/// # Parameters
///
/// + `press_threshold` is the button input value above which the button is considered pressed.
/// + `release_threshold` is the button input value below which the button is considered released.
///
/// Restrictions:
/// + `0.0 <= ``release_threshold`` <= ``press_threshold`` <= 1.0`
///
/// # Errors
///
/// If the restrictions are not met, returns one of
/// `GamepadSettingsError::ButtonReleaseThresholdOutOfRange`,
/// `GamepadSettingsError::ButtonPressThresholdOutOfRange`, or
/// `GamepadSettingsError::ButtonReleaseThresholdGreaterThanPressThreshold`.
pub fn new(
press_threshold: f32,
release_threshold: f32,
) -> Result<ButtonSettings, ButtonSettingsError> {
if !(0.0..=1.0).contains(&release_threshold) {
Err(ButtonSettingsError::ReleaseThresholdOutOfRange(
release_threshold,
))
} else if !(0.0..=1.0).contains(&press_threshold) {
Err(ButtonSettingsError::PressThresholdOutOfRange(
press_threshold,
))
} else if release_threshold > press_threshold {
Err(
ButtonSettingsError::ReleaseThresholdGreaterThanPressThreshold {
press_threshold,
release_threshold,
},
)
} else {
Ok(ButtonSettings {
press_threshold,
release_threshold,
})
}
}
/// Returns `true` if the button is pressed.
///
/// A button is considered pressed if the `value` passed is greater than or equal to the press threshold.
pub fn is_pressed(&self, value: f32) -> bool {
value >= self.press_threshold
}
/// Returns `true` if the button is released.
///
/// A button is considered released if the `value` passed is lower than or equal to the release threshold.
pub fn is_released(&self, value: f32) -> bool {
value <= self.release_threshold
}
/// Get the button input threshold above which the button is considered pressed.
pub fn press_threshold(&self) -> f32 {
self.press_threshold
}
/// Try to set the button input threshold above which the button is considered pressed.
///
/// # Errors
///
/// If the value passed is outside the range [release threshold..=1.0], returns either
/// `GamepadSettingsError::ButtonPressThresholdOutOfRange` or
/// `GamepadSettingsError::ButtonReleaseThresholdGreaterThanPressThreshold`.
pub fn try_set_press_threshold(&mut self, value: f32) -> Result<(), ButtonSettingsError> {
if (self.release_threshold..=1.0).contains(&value) {
self.press_threshold = value;
Ok(())
} else if !(0.0..1.0).contains(&value) {
Err(ButtonSettingsError::PressThresholdOutOfRange(value))
} else {
Err(
ButtonSettingsError::ReleaseThresholdGreaterThanPressThreshold {
press_threshold: value,
release_threshold: self.release_threshold,
},
)
}
}
/// Try to set the button input threshold above which the button is considered pressed.
/// If the value passed is outside the range [release threshold..=1.0], the value will not be changed.
///
/// Returns the new value of the press threshold.
pub fn set_press_threshold(&mut self, value: f32) -> f32 {
self.try_set_press_threshold(value).ok();
self.press_threshold
}
/// Get the button input threshold below which the button is considered released.
pub fn release_threshold(&self) -> f32 {
self.release_threshold
}
/// Try to set the button input threshold below which the button is considered released.
///
/// # Errors
///
/// If the value passed is outside the range [0.0..=press threshold], returns
/// `ButtonSettingsError::ReleaseThresholdOutOfRange` or
/// `ButtonSettingsError::ReleaseThresholdGreaterThanPressThreshold`.
pub fn try_set_release_threshold(&mut self, value: f32) -> Result<(), ButtonSettingsError> {
if (0.0..=self.press_threshold).contains(&value) {
self.release_threshold = value;
Ok(())
} else if !(0.0..1.0).contains(&value) {
Err(ButtonSettingsError::ReleaseThresholdOutOfRange(value))
} else {
Err(
ButtonSettingsError::ReleaseThresholdGreaterThanPressThreshold {
press_threshold: self.press_threshold,
release_threshold: value,
},
)
}
}
/// Try to set the button input threshold below which the button is considered released. If the
/// value passed is outside the range [0.0..=press threshold], the value will not be changed.
///
/// Returns the new value of the release threshold.
pub fn set_release_threshold(&mut self, value: f32) -> f32 {
self.try_set_release_threshold(value).ok();
self.release_threshold
}
}
/// Settings for a [`GamepadAxis`].
///
/// It is used inside the [`GamepadSettings`] to define the sensitivity range and
/// threshold for an axis.
/// Values that are higher than `livezone_upperbound` will be rounded up to 1.0.
/// Values that are lower than `livezone_lowerbound` will be rounded down to -1.0.
/// Values that are in-between `deadzone_lowerbound` and `deadzone_upperbound` will be rounded
/// to 0.0.
/// Otherwise, values will not be rounded.
///
/// The valid range is `[-1.0, 1.0]`.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Default))]
pub struct AxisSettings {
/// Values that are higher than `livezone_upperbound` will be rounded up to 1.0.
livezone_upperbound: f32,
/// Positive values that are less than `deadzone_upperbound` will be rounded down to 0.0.
deadzone_upperbound: f32,
/// Negative values that are greater than `deadzone_lowerbound` will be rounded up to 0.0.
deadzone_lowerbound: f32,
/// Values that are lower than `livezone_lowerbound` will be rounded down to -1.0.
livezone_lowerbound: f32,
/// `threshold` defines the minimum difference between old and new values to apply the changes.
threshold: f32,
}
impl Default for AxisSettings {
fn default() -> Self {
AxisSettings {
livezone_upperbound: 1.0,
deadzone_upperbound: 0.05,
deadzone_lowerbound: -0.05,
livezone_lowerbound: -1.0,
threshold: 0.01,
}
}
}
impl AxisSettings {
/// Creates a new [`AxisSettings`] instance.
///
/// # Arguments
///
/// + `livezone_lowerbound` - the value below which inputs will be rounded down to -1.0.
/// + `deadzone_lowerbound` - the value above which negative inputs will be rounded up to 0.0.
/// + `deadzone_upperbound` - the value below which positive inputs will be rounded down to 0.0.
/// + `livezone_upperbound` - the value above which inputs will be rounded up to 1.0.
/// + `threshold` - the minimum value by which input must change before the change is registered.
///
/// Restrictions:
///
/// + `-1.0 <= livezone_lowerbound <= deadzone_lowerbound <= 0.0`
/// + `0.0 <= deadzone_upperbound <= livezone_upperbound <= 1.0`
/// + `0.0 <= threshold <= 2.0`
///
/// # Errors
///
/// Returns an [`AxisSettingsError`] if any restrictions on the zone values are not met.
/// If the zone restrictions are met, but the `threshold` value restrictions are not met,
/// returns [`AxisSettingsError::Threshold`].
pub fn new(
livezone_lowerbound: f32,
deadzone_lowerbound: f32,
deadzone_upperbound: f32,
livezone_upperbound: f32,
threshold: f32,
) -> Result<AxisSettings, AxisSettingsError> {
if !(-1.0..=0.0).contains(&livezone_lowerbound) {
Err(AxisSettingsError::LiveZoneLowerBoundOutOfRange(
livezone_lowerbound,
))
} else if !(-1.0..=0.0).contains(&deadzone_lowerbound) {
Err(AxisSettingsError::DeadZoneLowerBoundOutOfRange(
deadzone_lowerbound,
))
} else if !(0.0..=1.0).contains(&deadzone_upperbound) {
Err(AxisSettingsError::DeadZoneUpperBoundOutOfRange(
deadzone_upperbound,
))
} else if !(0.0..=1.0).contains(&livezone_upperbound) {
Err(AxisSettingsError::LiveZoneUpperBoundOutOfRange(
livezone_upperbound,
))
} else if livezone_lowerbound > deadzone_lowerbound {
Err(
AxisSettingsError::LiveZoneLowerBoundGreaterThanDeadZoneLowerBound {
livezone_lowerbound,
deadzone_lowerbound,
},
)
} else if deadzone_upperbound > livezone_upperbound {
Err(
AxisSettingsError::DeadZoneUpperBoundGreaterThanLiveZoneUpperBound {
livezone_upperbound,
deadzone_upperbound,
},
)
} else if !(0.0..=2.0).contains(&threshold) {
Err(AxisSettingsError::Threshold(threshold))
} else {
Ok(Self {
livezone_lowerbound,
deadzone_lowerbound,
deadzone_upperbound,
livezone_upperbound,
threshold,
})
}
}
/// Get the value above which inputs will be rounded up to 1.0.
pub fn livezone_upperbound(&self) -> f32 {
self.livezone_upperbound
}
/// Try to set the value above which inputs will be rounded up to 1.0.
///
/// # Errors
///
/// If the value passed is less than the dead zone upper bound,
/// returns `AxisSettingsError::DeadZoneUpperBoundGreaterThanLiveZoneUpperBound`.
/// If the value passed is not in range [0.0..=1.0], returns `AxisSettingsError::LiveZoneUpperBoundOutOfRange`.
pub fn try_set_livezone_upperbound(&mut self, value: f32) -> Result<(), AxisSettingsError> {
if !(0.0..=1.0).contains(&value) {
Err(AxisSettingsError::LiveZoneUpperBoundOutOfRange(value))
} else if value < self.deadzone_upperbound {
Err(
AxisSettingsError::DeadZoneUpperBoundGreaterThanLiveZoneUpperBound {
livezone_upperbound: value,
deadzone_upperbound: self.deadzone_upperbound,
},
)
} else {
self.livezone_upperbound = value;
Ok(())
}
}
/// Try to set the value above which inputs will be rounded up to 1.0.
/// If the value passed is negative or less than `deadzone_upperbound`,
/// the value will not be changed.
///
/// Returns the new value of `livezone_upperbound`.
pub fn set_livezone_upperbound(&mut self, value: f32) -> f32 {
self.try_set_livezone_upperbound(value).ok();
self.livezone_upperbound
}
/// Get the value below which positive inputs will be rounded down to 0.0.
pub fn deadzone_upperbound(&self) -> f32 {
self.deadzone_upperbound
}
/// Try to set the value below which positive inputs will be rounded down to 0.0.
///
/// # Errors
///
/// If the value passed is greater than the live zone upper bound,
/// returns `AxisSettingsError::DeadZoneUpperBoundGreaterThanLiveZoneUpperBound`.
/// If the value passed is not in range [0.0..=1.0], returns `AxisSettingsError::DeadZoneUpperBoundOutOfRange`.
pub fn try_set_deadzone_upperbound(&mut self, value: f32) -> Result<(), AxisSettingsError> {
if !(0.0..=1.0).contains(&value) {
Err(AxisSettingsError::DeadZoneUpperBoundOutOfRange(value))
} else if self.livezone_upperbound < value {
Err(
AxisSettingsError::DeadZoneUpperBoundGreaterThanLiveZoneUpperBound {
livezone_upperbound: self.livezone_upperbound,
deadzone_upperbound: value,
},
)
} else {
self.deadzone_upperbound = value;
Ok(())
}
}
/// Try to set the value below which positive inputs will be rounded down to 0.0.
/// If the value passed is negative or greater than `livezone_upperbound`,
/// the value will not be changed.
///
/// Returns the new value of `deadzone_upperbound`.
pub fn set_deadzone_upperbound(&mut self, value: f32) -> f32 {
self.try_set_deadzone_upperbound(value).ok();
self.deadzone_upperbound
}
/// Get the value below which negative inputs will be rounded down to -1.0.
pub fn livezone_lowerbound(&self) -> f32 {
self.livezone_lowerbound
}
/// Try to set the value below which negative inputs will be rounded down to -1.0.
///
/// # Errors
///
/// If the value passed is less than the dead zone lower bound,
/// returns `AxisSettingsError::LiveZoneLowerBoundGreaterThanDeadZoneLowerBound`.
/// If the value passed is not in range [-1.0..=0.0], returns `AxisSettingsError::LiveZoneLowerBoundOutOfRange`.
pub fn try_set_livezone_lowerbound(&mut self, value: f32) -> Result<(), AxisSettingsError> {
if !(-1.0..=0.0).contains(&value) {
Err(AxisSettingsError::LiveZoneLowerBoundOutOfRange(value))
} else if value > self.deadzone_lowerbound {
Err(
AxisSettingsError::LiveZoneLowerBoundGreaterThanDeadZoneLowerBound {
livezone_lowerbound: value,
deadzone_lowerbound: self.deadzone_lowerbound,
},
)
} else {
self.livezone_lowerbound = value;
Ok(())
}
}
/// Try to set the value below which negative inputs will be rounded down to -1.0.
/// If the value passed is positive or greater than `deadzone_lowerbound`,
/// the value will not be changed.
///
/// Returns the new value of `livezone_lowerbound`.
pub fn set_livezone_lowerbound(&mut self, value: f32) -> f32 {
self.try_set_livezone_lowerbound(value).ok();
self.livezone_lowerbound
}
/// Get the value above which inputs will be rounded up to 0.0.
pub fn deadzone_lowerbound(&self) -> f32 {
self.deadzone_lowerbound
}
/// Try to set the value above which inputs will be rounded up to 0.0.
///
/// # Errors
///
/// If the value passed is less than the live zone lower bound,
/// returns `AxisSettingsError::LiveZoneLowerBoundGreaterThanDeadZoneLowerBound`.
/// If the value passed is not in range [-1.0..=0.0], returns `AxisSettingsError::DeadZoneLowerBoundOutOfRange`.
pub fn try_set_deadzone_lowerbound(&mut self, value: f32) -> Result<(), AxisSettingsError> {
if !(-1.0..=0.0).contains(&value) {
Err(AxisSettingsError::DeadZoneLowerBoundOutOfRange(value))
} else if self.livezone_lowerbound > value {
Err(
AxisSettingsError::LiveZoneLowerBoundGreaterThanDeadZoneLowerBound {
livezone_lowerbound: self.livezone_lowerbound,
deadzone_lowerbound: value,
},
)
} else {
self.deadzone_lowerbound = value;
Ok(())
}
}
/// Try to set the value above which inputs will be rounded up to 0.0.
/// If the value passed is less than -1.0 or less than `livezone_lowerbound`,
/// the value will not be changed.
///
/// Returns the new value of `deadzone_lowerbound`.
pub fn set_deadzone_lowerbound(&mut self, value: f32) -> f32 {
self.try_set_deadzone_lowerbound(value).ok();
self.deadzone_lowerbound
}
/// Get the minimum value by which input must change before the change is registered.
pub fn threshold(&self) -> f32 {
self.threshold
}
/// Try to set the minimum value by which input must change before the change is registered.
///
/// # Errors
///
/// If the value passed is not within [0.0..=2.0], returns `GamepadSettingsError::AxisThreshold`.
pub fn try_set_threshold(&mut self, value: f32) -> Result<(), AxisSettingsError> {
if !(0.0..=2.0).contains(&value) {
Err(AxisSettingsError::Threshold(value))
} else {
self.threshold = value;
Ok(())
}
}
/// Try to set the minimum value by which input must change before the changes will be applied.
/// If the value passed is not within [0.0..=2.0], the value will not be changed.
///
/// Returns the new value of threshold.
pub fn set_threshold(&mut self, value: f32) -> f32 {
self.try_set_threshold(value).ok();
self.threshold
}
/// Clamps the `raw_value` according to the `AxisSettings`.
pub fn clamp(&self, new_value: f32) -> f32 {
if self.deadzone_lowerbound <= new_value && new_value <= self.deadzone_upperbound {
0.0
} else if new_value >= self.livezone_upperbound {
1.0
} else if new_value <= self.livezone_lowerbound {
-1.0
} else {
new_value
}
}
/// Determines whether the change from `old_value` to `new_value` should
/// be registered as a change, according to the [`AxisSettings`].
fn should_register_change(&self, new_value: f32, old_value: Option<f32>) -> bool {
if old_value.is_none() {
return true;
}
f32::abs(new_value - old_value.unwrap()) > self.threshold
}
/// Filters the `new_value` based on the `old_value`, according to the [`AxisSettings`].
///
/// Returns the clamped `new_value` if the change exceeds the settings threshold,
/// and `None` otherwise.
pub fn filter(&self, new_value: f32, old_value: Option<f32>) -> Option<f32> {
let new_value = self.clamp(new_value);
if self.should_register_change(new_value, old_value) {
return Some(new_value);
}
None
}
}
/// Settings for a [`GamepadButton`].
///
/// It is used inside the [`GamepadSettings`] to define the sensitivity range and
/// threshold for a button axis.
///
/// ## Logic
///
/// - Values that are higher than or equal to `high` will be rounded to 1.0.
/// - Values that are lower than or equal to `low` will be rounded to 0.0.
/// - Otherwise, values will not be rounded.
///
/// The valid range is from 0.0 to 1.0, inclusive.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Default))]
pub struct ButtonAxisSettings {
/// The high value at which to apply rounding.
pub high: f32,
/// The low value at which to apply rounding.
pub low: f32,
/// The threshold to apply rounding.
pub threshold: f32,
}
impl Default for ButtonAxisSettings {
fn default() -> Self {
ButtonAxisSettings {
high: 0.95,
low: 0.05,
threshold: 0.01,
}
}
}
impl ButtonAxisSettings {
/// Clamps the `raw_value` according to the specified settings.
///
/// If the `raw_value` is:
/// - lower than or equal to `low` it will be rounded to 0.0.
/// - higher than or equal to `high` it will be rounded to 1.0.
/// - Otherwise it will not be rounded.
fn clamp(&self, raw_value: f32) -> f32 {
if raw_value <= self.low {
return 0.0;
}
if raw_value >= self.high {
return 1.0;
}
raw_value
}
/// Determines whether the change from an `old_value` to a `new_value` should
/// be registered as a change event, according to the specified settings.
fn should_register_change(&self, new_value: f32, old_value: Option<f32>) -> bool {
if old_value.is_none() {
return true;
}
f32::abs(new_value - old_value.unwrap()) > self.threshold
}
/// Filters the `new_value` based on the `old_value`, according to the [`ButtonAxisSettings`].
///
/// Returns the clamped `new_value`, according to the [`ButtonAxisSettings`], if the change
/// exceeds the settings threshold, and `None` otherwise.
pub fn filter(&self, new_value: f32, old_value: Option<f32>) -> Option<f32> {
let new_value = self.clamp(new_value);
if self.should_register_change(new_value, old_value) {
return Some(new_value);
}
None
}
}
/// Handles [`GamepadConnectionEvent`]s events.
///
/// On connection, adds the components representing a [`Gamepad`] to the entity.
/// On disconnection, removes the [`Gamepad`] and other related components.
/// Entities are left alive and might leave components like [`GamepadSettings`] to preserve state in the case of a reconnection
///
/// ## Note
///
/// Whenever a [`Gamepad`] connects or disconnects, an information gets printed to the console using the [`info!`] macro.
pub fn gamepad_connection_system(
mut commands: Commands,
mut connection_events: EventReader<GamepadConnectionEvent>,
) {
for connection_event in connection_events.read() {
let id = connection_event.gamepad;
match &connection_event.connection {
GamepadConnection::Connected {
name,
vendor_id,
product_id,
} => {
let Some(mut gamepad) = commands.get_entity(id) else {
warn!("Gamepad {:} removed before handling connection event.", id);
continue;
};
gamepad.insert((
Name::new(name.clone()),
Gamepad {
vendor_id: *vendor_id,
product_id: *product_id,
..Default::default()
},
));
info!("Gamepad {:?} connected.", id);
}
GamepadConnection::Disconnected => {
let Some(mut gamepad) = commands.get_entity(id) else {
warn!("Gamepad {:} removed before handling disconnection event. You can ignore this if you manually removed it.", id);
continue;
};
// Gamepad entities are left alive to preserve their state (e.g. [`GamepadSettings`]).
// Instead of despawning, we remove Gamepad components that don't need to preserve state
// and re-add them if they ever reconnect.
gamepad.remove::<Gamepad>();
info!("Gamepad {:} disconnected.", id);
}
}
}
}
// Note that we don't expose `gilrs::Gamepad::uuid` due to
// https://gitlab.com/gilrs-project/gilrs/-/issues/153.
//
/// The connection status of a gamepad.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq))]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serialize", feature = "bevy_reflect"),
reflect(Serialize, Deserialize)
)]
pub enum GamepadConnection {
/// The gamepad is connected.
Connected {
/// The name of the gamepad.
///
/// This name is generally defined by the OS.
///
/// For example on Windows the name may be "HID-compliant game controller".
name: String,
/// The USB vendor ID as assigned by the USB-IF, if available.
vendor_id: Option<u16>,
/// The USB product ID as assigned by the vendor, if available.
product_id: Option<u16>,
},
/// The gamepad is disconnected.
Disconnected,
}
/// Consumes [`RawGamepadEvent`] events, filters them using their [`GamepadSettings`] and if successful,
/// updates the [`Gamepad`] and sends [`GamepadAxisChangedEvent`], [`GamepadButtonStateChangedEvent`], [`GamepadButtonChangedEvent`] events.
pub fn gamepad_event_processing_system(
mut gamepads: Query<(&mut Gamepad, &GamepadSettings)>,
mut raw_events: EventReader<RawGamepadEvent>,
mut processed_events: EventWriter<GamepadEvent>,
mut processed_axis_events: EventWriter<GamepadAxisChangedEvent>,
mut processed_digital_events: EventWriter<GamepadButtonStateChangedEvent>,
mut processed_analog_events: EventWriter<GamepadButtonChangedEvent>,
) {
// Clear digital buttons state
for (mut gamepad, _) in gamepads.iter_mut() {
gamepad.bypass_change_detection().digital.clear();
}
for event in raw_events.read() {
match event {
// Connections require inserting/removing components so they are done in a separate system
RawGamepadEvent::Connection(send_event) => {
processed_events.send(GamepadEvent::from(send_event.clone()));
}
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent {
gamepad,
axis,
value,
}) => {
let (gamepad, axis, value) = (*gamepad, *axis, *value);
let Ok((mut gamepad_axis, gamepad_settings)) = gamepads.get_mut(gamepad) else {
continue;
};
let Some(filtered_value) = gamepad_settings
.get_axis_settings(axis)
.filter(value, gamepad_axis.get(axis))
else {
continue;
};
gamepad_axis.analog.set(axis, filtered_value);
let send_event = GamepadAxisChangedEvent::new(gamepad, axis, filtered_value);
processed_axis_events.send(send_event);
processed_events.send(GamepadEvent::from(send_event));
}
RawGamepadEvent::Button(RawGamepadButtonChangedEvent {
gamepad,
button,
value,
}) => {
let (gamepad, button, value) = (*gamepad, *button, *value);
let Ok((mut gamepad_buttons, settings)) = gamepads.get_mut(gamepad) else {
continue;
};
let Some(filtered_value) = settings
.get_button_axis_settings(button)
.filter(value, gamepad_buttons.get(button))
else {
continue;
};
let button_settings = settings.get_button_settings(button);
gamepad_buttons.analog.set(button, filtered_value);
if button_settings.is_released(filtered_value) {
// Check if button was previously pressed
if gamepad_buttons.pressed(button) {
processed_digital_events.send(GamepadButtonStateChangedEvent::new(
gamepad,
button,
ButtonState::Released,
));
}
// We don't have to check if the button was previously pressed here
// because that check is performed within Input<T>::release()
gamepad_buttons.digital.release(button);
} else if button_settings.is_pressed(filtered_value) {
// Check if button was previously not pressed
if !gamepad_buttons.pressed(button) {
processed_digital_events.send(GamepadButtonStateChangedEvent::new(
gamepad,
button,
ButtonState::Pressed,
));
}
gamepad_buttons.digital.press(button);
};
let button_state = if gamepad_buttons.digital.pressed(button) {
ButtonState::Pressed
} else {
ButtonState::Released
};
let send_event =
GamepadButtonChangedEvent::new(gamepad, button, button_state, filtered_value);
processed_analog_events.send(send_event);
processed_events.send(GamepadEvent::from(send_event));
}
}
}
}
/// The intensity at which a gamepad's force-feedback motors may rumble.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, PartialEq))]
pub struct GamepadRumbleIntensity {
/// The rumble intensity of the strong gamepad motor.
///
/// Ranges from `0.0` to `1.0`.
///
/// By convention, this is usually a low-frequency motor on the left-hand
/// side of the gamepad, though it may vary across platforms and hardware.
pub strong_motor: f32,
/// The rumble intensity of the weak gamepad motor.
///
/// Ranges from `0.0` to `1.0`.
///
/// By convention, this is usually a high-frequency motor on the right-hand
/// side of the gamepad, though it may vary across platforms and hardware.
pub weak_motor: f32,
}
impl GamepadRumbleIntensity {
/// Rumble both gamepad motors at maximum intensity.
pub const MAX: Self = GamepadRumbleIntensity {
strong_motor: 1.0,
weak_motor: 1.0,
};
/// Rumble the weak motor at maximum intensity.
pub const WEAK_MAX: Self = GamepadRumbleIntensity {
strong_motor: 0.0,
weak_motor: 1.0,
};
/// Rumble the strong motor at maximum intensity.
pub const STRONG_MAX: Self = GamepadRumbleIntensity {
strong_motor: 1.0,
weak_motor: 0.0,
};
/// Creates a new rumble intensity with weak motor intensity set to the given value.
///
/// Clamped within the `0.0` to `1.0` range.
pub const fn weak_motor(intensity: f32) -> Self {
Self {
weak_motor: intensity,
strong_motor: 0.0,
}
}
/// Creates a new rumble intensity with strong motor intensity set to the given value.
///
/// Clamped within the `0.0` to `1.0` range.
pub const fn strong_motor(intensity: f32) -> Self {
Self {
strong_motor: intensity,
weak_motor: 0.0,
}
}
}
/// An event that controls force-feedback rumbling of a [`Gamepad`] [`entity`](Entity).
///
/// # Notes
///
/// Does nothing if the gamepad or platform does not support rumble.
///
/// # Example
///
/// ```
/// # use bevy_input::gamepad::{Gamepad, GamepadRumbleRequest, GamepadRumbleIntensity};
/// # use bevy_ecs::prelude::{EventWriter, Res, Query, Entity, With};
/// # use bevy_utils::Duration;
/// fn rumble_gamepad_system(
/// mut rumble_requests: EventWriter<GamepadRumbleRequest>,
/// gamepads: Query<Entity, With<Gamepad>>,
/// ) {
/// for entity in gamepads.iter() {
/// rumble_requests.send(GamepadRumbleRequest::Add {
/// gamepad: entity,
/// intensity: GamepadRumbleIntensity::MAX,
/// duration: Duration::from_secs_f32(0.5),
/// });
/// }
/// }
/// ```
#[doc(alias = "haptic feedback")]
#[doc(alias = "force feedback")]
#[doc(alias = "vibration")]
#[doc(alias = "vibrate")]
#[derive(Event, Clone)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
pub enum GamepadRumbleRequest {
/// Add a rumble to the given gamepad.
///
/// Simultaneous rumble effects add up to the sum of their strengths.
///
/// Consequently, if two rumbles at half intensity are added at the same
/// time, their intensities will be added up, and the controller will rumble
/// at full intensity until one of the rumbles finishes, then the rumble
/// will continue at the intensity of the remaining event.
///
/// To replace an existing rumble, send a [`GamepadRumbleRequest::Stop`] event first.
Add {
/// How long the gamepad should rumble.
duration: Duration,
/// How intense the rumble should be.
intensity: GamepadRumbleIntensity,
/// The gamepad to rumble.
gamepad: Entity,
},
/// Stop all running rumbles on the given [`Entity`].
Stop {
/// The gamepad to stop rumble.
gamepad: Entity,
},
}
impl GamepadRumbleRequest {
/// Get the [`Entity`] associated with this request.
pub fn gamepad(&self) -> Entity {
match self {
Self::Add { gamepad, .. } | Self::Stop { gamepad } => *gamepad,
}
}
}
#[cfg(test)]
mod tests {
use super::{
gamepad_connection_system, gamepad_event_processing_system, AxisSettings,
AxisSettingsError, ButtonAxisSettings, ButtonSettings, ButtonSettingsError, Gamepad,
GamepadAxis, GamepadAxisChangedEvent, GamepadButton, GamepadButtonChangedEvent,
GamepadButtonStateChangedEvent,
GamepadConnection::{Connected, Disconnected},
GamepadConnectionEvent, GamepadEvent, GamepadSettings, RawGamepadAxisChangedEvent,
RawGamepadButtonChangedEvent, RawGamepadEvent,
};
use crate::ButtonState;
use bevy_app::{App, PreUpdate};
use bevy_ecs::entity::Entity;
use bevy_ecs::event::Events;
use bevy_ecs::schedule::IntoSystemConfigs;
fn test_button_axis_settings_filter(
settings: ButtonAxisSettings,
new_value: f32,
old_value: Option<f32>,
expected: Option<f32>,
) {
let actual = settings.filter(new_value, old_value);
assert_eq!(
expected, actual,
"Testing filtering for {settings:?} with new_value = {new_value:?}, old_value = {old_value:?}",
);
}
#[test]
fn test_button_axis_settings_default_filter() {
let cases = [
(1.0, None, Some(1.0)),
(0.99, None, Some(1.0)),
(0.96, None, Some(1.0)),
(0.95, None, Some(1.0)),
(0.9499, None, Some(0.9499)),
(0.84, None, Some(0.84)),
(0.43, None, Some(0.43)),
(0.05001, None, Some(0.05001)),
(0.05, None, Some(0.0)),
(0.04, None, Some(0.0)),
(0.01, None, Some(0.0)),
(0.0, None, Some(0.0)),
];
for (new_value, old_value, expected) in cases {
let settings = ButtonAxisSettings::default();
test_button_axis_settings_filter(settings, new_value, old_value, expected);
}
}
#[test]
fn test_button_axis_settings_default_filter_with_old_value() {
let cases = [
(0.43, Some(0.44001), Some(0.43)),
(0.43, Some(0.44), None),
(0.43, Some(0.43), None),
(0.43, Some(0.41999), Some(0.43)),
(0.43, Some(0.17), Some(0.43)),
(0.43, Some(0.84), Some(0.43)),
(0.05, Some(0.055), Some(0.0)),
(0.95, Some(0.945), Some(1.0)),
];
for (new_value, old_value, expected) in cases {
let settings = ButtonAxisSettings::default();
test_button_axis_settings_filter(settings, new_value, old_value, expected);
}
}
fn test_axis_settings_filter(
settings: AxisSettings,
new_value: f32,
old_value: Option<f32>,
expected: Option<f32>,
) {
let actual = settings.filter(new_value, old_value);
assert_eq!(
expected, actual,
"Testing filtering for {settings:?} with new_value = {new_value:?}, old_value = {old_value:?}",
);
}
#[test]
fn test_axis_settings_default_filter() {
let cases = [
(1.0, Some(1.0)),
(0.99, Some(1.0)),
(0.96, Some(1.0)),
(0.95, Some(1.0)),
(0.9499, Some(0.9499)),
(0.84, Some(0.84)),
(0.43, Some(0.43)),
(0.05001, Some(0.05001)),
(0.05, Some(0.0)),
(0.04, Some(0.0)),
(0.01, Some(0.0)),
(0.0, Some(0.0)),
(-1.0, Some(-1.0)),
(-0.99, Some(-1.0)),
(-0.96, Some(-1.0)),
(-0.95, Some(-1.0)),
(-0.9499, Some(-0.9499)),
(-0.84, Some(-0.84)),
(-0.43, Some(-0.43)),
(-0.05001, Some(-0.05001)),
(-0.05, Some(0.0)),
(-0.04, Some(0.0)),
(-0.01, Some(0.0)),
];
for (new_value, expected) in cases {
let settings = AxisSettings::new(-0.95, -0.05, 0.05, 0.95, 0.01).unwrap();
test_axis_settings_filter(settings, new_value, None, expected);
}
}
#[test]
fn test_axis_settings_default_filter_with_old_values() {
let cases = [
(0.43, Some(0.44001), Some(0.43)),
(0.43, Some(0.44), None),
(0.43, Some(0.43), None),
(0.43, Some(0.41999), Some(0.43)),
(0.43, Some(0.17), Some(0.43)),
(0.43, Some(0.84), Some(0.43)),
(0.05, Some(0.055), Some(0.0)),
(0.95, Some(0.945), Some(1.0)),
(-0.43, Some(-0.44001), Some(-0.43)),
(-0.43, Some(-0.44), None),
(-0.43, Some(-0.43), None),
(-0.43, Some(-0.41999), Some(-0.43)),
(-0.43, Some(-0.17), Some(-0.43)),
(-0.43, Some(-0.84), Some(-0.43)),
(-0.05, Some(-0.055), Some(0.0)),
(-0.95, Some(-0.945), Some(-1.0)),
];
for (new_value, old_value, expected) in cases {
let settings = AxisSettings::new(-0.95, -0.05, 0.05, 0.95, 0.01).unwrap();
test_axis_settings_filter(settings, new_value, old_value, expected);
}
}
#[test]
fn test_button_settings_default_is_pressed() {
let cases = [
(1.0, true),
(0.95, true),
(0.9, true),
(0.8, true),
(0.75, true),
(0.7, false),
(0.65, false),
(0.5, false),
(0.0, false),
];
for (value, expected) in cases {
let settings = ButtonSettings::default();
let actual = settings.is_pressed(value);
assert_eq!(
expected, actual,
"testing ButtonSettings::is_pressed() for value: {value}",
);
}
}
#[test]
fn test_button_settings_default_is_released() {
let cases = [
(1.0, false),
(0.95, false),
(0.9, false),
(0.8, false),
(0.75, false),
(0.7, false),
(0.65, true),
(0.5, true),
(0.0, true),
];
for (value, expected) in cases {
let settings = ButtonSettings::default();
let actual = settings.is_released(value);
assert_eq!(
expected, actual,
"testing ButtonSettings::is_released() for value: {value}",
);
}
}
#[test]
fn test_new_button_settings_given_valid_parameters() {
let cases = [
(1.0, 0.0),
(1.0, 1.0),
(1.0, 0.9),
(0.9, 0.9),
(0.9, 0.0),
(0.0, 0.0),
];
for (press_threshold, release_threshold) in cases {
let bs = ButtonSettings::new(press_threshold, release_threshold);
match bs {
Ok(button_settings) => {
assert_eq!(button_settings.press_threshold, press_threshold);
assert_eq!(button_settings.release_threshold, release_threshold);
}
Err(_) => {
panic!(
"ButtonSettings::new({press_threshold}, {release_threshold}) should be valid"
);
}
}
}
}
#[test]
fn test_new_button_settings_given_invalid_parameters() {
let cases = [
(1.1, 0.0),
(1.1, 1.0),
(1.0, 1.1),
(-1.0, 0.9),
(-1.0, 0.0),
(-1.0, -0.4),
(0.9, 1.0),
(0.0, 0.1),
];
for (press_threshold, release_threshold) in cases {
let bs = ButtonSettings::new(press_threshold, release_threshold);
match bs {
Ok(_) => {
panic!(
"ButtonSettings::new({press_threshold}, {release_threshold}) should be invalid"
);
}
Err(err_code) => match err_code {
ButtonSettingsError::PressThresholdOutOfRange(_press_threshold) => {}
ButtonSettingsError::ReleaseThresholdGreaterThanPressThreshold {
press_threshold: _press_threshold,
release_threshold: _release_threshold,
} => {}
ButtonSettingsError::ReleaseThresholdOutOfRange(_release_threshold) => {}
},
}
}
}
#[test]
fn test_try_out_of_range_axis_settings() {
let mut axis_settings = AxisSettings::default();
assert_eq!(
AxisSettings::new(-0.95, -0.05, 0.05, 0.95, 0.001),
Ok(AxisSettings {
livezone_lowerbound: -0.95,
deadzone_lowerbound: -0.05,
deadzone_upperbound: 0.05,
livezone_upperbound: 0.95,
threshold: 0.001,
})
);
assert_eq!(
Err(AxisSettingsError::LiveZoneLowerBoundOutOfRange(-2.0)),
axis_settings.try_set_livezone_lowerbound(-2.0)
);
assert_eq!(
Err(AxisSettingsError::LiveZoneLowerBoundOutOfRange(0.1)),
axis_settings.try_set_livezone_lowerbound(0.1)
);
assert_eq!(
Err(AxisSettingsError::DeadZoneLowerBoundOutOfRange(-2.0)),
axis_settings.try_set_deadzone_lowerbound(-2.0)
);
assert_eq!(
Err(AxisSettingsError::DeadZoneLowerBoundOutOfRange(0.1)),
axis_settings.try_set_deadzone_lowerbound(0.1)
);
assert_eq!(
Err(AxisSettingsError::DeadZoneUpperBoundOutOfRange(-0.1)),
axis_settings.try_set_deadzone_upperbound(-0.1)
);
assert_eq!(
Err(AxisSettingsError::DeadZoneUpperBoundOutOfRange(1.1)),
axis_settings.try_set_deadzone_upperbound(1.1)
);
assert_eq!(
Err(AxisSettingsError::LiveZoneUpperBoundOutOfRange(-0.1)),
axis_settings.try_set_livezone_upperbound(-0.1)
);
assert_eq!(
Err(AxisSettingsError::LiveZoneUpperBoundOutOfRange(1.1)),
axis_settings.try_set_livezone_upperbound(1.1)
);
axis_settings.set_livezone_lowerbound(-0.7);
axis_settings.set_deadzone_lowerbound(-0.3);
assert_eq!(
Err(
AxisSettingsError::LiveZoneLowerBoundGreaterThanDeadZoneLowerBound {
livezone_lowerbound: -0.1,
deadzone_lowerbound: -0.3,
}
),
axis_settings.try_set_livezone_lowerbound(-0.1)
);
assert_eq!(
Err(
AxisSettingsError::LiveZoneLowerBoundGreaterThanDeadZoneLowerBound {
livezone_lowerbound: -0.7,
deadzone_lowerbound: -0.9
}
),
axis_settings.try_set_deadzone_lowerbound(-0.9)
);
axis_settings.set_deadzone_upperbound(0.3);
axis_settings.set_livezone_upperbound(0.7);
assert_eq!(
Err(
AxisSettingsError::DeadZoneUpperBoundGreaterThanLiveZoneUpperBound {
deadzone_upperbound: 0.8,
livezone_upperbound: 0.7
}
),
axis_settings.try_set_deadzone_upperbound(0.8)
);
assert_eq!(
Err(
AxisSettingsError::DeadZoneUpperBoundGreaterThanLiveZoneUpperBound {
deadzone_upperbound: 0.3,
livezone_upperbound: 0.1
}
),
axis_settings.try_set_livezone_upperbound(0.1)
);
}
struct TestContext {
pub app: App,
}
impl TestContext {
pub fn new() -> Self {
let mut app = App::new();
app.add_systems(
PreUpdate,
(
gamepad_connection_system,
gamepad_event_processing_system.after(gamepad_connection_system),
),
)
.add_event::<GamepadEvent>()
.add_event::<GamepadConnectionEvent>()
.add_event::<RawGamepadButtonChangedEvent>()
.add_event::<GamepadButtonChangedEvent>()
.add_event::<GamepadButtonStateChangedEvent>()
.add_event::<GamepadAxisChangedEvent>()
.add_event::<RawGamepadAxisChangedEvent>()
.add_event::<RawGamepadEvent>();
Self { app }
}
pub fn update(&mut self) {
self.app.update();
}
pub fn send_gamepad_connection_event(&mut self, gamepad: Option<Entity>) -> Entity {
let gamepad = gamepad.unwrap_or_else(|| self.app.world_mut().spawn_empty().id());
self.app
.world_mut()
.resource_mut::<Events<GamepadConnectionEvent>>()
.send(GamepadConnectionEvent::new(
gamepad,
Connected {
name: "Test gamepad".to_string(),
vendor_id: None,
product_id: None,
},
));
gamepad
}
pub fn send_gamepad_disconnection_event(&mut self, gamepad: Entity) {
self.app
.world_mut()
.resource_mut::<Events<GamepadConnectionEvent>>()
.send(GamepadConnectionEvent::new(gamepad, Disconnected));
}
pub fn send_raw_gamepad_event(&mut self, event: RawGamepadEvent) {
self.app
.world_mut()
.resource_mut::<Events<RawGamepadEvent>>()
.send(event);
}
pub fn send_raw_gamepad_event_batch(
&mut self,
events: impl IntoIterator<Item = RawGamepadEvent>,
) {
self.app
.world_mut()
.resource_mut::<Events<RawGamepadEvent>>()
.send_batch(events);
}
}
#[test]
fn connection_event() {
let mut ctx = TestContext::new();
assert_eq!(
ctx.app
.world_mut()
.query::<&Gamepad>()
.iter(ctx.app.world())
.len(),
0
);
ctx.send_gamepad_connection_event(None);
ctx.update();
assert_eq!(
ctx.app
.world_mut()
.query::<(&Gamepad, &GamepadSettings)>()
.iter(ctx.app.world())
.len(),
1
);
}
#[test]
fn disconnection_event() {
let mut ctx = TestContext::new();
assert_eq!(
ctx.app
.world_mut()
.query::<&Gamepad>()
.iter(ctx.app.world())
.len(),
0
);
let entity = ctx.send_gamepad_connection_event(None);
ctx.update();
assert_eq!(
ctx.app
.world_mut()
.query::<(&Gamepad, &GamepadSettings)>()
.iter(ctx.app.world())
.len(),
1
);
ctx.send_gamepad_disconnection_event(entity);
ctx.update();
// Gamepad component should be removed
assert!(ctx
.app
.world_mut()
.query::<&Gamepad>()
.get(ctx.app.world(), entity)
.is_err());
// Settings should be kept
assert!(ctx
.app
.world_mut()
.query::<&GamepadSettings>()
.get(ctx.app.world(), entity)
.is_ok());
// Mistakenly sending a second disconnection event shouldn't break anything
ctx.send_gamepad_disconnection_event(entity);
ctx.update();
assert!(ctx
.app
.world_mut()
.query::<&Gamepad>()
.get(ctx.app.world(), entity)
.is_err());
assert!(ctx
.app
.world_mut()
.query::<&GamepadSettings>()
.get(ctx.app.world(), entity)
.is_ok());
}
#[test]
fn connection_disconnection_frame_event() {
let mut ctx = TestContext::new();
assert_eq!(
ctx.app
.world_mut()
.query::<&Gamepad>()
.iter(ctx.app.world())
.len(),
0
);
let entity = ctx.send_gamepad_connection_event(None);
ctx.send_gamepad_disconnection_event(entity);
ctx.update();
// Gamepad component should be removed
assert!(ctx
.app
.world_mut()
.query::<&Gamepad>()
.get(ctx.app.world(), entity)
.is_err());
// Settings should be kept
assert!(ctx
.app
.world_mut()
.query::<&GamepadSettings>()
.get(ctx.app.world(), entity)
.is_ok());
}
#[test]
fn reconnection_event() {
let button_settings = ButtonSettings::new(0.7, 0.2).expect("correct parameters");
let mut ctx = TestContext::new();
assert_eq!(
ctx.app
.world_mut()
.query::<&Gamepad>()
.iter(ctx.app.world())
.len(),
0
);
let entity = ctx.send_gamepad_connection_event(None);
ctx.update();
let mut settings = ctx
.app
.world_mut()
.query::<&mut GamepadSettings>()
.get_mut(ctx.app.world_mut(), entity)
.expect("be alive");
assert_ne!(settings.default_button_settings, button_settings);
settings.default_button_settings = button_settings.clone();
ctx.send_gamepad_disconnection_event(entity);
ctx.update();
assert_eq!(
ctx.app
.world_mut()
.query::<&Gamepad>()
.iter(ctx.app.world())
.len(),
0
);
ctx.send_gamepad_connection_event(Some(entity));
ctx.update();
let settings = ctx
.app
.world_mut()
.query::<&GamepadSettings>()
.get(ctx.app.world(), entity)
.expect("be alive");
assert_eq!(settings.default_button_settings, button_settings);
}
#[test]
fn reconnection_same_frame_event() {
let mut ctx = TestContext::new();
assert_eq!(
ctx.app
.world_mut()
.query::<&Gamepad>()
.iter(ctx.app.world())
.len(),
0
);
let entity = ctx.send_gamepad_connection_event(None);
ctx.send_gamepad_disconnection_event(entity);
ctx.update();
assert_eq!(
ctx.app
.world_mut()
.query::<&Gamepad>()
.iter(ctx.app.world())
.len(),
0
);
assert!(ctx
.app
.world_mut()
.query::<(Entity, &GamepadSettings)>()
.get(ctx.app.world(), entity)
.is_ok());
}
#[test]
fn gamepad_axis_valid() {
let mut ctx = TestContext::new();
// Create test gamepad
let entity = ctx.send_gamepad_connection_event(None);
ctx.app
.world_mut()
.resource_mut::<Events<RawGamepadEvent>>()
.send_batch([
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickY,
0.5,
)),
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::RightStickX,
0.6,
)),
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::RightZ,
-0.4,
)),
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::RightStickY,
-0.8,
)),
]);
ctx.update();
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadAxisChangedEvent>>()
.len(),
4
);
}
#[test]
fn gamepad_axis_threshold_filter() {
let mut ctx = TestContext::new();
// Create test gamepad
let entity = ctx.send_gamepad_connection_event(None);
let settings = GamepadSettings::default().default_axis_settings;
// Set of events to ensure they are being properly filtered
let base_value = 0.5;
let events = [
// Event above threshold
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
base_value,
)),
// Event below threshold, should be filtered
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
base_value + settings.threshold - 0.01,
)),
// Event above threshold
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
base_value + settings.threshold + 0.01,
)),
];
ctx.app
.world_mut()
.resource_mut::<Events<RawGamepadEvent>>()
.send_batch(events);
ctx.update();
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadAxisChangedEvent>>()
.len(),
2
);
}
#[test]
fn gamepad_axis_deadzone_filter() {
let mut ctx = TestContext::new();
// Create test gamepad
let entity = ctx.send_gamepad_connection_event(None);
let settings = GamepadSettings::default().default_axis_settings;
// Set of events to ensure they are being properly filtered
let events = [
// Event below deadzone upperbound should be filtered
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
settings.deadzone_upperbound - 0.01,
)),
// Event above deadzone lowerbound should be filtered
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
settings.deadzone_lowerbound + 0.01,
)),
];
ctx.app
.world_mut()
.resource_mut::<Events<RawGamepadEvent>>()
.send_batch(events);
ctx.update();
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadAxisChangedEvent>>()
.len(),
0
);
}
#[test]
fn gamepad_axis_deadzone_rounded() {
let mut ctx = TestContext::new();
// Create test gamepad
let entity = ctx.send_gamepad_connection_event(None);
let settings = GamepadSettings::default().default_axis_settings;
// Set of events to ensure they are being properly filtered
let events = [
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
1.0,
)),
// Event below deadzone upperbound should be rounded to 0
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
settings.deadzone_upperbound - 0.01,
)),
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
1.0,
)),
// Event above deadzone lowerbound should be rounded to 0
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
settings.deadzone_lowerbound + 0.01,
)),
];
let results = [1.0, 0.0, 1.0, 0.0];
ctx.app
.world_mut()
.resource_mut::<Events<RawGamepadEvent>>()
.send_batch(events);
ctx.update();
let events = ctx
.app
.world()
.resource::<Events<GamepadAxisChangedEvent>>();
let mut event_reader = events.get_cursor();
for (event, result) in event_reader.read(events).zip(results) {
assert_eq!(event.value, result);
}
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadAxisChangedEvent>>()
.len(),
4
);
}
#[test]
fn gamepad_axis_livezone_filter() {
let mut ctx = TestContext::new();
// Create test gamepad
let entity = ctx.send_gamepad_connection_event(None);
let settings = GamepadSettings::default().default_axis_settings;
// Set of events to ensure they are being properly filtered
let events = [
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
1.0,
)),
// Event above livezone upperbound should be filtered
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
settings.livezone_upperbound + 0.01,
)),
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
-1.0,
)),
// Event below livezone lowerbound should be filtered
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
settings.livezone_lowerbound - 0.01,
)),
];
ctx.app
.world_mut()
.resource_mut::<Events<RawGamepadEvent>>()
.send_batch(events);
ctx.update();
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadAxisChangedEvent>>()
.len(),
2
);
}
#[test]
fn gamepad_axis_livezone_rounded() {
let mut ctx = TestContext::new();
// Create test gamepad
let entity = ctx.send_gamepad_connection_event(None);
let settings = GamepadSettings::default().default_axis_settings;
// Set of events to ensure they are being properly filtered
let events = [
// Event above livezone upperbound should be rounded to 1
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
settings.livezone_upperbound + 0.01,
)),
// Event below livezone lowerbound should be rounded to -1
RawGamepadEvent::Axis(RawGamepadAxisChangedEvent::new(
entity,
GamepadAxis::LeftStickX,
settings.livezone_lowerbound - 0.01,
)),
];
let results = [1.0, -1.0];
ctx.app
.world_mut()
.resource_mut::<Events<RawGamepadEvent>>()
.send_batch(events);
ctx.update();
let events = ctx
.app
.world()
.resource::<Events<GamepadAxisChangedEvent>>();
let mut event_reader = events.get_cursor();
for (event, result) in event_reader.read(events).zip(results) {
assert_eq!(event.value, result);
}
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadAxisChangedEvent>>()
.len(),
2
);
}
#[test]
fn gamepad_buttons_pressed() {
let mut ctx = TestContext::new();
// Create test gamepad
let entity = ctx.send_gamepad_connection_event(None);
let digital_settings = GamepadSettings::default().default_button_settings;
let events = [RawGamepadEvent::Button(RawGamepadButtonChangedEvent::new(
entity,
GamepadButton::DPadDown,
digital_settings.press_threshold,
))];
ctx.app
.world_mut()
.resource_mut::<Events<RawGamepadEvent>>()
.send_batch(events);
ctx.update();
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadButtonStateChangedEvent>>()
.len(),
1
);
let events = ctx
.app
.world()
.resource::<Events<GamepadButtonStateChangedEvent>>();
let mut event_reader = events.get_cursor();
for event in event_reader.read(events) {
assert_eq!(event.button, GamepadButton::DPadDown);
assert_eq!(event.state, ButtonState::Pressed);
}
assert!(ctx
.app
.world_mut()
.query::<&Gamepad>()
.get(ctx.app.world(), entity)
.unwrap()
.pressed(GamepadButton::DPadDown));
ctx.app
.world_mut()
.resource_mut::<Events<GamepadButtonStateChangedEvent>>()
.clear();
ctx.update();
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadButtonStateChangedEvent>>()
.len(),
0
);
assert!(ctx
.app
.world_mut()
.query::<&Gamepad>()
.get(ctx.app.world(), entity)
.unwrap()
.pressed(GamepadButton::DPadDown));
}
#[test]
fn gamepad_buttons_just_pressed() {
let mut ctx = TestContext::new();
// Create test gamepad
let entity = ctx.send_gamepad_connection_event(None);
let digital_settings = GamepadSettings::default().default_button_settings;
ctx.send_raw_gamepad_event(RawGamepadEvent::Button(RawGamepadButtonChangedEvent::new(
entity,
GamepadButton::DPadDown,
digital_settings.press_threshold,
)));
ctx.update();
// Check it is flagged for this frame
assert!(ctx
.app
.world_mut()
.query::<&Gamepad>()
.get(ctx.app.world(), entity)
.unwrap()
.just_pressed(GamepadButton::DPadDown));
ctx.update();
//Check it clears next frame
assert!(!ctx
.app
.world_mut()
.query::<&Gamepad>()
.get(ctx.app.world(), entity)
.unwrap()
.just_pressed(GamepadButton::DPadDown));
}
#[test]
fn gamepad_buttons_released() {
let mut ctx = TestContext::new();
// Create test gamepad
let entity = ctx.send_gamepad_connection_event(None);
let digital_settings = GamepadSettings::default().default_button_settings;
ctx.send_raw_gamepad_event(RawGamepadEvent::Button(RawGamepadButtonChangedEvent::new(
entity,
GamepadButton::DPadDown,
digital_settings.press_threshold,
)));
ctx.update();
ctx.app
.world_mut()
.resource_mut::<Events<GamepadButtonStateChangedEvent>>()
.clear();
ctx.send_raw_gamepad_event(RawGamepadEvent::Button(RawGamepadButtonChangedEvent::new(
entity,
GamepadButton::DPadDown,
digital_settings.release_threshold - 0.01,
)));
ctx.update();
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadButtonStateChangedEvent>>()
.len(),
1
);
let events = ctx
.app
.world()
.resource::<Events<GamepadButtonStateChangedEvent>>();
let mut event_reader = events.get_cursor();
for event in event_reader.read(events) {
assert_eq!(event.button, GamepadButton::DPadDown);
assert_eq!(event.state, ButtonState::Released);
}
assert!(!ctx
.app
.world_mut()
.query::<&Gamepad>()
.get(ctx.app.world(), entity)
.unwrap()
.pressed(GamepadButton::DPadDown));
ctx.app
.world_mut()
.resource_mut::<Events<GamepadButtonStateChangedEvent>>()
.clear();
ctx.update();
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadButtonStateChangedEvent>>()
.len(),
0
);
}
#[test]
fn gamepad_buttons_just_released() {
let mut ctx = TestContext::new();
// Create test gamepad
let entity = ctx.send_gamepad_connection_event(None);
let digital_settings = GamepadSettings::default().default_button_settings;
ctx.send_raw_gamepad_event_batch([
RawGamepadEvent::Button(RawGamepadButtonChangedEvent::new(
entity,
GamepadButton::DPadDown,
digital_settings.press_threshold,
)),
RawGamepadEvent::Button(RawGamepadButtonChangedEvent::new(
entity,
GamepadButton::DPadDown,
digital_settings.release_threshold - 0.01,
)),
]);
ctx.update();
// Check it is flagged for this frame
assert!(ctx
.app
.world_mut()
.query::<&Gamepad>()
.get(ctx.app.world(), entity)
.unwrap()
.just_released(GamepadButton::DPadDown));
ctx.update();
//Check it clears next frame
assert!(!ctx
.app
.world_mut()
.query::<&Gamepad>()
.get(ctx.app.world(), entity)
.unwrap()
.just_released(GamepadButton::DPadDown));
}
#[test]
fn gamepad_buttons_axis() {
let mut ctx = TestContext::new();
// Create test gamepad
let entity = ctx.send_gamepad_connection_event(None);
let digital_settings = GamepadSettings::default().default_button_settings;
let analog_settings = GamepadSettings::default().default_button_axis_settings;
// Test events
let events = [
// Should trigger event
RawGamepadEvent::Button(RawGamepadButtonChangedEvent::new(
entity,
GamepadButton::DPadDown,
digital_settings.press_threshold,
)),
// Should trigger event
RawGamepadEvent::Button(RawGamepadButtonChangedEvent::new(
entity,
GamepadButton::DPadDown,
digital_settings.release_threshold,
)),
// Shouldn't trigger a state changed event
RawGamepadEvent::Button(RawGamepadButtonChangedEvent::new(
entity,
GamepadButton::DPadDown,
digital_settings.release_threshold - analog_settings.threshold * 1.01,
)),
// Shouldn't trigger any event
RawGamepadEvent::Button(RawGamepadButtonChangedEvent::new(
entity,
GamepadButton::DPadDown,
digital_settings.release_threshold - (analog_settings.threshold * 1.5),
)),
// Shouldn't trigger a state changed event
RawGamepadEvent::Button(RawGamepadButtonChangedEvent::new(
entity,
GamepadButton::DPadDown,
digital_settings.release_threshold - (analog_settings.threshold * 2.02),
)),
];
ctx.send_raw_gamepad_event_batch(events);
ctx.update();
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadButtonStateChangedEvent>>()
.len(),
2
);
assert_eq!(
ctx.app
.world()
.resource::<Events<GamepadButtonChangedEvent>>()
.len(),
4
);
}
}