InputActionState.cs 153 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using Unity.Collections;
  6. using Unity.Collections.LowLevel.Unsafe;
  7. using UnityEngine.InputSystem.Controls;
  8. using UnityEngine.InputSystem.LowLevel;
  9. using UnityEngine.InputSystem.Utilities;
  10. using UnityEngine.Profiling;
  11. ////TODO: now that we can bind to controls by display name, we need to re-resolve controls when those change (e.g. when the keyboard layout changes)
  12. ////TODO: remove direct references to InputManager
  13. ////TODO: make sure controls in per-action and per-map control arrays are unique (the internal arrays are probably okay to have duplicates)
  14. ////REVIEW: should the default interaction be an *explicit* interaction?
  15. ////REVIEW: should "pass-through" be an interaction instead of a setting on actions?
  16. ////REVIEW: allow setup where state monitor is enabled but action is disabled?
  17. namespace UnityEngine.InputSystem
  18. {
  19. using InputActionListener = Action<InputAction.CallbackContext>;
  20. /// <summary>
  21. /// Dynamic execution state of one or more <see cref="InputActionMap">action maps</see> and
  22. /// all the actions they contain.
  23. /// </summary>
  24. /// <remarks>
  25. /// The aim of this class is to both put all the dynamic execution state into one place as well
  26. /// as to organize state in tight, GC-optimized arrays. Also, by moving state out of individual
  27. /// <see cref="InputActionMap">action maps</see>, we can combine the state of several maps
  28. /// into one single object with a single set of arrays. Ideally, if you have a single action
  29. /// asset in the game, you get a single InputActionState that contains the entire dynamic
  30. /// execution state for your game's actions.
  31. ///
  32. /// Note that this class allocates unmanaged memory. It has to be disposed of or it will leak
  33. /// memory!
  34. ///
  35. /// An instance of this class is also used for singleton actions by means of the hidden action
  36. /// map we create for those actions. In that case, there will be both a hidden map instance
  37. /// as well as an action state for every separate singleton action. This makes singleton actions
  38. /// relatively expensive.
  39. /// </remarks>
  40. internal unsafe class InputActionState : IInputStateChangeMonitor, ICloneable, IDisposable
  41. {
  42. public const int kInvalidIndex = -1;
  43. /// <summary>
  44. /// Array of all maps added to the state.
  45. /// </summary>
  46. public InputActionMap[] maps;
  47. /// <summary>
  48. /// List of all resolved controls.
  49. /// </summary>
  50. /// <remarks>
  51. /// As we don't know in advance how many controls a binding may match (if any), we bump the size of
  52. /// this array in increments during resolution. This means it may be end up being larger than the total
  53. /// number of used controls and have empty entries at the end. Use <see cref="UnmanagedMemory.controlCount"/> and not
  54. /// <c>.Length</c> to find the actual number of controls.
  55. ///
  56. /// All bound controls are included in the array regardless of whether only a partial set of actions
  57. /// is currently enabled. What ultimately decides whether controls get triggered or not is whether we
  58. /// have installed state monitors for them or not.
  59. /// </remarks>
  60. public InputControl[] controls;
  61. /// <summary>
  62. /// Array of instantiated interaction objects.
  63. /// </summary>
  64. /// <remarks>
  65. /// Every binding that has interactions corresponds to a slice of this array.
  66. ///
  67. /// Indices match between this and interaction states in <see cref="memory"/>.
  68. /// </remarks>
  69. public IInputInteraction[] interactions;
  70. /// <summary>
  71. /// Processor objects instantiated for the bindings in the state.
  72. /// </summary>
  73. public InputProcessor[] processors;
  74. /// <summary>
  75. /// Array of instantiated composite objects.
  76. /// </summary>
  77. public InputBindingComposite[] composites;
  78. public int totalProcessorCount;
  79. public int totalCompositeCount => memory.compositeCount;
  80. public int totalMapCount => memory.mapCount;
  81. public int totalActionCount => memory.actionCount;
  82. public int totalBindingCount => memory.bindingCount;
  83. public int totalInteractionCount => memory.interactionCount;
  84. public int totalControlCount => memory.controlCount;
  85. /// <summary>
  86. /// Block of unmanaged memory that holds the dynamic execution state of the actions and their controls.
  87. /// </summary>
  88. /// <remarks>
  89. /// We keep several arrays of structured data in a single block of unmanaged memory.
  90. /// </remarks>
  91. public UnmanagedMemory memory;
  92. public ActionMapIndices* mapIndices => memory.mapIndices;
  93. public TriggerState* actionStates => memory.actionStates;
  94. public BindingState* bindingStates => memory.bindingStates;
  95. public InteractionState* interactionStates => memory.interactionStates;
  96. public int* controlIndexToBindingIndex => memory.controlIndexToBindingIndex;
  97. public int* enabledControls => memory.enabledControls;
  98. private bool m_OnBeforeUpdateHooked;
  99. private bool m_OnAfterUpdateHooked;
  100. private Action m_OnBeforeUpdateDelegate;
  101. private Action m_OnAfterUpdateDelegate;
  102. /// <summary>
  103. /// Initialize execution state with given resolved binding information.
  104. /// </summary>
  105. /// <param name="resolver"></param>
  106. public void Initialize(InputBindingResolver resolver)
  107. {
  108. ClaimDataFrom(resolver);
  109. AddToGlobaList();
  110. }
  111. internal void ClaimDataFrom(InputBindingResolver resolver)
  112. {
  113. totalProcessorCount = resolver.totalProcessorCount;
  114. maps = resolver.maps;
  115. interactions = resolver.interactions;
  116. processors = resolver.processors;
  117. composites = resolver.composites;
  118. controls = resolver.controls;
  119. memory = resolver.memory;
  120. resolver.memory = new UnmanagedMemory();
  121. }
  122. ~InputActionState()
  123. {
  124. Destroy(isFinalizing: true);
  125. }
  126. public void Dispose()
  127. {
  128. Destroy();
  129. }
  130. private void Destroy(bool isFinalizing = false)
  131. {
  132. if (!isFinalizing)
  133. {
  134. for (var i = 0; i < totalMapCount; ++i)
  135. {
  136. var map = maps[i];
  137. // Remove state change monitors.
  138. if (map.enabled)
  139. DisableControls(i, mapIndices[i].controlStartIndex, mapIndices[i].controlCount);
  140. if (map.m_Asset != null)
  141. map.m_Asset.m_SharedStateForAllMaps = null;
  142. map.m_State = null;
  143. map.m_MapIndexInState = kInvalidIndex;
  144. map.m_EnabledActionsCount = 0;
  145. // Reset action indices on the map's actions.
  146. var actions = map.m_Actions;
  147. if (actions != null)
  148. {
  149. for (var n = 0; n < actions.Length; ++n)
  150. actions[n].m_ActionIndexInState = kInvalidIndex;
  151. }
  152. }
  153. RemoveMapFromGlobalList();
  154. }
  155. memory.Dispose();
  156. }
  157. /// <summary>
  158. /// Create a copy of the state.
  159. /// </summary>
  160. /// <returns></returns>
  161. /// <remarks>
  162. /// The copy is non-functional in so far as it cannot be used to keep track of changes made to
  163. /// any associated actions. However, it can be used to freeze the binding resolution state of
  164. /// a particular set of enabled actions. This is used by <see cref="InputActionTrace"/>.
  165. /// </remarks>
  166. public InputActionState Clone()
  167. {
  168. return new InputActionState
  169. {
  170. maps = ArrayHelpers.Copy(maps),
  171. controls = ArrayHelpers.Copy(controls),
  172. interactions = ArrayHelpers.Copy(interactions),
  173. processors = ArrayHelpers.Copy(processors),
  174. composites = ArrayHelpers.Copy(composites),
  175. totalProcessorCount = totalProcessorCount,
  176. memory = memory.Clone(),
  177. };
  178. }
  179. object ICloneable.Clone()
  180. {
  181. return Clone();
  182. }
  183. /// <summary>
  184. /// Check if the state is currently using a control from the given device.
  185. /// </summary>
  186. /// <param name="device">Any input device.</param>
  187. /// <returns>True if any of the maps in the state has the device in its <see cref="InputActionMap.devices"/>
  188. /// list or if any of the device's controls are contained in <see cref="controls"/>.</returns>
  189. private bool IsUsingDevice(InputDevice device)
  190. {
  191. Debug.Assert(device != null, "Device is null");
  192. // If all maps have device restrictions, the device must be in it
  193. // or we're not using it.
  194. var haveMapsWithoutDeviceRestrictions = false;
  195. for (var i = 0; i < totalMapCount; ++i)
  196. {
  197. var map = maps[i];
  198. var devicesForMap = map.devices;
  199. if (devicesForMap == null)
  200. haveMapsWithoutDeviceRestrictions = true;
  201. else if (devicesForMap.Value.Contains(device))
  202. return true;
  203. }
  204. if (!haveMapsWithoutDeviceRestrictions)
  205. return false;
  206. // Check all our controls one by one.
  207. for (var i = 0; i < totalControlCount; ++i)
  208. if (controls[i].device == device)
  209. return true;
  210. return false;
  211. }
  212. // Check if the state would use a control from the given device.
  213. private bool CanUseDevice(InputDevice device)
  214. {
  215. Debug.Assert(device != null, "Device is null");
  216. // If all maps have device restrictions and the device isn't in them, we can't use
  217. // the device.
  218. var haveMapWithoutDeviceRestrictions = false;
  219. for (var i = 0; i < totalMapCount; ++i)
  220. {
  221. var map = maps[i];
  222. var devicesForMap = map.devices;
  223. if (devicesForMap == null)
  224. haveMapWithoutDeviceRestrictions = true;
  225. else if (devicesForMap.Value.Contains(device))
  226. return true;
  227. }
  228. if (!haveMapWithoutDeviceRestrictions)
  229. return false;
  230. for (var i = 0; i < totalMapCount; ++i)
  231. {
  232. var map = maps[i];
  233. var bindings = map.m_Bindings;
  234. if (bindings == null)
  235. continue;
  236. var bindingCount = bindings.Length;
  237. for (var n = 0; n < bindingCount; ++n)
  238. {
  239. if (InputControlPath.TryFindControl(device, bindings[n].effectivePath) != null)
  240. return true;
  241. }
  242. }
  243. return false;
  244. }
  245. /// <summary>
  246. /// Check whether the state has any actions that are currently enabled.
  247. /// </summary>
  248. /// <returns></returns>
  249. public bool HasEnabledActions()
  250. {
  251. for (var i = 0; i < totalMapCount; ++i)
  252. {
  253. var map = maps[i];
  254. if (map.enabled)
  255. return true;
  256. }
  257. return false;
  258. }
  259. /// <summary>
  260. /// Synchronize the current action states based on what they were before.
  261. /// </summary>
  262. /// <param name="oldState"></param>
  263. /// <remarks>
  264. /// We do this when we have to temporarily disable actions in order to re-resolve bindings.
  265. ///
  266. /// Note that we do NOT restore action states perfectly. I.e. will we will not preserve trigger
  267. /// and interaction states exactly to what they were before. Given that the bound controls may change,
  268. /// it would be non-trivial to reliably correlate the old and the new state. Instead, we simply
  269. /// reenable all the actions and controls that were enabled before and then let the next update
  270. /// take it from there.
  271. /// </remarks>
  272. public void RestoreActionStates(UnmanagedMemory oldState)
  273. {
  274. Debug.Assert(oldState.isAllocated, "Old state contains no memory");
  275. // This method cannot deal with actions and/or maps having been removed.
  276. // It DOES cope with bindings have been added and/or removed, though!
  277. Debug.Assert(oldState.actionCount == memory.actionCount, "Action count in old and new state must be the same");
  278. Debug.Assert(oldState.mapCount == memory.mapCount, "Map count in old and new state must be the same");
  279. // Go through the state map by map and in each map, binding by binding. Enable
  280. // all bound controls for which the respective action isn't disabled.
  281. for (var i = 0; i < memory.bindingCount; ++i)
  282. {
  283. var bindingState = &memory.bindingStates[i];
  284. if (bindingState->isPartOfComposite)
  285. {
  286. // Bindings that are part of composites get enabled through the composite itself.
  287. continue;
  288. }
  289. var actionIndex = bindingState->actionIndex;
  290. if (actionIndex == kInvalidIndex)
  291. {
  292. // Binding is not targeting an action.
  293. continue;
  294. }
  295. // Skip any binding for which the action was disabled.
  296. // NOTE: We check the OLD STATE here. The phase in the new state will change immediately
  297. // on the first binding to an action but there may be multiple bindings leading to the
  298. // same action.
  299. if (oldState.actionStates[actionIndex].phase == InputActionPhase.Disabled)
  300. continue;
  301. // Mark the action as enabled, if not already done.
  302. var actionState = &memory.actionStates[actionIndex];
  303. if (actionState->phase == InputActionPhase.Disabled)
  304. {
  305. actionState->phase = InputActionPhase.Waiting;
  306. // Keep track of actions we enable in each map.
  307. var mapIndex = actionState->mapIndex;
  308. var map = maps[mapIndex];
  309. ++map.m_EnabledActionsCount;
  310. }
  311. // Enable all controls on the binding.
  312. EnableControls(actionState->mapIndex, bindingState->controlStartIndex,
  313. bindingState->controlCount);
  314. }
  315. // Make sure we get an initial state check.
  316. HookOnBeforeUpdate();
  317. // Fire notifications.
  318. if (s_OnActionChange.length > 0)
  319. {
  320. for (var i = 0; i < totalMapCount; ++i)
  321. {
  322. var map = maps[i];
  323. if (map.m_SingletonAction == null && map.m_EnabledActionsCount == map.m_Actions.LengthSafe())
  324. NotifyListenersOfActionChange(InputActionChange.ActionMapEnabled, map);
  325. else
  326. {
  327. var actions = map.actions;
  328. for (var n = 0; n < actions.Count; ++n)
  329. NotifyListenersOfActionChange(InputActionChange.ActionEnabled, actions[n]);
  330. }
  331. }
  332. }
  333. }
  334. /// <summary>
  335. /// Reset the trigger state of the given action such that the action has no record of being triggered.
  336. /// </summary>
  337. /// <param name="actionIndex">Action whose state to reset.</param>
  338. /// <param name="toPhase">Phase to reset the action to. Must be either <see cref="InputActionPhase.Waiting"/>
  339. /// or <see cref="InputActionPhase.Disabled"/>. Other phases cannot be transitioned to through resets.</param>
  340. public void ResetActionState(int actionIndex, InputActionPhase toPhase = InputActionPhase.Waiting)
  341. {
  342. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount, "Action index out of range when resetting action");
  343. Debug.Assert(toPhase == InputActionPhase.Waiting || toPhase == InputActionPhase.Disabled,
  344. "Phase must be Waiting or Disabled");
  345. // If the action in started or performed phase, cancel it first.
  346. var actionState = &actionStates[actionIndex];
  347. if (actionState->phase != InputActionPhase.Waiting)
  348. {
  349. // Cancellation calls should receive current time.
  350. actionState->time = InputRuntime.s_Instance.currentTime;
  351. // If the action got triggered from an interaction, go and reset all interactions on the binding
  352. // that got triggered.
  353. if (actionState->interactionIndex != kInvalidIndex)
  354. {
  355. var bindingIndex = actionState->bindingIndex;
  356. if (bindingIndex != kInvalidIndex)
  357. {
  358. var mapIndex = actionState->mapIndex;
  359. var interactionCount = bindingStates[bindingIndex].interactionCount;
  360. var interactionStartIndex = bindingStates[bindingIndex].interactionStartIndex;
  361. for (var i = 0; i < interactionCount; ++i)
  362. {
  363. var interactionIndex = interactionStartIndex + i;
  364. ResetInteractionStateAndCancelIfNecessary(mapIndex, bindingIndex, interactionIndex);
  365. }
  366. }
  367. }
  368. else
  369. {
  370. // No interactions. Cancel the action directly.
  371. Debug.Assert(actionState->bindingIndex != kInvalidIndex, "Binding index on trigger state is invalid");
  372. Debug.Assert(bindingStates[actionState->bindingIndex].interactionCount == 0,
  373. "Action has been triggered but apparently not from an interaction yet there's interactions on the binding that got triggered?!?");
  374. ChangePhaseOfAction(InputActionPhase.Canceled, ref actionStates[actionIndex]);
  375. }
  376. }
  377. // Wipe state.
  378. var state = *actionState;
  379. state.phase = toPhase;
  380. state.controlIndex = kInvalidIndex;
  381. state.bindingIndex = 0;
  382. state.interactionIndex = kInvalidIndex;
  383. state.startTime = 0;
  384. state.time = 0;
  385. state.hasMultipleConcurrentActuations = false;
  386. state.lastTriggeredInUpdate = default;
  387. *actionState = state;
  388. }
  389. public ref TriggerState FetchActionState(InputAction action)
  390. {
  391. Debug.Assert(action != null, "Action must not be null");
  392. Debug.Assert(action.m_ActionMap != null, "Action must have an action map");
  393. Debug.Assert(action.m_ActionMap.m_MapIndexInState != kInvalidIndex, "Action must have index set");
  394. Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
  395. Debug.Assert(action.m_ActionIndexInState >= 0 && action.m_ActionIndexInState < totalActionCount, "Action index is out of range");
  396. return ref actionStates[action.m_ActionIndexInState];
  397. }
  398. public ActionMapIndices FetchMapIndices(InputActionMap map)
  399. {
  400. Debug.Assert(map != null, "Must must not be null");
  401. Debug.Assert(maps.Contains(map), "Map must be contained in state");
  402. return mapIndices[map.m_MapIndexInState];
  403. }
  404. public void EnableAllActions(InputActionMap map)
  405. {
  406. Debug.Assert(map != null, "Map must not be null");
  407. Debug.Assert(map.m_Actions != null, "Map must have actions");
  408. Debug.Assert(maps.Contains(map), "Map must be contained in state");
  409. // Enable all controls in map that aren't already enabled.
  410. EnableControls(map);
  411. // Put all actions that aren't already enbaled into waiting state.
  412. var mapIndex = map.m_MapIndexInState;
  413. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index on InputActionMap is out of range");
  414. var actionCount = mapIndices[mapIndex].actionCount;
  415. var actionStartIndex = mapIndices[mapIndex].actionStartIndex;
  416. for (var i = 0; i < actionCount; ++i)
  417. {
  418. var actionIndex = actionStartIndex + i;
  419. if (actionStates[actionIndex].isDisabled)
  420. actionStates[actionIndex].phase = InputActionPhase.Waiting;
  421. }
  422. map.m_EnabledActionsCount = actionCount;
  423. HookOnBeforeUpdate();
  424. // Make sure that if we happen to get here with one of the hidden action maps we create for singleton
  425. // action, we notify on the action, not the hidden map.
  426. if (map.m_SingletonAction != null)
  427. NotifyListenersOfActionChange(InputActionChange.ActionEnabled, map.m_SingletonAction);
  428. else
  429. NotifyListenersOfActionChange(InputActionChange.ActionMapEnabled, map);
  430. }
  431. private void EnableControls(InputActionMap map)
  432. {
  433. Debug.Assert(map != null, "Map must not be null");
  434. Debug.Assert(map.m_Actions != null, "Map must have actions");
  435. Debug.Assert(maps.Contains(map), "Map must be contained in state");
  436. var mapIndex = map.m_MapIndexInState;
  437. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index on InputActionMap is out of range");
  438. // Install state monitors for all controls.
  439. var controlCount = mapIndices[mapIndex].controlCount;
  440. var controlStartIndex = mapIndices[mapIndex].controlStartIndex;
  441. if (controlCount > 0)
  442. EnableControls(mapIndex, controlStartIndex, controlCount);
  443. }
  444. public void EnableSingleAction(InputAction action)
  445. {
  446. Debug.Assert(action != null, "Action must not be null");
  447. Debug.Assert(action.m_ActionMap != null, "Action must have action map");
  448. Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
  449. EnableControls(action);
  450. // Put action into waiting state.
  451. var actionIndex = action.m_ActionIndexInState;
  452. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  453. "Action index out of range when enabling single action");
  454. actionStates[actionIndex].phase = InputActionPhase.Waiting;
  455. ++action.m_ActionMap.m_EnabledActionsCount;
  456. HookOnBeforeUpdate();
  457. NotifyListenersOfActionChange(InputActionChange.ActionEnabled, action);
  458. }
  459. private void EnableControls(InputAction action)
  460. {
  461. Debug.Assert(action != null, "Action must not be null");
  462. Debug.Assert(action.m_ActionMap != null, "Action must have action map");
  463. Debug.Assert(maps.Contains(action.m_ActionMap), "Map must be contained in state");
  464. var actionIndex = action.m_ActionIndexInState;
  465. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  466. "Action index out of range when enabling controls");
  467. var map = action.m_ActionMap;
  468. var mapIndex = map.m_MapIndexInState;
  469. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range");
  470. // Go through all bindings in the map and for all that belong to the given action,
  471. // enable the associated controls.
  472. var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
  473. var bindingCount = mapIndices[mapIndex].bindingCount;
  474. var bindingStatesPtr = memory.bindingStates;
  475. for (var i = 0; i < bindingCount; ++i)
  476. {
  477. var bindingIndex = bindingStartIndex + i;
  478. var bindingState = &bindingStatesPtr[bindingIndex];
  479. if (bindingState->actionIndex != actionIndex)
  480. continue;
  481. // Composites enable en-bloc through the composite binding itself.
  482. if (bindingState->isPartOfComposite)
  483. continue;
  484. var controlCount = bindingState->controlCount;
  485. if (controlCount == 0)
  486. continue;
  487. EnableControls(mapIndex, bindingState->controlStartIndex, controlCount);
  488. }
  489. }
  490. public void DisableAllActions(InputActionMap map)
  491. {
  492. Debug.Assert(map != null, "Map must not be null");
  493. Debug.Assert(map.m_Actions != null, "Map must have actions");
  494. Debug.Assert(maps.Contains(map), "Map must be contained in state");
  495. DisableControls(map);
  496. // Mark all actions as disabled.
  497. var mapIndex = map.m_MapIndexInState;
  498. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range");
  499. var actionStartIndex = mapIndices[mapIndex].actionStartIndex;
  500. var actionCount = mapIndices[mapIndex].actionCount;
  501. for (var i = 0; i < actionCount; ++i)
  502. {
  503. var actionIndex = actionStartIndex + i;
  504. if (actionStates[actionIndex].phase != InputActionPhase.Disabled)
  505. ResetActionState(actionIndex, toPhase: InputActionPhase.Disabled);
  506. }
  507. map.m_EnabledActionsCount = 0;
  508. // Make sure that if we happen to get here with one of the hidden action maps we create for singleton
  509. // action, we notify on the action, not the hidden map.
  510. if (map.m_SingletonAction != null)
  511. NotifyListenersOfActionChange(InputActionChange.ActionDisabled, map.m_SingletonAction);
  512. else
  513. NotifyListenersOfActionChange(InputActionChange.ActionMapDisabled, map);
  514. }
  515. private void DisableControls(InputActionMap map)
  516. {
  517. Debug.Assert(map != null, "Map must not be null");
  518. Debug.Assert(map.m_Actions != null, "Map must have actions");
  519. Debug.Assert(maps.Contains(map), "Map must be contained in state");
  520. var mapIndex = map.m_MapIndexInState;
  521. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range");
  522. // Remove state monitors from all controls.
  523. var controlCount = mapIndices[mapIndex].controlCount;
  524. var controlStartIndex = mapIndices[mapIndex].controlStartIndex;
  525. if (controlCount > 0)
  526. DisableControls(mapIndex, controlStartIndex, controlCount);
  527. }
  528. public void DisableSingleAction(InputAction action)
  529. {
  530. Debug.Assert(action != null, "Action must not be null");
  531. Debug.Assert(action.m_ActionMap != null, "Action must have action map");
  532. Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
  533. DisableControls(action);
  534. ResetActionState(action.m_ActionIndexInState, toPhase: InputActionPhase.Disabled);
  535. --action.m_ActionMap.m_EnabledActionsCount;
  536. NotifyListenersOfActionChange(InputActionChange.ActionDisabled, action);
  537. }
  538. private void DisableControls(InputAction action)
  539. {
  540. Debug.Assert(action != null, "Action must not be null");
  541. Debug.Assert(action.m_ActionMap != null, "Action must have action map");
  542. Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
  543. var actionIndex = action.m_ActionIndexInState;
  544. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  545. "Action index out of range when disabling controls");
  546. var map = action.m_ActionMap;
  547. var mapIndex = map.m_MapIndexInState;
  548. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range");
  549. // Go through all bindings in the map and for all that belong to the given action,
  550. // disable the associated controls.
  551. var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
  552. var bindingCount = mapIndices[mapIndex].bindingCount;
  553. var bindingStatesPtr = memory.bindingStates;
  554. for (var i = 0; i < bindingCount; ++i)
  555. {
  556. var bindingIndex = bindingStartIndex + i;
  557. var bindingState = &bindingStatesPtr[bindingIndex];
  558. if (bindingState->actionIndex != actionIndex)
  559. continue;
  560. // Composites enable en-bloc through the composite binding itself.
  561. if (bindingState->isPartOfComposite)
  562. continue;
  563. var controlCount = bindingState->controlCount;
  564. if (controlCount == 0)
  565. continue;
  566. DisableControls(mapIndex, bindingState->controlStartIndex, controlCount);
  567. }
  568. }
  569. ////REVIEW: can we have a method on InputManager doing this in bulk?
  570. ////NOTE: This must not enable only a partial set of controls on a binding (currently we have no setup that would lead to that)
  571. private void EnableControls(int mapIndex, int controlStartIndex, int numControls)
  572. {
  573. Debug.Assert(controls != null, "State must have controls");
  574. Debug.Assert(controlStartIndex >= 0 && (controlStartIndex < totalControlCount || numControls == 0),
  575. "Control start index out of range");
  576. Debug.Assert(controlStartIndex + numControls <= totalControlCount, "Control range out of bounds");
  577. var manager = InputSystem.s_Manager;
  578. for (var i = 0; i < numControls; ++i)
  579. {
  580. var controlIndex = controlStartIndex + i;
  581. // We don't want to add multiple state monitors for the same control. This can happen if enabling
  582. // single actions is mixed with enabling actions maps containing them.
  583. if (IsControlEnabled(controlIndex))
  584. continue;
  585. var bindingIndex = controlIndexToBindingIndex[controlIndex];
  586. var mapControlAndBindingIndex = ToCombinedMapAndControlAndBindingIndex(mapIndex, controlIndex, bindingIndex);
  587. var bindingStatePtr = &bindingStates[bindingIndex];
  588. if (bindingStatePtr->wantsInitialStateCheck)
  589. bindingStatePtr->initialStateCheckPending = true;
  590. manager.AddStateChangeMonitor(controls[controlIndex], this, mapControlAndBindingIndex);
  591. SetControlEnabled(controlIndex, true);
  592. }
  593. }
  594. private void DisableControls(int mapIndex, int controlStartIndex, int numControls)
  595. {
  596. Debug.Assert(controls != null, "State must have controls");
  597. Debug.Assert(controlStartIndex >= 0 && (controlStartIndex < totalControlCount || numControls == 0),
  598. "Control start index out of range");
  599. Debug.Assert(controlStartIndex + numControls <= totalControlCount, "Control range out of bounds");
  600. var manager = InputSystem.s_Manager;
  601. for (var i = 0; i < numControls; ++i)
  602. {
  603. var controlIndex = controlStartIndex + i;
  604. if (!IsControlEnabled(controlIndex))
  605. continue;
  606. var bindingIndex = controlIndexToBindingIndex[controlIndex];
  607. var mapControlAndBindingIndex = ToCombinedMapAndControlAndBindingIndex(mapIndex, controlIndex, bindingIndex);
  608. var bindingStatePtr = &bindingStates[bindingIndex];
  609. if (bindingStatePtr->wantsInitialStateCheck)
  610. bindingStatePtr->initialStateCheckPending = false;
  611. manager.RemoveStateChangeMonitor(controls[controlIndex], this, mapControlAndBindingIndex);
  612. SetControlEnabled(controlIndex, false);
  613. }
  614. }
  615. private bool IsControlEnabled(int controlIndex)
  616. {
  617. var intIndex = controlIndex / 32;
  618. var intMask = 1 << (controlIndex % 32);
  619. return (enabledControls[intIndex] & intMask) != 0;
  620. }
  621. private void SetControlEnabled(int controlIndex, bool state)
  622. {
  623. var intIndex = controlIndex / 32;
  624. var intMask = 1 << (controlIndex % 32);
  625. if (state)
  626. enabledControls[intIndex] |= intMask;
  627. else
  628. enabledControls[intIndex] &= ~intMask;
  629. }
  630. private void HookOnBeforeUpdate()
  631. {
  632. if (m_OnBeforeUpdateHooked)
  633. return;
  634. if (m_OnBeforeUpdateDelegate == null)
  635. m_OnBeforeUpdateDelegate = OnBeforeInitialUpdate;
  636. InputSystem.s_Manager.onBeforeUpdate += m_OnBeforeUpdateDelegate;
  637. m_OnBeforeUpdateHooked = true;
  638. }
  639. private void UnhookOnBeforeUpdate()
  640. {
  641. if (!m_OnBeforeUpdateHooked)
  642. return;
  643. InputSystem.s_Manager.onBeforeUpdate -= m_OnBeforeUpdateDelegate;
  644. m_OnBeforeUpdateHooked = false;
  645. }
  646. // We hook this into InputManager.onBeforeUpdate every time actions are enabled and then take it off
  647. // the list after the first call. Inside here we check whether any actions we enabled already have
  648. // non-default state on bound controls.
  649. //
  650. // NOTE: We do this as a callback from onBeforeUpdate rather than directly when the action is enabled
  651. // to ensure that the callbacks happen during input processing and not randomly from wherever
  652. // an action happens to be enabled.
  653. private void OnBeforeInitialUpdate()
  654. {
  655. if (InputState.currentUpdateType == InputUpdateType.BeforeRender)
  656. return;
  657. // Remove us from the callback as the processing we're doing here is a one-time thing.
  658. UnhookOnBeforeUpdate();
  659. Profiler.BeginSample("InitialActionStateCheck");
  660. // The composite logic relies on the event ID to determine whether a composite binding should trigger again
  661. // when already triggered. Make up a fake event with just an ID.
  662. var inputEvent = new InputEvent {eventId = 1234};
  663. var eventPtr = new InputEventPtr(&inputEvent);
  664. // Use current time as time of control state change.
  665. var time = InputRuntime.s_Instance.currentTime;
  666. ////REVIEW: should we store this data in a separate place rather than go through all bindingStates?
  667. // Go through all binding states and for every binding that needs an initial state check,
  668. // go through all bound controls and for each one that isn't in its default state, pretend
  669. // that the control just got actuated.
  670. for (var bindingIndex = 0; bindingIndex < totalBindingCount; ++bindingIndex)
  671. {
  672. if (!bindingStates[bindingIndex].initialStateCheckPending)
  673. continue;
  674. bindingStates[bindingIndex].initialStateCheckPending = false;
  675. var mapIndex = bindingStates[bindingIndex].mapIndex;
  676. var controlStartIndex = bindingStates[bindingIndex].controlStartIndex;
  677. var controlCount = bindingStates[bindingIndex].controlCount;
  678. for (var n = 0; n < controlCount; ++n)
  679. {
  680. var controlIndex = controlStartIndex + n;
  681. var control = controls[controlIndex];
  682. if (!control.CheckStateIsAtDefault())
  683. ProcessControlStateChange(mapIndex, controlIndex, bindingIndex, time, eventPtr);
  684. }
  685. }
  686. Profiler.EndSample();
  687. }
  688. // Called from InputManager when one of our state change monitors has fired.
  689. // Tells us the time of the change *according to the state events coming in*.
  690. // Also tells us which control of the controls we are binding to triggered the
  691. // change and relays the binding index we gave it when we called AddChangeMonitor.
  692. void IInputStateChangeMonitor.NotifyControlStateChanged(InputControl control, double time,
  693. InputEventPtr eventPtr, long mapControlAndBindingIndex)
  694. {
  695. #if UNITY_EDITOR
  696. if (InputState.currentUpdateType == InputUpdateType.Editor)
  697. return;
  698. #endif
  699. SplitUpMapAndControlAndBindingIndex(mapControlAndBindingIndex, out var mapIndex, out var controlIndex, out var bindingIndex);
  700. ProcessControlStateChange(mapIndex, controlIndex, bindingIndex, time, eventPtr);
  701. }
  702. void IInputStateChangeMonitor.NotifyTimerExpired(InputControl control, double time,
  703. long mapControlAndBindingIndex, int interactionIndex)
  704. {
  705. SplitUpMapAndControlAndBindingIndex(mapControlAndBindingIndex, out var mapIndex, out var controlIndex, out var bindingIndex);
  706. ProcessTimeout(time, mapIndex, controlIndex, bindingIndex, interactionIndex);
  707. }
  708. // We mangle the various indices we use into a single long for association with state change
  709. // monitors. While we could look up map and binding indices from control indices, keeping
  710. // all the information together avoids having to unnecessarily jump around in memory to grab
  711. // the various pieces of data.
  712. private static long ToCombinedMapAndControlAndBindingIndex(int mapIndex, int controlIndex, int bindingIndex)
  713. {
  714. var result = (long)controlIndex;
  715. result |= (long)bindingIndex << 32;
  716. result |= (long)mapIndex << 48;
  717. return result;
  718. }
  719. private static void SplitUpMapAndControlAndBindingIndex(long mapControlAndBindingIndex, out int mapIndex,
  720. out int controlIndex, out int bindingIndex)
  721. {
  722. controlIndex = (int)(mapControlAndBindingIndex & 0xffffffff);
  723. bindingIndex = (int)((mapControlAndBindingIndex >> 32) & 0xffff);
  724. mapIndex = (int)(mapControlAndBindingIndex >> 48);
  725. }
  726. /// <summary>
  727. /// Process a state change that has happened in one of the controls attached
  728. /// to this action map state.
  729. /// </summary>
  730. /// <param name="mapIndex">Index of the action map to which the binding belongs.</param>
  731. /// <param name="controlIndex">Index of the control that changed state.</param>
  732. /// <param name="bindingIndex">Index of the binding associated with the given control.</param>
  733. /// <param name="time">The timestamp associated with the state change (comes from the state change event).</param>
  734. /// <param name="eventPtr">Event (if any) that triggered the state change.</param>
  735. /// <remarks>
  736. /// This is where we end up if one of the state monitors we've put in the system has triggered.
  737. /// From here we go back to the associated binding and then let it figure out what the state change
  738. /// means for it.
  739. ///
  740. /// Note that we get called for any change in state even if the change in state does not actually
  741. /// result in a change of value on the respective control.
  742. /// </remarks>
  743. private void ProcessControlStateChange(int mapIndex, int controlIndex, int bindingIndex, double time, InputEventPtr eventPtr)
  744. {
  745. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range");
  746. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index out of range");
  747. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  748. var bindingStatePtr = &bindingStates[bindingIndex];
  749. var actionIndex = bindingStatePtr->actionIndex;
  750. var trigger = new TriggerState
  751. {
  752. mapIndex = mapIndex,
  753. controlIndex = controlIndex,
  754. bindingIndex = bindingIndex,
  755. interactionIndex = kInvalidIndex,
  756. time = time,
  757. startTime = time,
  758. isPassThrough = actionIndex != kInvalidIndex && actionStates[actionIndex].isPassThrough,
  759. };
  760. // If we have pending initial state checks that will run in the next update,
  761. // force-reset the flag on the control that just triggered. This ensures that we're
  762. // not triggering an action twice from the same state change in case the initial state
  763. // check happens later (see Actions_ValueActionsEnabledInOnEvent_DoNotReactToCurrentStateOfControlTwice).
  764. if (m_OnBeforeUpdateHooked)
  765. bindingStatePtr->initialStateCheckPending = false;
  766. // If the binding is part of a composite, check for interactions on the composite
  767. // itself and give them a first shot at processing the value change.
  768. var haveInteractionsOnComposite = false;
  769. if (bindingStatePtr->isPartOfComposite)
  770. {
  771. var compositeBindingIndex = bindingStatePtr->compositeOrCompositeBindingIndex;
  772. var compositeBindingPtr = &bindingStates[compositeBindingIndex];
  773. // If the composite has already been triggered from the very same event, ignore it.
  774. // Example: KeyboardState change that includes both A and W key state changes and we're looking
  775. // at a WASD composite binding. There's a state change monitor on both the A and the W
  776. // key and thus the manager will notify us individually of both changes. However, we
  777. // want to perform the action only once.
  778. if (ShouldIgnoreControlStateChangeOnCompositeBinding(compositeBindingPtr, eventPtr))
  779. return;
  780. // Common conflict resolution. We do this *after* the check above as it is more expensive.
  781. if (ShouldIgnoreControlStateChange(ref trigger, actionIndex))
  782. return;
  783. // Run through interactions on composite.
  784. var interactionCountOnComposite = compositeBindingPtr->interactionCount;
  785. if (interactionCountOnComposite > 0)
  786. {
  787. haveInteractionsOnComposite = true;
  788. ProcessInteractions(ref trigger,
  789. compositeBindingPtr->interactionStartIndex,
  790. interactionCountOnComposite);
  791. }
  792. }
  793. else if (ShouldIgnoreControlStateChange(ref trigger, actionIndex))
  794. {
  795. return;
  796. }
  797. // If we have interactions, let them do all the processing. The presence of an interaction
  798. // essentially bypasses the default phase progression logic of an action.
  799. var interactionCount = bindingStatePtr->interactionCount;
  800. if (interactionCount > 0 && !bindingStatePtr->isPartOfComposite)
  801. {
  802. ProcessInteractions(ref trigger, bindingStatePtr->interactionStartIndex, interactionCount);
  803. }
  804. else if (!haveInteractionsOnComposite)
  805. {
  806. ProcessDefaultInteraction(ref trigger, actionIndex);
  807. }
  808. }
  809. /// <summary>
  810. /// Whether the given state change on a composite binding should be ignored.
  811. /// </summary>
  812. /// <param name="binding"></param>
  813. /// <param name="eventPtr"></param>
  814. /// <returns></returns>
  815. /// <remarks>
  816. /// Each state event may change the state of arbitrary many controls on a device and thus may trigger
  817. /// several bindings at once that are part of the same composite binding. We still want to trigger the
  818. /// composite binding only once for the event.
  819. ///
  820. /// To do so, we store the ID of the event on the binding and ignore events if they have the same
  821. /// ID as the one we've already recorded.
  822. /// </remarks>
  823. private static bool ShouldIgnoreControlStateChangeOnCompositeBinding(BindingState* binding, InputEvent* eventPtr)
  824. {
  825. if (eventPtr == null)
  826. return false;
  827. var eventId = eventPtr->eventId;
  828. if (binding->triggerEventIdForComposite == eventId)
  829. return true;
  830. binding->triggerEventIdForComposite = eventId;
  831. return false;
  832. }
  833. /// <summary>
  834. /// Whether the given control state should be ignored.
  835. /// </summary>
  836. /// <param name="trigger"></param>
  837. /// <param name="actionIndex"></param>
  838. /// <returns></returns>
  839. /// <remarks>
  840. /// If an action has multiple controls bound to it, control state changes on the action may conflict with each other.
  841. /// If that happens, we resolve the conflict by always sticking to the most actuated control.
  842. ///
  843. /// Pass-through actions (<see cref="InputAction.passThrough"/>) will always bypass conflict resolution and respond
  844. /// to every value change.
  845. ///
  846. /// Actions that are resolved to only a single control will early out of conflict resolution.
  847. ///
  848. /// Actions that are bound to multiple controls but have only one control actuated will early out of conflict
  849. /// resolution as well.
  850. ///
  851. /// Note that conflict resolution here is entirely tied to magnitude. This ignores other qualities that the value
  852. /// of a control may have. For example, one 2D vector may have a similar magnitude to another yet point in an
  853. /// entirely different direction.
  854. ///
  855. /// There are other conflict resolution mechanisms that could be used. For example, we could average the values
  856. /// from all controls. However, it would not necessarily result in more useful conflict resolution and would
  857. /// at the same time be much more expensive.
  858. /// </remarks>
  859. private bool ShouldIgnoreControlStateChange(ref TriggerState trigger, int actionIndex)
  860. {
  861. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  862. "Action index out of range when checking for conflicting control input");
  863. // The goal of this method is to provide conflict resolution but do so ONLY if it is
  864. // really needed. In the vast majority of cases, this method should do almost nothing and
  865. // simply return straight away.
  866. // If conflict resolution is disabled on the action, early out. This is the case for pass-through
  867. // actions and for actions that cannot get into an ambiguous state based on the controls they
  868. // are bound to.
  869. var actionState = &actionStates[actionIndex];
  870. if (!actionState->mayNeedConflictResolution)
  871. return false;
  872. // Anything past here happens only for actions that may have conflicts.
  873. // Anything below here we want to avoid executing whenever we can.
  874. Debug.Assert(actionState->mayNeedConflictResolution);
  875. Profiler.BeginSample("InputActionResolveConflict");
  876. // Compute magnitude, if necessary.
  877. // NOTE: This will automatically take composites into account.
  878. if (!trigger.haveMagnitude)
  879. trigger.magnitude = ComputeMagnitude(trigger.bindingIndex, trigger.controlIndex);
  880. // We take a local copy of this value, so we can change it to use the starting control of composites
  881. // for simpler conflict resolution (so composites always use the same value), but still report the actually
  882. // actuated control to the user.
  883. var triggerControlIndex = trigger.controlIndex;
  884. // Update magnitude stored in state.
  885. if (bindingStates[trigger.bindingIndex].isPartOfComposite)
  886. {
  887. // Control is part of a composite. Store magnitude in compositeMagnitudes.
  888. // NOTE: This path here implies that we never store magnitudes individually for controls
  889. // that are part of composites.
  890. var compositeBindingIndex = bindingStates[trigger.bindingIndex].compositeOrCompositeBindingIndex;
  891. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  892. memory.compositeMagnitudes[compositeIndex] = trigger.magnitude;
  893. // For actions that need conflict resolution, we force TriggerState.controlIndex to the
  894. // first control in a composite. Otherwise it becomes much harder to tell if the we have
  895. // multiple concurrent actuations or not.
  896. // Since composites always evaluate as a whole instead of as single controls, having
  897. // triggerControlIndex differ from the state monitor that fired should be fine.
  898. triggerControlIndex = bindingStates[compositeBindingIndex].controlStartIndex;
  899. Debug.Assert(triggerControlIndex >= 0 && triggerControlIndex < totalControlCount,
  900. "Control start index on composite binding out of range");
  901. }
  902. else
  903. {
  904. Debug.Assert(!bindingStates[trigger.bindingIndex].isComposite,
  905. "Composite should not trigger directly from a control");
  906. // "Normal" control. Store magnitude in controlMagnitudes.
  907. memory.controlMagnitudes[triggerControlIndex] = trigger.magnitude;
  908. }
  909. // Never ignore state changes for actions that aren't currently driven by
  910. // anything.
  911. if (actionState->controlIndex == kInvalidIndex)
  912. {
  913. Profiler.EndSample();
  914. return false;
  915. }
  916. // If the control is actuated *more* than the current level of actuation we recorded for the
  917. // action, we process the state change normally. If this isn't the control that is already
  918. // driving the action, it will become the one now.
  919. //
  920. // NOTE: For composites, we're looking at the combined actuation of the entire binding here,
  921. // not just at the actuation level of the individual control. ComputeMagnitude()
  922. // automatically takes care of that for us.
  923. if (trigger.magnitude > actionState->magnitude)
  924. {
  925. // If this is not the control that is currently driving the action, we know
  926. // there are multiple controls that are concurrently actuated on the control.
  927. // Remember that so that when the controls are released again, we can more
  928. // efficiently determine whether we need to take multiple bound controls into
  929. // account or not.
  930. // NOTE: For composites, we have forced triggerControlIndex to the first control
  931. // in the composite. See above.
  932. if (trigger.magnitude > 0 && triggerControlIndex != actionState->controlIndex && actionState->magnitude > 0)
  933. actionState->hasMultipleConcurrentActuations = true;
  934. Profiler.EndSample();
  935. return false;
  936. }
  937. var actionStateControlIndex = actionState->controlIndex;
  938. if (bindingStates[actionState->bindingIndex].isPartOfComposite)
  939. {
  940. var compositeBindingIndex = bindingStates[actionState->bindingIndex].compositeOrCompositeBindingIndex;
  941. actionStateControlIndex = bindingStates[compositeBindingIndex].controlStartIndex;
  942. }
  943. // If the control is actuated *less* then the current level of actuation we
  944. // recorded for the action *and* the control that changed is the one that is currently
  945. // driving the action, we have to check whether there is another actuation
  946. // that is now *higher* than what we're getting from the current control.
  947. if (trigger.magnitude < actionState->magnitude)
  948. {
  949. // If we're not currently driving the action, it's simple. Doesn't matter that we lowered
  950. // actuation as we didn't have the highest actuation anyway.
  951. if (triggerControlIndex != actionStateControlIndex)
  952. {
  953. Profiler.EndSample();
  954. ////REVIEW: should we *count* actuations instead? (problem is that then we have to reliably determine when a control
  955. //// first actuates; the current solution will occasionally run conflict resolution when it doesn't have to
  956. //// but won't require the extra bookkeeping)
  957. // Do NOT let this control state change affect the action.
  958. // NOTE: We do not update hasMultipleConcurrentActuations here which means that it may
  959. // temporarily be wrong. If that happens, we will end up eventually running the
  960. // conflict resolution code below even when we technically wouldn't need to but
  961. // it'll sync the actuation state.
  962. return true;
  963. }
  964. // If we don't have multiple controls that are currently actuated, it's simple.
  965. if (!actionState->hasMultipleConcurrentActuations)
  966. {
  967. Profiler.EndSample();
  968. return false;
  969. }
  970. ////REVIEW: is there a simpler way we can do this???
  971. // So, now we know we are actually looking at a potential conflict. Multiple
  972. // controls bound to the action are actuated but we don't yet know whether
  973. // any of them is actuated *more* than the control that had just changed value.
  974. // Go through the bindings for the action and see what we've got.
  975. var bindingStartIndex = memory.actionBindingIndicesAndCounts[actionIndex * 2];
  976. var bindingCount = memory.actionBindingIndicesAndCounts[actionIndex * 2 + 1];
  977. var highestActuationLevel = trigger.magnitude;
  978. var controlWithHighestActuation = kInvalidIndex;
  979. var bindingWithHighestActuation = kInvalidIndex;
  980. var numActuations = 0;
  981. for (var i = 0; i < bindingCount; ++i)
  982. {
  983. var bindingIndex = memory.actionBindingIndices[bindingStartIndex + i];
  984. var binding = &memory.bindingStates[bindingIndex];
  985. if (binding->isComposite)
  986. {
  987. // Composite bindings result in a single actuation value regardless of how
  988. // many controls are bound through the parts of the composite.
  989. var firstControlIndex = binding->controlStartIndex;
  990. var compositeIndex = binding->compositeOrCompositeBindingIndex;
  991. Debug.Assert(firstControlIndex >= 0 && firstControlIndex < totalControlCount,
  992. "Control start index out of range on composite");
  993. Debug.Assert(compositeIndex >= 0 && compositeIndex < totalCompositeCount,
  994. "Composite index out of range on composite");
  995. var magnitude = memory.compositeMagnitudes[compositeIndex];
  996. if (magnitude > 0)
  997. ++numActuations;
  998. if (magnitude > highestActuationLevel)
  999. {
  1000. controlWithHighestActuation = firstControlIndex;
  1001. bindingWithHighestActuation = controlIndexToBindingIndex[firstControlIndex];
  1002. highestActuationLevel = magnitude;
  1003. }
  1004. }
  1005. else if (!binding->isPartOfComposite)
  1006. {
  1007. // Check actuation of each control on the binding.
  1008. for (var n = 0; n < binding->controlCount; ++n)
  1009. {
  1010. var controlIndex = binding->controlStartIndex + n;
  1011. var magnitude = memory.controlMagnitudes[controlIndex];
  1012. if (magnitude > 0)
  1013. ++numActuations;
  1014. if (magnitude > highestActuationLevel)
  1015. {
  1016. controlWithHighestActuation = controlIndex;
  1017. bindingWithHighestActuation = bindingIndex;
  1018. highestActuationLevel = magnitude;
  1019. }
  1020. }
  1021. }
  1022. }
  1023. // Update our record of whether there are multiple concurrent actuations.
  1024. if (numActuations <= 1)
  1025. actionState->hasMultipleConcurrentActuations = false;
  1026. // If we didn't find a control with a higher actuation level, then go and process
  1027. // the control value change.
  1028. if (controlWithHighestActuation != kInvalidIndex)
  1029. {
  1030. // We do have a control with a higher actuation level. Switch from our current
  1031. // control to processing the control with the now highest actuation level.
  1032. //
  1033. // NOTE: We are processing an artificial control state change here. Information
  1034. // such as the timestamp will not correspond to when the control actually
  1035. // changed value. However, if we skip processing this as a separate control
  1036. // change here, interactions may not behave properly as they would not be
  1037. // seeing that we just lowered the actuation level on the action.
  1038. trigger.controlIndex = controlWithHighestActuation;
  1039. trigger.bindingIndex = bindingWithHighestActuation;
  1040. trigger.magnitude = highestActuationLevel;
  1041. Profiler.EndSample();
  1042. return false;
  1043. }
  1044. }
  1045. Profiler.EndSample();
  1046. // If we're not really effecting any change on the action, ignore the control state change.
  1047. // NOTE: We may be looking at a control here that points in a completely direction, for example, even
  1048. // though it has the same magnitude. However, we require a control to *higher* absolute actuation
  1049. // before we let it drive the action.
  1050. if (Mathf.Approximately(trigger.magnitude, actionState->magnitude))
  1051. {
  1052. // However, if we have changed the control to a different control on the same composite, we *should* let
  1053. // it drive the action - this is like a direction change on the same control.
  1054. if (bindingStates[trigger.bindingIndex].isPartOfComposite && triggerControlIndex == actionStateControlIndex)
  1055. return false;
  1056. if (trigger.magnitude > 0 && triggerControlIndex != actionState->controlIndex)
  1057. actionState->hasMultipleConcurrentActuations = true;
  1058. return true;
  1059. }
  1060. return false;
  1061. }
  1062. /// <summary>
  1063. /// When there is no interaction on an action, this method perform the default interaction logic that we
  1064. /// run when a bound control changes value.
  1065. /// </summary>
  1066. /// <param name="trigger">Control trigger state.</param>
  1067. /// <param name="actionIndex"></param>
  1068. /// <remarks>
  1069. /// The default interaction does not have its own <see cref="InteractionState"/>. Whatever we do in here,
  1070. /// we store directly on the action state.
  1071. ///
  1072. /// The default interaction is basically a sort of optimization where we don't require having an explicit
  1073. /// interaction object. Conceptually, it can be thought of, however, as putting this interaction on any
  1074. /// binding that doesn't have any other interaction on it.
  1075. /// </remarks>
  1076. private void ProcessDefaultInteraction(ref TriggerState trigger, int actionIndex)
  1077. {
  1078. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  1079. "Action index out of range when processing default interaction");
  1080. switch (actionStates[actionIndex].phase)
  1081. {
  1082. case InputActionPhase.Waiting:
  1083. {
  1084. // Pass-through actions we perform on every value change and then go back
  1085. // to waiting.
  1086. if (trigger.isPassThrough)
  1087. {
  1088. ChangePhaseOfAction(InputActionPhase.Performed, ref trigger,
  1089. phaseAfterPerformedOrCanceled: InputActionPhase.Waiting);
  1090. break;
  1091. }
  1092. // Ignore if the control has not crossed its actuation threshold.
  1093. if (IsActuated(ref trigger))
  1094. {
  1095. // Go into started, then perform and then go back to started.
  1096. ChangePhaseOfAction(InputActionPhase.Started, ref trigger);
  1097. ChangePhaseOfAction(InputActionPhase.Performed, ref trigger,
  1098. phaseAfterPerformedOrCanceled: InputActionPhase.Started);
  1099. }
  1100. break;
  1101. }
  1102. case InputActionPhase.Started:
  1103. {
  1104. if (!IsActuated(ref trigger))
  1105. {
  1106. // Control went back to below actuation threshold. Cancel interaction.
  1107. ChangePhaseOfAction(InputActionPhase.Canceled, ref trigger);
  1108. }
  1109. else
  1110. {
  1111. // Control changed value above magnitude threshold. Perform and remain started.
  1112. ChangePhaseOfAction(InputActionPhase.Performed, ref trigger,
  1113. phaseAfterPerformedOrCanceled: InputActionPhase.Started);
  1114. }
  1115. break;
  1116. }
  1117. case InputActionPhase.Performed:
  1118. {
  1119. Debug.Assert(actionStates[actionIndex].isPassThrough,
  1120. "Only pass-through actions should be left in performed state by default interaction");
  1121. ChangePhaseOfAction(InputActionPhase.Performed, ref trigger,
  1122. phaseAfterPerformedOrCanceled: InputActionPhase.Performed);
  1123. break;
  1124. }
  1125. default:
  1126. Debug.Assert(false, "Should not get here");
  1127. break;
  1128. }
  1129. }
  1130. private void ProcessInteractions(ref TriggerState trigger, int interactionStartIndex, int interactionCount)
  1131. {
  1132. var context = new InputInteractionContext
  1133. {
  1134. m_State = this,
  1135. m_TriggerState = trigger
  1136. };
  1137. for (var i = 0; i < interactionCount; ++i)
  1138. {
  1139. var index = interactionStartIndex + i;
  1140. var state = interactionStates[index];
  1141. var interaction = interactions[index];
  1142. context.m_TriggerState.phase = state.phase;
  1143. context.m_TriggerState.startTime = state.startTime;
  1144. context.m_TriggerState.interactionIndex = index;
  1145. interaction.Process(ref context);
  1146. }
  1147. }
  1148. private void ProcessTimeout(double time, int mapIndex, int controlIndex, int bindingIndex, int interactionIndex)
  1149. {
  1150. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index out of range");
  1151. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1152. Debug.Assert(interactionIndex >= 0 && interactionIndex < totalInteractionCount, "Interaction index out of range");
  1153. var currentState = interactionStates[interactionIndex];
  1154. var context = new InputInteractionContext
  1155. {
  1156. m_State = this,
  1157. m_TriggerState =
  1158. new TriggerState
  1159. {
  1160. phase = currentState.phase,
  1161. time = time,
  1162. mapIndex = mapIndex,
  1163. controlIndex = controlIndex,
  1164. bindingIndex = bindingIndex,
  1165. interactionIndex = interactionIndex,
  1166. startTime = currentState.startTime
  1167. },
  1168. timerHasExpired = true,
  1169. };
  1170. currentState.isTimerRunning = false;
  1171. interactionStates[interactionIndex] = currentState;
  1172. // Let interaction handle timer expiration.
  1173. interactions[interactionIndex].Process(ref context);
  1174. }
  1175. internal void StartTimeout(float seconds, ref TriggerState trigger)
  1176. {
  1177. Debug.Assert(trigger.mapIndex >= 0 && trigger.mapIndex < totalMapCount, "Map index out of range");
  1178. Debug.Assert(trigger.controlIndex >= 0 && trigger.controlIndex < totalControlCount, "Control index out of range");
  1179. Debug.Assert(trigger.interactionIndex >= 0 && trigger.interactionIndex < totalInteractionCount, "Interaction index out of range");
  1180. var manager = InputSystem.s_Manager;
  1181. var currentTime = trigger.time;
  1182. var control = controls[trigger.controlIndex];
  1183. var interactionIndex = trigger.interactionIndex;
  1184. var monitorIndex =
  1185. ToCombinedMapAndControlAndBindingIndex(trigger.mapIndex, trigger.controlIndex, trigger.bindingIndex);
  1186. // If there's already a timeout running, cancel it first.
  1187. if (interactionStates[interactionIndex].isTimerRunning)
  1188. StopTimeout(trigger.mapIndex, trigger.controlIndex, trigger.bindingIndex, interactionIndex);
  1189. // Add new timeout.
  1190. manager.AddStateChangeMonitorTimeout(control, this, currentTime + seconds, monitorIndex,
  1191. interactionIndex);
  1192. // Update state.
  1193. var interactionState = interactionStates[interactionIndex];
  1194. interactionState.isTimerRunning = true;
  1195. interactionStates[interactionIndex] = interactionState;
  1196. }
  1197. private void StopTimeout(int mapIndex, int controlIndex, int bindingIndex, int interactionIndex)
  1198. {
  1199. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range");
  1200. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index out of range");
  1201. Debug.Assert(interactionIndex >= 0 && interactionIndex < totalInteractionCount, "Interaction index out of range");
  1202. var manager = InputSystem.s_Manager;
  1203. var monitorIndex =
  1204. ToCombinedMapAndControlAndBindingIndex(mapIndex, controlIndex, bindingIndex);
  1205. manager.RemoveStateChangeMonitorTimeout(this, monitorIndex, interactionIndex);
  1206. // Update state.
  1207. var interactionState = interactionStates[interactionIndex];
  1208. interactionState.isTimerRunning = false;
  1209. interactionStates[interactionIndex] = interactionState;
  1210. }
  1211. /// <summary>
  1212. /// Perform a phase change on the given interaction. Only visible to observers
  1213. /// if it happens to change the phase of the action, too.
  1214. /// </summary>
  1215. /// <param name="newPhase">New phase to transition the interaction to.</param>
  1216. /// <param name="trigger">Information about the binding and control that triggered the phase change.</param>
  1217. /// <param name="phaseAfterPerformed">If <paramref name="newPhase"/> is <see cref="InputActionPhase.Performed"/>,
  1218. /// this determines which phase to transition to after the action has been performed. This would usually be
  1219. /// <see cref="InputActionPhase.Waiting"/> (default), <see cref="InputActionPhase.Started"/> (if the action is supposed
  1220. /// to be oscillate between started and performed), or <see cref="InputActionPhase.Performed"/> (if the action is
  1221. /// supposed to perform over and over again until canceled).</param>
  1222. /// <remarks>
  1223. /// Multiple interactions on the same binding can be started concurrently but the
  1224. /// first interaction that starts will get to drive an action until it either cancels
  1225. /// or performs the action.
  1226. ///
  1227. /// If an interaction driving an action performs it, all interactions will reset and
  1228. /// go back waiting.
  1229. ///
  1230. /// If an interaction driving an action cancels it, the next interaction in the list which
  1231. /// has already started will get to drive the action (example: a TapInteraction and a
  1232. /// SlowTapInteraction both start and the TapInteraction gets to drive the action because
  1233. /// it comes first; then the TapInteraction cancels because the button is held for too
  1234. /// long and the SlowTapInteraction will get to drive the action next).
  1235. /// </remarks>
  1236. internal void ChangePhaseOfInteraction(InputActionPhase newPhase, ref TriggerState trigger,
  1237. InputActionPhase phaseAfterPerformed = InputActionPhase.Waiting)
  1238. {
  1239. var interactionIndex = trigger.interactionIndex;
  1240. var bindingIndex = trigger.bindingIndex;
  1241. Debug.Assert(interactionIndex >= 0 && interactionIndex < totalInteractionCount, "Interaction index out of range");
  1242. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1243. ////TODO: need to make sure that performed and canceled phase changes happen on the *same* binding&control
  1244. //// as the start of the phase
  1245. var phaseAfterPerformedOrCanceled = InputActionPhase.Waiting;
  1246. if (newPhase == InputActionPhase.Performed)
  1247. phaseAfterPerformedOrCanceled = phaseAfterPerformed;
  1248. // Any time an interaction changes phase, we cancel all pending timeouts.
  1249. if (interactionStates[interactionIndex].isTimerRunning)
  1250. StopTimeout(trigger.mapIndex, trigger.controlIndex, trigger.bindingIndex, trigger.interactionIndex);
  1251. // Update interaction state.
  1252. interactionStates[interactionIndex].phase = newPhase;
  1253. interactionStates[interactionIndex].triggerControlIndex = trigger.controlIndex;
  1254. interactionStates[interactionIndex].startTime = trigger.startTime;
  1255. ////REVIEW: If we want to defer triggering of actions, this is the point where we probably need to cut things off
  1256. // See if it affects the phase of an associated action.
  1257. var actionIndex = bindingStates[bindingIndex].actionIndex; // We already had to tap this array and entry in ProcessControlStateChange.
  1258. if (actionIndex != -1)
  1259. {
  1260. if (actionStates[actionIndex].phase == InputActionPhase.Waiting)
  1261. {
  1262. // We're the first interaction to go to the start phase.
  1263. ChangePhaseOfAction(newPhase, ref trigger,
  1264. phaseAfterPerformedOrCanceled: phaseAfterPerformedOrCanceled);
  1265. }
  1266. else if (newPhase == InputActionPhase.Canceled && actionStates[actionIndex].interactionIndex == trigger.interactionIndex)
  1267. {
  1268. // We're canceling but maybe there's another interaction ready
  1269. // to go into start phase.
  1270. ChangePhaseOfAction(newPhase, ref trigger);
  1271. var interactionStartIndex = bindingStates[bindingIndex].interactionStartIndex;
  1272. var numInteractions = bindingStates[bindingIndex].interactionCount;
  1273. for (var i = 0; i < numInteractions; ++i)
  1274. {
  1275. var index = interactionStartIndex + i;
  1276. if (index != trigger.interactionIndex && interactionStates[index].phase == InputActionPhase.Started)
  1277. {
  1278. var startTime = interactionStates[index].startTime;
  1279. var triggerForInteraction = new TriggerState
  1280. {
  1281. phase = InputActionPhase.Started,
  1282. controlIndex = interactionStates[index].triggerControlIndex,
  1283. bindingIndex = trigger.bindingIndex,
  1284. interactionIndex = index,
  1285. time = startTime,
  1286. startTime = startTime,
  1287. };
  1288. ChangePhaseOfAction(InputActionPhase.Started, ref triggerForInteraction);
  1289. break;
  1290. }
  1291. }
  1292. }
  1293. else if (actionStates[actionIndex].interactionIndex == trigger.interactionIndex)
  1294. {
  1295. // Any other phase change goes to action if we're the interaction driving
  1296. // the current phase.
  1297. ChangePhaseOfAction(newPhase, ref trigger, phaseAfterPerformedOrCanceled);
  1298. // We're the interaction driving the action and we performed the action,
  1299. // so reset any other interaction to waiting state.
  1300. if (newPhase == InputActionPhase.Performed)
  1301. {
  1302. var interactionStartIndex = bindingStates[bindingIndex].interactionStartIndex;
  1303. var numInteractions = bindingStates[bindingIndex].interactionCount;
  1304. for (var i = 0; i < numInteractions; ++i)
  1305. {
  1306. var index = interactionStartIndex + i;
  1307. if (index != trigger.interactionIndex)
  1308. ResetInteractionState(trigger.mapIndex, trigger.bindingIndex, index);
  1309. }
  1310. }
  1311. }
  1312. }
  1313. // If the interaction performed or canceled, go back to waiting.
  1314. // Exception: if it was performed and we're to remain in started state, set the interaction
  1315. // to started. Note that for that phase transition, there are no callbacks being
  1316. // triggered (i.e. we don't call 'started' every time after 'performed').
  1317. if (newPhase == InputActionPhase.Performed && phaseAfterPerformed != InputActionPhase.Waiting)
  1318. {
  1319. interactionStates[interactionIndex].phase = phaseAfterPerformed;
  1320. }
  1321. else if (newPhase == InputActionPhase.Performed || newPhase == InputActionPhase.Canceled)
  1322. {
  1323. ResetInteractionState(trigger.mapIndex, trigger.bindingIndex, trigger.interactionIndex);
  1324. }
  1325. ////TODO: reset entire chain
  1326. }
  1327. /// <summary>
  1328. /// Change the current phase of the action referenced by <paramref name="trigger"/> to <paramref name="newPhase"/>.
  1329. /// </summary>
  1330. /// <param name="newPhase">New phase to transition to.</param>
  1331. /// <param name="trigger">Trigger that caused the change in phase.</param>
  1332. /// <param name="phaseAfterPerformedOrCanceled"></param>
  1333. /// <remarks>
  1334. /// The change in phase is visible to observers, i.e. on the various callbacks and notifications.
  1335. ///
  1336. /// If <paramref name="newPhase"/> is <see cref="InputActionPhase.Performed"/> or <see cref="InputActionPhase.Canceled"/>,
  1337. /// the action will subsequently immediately transition to <paramref name="phaseAfterPerformedOrCanceled"/>
  1338. /// (<see cref="InputActionPhase.Waiting"/> by default). This change is not visible to observers, i.e. there won't
  1339. /// be another run through callbacks.
  1340. /// </remarks>
  1341. private void ChangePhaseOfAction(InputActionPhase newPhase, ref TriggerState trigger,
  1342. InputActionPhase phaseAfterPerformedOrCanceled = InputActionPhase.Waiting)
  1343. {
  1344. Debug.Assert(newPhase != InputActionPhase.Disabled, "Should not disable an action using this method");
  1345. Debug.Assert(trigger.mapIndex >= 0 && trigger.mapIndex < totalMapCount, "Map index out of range");
  1346. Debug.Assert(trigger.controlIndex >= 0 && trigger.controlIndex < totalControlCount, "Control index out of range");
  1347. Debug.Assert(trigger.bindingIndex >= 0 && trigger.bindingIndex < totalBindingCount, "Binding index out of range");
  1348. var actionIndex = bindingStates[trigger.bindingIndex].actionIndex;
  1349. if (actionIndex == kInvalidIndex)
  1350. return; // No action associated with binding.
  1351. // Ignore if action is disabled.
  1352. var actionState = &actionStates[actionIndex];
  1353. if (actionState->isDisabled)
  1354. return;
  1355. // Enforce transition constraints.
  1356. if (actionState->isPassThrough && trigger.interactionIndex == kInvalidIndex)
  1357. {
  1358. // No constraints on pass-through actions except if there are interactions driving the action.
  1359. ChangePhaseOfActionInternal(actionIndex, actionState, newPhase, ref trigger);
  1360. if (actionState->isDisabled)
  1361. return;
  1362. }
  1363. else if (newPhase == InputActionPhase.Performed && actionState->phase == InputActionPhase.Waiting)
  1364. {
  1365. // Going from waiting to performed, we make a detour via started.
  1366. ChangePhaseOfActionInternal(actionIndex, actionState, InputActionPhase.Started, ref trigger);
  1367. if (actionState->isDisabled)
  1368. return;
  1369. // Then we perform.
  1370. ChangePhaseOfActionInternal(actionIndex, actionState, newPhase, ref trigger);
  1371. if (actionState->isDisabled)
  1372. return;
  1373. // And finally, if we're going back to waiting, we make a detour via canceled.
  1374. if (phaseAfterPerformedOrCanceled == InputActionPhase.Waiting)
  1375. ChangePhaseOfActionInternal(actionIndex, actionState, InputActionPhase.Canceled, ref trigger);
  1376. if (actionState->isDisabled)
  1377. return;
  1378. actionState->phase = phaseAfterPerformedOrCanceled;
  1379. }
  1380. else
  1381. {
  1382. ChangePhaseOfActionInternal(actionIndex, actionState, newPhase, ref trigger);
  1383. if (actionState->isDisabled)
  1384. return;
  1385. if (newPhase == InputActionPhase.Performed || newPhase == InputActionPhase.Canceled)
  1386. actionState->phase = phaseAfterPerformedOrCanceled;
  1387. }
  1388. // If we're now waiting, reset control state. This is important for the disambiguation code
  1389. // to not consider whatever control actuation happened on the action last.
  1390. if (actionState->phase == InputActionPhase.Waiting)
  1391. {
  1392. actionState->controlIndex = kInvalidIndex;
  1393. actionState->flags &= ~TriggerState.Flags.HaveMagnitude;
  1394. }
  1395. }
  1396. private void ChangePhaseOfActionInternal(int actionIndex, TriggerState* actionState, InputActionPhase newPhase, ref TriggerState trigger)
  1397. {
  1398. // Update action state.
  1399. Debug.Assert(trigger.mapIndex == actionState->mapIndex,
  1400. "Map index on trigger does not correspond to map index of trigger state");
  1401. var newState = trigger;
  1402. newState.flags = actionState->flags;
  1403. newState.phase = newPhase;
  1404. if (!newState.haveMagnitude)
  1405. newState.magnitude = ComputeMagnitude(trigger.bindingIndex, trigger.controlIndex);
  1406. if (newPhase == InputActionPhase.Performed)
  1407. newState.lastTriggeredInUpdate = InputUpdate.s_UpdateStepCount;
  1408. else
  1409. newState.lastTriggeredInUpdate = actionState->lastTriggeredInUpdate;
  1410. if (newPhase == InputActionPhase.Started)
  1411. newState.startTime = newState.time;
  1412. *actionState = newState;
  1413. // Let listeners know.
  1414. var map = maps[trigger.mapIndex];
  1415. Debug.Assert(actionIndex >= mapIndices[trigger.mapIndex].actionStartIndex,
  1416. "actionIndex is below actionStartIndex for map that the action belongs to");
  1417. var action = map.m_Actions[actionIndex - mapIndices[trigger.mapIndex].actionStartIndex];
  1418. trigger.phase = newPhase;
  1419. switch (newPhase)
  1420. {
  1421. case InputActionPhase.Started:
  1422. {
  1423. CallActionListeners(actionIndex, map, newPhase, ref action.m_OnStarted, "started");
  1424. break;
  1425. }
  1426. case InputActionPhase.Performed:
  1427. {
  1428. CallActionListeners(actionIndex, map, newPhase, ref action.m_OnPerformed, "performed");
  1429. break;
  1430. }
  1431. case InputActionPhase.Canceled:
  1432. {
  1433. CallActionListeners(actionIndex, map, newPhase, ref action.m_OnCanceled, "canceled");
  1434. break;
  1435. }
  1436. }
  1437. }
  1438. private void CallActionListeners(int actionIndex, InputActionMap actionMap, InputActionPhase phase, ref InlinedArray<InputActionListener> listeners, string callbackName)
  1439. {
  1440. // If there's no listeners, don't bother with anything else.
  1441. var callbacksOnMap = actionMap.m_ActionCallbacks;
  1442. if (listeners.length == 0 && callbacksOnMap.length == 0 && s_OnActionChange.length == 0)
  1443. return;
  1444. var context = new InputAction.CallbackContext
  1445. {
  1446. m_State = this,
  1447. m_ActionIndex = actionIndex,
  1448. };
  1449. Profiler.BeginSample("InputActionCallback");
  1450. // Global callback goes first.
  1451. var action = context.action;
  1452. if (s_OnActionChange.length > 0)
  1453. {
  1454. InputActionChange change;
  1455. switch (phase)
  1456. {
  1457. case InputActionPhase.Started:
  1458. change = InputActionChange.ActionStarted;
  1459. break;
  1460. case InputActionPhase.Performed:
  1461. change = InputActionChange.ActionPerformed;
  1462. break;
  1463. case InputActionPhase.Canceled:
  1464. change = InputActionChange.ActionCanceled;
  1465. break;
  1466. default:
  1467. Debug.Assert(false, "Should not reach here");
  1468. return;
  1469. }
  1470. for (var i = 0; i < s_OnActionChange.length; ++i)
  1471. s_OnActionChange[i](action, change);
  1472. }
  1473. // Run callbacks (if any) directly on action.
  1474. DelegateHelpers.InvokeCallbacksSafe(ref listeners, context, callbackName, action);
  1475. // Run callbacks (if any) on action map.
  1476. DelegateHelpers.InvokeCallbacksSafe(ref callbacksOnMap, context, callbackName, actionMap);
  1477. Profiler.EndSample();
  1478. }
  1479. private object GetActionOrNoneString(ref TriggerState trigger)
  1480. {
  1481. var action = GetActionOrNull(ref trigger);
  1482. if (action == null)
  1483. return "<none>";
  1484. return action;
  1485. }
  1486. internal InputAction GetActionOrNull(int bindingIndex)
  1487. {
  1488. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1489. var actionIndex = bindingStates[bindingIndex].actionIndex;
  1490. if (actionIndex == kInvalidIndex)
  1491. return null;
  1492. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  1493. "Action index out of range when getting action");
  1494. var mapIndex = bindingStates[bindingIndex].mapIndex;
  1495. var actionStartIndex = mapIndices[mapIndex].actionStartIndex;
  1496. return maps[mapIndex].m_Actions[actionIndex - actionStartIndex];
  1497. }
  1498. internal InputAction GetActionOrNull(ref TriggerState trigger)
  1499. {
  1500. Debug.Assert(trigger.mapIndex >= 0 && trigger.mapIndex < totalMapCount, "Map index out of range");
  1501. Debug.Assert(trigger.bindingIndex >= 0 && trigger.bindingIndex < totalBindingCount, "Binding index out of range");
  1502. var actionIndex = bindingStates[trigger.bindingIndex].actionIndex;
  1503. if (actionIndex == kInvalidIndex)
  1504. return null;
  1505. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount, "Action index out of range");
  1506. var actionStartIndex = mapIndices[trigger.mapIndex].actionStartIndex;
  1507. return maps[trigger.mapIndex].m_Actions[actionIndex - actionStartIndex];
  1508. }
  1509. internal InputControl GetControl(ref TriggerState trigger)
  1510. {
  1511. Debug.Assert(trigger.controlIndex != kInvalidIndex, "Control index is invalid");
  1512. Debug.Assert(trigger.controlIndex >= 0 && trigger.controlIndex < totalControlCount, "Control index out of range");
  1513. return controls[trigger.controlIndex];
  1514. }
  1515. private IInputInteraction GetInteractionOrNull(ref TriggerState trigger)
  1516. {
  1517. if (trigger.interactionIndex == kInvalidIndex)
  1518. return null;
  1519. Debug.Assert(trigger.interactionIndex >= 0 && trigger.interactionIndex < totalInteractionCount, "Interaction index out of range");
  1520. return interactions[trigger.interactionIndex];
  1521. }
  1522. internal int GetBindingIndexInMap(int bindingIndex)
  1523. {
  1524. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1525. var mapIndex = bindingStates[bindingIndex].mapIndex;
  1526. var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
  1527. return bindingIndex - bindingStartIndex;
  1528. }
  1529. internal int GetBindingIndexInState(int mapIndex, int bindingIndexInMap)
  1530. {
  1531. var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
  1532. return bindingStartIndex + bindingIndexInMap;
  1533. }
  1534. internal InputBinding GetBinding(int bindingIndex)
  1535. {
  1536. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1537. var mapIndex = bindingStates[bindingIndex].mapIndex;
  1538. var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
  1539. return maps[mapIndex].m_Bindings[bindingIndex - bindingStartIndex];
  1540. }
  1541. private void ResetInteractionStateAndCancelIfNecessary(int mapIndex, int bindingIndex, int interactionIndex)
  1542. {
  1543. Debug.Assert(interactionIndex >= 0 && interactionIndex < totalInteractionCount, "Interaction index out of range");
  1544. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1545. // If interaction is currently driving an action and it has been started or performed,
  1546. // cancel it.
  1547. //
  1548. // NOTE: We could just blindly call ChangePhaseOfInteraction() and it would handle the case of
  1549. // when the interaction is currently driving the action automatically. However, doing so
  1550. // would give other interactions a chance to take over which is something we don't want to
  1551. // happen when resetting actions.
  1552. var actionIndex = bindingStates[bindingIndex].actionIndex;
  1553. if (actionStates[actionIndex].interactionIndex == interactionIndex)
  1554. {
  1555. switch (interactionStates[interactionIndex].phase)
  1556. {
  1557. case InputActionPhase.Started:
  1558. case InputActionPhase.Performed:
  1559. ChangePhaseOfInteraction(InputActionPhase.Canceled, ref actionStates[actionIndex]);
  1560. break;
  1561. }
  1562. }
  1563. ResetInteractionState(mapIndex, bindingIndex, interactionIndex);
  1564. }
  1565. private void ResetInteractionState(int mapIndex, int bindingIndex, int interactionIndex)
  1566. {
  1567. Debug.Assert(interactionIndex >= 0 && interactionIndex < totalInteractionCount, "Interaction index out of range");
  1568. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1569. // Clean up internal state that the interaction may keep.
  1570. interactions[interactionIndex].Reset();
  1571. // Clean up timer.
  1572. if (interactionStates[interactionIndex].isTimerRunning)
  1573. {
  1574. var controlIndex = interactionStates[interactionIndex].triggerControlIndex;
  1575. StopTimeout(mapIndex, controlIndex, bindingIndex, interactionIndex);
  1576. }
  1577. // Reset state record.
  1578. interactionStates[interactionIndex] =
  1579. new InteractionState
  1580. {
  1581. // We never set interactions to disabled. This way we don't have to go through them
  1582. // when we disable/enable actions.
  1583. phase = InputActionPhase.Waiting,
  1584. };
  1585. }
  1586. internal int GetValueSizeInBytes(int bindingIndex, int controlIndex)
  1587. {
  1588. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1589. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index out of range");
  1590. if (bindingStates[bindingIndex].isPartOfComposite) ////TODO: instead, just have compositeOrCompositeBindingIndex be invalid
  1591. {
  1592. var compositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex;
  1593. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  1594. var compositeObject = composites[compositeIndex];
  1595. Debug.Assert(compositeObject != null, "Composite object on composite state is null");
  1596. return compositeObject.valueSizeInBytes;
  1597. }
  1598. var control = controls[controlIndex];
  1599. Debug.Assert(control != null, "Control at given index is null");
  1600. return control.valueSizeInBytes;
  1601. }
  1602. internal Type GetValueType(int bindingIndex, int controlIndex)
  1603. {
  1604. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1605. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index out of range");
  1606. if (bindingStates[bindingIndex].isPartOfComposite) ////TODO: instead, just have compositeOrCompositeBindingIndex be invalid
  1607. {
  1608. var compositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex;
  1609. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  1610. var compositeObject = composites[compositeIndex];
  1611. Debug.Assert(compositeObject != null, "Composite object is null");
  1612. return compositeObject.valueType;
  1613. }
  1614. var control = controls[controlIndex];
  1615. Debug.Assert(control != null, "Control is null");
  1616. return control.valueType;
  1617. }
  1618. internal bool IsActuated(ref TriggerState trigger, float threshold = 0)
  1619. {
  1620. if (!trigger.haveMagnitude)
  1621. trigger.magnitude = ComputeMagnitude(trigger.bindingIndex, trigger.controlIndex);
  1622. if (trigger.magnitude < 0)
  1623. return true;
  1624. if (Mathf.Approximately(threshold, 0))
  1625. return trigger.magnitude > 0;
  1626. return trigger.magnitude >= threshold;
  1627. }
  1628. private float ComputeMagnitude(int bindingIndex, int controlIndex)
  1629. {
  1630. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index is out of range");
  1631. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index is out of range");
  1632. if (bindingStates[bindingIndex].isPartOfComposite)
  1633. {
  1634. var compositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex;
  1635. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  1636. var compositeObject = composites[compositeIndex];
  1637. var context = new InputBindingCompositeContext
  1638. {
  1639. m_State = this,
  1640. m_BindingIndex = compositeBindingIndex
  1641. };
  1642. return compositeObject.EvaluateMagnitude(ref context);
  1643. }
  1644. var control = controls[controlIndex];
  1645. if (control.CheckStateIsAtDefault())
  1646. {
  1647. // Avoid magnitude computation if control state is at default.
  1648. return 0;
  1649. }
  1650. return control.EvaluateMagnitude();
  1651. }
  1652. ////REVIEW: we can unify the reading paths once we have blittable type constraints
  1653. internal void ReadValue(int bindingIndex, int controlIndex, void* buffer, int bufferSize)
  1654. {
  1655. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1656. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index out of range");
  1657. InputControl control = null;
  1658. // If the binding that triggered the action is part of a composite, let
  1659. // the composite determine the value we return.
  1660. if (bindingStates[bindingIndex].isPartOfComposite)
  1661. {
  1662. var compositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex;
  1663. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  1664. var compositeObject = composites[compositeIndex];
  1665. Debug.Assert(compositeObject != null, "Composite object is null");
  1666. var context = new InputBindingCompositeContext
  1667. {
  1668. m_State = this,
  1669. m_BindingIndex = compositeBindingIndex
  1670. };
  1671. compositeObject.ReadValue(ref context, buffer, bufferSize);
  1672. }
  1673. else
  1674. {
  1675. control = controls[controlIndex];
  1676. Debug.Assert(control != null, "Control is null");
  1677. control.ReadValueIntoBuffer(buffer, bufferSize);
  1678. }
  1679. // Run value through processors, if any.
  1680. var processorCount = bindingStates[bindingIndex].processorCount;
  1681. if (processorCount > 0)
  1682. {
  1683. var processorStartIndex = bindingStates[bindingIndex].processorStartIndex;
  1684. for (var i = 0; i < processorCount; ++i)
  1685. processors[processorStartIndex + i].Process(buffer, bufferSize, control);
  1686. }
  1687. }
  1688. internal TValue ReadValue<TValue>(int bindingIndex, int controlIndex, bool ignoreComposites = false)
  1689. where TValue : struct
  1690. {
  1691. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index is out of range");
  1692. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index is out of range");
  1693. var value = default(TValue);
  1694. // In the case of a composite, this will be null.
  1695. InputControl<TValue> controlOfType = null;
  1696. // If the binding that triggered the action is part of a composite, let
  1697. // the composite determine the value we return.
  1698. if (!ignoreComposites && bindingStates[bindingIndex].isPartOfComposite)
  1699. {
  1700. var compositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex;
  1701. Debug.Assert(compositeBindingIndex >= 0 && compositeBindingIndex < totalBindingCount, "Composite binding index is out of range");
  1702. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  1703. var compositeObject = composites[compositeIndex];
  1704. Debug.Assert(compositeObject != null, "Composite object is null");
  1705. var compositeOfType = compositeObject as InputBindingComposite<TValue>;
  1706. if (compositeOfType == null)
  1707. {
  1708. var compositeType = compositeObject.GetType();
  1709. while (compositeType != null && !compositeType.IsGenericType)
  1710. compositeType = compositeType.BaseType;
  1711. throw new InvalidOperationException(
  1712. $"Cannot read value of type '{typeof(TValue).Name}' from composite '{compositeObject}' bound to action '{GetActionOrNull(bindingIndex)}' (composite is a '{compositeIndex.GetType().Name}' with value type '{TypeHelpers.GetNiceTypeName(compositeType.GetGenericArguments()[0])}')");
  1713. }
  1714. var context = new InputBindingCompositeContext
  1715. {
  1716. m_State = this,
  1717. m_BindingIndex = compositeBindingIndex
  1718. };
  1719. value = compositeOfType.ReadValue(ref context);
  1720. // Switch bindingIndex to that of composite so that we use the right processors.
  1721. bindingIndex = compositeBindingIndex;
  1722. }
  1723. else
  1724. {
  1725. var control = controls[controlIndex];
  1726. Debug.Assert(control != null, "Control is null");
  1727. controlOfType = control as InputControl<TValue>;
  1728. if (controlOfType == null)
  1729. throw new InvalidOperationException(
  1730. $"Cannot read value of type '{TypeHelpers.GetNiceTypeName(typeof(TValue))}' from control '{control.path}' bound to action '{GetActionOrNull(bindingIndex)}' (control is a '{control.GetType().Name}' with value type '{TypeHelpers.GetNiceTypeName(control.valueType)}')");
  1731. value = controlOfType.ReadValue();
  1732. }
  1733. // Run value through processors, if any.
  1734. var processorCount = bindingStates[bindingIndex].processorCount;
  1735. if (processorCount > 0)
  1736. {
  1737. var processorStartIndex = bindingStates[bindingIndex].processorStartIndex;
  1738. for (var i = 0; i < processorCount; ++i)
  1739. {
  1740. if (processors[processorStartIndex + i] is InputProcessor<TValue> processor)
  1741. value = processor.Process(value, controlOfType);
  1742. }
  1743. }
  1744. return value;
  1745. }
  1746. /// <summary>
  1747. /// Read the value of the given part of a composite binding.
  1748. /// </summary>
  1749. /// <param name="bindingIndex">Index of the composite binding in <see cref="bindingStates"/>.</param>
  1750. /// <param name="partNumber">Index of the part. Note that part indices start at 1!</param>
  1751. /// <typeparam name="TValue">Value type to read. Must correspond to the value of bound controls or an exception will
  1752. /// be thrown.</typeparam>
  1753. /// <returns>Greatest value from among the bound controls for the given part.</returns>
  1754. /// <remarks>
  1755. /// Composites are composed of "parts". Each part has an associated name (e.g. "negative" or "positive") which is
  1756. /// referenced by <see cref="InputBinding.name"/> of bindings that are part of the composite. However, multiple
  1757. /// bindings may reference the same part (e.g. there could be a binding for "W" and another binding for "UpArrow"
  1758. /// and both would reference the "Up" part).
  1759. ///
  1760. /// However, a given composite will only be interested in a single value for any given part. What we do is give
  1761. /// a composite an integer key for every part. When it asks for a value for the given part, we go through all
  1762. /// bindings that reference the given part and return the greatest value from among the controls of all those
  1763. /// bindings.
  1764. ///
  1765. /// <example>
  1766. /// <code>
  1767. /// // Read a float value from the second part of the composite binding at index 3.
  1768. /// ReadCompositePartValue&lt;float&gt;(3, 2);
  1769. /// </code>
  1770. /// </example>
  1771. /// </remarks>
  1772. internal TValue ReadCompositePartValue<TValue, TComparer>(int bindingIndex, int partNumber,
  1773. bool* buttonValuePtr, out int controlIndex, TComparer comparer = default)
  1774. where TValue : struct
  1775. where TComparer : IComparer<TValue>
  1776. {
  1777. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index is out of range");
  1778. Debug.Assert(bindingStates[bindingIndex].isComposite, "Binding must be a composite");
  1779. var result = default(TValue);
  1780. var firstChildBindingIndex = bindingIndex + 1;
  1781. var isFirstValue = true;
  1782. controlIndex = kInvalidIndex;
  1783. // Find the binding in the composite that both has the given part number and
  1784. // the greatest value.
  1785. //
  1786. // NOTE: It is tempting to go by control magnitudes instead as those are readily available to us (controlMagnitudes)
  1787. // and avoids us reading values that we're not going to use. Unfortunately, we can't do that as several controls
  1788. // used by a composite may all have been updated with a single event (e.g. WASD on a keyboard will usually see
  1789. // just one update that refreshes the entire state of the keyboard). In that case, one of the controls will
  1790. // see its state monitor trigger first and in turn trigger processing of the action and composite. Thus only
  1791. // that one single control would have its value refreshed in controlMagnitudes whereas the other control magnitudes
  1792. // would be stale.
  1793. for (var index = firstChildBindingIndex; index < totalBindingCount && bindingStates[index].isPartOfComposite; ++index)
  1794. {
  1795. if (bindingStates[index].partIndex != partNumber)
  1796. continue;
  1797. var controlCount = bindingStates[index].controlCount;
  1798. var controlStartIndex = bindingStates[index].controlStartIndex;
  1799. for (var i = 0; i < controlCount; ++i)
  1800. {
  1801. var thisControlIndex = controlStartIndex + i;
  1802. var value = ReadValue<TValue>(index, thisControlIndex, ignoreComposites: true);
  1803. if (isFirstValue)
  1804. {
  1805. result = value;
  1806. controlIndex = thisControlIndex;
  1807. isFirstValue = false;
  1808. }
  1809. else if (comparer.Compare(value, result) > 0)
  1810. {
  1811. result = value;
  1812. controlIndex = thisControlIndex;
  1813. }
  1814. if (buttonValuePtr != null && controlIndex == thisControlIndex)
  1815. {
  1816. var control = controls[thisControlIndex];
  1817. if (control is ButtonControl button)
  1818. {
  1819. *buttonValuePtr = button.isPressed;
  1820. }
  1821. else if (control is InputControl<float>)
  1822. {
  1823. var valuePtr = UnsafeUtility.AddressOf(ref value);
  1824. *buttonValuePtr = *(float*)valuePtr >= ButtonControl.s_GlobalDefaultButtonPressPoint;
  1825. }
  1826. ////REVIEW: Early out here as soon as *any* button is pressed? Technically, the comparer
  1827. //// could still select a different control, though...
  1828. }
  1829. }
  1830. }
  1831. return result;
  1832. }
  1833. internal object ReadValueAsObject(int bindingIndex, int controlIndex)
  1834. {
  1835. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index is out of range");
  1836. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index is out of range");
  1837. InputControl control = null;
  1838. object value;
  1839. // If the binding that triggered the action is part of a composite, let
  1840. // the composite determine the value we return.
  1841. if (bindingStates[bindingIndex].isPartOfComposite) ////TODO: instead, just have compositeOrCompositeBindingIndex be invalid
  1842. {
  1843. var compositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex;
  1844. Debug.Assert(compositeBindingIndex >= 0 && compositeBindingIndex < totalBindingCount, "Binding index is out of range");
  1845. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  1846. var compositeObject = composites[compositeIndex];
  1847. Debug.Assert(compositeObject != null, "Composite object is null");
  1848. var context = new InputBindingCompositeContext
  1849. {
  1850. m_State = this,
  1851. m_BindingIndex = compositeBindingIndex
  1852. };
  1853. value = compositeObject.ReadValueAsObject(ref context);
  1854. }
  1855. else
  1856. {
  1857. control = controls[controlIndex];
  1858. Debug.Assert(control != null, "Control is null");
  1859. value = control.ReadValueAsObject();
  1860. }
  1861. // Run value through processors, if any.
  1862. var processorCount = bindingStates[bindingIndex].processorCount;
  1863. if (processorCount > 0)
  1864. {
  1865. var processorStartIndex = bindingStates[bindingIndex].processorStartIndex;
  1866. for (var i = 0; i < processorCount; ++i)
  1867. value = processors[processorStartIndex + i].ProcessAsObject(value, control);
  1868. }
  1869. return value;
  1870. }
  1871. internal bool ReadValueAsButton(int bindingIndex, int controlIndex)
  1872. {
  1873. var buttonControl = default(ButtonControl);
  1874. if (!bindingStates[bindingIndex].isPartOfComposite)
  1875. buttonControl = controls[controlIndex] as ButtonControl;
  1876. // Read float value.
  1877. var floatValue = ReadValue<float>(bindingIndex, controlIndex);
  1878. // Compare to press point.
  1879. if (buttonControl != null)
  1880. return floatValue >= buttonControl.pressPointOrDefault;
  1881. return floatValue >= ButtonControl.s_GlobalDefaultButtonPressPoint;
  1882. }
  1883. /// <summary>
  1884. /// Records the current state of a single interaction attached to a binding.
  1885. /// Each interaction keeps track of its own trigger control and phase progression.
  1886. /// </summary>
  1887. [StructLayout(LayoutKind.Explicit, Size = 12)]
  1888. internal struct InteractionState
  1889. {
  1890. [FieldOffset(0)] private ushort m_TriggerControlIndex;
  1891. [FieldOffset(2)] private byte m_Phase;
  1892. [FieldOffset(3)] private byte m_Flags;
  1893. [FieldOffset(4)] private double m_StartTime;
  1894. public int triggerControlIndex
  1895. {
  1896. get => m_TriggerControlIndex;
  1897. set
  1898. {
  1899. Debug.Assert(value >= 0 && value <= ushort.MaxValue, "Trigger control index is out of range");
  1900. if (value < 0 || value > ushort.MaxValue)
  1901. throw new NotSupportedException("Cannot have more than ushort.MaxValue controls in a single InputActionState");
  1902. m_TriggerControlIndex = (ushort)value;
  1903. }
  1904. }
  1905. public double startTime
  1906. {
  1907. get => m_StartTime;
  1908. set => m_StartTime = value;
  1909. }
  1910. public bool isTimerRunning
  1911. {
  1912. get => ((Flags)m_Flags & Flags.TimerRunning) == Flags.TimerRunning;
  1913. set
  1914. {
  1915. if (value)
  1916. m_Flags |= (byte)Flags.TimerRunning;
  1917. else
  1918. {
  1919. var mask = ~Flags.TimerRunning;
  1920. m_Flags &= (byte)mask;
  1921. }
  1922. }
  1923. }
  1924. public InputActionPhase phase
  1925. {
  1926. get => (InputActionPhase)m_Phase;
  1927. set => m_Phase = (byte)value;
  1928. }
  1929. [Flags]
  1930. private enum Flags
  1931. {
  1932. TimerRunning = 1 << 0,
  1933. }
  1934. }
  1935. /// <summary>
  1936. /// Runtime state for a single binding.
  1937. /// </summary>
  1938. /// <remarks>
  1939. /// Correlated to the <see cref="InputBinding"/> it corresponds to by the index in the binding
  1940. /// array.
  1941. /// </remarks>
  1942. [StructLayout(LayoutKind.Explicit, Size = 20)]
  1943. internal struct BindingState
  1944. {
  1945. [FieldOffset(0)] private byte m_ControlCount;
  1946. [FieldOffset(1)] private byte m_InteractionCount;
  1947. [FieldOffset(2)] private byte m_ProcessorCount;
  1948. [FieldOffset(3)] private byte m_MapIndex;
  1949. [FieldOffset(4)] private byte m_Flags;
  1950. [FieldOffset(5)] private byte m_PartIndex;
  1951. [FieldOffset(6)] private ushort m_ActionIndex;
  1952. [FieldOffset(8)] private ushort m_CompositeOrCompositeBindingIndex;
  1953. [FieldOffset(10)] private ushort m_ProcessorStartIndex;
  1954. [FieldOffset(12)] private ushort m_InteractionStartIndex;
  1955. [FieldOffset(14)] private ushort m_ControlStartIndex;
  1956. [FieldOffset(16)] private int m_TriggerEventIdForComposite;
  1957. [Flags]
  1958. public enum Flags
  1959. {
  1960. ChainsWithNext = 1 << 0,
  1961. EndOfChain = 1 << 1,
  1962. Composite = 1 << 2,
  1963. PartOfComposite = 1 << 3,
  1964. InitialStateCheckPending = 1 << 4,
  1965. WantsInitialStateCheck = 1 << 5,
  1966. }
  1967. /// <summary>
  1968. /// Index into <see cref="controls"/> of first control associated with the binding.
  1969. /// </summary>
  1970. /// <remarks>
  1971. /// For composites, this is the index of the first control that is bound by any of the parts in the composite.
  1972. /// </remarks>
  1973. public int controlStartIndex
  1974. {
  1975. get => m_ControlStartIndex;
  1976. set
  1977. {
  1978. Debug.Assert(value != kInvalidIndex, "Control state index is invalid");
  1979. if (value >= ushort.MaxValue)
  1980. throw new NotSupportedException("Total control count in state cannot exceed byte.MaxValue=" + ushort.MaxValue);
  1981. m_ControlStartIndex = (ushort)value;
  1982. }
  1983. }
  1984. /// <summary>
  1985. /// Number of controls associated with this binding.
  1986. /// </summary>
  1987. /// <remarks>
  1988. /// For composites, this is the total number of controls bound by all parts of the composite combined.
  1989. /// </remarks>
  1990. public int controlCount
  1991. {
  1992. get => m_ControlCount;
  1993. set
  1994. {
  1995. if (value >= byte.MaxValue)
  1996. throw new NotSupportedException("Control count per binding cannot exceed byte.MaxValue=" + byte.MaxValue);
  1997. m_ControlCount = (byte)value;
  1998. }
  1999. }
  2000. /// <summary>
  2001. /// Index into <see cref="InputActionState.interactionStates"/> of first interaction associated with the binding.
  2002. /// </summary>
  2003. public int interactionStartIndex
  2004. {
  2005. get
  2006. {
  2007. if (m_InteractionStartIndex == ushort.MaxValue)
  2008. return kInvalidIndex;
  2009. return m_InteractionStartIndex;
  2010. }
  2011. set
  2012. {
  2013. if (value == kInvalidIndex)
  2014. m_InteractionStartIndex = ushort.MaxValue;
  2015. else
  2016. {
  2017. if (value >= ushort.MaxValue)
  2018. throw new NotSupportedException("Interaction count cannot exceed ushort.MaxValue=" + ushort.MaxValue);
  2019. m_InteractionStartIndex = (ushort)value;
  2020. }
  2021. }
  2022. }
  2023. /// <summary>
  2024. /// Number of interactions associated with this binding.
  2025. /// </summary>
  2026. public int interactionCount
  2027. {
  2028. get => m_InteractionCount;
  2029. set
  2030. {
  2031. if (value >= byte.MaxValue)
  2032. throw new NotSupportedException("Interaction count per binding cannot exceed byte.MaxValue=" + byte.MaxValue);
  2033. m_InteractionCount = (byte)value;
  2034. }
  2035. }
  2036. public int processorStartIndex
  2037. {
  2038. get
  2039. {
  2040. if (m_ProcessorStartIndex == ushort.MaxValue)
  2041. return kInvalidIndex;
  2042. return m_ProcessorStartIndex;
  2043. }
  2044. set
  2045. {
  2046. if (value == kInvalidIndex)
  2047. m_ProcessorStartIndex = ushort.MaxValue;
  2048. else
  2049. {
  2050. if (value >= ushort.MaxValue)
  2051. throw new NotSupportedException("Processor count cannot exceed ushort.MaxValue=" + ushort.MaxValue);
  2052. m_ProcessorStartIndex = (ushort)value;
  2053. }
  2054. }
  2055. }
  2056. public int processorCount
  2057. {
  2058. get => m_ProcessorCount;
  2059. set
  2060. {
  2061. if (value >= byte.MaxValue)
  2062. throw new NotSupportedException("Processor count per binding cannot exceed byte.MaxValue=" + byte.MaxValue);
  2063. m_ProcessorCount = (byte)value;
  2064. }
  2065. }
  2066. /// <summary>
  2067. /// Index of the action being triggered by the binding (if any).
  2068. /// </summary>
  2069. /// <remarks>
  2070. /// For bindings that don't trigger actions, this is <see cref="kInvalidIndex"/>.
  2071. ///
  2072. /// For bindings that are part of a composite, we force this to be the action set on the composite itself.
  2073. /// </remarks>
  2074. public int actionIndex
  2075. {
  2076. get
  2077. {
  2078. if (m_ActionIndex == ushort.MaxValue)
  2079. return kInvalidIndex;
  2080. return m_ActionIndex;
  2081. }
  2082. set
  2083. {
  2084. if (value == kInvalidIndex)
  2085. m_ActionIndex = ushort.MaxValue;
  2086. else
  2087. {
  2088. if (value >= ushort.MaxValue)
  2089. throw new NotSupportedException("Action count cannot exceed ushort.MaxValue=" + ushort.MaxValue);
  2090. m_ActionIndex = (ushort)value;
  2091. }
  2092. }
  2093. }
  2094. public int mapIndex
  2095. {
  2096. get => m_MapIndex;
  2097. set
  2098. {
  2099. Debug.Assert(value != kInvalidIndex, "Map index is invalid");
  2100. if (value >= byte.MaxValue)
  2101. throw new NotSupportedException("Map count cannot exceed byte.MaxValue=" + byte.MaxValue);
  2102. m_MapIndex = (byte)value;
  2103. }
  2104. }
  2105. /// <summary>
  2106. /// If this is a composite binding, this is the index of the composite in <see cref="composites"/>.
  2107. /// If the binding is part of a composite, this is the index of the binding that is the composite.
  2108. /// If the binding is neither a composite nor part of a composite, this is <see cref="kInvalidIndex"/>.
  2109. /// </summary>
  2110. public int compositeOrCompositeBindingIndex
  2111. {
  2112. get
  2113. {
  2114. if (m_CompositeOrCompositeBindingIndex == ushort.MaxValue)
  2115. return kInvalidIndex;
  2116. return m_CompositeOrCompositeBindingIndex;
  2117. }
  2118. set
  2119. {
  2120. if (value == kInvalidIndex)
  2121. m_CompositeOrCompositeBindingIndex = ushort.MaxValue;
  2122. else
  2123. {
  2124. if (value >= ushort.MaxValue)
  2125. throw new NotSupportedException("Composite count cannot exceed ushort.MaxValue=" + ushort.MaxValue);
  2126. m_CompositeOrCompositeBindingIndex = (ushort)value;
  2127. }
  2128. }
  2129. }
  2130. /// <summary>
  2131. /// <see cref="InputEvent.eventId">ID</see> of the event that last triggered the binding.
  2132. /// </summary>
  2133. /// <remarks>
  2134. /// We only store this for composites ATM.
  2135. /// </remarks>
  2136. public int triggerEventIdForComposite
  2137. {
  2138. get => m_TriggerEventIdForComposite;
  2139. set => m_TriggerEventIdForComposite = value;
  2140. }
  2141. public Flags flags
  2142. {
  2143. get => (Flags)m_Flags;
  2144. set => m_Flags = (byte)value;
  2145. }
  2146. public bool chainsWithNext
  2147. {
  2148. get => (flags & Flags.ChainsWithNext) == Flags.ChainsWithNext;
  2149. set
  2150. {
  2151. if (value)
  2152. flags |= Flags.ChainsWithNext;
  2153. else
  2154. flags &= ~Flags.ChainsWithNext;
  2155. }
  2156. }
  2157. public bool isEndOfChain
  2158. {
  2159. get => (flags & Flags.EndOfChain) == Flags.EndOfChain;
  2160. set
  2161. {
  2162. if (value)
  2163. flags |= Flags.EndOfChain;
  2164. else
  2165. flags &= ~Flags.EndOfChain;
  2166. }
  2167. }
  2168. public bool isPartOfChain => chainsWithNext || isEndOfChain;
  2169. public bool isComposite
  2170. {
  2171. get => (flags & Flags.Composite) == Flags.Composite;
  2172. set
  2173. {
  2174. if (value)
  2175. flags |= Flags.Composite;
  2176. else
  2177. flags &= ~Flags.Composite;
  2178. }
  2179. }
  2180. public bool isPartOfComposite
  2181. {
  2182. get => (flags & Flags.PartOfComposite) == Flags.PartOfComposite;
  2183. set
  2184. {
  2185. if (value)
  2186. flags |= Flags.PartOfComposite;
  2187. else
  2188. flags &= ~Flags.PartOfComposite;
  2189. }
  2190. }
  2191. public bool initialStateCheckPending
  2192. {
  2193. get => (flags & Flags.InitialStateCheckPending) != 0;
  2194. set
  2195. {
  2196. if (value)
  2197. flags |= Flags.InitialStateCheckPending;
  2198. else
  2199. flags &= ~Flags.InitialStateCheckPending;
  2200. }
  2201. }
  2202. public bool wantsInitialStateCheck
  2203. {
  2204. get => (flags & Flags.WantsInitialStateCheck) != 0;
  2205. set
  2206. {
  2207. if (value)
  2208. flags |= Flags.WantsInitialStateCheck;
  2209. else
  2210. flags &= ~Flags.WantsInitialStateCheck;
  2211. }
  2212. }
  2213. public int partIndex
  2214. {
  2215. get => m_PartIndex;
  2216. set
  2217. {
  2218. if (partIndex < 0)
  2219. throw new ArgumentOutOfRangeException(nameof(value), "Part index must not be negative");
  2220. if (partIndex > byte.MaxValue)
  2221. throw new InvalidOperationException("Part count must not exceed byte.MaxValue=" + byte.MaxValue);
  2222. m_PartIndex = (byte)value;
  2223. }
  2224. }
  2225. }
  2226. /// <summary>
  2227. /// Record of an input control change and its related data.
  2228. /// </summary>
  2229. /// <remarks>
  2230. /// This serves a dual purpose. One is, trigger states represent control actuations while we process them. The
  2231. /// other is to represent the current actuation state of an action as a whole. The latter is stored in <see cref="actionStates"/>
  2232. /// while the former is passed around as temporary instances on the stack.
  2233. /// </remarks>
  2234. [StructLayout(LayoutKind.Explicit, Size = 36)]
  2235. public struct TriggerState
  2236. {
  2237. [FieldOffset(0)] private byte m_Phase;
  2238. [FieldOffset(1)] private byte m_Flags;
  2239. [FieldOffset(2)] private byte m_MapIndex;
  2240. // One byte available here.
  2241. ////REVIEW: can we condense these to floats? would save us a whopping 8 bytes
  2242. [FieldOffset(4)] private double m_Time;
  2243. [FieldOffset(12)] private double m_StartTime;
  2244. [FieldOffset(20)] private ushort m_ControlIndex;
  2245. // Two bytes available here.
  2246. [FieldOffset(24)] private ushort m_BindingIndex;
  2247. [FieldOffset(26)] private ushort m_InteractionIndex;
  2248. [FieldOffset(28)] private float m_Magnitude;
  2249. [FieldOffset(32)] private uint m_LastTriggeredInUpdate;
  2250. /// <summary>
  2251. /// Phase being triggered by the control value change.
  2252. /// </summary>
  2253. public InputActionPhase phase
  2254. {
  2255. get => (InputActionPhase)m_Phase;
  2256. set => m_Phase = (byte)value;
  2257. }
  2258. public bool isDisabled => phase == InputActionPhase.Disabled;
  2259. public bool isWaiting => phase == InputActionPhase.Waiting;
  2260. public bool isStarted => phase == InputActionPhase.Started;
  2261. public bool isPerformed => phase == InputActionPhase.Performed;
  2262. public bool isCanceled => phase == InputActionPhase.Canceled;
  2263. /// <summary>
  2264. /// The time the binding got triggered.
  2265. /// </summary>
  2266. public double time
  2267. {
  2268. get => m_Time;
  2269. set => m_Time = value;
  2270. }
  2271. /// <summary>
  2272. /// The time when the binding moved into <see cref="InputActionPhase.Started"/>.
  2273. /// </summary>
  2274. public double startTime
  2275. {
  2276. get => m_StartTime;
  2277. set => m_StartTime = value;
  2278. }
  2279. /// <summary>
  2280. /// Amount of actuation on the control.
  2281. /// </summary>
  2282. /// <remarks>
  2283. /// This is only valid if <see cref="haveMagnitude"/> is true.
  2284. ///
  2285. /// Note that this may differ from the actuation stored for <see cref="controlIndex"/> in <see
  2286. /// cref="UnmanagedMemory.controlMagnitudes"/> if the binding is a composite.
  2287. /// </remarks>
  2288. public float magnitude
  2289. {
  2290. get => m_Magnitude;
  2291. set
  2292. {
  2293. flags |= Flags.HaveMagnitude;
  2294. m_Magnitude = value;
  2295. }
  2296. }
  2297. /// <summary>
  2298. /// Whether <see cref="magnitude"/> has been set.
  2299. /// </summary>
  2300. /// <remarks>
  2301. /// Magnitude computation is expensive so we only want to do it once. Also, we sometimes need to compare
  2302. /// a current magnitude to a magnitude value from a previous frame and the magnitude of the control
  2303. /// may have already changed.
  2304. /// </remarks>
  2305. public bool haveMagnitude => (flags & Flags.HaveMagnitude) != 0;
  2306. /// <summary>
  2307. /// Index of the action map in <see cref="maps"/> that contains the binding that triggered.
  2308. /// </summary>
  2309. public int mapIndex
  2310. {
  2311. get => m_MapIndex;
  2312. set
  2313. {
  2314. if (value < 0 || value > byte.MaxValue)
  2315. throw new NotSupportedException("More than byte.MaxValue InputActionMaps in a single InputActionState");
  2316. m_MapIndex = (byte)value;
  2317. }
  2318. }
  2319. /// <summary>
  2320. /// Index of the control currently driving the action or <see cref="kInvalidIndex"/> if none.
  2321. /// </summary>
  2322. public int controlIndex
  2323. {
  2324. get
  2325. {
  2326. if (m_ControlIndex == ushort.MaxValue)
  2327. return kInvalidIndex;
  2328. return m_ControlIndex;
  2329. }
  2330. set
  2331. {
  2332. if (value == kInvalidIndex)
  2333. m_ControlIndex = ushort.MaxValue;
  2334. else
  2335. {
  2336. if (value < 0 || value >= ushort.MaxValue)
  2337. throw new NotSupportedException("More than ushort.MaxValue-1 controls in a single InputActionState");
  2338. m_ControlIndex = (ushort)value;
  2339. }
  2340. }
  2341. }
  2342. /// <summary>
  2343. /// Index into <see cref="bindingStates"/> for the binding that triggered.
  2344. /// </summary>
  2345. /// <remarks>
  2346. /// This corresponds 1:1 to an <see cref="InputBinding"/>.
  2347. /// </remarks>
  2348. public int bindingIndex
  2349. {
  2350. get => m_BindingIndex;
  2351. set
  2352. {
  2353. if (value < 0 || value > ushort.MaxValue)
  2354. throw new NotSupportedException("More than ushort.MaxValue bindings in a single InputActionState");
  2355. m_BindingIndex = (ushort)value;
  2356. }
  2357. }
  2358. /// <summary>
  2359. /// Index into <see cref="InputActionState.interactionStates"/> for the interaction that triggered.
  2360. /// </summary>
  2361. /// <remarks>
  2362. /// Is <see cref="InputActionState.kInvalidIndex"/> if there is no interaction present on the binding.
  2363. /// </remarks>
  2364. public int interactionIndex
  2365. {
  2366. get
  2367. {
  2368. if (m_InteractionIndex == ushort.MaxValue)
  2369. return kInvalidIndex;
  2370. return m_InteractionIndex;
  2371. }
  2372. set
  2373. {
  2374. if (value == kInvalidIndex)
  2375. m_InteractionIndex = ushort.MaxValue;
  2376. else
  2377. {
  2378. if (value < 0 || value >= ushort.MaxValue)
  2379. throw new NotSupportedException("More than ushort.MaxValue-1 interactions in a single InputActionState");
  2380. m_InteractionIndex = (ushort)value;
  2381. }
  2382. }
  2383. }
  2384. /// <summary>
  2385. /// Update step count (<see cref="InputUpdate.s_UpdateStepCount"/>) in which action triggered/performed last.
  2386. /// Zero if the action did not trigger yet. Also reset to zero when the action is disabled.
  2387. /// </summary>
  2388. public uint lastTriggeredInUpdate
  2389. {
  2390. get => m_LastTriggeredInUpdate;
  2391. set => m_LastTriggeredInUpdate = value;
  2392. }
  2393. /// <summary>
  2394. /// Whether the action associated with the trigger state is marked as pass-through.
  2395. /// </summary>
  2396. /// <seealso cref="InputActionType.PassThrough"/>
  2397. public bool isPassThrough
  2398. {
  2399. get => (flags & Flags.PassThrough) != 0;
  2400. set
  2401. {
  2402. if (value)
  2403. flags |= Flags.PassThrough;
  2404. else
  2405. flags &= ~Flags.PassThrough;
  2406. }
  2407. }
  2408. /// <summary>
  2409. /// Whether the action may potentially see multiple concurrent actuations from its bindings
  2410. /// and wants them resolved automatically.
  2411. /// </summary>
  2412. /// <remarks>
  2413. /// We use this to gate some of the more expensive checks that are pointless to
  2414. /// perform if we don't have to disambiguate input from concurrent sources.
  2415. ///
  2416. /// Always disabled if <see cref="isPassThrough"/> is true.
  2417. /// </remarks>
  2418. public bool mayNeedConflictResolution
  2419. {
  2420. get => (flags & Flags.MayNeedConflictResolution) != 0;
  2421. set
  2422. {
  2423. if (value)
  2424. flags |= Flags.MayNeedConflictResolution;
  2425. else
  2426. flags &= ~Flags.MayNeedConflictResolution;
  2427. }
  2428. }
  2429. /// <summary>
  2430. /// Whether the action currently has several concurrent actuations from its bindings.
  2431. /// </summary>
  2432. /// <remarks>
  2433. /// This is only used when automatic conflict resolution is enabled (<see cref="mayNeedConflictResolution"/>).
  2434. /// </remarks>
  2435. public bool hasMultipleConcurrentActuations
  2436. {
  2437. get => (flags & Flags.HasMultipleConcurrentActuations) != 0;
  2438. set
  2439. {
  2440. if (value)
  2441. flags |= Flags.HasMultipleConcurrentActuations;
  2442. else
  2443. flags &= ~Flags.HasMultipleConcurrentActuations;
  2444. }
  2445. }
  2446. public Flags flags
  2447. {
  2448. get => (Flags)m_Flags;
  2449. set => m_Flags = (byte)value;
  2450. }
  2451. [Flags]
  2452. public enum Flags
  2453. {
  2454. /// <summary>
  2455. /// Whether <see cref="magnitude"/> has been set.
  2456. /// </summary>
  2457. HaveMagnitude = 1 << 0,
  2458. /// <summary>
  2459. /// Whether the action associated with the trigger state is marked as pass-through.
  2460. /// </summary>
  2461. /// <seealso cref="InputActionType.PassThrough"/>
  2462. PassThrough = 1 << 1,
  2463. /// <summary>
  2464. /// Whether the action has more than one control bound to it.
  2465. /// </summary>
  2466. /// <remarks>
  2467. /// An action may have arbitrary many bindings yet may still resolve only to a single control
  2468. /// at runtime. In that case, this flag is NOT set. We only set it if binding resolution for
  2469. /// an action indeed ended up with multiple controls able to trigger the same action.
  2470. /// </remarks>
  2471. MayNeedConflictResolution = 1 << 2,
  2472. /// <summary>
  2473. /// Whether there are currently multiple bound controls that are actuated.
  2474. /// </summary>
  2475. /// <remarks>
  2476. /// This is only used if <see cref="TriggerState.mayNeedConflictResolution"/> is true.
  2477. /// </remarks>
  2478. HasMultipleConcurrentActuations = 1 << 3,
  2479. }
  2480. }
  2481. /// <summary>
  2482. /// Tells us where the data for a single action map is found in the
  2483. /// various arrays.
  2484. /// </summary>
  2485. public struct ActionMapIndices
  2486. {
  2487. public int actionStartIndex;
  2488. public int actionCount;
  2489. public int controlStartIndex;
  2490. public int controlCount;
  2491. public int bindingStartIndex;
  2492. public int bindingCount;
  2493. public int interactionStartIndex;
  2494. public int interactionCount;
  2495. public int processorStartIndex;
  2496. public int processorCount;
  2497. public int compositeStartIndex;
  2498. public int compositeCount;
  2499. }
  2500. /// <summary>
  2501. /// Unmanaged memory kept for action maps.
  2502. /// </summary>
  2503. /// <remarks>
  2504. /// Most of the dynamic execution state for actions we keep in a single block of unmanaged memory.
  2505. /// Essentially, only the C# heap objects (like IInputInteraction and such) we keep in managed arrays.
  2506. /// Aside from being able to condense the data into a single block of memory and not having to have
  2507. /// it spread out on the GC heap, we gain the advantage of being able to freely allocate and re-allocate
  2508. /// these blocks without creating garbage on the GC heap.
  2509. ///
  2510. /// The data here is set up by <see cref="InputBindingResolver"/>.
  2511. /// </remarks>
  2512. public struct UnmanagedMemory : IDisposable
  2513. {
  2514. public bool isAllocated => basePtr != null;
  2515. public void* basePtr;
  2516. /// <summary>
  2517. /// Number of action maps and entries in <see cref="mapIndices"/> and <see cref="maps"/>.
  2518. /// </summary>
  2519. public int mapCount;
  2520. /// <summary>
  2521. /// Total number of actions (i.e. from all maps combined) and entries in <see cref="actionStates"/>.
  2522. /// </summary>
  2523. public int actionCount;
  2524. /// <summary>
  2525. /// Total number of interactions and entries in <see cref="interactionStates"/> and <see cref="interactions"/>.
  2526. /// </summary>
  2527. public int interactionCount;
  2528. /// <summary>
  2529. /// Total number of bindings and entries in <see cref="bindingStates"/>.
  2530. /// </summary>
  2531. public int bindingCount;
  2532. /// <summary>
  2533. /// Total number of bound controls and entries in <see cref="controls"/>.
  2534. /// </summary>
  2535. public int controlCount;
  2536. /// <summary>
  2537. /// Total number of composite bindings and entries in <see cref="composites"/>.
  2538. /// </summary>
  2539. public int compositeCount;
  2540. /// <summary>
  2541. /// Total size of allocated unmanaged memory.
  2542. /// </summary>
  2543. public int sizeInBytes =>
  2544. mapCount * sizeof(ActionMapIndices) + // mapIndices
  2545. actionCount * sizeof(TriggerState) + // actionStates
  2546. bindingCount * sizeof(BindingState) + // bindingStates
  2547. interactionCount * sizeof(InteractionState) + // interactionStates
  2548. controlCount * sizeof(float) + // controlMagnitudes
  2549. compositeCount * sizeof(float) + // compositeMagnitudes
  2550. controlCount * sizeof(int) + // controlIndexToBindingIndex
  2551. actionCount * sizeof(ushort) * 2 + // actionBindingIndicesAndCounts
  2552. bindingCount * sizeof(ushort) + // actionBindingIndices
  2553. (controlCount + 31) / 32 * sizeof(int); // enabledControlsArray
  2554. /// <summary>
  2555. /// Trigger state of all actions added to the state.
  2556. /// </summary>
  2557. /// <remarks>
  2558. /// This array also tells which actions are enabled or disabled. Any action with phase
  2559. /// <see cref="InputActionPhase.Disabled"/> is disabled.
  2560. /// </remarks>
  2561. public TriggerState* actionStates;
  2562. /// <summary>
  2563. /// State of all bindings added to the state.
  2564. /// </summary>
  2565. /// <remarks>
  2566. /// For the most part, this is read-only information set up during resolution.
  2567. /// </remarks>
  2568. public BindingState* bindingStates;
  2569. /// <summary>
  2570. /// State of all interactions on bindings in the action map.
  2571. /// </summary>
  2572. /// <remarks>
  2573. /// Any interaction mentioned on any of the bindings gets its own execution state record
  2574. /// in here. The interactions for any one binding are grouped together.
  2575. /// </remarks>
  2576. public InteractionState* interactionStates;
  2577. /// <summary>
  2578. ///
  2579. /// </summary>
  2580. /// <remarks>
  2581. /// This array is NOT kept strictly up to date. In fact, we only use it for conflict resolution
  2582. /// between multiple bound controls at the moment. Meaning that in the majority of cases, the magnitude
  2583. /// stored for a control here will NOT be up to date.
  2584. ///
  2585. /// Also note that for controls that are part of composites, this will NOT be the magnitude of the
  2586. /// control but rather be the magnitude of the entire compound.
  2587. /// </remarks>
  2588. public float* controlMagnitudes;
  2589. public float* compositeMagnitudes;
  2590. public int* enabledControls;
  2591. /// <summary>
  2592. /// Array of pair of ints, one pair for each action (same index as <see cref="actionStates"/>). First int
  2593. /// is count of bindings on action, second int is index into <see cref="actionBindingIndices"/> where
  2594. /// bindings of action are found.
  2595. /// </summary>
  2596. public ushort* actionBindingIndicesAndCounts;
  2597. /// <summary>
  2598. /// Array of indices into <see cref="bindingStates"/>. The indices for every action are laid out sequentially.
  2599. /// The array slice corresponding to each action can be determined by looking it up in <see cref="actionBindingIndicesAndCounts"/>.
  2600. /// </summary>
  2601. public ushort* actionBindingIndices;
  2602. ////REVIEW: make this an array of shorts rather than ints?
  2603. public int* controlIndexToBindingIndex;
  2604. public ActionMapIndices* mapIndices;
  2605. public void Allocate(int mapCount, int actionCount, int bindingCount, int controlCount, int interactionCount, int compositeCount)
  2606. {
  2607. Debug.Assert(basePtr == null, "Memory already allocated! Free first!");
  2608. Debug.Assert(mapCount >= 1, "Map count out of range");
  2609. Debug.Assert(actionCount >= 0, "Action count out of range");
  2610. Debug.Assert(bindingCount >= 0, "Binding count out of range");
  2611. Debug.Assert(interactionCount >= 0, "Interaction count out of range");
  2612. Debug.Assert(compositeCount >= 0, "Composite count out of range");
  2613. this.mapCount = mapCount;
  2614. this.actionCount = actionCount;
  2615. this.interactionCount = interactionCount;
  2616. this.bindingCount = bindingCount;
  2617. this.controlCount = controlCount;
  2618. this.compositeCount = compositeCount;
  2619. var ptr = (byte*)UnsafeUtility.Malloc(sizeInBytes, 4, Allocator.Persistent);
  2620. UnsafeUtility.MemClear(ptr, sizeInBytes);
  2621. basePtr = ptr;
  2622. // NOTE: This depends on the individual structs being sufficiently aligned in order to not
  2623. // cause any misalignment here.
  2624. mapIndices = (ActionMapIndices*)ptr; ptr += mapCount * sizeof(ActionMapIndices);
  2625. actionStates = (TriggerState*)ptr; ptr += actionCount * sizeof(TriggerState);
  2626. interactionStates = (InteractionState*)ptr; ptr += interactionCount * sizeof(InteractionState);
  2627. bindingStates = (BindingState*)ptr; ptr += bindingCount * sizeof(BindingState);
  2628. controlMagnitudes = (float*)ptr; ptr += controlCount * sizeof(float);
  2629. compositeMagnitudes = (float*)ptr; ptr += compositeCount * sizeof(float);
  2630. controlIndexToBindingIndex = (int*)ptr; ptr += controlCount * sizeof(int);
  2631. actionBindingIndicesAndCounts = (ushort*)ptr; ptr += actionCount * sizeof(ushort) * 2;
  2632. actionBindingIndices = (ushort*)ptr; ptr += bindingCount * sizeof(ushort);
  2633. enabledControls = (int*)ptr; ptr += (controlCount + 31) / 32 * sizeof(int);
  2634. }
  2635. public void Dispose()
  2636. {
  2637. if (basePtr == null)
  2638. return;
  2639. UnsafeUtility.Free(basePtr, Allocator.Persistent);
  2640. basePtr = null;
  2641. actionStates = null;
  2642. interactionStates = null;
  2643. bindingStates = null;
  2644. mapIndices = null;
  2645. controlMagnitudes = null;
  2646. compositeMagnitudes = null;
  2647. controlIndexToBindingIndex = null;
  2648. actionBindingIndices = null;
  2649. actionBindingIndicesAndCounts = null;
  2650. mapCount = 0;
  2651. actionCount = 0;
  2652. bindingCount = 0;
  2653. controlCount = 0;
  2654. interactionCount = 0;
  2655. compositeCount = 0;
  2656. }
  2657. public void CopyDataFrom(UnmanagedMemory memory)
  2658. {
  2659. Debug.Assert(memory.basePtr != null, "Given struct has no allocated data");
  2660. // Even if a certain array is empty (e.g. we have no controls), we set the pointer
  2661. // in Allocate() to something other than null.
  2662. UnsafeUtility.MemCpy(mapIndices, memory.mapIndices, memory.mapCount * sizeof(ActionMapIndices));
  2663. UnsafeUtility.MemCpy(actionStates, memory.actionStates, memory.actionCount * sizeof(TriggerState));
  2664. UnsafeUtility.MemCpy(bindingStates, memory.bindingStates, memory.bindingCount * sizeof(BindingState));
  2665. UnsafeUtility.MemCpy(interactionStates, memory.interactionStates, memory.interactionCount * sizeof(InteractionState));
  2666. UnsafeUtility.MemCpy(controlMagnitudes, memory.controlMagnitudes, memory.controlCount * sizeof(float));
  2667. UnsafeUtility.MemCpy(compositeMagnitudes, memory.compositeMagnitudes, memory.compositeCount * sizeof(float));
  2668. UnsafeUtility.MemCpy(controlIndexToBindingIndex, memory.controlIndexToBindingIndex, memory.controlCount * sizeof(int));
  2669. UnsafeUtility.MemCpy(actionBindingIndicesAndCounts, memory.actionBindingIndicesAndCounts, memory.actionCount * sizeof(ushort) * 2);
  2670. UnsafeUtility.MemCpy(actionBindingIndices, memory.actionBindingIndices, memory.bindingCount * sizeof(ushort));
  2671. UnsafeUtility.MemCpy(enabledControls, memory.enabledControls, (memory.controlCount + 31) / 32 * sizeof(int));
  2672. }
  2673. public UnmanagedMemory Clone()
  2674. {
  2675. if (!isAllocated)
  2676. return new UnmanagedMemory();
  2677. var clone = new UnmanagedMemory();
  2678. clone.Allocate(
  2679. mapCount: mapCount,
  2680. actionCount: actionCount,
  2681. controlCount: controlCount,
  2682. bindingCount: bindingCount,
  2683. interactionCount: interactionCount,
  2684. compositeCount: compositeCount);
  2685. clone.CopyDataFrom(this);
  2686. return clone;
  2687. }
  2688. }
  2689. #region Global State
  2690. /// <summary>
  2691. /// List of weak references to all action map states currently in the system.
  2692. /// </summary>
  2693. /// <remarks>
  2694. /// When the control setup in the system changes, we need a way for control resolution that
  2695. /// has already been done to be invalidated and redone. We also want a way to find all
  2696. /// currently enabled actions in the system.
  2697. ///
  2698. /// Both of these needs are served by this global list.
  2699. /// </remarks>
  2700. internal static InlinedArray<GCHandle> s_GlobalList;
  2701. internal static InlinedArray<Action<object, InputActionChange>> s_OnActionChange;
  2702. internal static InlinedArray<Action<object>> s_OnActionControlsChanged;
  2703. private void AddToGlobaList()
  2704. {
  2705. CompactGlobalList();
  2706. var handle = GCHandle.Alloc(this, GCHandleType.Weak);
  2707. s_GlobalList.AppendWithCapacity(handle);
  2708. }
  2709. private void RemoveMapFromGlobalList()
  2710. {
  2711. var count = s_GlobalList.length;
  2712. for (var i = 0; i < count; ++i)
  2713. if (s_GlobalList[i].Target == this)
  2714. {
  2715. s_GlobalList[i].Free();
  2716. s_GlobalList.RemoveAtByMovingTailWithCapacity(i);
  2717. break;
  2718. }
  2719. }
  2720. /// <summary>
  2721. /// Remove any entries for states that have been reclaimed by GC.
  2722. /// </summary>
  2723. private static void CompactGlobalList()
  2724. {
  2725. var length = s_GlobalList.length;
  2726. var head = 0;
  2727. for (var i = 0; i < length; ++i)
  2728. {
  2729. var handle = s_GlobalList[i];
  2730. if (handle.IsAllocated && handle.Target != null)
  2731. {
  2732. if (head != i)
  2733. s_GlobalList[head] = handle;
  2734. ++head;
  2735. }
  2736. else
  2737. {
  2738. if (handle.IsAllocated)
  2739. s_GlobalList[i].Free();
  2740. s_GlobalList[i] = default;
  2741. }
  2742. }
  2743. s_GlobalList.length = head;
  2744. }
  2745. internal static void NotifyListenersOfActionChange(InputActionChange change, object actionOrMapOrAsset)
  2746. {
  2747. Debug.Assert(actionOrMapOrAsset != null, "Should have action or action map or asset object to notify about");
  2748. Debug.Assert(actionOrMapOrAsset is InputAction || (actionOrMapOrAsset as InputActionMap)?.m_SingletonAction == null,
  2749. "Must not send notifications for changes made to hidden action maps of singleton actions");
  2750. DelegateHelpers.InvokeCallbacksSafe(ref s_OnActionChange, actionOrMapOrAsset, change, "onActionChange");
  2751. if (change == InputActionChange.BoundControlsChanged)
  2752. DelegateHelpers.InvokeCallbacksSafe(ref s_OnActionControlsChanged, actionOrMapOrAsset, "onActionControlsChange");
  2753. }
  2754. /// <summary>
  2755. /// Nuke global state we have to keep track of action map states.
  2756. /// </summary>
  2757. internal static void ResetGlobals()
  2758. {
  2759. DestroyAllActionMapStates();
  2760. for (var i = 0; i < s_GlobalList.length; ++i)
  2761. if (s_GlobalList[i].IsAllocated)
  2762. s_GlobalList[i].Free();
  2763. s_GlobalList.length = 0;
  2764. s_OnActionChange.Clear();
  2765. s_OnActionControlsChanged.Clear();
  2766. }
  2767. // Walk all maps with enabled actions and add all enabled actions to the given list.
  2768. internal static int FindAllEnabledActions(List<InputAction> result)
  2769. {
  2770. var numFound = 0;
  2771. var stateCount = s_GlobalList.length;
  2772. for (var i = 0; i < stateCount; ++i)
  2773. {
  2774. var handle = s_GlobalList[i];
  2775. if (!handle.IsAllocated)
  2776. continue;
  2777. var state = (InputActionState)handle.Target;
  2778. if (state == null)
  2779. continue;
  2780. var mapCount = state.totalMapCount;
  2781. var maps = state.maps;
  2782. for (var n = 0; n < mapCount; ++n)
  2783. {
  2784. var map = maps[n];
  2785. if (!map.enabled)
  2786. continue;
  2787. var actions = map.m_Actions;
  2788. var actionCount = actions.Length;
  2789. if (map.m_EnabledActionsCount == actionCount)
  2790. {
  2791. result.AddRange(actions);
  2792. numFound += actionCount;
  2793. }
  2794. else
  2795. {
  2796. var actionStartIndex = state.mapIndices[map.m_MapIndexInState].actionStartIndex;
  2797. for (var k = 0; k < actionCount; ++k)
  2798. {
  2799. if (state.actionStates[actionStartIndex + k].phase != InputActionPhase.Disabled)
  2800. {
  2801. result.Add(actions[k]);
  2802. ++numFound;
  2803. }
  2804. }
  2805. }
  2806. }
  2807. }
  2808. return numFound;
  2809. }
  2810. ////TODO: when re-resolving, we need to preserve InteractionStates and not just reset them
  2811. /// <summary>
  2812. /// Deal with the fact that the control setup in the system may change at any time and can affect
  2813. /// actions that had their controls already resolved.
  2814. /// </summary>
  2815. /// <remarks>
  2816. /// Note that this method can NOT deal with changes other than the control setup in the system
  2817. /// changing. Specifically, it will NOT handle configuration changes in action maps (e.g. bindings
  2818. /// being altered) correctly.
  2819. ///
  2820. /// We get called from <see cref="InputManager"/> directly rather than hooking into <see cref="InputSystem.onDeviceChange"/>
  2821. /// so that we're not adding needless calls for device changes that are not of interest to us.
  2822. /// </remarks>
  2823. internal static void OnDeviceChange(InputDevice device, InputDeviceChange change)
  2824. {
  2825. Debug.Assert(device != null, "Device is null");
  2826. ////REVIEW: should we ignore disconnected devices in InputBindingResolver?
  2827. Debug.Assert(
  2828. change == InputDeviceChange.Added || change == InputDeviceChange.Removed ||
  2829. change == InputDeviceChange.UsageChanged || change == InputDeviceChange.ConfigurationChanged,
  2830. "Should only be called for relevant changes");
  2831. for (var i = 0; i < s_GlobalList.length; ++i)
  2832. {
  2833. var handle = s_GlobalList[i];
  2834. if (!handle.IsAllocated || handle.Target == null)
  2835. {
  2836. // Stale entry in the list. State has already been reclaimed by GC. Remove it.
  2837. if (handle.IsAllocated)
  2838. s_GlobalList[i].Free();
  2839. s_GlobalList.RemoveAtWithCapacity(i);
  2840. --i;
  2841. continue;
  2842. }
  2843. var state = (InputActionState)handle.Target;
  2844. // If this state is not affected by the change, skip.
  2845. if (change == InputDeviceChange.Added && !state.CanUseDevice(device))
  2846. continue;
  2847. if (change == InputDeviceChange.Removed && !state.IsUsingDevice(device))
  2848. continue;
  2849. if (change == InputDeviceChange.UsageChanged && !state.IsUsingDevice(device) && !state.CanUseDevice(device))
  2850. continue;
  2851. if (change == InputDeviceChange.ConfigurationChanged && !state.IsUsingDevice(device))
  2852. continue;
  2853. // Trigger a lazy-resolve on all action maps in the state.
  2854. for (var n = 0; n < state.totalMapCount; ++n)
  2855. if (state.maps[n].LazyResolveBindings())
  2856. {
  2857. // Map has chosen to resolve right away. This will resolve bindings for *all*
  2858. // maps in the state, so we're done here.
  2859. break;
  2860. }
  2861. }
  2862. }
  2863. internal static void DeferredResolutionOfBindings()
  2864. {
  2865. for (var i = 0; i < s_GlobalList.length; ++i)
  2866. {
  2867. var handle = s_GlobalList[i];
  2868. if (!handle.IsAllocated || handle.Target == null)
  2869. {
  2870. // Stale entry in the list. State has already been reclaimed by GC. Remove it.
  2871. if (handle.IsAllocated)
  2872. s_GlobalList[i].Free();
  2873. s_GlobalList.RemoveAtWithCapacity(i);
  2874. --i;
  2875. continue;
  2876. }
  2877. var state = (InputActionState)handle.Target;
  2878. for (var n = 0; n < state.totalMapCount; ++n)
  2879. state.maps[n].ResolveBindingsIfNecessary();
  2880. }
  2881. }
  2882. internal static void DisableAllActions()
  2883. {
  2884. for (var i = 0; i < s_GlobalList.length; ++i)
  2885. {
  2886. var handle = s_GlobalList[i];
  2887. if (!handle.IsAllocated || handle.Target == null)
  2888. continue;
  2889. var state = (InputActionState)handle.Target;
  2890. var mapCount = state.totalMapCount;
  2891. var maps = state.maps;
  2892. for (var n = 0; n < mapCount; ++n)
  2893. {
  2894. maps[n].Disable();
  2895. Debug.Assert(!maps[n].enabled, "Map is still enabled after calling Disable");
  2896. }
  2897. }
  2898. }
  2899. /// <summary>
  2900. /// Forcibly destroy all states currently on the global list.
  2901. /// </summary>
  2902. /// <remarks>
  2903. /// We do this when exiting play mode in the editor to make sure we are cleaning up our
  2904. /// unmanaged memory allocations.
  2905. /// </remarks>
  2906. internal static void DestroyAllActionMapStates()
  2907. {
  2908. while (s_GlobalList.length > 0)
  2909. {
  2910. var index = s_GlobalList.length - 1;
  2911. var handle = s_GlobalList[index];
  2912. if (!handle.IsAllocated || handle.Target == null)
  2913. {
  2914. // Already destroyed.
  2915. if (handle.IsAllocated)
  2916. s_GlobalList[index].Free();
  2917. s_GlobalList.RemoveAtWithCapacity(index);
  2918. continue;
  2919. }
  2920. var state = (InputActionState)handle.Target;
  2921. state.Destroy();
  2922. }
  2923. }
  2924. #endregion
  2925. }
  2926. }