PlayerInputManager.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. using System;
  2. using UnityEngine.Events;
  3. using UnityEngine.InputSystem.Controls;
  4. using UnityEngine.InputSystem.LowLevel;
  5. using UnityEngine.InputSystem.Users;
  6. using UnityEngine.InputSystem.Utilities;
  7. ////REVIEW: should we automatically pool/retain up to maxPlayerCount player instances?
  8. ////REVIEW: the join/leave messages should probably give a *GameObject* rather than the PlayerInput component (which can be gotten to via a simple GetComponent(InChildren) call)
  9. ////TODO: add support for reacting to players missing devices
  10. namespace UnityEngine.InputSystem
  11. {
  12. /// <summary>
  13. /// Manages joining and leaving of players.
  14. /// </summary>
  15. /// <remarks>
  16. /// This is a singleton component. Only one instance is meant to be active in a game
  17. /// at any one time. To retrieve the current instance, use <see cref="instance"/>.
  18. ///
  19. /// Note that a PlayerInputManager is not strictly required to have multiple <see cref="PlayerInput"/> components.
  20. /// What PlayerInputManager provides is the implementation of specific player join mechanisms
  21. /// (<see cref="joinBehavior"/>) as well as automatic assignment of split-screen areas (<see cref="splitScreen"/>).
  22. /// However, you can always implement your own custom logic instead and simply instantiate multiple GameObjects with
  23. /// <see cref="PlayerInput"/> yourself.
  24. /// </remarks>
  25. [AddComponentMenu("Input/Player Input Manager")]
  26. public class PlayerInputManager : MonoBehaviour
  27. {
  28. /// <summary>
  29. /// Name of the message that is sent when a player joins the game.
  30. /// </summary>
  31. public const string PlayerJoinedMessage = "OnPlayerJoined";
  32. public const string PlayerLeftMessage = "OnPlayerLeft";
  33. /// <summary>
  34. /// If enabled, each player will automatically be assigned a portion of the available screen area.
  35. /// </summary>
  36. /// <remarks>
  37. /// For this to work, each <see cref="PlayerInput"/> component must have an associated <see cref="Camera"/>
  38. /// object through <see cref="PlayerInput.camera"/>.
  39. ///
  40. /// Note that as player join, the screen may be increasingly subdivided and players may see their
  41. /// previous screen area getting resized.
  42. /// </remarks>
  43. public bool splitScreen
  44. {
  45. get => m_SplitScreen;
  46. set
  47. {
  48. if (m_SplitScreen == value)
  49. return;
  50. m_SplitScreen = value;
  51. if (!m_SplitScreen)
  52. {
  53. // Reset rects on all player cameras.
  54. foreach (var player in PlayerInput.all)
  55. {
  56. var camera = player.camera;
  57. if (camera != null)
  58. camera.rect = new Rect(0, 0, 1, 1);
  59. }
  60. }
  61. else
  62. {
  63. UpdateSplitScreen();
  64. }
  65. }
  66. }
  67. ////REVIEW: we probably need support for filling unused screen areas automatically
  68. /// <summary>
  69. /// If <see cref="splitScreen"/> is enabled, this property determines whether subdividing the screen is allowed to
  70. /// produce screen areas that have an aspect ratio different from the screen resolution.
  71. /// </summary>
  72. /// <remarks>
  73. /// By default, when <see cref="splitScreen"/> is enabled, the manager will add or remove screen subdivisions in
  74. /// steps of two. This means that when, for example, the second player is added, the screen will be subdivided into
  75. /// a left and a right screen area; the left one allocated to the first player and the right one allocated to the
  76. /// second player.
  77. ///
  78. /// This behavior makes optimal use of screen real estate but will result in screen areas that have aspect ratios
  79. /// different from the screen resolution. If this is not acceptable, this property can be set to true to enforce
  80. /// split-screen to only create screen areas that have the same aspect ratio of the screen.
  81. ///
  82. /// This results in the screen being subdivided more aggressively. When, for example, a second player is added,
  83. /// the screen will immediately be divided into a four-way split-screen setup with the lower two screen areas
  84. /// not being used.
  85. ///
  86. /// This property is irrelevant if <see cref="fixedNumberOfSplitScreens"/> is used.
  87. /// </remarks>
  88. public bool maintainAspectRatioInSplitScreen => m_MaintainAspectRatioInSplitScreen;
  89. public int fixedNumberOfSplitScreens => m_FixedNumberOfSplitScreens;
  90. /// <summary>
  91. /// The normalized screen rectangle available for allocating player split-screens into.
  92. /// </summary>
  93. /// <remarks>
  94. /// This is only used if <see cref="splitScreen"/> is true.
  95. ///
  96. /// By default it is set to <c>(0,0,1,1)</c>, i.e. the entire screen area will be used for player screens.
  97. /// If, for example, part of the screen should display a UI/information shared by all players, this
  98. /// property can be used to cut off the area and not have it used by PlayerInputManager.
  99. /// </remarks>
  100. public Rect splitScreenArea => m_SplitScreenRect;
  101. /// <summary>
  102. /// The current number of active players.
  103. /// </summary>
  104. /// <remarks>
  105. /// This count corresponds to all <see cref="PlayerInput"/> instances that are currently enabled.
  106. /// </remarks>
  107. public int playerCount => PlayerInput.s_AllActivePlayersCount;
  108. /// <summary>
  109. /// Maximum number of players allowed concurrently in the game.
  110. /// </summary>
  111. /// <remarks>
  112. /// If this limit is reached, joining is turned off automatically.
  113. ///
  114. /// By default this is set to -1. Any negative value deactivates the player limit and allows
  115. /// arbitrary many players to join.
  116. /// </remarks>
  117. public int maxPlayerCount => m_MaxPlayerCount;
  118. /// <summary>
  119. /// Whether new players can currently join.
  120. /// </summary>
  121. /// <remarks>
  122. /// While this is true, new players can join via the mechanism determined by <see cref="joinBehavior"/>.
  123. /// </remarks>
  124. /// <seealso cref="EnableJoining"/>
  125. /// <seealso cref="DisableJoining"/>
  126. public bool joiningEnabled => m_AllowJoining;
  127. /// <summary>
  128. /// Determines the mechanism by which players can join when joining is enabled (<see cref="joiningEnabled"/>).
  129. /// </summary>
  130. /// <remarks>
  131. /// </remarks>
  132. public PlayerJoinBehavior joinBehavior
  133. {
  134. get => m_JoinBehavior;
  135. set
  136. {
  137. if (m_JoinBehavior == value)
  138. return;
  139. var joiningEnabled = m_AllowJoining;
  140. if (joiningEnabled)
  141. DisableJoining();
  142. m_JoinBehavior = value;
  143. if (joiningEnabled)
  144. EnableJoining();
  145. }
  146. }
  147. public InputActionProperty joinAction
  148. {
  149. get => m_JoinAction;
  150. set
  151. {
  152. if (m_JoinAction == value)
  153. return;
  154. ////REVIEW: should we suppress notifications for temporary disables?
  155. var joinEnabled = m_AllowJoining && m_JoinBehavior == PlayerJoinBehavior.JoinPlayersWhenJoinActionIsTriggered;
  156. if (joinEnabled)
  157. DisableJoining();
  158. m_JoinAction = value;
  159. if (joinEnabled)
  160. EnableJoining();
  161. }
  162. }
  163. public PlayerNotifications notificationBehavior
  164. {
  165. get => m_NotificationBehavior;
  166. set => m_NotificationBehavior = value;
  167. }
  168. public PlayerJoinedEvent playerJoinedEvent
  169. {
  170. get
  171. {
  172. if (m_PlayerJoinedEvent == null)
  173. m_PlayerJoinedEvent = new PlayerJoinedEvent();
  174. return m_PlayerJoinedEvent;
  175. }
  176. }
  177. public PlayerLeftEvent playerLeftEvent
  178. {
  179. get
  180. {
  181. if (m_PlayerLeftEvent == null)
  182. m_PlayerLeftEvent = new PlayerLeftEvent();
  183. return m_PlayerLeftEvent;
  184. }
  185. }
  186. public event Action<PlayerInput> onPlayerJoined
  187. {
  188. add
  189. {
  190. if (value == null)
  191. throw new ArgumentNullException(nameof(value));
  192. m_PlayerJoinedCallbacks.AppendWithCapacity(value, 4);
  193. }
  194. remove
  195. {
  196. if (value == null)
  197. throw new ArgumentNullException(nameof(value));
  198. var index = m_PlayerJoinedCallbacks.IndexOf(value);
  199. if (index != -1)
  200. m_PlayerJoinedCallbacks.RemoveAtWithCapacity(index);
  201. }
  202. }
  203. public event Action<PlayerInput> onPlayerLeft
  204. {
  205. add
  206. {
  207. if (value == null)
  208. throw new ArgumentNullException(nameof(value));
  209. m_PlayerLeftCallbacks.AppendWithCapacity(value, 4);
  210. }
  211. remove
  212. {
  213. if (value == null)
  214. throw new ArgumentNullException(nameof(value));
  215. var index = m_PlayerLeftCallbacks.IndexOf(value);
  216. if (index != -1)
  217. m_PlayerLeftCallbacks.RemoveAtWithCapacity(index);
  218. }
  219. }
  220. /// <summary>
  221. /// Reference to the prefab that the manager will instantiate when players join.
  222. /// </summary>
  223. /// <value>Prefab to instantiate for new players.</value>
  224. public GameObject playerPrefab
  225. {
  226. get => m_PlayerPrefab;
  227. set => m_PlayerPrefab = value;
  228. }
  229. /// <summary>
  230. /// Singleton instance of the manager.
  231. /// </summary>
  232. /// <value>Singleton instance or null.</value>
  233. public static PlayerInputManager instance { get; private set; }
  234. /// <summary>
  235. /// Allow players to join the game based on <see cref="joinBehavior"/>.
  236. /// </summary>
  237. /// <seealso cref="DisableJoining"/>
  238. /// <seealso cref="joiningEnabled"/>
  239. public void EnableJoining()
  240. {
  241. switch (m_JoinBehavior)
  242. {
  243. case PlayerJoinBehavior.JoinPlayersWhenButtonIsPressed:
  244. if (!m_UnpairedDeviceUsedDelegateHooked)
  245. {
  246. if (m_UnpairedDeviceUsedDelegate == null)
  247. m_UnpairedDeviceUsedDelegate = OnUnpairedDeviceUsed;
  248. InputUser.onUnpairedDeviceUsed += m_UnpairedDeviceUsedDelegate;
  249. m_UnpairedDeviceUsedDelegateHooked = true;
  250. ++InputUser.listenForUnpairedDeviceActivity;
  251. }
  252. break;
  253. case PlayerJoinBehavior.JoinPlayersWhenJoinActionIsTriggered:
  254. // Hook into join action if we have one.
  255. if (m_JoinAction.action != null)
  256. {
  257. if (!m_JoinActionDelegateHooked)
  258. {
  259. if (m_JoinActionDelegate == null)
  260. m_JoinActionDelegate = JoinPlayerFromActionIfNotAlreadyJoined;
  261. m_JoinAction.action.performed += m_JoinActionDelegate;
  262. m_JoinActionDelegateHooked = true;
  263. }
  264. m_JoinAction.action.Enable();
  265. }
  266. else
  267. {
  268. Debug.LogError(
  269. "No join action configured on PlayerInputManager but join behavior is set to JoinPlayersWhenActionIsTriggered",
  270. this);
  271. }
  272. break;
  273. }
  274. m_AllowJoining = true;
  275. }
  276. /// <summary>
  277. /// Inhibit players from joining the game.
  278. /// </summary>
  279. /// <seealso cref="EnableJoining"/>
  280. /// <seealso cref="joiningEnabled"/>
  281. public void DisableJoining()
  282. {
  283. switch (m_JoinBehavior)
  284. {
  285. case PlayerJoinBehavior.JoinPlayersWhenButtonIsPressed:
  286. if (m_UnpairedDeviceUsedDelegateHooked)
  287. {
  288. InputUser.onUnpairedDeviceUsed -= m_UnpairedDeviceUsedDelegate;
  289. m_UnpairedDeviceUsedDelegateHooked = false;
  290. --InputUser.listenForUnpairedDeviceActivity;
  291. }
  292. break;
  293. case PlayerJoinBehavior.JoinPlayersWhenJoinActionIsTriggered:
  294. if (m_JoinActionDelegateHooked)
  295. {
  296. var joinAction = m_JoinAction.action;
  297. if (joinAction != null)
  298. m_JoinAction.action.performed -= m_JoinActionDelegate;
  299. m_JoinActionDelegateHooked = false;
  300. }
  301. m_JoinAction.action?.Disable();
  302. break;
  303. }
  304. m_AllowJoining = false;
  305. }
  306. ////TODO
  307. /// <summary>
  308. /// Join a new player based on input on a UI element.
  309. /// </summary>
  310. /// <remarks>
  311. /// This should be called directly from a UI callback such as <see cref="Button.onClick"/>. The device
  312. /// that the player joins with is taken from the device that was used to interact with the UI element.
  313. /// </remarks>
  314. internal void JoinPlayerFromUI()
  315. {
  316. if (!CheckIfPlayerCanJoin())
  317. return;
  318. //find used device; InputSystemUIInputModule should probably make that available
  319. throw new NotImplementedException();
  320. }
  321. /// <summary>
  322. /// Join a new player based on input received through an <see cref="InputAction"/>.
  323. /// </summary>
  324. /// <param name="context"></param>
  325. /// <remarks>
  326. /// </remarks>
  327. public void JoinPlayerFromAction(InputAction.CallbackContext context)
  328. {
  329. if (!CheckIfPlayerCanJoin())
  330. return;
  331. var device = context.control.device;
  332. JoinPlayer(pairWithDevice: device);
  333. }
  334. public void JoinPlayerFromActionIfNotAlreadyJoined(InputAction.CallbackContext context)
  335. {
  336. if (!CheckIfPlayerCanJoin())
  337. return;
  338. var device = context.control.device;
  339. if (PlayerInput.FindFirstPairedToDevice(device) != null)
  340. return;
  341. JoinPlayer(pairWithDevice: device);
  342. }
  343. /// <summary>
  344. /// Spawn a new player from <see cref="playerPrefab"/>.
  345. /// </summary>
  346. /// <param name="playerIndex">Optional explicit <see cref="PlayerInput.playerIndex"/> to assign to the player. Must be unique within
  347. /// <see cref="PlayerInput.all"/>. If not supplied, a player index will be assigned automatically (smallest unused index will be used).</param>
  348. /// <param name="splitScreenIndex">Optional <see cref="PlayerInput.splitScreenIndex"/>. If supplied, this assigns a split-screen area to the player. For example,
  349. /// a split-screen index of </param>
  350. /// <param name="controlScheme">Control scheme to activate on the player (optional). If not supplied, a control scheme will
  351. /// be selected based on <paramref name="pairWithDevice"/>. If no device is given either, the first control scheme that matches
  352. /// the currently available unpaired devices (see <see cref="InputUser.GetUnpairedInputDevices()"/>) is used.</param>
  353. /// <param name="pairWithDevice">Device to pair to the player. Also determines which control scheme to use if <paramref name="controlScheme"/>
  354. /// is not given.</param>
  355. /// <returns>The newly instantiated player or <c>null</c> if joining failed.</returns>
  356. /// <remarks>
  357. /// Joining must be enabled (see <see cref="joiningEnabled"/>) or the method will fail.
  358. ///
  359. /// To pair multiple devices, use <see cref="JoinPlayer(int,int,string,InputDevice[])"/>.
  360. /// </remarks>
  361. public PlayerInput JoinPlayer(int playerIndex = -1, int splitScreenIndex = -1, string controlScheme = null, InputDevice pairWithDevice = null)
  362. {
  363. if (!CheckIfPlayerCanJoin(playerIndex))
  364. return null;
  365. PlayerInput.s_DestroyIfDeviceSetupUnsuccessful = true;
  366. return PlayerInput.Instantiate(m_PlayerPrefab, playerIndex: playerIndex, splitScreenIndex: splitScreenIndex,
  367. controlScheme: controlScheme, pairWithDevice: pairWithDevice);
  368. }
  369. /// <summary>
  370. /// Spawn a new player from <see cref="playerPrefab"/>.
  371. /// </summary>
  372. /// <param name="playerIndex">Optional explicit <see cref="PlayerInput.playerIndex"/> to assign to the player. Must be unique within
  373. /// <see cref="PlayerInput.all"/>. If not supplied, a player index will be assigned automatically (smallest unused index will be used).</param>
  374. /// <param name="splitScreenIndex">Optional <see cref="PlayerInput.splitScreenIndex"/>. If supplied, this assigns a split-screen area to the player. For example,
  375. /// a split-screen index of </param>
  376. /// <param name="controlScheme">Control scheme to activate on the player (optional). If not supplied, a control scheme will
  377. /// be selected based on <paramref name="pairWithDevices"/>. If no device is given either, the first control scheme that matches
  378. /// the currently available unpaired devices (see <see cref="InputUser.GetUnpairedInputDevices()"/>) is used.</param>
  379. /// <param name="pairWithDevices">Devices to pair to the player. Also determines which control scheme to use if <paramref name="controlScheme"/>
  380. /// is not given.</param>
  381. /// <returns>The newly instantiated player or <c>null</c> if joining failed.</returns>
  382. /// <remarks>
  383. /// Joining must be enabled (see <see cref="joiningEnabled"/>) or the method will fail.
  384. /// </remarks>
  385. public PlayerInput JoinPlayer(int playerIndex = -1, int splitScreenIndex = -1, string controlScheme = null, params InputDevice[] pairWithDevices)
  386. {
  387. if (!CheckIfPlayerCanJoin(playerIndex))
  388. return null;
  389. PlayerInput.s_DestroyIfDeviceSetupUnsuccessful = true;
  390. return PlayerInput.Instantiate(m_PlayerPrefab, playerIndex: playerIndex, splitScreenIndex: splitScreenIndex,
  391. controlScheme: controlScheme, pairWithDevices: pairWithDevices);
  392. }
  393. [SerializeField] internal PlayerNotifications m_NotificationBehavior;
  394. [SerializeField] internal int m_MaxPlayerCount = -1;
  395. [SerializeField] internal bool m_AllowJoining = true;
  396. [SerializeField] internal PlayerJoinBehavior m_JoinBehavior;
  397. [SerializeField] internal PlayerJoinedEvent m_PlayerJoinedEvent;
  398. [SerializeField] internal PlayerLeftEvent m_PlayerLeftEvent;
  399. [SerializeField] internal InputActionProperty m_JoinAction;
  400. [SerializeField] internal GameObject m_PlayerPrefab;
  401. [SerializeField] internal bool m_SplitScreen;
  402. [SerializeField] internal bool m_MaintainAspectRatioInSplitScreen;
  403. [SerializeField] internal int m_FixedNumberOfSplitScreens = -1;
  404. [SerializeField] internal Rect m_SplitScreenRect = new Rect(0, 0, 1, 1);
  405. [NonSerialized] private bool m_JoinActionDelegateHooked;
  406. [NonSerialized] private bool m_UnpairedDeviceUsedDelegateHooked;
  407. [NonSerialized] private Action<InputAction.CallbackContext> m_JoinActionDelegate;
  408. [NonSerialized] private Action<InputControl, InputEventPtr> m_UnpairedDeviceUsedDelegate;
  409. [NonSerialized] private InlinedArray<Action<PlayerInput>> m_PlayerJoinedCallbacks;
  410. [NonSerialized] private InlinedArray<Action<PlayerInput>> m_PlayerLeftCallbacks;
  411. internal static string[] messages => new[]
  412. {
  413. PlayerJoinedMessage,
  414. PlayerLeftMessage,
  415. };
  416. private bool CheckIfPlayerCanJoin(int playerIndex = -1)
  417. {
  418. if (m_PlayerPrefab == null)
  419. {
  420. Debug.LogError("playerPrefab must be set in order to be able to join new players", this);
  421. return false;
  422. }
  423. if (m_MaxPlayerCount >= 0 && playerCount >= m_MaxPlayerCount)
  424. {
  425. Debug.LogError("Have reached maximum player count of " + maxPlayerCount, this);
  426. return false;
  427. }
  428. // If we have a player index, make sure it's unique.
  429. if (playerIndex != -1)
  430. {
  431. for (var i = 0; i < PlayerInput.s_AllActivePlayersCount; ++i)
  432. if (PlayerInput.s_AllActivePlayers[i].playerIndex == playerIndex)
  433. {
  434. Debug.LogError(
  435. $"Player index #{playerIndex} is already taken by player {PlayerInput.s_AllActivePlayers[i]}",
  436. PlayerInput.s_AllActivePlayers[i]);
  437. return false;
  438. }
  439. }
  440. return true;
  441. }
  442. private void OnUnpairedDeviceUsed(InputControl control, InputEventPtr eventPtr)
  443. {
  444. if (!m_AllowJoining)
  445. return;
  446. if (m_JoinBehavior == PlayerJoinBehavior.JoinPlayersWhenButtonIsPressed)
  447. {
  448. // Make sure it's a button that was actuated.
  449. if (!(control is ButtonControl))
  450. return;
  451. // Make sure it's a device that is usable by the player's actions. We don't want
  452. // to join a player who's then stranded and has no way to actually interact with the game.
  453. if (!IsDeviceUsableWithPlayerActions(control.device))
  454. return;
  455. ////REVIEW: should we log a warning or error when the actions for the player do not have control schemes?
  456. JoinPlayer(pairWithDevice: control.device);
  457. }
  458. }
  459. private void OnEnable()
  460. {
  461. if (instance == null)
  462. {
  463. instance = this;
  464. }
  465. else
  466. {
  467. Debug.LogWarning("Multiple PlayerInputManagers in the game. There should only be one PlayerInputManager", this);
  468. return;
  469. }
  470. // Join all players already in the game.
  471. for (var i = 0; i < PlayerInput.s_AllActivePlayersCount; ++i)
  472. NotifyPlayerJoined(PlayerInput.s_AllActivePlayers[i]);
  473. if (m_AllowJoining)
  474. EnableJoining();
  475. }
  476. private void OnDisable()
  477. {
  478. if (instance == this)
  479. instance = null;
  480. if (m_AllowJoining)
  481. DisableJoining();
  482. }
  483. /// <summary>
  484. /// If split-screen is enabled, then for each player in the game, adjust the player's <see cref="Camera.rect"/>
  485. /// to fit the player's split screen area according to the number of players currently in the game and the
  486. /// current split-screen configuration.
  487. /// </summary>
  488. private void UpdateSplitScreen()
  489. {
  490. // Nothing to do if split-screen is not enabled.
  491. if (!m_SplitScreen)
  492. return;
  493. // Determine number of split-screens to create based on highest player index we have.
  494. var minSplitScreenCount = 0;
  495. foreach (var player in PlayerInput.all)
  496. {
  497. if (player.playerIndex >= minSplitScreenCount)
  498. minSplitScreenCount = player.playerIndex + 1;
  499. }
  500. // Adjust to fixed number if we have it.
  501. if (m_FixedNumberOfSplitScreens > 0)
  502. {
  503. if (m_FixedNumberOfSplitScreens < minSplitScreenCount)
  504. Debug.LogWarning(
  505. $"Highest playerIndex of {minSplitScreenCount} exceeds fixed number of split-screens of {m_FixedNumberOfSplitScreens}",
  506. this);
  507. minSplitScreenCount = m_FixedNumberOfSplitScreens;
  508. }
  509. // Determine divisions along X and Y. Usually, we have a square grid of split-screens so all we need to
  510. // do is make it large enough to fit all players.
  511. var numDivisionsX = Mathf.CeilToInt(Mathf.Sqrt(minSplitScreenCount));
  512. var numDivisionsY = numDivisionsX;
  513. if (!m_MaintainAspectRatioInSplitScreen && numDivisionsX * (numDivisionsX - 1) >= minSplitScreenCount)
  514. {
  515. // We're allowed to produce split-screens with aspect ratios different from the screen meaning
  516. // that we always add one more column before finally adding an entirely new row.
  517. numDivisionsY -= 1;
  518. }
  519. // Assign split-screen area to each player.
  520. foreach (var player in PlayerInput.all)
  521. {
  522. // Make sure the player's splitScreenIndex isn't out of range.
  523. var splitScreenIndex = player.splitScreenIndex;
  524. if (splitScreenIndex >= numDivisionsX * numDivisionsY)
  525. {
  526. Debug.LogError(
  527. $"Split-screen index of {splitScreenIndex} on player is out of range (have {numDivisionsX * numDivisionsY} screens); resetting to playerIndex",
  528. player);
  529. player.m_SplitScreenIndex = player.playerIndex;
  530. }
  531. // Make sure we have a camera.
  532. var camera = player.camera;
  533. if (camera == null)
  534. {
  535. Debug.LogError(
  536. "Player has no camera associated with it. Cannot set up split-screen. Point PlayerInput.camera to camera for player.",
  537. player);
  538. continue;
  539. }
  540. // Assign split-screen area based on m_SplitScreenRect.
  541. var column = splitScreenIndex % numDivisionsX;
  542. var row = splitScreenIndex / numDivisionsX;
  543. var rect = new Rect
  544. {
  545. width = m_SplitScreenRect.width / numDivisionsX,
  546. height = m_SplitScreenRect.height / numDivisionsY
  547. };
  548. rect.x = m_SplitScreenRect.x + column * rect.width;
  549. // Y is bottom-to-top but we fill from top down.
  550. rect.y = m_SplitScreenRect.y + m_SplitScreenRect.height - (row + 1) * rect.height;
  551. camera.rect = rect;
  552. }
  553. }
  554. private bool IsDeviceUsableWithPlayerActions(InputDevice device)
  555. {
  556. Debug.Assert(device != null);
  557. if (m_PlayerPrefab == null)
  558. return true;
  559. var playerInput = m_PlayerPrefab.GetComponentInChildren<PlayerInput>();
  560. if (playerInput == null)
  561. return true;
  562. var actions = playerInput.actions;
  563. if (actions == null)
  564. return true;
  565. // If the asset has control schemes, see if there's one that works with the device plus
  566. // whatever unpaired devices we have left.
  567. if (actions.controlSchemes.Count > 0)
  568. {
  569. using (var unpairedDevices = InputUser.GetUnpairedInputDevices())
  570. {
  571. if (InputControlScheme.FindControlSchemeForDevices(unpairedDevices, actions.controlSchemes,
  572. mustIncludeDevice: device) == null)
  573. return false;
  574. }
  575. return true;
  576. }
  577. // Otherwise just check whether any of the maps has bindings usable with the device.
  578. foreach (var actionMap in actions.actionMaps)
  579. if (actionMap.IsUsableWithDevice(device))
  580. return true;
  581. return false;
  582. }
  583. /// <summary>
  584. /// Called by <see cref="PlayerInput"/> when it is enabled.
  585. /// </summary>
  586. /// <param name="player"></param>
  587. internal void NotifyPlayerJoined(PlayerInput player)
  588. {
  589. Debug.Assert(player != null);
  590. UpdateSplitScreen();
  591. switch (m_NotificationBehavior)
  592. {
  593. case PlayerNotifications.SendMessages:
  594. SendMessage(PlayerJoinedMessage, player, SendMessageOptions.DontRequireReceiver);
  595. break;
  596. case PlayerNotifications.BroadcastMessages:
  597. BroadcastMessage(PlayerJoinedMessage, player, SendMessageOptions.DontRequireReceiver);
  598. break;
  599. case PlayerNotifications.InvokeUnityEvents:
  600. m_PlayerJoinedEvent?.Invoke(player);
  601. break;
  602. case PlayerNotifications.InvokeCSharpEvents:
  603. DelegateHelpers.InvokeCallbacksSafe(ref m_PlayerJoinedCallbacks, player, "onPlayerJoined");
  604. break;
  605. }
  606. }
  607. /// <summary>
  608. /// Called by <see cref="PlayerInput"/> when it is disabled.
  609. /// </summary>
  610. /// <param name="player"></param>
  611. internal void NotifyPlayerLeft(PlayerInput player)
  612. {
  613. Debug.Assert(player != null);
  614. UpdateSplitScreen();
  615. switch (m_NotificationBehavior)
  616. {
  617. case PlayerNotifications.SendMessages:
  618. SendMessage(PlayerLeftMessage, player, SendMessageOptions.DontRequireReceiver);
  619. break;
  620. case PlayerNotifications.BroadcastMessages:
  621. BroadcastMessage(PlayerLeftMessage, player, SendMessageOptions.DontRequireReceiver);
  622. break;
  623. case PlayerNotifications.InvokeUnityEvents:
  624. m_PlayerLeftEvent?.Invoke(player);
  625. break;
  626. case PlayerNotifications.InvokeCSharpEvents:
  627. DelegateHelpers.InvokeCallbacksSafe(ref m_PlayerLeftCallbacks, player, "onPlayerLeft");
  628. break;
  629. }
  630. }
  631. [Serializable]
  632. public class PlayerJoinedEvent : UnityEvent<PlayerInput>
  633. {
  634. }
  635. [Serializable]
  636. public class PlayerLeftEvent : UnityEvent<PlayerInput>
  637. {
  638. }
  639. }
  640. }