Sin descripción
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

InputActionState.cs 216KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548
  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 ushort* controlGroupingAndComplexity => memory.controlGroupingAndComplexity;
  98. public float* controlMagnitudes => memory.controlMagnitudes;
  99. public uint* enabledControls => (uint*)memory.enabledControls;
  100. public bool isProcessingControlStateChange => m_InProcessControlStateChange;
  101. private bool m_OnBeforeUpdateHooked;
  102. private bool m_OnAfterUpdateHooked;
  103. private bool m_InProcessControlStateChange;
  104. private InputEventPtr m_CurrentlyProcessingThisEvent;
  105. private Action m_OnBeforeUpdateDelegate;
  106. private Action m_OnAfterUpdateDelegate;
  107. /// <summary>
  108. /// Initialize execution state with given resolved binding information.
  109. /// </summary>
  110. /// <param name="resolver"></param>
  111. public void Initialize(InputBindingResolver resolver)
  112. {
  113. ClaimDataFrom(resolver);
  114. AddToGlobalList();
  115. }
  116. private void ComputeControlGroupingIfNecessary()
  117. {
  118. if (memory.controlGroupingInitialized)
  119. return;
  120. // If shortcut support is disabled, we simply put put all bindings at complexity=1 and
  121. // in their own group.
  122. var disableControlGrouping = !InputSystem.settings.shortcutKeysConsumeInput;
  123. var currentGroup = 1u;
  124. for (var i = 0; i < totalControlCount; ++i)
  125. {
  126. var control = controls[i];
  127. var bindingIndex = controlIndexToBindingIndex[i];
  128. ref var binding = ref bindingStates[bindingIndex];
  129. ////REVIEW: take processors and interactions into account??
  130. // Compute complexity.
  131. var complexity = 1;
  132. if (binding.isPartOfComposite && !disableControlGrouping)
  133. {
  134. var compositeBindingIndex = binding.compositeOrCompositeBindingIndex;
  135. for (var n = compositeBindingIndex + 1; n < totalBindingCount; ++n)
  136. {
  137. ref var partBinding = ref bindingStates[n];
  138. if (!partBinding.isPartOfComposite || partBinding.compositeOrCompositeBindingIndex != compositeBindingIndex)
  139. break;
  140. ++complexity;
  141. }
  142. }
  143. controlGroupingAndComplexity[i * 2 + 1] = (ushort)complexity;
  144. // Compute grouping. If already set, skip.
  145. if (controlGroupingAndComplexity[i * 2] == 0)
  146. {
  147. if (!disableControlGrouping)
  148. {
  149. for (var n = 0; n < totalControlCount; ++n)
  150. {
  151. // NOTE: We could compute group numbers based on device index + control offsets
  152. // and thus make them work globally in a stable way. But we'd need a mechanism
  153. // to then determine ordering of actions globally such that it is clear which
  154. // action gets a first shot at an input.
  155. var otherControl = controls[n];
  156. if (control != otherControl)
  157. continue;
  158. controlGroupingAndComplexity[n * 2] = (ushort)currentGroup;
  159. }
  160. }
  161. controlGroupingAndComplexity[i * 2] = (ushort)currentGroup;
  162. ++currentGroup;
  163. }
  164. }
  165. memory.controlGroupingInitialized = true;
  166. }
  167. public void ClaimDataFrom(InputBindingResolver resolver)
  168. {
  169. totalProcessorCount = resolver.totalProcessorCount;
  170. maps = resolver.maps;
  171. interactions = resolver.interactions;
  172. processors = resolver.processors;
  173. composites = resolver.composites;
  174. controls = resolver.controls;
  175. memory = resolver.memory;
  176. resolver.memory = new UnmanagedMemory();
  177. ComputeControlGroupingIfNecessary();
  178. }
  179. ~InputActionState()
  180. {
  181. Destroy(isFinalizing: true);
  182. }
  183. public void Dispose()
  184. {
  185. Destroy();
  186. }
  187. private void Destroy(bool isFinalizing = false)
  188. {
  189. Debug.Assert(!isProcessingControlStateChange, "Must not destroy InputActionState while executing an action callback within it");
  190. if (!isFinalizing)
  191. {
  192. for (var i = 0; i < totalMapCount; ++i)
  193. {
  194. var map = maps[i];
  195. // Remove state change monitors.
  196. if (map.enabled)
  197. DisableControls(i, mapIndices[i].controlStartIndex, mapIndices[i].controlCount);
  198. if (map.m_Asset != null)
  199. map.m_Asset.m_SharedStateForAllMaps = null;
  200. map.m_State = null;
  201. map.m_MapIndexInState = kInvalidIndex;
  202. map.m_EnabledActionsCount = 0;
  203. // Reset action indices on the map's actions.
  204. var actions = map.m_Actions;
  205. if (actions != null)
  206. {
  207. for (var n = 0; n < actions.Length; ++n)
  208. actions[n].m_ActionIndexInState = kInvalidIndex;
  209. }
  210. }
  211. RemoveMapFromGlobalList();
  212. }
  213. memory.Dispose();
  214. }
  215. /// <summary>
  216. /// Create a copy of the state.
  217. /// </summary>
  218. /// <returns></returns>
  219. /// <remarks>
  220. /// The copy is non-functional in so far as it cannot be used to keep track of changes made to
  221. /// any associated actions. However, it can be used to freeze the binding resolution state of
  222. /// a particular set of enabled actions. This is used by <see cref="InputActionTrace"/>.
  223. /// </remarks>
  224. public InputActionState Clone()
  225. {
  226. return new InputActionState
  227. {
  228. maps = ArrayHelpers.Copy(maps),
  229. controls = ArrayHelpers.Copy(controls),
  230. interactions = ArrayHelpers.Copy(interactions),
  231. processors = ArrayHelpers.Copy(processors),
  232. composites = ArrayHelpers.Copy(composites),
  233. totalProcessorCount = totalProcessorCount,
  234. memory = memory.Clone(),
  235. };
  236. }
  237. object ICloneable.Clone()
  238. {
  239. return Clone();
  240. }
  241. /// <summary>
  242. /// Check if the state is currently using a control from the given device.
  243. /// </summary>
  244. /// <param name="device">Any input device.</param>
  245. /// <returns>True if any of the maps in the state has the device in its <see cref="InputActionMap.devices"/>
  246. /// list or if any of the device's controls are contained in <see cref="controls"/>.</returns>
  247. private bool IsUsingDevice(InputDevice device)
  248. {
  249. Debug.Assert(device != null, "Device is null");
  250. // If all maps have device restrictions, the device must be in it
  251. // or we're not using it.
  252. var haveMapsWithoutDeviceRestrictions = false;
  253. for (var i = 0; i < totalMapCount; ++i)
  254. {
  255. var map = maps[i];
  256. var devicesForMap = map.devices;
  257. if (devicesForMap == null)
  258. haveMapsWithoutDeviceRestrictions = true;
  259. else if (devicesForMap.Value.Contains(device))
  260. return true;
  261. }
  262. if (!haveMapsWithoutDeviceRestrictions)
  263. return false;
  264. // Check all our controls one by one.
  265. for (var i = 0; i < totalControlCount; ++i)
  266. if (controls[i].device == device)
  267. return true;
  268. return false;
  269. }
  270. // Check if the state would use a control from the given device.
  271. private bool CanUseDevice(InputDevice device)
  272. {
  273. Debug.Assert(device != null, "Device is null");
  274. // If all maps have device restrictions and the device isn't in them, we can't use
  275. // the device.
  276. var haveMapWithoutDeviceRestrictions = false;
  277. for (var i = 0; i < totalMapCount; ++i)
  278. {
  279. var map = maps[i];
  280. var devicesForMap = map.devices;
  281. if (devicesForMap == null)
  282. haveMapWithoutDeviceRestrictions = true;
  283. else if (devicesForMap.Value.Contains(device))
  284. return true;
  285. }
  286. if (!haveMapWithoutDeviceRestrictions)
  287. return false;
  288. for (var i = 0; i < totalMapCount; ++i)
  289. {
  290. var map = maps[i];
  291. var bindings = map.m_Bindings;
  292. if (bindings == null)
  293. continue;
  294. var bindingCount = bindings.Length;
  295. for (var n = 0; n < bindingCount; ++n)
  296. {
  297. if (InputControlPath.TryFindControl(device, bindings[n].effectivePath) != null)
  298. return true;
  299. }
  300. }
  301. return false;
  302. }
  303. /// <summary>
  304. /// Check whether the state has any actions that are currently enabled.
  305. /// </summary>
  306. /// <returns></returns>
  307. public bool HasEnabledActions()
  308. {
  309. for (var i = 0; i < totalMapCount; ++i)
  310. {
  311. var map = maps[i];
  312. if (map.enabled)
  313. return true;
  314. }
  315. return false;
  316. }
  317. private void FinishBindingCompositeSetups()
  318. {
  319. for (var i = 0; i < totalBindingCount; ++i)
  320. {
  321. ref var binding = ref bindingStates[i];
  322. if (!binding.isComposite || binding.compositeOrCompositeBindingIndex == -1)
  323. continue;
  324. var composite = composites[binding.compositeOrCompositeBindingIndex];
  325. var context = new InputBindingCompositeContext { m_State = this, m_BindingIndex = i };
  326. composite.CallFinishSetup(ref context);
  327. }
  328. }
  329. internal void PrepareForBindingReResolution(bool needFullResolve,
  330. ref InputControlList<InputControl> activeControls, ref bool hasEnabledActions)
  331. {
  332. // Let listeners know we're about to modify bindings.
  333. var needToCloneActiveControls = false;
  334. for (var i = 0; i < totalMapCount; ++i)
  335. {
  336. var map = maps[i];
  337. if (map.enabled)
  338. {
  339. hasEnabledActions = true;
  340. if (needFullResolve)
  341. {
  342. // For a full-resolve, we temporarily disable all actions and then re-enable
  343. // all that were enabled after bindings have been resolved (plus we also flip on
  344. // initial state checks for those actions to make sure they react right away
  345. // to whatever state controls are in).
  346. DisableAllActions(map);
  347. }
  348. else
  349. {
  350. // Cancel any action that is driven from a control we will lose when we re-resolve.
  351. // For any other on-going action, save active controls.
  352. foreach (var action in map.actions)
  353. {
  354. if (!action.phase.IsInProgress())
  355. continue;
  356. // Skip action's that are in progress but whose active control is not affected
  357. // by the changes that lead to re-resolution.
  358. if (action.ActiveControlIsValid(action.activeControl))
  359. {
  360. // As part of re-resolving, we're losing m_State.controls. So, while we retain
  361. // the current execution state of the method including the index of the currently
  362. // active control, we lose the actual references to the control.
  363. // Thus, we retain an explicit list of active controls into which we *only* copy
  364. // those few controls that are currently active. Also, this list is kept in unmanaged
  365. // memory so we don't add an additional GC allocation here.
  366. if (needToCloneActiveControls == false)
  367. {
  368. activeControls = new InputControlList<InputControl>(Allocator.Temp);
  369. activeControls.Resize(totalControlCount);
  370. needToCloneActiveControls = true;
  371. }
  372. ref var actionState = ref actionStates[action.m_ActionIndexInState];
  373. var activeControlIndex = actionState.controlIndex;
  374. activeControls[activeControlIndex] = controls[activeControlIndex];
  375. // Also save active controls for other ongoing interactions.
  376. var bindingState = bindingStates[actionState.bindingIndex];
  377. for (var n = 0; n < bindingState.interactionCount; ++n)
  378. {
  379. var interactionIndex = bindingState.interactionStartIndex + n;
  380. if (!interactionStates[interactionIndex].phase.IsInProgress())
  381. continue;
  382. activeControlIndex = interactionStates[interactionIndex]
  383. .triggerControlIndex;
  384. if (action.ActiveControlIsValid(controls[activeControlIndex]))
  385. activeControls[activeControlIndex] = controls[activeControlIndex];
  386. else
  387. ResetInteractionState(interactionIndex);
  388. }
  389. }
  390. else
  391. {
  392. ResetActionState(action.m_ActionIndexInState);
  393. }
  394. }
  395. // NOTE: Removing state monitors here also means we're terminating any pending
  396. // timeouts. However, we have information in the action state about how much
  397. // is time is remaining on each of them so we can resume them later.
  398. DisableControls(map);
  399. }
  400. }
  401. map.ClearCachedActionData(onlyControls: !needFullResolve);
  402. }
  403. NotifyListenersOfActionChange(InputActionChange.BoundControlsAboutToChange);
  404. }
  405. public void FinishBindingResolution(bool hasEnabledActions, UnmanagedMemory oldMemory, InputControlList<InputControl> activeControls, bool isFullResolve)
  406. {
  407. // Fire InputBindingComposite.FinishSetup() calls.
  408. FinishBindingCompositeSetups();
  409. // Sync action states between the old and the new state. This also ensures
  410. // that any action that was already in progress just keeps going -- except
  411. // if we actually lost the control that was driving it.
  412. if (hasEnabledActions)
  413. RestoreActionStatesAfterReResolvingBindings(oldMemory, activeControls, isFullResolve);
  414. else
  415. NotifyListenersOfActionChange(InputActionChange.BoundControlsChanged);
  416. }
  417. /// <summary>
  418. /// Synchronize the current action states based on what they were before.
  419. /// </summary>
  420. /// <param name="oldState"></param>
  421. /// <remarks>
  422. /// We do this when we have to temporarily disable actions in order to re-resolve bindings.
  423. ///
  424. /// Note that we do NOT restore action states perfectly. I.e. will we will not preserve trigger
  425. /// and interaction states exactly to what they were before. Given that the bound controls may change,
  426. /// it would be non-trivial to reliably correlate the old and the new state. Instead, we simply
  427. /// reenable all the actions and controls that were enabled before and then let the next update
  428. /// take it from there.
  429. /// </remarks>
  430. private void RestoreActionStatesAfterReResolvingBindings(UnmanagedMemory oldState, InputControlList<InputControl> activeControls, bool isFullResolve)
  431. {
  432. Debug.Assert(oldState.isAllocated, "Old state contains no memory");
  433. // No maps and/or actions must have been added, replaced, or removed.
  434. //
  435. // IF
  436. // isFullResolve==true:
  437. // - No bindings must have been added, replaced, or removed or touched in any other way.
  438. // - The only thing that is allowed to have changed is the list of controls used by the actions.
  439. // - Binding masks must not have changed.
  440. //
  441. // isFullResolve==false:
  442. // - Bindings may have been added, replaced, modified, and/or removed.
  443. // - Also, the list of controls may have changed.
  444. // - Binding masks may have changed.
  445. //
  446. // This means that when we compare UnmanagedMemory from before and after:
  447. // - Map indices are identical.
  448. // - Action indices are identical.
  449. // - Binding indices may have changed arbitrarily.
  450. // - Control indices may have changed arbitrarily (controls[] before and after need not relate at all).
  451. // - Processor indices may have changed arbitrarily.
  452. // - Interaction indices may have changed arbitrarily.
  453. //
  454. // HOWEVER, if isFullResolve==false, then ONLY control indices may have changed. All other
  455. // indices must have remained unchanged.
  456. Debug.Assert(oldState.actionCount == memory.actionCount, "Action count in old and new state must be the same");
  457. Debug.Assert(oldState.mapCount == memory.mapCount, "Map count in old and new state must be the same");
  458. if (!isFullResolve)
  459. {
  460. Debug.Assert(oldState.bindingCount == memory.bindingCount, "Binding count in old and new state must be the same");
  461. Debug.Assert(oldState.interactionCount == memory.interactionCount, "Interaction count in old and new state must be the same");
  462. Debug.Assert(oldState.compositeCount == memory.compositeCount, "Composite count in old and new state must be the same");
  463. }
  464. // Restore action states.
  465. for (var actionIndex = 0; actionIndex < totalActionCount; ++actionIndex)
  466. {
  467. ref var oldActionState = ref oldState.actionStates[actionIndex];
  468. ref var newActionState = ref actionStates[actionIndex];
  469. newActionState.lastCanceledInUpdate = oldActionState.lastCanceledInUpdate;
  470. newActionState.lastPerformedInUpdate = oldActionState.lastPerformedInUpdate;
  471. newActionState.lastCompletedInUpdate = oldActionState.lastCompletedInUpdate;
  472. newActionState.pressedInUpdate = oldActionState.pressedInUpdate;
  473. newActionState.releasedInUpdate = oldActionState.releasedInUpdate;
  474. newActionState.startTime = oldActionState.startTime;
  475. newActionState.bindingIndex = oldActionState.bindingIndex;
  476. if (oldActionState.phase != InputActionPhase.Disabled)
  477. {
  478. // In this step, we only put enabled actions into Waiting phase.
  479. // When isFullResolve==false, we will restore the actual phase from
  480. // before when we look at bindings further down in the code.
  481. newActionState.phase = InputActionPhase.Waiting;
  482. // In a full resolve, we actually disable any action we find enabled.
  483. // So count any action we reenable here.
  484. if (isFullResolve)
  485. ++maps[newActionState.mapIndex].m_EnabledActionsCount;
  486. }
  487. }
  488. // Restore binding (and interaction) states.
  489. for (var bindingIndex = 0; bindingIndex < totalBindingCount; ++bindingIndex)
  490. {
  491. ref var newBindingState = ref memory.bindingStates[bindingIndex];
  492. if (newBindingState.isPartOfComposite)
  493. {
  494. // Bindings that are part of composites get enabled through the composite itself.
  495. continue;
  496. }
  497. // For composites, bring magnitudes along.
  498. if (newBindingState.isComposite)
  499. {
  500. var compositeIndex = newBindingState.compositeOrCompositeBindingIndex;
  501. memory.compositeMagnitudes[compositeIndex] = oldState.compositeMagnitudes[compositeIndex];
  502. }
  503. var actionIndex = newBindingState.actionIndex;
  504. if (actionIndex == kInvalidIndex)
  505. {
  506. // Binding is not targeting an action.
  507. continue;
  508. }
  509. // Skip if action is disabled.
  510. ref var newActionState = ref actionStates[actionIndex];
  511. if (newActionState.isDisabled)
  512. continue;
  513. // For all bindings to actions that are enabled, we flip on initial state checks to make sure
  514. // we're checking the action's current state against the most up-to-date actuation state of controls.
  515. // NOTE: We're only restore execution state for currently active controls. So, if there were multiple
  516. // concurrent actuations on an action that was in progress, we let initial state checks restore
  517. // relevant state.
  518. newBindingState.initialStateCheckPending = newBindingState.wantsInitialStateCheck;
  519. // Enable all controls on the binding.
  520. EnableControls(newBindingState.mapIndex, newBindingState.controlStartIndex,
  521. newBindingState.controlCount);
  522. // For the remainder of what we do, we need binding indices to be stable.
  523. if (isFullResolve)
  524. continue;
  525. ref var oldBindingState = ref memory.bindingStates[bindingIndex];
  526. newBindingState.triggerEventIdForComposite = oldBindingState.triggerEventIdForComposite;
  527. // If we only re-resolved controls and the action was in progress from the binding we're currently
  528. // looking at and we still have the control that was driving the action, we can simply keep the
  529. // action going from its previous state. However, control indices may have shifted (devices may have been added
  530. // or removed) so we need to be careful to update those. Other indices (bindings, actions, maps, etc.)
  531. // are guaranteed to still match.
  532. ref var oldActionState = ref oldState.actionStates[actionIndex];
  533. if (bindingIndex == oldActionState.bindingIndex && oldActionState.phase.IsInProgress() &&
  534. activeControls.Count > 0 && activeControls[oldActionState.controlIndex] != null)
  535. {
  536. var control = activeControls[oldActionState.controlIndex];
  537. // Find the new control index. Binding index is guaranteed to be the same,
  538. // so we can simply look on the binding for where the control is now.
  539. var newControlIndex = FindControlIndexOnBinding(bindingIndex, control);
  540. // This assert is used by test: Actions_ActiveBindingsHaveCorrectBindingIndicesAfterBindingResolution
  541. Debug.Assert(newControlIndex != kInvalidIndex, "Could not find active control after binding resolution");
  542. if (newControlIndex != kInvalidIndex)
  543. {
  544. newActionState.phase = oldActionState.phase;
  545. newActionState.controlIndex = newControlIndex;
  546. newActionState.magnitude = oldActionState.magnitude;
  547. newActionState.interactionIndex = oldActionState.interactionIndex;
  548. memory.controlMagnitudes[newControlIndex] = oldActionState.magnitude;
  549. }
  550. // Also bring over interaction states.
  551. Debug.Assert(newBindingState.interactionCount == oldBindingState.interactionCount,
  552. "Interaction count on binding must not have changed when doing a control-only resolve");
  553. for (var n = 0; n < newBindingState.interactionCount; ++n)
  554. {
  555. ref var oldInteractionState = ref oldState.interactionStates[oldBindingState.interactionStartIndex + n];
  556. if (!oldInteractionState.phase.IsInProgress())
  557. continue;
  558. control = activeControls[oldInteractionState.triggerControlIndex];
  559. if (control == null)
  560. continue;
  561. newControlIndex = FindControlIndexOnBinding(bindingIndex, control);
  562. Debug.Assert(newControlIndex != kInvalidIndex, "Could not find active control on interaction after binding resolution");
  563. ref var newInteractionState = ref interactionStates[newBindingState.interactionStartIndex + n];
  564. newInteractionState.phase = oldInteractionState.phase;
  565. newInteractionState.performedTime = oldInteractionState.performedTime;
  566. newInteractionState.startTime = oldInteractionState.startTime;
  567. newInteractionState.triggerControlIndex = newControlIndex;
  568. // If there was a running timeout on the interaction, resume it now.
  569. if (oldInteractionState.isTimerRunning)
  570. {
  571. var trigger = new TriggerState
  572. {
  573. mapIndex = newBindingState.mapIndex,
  574. controlIndex = newControlIndex,
  575. bindingIndex = bindingIndex,
  576. time = oldInteractionState.timerStartTime,
  577. interactionIndex = newBindingState.interactionStartIndex + n
  578. };
  579. StartTimeout(oldInteractionState.timerDuration, ref trigger);
  580. newInteractionState.totalTimeoutCompletionDone = oldInteractionState.totalTimeoutCompletionDone;
  581. newInteractionState.totalTimeoutCompletionTimeRemaining = oldInteractionState.totalTimeoutCompletionTimeRemaining;
  582. }
  583. }
  584. }
  585. }
  586. // Make sure we get an initial state check.
  587. HookOnBeforeUpdate();
  588. // Let listeners know we have changed controls.
  589. NotifyListenersOfActionChange(InputActionChange.BoundControlsChanged);
  590. // For a full resolve, we will have temporarily disabled actions and reenabled them now.
  591. // Let listeners now.
  592. if (isFullResolve && s_GlobalState.onActionChange.length > 0)
  593. {
  594. for (var i = 0; i < totalMapCount; ++i)
  595. {
  596. var map = maps[i];
  597. if (map.m_SingletonAction == null && map.m_EnabledActionsCount == map.m_Actions.LengthSafe())
  598. {
  599. NotifyListenersOfActionChange(InputActionChange.ActionMapEnabled, map);
  600. }
  601. else
  602. {
  603. var actions = map.actions;
  604. foreach (var action in actions)
  605. if (action.enabled)
  606. NotifyListenersOfActionChange(InputActionChange.ActionEnabled, action);
  607. }
  608. }
  609. }
  610. }
  611. // Return true if the action that bindingIndex is bound to is currently driven from the given control
  612. // -OR- if any of the interactions on the binding are currently driven from the control.
  613. private bool IsActiveControl(int bindingIndex, int controlIndex)
  614. {
  615. ref var bindingState = ref bindingStates[bindingIndex];
  616. var actionIndex = bindingState.actionIndex;
  617. if (actionIndex == kInvalidIndex)
  618. return false;
  619. if (actionStates[actionIndex].controlIndex == controlIndex)
  620. return true;
  621. for (var i = 0; i < bindingState.interactionCount; ++i)
  622. if (interactionStates[bindingStates->interactionStartIndex + i].triggerControlIndex == controlIndex)
  623. return true;
  624. return false;
  625. }
  626. private int FindControlIndexOnBinding(int bindingIndex, InputControl control)
  627. {
  628. var controlStartIndex = bindingStates[bindingIndex].controlStartIndex;
  629. var controlCount = bindingStates[bindingIndex].controlCount;
  630. for (var n = 0; n < controlCount; ++n)
  631. {
  632. if (control == controls[controlStartIndex + n])
  633. return controlStartIndex + n;
  634. }
  635. return kInvalidIndex;
  636. }
  637. private void ResetActionStatesDrivenBy(InputDevice device)
  638. {
  639. using (InputActionRebindingExtensions.DeferBindingResolution())
  640. {
  641. for (var actionIndex = 0; actionIndex < totalActionCount; ++actionIndex)
  642. {
  643. var actionState = &actionStates[actionIndex];
  644. // Skip actions that aren't in progress.
  645. if (actionState->phase == InputActionPhase.Waiting || actionState->phase == InputActionPhase.Disabled)
  646. continue;
  647. // Skip actions not driven from this device.
  648. if (actionState->isPassThrough)
  649. {
  650. // Pass-through actions are not driven from specific controls yet still benefit
  651. // from being able to observe resets. So for these, we need to check all bound controls,
  652. // not just the one that happen to trigger last.
  653. if (!IsActionBoundToControlFromDevice(device, actionIndex))
  654. continue;
  655. }
  656. else
  657. {
  658. // For button and value actions, we go by whatever is currently driving the action.
  659. var controlIndex = actionState->controlIndex;
  660. if (controlIndex == -1)
  661. continue;
  662. var control = controls[controlIndex];
  663. if (control.device != device)
  664. continue;
  665. }
  666. // Reset.
  667. ResetActionState(actionIndex);
  668. }
  669. }
  670. }
  671. private bool IsActionBoundToControlFromDevice(InputDevice device, int actionIndex)
  672. {
  673. var usesControlFromDevice = false;
  674. var bindingStartIndex = GetActionBindingStartIndexAndCount(actionIndex, out var bindingCount);
  675. for (var i = 0; i < bindingCount; ++i)
  676. {
  677. var bindingIndex = memory.actionBindingIndices[bindingStartIndex + i];
  678. var controlCount = bindingStates[bindingIndex].controlCount;
  679. var controlStartIndex = bindingStates[bindingIndex].controlStartIndex;
  680. for (var n = 0; n < controlCount; ++n)
  681. {
  682. var control = controls[controlStartIndex + n];
  683. if (control.device == device)
  684. {
  685. usesControlFromDevice = true;
  686. break;
  687. }
  688. }
  689. }
  690. return usesControlFromDevice;
  691. }
  692. /// <summary>
  693. /// Reset the trigger state of the given action such that the action has no record of being triggered.
  694. /// </summary>
  695. /// <param name="actionIndex">Action whose state to reset.</param>
  696. /// <param name="toPhase">Phase to reset the action to. Must be either <see cref="InputActionPhase.Waiting"/>
  697. /// or <see cref="InputActionPhase.Disabled"/>. Other phases cannot be transitioned to through resets.</param>
  698. /// <param name="hardReset">If true, also wipe state such as for <see cref="InputAction.WasPressedThisFrame"/> which normally
  699. /// persists even if an action is disabled.</param>
  700. public void ResetActionState(int actionIndex, InputActionPhase toPhase = InputActionPhase.Waiting, bool hardReset = false)
  701. {
  702. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount, "Action index out of range when resetting action");
  703. Debug.Assert(toPhase == InputActionPhase.Waiting || toPhase == InputActionPhase.Disabled,
  704. "Phase must be Waiting or Disabled");
  705. // If the action in started or performed phase, cancel it first.
  706. var actionState = &actionStates[actionIndex];
  707. if (actionState->phase != InputActionPhase.Waiting && actionState->phase != InputActionPhase.Disabled)
  708. {
  709. // Cancellation calls should receive current time.
  710. actionState->time = InputState.currentTime;
  711. // If the action got triggered from an interaction, go and reset all interactions on the binding
  712. // that got triggered.
  713. if (actionState->interactionIndex != kInvalidIndex)
  714. {
  715. var bindingIndex = actionState->bindingIndex;
  716. if (bindingIndex != kInvalidIndex)
  717. {
  718. var mapIndex = actionState->mapIndex;
  719. var interactionCount = bindingStates[bindingIndex].interactionCount;
  720. var interactionStartIndex = bindingStates[bindingIndex].interactionStartIndex;
  721. for (var i = 0; i < interactionCount; ++i)
  722. {
  723. var interactionIndex = interactionStartIndex + i;
  724. ResetInteractionStateAndCancelIfNecessary(mapIndex, bindingIndex, interactionIndex, phaseAfterCanceled: toPhase);
  725. }
  726. }
  727. }
  728. else
  729. {
  730. // No interactions. Cancel the action directly.
  731. Debug.Assert(actionState->bindingIndex != kInvalidIndex, "Binding index on trigger state is invalid");
  732. Debug.Assert(bindingStates[actionState->bindingIndex].interactionCount == 0,
  733. "Action has been triggered but apparently not from an interaction yet there's interactions on the binding that got triggered?!?");
  734. if (actionState->phase != InputActionPhase.Canceled)
  735. ChangePhaseOfAction(InputActionPhase.Canceled, ref actionStates[actionIndex],
  736. phaseAfterPerformedOrCanceled: toPhase);
  737. }
  738. }
  739. // Wipe state.
  740. actionState->phase = toPhase;
  741. actionState->controlIndex = kInvalidIndex;
  742. actionState->bindingIndex = memory.actionBindingIndices[memory.actionBindingIndicesAndCounts[actionIndex]];
  743. actionState->interactionIndex = kInvalidIndex;
  744. actionState->startTime = 0;
  745. actionState->time = 0;
  746. actionState->hasMultipleConcurrentActuations = false;
  747. actionState->inProcessing = false;
  748. actionState->isPressed = false;
  749. // For "hard resets", wipe state we don't normally wipe. This resets things such as WasPressedThisFrame().
  750. if (hardReset)
  751. {
  752. actionState->lastCanceledInUpdate = default;
  753. actionState->lastPerformedInUpdate = default;
  754. actionState->lastCompletedInUpdate = default;
  755. actionState->pressedInUpdate = default;
  756. actionState->releasedInUpdate = default;
  757. }
  758. Debug.Assert(!actionState->isStarted, "Cannot reset an action to started phase");
  759. Debug.Assert(!actionState->isPerformed, "Cannot reset an action to performed phase");
  760. Debug.Assert(!actionState->isCanceled, "Cannot reset an action to canceled phase");
  761. }
  762. public ref TriggerState FetchActionState(InputAction action)
  763. {
  764. Debug.Assert(action != null, "Action must not be null");
  765. Debug.Assert(action.m_ActionMap != null, "Action must have an action map");
  766. Debug.Assert(action.m_ActionMap.m_MapIndexInState != kInvalidIndex, "Action must have index set");
  767. Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
  768. Debug.Assert(action.m_ActionIndexInState >= 0 && action.m_ActionIndexInState < totalActionCount, "Action index is out of range");
  769. return ref actionStates[action.m_ActionIndexInState];
  770. }
  771. public ActionMapIndices FetchMapIndices(InputActionMap map)
  772. {
  773. Debug.Assert(map != null, "Must must not be null");
  774. Debug.Assert(maps.Contains(map), "Map must be contained in state");
  775. return mapIndices[map.m_MapIndexInState];
  776. }
  777. public void EnableAllActions(InputActionMap map)
  778. {
  779. Debug.Assert(map != null, "Map must not be null");
  780. Debug.Assert(map.m_Actions != null, "Map must have actions");
  781. Debug.Assert(maps.Contains(map), "Map must be contained in state");
  782. // Enable all controls in map that aren't already enabled.
  783. EnableControls(map);
  784. // Put all actions that aren't already enabled into waiting state.
  785. var mapIndex = map.m_MapIndexInState;
  786. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index on InputActionMap is out of range");
  787. var actionCount = mapIndices[mapIndex].actionCount;
  788. var actionStartIndex = mapIndices[mapIndex].actionStartIndex;
  789. for (var i = 0; i < actionCount; ++i)
  790. {
  791. var actionIndex = actionStartIndex + i;
  792. var actionState = &actionStates[actionIndex];
  793. if (actionState->isDisabled)
  794. actionState->phase = InputActionPhase.Waiting;
  795. actionState->inProcessing = false;
  796. }
  797. map.m_EnabledActionsCount = actionCount;
  798. HookOnBeforeUpdate();
  799. // Make sure that if we happen to get here with one of the hidden action maps we create for singleton
  800. // action, we notify on the action, not the hidden map.
  801. if (map.m_SingletonAction != null)
  802. NotifyListenersOfActionChange(InputActionChange.ActionEnabled, map.m_SingletonAction);
  803. else
  804. NotifyListenersOfActionChange(InputActionChange.ActionMapEnabled, map);
  805. }
  806. private void EnableControls(InputActionMap map)
  807. {
  808. Debug.Assert(map != null, "Map must not be null");
  809. Debug.Assert(map.m_Actions != null, "Map must have actions");
  810. Debug.Assert(maps.Contains(map), "Map must be contained in state");
  811. var mapIndex = map.m_MapIndexInState;
  812. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index on InputActionMap is out of range");
  813. // Install state monitors for all controls.
  814. var controlCount = mapIndices[mapIndex].controlCount;
  815. var controlStartIndex = mapIndices[mapIndex].controlStartIndex;
  816. if (controlCount > 0)
  817. EnableControls(mapIndex, controlStartIndex, controlCount);
  818. }
  819. public void EnableSingleAction(InputAction action)
  820. {
  821. Debug.Assert(action != null, "Action must not be null");
  822. Debug.Assert(action.m_ActionMap != null, "Action must have action map");
  823. Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
  824. EnableControls(action);
  825. // Put action into waiting state.
  826. var actionIndex = action.m_ActionIndexInState;
  827. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  828. "Action index out of range when enabling single action");
  829. actionStates[actionIndex].phase = InputActionPhase.Waiting;
  830. ++action.m_ActionMap.m_EnabledActionsCount;
  831. HookOnBeforeUpdate();
  832. NotifyListenersOfActionChange(InputActionChange.ActionEnabled, action);
  833. }
  834. private void EnableControls(InputAction action)
  835. {
  836. Debug.Assert(action != null, "Action must not be null");
  837. Debug.Assert(action.m_ActionMap != null, "Action must have action map");
  838. Debug.Assert(maps.Contains(action.m_ActionMap), "Map must be contained in state");
  839. var actionIndex = action.m_ActionIndexInState;
  840. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  841. "Action index out of range when enabling controls");
  842. var map = action.m_ActionMap;
  843. var mapIndex = map.m_MapIndexInState;
  844. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range in EnableControls");
  845. // Go through all bindings in the map and for all that belong to the given action,
  846. // enable the associated controls.
  847. var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
  848. var bindingCount = mapIndices[mapIndex].bindingCount;
  849. var bindingStatesPtr = memory.bindingStates;
  850. for (var i = 0; i < bindingCount; ++i)
  851. {
  852. var bindingIndex = bindingStartIndex + i;
  853. var bindingState = &bindingStatesPtr[bindingIndex];
  854. if (bindingState->actionIndex != actionIndex)
  855. continue;
  856. // Composites enable en-bloc through the composite binding itself.
  857. if (bindingState->isPartOfComposite)
  858. continue;
  859. var controlCount = bindingState->controlCount;
  860. if (controlCount == 0)
  861. continue;
  862. EnableControls(mapIndex, bindingState->controlStartIndex, controlCount);
  863. }
  864. }
  865. public void DisableAllActions(InputActionMap map)
  866. {
  867. Debug.Assert(map != null, "Map must not be null");
  868. Debug.Assert(map.m_Actions != null, "Map must have actions");
  869. Debug.Assert(maps.Contains(map), "Map must be contained in state");
  870. DisableControls(map);
  871. // Mark all actions as disabled.
  872. var mapIndex = map.m_MapIndexInState;
  873. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range in DisableAllActions");
  874. var actionStartIndex = mapIndices[mapIndex].actionStartIndex;
  875. var actionCount = mapIndices[mapIndex].actionCount;
  876. var allActionsEnabled = map.m_EnabledActionsCount == actionCount;
  877. for (var i = 0; i < actionCount; ++i)
  878. {
  879. var actionIndex = actionStartIndex + i;
  880. if (actionStates[actionIndex].phase != InputActionPhase.Disabled)
  881. {
  882. ResetActionState(actionIndex, toPhase: InputActionPhase.Disabled);
  883. if (!allActionsEnabled)
  884. NotifyListenersOfActionChange(InputActionChange.ActionDisabled, map.m_Actions[i]);
  885. }
  886. }
  887. map.m_EnabledActionsCount = 0;
  888. // Make sure that if we happen to get here with one of the hidden action maps we create for singleton
  889. // action, we notify on the action, not the hidden map.
  890. if (map.m_SingletonAction != null)
  891. NotifyListenersOfActionChange(InputActionChange.ActionDisabled, map.m_SingletonAction);
  892. else if (allActionsEnabled)
  893. NotifyListenersOfActionChange(InputActionChange.ActionMapDisabled, map);
  894. }
  895. public void DisableControls(InputActionMap map)
  896. {
  897. Debug.Assert(map != null, "Map must not be null");
  898. Debug.Assert(map.m_Actions != null, "Map must have actions");
  899. Debug.Assert(maps.Contains(map), "Map must be contained in state");
  900. var mapIndex = map.m_MapIndexInState;
  901. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range in DisableControls(InputActionMap)");
  902. // Remove state monitors from all controls.
  903. var controlCount = mapIndices[mapIndex].controlCount;
  904. var controlStartIndex = mapIndices[mapIndex].controlStartIndex;
  905. if (controlCount > 0)
  906. DisableControls(mapIndex, controlStartIndex, controlCount);
  907. }
  908. public void DisableSingleAction(InputAction action)
  909. {
  910. Debug.Assert(action != null, "Action must not be null");
  911. Debug.Assert(action.m_ActionMap != null, "Action must have action map");
  912. Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
  913. DisableControls(action);
  914. ResetActionState(action.m_ActionIndexInState, toPhase: InputActionPhase.Disabled);
  915. --action.m_ActionMap.m_EnabledActionsCount;
  916. NotifyListenersOfActionChange(InputActionChange.ActionDisabled, action);
  917. }
  918. private void DisableControls(InputAction action)
  919. {
  920. Debug.Assert(action != null, "Action must not be null");
  921. Debug.Assert(action.m_ActionMap != null, "Action must have action map");
  922. Debug.Assert(maps.Contains(action.m_ActionMap), "Action map must be contained in state");
  923. var actionIndex = action.m_ActionIndexInState;
  924. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  925. "Action index out of range when disabling controls");
  926. var map = action.m_ActionMap;
  927. var mapIndex = map.m_MapIndexInState;
  928. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range in DisableControls(InputAction)");
  929. // Go through all bindings in the map and for all that belong to the given action,
  930. // disable the associated controls.
  931. var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
  932. var bindingCount = mapIndices[mapIndex].bindingCount;
  933. var bindingStatesPtr = memory.bindingStates;
  934. for (var i = 0; i < bindingCount; ++i)
  935. {
  936. var bindingIndex = bindingStartIndex + i;
  937. var bindingState = &bindingStatesPtr[bindingIndex];
  938. if (bindingState->actionIndex != actionIndex)
  939. continue;
  940. // Composites enable en-bloc through the composite binding itself.
  941. if (bindingState->isPartOfComposite)
  942. continue;
  943. var controlCount = bindingState->controlCount;
  944. if (controlCount == 0)
  945. continue;
  946. DisableControls(mapIndex, bindingState->controlStartIndex, controlCount);
  947. }
  948. }
  949. ////REVIEW: can we have a method on InputManager doing this in bulk?
  950. ////NOTE: This must not enable only a partial set of controls on a binding (currently we have no setup that would lead to that)
  951. private void EnableControls(int mapIndex, int controlStartIndex, int numControls)
  952. {
  953. Debug.Assert(controls != null, "State must have controls");
  954. Debug.Assert(controlStartIndex >= 0 && (controlStartIndex < totalControlCount || numControls == 0),
  955. "Control start index out of range");
  956. Debug.Assert(controlStartIndex + numControls <= totalControlCount, "Control range out of bounds");
  957. var manager = InputSystem.s_Manager;
  958. for (var i = 0; i < numControls; ++i)
  959. {
  960. var controlIndex = controlStartIndex + i;
  961. // We don't want to add multiple state monitors for the same control. This can happen if enabling
  962. // single actions is mixed with enabling actions maps containing them.
  963. if (IsControlEnabled(controlIndex))
  964. continue;
  965. var bindingIndex = controlIndexToBindingIndex[controlIndex];
  966. var mapControlAndBindingIndex = ToCombinedMapAndControlAndBindingIndex(mapIndex, controlIndex, bindingIndex);
  967. var bindingStatePtr = &bindingStates[bindingIndex];
  968. if (bindingStatePtr->wantsInitialStateCheck)
  969. SetInitialStateCheckPending(bindingStatePtr, true);
  970. manager.AddStateChangeMonitor(controls[controlIndex], this, mapControlAndBindingIndex, controlGroupingAndComplexity[controlIndex * 2]);
  971. SetControlEnabled(controlIndex, true);
  972. }
  973. }
  974. private void DisableControls(int mapIndex, int controlStartIndex, int numControls)
  975. {
  976. Debug.Assert(controls != null, "State must have controls");
  977. Debug.Assert(controlStartIndex >= 0 && (controlStartIndex < totalControlCount || numControls == 0),
  978. "Control start index out of range");
  979. Debug.Assert(controlStartIndex + numControls <= totalControlCount, "Control range out of bounds");
  980. var manager = InputSystem.s_Manager;
  981. for (var i = 0; i < numControls; ++i)
  982. {
  983. var controlIndex = controlStartIndex + i;
  984. ////TODO: This can be done much more efficiently by at least going byte by byte in the mask instead of just bit by bit
  985. if (!IsControlEnabled(controlIndex))
  986. continue;
  987. var bindingIndex = controlIndexToBindingIndex[controlIndex];
  988. var mapControlAndBindingIndex = ToCombinedMapAndControlAndBindingIndex(mapIndex, controlIndex, bindingIndex);
  989. var bindingStatePtr = &bindingStates[bindingIndex];
  990. if (bindingStatePtr->wantsInitialStateCheck)
  991. SetInitialStateCheckPending(bindingStatePtr, false);
  992. manager.RemoveStateChangeMonitor(controls[controlIndex], this, mapControlAndBindingIndex);
  993. SetControlEnabled(controlIndex, false);
  994. }
  995. }
  996. public void SetInitialStateCheckPending(int actionIndex, bool value = true)
  997. {
  998. var mapIndex = actionStates[actionIndex].mapIndex;
  999. var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
  1000. var bindingCount = mapIndices[mapIndex].bindingCount;
  1001. for (var i = 0; i < bindingCount; ++i)
  1002. {
  1003. ref var bindingState = ref bindingStates[bindingStartIndex + i];
  1004. if (bindingState.actionIndex == actionIndex && !bindingState.isPartOfComposite)
  1005. bindingState.initialStateCheckPending = value;
  1006. }
  1007. }
  1008. private void SetInitialStateCheckPending(BindingState* bindingStatePtr, bool value)
  1009. {
  1010. if (bindingStatePtr->isPartOfComposite)
  1011. {
  1012. // For composites, we always flag the composite itself as wanting an initial state check. This
  1013. // way, we don't have to worry about triggering the composite multiple times when several of its
  1014. // controls are actuated.
  1015. var compositeIndex = bindingStatePtr->compositeOrCompositeBindingIndex;
  1016. bindingStates[compositeIndex].initialStateCheckPending = value;
  1017. }
  1018. else
  1019. {
  1020. bindingStatePtr->initialStateCheckPending = value;
  1021. }
  1022. }
  1023. private bool IsControlEnabled(int controlIndex)
  1024. {
  1025. var intIndex = controlIndex / 32;
  1026. var mask = 1U << (controlIndex % 32);
  1027. return (enabledControls[intIndex] & mask) != 0;
  1028. }
  1029. private void SetControlEnabled(int controlIndex, bool state)
  1030. {
  1031. var intIndex = controlIndex / 32;
  1032. var mask = 1U << (controlIndex % 32);
  1033. if (state)
  1034. enabledControls[intIndex] |= mask;
  1035. else
  1036. enabledControls[intIndex] &= ~mask;
  1037. }
  1038. private void HookOnBeforeUpdate()
  1039. {
  1040. if (m_OnBeforeUpdateHooked)
  1041. return;
  1042. if (m_OnBeforeUpdateDelegate == null)
  1043. m_OnBeforeUpdateDelegate = OnBeforeInitialUpdate;
  1044. InputSystem.s_Manager.onBeforeUpdate += m_OnBeforeUpdateDelegate;
  1045. m_OnBeforeUpdateHooked = true;
  1046. }
  1047. private void UnhookOnBeforeUpdate()
  1048. {
  1049. if (!m_OnBeforeUpdateHooked)
  1050. return;
  1051. InputSystem.s_Manager.onBeforeUpdate -= m_OnBeforeUpdateDelegate;
  1052. m_OnBeforeUpdateHooked = false;
  1053. }
  1054. // We hook this into InputManager.onBeforeUpdate every time actions are enabled and then take it off
  1055. // the list after the first call. Inside here we check whether any actions we enabled already have
  1056. // non-default state on bound controls.
  1057. //
  1058. // NOTE: We do this as a callback from onBeforeUpdate rather than directly when the action is enabled
  1059. // to ensure that the callbacks happen during input processing and not randomly from wherever
  1060. // an action happens to be enabled.
  1061. private void OnBeforeInitialUpdate()
  1062. {
  1063. if (InputState.currentUpdateType == InputUpdateType.BeforeRender
  1064. #if UNITY_EDITOR
  1065. || InputState.currentUpdateType == InputUpdateType.Editor
  1066. #endif
  1067. )
  1068. return;
  1069. // Remove us from the callback as the processing we're doing here is a one-time thing.
  1070. UnhookOnBeforeUpdate();
  1071. Profiler.BeginSample("InitialActionStateCheck");
  1072. // Use current time as time of control state change.
  1073. var time = InputState.currentTime;
  1074. ////REVIEW: should we store this data in a separate place rather than go through all bindingStates?
  1075. // Go through all binding states and for every binding that needs an initial state check,
  1076. // go through all bound controls and for each one that isn't in its default state, pretend
  1077. // that the control just got actuated.
  1078. var manager = InputSystem.s_Manager;
  1079. for (var bindingIndex = 0; bindingIndex < totalBindingCount; ++bindingIndex)
  1080. {
  1081. ref var bindingState = ref bindingStates[bindingIndex];
  1082. if (!bindingState.initialStateCheckPending)
  1083. continue;
  1084. Debug.Assert(!bindingState.isPartOfComposite, "Initial state check flag must be set on composite, not on its parts");
  1085. bindingState.initialStateCheckPending = false;
  1086. var controlStartIndex = bindingState.controlStartIndex;
  1087. var controlCount = bindingState.controlCount;
  1088. var isComposite = bindingState.isComposite;
  1089. var didFindControlToSignal = false;
  1090. for (var n = 0; n < controlCount; ++n)
  1091. {
  1092. var controlIndex = controlStartIndex + n;
  1093. var control = controls[controlIndex];
  1094. // Leave any control alone that is already driving an interaction and/or action.
  1095. if (IsActiveControl(bindingIndex, controlIndex))
  1096. continue;
  1097. if (!control.CheckStateIsAtDefault())
  1098. {
  1099. // Update press times.
  1100. if (control.IsValueConsideredPressed(control.magnitude))
  1101. {
  1102. // ReSharper disable once CompareOfFloatsByEqualityOperator
  1103. if (bindingState.pressTime == default || bindingState.pressTime > time)
  1104. bindingState.pressTime = time;
  1105. }
  1106. // For composites, any one actuated control will lead to the composite being
  1107. // processed as a whole so we can stop here. This also ensures that we are
  1108. // not triggering the composite repeatedly if there are multiple actuated
  1109. // controls bound to its parts.
  1110. if (isComposite && didFindControlToSignal)
  1111. continue;
  1112. manager.SignalStateChangeMonitor(control, this);
  1113. didFindControlToSignal = true;
  1114. }
  1115. }
  1116. }
  1117. manager.FireStateChangeNotifications();
  1118. Profiler.EndSample();
  1119. }
  1120. // Called from InputManager when one of our state change monitors has fired.
  1121. // Tells us the time of the change *according to the state events coming in*.
  1122. // Also tells us which control of the controls we are binding to triggered the
  1123. // change and relays the binding index we gave it when we called AddChangeMonitor.
  1124. void IInputStateChangeMonitor.NotifyControlStateChanged(InputControl control, double time,
  1125. InputEventPtr eventPtr, long mapControlAndBindingIndex)
  1126. {
  1127. #if UNITY_EDITOR
  1128. if (InputState.currentUpdateType == InputUpdateType.Editor)
  1129. return;
  1130. #endif
  1131. SplitUpMapAndControlAndBindingIndex(mapControlAndBindingIndex, out var mapIndex, out var controlIndex, out var bindingIndex);
  1132. ProcessControlStateChange(mapIndex, controlIndex, bindingIndex, time, eventPtr);
  1133. }
  1134. void IInputStateChangeMonitor.NotifyTimerExpired(InputControl control, double time,
  1135. long mapControlAndBindingIndex, int interactionIndex)
  1136. {
  1137. SplitUpMapAndControlAndBindingIndex(mapControlAndBindingIndex, out var mapIndex, out var controlIndex, out var bindingIndex);
  1138. ProcessTimeout(time, mapIndex, controlIndex, bindingIndex, interactionIndex);
  1139. }
  1140. /// <summary>
  1141. /// Bit pack the mapIndex, controlIndex, bindingIndex and complexity components into a single long monitor index value.
  1142. /// </summary>
  1143. /// <param name="mapIndex">The mapIndex value to pack.</param>
  1144. /// <param name="controlIndex">The controlIndex value to pack.</param>
  1145. /// <param name="bindingIndex">The bindingIndex value to pack..</param>
  1146. /// <remarks>
  1147. /// We mangle the various indices we use into a single long for association with state change
  1148. /// monitors. While we could look up map and binding indices from control indices, keeping
  1149. /// all the information together avoids having to unnecessarily jump around in memory to grab
  1150. /// the various pieces of data.
  1151. /// The complexity component is implicitly derived and does not need to be passed as an argument.
  1152. /// </remarks>
  1153. private long ToCombinedMapAndControlAndBindingIndex(int mapIndex, int controlIndex, int bindingIndex)
  1154. {
  1155. // We have limits on the numbers of maps, controls, and bindings we allow in any single
  1156. // action state (see TriggerState.kMaxNumXXX).
  1157. var complexity = controlGroupingAndComplexity[controlIndex * 2 + 1];
  1158. var result = (long)controlIndex;
  1159. result |= (long)bindingIndex << 24;
  1160. result |= (long)mapIndex << 40;
  1161. result |= (long)complexity << 48;
  1162. return result;
  1163. }
  1164. /// <summary>
  1165. /// Extract the mapIndex, controlIndex and bindingIndex components from the provided bit packed argument (monitor index).
  1166. /// </summary>
  1167. /// <param name="mapControlAndBindingIndex">Represents a monitor index, which is a bit packed field containing multiple components.</param>
  1168. /// <param name="mapIndex">Will hold the extracted mapIndex value after the function completes.</param>
  1169. /// <param name="controlIndex">Will hold the extracted controlIndex value after the function completes.</param>
  1170. /// <param name="bindingIndex">Will hold the extracted bindingIndex value after the function completes.</param>
  1171. private void SplitUpMapAndControlAndBindingIndex(long mapControlAndBindingIndex, out int mapIndex,
  1172. out int controlIndex, out int bindingIndex)
  1173. {
  1174. controlIndex = (int)(mapControlAndBindingIndex & 0x00ffffff);
  1175. bindingIndex = (int)((mapControlAndBindingIndex >> 24) & 0xffff);
  1176. mapIndex = (int)((mapControlAndBindingIndex >> 40) & 0xff);
  1177. }
  1178. /// <summary>
  1179. /// Extract the 'complexity' component from the provided bit packed argument (monitor index).
  1180. /// </summary>
  1181. /// <param name="mapControlAndBindingIndex">Represents a monitor index, which is a bit packed field containing multiple components.</param>
  1182. internal static int GetComplexityFromMonitorIndex(long mapControlAndBindingIndex)
  1183. {
  1184. return (int)((mapControlAndBindingIndex >> 48) & 0xff);
  1185. }
  1186. /// <summary>
  1187. /// Process a state change that has happened in one of the controls attached
  1188. /// to this action map state.
  1189. /// </summary>
  1190. /// <param name="mapIndex">Index of the action map to which the binding belongs.</param>
  1191. /// <param name="controlIndex">Index of the control that changed state.</param>
  1192. /// <param name="bindingIndex">Index of the binding associated with the given control.</param>
  1193. /// <param name="time">The timestamp associated with the state change (comes from the state change event).</param>
  1194. /// <param name="eventPtr">Event (if any) that triggered the state change.</param>
  1195. /// <remarks>
  1196. /// This is where we end up if one of the state monitors we've put in the system has triggered.
  1197. /// From here we go back to the associated binding and then let it figure out what the state change
  1198. /// means for it.
  1199. ///
  1200. /// Note that we get called for any change in state even if the change in state does not actually
  1201. /// result in a change of value on the respective control.
  1202. /// </remarks>
  1203. private void ProcessControlStateChange(int mapIndex, int controlIndex, int bindingIndex, double time, InputEventPtr eventPtr)
  1204. {
  1205. Debug.Assert(mapIndex >= 0 && mapIndex < totalMapCount, "Map index out of range in ProcessControlStateChange");
  1206. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index out of range");
  1207. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1208. using (InputActionRebindingExtensions.DeferBindingResolution())
  1209. {
  1210. // Callbacks can do pretty much anything and thus trigger arbitrary state/configuration
  1211. // changes in the system. We have to ensure that while we're executing callbacks, our
  1212. // current InputActionState is not getting changed from under us. We dictate that while
  1213. // m_InProcessControlStateChange is true, no binding resolution can be triggered on the state and
  1214. // it cannot be destroyed.
  1215. //
  1216. // This is also why we defer binding resolution above. If there is a configuration change
  1217. // triggered by an action callback, the state will be marked dirty and re-resolved after
  1218. // we have completed the callback.
  1219. m_InProcessControlStateChange = true;
  1220. m_CurrentlyProcessingThisEvent = eventPtr;
  1221. try
  1222. {
  1223. var bindingStatePtr = &bindingStates[bindingIndex];
  1224. var actionIndex = bindingStatePtr->actionIndex;
  1225. var trigger = new TriggerState
  1226. {
  1227. mapIndex = mapIndex,
  1228. controlIndex = controlIndex,
  1229. bindingIndex = bindingIndex,
  1230. interactionIndex = kInvalidIndex,
  1231. time = time,
  1232. startTime = time,
  1233. isPassThrough = actionIndex != kInvalidIndex && actionStates[actionIndex].isPassThrough,
  1234. isButton = actionIndex != kInvalidIndex && actionStates[actionIndex].isButton,
  1235. };
  1236. // If we have pending initial state checks that will run in the next update,
  1237. // force-reset the flag on the control that just triggered. This ensures that we're
  1238. // not triggering an action twice from the same state change in case the initial state
  1239. // check happens later (see Actions_ValueActionsEnabledInOnEvent_DoNotReactToCurrentStateOfControlTwice).
  1240. if (m_OnBeforeUpdateHooked)
  1241. bindingStatePtr->initialStateCheckPending = false;
  1242. // Store magnitude. We do this once and then only read it from here.
  1243. var control = controls[controlIndex];
  1244. trigger.magnitude = control.CheckStateIsAtDefault() ? 0f : control.magnitude;
  1245. controlMagnitudes[controlIndex] = trigger.magnitude;
  1246. // Update press times.
  1247. if (control.IsValueConsideredPressed(trigger.magnitude))
  1248. {
  1249. // ReSharper disable once CompareOfFloatsByEqualityOperator
  1250. if (bindingStatePtr->pressTime == default || bindingStatePtr->pressTime > trigger.time)
  1251. bindingStatePtr->pressTime = trigger.time;
  1252. }
  1253. // If the binding is part of a composite, check for interactions on the composite
  1254. // itself and give them a first shot at processing the value change.
  1255. var haveInteractionsOnComposite = false;
  1256. if (bindingStatePtr->isPartOfComposite)
  1257. {
  1258. var compositeBindingIndex = bindingStatePtr->compositeOrCompositeBindingIndex;
  1259. var compositeBindingPtr = &bindingStates[compositeBindingIndex];
  1260. // If the composite has already been triggered from the very same event, ignore it.
  1261. // Example: KeyboardState change that includes both A and W key state changes and we're looking
  1262. // at a WASD composite binding. There's a state change monitor on both the A and the W
  1263. // key and thus the manager will notify us individually of both changes. However, we
  1264. // want to perform the action only once.
  1265. if (ShouldIgnoreInputOnCompositeBinding(compositeBindingPtr, eventPtr))
  1266. return;
  1267. // Update magnitude for composite.
  1268. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  1269. var compositeContext = new InputBindingCompositeContext
  1270. {
  1271. m_State = this,
  1272. m_BindingIndex = compositeBindingIndex
  1273. };
  1274. trigger.magnitude = composites[compositeIndex].EvaluateMagnitude(ref compositeContext);
  1275. memory.compositeMagnitudes[compositeIndex] = trigger.magnitude;
  1276. // Run through interactions on composite.
  1277. var interactionCountOnComposite = compositeBindingPtr->interactionCount;
  1278. if (interactionCountOnComposite > 0)
  1279. {
  1280. haveInteractionsOnComposite = true;
  1281. ProcessInteractions(ref trigger,
  1282. compositeBindingPtr->interactionStartIndex,
  1283. interactionCountOnComposite);
  1284. }
  1285. }
  1286. // Check if we have multiple concurrent actuations on the same action. This may lead us
  1287. // to ignore certain inputs (e.g. when we get an input of lesser magnitude while already having
  1288. // one of higher magnitude) or may even lead us to switch to processing a different binding
  1289. // (e.g. when an input of previously greater magnitude has now fallen below the level of another
  1290. // ongoing input with now higher magnitude).
  1291. var isConflictingInput = IsConflictingInput(ref trigger, actionIndex);
  1292. bindingStatePtr = &bindingStates[trigger.bindingIndex]; // IsConflictingInput may switch us to a different binding.
  1293. // Process button presses/releases.
  1294. if (!isConflictingInput)
  1295. ProcessButtonState(ref trigger, actionIndex, bindingStatePtr);
  1296. // If we have interactions, let them do all the processing. The presence of an interaction
  1297. // essentially bypasses the default phase progression logic of an action.
  1298. var interactionCount = bindingStatePtr->interactionCount;
  1299. if (interactionCount > 0 && !bindingStatePtr->isPartOfComposite)
  1300. {
  1301. ProcessInteractions(ref trigger, bindingStatePtr->interactionStartIndex, interactionCount);
  1302. }
  1303. else if (!haveInteractionsOnComposite && !isConflictingInput)
  1304. {
  1305. ProcessDefaultInteraction(ref trigger, actionIndex);
  1306. }
  1307. }
  1308. finally
  1309. {
  1310. m_InProcessControlStateChange = default;
  1311. m_CurrentlyProcessingThisEvent = default;
  1312. }
  1313. }
  1314. }
  1315. private void ProcessButtonState(ref TriggerState trigger, int actionIndex, BindingState* bindingStatePtr)
  1316. {
  1317. var control = controls[trigger.controlIndex];
  1318. var pressPoint = control.isButton
  1319. ? ((ButtonControl)control).pressPointOrDefault
  1320. : ButtonControl.s_GlobalDefaultButtonPressPoint;
  1321. // NOTE: This method relies on conflict resolution happening *first*. Otherwise, we may inadvertently
  1322. // detect a "release" from a control that is not actually driving the action.
  1323. // Record release time on the binding.
  1324. // NOTE: Explicitly look up control magnitude here instead of using trigger.magnitude
  1325. // as for part bindings, the trigger will have the magnitude of the whole composite.
  1326. var controlActuation = controlMagnitudes[trigger.controlIndex];
  1327. if (controlActuation <= pressPoint * ButtonControl.s_GlobalDefaultButtonReleaseThreshold)
  1328. bindingStatePtr->pressTime = 0d;
  1329. var actuation = trigger.magnitude;
  1330. var actionState = &actionStates[actionIndex];
  1331. if (!actionState->isPressed && actuation >= pressPoint)
  1332. {
  1333. actionState->pressedInUpdate = InputUpdate.s_UpdateStepCount;
  1334. actionState->isPressed = true;
  1335. }
  1336. else if (actionState->isPressed)
  1337. {
  1338. var releasePoint = pressPoint * ButtonControl.s_GlobalDefaultButtonReleaseThreshold;
  1339. if (actuation <= releasePoint)
  1340. {
  1341. actionState->releasedInUpdate = InputUpdate.s_UpdateStepCount;
  1342. actionState->isPressed = false;
  1343. }
  1344. }
  1345. }
  1346. /// <summary>
  1347. /// Whether the given state change on a composite binding should be ignored.
  1348. /// </summary>
  1349. /// <param name="binding"></param>
  1350. /// <param name="eventPtr"></param>
  1351. /// <returns></returns>
  1352. /// <remarks>
  1353. /// Each state event may change the state of arbitrary many controls on a device and thus may trigger
  1354. /// several bindings at once that are part of the same composite binding. We still want to trigger the
  1355. /// composite binding only once for the event.
  1356. ///
  1357. /// To do so, we store the ID of the event on the binding and ignore events if they have the same
  1358. /// ID as the one we've already recorded.
  1359. /// </remarks>
  1360. private static bool ShouldIgnoreInputOnCompositeBinding(BindingState* binding, InputEvent* eventPtr)
  1361. {
  1362. if (eventPtr == null)
  1363. return false;
  1364. var eventId = eventPtr->eventId;
  1365. if (eventId != 0 && binding->triggerEventIdForComposite == eventId)
  1366. return true;
  1367. binding->triggerEventIdForComposite = eventId;
  1368. return false;
  1369. }
  1370. /// <summary>
  1371. /// Whether the given control state should be ignored.
  1372. /// </summary>
  1373. /// <param name="trigger"></param>
  1374. /// <param name="actionIndex"></param>
  1375. /// <returns></returns>
  1376. /// <remarks>
  1377. /// If an action has multiple controls bound to it, control state changes on the action may conflict with each other.
  1378. /// If that happens, we resolve the conflict by always sticking to the most actuated control.
  1379. ///
  1380. /// Pass-through actions (<see cref="InputActionType.PassThrough"/>) will always bypass conflict resolution and respond
  1381. /// to every value change.
  1382. ///
  1383. /// Actions that are resolved to only a single control will early out of conflict resolution.
  1384. ///
  1385. /// Actions that are bound to multiple controls but have only one control actuated will early out of conflict
  1386. /// resolution as well.
  1387. ///
  1388. /// Note that conflict resolution here is entirely tied to magnitude. This ignores other qualities that the value
  1389. /// of a control may have. For example, one 2D vector may have a similar magnitude to another yet point in an
  1390. /// entirely different direction.
  1391. ///
  1392. /// There are other conflict resolution mechanisms that could be used. For example, we could average the values
  1393. /// from all controls. However, it would not necessarily result in more useful conflict resolution and would
  1394. /// at the same time be much more expensive.
  1395. /// </remarks>
  1396. private bool IsConflictingInput(ref TriggerState trigger, int actionIndex)
  1397. {
  1398. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  1399. "Action index out of range when checking for conflicting control input");
  1400. // The goal of this method is to provide conflict resolution but do so ONLY if it is
  1401. // really needed. In the vast majority of cases, this method should do almost nothing and
  1402. // simply return straight away.
  1403. // If conflict resolution is disabled on the action, early out. This is the case for pass-through
  1404. // actions and for actions that cannot get into an ambiguous state based on the controls they
  1405. // are bound to.
  1406. var actionState = &actionStates[actionIndex];
  1407. if (!actionState->mayNeedConflictResolution)
  1408. return false;
  1409. // Anything past here happens only for actions that may have conflicts.
  1410. // Anything below here we want to avoid executing whenever we can.
  1411. Debug.Assert(actionState->mayNeedConflictResolution);
  1412. Profiler.BeginSample("InputActionResolveConflict");
  1413. // We take a local copy of this value, so we can change it to use the starting control of composites
  1414. // for simpler conflict resolution (so composites always use the same value), but still report the actually
  1415. // actuated control to the user.
  1416. var triggerControlIndex = trigger.controlIndex;
  1417. if (bindingStates[trigger.bindingIndex].isPartOfComposite)
  1418. {
  1419. // For actions that need conflict resolution, we force TriggerState.controlIndex to the
  1420. // first control in a composite. Otherwise it becomes much harder to tell if the we have
  1421. // multiple concurrent actuations or not.
  1422. // Since composites always evaluate as a whole instead of as single controls, having
  1423. // triggerControlIndex differ from the state monitor that fired should be fine.
  1424. var compositeBindingIndex = bindingStates[trigger.bindingIndex].compositeOrCompositeBindingIndex;
  1425. triggerControlIndex = bindingStates[compositeBindingIndex].controlStartIndex;
  1426. Debug.Assert(triggerControlIndex >= 0 && triggerControlIndex < totalControlCount,
  1427. "Control start index on composite binding out of range");
  1428. }
  1429. // Determine which control to consider the one currently associated with the action.
  1430. // We do the same thing as for the triggered control and in the case of a composite,
  1431. // switch to the first control of the composite.
  1432. var actionStateControlIndex = actionState->controlIndex;
  1433. if (bindingStates[actionState->bindingIndex].isPartOfComposite)
  1434. {
  1435. var compositeBindingIndex = bindingStates[actionState->bindingIndex].compositeOrCompositeBindingIndex;
  1436. actionStateControlIndex = bindingStates[compositeBindingIndex].controlStartIndex;
  1437. }
  1438. // Never ignore state changes for actions that aren't currently driven by
  1439. // anything.
  1440. if (actionStateControlIndex == kInvalidIndex)
  1441. {
  1442. actionState->magnitude = trigger.magnitude;
  1443. Profiler.EndSample();
  1444. return false;
  1445. }
  1446. // Find out if we get triggered from the control that is actively driving the action.
  1447. var isControlCurrentlyDrivingTheAction = triggerControlIndex == actionStateControlIndex ||
  1448. controls[triggerControlIndex] == controls[actionStateControlIndex]; // Same control, different binding.
  1449. // If the control is actuated *more* than the current level of actuation we recorded for the
  1450. // action, we process the state change normally. If this isn't the control that is already
  1451. // driving the action, it will become the one now.
  1452. //
  1453. // NOTE: For composites, we're looking at the combined actuation of the entire binding here,
  1454. // not just at the actuation level of the individual control. ComputeMagnitude()
  1455. // automatically takes care of that for us.
  1456. if (trigger.magnitude > actionState->magnitude)
  1457. {
  1458. // If this is not the control that is currently driving the action, we know
  1459. // there are multiple controls that are concurrently actuated on the action.
  1460. // Remember that so that when the controls are released again, we can more
  1461. // efficiently determine whether we need to take multiple bound controls into
  1462. // account or not.
  1463. // NOTE: For composites, we have forced triggerControlIndex to the first control
  1464. // in the composite. See above.
  1465. if (trigger.magnitude > 0 && !isControlCurrentlyDrivingTheAction && actionState->magnitude > 0)
  1466. actionState->hasMultipleConcurrentActuations = true;
  1467. // Keep recorded magnitude in action state up to date.
  1468. actionState->magnitude = trigger.magnitude;
  1469. Profiler.EndSample();
  1470. return false;
  1471. }
  1472. // If the control is actuated *less* then the current level of actuation we
  1473. // recorded for the action *and* the control that changed is the one that is currently
  1474. // driving the action, we have to check whether there is another actuation
  1475. // that is now *higher* than what we're getting from the current control.
  1476. if (trigger.magnitude < actionState->magnitude)
  1477. {
  1478. // If we're not currently driving the action, it's simple. Doesn't matter that we lowered
  1479. // actuation as we didn't have the highest actuation anyway.
  1480. if (!isControlCurrentlyDrivingTheAction)
  1481. {
  1482. Profiler.EndSample();
  1483. ////REVIEW: should we *count* actuations instead? (problem is that then we have to reliably determine when a control
  1484. //// first actuates; the current solution will occasionally run conflict resolution when it doesn't have to
  1485. //// but won't require the extra bookkeeping)
  1486. // Do NOT let this control state change affect the action.
  1487. if (trigger.magnitude > 0)
  1488. actionState->hasMultipleConcurrentActuations = true;
  1489. return true;
  1490. }
  1491. // If we don't have multiple controls that are currently actuated, it's simple.
  1492. if (!actionState->hasMultipleConcurrentActuations)
  1493. {
  1494. // Keep recorded magnitude in action state up to date.
  1495. actionState->magnitude = trigger.magnitude;
  1496. Profiler.EndSample();
  1497. return false;
  1498. }
  1499. ////REVIEW: is there a simpler way we can do this???
  1500. // So, now we know we are actually looking at a potential conflict. Multiple
  1501. // controls bound to the action are actuated but we don't yet know whether
  1502. // any of them is actuated *more* than the control that had just changed value.
  1503. // Go through the bindings for the action and see what we've got.
  1504. var bindingStartIndex = GetActionBindingStartIndexAndCount(actionIndex, out var bindingCount);
  1505. var highestActuationLevel = trigger.magnitude;
  1506. var controlWithHighestActuation = kInvalidIndex;
  1507. var bindingWithHighestActuation = kInvalidIndex;
  1508. var numActuations = 0;
  1509. for (var i = 0; i < bindingCount; ++i)
  1510. {
  1511. var bindingIndex = memory.actionBindingIndices[bindingStartIndex + i];
  1512. var binding = &memory.bindingStates[bindingIndex];
  1513. if (binding->isComposite)
  1514. {
  1515. // Composite bindings result in a single actuation value regardless of how
  1516. // many controls are bound through the parts of the composite.
  1517. var firstControlIndex = binding->controlStartIndex;
  1518. var compositeIndex = binding->compositeOrCompositeBindingIndex;
  1519. Debug.Assert(compositeIndex >= 0 && compositeIndex < totalCompositeCount,
  1520. "Composite index out of range on composite");
  1521. var magnitude = memory.compositeMagnitudes[compositeIndex];
  1522. if (magnitude > 0)
  1523. ++numActuations;
  1524. if (magnitude > highestActuationLevel)
  1525. {
  1526. Debug.Assert(firstControlIndex >= 0 && firstControlIndex < totalControlCount,
  1527. "Control start index out of range on composite");
  1528. controlWithHighestActuation = firstControlIndex;
  1529. bindingWithHighestActuation = controlIndexToBindingIndex[firstControlIndex];
  1530. highestActuationLevel = magnitude;
  1531. }
  1532. }
  1533. else if (!binding->isPartOfComposite)
  1534. {
  1535. // Check actuation of each control on the binding.
  1536. for (var n = 0; n < binding->controlCount; ++n)
  1537. {
  1538. var controlIndex = binding->controlStartIndex + n;
  1539. var magnitude = memory.controlMagnitudes[controlIndex];
  1540. if (magnitude > 0)
  1541. ++numActuations;
  1542. if (magnitude > highestActuationLevel)
  1543. {
  1544. controlWithHighestActuation = controlIndex;
  1545. bindingWithHighestActuation = bindingIndex;
  1546. highestActuationLevel = magnitude;
  1547. }
  1548. }
  1549. }
  1550. }
  1551. // Update our record of whether there are multiple concurrent actuations.
  1552. if (numActuations <= 1)
  1553. actionState->hasMultipleConcurrentActuations = false;
  1554. // If we didn't find a control with a higher actuation level, then go and process
  1555. // the control value change.
  1556. if (controlWithHighestActuation != kInvalidIndex)
  1557. {
  1558. // We do have a control with a higher actuation level. Switch from our current
  1559. // control to processing the control with the now highest actuation level.
  1560. //
  1561. // NOTE: We are processing an artificial control state change here. Information
  1562. // such as the timestamp will not correspond to when the control actually
  1563. // changed value. However, if we skip processing this as a separate control
  1564. // change here, interactions may not behave properly as they would not be
  1565. // seeing that we just lowered the actuation level on the action.
  1566. trigger.controlIndex = controlWithHighestActuation;
  1567. trigger.bindingIndex = bindingWithHighestActuation;
  1568. trigger.magnitude = highestActuationLevel;
  1569. // If we're switching to a different binding, we may also have to switch to a
  1570. // different stack of interactions.
  1571. if (actionState->bindingIndex != bindingWithHighestActuation)
  1572. {
  1573. // If there's an interaction currently driving the action, reset it.
  1574. // NOTE: This will also cancel an ongoing timer. So, say we're currently 0.5 seconds into
  1575. // a 1 second "Hold" when the user shifts to a different control, then this code here
  1576. // will *cancel* the current "Hold" and restart from scratch.
  1577. if (actionState->interactionIndex != kInvalidIndex)
  1578. ResetInteractionState(actionState->interactionIndex);
  1579. // If there's an interaction in progress on the new binding, let
  1580. // it drive the action.
  1581. var bindingState = &bindingStates[bindingWithHighestActuation];
  1582. var interactionCount = bindingState->interactionCount;
  1583. var interactionStartIndex = bindingState->interactionStartIndex;
  1584. for (var i = 0; i < interactionCount; ++i)
  1585. {
  1586. if (!interactionStates[interactionStartIndex + i].phase.IsInProgress())
  1587. continue;
  1588. actionState->interactionIndex = interactionStartIndex + i;
  1589. trigger.interactionIndex = interactionStartIndex + i;
  1590. break;
  1591. }
  1592. }
  1593. // We're switching the action to a different control so regardless of whether
  1594. // the processing of the control state change results in a call to ChangePhaseOfAction,
  1595. // we need to record this or the disambiguation code may start ignoring valid input.
  1596. actionState->controlIndex = controlWithHighestActuation;
  1597. actionState->bindingIndex = bindingWithHighestActuation;
  1598. actionState->magnitude = highestActuationLevel;
  1599. Profiler.EndSample();
  1600. return false;
  1601. }
  1602. }
  1603. Profiler.EndSample();
  1604. // If we're not really effecting any change on the action, ignore the control state change.
  1605. // NOTE: We may be looking at a control here that points in a completely direction, for example, even
  1606. // though it has the same magnitude. However, we require a control to *increase* absolute actuation
  1607. // before we let it drive the action.
  1608. if (!isControlCurrentlyDrivingTheAction && Mathf.Approximately(trigger.magnitude, actionState->magnitude))
  1609. {
  1610. // If we do have an actuation on a control that isn't currently driving the action, flag the action has
  1611. // having multiple concurrent inputs ATM.
  1612. if (trigger.magnitude > 0)
  1613. actionState->hasMultipleConcurrentActuations = true;
  1614. return true;
  1615. }
  1616. return false;
  1617. }
  1618. private ushort GetActionBindingStartIndexAndCount(int actionIndex, out ushort bindingCount)
  1619. {
  1620. bindingCount = memory.actionBindingIndicesAndCounts[actionIndex * 2 + 1];
  1621. return memory.actionBindingIndicesAndCounts[actionIndex * 2];
  1622. }
  1623. /// <summary>
  1624. /// When there is no interaction on an action, this method perform the default interaction logic that we
  1625. /// run when a bound control changes value.
  1626. /// </summary>
  1627. /// <param name="trigger">Control trigger state.</param>
  1628. /// <param name="actionIndex"></param>
  1629. /// <remarks>
  1630. /// The default interaction does not have its own <see cref="InteractionState"/>. Whatever we do in here,
  1631. /// we store directly on the action state.
  1632. ///
  1633. /// The default interaction is basically a sort of optimization where we don't require having an explicit
  1634. /// interaction object. Conceptually, it can be thought of, however, as putting this interaction on any
  1635. /// binding that doesn't have any other interaction on it.
  1636. /// </remarks>
  1637. private void ProcessDefaultInteraction(ref TriggerState trigger, int actionIndex)
  1638. {
  1639. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  1640. "Action index out of range when processing default interaction");
  1641. var actionState = &actionStates[actionIndex];
  1642. switch (actionState->phase)
  1643. {
  1644. case InputActionPhase.Waiting:
  1645. {
  1646. // Pass-through actions we perform on every value change and then go back
  1647. // to waiting.
  1648. if (trigger.isPassThrough)
  1649. {
  1650. ChangePhaseOfAction(InputActionPhase.Performed, ref trigger,
  1651. phaseAfterPerformedOrCanceled: InputActionPhase.Waiting);
  1652. break;
  1653. }
  1654. // Button actions need to cross the button-press threshold.
  1655. if (trigger.isButton)
  1656. {
  1657. var actuation = trigger.magnitude;
  1658. if (actuation > 0)
  1659. ChangePhaseOfAction(InputActionPhase.Started, ref trigger);
  1660. var threshold = controls[trigger.controlIndex] is ButtonControl button ? button.pressPointOrDefault : ButtonControl.s_GlobalDefaultButtonPressPoint;
  1661. if (actuation >= threshold)
  1662. {
  1663. ChangePhaseOfAction(InputActionPhase.Performed, ref trigger,
  1664. phaseAfterPerformedOrCanceled: InputActionPhase.Performed);
  1665. }
  1666. }
  1667. else
  1668. {
  1669. // Value-type action.
  1670. // Ignore if the control has not crossed its actuation threshold.
  1671. if (IsActuated(ref trigger))
  1672. {
  1673. ////REVIEW: Why is it we don't stay in performed but rather go back to started all the time?
  1674. // Go into started, then perform and then go back to started.
  1675. ChangePhaseOfAction(InputActionPhase.Started, ref trigger);
  1676. ChangePhaseOfAction(InputActionPhase.Performed, ref trigger,
  1677. phaseAfterPerformedOrCanceled: InputActionPhase.Started);
  1678. }
  1679. }
  1680. break;
  1681. }
  1682. case InputActionPhase.Started:
  1683. {
  1684. if (actionState->isButton)
  1685. {
  1686. var actuation = trigger.magnitude;
  1687. var threshold = controls[trigger.controlIndex] is ButtonControl button ? button.pressPointOrDefault : ButtonControl.s_GlobalDefaultButtonPressPoint;
  1688. if (actuation >= threshold)
  1689. {
  1690. // Button crossed press threshold. Perform.
  1691. ChangePhaseOfAction(InputActionPhase.Performed, ref trigger,
  1692. phaseAfterPerformedOrCanceled: InputActionPhase.Performed);
  1693. }
  1694. else if (Mathf.Approximately(actuation, 0))
  1695. {
  1696. // Button is no longer actuated. Never reached threshold to perform.
  1697. // Cancel.
  1698. ChangePhaseOfAction(InputActionPhase.Canceled, ref trigger);
  1699. }
  1700. }
  1701. else
  1702. {
  1703. if (!IsActuated(ref trigger))
  1704. {
  1705. // Control went back to below actuation threshold. Cancel interaction.
  1706. ChangePhaseOfAction(InputActionPhase.Canceled, ref trigger);
  1707. }
  1708. else
  1709. {
  1710. // Control changed value above magnitude threshold. Perform and remain started.
  1711. ChangePhaseOfAction(InputActionPhase.Performed, ref trigger,
  1712. phaseAfterPerformedOrCanceled: InputActionPhase.Started);
  1713. }
  1714. }
  1715. break;
  1716. }
  1717. case InputActionPhase.Performed:
  1718. {
  1719. if (actionState->isButton)
  1720. {
  1721. var actuation = trigger.magnitude;
  1722. var pressPoint = controls[trigger.controlIndex] is ButtonControl button ? button.pressPointOrDefault : ButtonControl.s_GlobalDefaultButtonPressPoint;
  1723. if (Mathf.Approximately(0f, actuation))
  1724. {
  1725. ChangePhaseOfAction(InputActionPhase.Canceled, ref trigger);
  1726. }
  1727. else
  1728. {
  1729. var threshold = pressPoint * ButtonControl.s_GlobalDefaultButtonReleaseThreshold;
  1730. if (actuation <= threshold)
  1731. {
  1732. // Button released to below threshold but not fully released.
  1733. ChangePhaseOfAction(InputActionPhase.Started, ref trigger);
  1734. }
  1735. }
  1736. }
  1737. else if (actionState->isPassThrough)
  1738. {
  1739. ////REVIEW: even for pass-through actions, shouldn't we cancel when seeing a default value?
  1740. ChangePhaseOfAction(InputActionPhase.Performed, ref trigger,
  1741. phaseAfterPerformedOrCanceled: InputActionPhase.Performed);
  1742. }
  1743. break;
  1744. }
  1745. default:
  1746. Debug.Assert(false, "Should not get here");
  1747. break;
  1748. }
  1749. }
  1750. private void ProcessInteractions(ref TriggerState trigger, int interactionStartIndex, int interactionCount)
  1751. {
  1752. var context = new InputInteractionContext
  1753. {
  1754. m_State = this,
  1755. m_TriggerState = trigger
  1756. };
  1757. for (var i = 0; i < interactionCount; ++i)
  1758. {
  1759. var index = interactionStartIndex + i;
  1760. var state = interactionStates[index];
  1761. var interaction = interactions[index];
  1762. context.m_TriggerState.phase = state.phase;
  1763. context.m_TriggerState.startTime = state.startTime;
  1764. context.m_TriggerState.interactionIndex = index;
  1765. interaction.Process(ref context);
  1766. }
  1767. }
  1768. private void ProcessTimeout(double time, int mapIndex, int controlIndex, int bindingIndex, int interactionIndex)
  1769. {
  1770. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index out of range");
  1771. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1772. Debug.Assert(interactionIndex >= 0 && interactionIndex < totalInteractionCount, "Interaction index out of range");
  1773. ref var currentState = ref interactionStates[interactionIndex];
  1774. var context = new InputInteractionContext
  1775. {
  1776. m_State = this,
  1777. m_TriggerState =
  1778. new TriggerState
  1779. {
  1780. phase = currentState.phase,
  1781. time = time,
  1782. mapIndex = mapIndex,
  1783. controlIndex = controlIndex,
  1784. bindingIndex = bindingIndex,
  1785. interactionIndex = interactionIndex,
  1786. startTime = currentState.startTime
  1787. },
  1788. timerHasExpired = true,
  1789. };
  1790. currentState.isTimerRunning = false;
  1791. currentState.totalTimeoutCompletionTimeRemaining =
  1792. Mathf.Max(currentState.totalTimeoutCompletionTimeRemaining - currentState.timerDuration, 0);
  1793. currentState.timerDuration = default;
  1794. // Let interaction handle timer expiration.
  1795. interactions[interactionIndex].Process(ref context);
  1796. }
  1797. internal void SetTotalTimeoutCompletionTime(float seconds, ref TriggerState trigger)
  1798. {
  1799. Debug.Assert(trigger.interactionIndex >= 0 && trigger.interactionIndex < totalInteractionCount, "Interaction index out of range");
  1800. ref var interactionState = ref interactionStates[trigger.interactionIndex];
  1801. interactionState.totalTimeoutCompletionDone = 0;
  1802. interactionState.totalTimeoutCompletionTimeRemaining = seconds;
  1803. }
  1804. internal void StartTimeout(float seconds, ref TriggerState trigger)
  1805. {
  1806. Debug.Assert(trigger.mapIndex >= 0 && trigger.mapIndex < totalMapCount, "Map index out of range");
  1807. Debug.Assert(trigger.controlIndex >= 0 && trigger.controlIndex < totalControlCount, "Control index out of range");
  1808. Debug.Assert(trigger.interactionIndex >= 0 && trigger.interactionIndex < totalInteractionCount, "Interaction index out of range");
  1809. var manager = InputSystem.s_Manager;
  1810. var currentTime = trigger.time;
  1811. var control = controls[trigger.controlIndex];
  1812. var interactionIndex = trigger.interactionIndex;
  1813. var monitorIndex =
  1814. ToCombinedMapAndControlAndBindingIndex(trigger.mapIndex, trigger.controlIndex, trigger.bindingIndex);
  1815. // If there's already a timeout running, cancel it first.
  1816. ref var interactionState = ref interactionStates[interactionIndex];
  1817. if (interactionState.isTimerRunning)
  1818. StopTimeout(interactionIndex);
  1819. // Add new timeout.
  1820. manager.AddStateChangeMonitorTimeout(control, this, currentTime + seconds, monitorIndex,
  1821. interactionIndex);
  1822. // Update state.
  1823. interactionState.isTimerRunning = true;
  1824. interactionState.timerStartTime = currentTime;
  1825. interactionState.timerDuration = seconds;
  1826. interactionState.timerMonitorIndex = monitorIndex;
  1827. }
  1828. private void StopTimeout(int interactionIndex)
  1829. {
  1830. Debug.Assert(interactionIndex >= 0 && interactionIndex < totalInteractionCount, "Interaction index out of range");
  1831. ref var interactionState = ref interactionStates[interactionIndex];
  1832. var manager = InputSystem.s_Manager;
  1833. manager.RemoveStateChangeMonitorTimeout(this, interactionState.timerMonitorIndex, interactionIndex);
  1834. // Update state.
  1835. interactionState.isTimerRunning = false;
  1836. interactionState.totalTimeoutCompletionDone += interactionState.timerDuration;
  1837. interactionState.totalTimeoutCompletionTimeRemaining =
  1838. Mathf.Max(interactionState.totalTimeoutCompletionTimeRemaining - interactionState.timerDuration, 0);
  1839. interactionState.timerDuration = default;
  1840. interactionState.timerStartTime = default;
  1841. interactionState.timerMonitorIndex = default;
  1842. }
  1843. /// <summary>
  1844. /// Perform a phase change on the given interaction. Only visible to observers
  1845. /// if it happens to change the phase of the action, too.
  1846. /// </summary>
  1847. /// <param name="newPhase">New phase to transition the interaction to.</param>
  1848. /// <param name="trigger">Information about the binding and control that triggered the phase change.</param>
  1849. /// <param name="phaseAfterPerformed">If <paramref name="newPhase"/> is <see cref="InputActionPhase.Performed"/>,
  1850. /// this determines which phase to transition to after the action has been performed. This would usually be
  1851. /// <see cref="InputActionPhase.Waiting"/> (default), <see cref="InputActionPhase.Started"/> (if the action is supposed
  1852. /// to be oscillate between started and performed), or <see cref="InputActionPhase.Performed"/> (if the action is
  1853. /// supposed to perform over and over again until canceled).</param>
  1854. /// <param name="phaseAfterCanceled">If <paramref name="newPhase"/> is <see cref="InputActionPhase.Canceled"/>,
  1855. /// this determines which phase to transition to after the action has been canceled.</param>
  1856. /// <param name="processNextInteractionOnCancel">Indicates if the system should try and change the phase of other
  1857. /// interactions on the same action that are already started or performed after cancelling this interaction. This should be
  1858. /// false when resetting interactions.</param>
  1859. /// <remarks>
  1860. /// Multiple interactions on the same binding can be started concurrently but the
  1861. /// first interaction that starts will get to drive an action until it either cancels
  1862. /// or performs the action.
  1863. ///
  1864. /// If an interaction driving an action performs it, all interactions will reset and
  1865. /// go back waiting.
  1866. ///
  1867. /// If an interaction driving an action cancels it, the next interaction in the list which
  1868. /// has already started will get to drive the action (example: a TapInteraction and a
  1869. /// SlowTapInteraction both start and the TapInteraction gets to drive the action because
  1870. /// it comes first; then the TapInteraction cancels because the button is held for too
  1871. /// long and the SlowTapInteraction will get to drive the action next).
  1872. /// </remarks>
  1873. internal void ChangePhaseOfInteraction(InputActionPhase newPhase, ref TriggerState trigger,
  1874. InputActionPhase phaseAfterPerformed = InputActionPhase.Waiting,
  1875. InputActionPhase phaseAfterCanceled = InputActionPhase.Waiting,
  1876. bool processNextInteractionOnCancel = true)
  1877. {
  1878. var interactionIndex = trigger.interactionIndex;
  1879. var bindingIndex = trigger.bindingIndex;
  1880. Debug.Assert(interactionIndex >= 0 && interactionIndex < totalInteractionCount, "Interaction index out of range");
  1881. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  1882. ////TODO: need to make sure that performed and canceled phase changes happen on the *same* binding&control
  1883. //// as the start of the phase
  1884. var phaseAfterPerformedOrCanceled = InputActionPhase.Waiting;
  1885. if (newPhase == InputActionPhase.Performed)
  1886. phaseAfterPerformedOrCanceled = phaseAfterPerformed;
  1887. else if (newPhase == InputActionPhase.Canceled)
  1888. phaseAfterPerformedOrCanceled = phaseAfterCanceled;
  1889. // Any time an interaction changes phase, we cancel all pending timeouts.
  1890. ref var interactionState = ref interactionStates[interactionIndex];
  1891. if (interactionState.isTimerRunning)
  1892. StopTimeout(trigger.interactionIndex);
  1893. // Update interaction state.
  1894. interactionState.phase = newPhase;
  1895. interactionState.triggerControlIndex = trigger.controlIndex;
  1896. interactionState.startTime = trigger.startTime;
  1897. if (newPhase == InputActionPhase.Performed)
  1898. interactionState.performedTime = trigger.time;
  1899. // See if it affects the phase of an associated action.
  1900. var actionIndex = bindingStates[bindingIndex].actionIndex; // We already had to tap this array and entry in ProcessControlStateChange.
  1901. if (actionIndex != -1)
  1902. {
  1903. if (actionStates[actionIndex].phase == InputActionPhase.Waiting)
  1904. {
  1905. // We're the first interaction to go to the start phase.
  1906. if (!ChangePhaseOfAction(newPhase, ref trigger, phaseAfterPerformedOrCanceled))
  1907. return;
  1908. }
  1909. else if (newPhase == InputActionPhase.Canceled && actionStates[actionIndex].interactionIndex == trigger.interactionIndex)
  1910. {
  1911. // We're canceling but maybe there's another interaction ready
  1912. // to go into start phase. *Or* there's an interaction that has
  1913. // already performed.
  1914. if (!ChangePhaseOfAction(newPhase, ref trigger, phaseAfterPerformedOrCanceled))
  1915. return;
  1916. if (processNextInteractionOnCancel == false)
  1917. return;
  1918. var interactionStartIndex = bindingStates[bindingIndex].interactionStartIndex;
  1919. var numInteractions = bindingStates[bindingIndex].interactionCount;
  1920. for (var i = 0; i < numInteractions; ++i)
  1921. {
  1922. var index = interactionStartIndex + i;
  1923. if (index != trigger.interactionIndex && (interactionStates[index].phase == InputActionPhase.Started ||
  1924. interactionStates[index].phase == InputActionPhase.Performed))
  1925. {
  1926. // Trigger start.
  1927. var startTime = interactionStates[index].startTime;
  1928. var triggerForInteraction = new TriggerState
  1929. {
  1930. phase = InputActionPhase.Started,
  1931. controlIndex = interactionStates[index].triggerControlIndex,
  1932. bindingIndex = trigger.bindingIndex,
  1933. interactionIndex = index,
  1934. mapIndex = trigger.mapIndex,
  1935. time = startTime,
  1936. startTime = startTime,
  1937. };
  1938. if (!ChangePhaseOfAction(InputActionPhase.Started, ref triggerForInteraction, phaseAfterPerformedOrCanceled))
  1939. return;
  1940. // If the interaction has already performed, trigger it now.
  1941. if (interactionStates[index].phase == InputActionPhase.Performed)
  1942. {
  1943. triggerForInteraction = new TriggerState
  1944. {
  1945. phase = InputActionPhase.Performed,
  1946. controlIndex = interactionStates[index].triggerControlIndex,
  1947. bindingIndex = trigger.bindingIndex,
  1948. interactionIndex = index,
  1949. mapIndex = trigger.mapIndex,
  1950. time = interactionStates[index].performedTime, // Time when the interaction performed.
  1951. startTime = startTime,
  1952. };
  1953. if (!ChangePhaseOfAction(InputActionPhase.Performed, ref triggerForInteraction, phaseAfterPerformedOrCanceled))
  1954. return;
  1955. }
  1956. break;
  1957. }
  1958. }
  1959. }
  1960. else if (actionStates[actionIndex].interactionIndex == trigger.interactionIndex)
  1961. {
  1962. // Any other phase change goes to action if we're the interaction driving
  1963. // the current phase.
  1964. if (!ChangePhaseOfAction(newPhase, ref trigger, phaseAfterPerformedOrCanceled))
  1965. return;
  1966. // We're the interaction driving the action and we performed the action,
  1967. // so reset any other interaction to waiting state.
  1968. if (newPhase == InputActionPhase.Performed)
  1969. {
  1970. var interactionStartIndex = bindingStates[bindingIndex].interactionStartIndex;
  1971. var numInteractions = bindingStates[bindingIndex].interactionCount;
  1972. for (var i = 0; i < numInteractions; ++i)
  1973. {
  1974. var index = interactionStartIndex + i;
  1975. if (index != trigger.interactionIndex)
  1976. ResetInteractionState(index);
  1977. }
  1978. }
  1979. }
  1980. }
  1981. // If the interaction performed or canceled, go back to waiting.
  1982. // Exception: if it was performed and we're to remain in started state, set the interaction
  1983. // to started. Note that for that phase transition, there are no callbacks being
  1984. // triggered (i.e. we don't call 'started' every time after 'performed').
  1985. if (newPhase == InputActionPhase.Performed && actionStates[actionIndex].interactionIndex != trigger.interactionIndex)
  1986. {
  1987. // We performed but we're not the interaction driving the action. We want to stay performed to make
  1988. // sure that if the interaction that is currently driving the action cancels, we get to perform
  1989. // the action. If we go back to waiting here, then the system can't tell that there's another interaction
  1990. // ready to perform (in fact, that has already performed).
  1991. }
  1992. else if (newPhase == InputActionPhase.Performed && phaseAfterPerformed != InputActionPhase.Waiting)
  1993. {
  1994. interactionState.phase = phaseAfterPerformed;
  1995. }
  1996. else if (newPhase == InputActionPhase.Performed || newPhase == InputActionPhase.Canceled)
  1997. {
  1998. ResetInteractionState(trigger.interactionIndex);
  1999. }
  2000. }
  2001. /// <summary>
  2002. /// Change the current phase of the action referenced by <paramref name="trigger"/> to <paramref name="newPhase"/>.
  2003. /// </summary>
  2004. /// <param name="newPhase">New phase to transition to.</param>
  2005. /// <param name="trigger">Trigger that caused the change in phase.</param>
  2006. /// <param name="phaseAfterPerformedOrCanceled">The phase to immediately transition to after <paramref name="newPhase"/>
  2007. /// when that is <see cref="InputActionPhase.Performed"/> or <see cref="InputActionPhase.Canceled"/> (<see cref="InputActionPhase.Waiting"/>
  2008. /// by default).</param>
  2009. /// <remarks>
  2010. /// The change in phase is visible to observers, i.e. on the various callbacks and notifications.
  2011. ///
  2012. /// If <paramref name="newPhase"/> is <see cref="InputActionPhase.Performed"/> or <see cref="InputActionPhase.Canceled"/>,
  2013. /// the action will subsequently immediately transition to <paramref name="phaseAfterPerformedOrCanceled"/>
  2014. /// (<see cref="InputActionPhase.Waiting"/> by default). This change is not visible to observers, i.e. there won't
  2015. /// be another run through callbacks.
  2016. /// </remarks>
  2017. private bool ChangePhaseOfAction(InputActionPhase newPhase, ref TriggerState trigger,
  2018. InputActionPhase phaseAfterPerformedOrCanceled = InputActionPhase.Waiting)
  2019. {
  2020. Debug.Assert(newPhase != InputActionPhase.Disabled, "Should not disable an action using this method");
  2021. Debug.Assert(trigger.mapIndex >= 0 && trigger.mapIndex < totalMapCount, "Map index out of range");
  2022. Debug.Assert(trigger.controlIndex >= 0 && trigger.controlIndex < totalControlCount, "Control index out of range");
  2023. Debug.Assert(trigger.bindingIndex >= 0 && trigger.bindingIndex < totalBindingCount, "Binding index out of range");
  2024. var actionIndex = bindingStates[trigger.bindingIndex].actionIndex;
  2025. if (actionIndex == kInvalidIndex)
  2026. return true; // No action associated with binding.
  2027. // Ignore if action is disabled.
  2028. var actionState = &actionStates[actionIndex];
  2029. if (actionState->isDisabled)
  2030. return true;
  2031. // We mark the action as in-processing while we execute its phase transitions and perform
  2032. // callbacks. The callbacks may alter system state such that the action may get disabled
  2033. // (and potentially re-enabled) while the callback is in progress. We need to make sure that
  2034. // if that happens, we don't go and then do more processing on the action.
  2035. actionState->inProcessing = true;
  2036. try
  2037. {
  2038. // Enforce transition constraints.
  2039. if (actionState->isPassThrough && trigger.interactionIndex == kInvalidIndex)
  2040. {
  2041. // No constraints on pass-through actions except if there are interactions driving the action.
  2042. ChangePhaseOfActionInternal(actionIndex, actionState, newPhase, ref trigger,
  2043. isDisablingAction: newPhase == InputActionPhase.Canceled && phaseAfterPerformedOrCanceled == InputActionPhase.Disabled);
  2044. if (!actionState->inProcessing)
  2045. return false;
  2046. }
  2047. else if (newPhase == InputActionPhase.Performed && actionState->phase == InputActionPhase.Waiting)
  2048. {
  2049. // Going from waiting to performed, we make a detour via started.
  2050. ChangePhaseOfActionInternal(actionIndex, actionState, InputActionPhase.Started, ref trigger);
  2051. if (!actionState->inProcessing)
  2052. return false;
  2053. // Then we perform.
  2054. ChangePhaseOfActionInternal(actionIndex, actionState, newPhase, ref trigger);
  2055. if (!actionState->inProcessing)
  2056. return false;
  2057. // And finally, if we're going back to waiting, we make a detour via canceled.
  2058. if (phaseAfterPerformedOrCanceled == InputActionPhase.Waiting)
  2059. ChangePhaseOfActionInternal(actionIndex, actionState, InputActionPhase.Canceled, ref trigger);
  2060. if (!actionState->inProcessing)
  2061. return false;
  2062. actionState->phase = phaseAfterPerformedOrCanceled;
  2063. }
  2064. else if (actionState->phase != newPhase || newPhase == InputActionPhase.Performed) // We allow Performed to trigger repeatedly.
  2065. {
  2066. ChangePhaseOfActionInternal(actionIndex, actionState, newPhase, ref trigger,
  2067. isDisablingAction: newPhase == InputActionPhase.Canceled && phaseAfterPerformedOrCanceled == InputActionPhase.Disabled);
  2068. if (!actionState->inProcessing)
  2069. return false;
  2070. if (newPhase == InputActionPhase.Performed || newPhase == InputActionPhase.Canceled)
  2071. actionState->phase = phaseAfterPerformedOrCanceled;
  2072. }
  2073. }
  2074. finally
  2075. {
  2076. actionState->inProcessing = false;
  2077. }
  2078. // If we're now waiting, reset control state. This is important for the disambiguation code
  2079. // to not consider whatever control actuation happened on the action last.
  2080. if (actionState->phase == InputActionPhase.Waiting)
  2081. {
  2082. actionState->controlIndex = kInvalidIndex;
  2083. actionState->flags &= ~TriggerState.Flags.HaveMagnitude;
  2084. }
  2085. return true;
  2086. }
  2087. private void ChangePhaseOfActionInternal(int actionIndex, TriggerState* actionState, InputActionPhase newPhase, ref TriggerState trigger, bool isDisablingAction = false)
  2088. {
  2089. Debug.Assert(trigger.mapIndex == actionState->mapIndex,
  2090. "Map index on trigger does not correspond to map index of trigger state");
  2091. // Update action state.
  2092. var newState = trigger;
  2093. // We need to make sure here that any HaveMagnitude flag we may be carrying over from actionState
  2094. // is handled correctly (case 1239551).
  2095. newState.flags = actionState->flags; // Preserve flags.
  2096. if (newPhase != InputActionPhase.Canceled)
  2097. newState.magnitude = trigger.magnitude;
  2098. else
  2099. newState.magnitude = 0f;
  2100. newState.phase = newPhase;
  2101. if (newPhase == InputActionPhase.Performed)
  2102. {
  2103. newState.lastPerformedInUpdate = InputUpdate.s_UpdateStepCount;
  2104. newState.lastCanceledInUpdate = actionState->lastCanceledInUpdate;
  2105. // When we perform an action, we mark the event handled such that FireStateChangeNotifications()
  2106. // can then reset state monitors in the same group.
  2107. // NOTE: We don't consume for controls at binding complexity 1. Those we fire in unison.
  2108. if (controlGroupingAndComplexity[trigger.controlIndex * 2 + 1] > 1 &&
  2109. // we can end up switching to performed state from an interaction with a timeout, at which point
  2110. // the original event will probably have been removed from memory, so make sure to check
  2111. // we still have one
  2112. m_CurrentlyProcessingThisEvent.valid)
  2113. m_CurrentlyProcessingThisEvent.handled = true;
  2114. }
  2115. else if (newPhase == InputActionPhase.Canceled)
  2116. {
  2117. newState.lastCanceledInUpdate = InputUpdate.s_UpdateStepCount;
  2118. newState.lastPerformedInUpdate = actionState->lastPerformedInUpdate;
  2119. }
  2120. else
  2121. {
  2122. newState.lastPerformedInUpdate = actionState->lastPerformedInUpdate;
  2123. newState.lastCanceledInUpdate = actionState->lastCanceledInUpdate;
  2124. }
  2125. // When we go from Performed to Disabling, we take a detour through Canceled.
  2126. // To replicate the behavior of releasedInUpdate where it doesn't get updated when the action is disabled
  2127. // from being performed, we skip updating lastCompletedInUpdate if Disabled is the phase after Canceled.
  2128. if (actionState->phase == InputActionPhase.Performed && newPhase != InputActionPhase.Performed && !isDisablingAction)
  2129. newState.lastCompletedInUpdate = InputUpdate.s_UpdateStepCount;
  2130. else
  2131. newState.lastCompletedInUpdate = actionState->lastCompletedInUpdate;
  2132. newState.pressedInUpdate = actionState->pressedInUpdate;
  2133. newState.releasedInUpdate = actionState->releasedInUpdate;
  2134. if (newPhase == InputActionPhase.Started)
  2135. newState.startTime = newState.time;
  2136. *actionState = newState;
  2137. // Let listeners know.
  2138. var map = maps[trigger.mapIndex];
  2139. Debug.Assert(actionIndex >= mapIndices[trigger.mapIndex].actionStartIndex,
  2140. "actionIndex is below actionStartIndex for map that the action belongs to");
  2141. var action = map.m_Actions[actionIndex - mapIndices[trigger.mapIndex].actionStartIndex];
  2142. trigger.phase = newPhase;
  2143. switch (newPhase)
  2144. {
  2145. case InputActionPhase.Started:
  2146. {
  2147. Debug.Assert(trigger.controlIndex != -1, "Must have control to start an action");
  2148. CallActionListeners(actionIndex, map, newPhase, ref action.m_OnStarted, "started");
  2149. break;
  2150. }
  2151. case InputActionPhase.Performed:
  2152. {
  2153. Debug.Assert(trigger.controlIndex != -1, "Must have control to perform an action");
  2154. CallActionListeners(actionIndex, map, newPhase, ref action.m_OnPerformed, "performed");
  2155. break;
  2156. }
  2157. case InputActionPhase.Canceled:
  2158. {
  2159. Debug.Assert(trigger.controlIndex != -1, "When canceling, must have control that started action");
  2160. CallActionListeners(actionIndex, map, newPhase, ref action.m_OnCanceled, "canceled");
  2161. break;
  2162. }
  2163. }
  2164. }
  2165. private void CallActionListeners(int actionIndex, InputActionMap actionMap, InputActionPhase phase, ref CallbackArray<InputActionListener> listeners, string callbackName)
  2166. {
  2167. // If there's no listeners, don't bother with anything else.
  2168. var callbacksOnMap = actionMap.m_ActionCallbacks;
  2169. if (listeners.length == 0 && callbacksOnMap.length == 0 && s_GlobalState.onActionChange.length == 0)
  2170. return;
  2171. var context = new InputAction.CallbackContext
  2172. {
  2173. m_State = this,
  2174. m_ActionIndex = actionIndex,
  2175. };
  2176. Profiler.BeginSample("InputActionCallback");
  2177. // Global callback goes first.
  2178. var action = context.action;
  2179. if (s_GlobalState.onActionChange.length > 0)
  2180. {
  2181. InputActionChange change;
  2182. switch (phase)
  2183. {
  2184. case InputActionPhase.Started:
  2185. change = InputActionChange.ActionStarted;
  2186. break;
  2187. case InputActionPhase.Performed:
  2188. change = InputActionChange.ActionPerformed;
  2189. break;
  2190. case InputActionPhase.Canceled:
  2191. change = InputActionChange.ActionCanceled;
  2192. break;
  2193. default:
  2194. Debug.Assert(false, "Should not reach here");
  2195. return;
  2196. }
  2197. DelegateHelpers.InvokeCallbacksSafe(ref s_GlobalState.onActionChange, action, change, "InputSystem.onActionChange");
  2198. }
  2199. // Run callbacks (if any) directly on action.
  2200. DelegateHelpers.InvokeCallbacksSafe(ref listeners, context, callbackName, action);
  2201. // Run callbacks (if any) on action map.
  2202. DelegateHelpers.InvokeCallbacksSafe(ref callbacksOnMap, context, callbackName, actionMap);
  2203. Profiler.EndSample();
  2204. }
  2205. private object GetActionOrNoneString(ref TriggerState trigger)
  2206. {
  2207. var action = GetActionOrNull(ref trigger);
  2208. if (action == null)
  2209. return "<none>";
  2210. return action;
  2211. }
  2212. internal InputAction GetActionOrNull(int bindingIndex)
  2213. {
  2214. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  2215. var actionIndex = bindingStates[bindingIndex].actionIndex;
  2216. if (actionIndex == kInvalidIndex)
  2217. return null;
  2218. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount,
  2219. "Action index out of range when getting action");
  2220. var mapIndex = bindingStates[bindingIndex].mapIndex;
  2221. var actionStartIndex = mapIndices[mapIndex].actionStartIndex;
  2222. return maps[mapIndex].m_Actions[actionIndex - actionStartIndex];
  2223. }
  2224. internal InputAction GetActionOrNull(ref TriggerState trigger)
  2225. {
  2226. Debug.Assert(trigger.mapIndex >= 0 && trigger.mapIndex < totalMapCount, "Map index out of range");
  2227. Debug.Assert(trigger.bindingIndex >= 0 && trigger.bindingIndex < totalBindingCount, "Binding index out of range");
  2228. var actionIndex = bindingStates[trigger.bindingIndex].actionIndex;
  2229. if (actionIndex == kInvalidIndex)
  2230. return null;
  2231. Debug.Assert(actionIndex >= 0 && actionIndex < totalActionCount, "Action index out of range");
  2232. var actionStartIndex = mapIndices[trigger.mapIndex].actionStartIndex;
  2233. return maps[trigger.mapIndex].m_Actions[actionIndex - actionStartIndex];
  2234. }
  2235. internal InputControl GetControl(ref TriggerState trigger)
  2236. {
  2237. Debug.Assert(trigger.controlIndex != kInvalidIndex, "Control index is invalid");
  2238. Debug.Assert(trigger.controlIndex >= 0 && trigger.controlIndex < totalControlCount, "Control index out of range");
  2239. return controls[trigger.controlIndex];
  2240. }
  2241. private IInputInteraction GetInteractionOrNull(ref TriggerState trigger)
  2242. {
  2243. if (trigger.interactionIndex == kInvalidIndex)
  2244. return null;
  2245. Debug.Assert(trigger.interactionIndex >= 0 && trigger.interactionIndex < totalInteractionCount, "Interaction index out of range");
  2246. return interactions[trigger.interactionIndex];
  2247. }
  2248. internal int GetBindingIndexInMap(int bindingIndex)
  2249. {
  2250. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  2251. var mapIndex = bindingStates[bindingIndex].mapIndex;
  2252. var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
  2253. return bindingIndex - bindingStartIndex;
  2254. }
  2255. internal int GetBindingIndexInState(int mapIndex, int bindingIndexInMap)
  2256. {
  2257. var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
  2258. return bindingStartIndex + bindingIndexInMap;
  2259. }
  2260. // Iterators may not use unsafe code so do the detour here.
  2261. internal ref BindingState GetBindingState(int bindingIndex)
  2262. {
  2263. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  2264. return ref bindingStates[bindingIndex];
  2265. }
  2266. internal ref InputBinding GetBinding(int bindingIndex)
  2267. {
  2268. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  2269. var mapIndex = bindingStates[bindingIndex].mapIndex;
  2270. var bindingStartIndex = mapIndices[mapIndex].bindingStartIndex;
  2271. return ref maps[mapIndex].m_Bindings[bindingIndex - bindingStartIndex];
  2272. }
  2273. internal InputActionMap GetActionMap(int bindingIndex)
  2274. {
  2275. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  2276. var mapIndex = bindingStates[bindingIndex].mapIndex;
  2277. return maps[mapIndex];
  2278. }
  2279. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "mapIndex", Justification = "Keep this for future implementation")]
  2280. private void ResetInteractionStateAndCancelIfNecessary(int mapIndex, int bindingIndex, int interactionIndex, InputActionPhase phaseAfterCanceled)
  2281. {
  2282. Debug.Assert(interactionIndex >= 0 && interactionIndex < totalInteractionCount, "Interaction index out of range");
  2283. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  2284. // If interaction is currently driving an action and it has been started or performed,
  2285. // cancel it.
  2286. //
  2287. // NOTE: We could just blindly call ChangePhaseOfInteraction() and it would handle the case of
  2288. // when the interaction is currently driving the action automatically. However, doing so
  2289. // would give other interactions a chance to take over which is something we don't want to
  2290. // happen when resetting actions.
  2291. var actionIndex = bindingStates[bindingIndex].actionIndex;
  2292. if (actionStates[actionIndex].interactionIndex == interactionIndex)
  2293. {
  2294. switch (interactionStates[interactionIndex].phase)
  2295. {
  2296. case InputActionPhase.Started:
  2297. case InputActionPhase.Performed:
  2298. ChangePhaseOfInteraction(InputActionPhase.Canceled, ref actionStates[actionIndex],
  2299. phaseAfterCanceled: phaseAfterCanceled,
  2300. processNextInteractionOnCancel: false);
  2301. break;
  2302. }
  2303. actionStates[actionIndex].interactionIndex = kInvalidIndex;
  2304. }
  2305. ResetInteractionState(interactionIndex);
  2306. }
  2307. private void ResetInteractionState(int interactionIndex)
  2308. {
  2309. Debug.Assert(interactionIndex >= 0 && interactionIndex < totalInteractionCount, "Interaction index out of range");
  2310. // Clean up internal state that the interaction may keep.
  2311. interactions[interactionIndex].Reset();
  2312. // Clean up timer.
  2313. if (interactionStates[interactionIndex].isTimerRunning)
  2314. StopTimeout(interactionIndex);
  2315. // Reset state record.
  2316. interactionStates[interactionIndex] =
  2317. new InteractionState
  2318. {
  2319. // We never set interactions to disabled. This way we don't have to go through them
  2320. // when we disable/enable actions.
  2321. phase = InputActionPhase.Waiting,
  2322. triggerControlIndex = kInvalidIndex
  2323. };
  2324. }
  2325. internal int GetValueSizeInBytes(int bindingIndex, int controlIndex)
  2326. {
  2327. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  2328. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index out of range");
  2329. if (bindingStates[bindingIndex].isPartOfComposite) ////TODO: instead, just have compositeOrCompositeBindingIndex be invalid
  2330. {
  2331. var compositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex;
  2332. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  2333. var compositeObject = composites[compositeIndex];
  2334. Debug.Assert(compositeObject != null, "Composite object on composite state is null");
  2335. return compositeObject.valueSizeInBytes;
  2336. }
  2337. var control = controls[controlIndex];
  2338. Debug.Assert(control != null, "Control at given index is null");
  2339. return control.valueSizeInBytes;
  2340. }
  2341. internal Type GetValueType(int bindingIndex, int controlIndex)
  2342. {
  2343. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  2344. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index out of range");
  2345. if (bindingStates[bindingIndex].isPartOfComposite) ////TODO: instead, just have compositeOrCompositeBindingIndex be invalid
  2346. {
  2347. var compositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex;
  2348. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  2349. var compositeObject = composites[compositeIndex];
  2350. Debug.Assert(compositeObject != null, "Composite object is null");
  2351. return compositeObject.valueType;
  2352. }
  2353. var control = controls[controlIndex];
  2354. Debug.Assert(control != null, "Control is null");
  2355. return control.valueType;
  2356. }
  2357. internal static bool IsActuated(ref TriggerState trigger, float threshold = 0)
  2358. {
  2359. var magnitude = trigger.magnitude;
  2360. if (magnitude < 0)
  2361. return true;
  2362. if (Mathf.Approximately(threshold, 0))
  2363. return magnitude > 0;
  2364. return magnitude >= threshold;
  2365. }
  2366. ////REVIEW: we can unify the reading paths once we have blittable type constraints
  2367. internal void ReadValue(int bindingIndex, int controlIndex, void* buffer, int bufferSize, bool ignoreComposites = false)
  2368. {
  2369. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index out of range");
  2370. Debug.Assert(controlIndex >= 0 && controlIndex < totalControlCount, "Control index out of range");
  2371. InputControl control = null;
  2372. // If the binding that triggered the action is part of a composite, let
  2373. // the composite determine the value we return.
  2374. if (!ignoreComposites && bindingStates[bindingIndex].isPartOfComposite)
  2375. {
  2376. var compositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex;
  2377. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  2378. var compositeObject = composites[compositeIndex];
  2379. Debug.Assert(compositeObject != null, "Composite object is null");
  2380. var context = new InputBindingCompositeContext
  2381. {
  2382. m_State = this,
  2383. m_BindingIndex = compositeBindingIndex
  2384. };
  2385. compositeObject.ReadValue(ref context, buffer, bufferSize);
  2386. // Switch bindingIndex to that of composite so that we use the right processors.
  2387. bindingIndex = compositeBindingIndex;
  2388. }
  2389. else
  2390. {
  2391. control = controls[controlIndex];
  2392. Debug.Assert(control != null, "Control is null");
  2393. control.ReadValueIntoBuffer(buffer, bufferSize);
  2394. }
  2395. // Run value through processors, if any.
  2396. var processorCount = bindingStates[bindingIndex].processorCount;
  2397. if (processorCount > 0)
  2398. {
  2399. var processorStartIndex = bindingStates[bindingIndex].processorStartIndex;
  2400. for (var i = 0; i < processorCount; ++i)
  2401. processors[processorStartIndex + i].Process(buffer, bufferSize, control);
  2402. }
  2403. }
  2404. internal TValue ReadValue<TValue>(int bindingIndex, int controlIndex, bool ignoreComposites = false)
  2405. where TValue : struct
  2406. {
  2407. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index is out of range");
  2408. var value = default(TValue);
  2409. // In the case of a composite, this will be null.
  2410. InputControl<TValue> controlOfType = null;
  2411. // If the binding that triggered the action is part of a composite, let
  2412. // the composite determine the value we return.
  2413. if (!ignoreComposites && bindingStates[bindingIndex].isPartOfComposite)
  2414. {
  2415. var compositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex;
  2416. Debug.Assert(compositeBindingIndex >= 0 && compositeBindingIndex < totalBindingCount, "Composite binding index is out of range");
  2417. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  2418. var compositeObject = composites[compositeIndex];
  2419. Debug.Assert(compositeObject != null, "Composite object is null");
  2420. var context = new InputBindingCompositeContext
  2421. {
  2422. m_State = this,
  2423. m_BindingIndex = compositeBindingIndex
  2424. };
  2425. var compositeOfType = compositeObject as InputBindingComposite<TValue>;
  2426. if (compositeOfType == null)
  2427. {
  2428. // Composite is not derived from InputBindingComposite<TValue>. Do an explicit value
  2429. // type check here. Might be a composite like OneModifierComposite that dynamically
  2430. // determines its value type based on what its parts are bound to.
  2431. var valueType = compositeObject.valueType;
  2432. if (!valueType.IsAssignableFrom(typeof(TValue)))
  2433. throw new InvalidOperationException(
  2434. $"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(valueType)}')");
  2435. compositeObject.ReadValue(ref context, UnsafeUtility.AddressOf(ref value), UnsafeUtility.SizeOf<TValue>());
  2436. }
  2437. else
  2438. {
  2439. value = compositeOfType.ReadValue(ref context);
  2440. }
  2441. // Switch bindingIndex to that of composite so that we use the right processors.
  2442. bindingIndex = compositeBindingIndex;
  2443. }
  2444. else
  2445. {
  2446. if (controlIndex != kInvalidIndex)
  2447. {
  2448. var control = controls[controlIndex];
  2449. Debug.Assert(control != null, "Control is null");
  2450. controlOfType = control as InputControl<TValue>;
  2451. if (controlOfType == null)
  2452. throw new InvalidOperationException(
  2453. $"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)}')");
  2454. value = controlOfType.value;
  2455. }
  2456. }
  2457. // Run value through processors, if any.
  2458. return ApplyProcessors(bindingIndex, value, controlOfType);
  2459. }
  2460. internal TValue ApplyProcessors<TValue>(int bindingIndex, TValue value, InputControl<TValue> controlOfType = null)
  2461. where TValue : struct
  2462. {
  2463. var processorCount = bindingStates[bindingIndex].processorCount;
  2464. if (processorCount > 0)
  2465. {
  2466. var processorStartIndex = bindingStates[bindingIndex].processorStartIndex;
  2467. for (var i = 0; i < processorCount; ++i)
  2468. {
  2469. if (processors[processorStartIndex + i] is InputProcessor<TValue> processor)
  2470. value = processor.Process(value, controlOfType);
  2471. }
  2472. }
  2473. return value;
  2474. }
  2475. public float EvaluateCompositePartMagnitude(int bindingIndex, int partNumber)
  2476. {
  2477. var firstChildBindingIndex = bindingIndex + 1;
  2478. var currentMagnitude = float.MinValue;
  2479. for (var index = firstChildBindingIndex; index < totalBindingCount && bindingStates[index].isPartOfComposite; ++index)
  2480. {
  2481. if (bindingStates[index].partIndex != partNumber)
  2482. continue;
  2483. var controlCount = bindingStates[index].controlCount;
  2484. var controlStartIndex = bindingStates[index].controlStartIndex;
  2485. for (var i = 0; i < controlCount; ++i)
  2486. {
  2487. var control = controls[controlStartIndex + i];
  2488. // NOTE: We do *NOT* go to controlMagnitudes here. The reason is we may not yet have received the ProcessControlStateChange
  2489. // call for a specific control that is part of the composite and thus controlMagnitudes may not yet have been updated
  2490. // for a specific control.
  2491. currentMagnitude = Mathf.Max(control.magnitude, currentMagnitude);
  2492. }
  2493. }
  2494. return currentMagnitude;
  2495. }
  2496. internal double GetCompositePartPressTime(int bindingIndex, int partNumber)
  2497. {
  2498. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index is out of range");
  2499. Debug.Assert(bindingStates[bindingIndex].isComposite, "Binding must be a composite");
  2500. var firstChildBindingIndex = bindingIndex + 1;
  2501. var pressTime = double.MaxValue;
  2502. for (var index = firstChildBindingIndex; index < totalBindingCount && bindingStates[index].isPartOfComposite; ++index)
  2503. {
  2504. ref var bindingState = ref bindingStates[index];
  2505. if (bindingState.partIndex != partNumber)
  2506. continue;
  2507. // ReSharper disable once CompareOfFloatsByEqualityOperator
  2508. if (bindingState.pressTime != default && bindingState.pressTime < pressTime)
  2509. pressTime = bindingState.pressTime;
  2510. }
  2511. // ReSharper disable once CompareOfFloatsByEqualityOperator
  2512. if (pressTime == double.MaxValue)
  2513. return -1d;
  2514. return pressTime;
  2515. }
  2516. /// <summary>
  2517. /// Read the value of the given part of a composite binding.
  2518. /// </summary>
  2519. /// <param name="bindingIndex">Index of the composite binding in <see cref="bindingStates"/>.</param>
  2520. /// <param name="partNumber">Index of the part. Note that part indices start at 1!</param>
  2521. /// <typeparam name="TValue">Value type to read. Must correspond to the value of bound controls or an exception will
  2522. /// be thrown.</typeparam>
  2523. /// <returns>Greatest value from among the bound controls for the given part.</returns>
  2524. /// <remarks>
  2525. /// Composites are composed of "parts". Each part has an associated name (e.g. "negative" or "positive") which is
  2526. /// referenced by <see cref="InputBinding.name"/> of bindings that are part of the composite. However, multiple
  2527. /// bindings may reference the same part (e.g. there could be a binding for "W" and another binding for "UpArrow"
  2528. /// and both would reference the "Up" part).
  2529. ///
  2530. /// However, a given composite will only be interested in a single value for any given part. What we do is give
  2531. /// a composite an integer key for every part. When it asks for a value for the given part, we go through all
  2532. /// bindings that reference the given part and return the greatest value from among the controls of all those
  2533. /// bindings.
  2534. ///
  2535. /// <example>
  2536. /// <code>
  2537. /// // Read a float value from the second part of the composite binding at index 3.
  2538. /// ReadCompositePartValue&lt;float&gt;(3, 2);
  2539. /// </code>
  2540. /// </example>
  2541. /// </remarks>
  2542. internal TValue ReadCompositePartValue<TValue, TComparer>(int bindingIndex, int partNumber,
  2543. bool* buttonValuePtr, out int controlIndex, TComparer comparer = default)
  2544. where TValue : struct
  2545. where TComparer : IComparer<TValue>
  2546. {
  2547. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index is out of range");
  2548. Debug.Assert(bindingStates[bindingIndex].isComposite, "Binding must be a composite");
  2549. var result = default(TValue);
  2550. var firstChildBindingIndex = bindingIndex + 1;
  2551. var isFirstValue = true;
  2552. controlIndex = kInvalidIndex;
  2553. // Find the binding in the composite that has both the given part number and
  2554. // the greatest value.
  2555. //
  2556. // NOTE: It is tempting to go by control magnitudes instead as those are readily available to us (controlMagnitudes)
  2557. // and avoids us reading values that we're not going to use. Unfortunately, we can't do that as several controls
  2558. // used by a composite may all have been updated with a single event (e.g. WASD on a keyboard will usually see
  2559. // just one update that refreshes the entire state of the keyboard). In that case, one of the controls will
  2560. // see its state monitor trigger first and in turn trigger processing of the action and composite. Thus only
  2561. // that one single control would have its value refreshed in controlMagnitudes whereas the other control magnitudes
  2562. // would be stale.
  2563. for (var index = firstChildBindingIndex; index < totalBindingCount && bindingStates[index].isPartOfComposite; ++index)
  2564. {
  2565. if (bindingStates[index].partIndex != partNumber)
  2566. continue;
  2567. var controlCount = bindingStates[index].controlCount;
  2568. var controlStartIndex = bindingStates[index].controlStartIndex;
  2569. for (var i = 0; i < controlCount; ++i)
  2570. {
  2571. var thisControlIndex = controlStartIndex + i;
  2572. var value = ReadValue<TValue>(index, thisControlIndex, ignoreComposites: true);
  2573. if (isFirstValue)
  2574. {
  2575. result = value;
  2576. controlIndex = thisControlIndex;
  2577. isFirstValue = false;
  2578. }
  2579. else if (comparer.Compare(value, result) > 0)
  2580. {
  2581. result = value;
  2582. controlIndex = thisControlIndex;
  2583. }
  2584. if (buttonValuePtr != null && controlIndex == thisControlIndex)
  2585. {
  2586. var control = controls[thisControlIndex];
  2587. if (control is ButtonControl button)
  2588. {
  2589. *buttonValuePtr = button.isPressed;
  2590. }
  2591. else if (control is InputControl<float>)
  2592. {
  2593. var valuePtr = UnsafeUtility.AddressOf(ref value);
  2594. *buttonValuePtr = *(float*)valuePtr >= ButtonControl.s_GlobalDefaultButtonPressPoint;
  2595. }
  2596. ////REVIEW: Early out here as soon as *any* button is pressed? Technically, the comparer
  2597. //// could still select a different control, though...
  2598. }
  2599. }
  2600. }
  2601. return result;
  2602. }
  2603. internal bool ReadCompositePartValue(int bindingIndex, int partNumber, void* buffer, int bufferSize)
  2604. {
  2605. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index is out of range");
  2606. Debug.Assert(bindingStates[bindingIndex].isComposite, "Binding must be a composite");
  2607. var firstChildBindingIndex = bindingIndex + 1;
  2608. // Find the binding in the composite that has both the given part number and
  2609. // the greatest amount of actuation.
  2610. var currentMagnitude = float.MinValue;
  2611. for (var index = firstChildBindingIndex; index < totalBindingCount && bindingStates[index].isPartOfComposite; ++index)
  2612. {
  2613. if (bindingStates[index].partIndex != partNumber)
  2614. continue;
  2615. var controlCount = bindingStates[index].controlCount;
  2616. var controlStartIndex = bindingStates[index].controlStartIndex;
  2617. for (var i = 0; i < controlCount; ++i)
  2618. {
  2619. var thisControlIndex = controlStartIndex + i;
  2620. // Check if the control has greater actuation than the most actuated control
  2621. // we've found so far.
  2622. //
  2623. // NOTE: We cannot rely on controlMagnitudes here as several controls used by a composite may all have been updated
  2624. // with a single event (e.g. WASD on a keyboard will usually see just one update that refreshes the entire state
  2625. // of the keyboard). In that case, one of the controls will see its state monitor trigger first and in turn
  2626. // trigger processing of the action and composite. Thus only that one single control would have its value
  2627. // refreshed in controlMagnitudes whereas the other control magnitudes would be stale.
  2628. var control = controls[thisControlIndex];
  2629. var magnitude = control.magnitude;
  2630. if (magnitude < currentMagnitude)
  2631. continue;
  2632. // If so, read the value.
  2633. ReadValue(index, thisControlIndex, buffer, bufferSize, ignoreComposites: true);
  2634. currentMagnitude = magnitude;
  2635. }
  2636. }
  2637. return currentMagnitude > float.MinValue;
  2638. }
  2639. internal object ReadCompositePartValueAsObject(int bindingIndex, int partNumber)
  2640. {
  2641. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index is out of range");
  2642. Debug.Assert(bindingStates[bindingIndex].isComposite, "Binding must be a composite");
  2643. var firstChildBindingIndex = bindingIndex + 1;
  2644. // Find the binding in the composite that both has the given part number and
  2645. // the greatest amount of actuation.
  2646. var currentMagnitude = float.MinValue;
  2647. object currentValue = null;
  2648. for (var index = firstChildBindingIndex; index < totalBindingCount && bindingStates[index].isPartOfComposite; ++index)
  2649. {
  2650. if (bindingStates[index].partIndex != partNumber)
  2651. continue;
  2652. var controlCount = bindingStates[index].controlCount;
  2653. var controlStartIndex = bindingStates[index].controlStartIndex;
  2654. for (var i = 0; i < controlCount; ++i)
  2655. {
  2656. var thisControlIndex = controlStartIndex + i;
  2657. // Check if the control has greater actuation than the most actuated control
  2658. // we've found so far.
  2659. //
  2660. // NOTE: We cannot rely on controlMagnitudes here as several controls used by a composite may all have been updated
  2661. // with a single event (e.g. WASD on a keyboard will usually see just one update that refreshes the entire state
  2662. // of the keyboard). In that case, one of the controls will see its state monitor trigger first and in turn
  2663. // trigger processing of the action and composite. Thus only that one single control would have its value
  2664. // refreshed in controlMagnitudes whereas the other control magnitudes would be stale.
  2665. var control = controls[thisControlIndex];
  2666. var magnitude = control.magnitude;
  2667. if (magnitude < currentMagnitude)
  2668. continue;
  2669. // If so, read the value.
  2670. currentValue = ReadValueAsObject(index, thisControlIndex, ignoreComposites: true);
  2671. currentMagnitude = magnitude;
  2672. }
  2673. }
  2674. return currentValue;
  2675. }
  2676. internal object ReadValueAsObject(int bindingIndex, int controlIndex, bool ignoreComposites = false)
  2677. {
  2678. Debug.Assert(bindingIndex >= 0 && bindingIndex < totalBindingCount, "Binding index is out of range");
  2679. InputControl control = null;
  2680. object value = null;
  2681. // If the binding that triggered the action is part of a composite, let
  2682. // the composite determine the value we return.
  2683. if (!ignoreComposites && bindingStates[bindingIndex].isPartOfComposite) ////TODO: instead, just have compositeOrCompositeBindingIndex be invalid
  2684. {
  2685. var compositeBindingIndex = bindingStates[bindingIndex].compositeOrCompositeBindingIndex;
  2686. Debug.Assert(compositeBindingIndex >= 0 && compositeBindingIndex < totalBindingCount, "Binding index is out of range");
  2687. var compositeIndex = bindingStates[compositeBindingIndex].compositeOrCompositeBindingIndex;
  2688. var compositeObject = composites[compositeIndex];
  2689. Debug.Assert(compositeObject != null, "Composite object is null");
  2690. var context = new InputBindingCompositeContext
  2691. {
  2692. m_State = this,
  2693. m_BindingIndex = compositeBindingIndex
  2694. };
  2695. value = compositeObject.ReadValueAsObject(ref context);
  2696. // Switch bindingIndex to that of composite so that we use the right processors.
  2697. bindingIndex = compositeBindingIndex;
  2698. }
  2699. else
  2700. {
  2701. if (controlIndex != kInvalidIndex)
  2702. {
  2703. control = controls[controlIndex];
  2704. Debug.Assert(control != null, "Control is null");
  2705. value = control.ReadValueAsObject();
  2706. }
  2707. }
  2708. if (value != null)
  2709. {
  2710. // Run value through processors, if any.
  2711. var processorCount = bindingStates[bindingIndex].processorCount;
  2712. if (processorCount > 0)
  2713. {
  2714. var processorStartIndex = bindingStates[bindingIndex].processorStartIndex;
  2715. for (var i = 0; i < processorCount; ++i)
  2716. value = processors[processorStartIndex + i].ProcessAsObject(value, control);
  2717. }
  2718. }
  2719. return value;
  2720. }
  2721. internal bool ReadValueAsButton(int bindingIndex, int controlIndex)
  2722. {
  2723. var buttonControl = default(ButtonControl);
  2724. if (!bindingStates[bindingIndex].isPartOfComposite)
  2725. buttonControl = controls[controlIndex] as ButtonControl;
  2726. // Read float value.
  2727. var floatValue = ReadValue<float>(bindingIndex, controlIndex);
  2728. // Compare to press point.
  2729. if (buttonControl != null)
  2730. return floatValue >= buttonControl.pressPointOrDefault;
  2731. return floatValue >= ButtonControl.s_GlobalDefaultButtonPressPoint;
  2732. }
  2733. /// <summary>
  2734. /// Records the current state of a single interaction attached to a binding.
  2735. /// Each interaction keeps track of its own trigger control and phase progression.
  2736. /// </summary>
  2737. [StructLayout(LayoutKind.Explicit, Size = 48)]
  2738. internal struct InteractionState
  2739. {
  2740. [FieldOffset(0)] private ushort m_TriggerControlIndex;
  2741. [FieldOffset(2)] private byte m_Phase;
  2742. [FieldOffset(3)] private byte m_Flags;
  2743. [FieldOffset(4)] private float m_TimerDuration;
  2744. [FieldOffset(8)] private double m_StartTime;
  2745. [FieldOffset(16)] private double m_TimerStartTime;
  2746. [FieldOffset(24)] private double m_PerformedTime;
  2747. [FieldOffset(32)] private float m_TotalTimeoutCompletionTimeDone;
  2748. [FieldOffset(36)] private float m_TotalTimeoutCompletionTimeRemaining;
  2749. [FieldOffset(40)] private long m_TimerMonitorIndex;
  2750. public int triggerControlIndex
  2751. {
  2752. get
  2753. {
  2754. if (m_TriggerControlIndex == ushort.MaxValue)
  2755. return kInvalidIndex;
  2756. return m_TriggerControlIndex;
  2757. }
  2758. set
  2759. {
  2760. if (value == kInvalidIndex)
  2761. m_TriggerControlIndex = ushort.MaxValue;
  2762. else
  2763. {
  2764. if (value < 0 || value >= ushort.MaxValue)
  2765. throw new NotSupportedException("More than ushort.MaxValue-1 controls in a single InputActionState");
  2766. m_TriggerControlIndex = (ushort)value;
  2767. }
  2768. }
  2769. }
  2770. public double startTime
  2771. {
  2772. get => m_StartTime;
  2773. set => m_StartTime = value;
  2774. }
  2775. public double performedTime
  2776. {
  2777. get => m_PerformedTime;
  2778. set => m_PerformedTime = value;
  2779. }
  2780. public double timerStartTime
  2781. {
  2782. get => m_TimerStartTime;
  2783. set => m_TimerStartTime = value;
  2784. }
  2785. public float timerDuration
  2786. {
  2787. get => m_TimerDuration;
  2788. set => m_TimerDuration = value;
  2789. }
  2790. public float totalTimeoutCompletionDone
  2791. {
  2792. get => m_TotalTimeoutCompletionTimeDone;
  2793. set => m_TotalTimeoutCompletionTimeDone = value;
  2794. }
  2795. public float totalTimeoutCompletionTimeRemaining
  2796. {
  2797. get => m_TotalTimeoutCompletionTimeRemaining;
  2798. set => m_TotalTimeoutCompletionTimeRemaining = value;
  2799. }
  2800. public long timerMonitorIndex
  2801. {
  2802. get => m_TimerMonitorIndex;
  2803. set => m_TimerMonitorIndex = value;
  2804. }
  2805. public bool isTimerRunning
  2806. {
  2807. get => ((Flags)m_Flags & Flags.TimerRunning) == Flags.TimerRunning;
  2808. set
  2809. {
  2810. if (value)
  2811. m_Flags |= (byte)Flags.TimerRunning;
  2812. else
  2813. {
  2814. var mask = ~Flags.TimerRunning;
  2815. m_Flags &= (byte)mask;
  2816. }
  2817. }
  2818. }
  2819. public InputActionPhase phase
  2820. {
  2821. get => (InputActionPhase)m_Phase;
  2822. set => m_Phase = (byte)value;
  2823. }
  2824. [Flags]
  2825. private enum Flags
  2826. {
  2827. TimerRunning = 1 << 0,
  2828. }
  2829. }
  2830. /// <summary>
  2831. /// Runtime state for a single binding.
  2832. /// </summary>
  2833. /// <remarks>
  2834. /// Correlated to the <see cref="InputBinding"/> it corresponds to by the index in the binding
  2835. /// array.
  2836. /// </remarks>
  2837. [StructLayout(LayoutKind.Explicit, Size = 32)]
  2838. internal struct BindingState
  2839. {
  2840. [FieldOffset(0)] private byte m_ControlCount;
  2841. [FieldOffset(1)] private byte m_InteractionCount;
  2842. [FieldOffset(2)] private byte m_ProcessorCount;
  2843. [FieldOffset(3)] private byte m_MapIndex;
  2844. [FieldOffset(4)] private byte m_Flags;
  2845. [FieldOffset(5)] private byte m_PartIndex;
  2846. [FieldOffset(6)] private ushort m_ActionIndex;
  2847. [FieldOffset(8)] private ushort m_CompositeOrCompositeBindingIndex;
  2848. [FieldOffset(10)] private ushort m_ProcessorStartIndex;
  2849. [FieldOffset(12)] private ushort m_InteractionStartIndex;
  2850. [FieldOffset(14)] private ushort m_ControlStartIndex;
  2851. [FieldOffset(16)] private double m_PressTime;
  2852. [FieldOffset(24)] private int m_TriggerEventIdForComposite;
  2853. [FieldOffset(28)] private int __padding; // m_PressTime double must be aligned
  2854. [Flags]
  2855. public enum Flags
  2856. {
  2857. ChainsWithNext = 1 << 0,
  2858. EndOfChain = 1 << 1,
  2859. Composite = 1 << 2,
  2860. PartOfComposite = 1 << 3,
  2861. InitialStateCheckPending = 1 << 4,
  2862. WantsInitialStateCheck = 1 << 5,
  2863. }
  2864. /// <summary>
  2865. /// Index into <see cref="controls"/> of first control associated with the binding.
  2866. /// </summary>
  2867. /// <remarks>
  2868. /// For composites, this is the index of the first control that is bound by any of the parts in the composite.
  2869. /// </remarks>
  2870. public int controlStartIndex
  2871. {
  2872. get => m_ControlStartIndex;
  2873. set
  2874. {
  2875. Debug.Assert(value != kInvalidIndex, "Control state index is invalid");
  2876. if (value >= ushort.MaxValue)
  2877. throw new NotSupportedException("Total control count in state cannot exceed byte.MaxValue=" + ushort.MaxValue);
  2878. m_ControlStartIndex = (ushort)value;
  2879. }
  2880. }
  2881. /// <summary>
  2882. /// Number of controls associated with this binding.
  2883. /// </summary>
  2884. /// <remarks>
  2885. /// For composites, this is the total number of controls bound by all parts of the composite combined.
  2886. /// </remarks>
  2887. public int controlCount
  2888. {
  2889. get => m_ControlCount;
  2890. set
  2891. {
  2892. if (value >= byte.MaxValue)
  2893. throw new NotSupportedException("Control count per binding cannot exceed byte.MaxValue=" + byte.MaxValue);
  2894. m_ControlCount = (byte)value;
  2895. }
  2896. }
  2897. /// <summary>
  2898. /// Index into <see cref="InputActionState.interactionStates"/> of first interaction associated with the binding.
  2899. /// </summary>
  2900. public int interactionStartIndex
  2901. {
  2902. get
  2903. {
  2904. if (m_InteractionStartIndex == ushort.MaxValue)
  2905. return kInvalidIndex;
  2906. return m_InteractionStartIndex;
  2907. }
  2908. set
  2909. {
  2910. if (value == kInvalidIndex)
  2911. m_InteractionStartIndex = ushort.MaxValue;
  2912. else
  2913. {
  2914. if (value >= ushort.MaxValue)
  2915. throw new NotSupportedException("Interaction count cannot exceed ushort.MaxValue=" + ushort.MaxValue);
  2916. m_InteractionStartIndex = (ushort)value;
  2917. }
  2918. }
  2919. }
  2920. /// <summary>
  2921. /// Number of interactions associated with this binding.
  2922. /// </summary>
  2923. public int interactionCount
  2924. {
  2925. get => m_InteractionCount;
  2926. set
  2927. {
  2928. if (value >= byte.MaxValue)
  2929. throw new NotSupportedException("Interaction count per binding cannot exceed byte.MaxValue=" + byte.MaxValue);
  2930. m_InteractionCount = (byte)value;
  2931. }
  2932. }
  2933. public int processorStartIndex
  2934. {
  2935. get
  2936. {
  2937. if (m_ProcessorStartIndex == ushort.MaxValue)
  2938. return kInvalidIndex;
  2939. return m_ProcessorStartIndex;
  2940. }
  2941. set
  2942. {
  2943. if (value == kInvalidIndex)
  2944. m_ProcessorStartIndex = ushort.MaxValue;
  2945. else
  2946. {
  2947. if (value >= ushort.MaxValue)
  2948. throw new NotSupportedException("Processor count cannot exceed ushort.MaxValue=" + ushort.MaxValue);
  2949. m_ProcessorStartIndex = (ushort)value;
  2950. }
  2951. }
  2952. }
  2953. public int processorCount
  2954. {
  2955. get => m_ProcessorCount;
  2956. set
  2957. {
  2958. if (value >= byte.MaxValue)
  2959. throw new NotSupportedException("Processor count per binding cannot exceed byte.MaxValue=" + byte.MaxValue);
  2960. m_ProcessorCount = (byte)value;
  2961. }
  2962. }
  2963. /// <summary>
  2964. /// Index of the action being triggered by the binding (if any).
  2965. /// </summary>
  2966. /// <remarks>
  2967. /// For bindings that don't trigger actions, this is <see cref="kInvalidIndex"/>.
  2968. ///
  2969. /// For bindings that are part of a composite, we force this to be the action set on the composite itself.
  2970. /// </remarks>
  2971. public int actionIndex
  2972. {
  2973. get
  2974. {
  2975. if (m_ActionIndex == ushort.MaxValue)
  2976. return kInvalidIndex;
  2977. return m_ActionIndex;
  2978. }
  2979. set
  2980. {
  2981. if (value == kInvalidIndex)
  2982. m_ActionIndex = ushort.MaxValue;
  2983. else
  2984. {
  2985. if (value >= ushort.MaxValue)
  2986. throw new NotSupportedException("Action count cannot exceed ushort.MaxValue=" + ushort.MaxValue);
  2987. m_ActionIndex = (ushort)value;
  2988. }
  2989. }
  2990. }
  2991. public int mapIndex
  2992. {
  2993. get => m_MapIndex;
  2994. set
  2995. {
  2996. Debug.Assert(value != kInvalidIndex, "Map index is invalid");
  2997. if (value >= byte.MaxValue)
  2998. throw new NotSupportedException("Map count cannot exceed byte.MaxValue=" + byte.MaxValue);
  2999. m_MapIndex = (byte)value;
  3000. }
  3001. }
  3002. /// <summary>
  3003. /// If this is a composite binding, this is the index of the composite in <see cref="composites"/>.
  3004. /// If the binding is part of a composite, this is the index of the binding that is the composite.
  3005. /// If the binding is neither a composite nor part of a composite, this is <see cref="kInvalidIndex"/>.
  3006. /// </summary>
  3007. public int compositeOrCompositeBindingIndex
  3008. {
  3009. get
  3010. {
  3011. if (m_CompositeOrCompositeBindingIndex == ushort.MaxValue)
  3012. return kInvalidIndex;
  3013. return m_CompositeOrCompositeBindingIndex;
  3014. }
  3015. set
  3016. {
  3017. if (value == kInvalidIndex)
  3018. m_CompositeOrCompositeBindingIndex = ushort.MaxValue;
  3019. else
  3020. {
  3021. if (value >= ushort.MaxValue)
  3022. throw new NotSupportedException("Composite count cannot exceed ushort.MaxValue=" + ushort.MaxValue);
  3023. m_CompositeOrCompositeBindingIndex = (ushort)value;
  3024. }
  3025. }
  3026. }
  3027. /// <summary>
  3028. /// <see cref="InputEvent.eventId">ID</see> of the event that last triggered the binding.
  3029. /// </summary>
  3030. /// <remarks>
  3031. /// We only store this for composites ATM.
  3032. /// </remarks>
  3033. public int triggerEventIdForComposite
  3034. {
  3035. get => m_TriggerEventIdForComposite;
  3036. set => m_TriggerEventIdForComposite = value;
  3037. }
  3038. // For now, we only record this for part bindings!
  3039. public double pressTime
  3040. {
  3041. get => m_PressTime;
  3042. set => m_PressTime = value;
  3043. }
  3044. public Flags flags
  3045. {
  3046. get => (Flags)m_Flags;
  3047. set => m_Flags = (byte)value;
  3048. }
  3049. public bool chainsWithNext
  3050. {
  3051. get => (flags & Flags.ChainsWithNext) == Flags.ChainsWithNext;
  3052. set
  3053. {
  3054. if (value)
  3055. flags |= Flags.ChainsWithNext;
  3056. else
  3057. flags &= ~Flags.ChainsWithNext;
  3058. }
  3059. }
  3060. public bool isEndOfChain
  3061. {
  3062. get => (flags & Flags.EndOfChain) == Flags.EndOfChain;
  3063. set
  3064. {
  3065. if (value)
  3066. flags |= Flags.EndOfChain;
  3067. else
  3068. flags &= ~Flags.EndOfChain;
  3069. }
  3070. }
  3071. public bool isPartOfChain => chainsWithNext || isEndOfChain;
  3072. public bool isComposite
  3073. {
  3074. get => (flags & Flags.Composite) == Flags.Composite;
  3075. set
  3076. {
  3077. if (value)
  3078. flags |= Flags.Composite;
  3079. else
  3080. flags &= ~Flags.Composite;
  3081. }
  3082. }
  3083. public bool isPartOfComposite
  3084. {
  3085. get => (flags & Flags.PartOfComposite) == Flags.PartOfComposite;
  3086. set
  3087. {
  3088. if (value)
  3089. flags |= Flags.PartOfComposite;
  3090. else
  3091. flags &= ~Flags.PartOfComposite;
  3092. }
  3093. }
  3094. public bool initialStateCheckPending
  3095. {
  3096. get => (flags & Flags.InitialStateCheckPending) != 0;
  3097. set
  3098. {
  3099. if (value)
  3100. flags |= Flags.InitialStateCheckPending;
  3101. else
  3102. flags &= ~Flags.InitialStateCheckPending;
  3103. }
  3104. }
  3105. public bool wantsInitialStateCheck
  3106. {
  3107. get => (flags & Flags.WantsInitialStateCheck) != 0;
  3108. set
  3109. {
  3110. if (value)
  3111. flags |= Flags.WantsInitialStateCheck;
  3112. else
  3113. flags &= ~Flags.WantsInitialStateCheck;
  3114. }
  3115. }
  3116. public int partIndex
  3117. {
  3118. get => m_PartIndex;
  3119. set
  3120. {
  3121. if (partIndex < 0)
  3122. throw new ArgumentOutOfRangeException(nameof(value), "Part index must not be negative");
  3123. if (partIndex > byte.MaxValue)
  3124. throw new InvalidOperationException("Part count must not exceed byte.MaxValue=" + byte.MaxValue);
  3125. m_PartIndex = (byte)value;
  3126. }
  3127. }
  3128. }
  3129. /// <summary>
  3130. /// Record of an input control change and its related data.
  3131. /// </summary>
  3132. /// <remarks>
  3133. /// This serves a dual purpose. One is, trigger states represent control actuations while we process them. The
  3134. /// other is to represent the current actuation state of an action as a whole. The latter is stored in <see cref="actionStates"/>
  3135. /// while the former is passed around as temporary instances on the stack.
  3136. /// </remarks>
  3137. [StructLayout(LayoutKind.Explicit, Size = 52)]
  3138. public struct TriggerState
  3139. {
  3140. public const int kMaxNumMaps = byte.MaxValue;
  3141. public const int kMaxNumControls = ushort.MaxValue;
  3142. public const int kMaxNumBindings = ushort.MaxValue;
  3143. [FieldOffset(0)] private byte m_Phase;
  3144. [FieldOffset(1)] private byte m_Flags;
  3145. [FieldOffset(2)] private byte m_MapIndex;
  3146. // One byte available here.
  3147. [FieldOffset(4)] private ushort m_ControlIndex;
  3148. // Two bytes available here.
  3149. ////REVIEW: can we condense these to floats? would save us a whopping 8 bytes
  3150. [FieldOffset(8)] private double m_Time;
  3151. [FieldOffset(16)] private double m_StartTime;
  3152. [FieldOffset(24)] private ushort m_BindingIndex;
  3153. [FieldOffset(26)] private ushort m_InteractionIndex;
  3154. [FieldOffset(28)] private float m_Magnitude;
  3155. [FieldOffset(32)] private uint m_LastPerformedInUpdate;
  3156. [FieldOffset(36)] private uint m_LastCanceledInUpdate;
  3157. [FieldOffset(40)] private uint m_PressedInUpdate;
  3158. [FieldOffset(44)] private uint m_ReleasedInUpdate;
  3159. [FieldOffset(48)] private uint m_LastCompletedInUpdate;
  3160. /// <summary>
  3161. /// Phase being triggered by the control value change.
  3162. /// </summary>
  3163. public InputActionPhase phase
  3164. {
  3165. get => (InputActionPhase)m_Phase;
  3166. set => m_Phase = (byte)value;
  3167. }
  3168. public bool isDisabled => phase == InputActionPhase.Disabled;
  3169. public bool isWaiting => phase == InputActionPhase.Waiting;
  3170. public bool isStarted => phase == InputActionPhase.Started;
  3171. public bool isPerformed => phase == InputActionPhase.Performed;
  3172. public bool isCanceled => phase == InputActionPhase.Canceled;
  3173. /// <summary>
  3174. /// The time the binding got triggered.
  3175. /// </summary>
  3176. public double time
  3177. {
  3178. get => m_Time;
  3179. set => m_Time = value;
  3180. }
  3181. /// <summary>
  3182. /// The time when the binding moved into <see cref="InputActionPhase.Started"/>.
  3183. /// </summary>
  3184. public double startTime
  3185. {
  3186. get => m_StartTime;
  3187. set => m_StartTime = value;
  3188. }
  3189. /// <summary>
  3190. /// Amount of actuation on the control.
  3191. /// </summary>
  3192. /// <remarks>
  3193. /// This is only valid if <see cref="haveMagnitude"/> is true.
  3194. ///
  3195. /// Note that this may differ from the actuation stored for <see cref="controlIndex"/> in <see
  3196. /// cref="UnmanagedMemory.controlMagnitudes"/> if the binding is a composite.
  3197. /// </remarks>
  3198. public float magnitude
  3199. {
  3200. get => m_Magnitude;
  3201. set
  3202. {
  3203. flags |= Flags.HaveMagnitude;
  3204. m_Magnitude = value;
  3205. }
  3206. }
  3207. /// <summary>
  3208. /// Whether <see cref="magnitude"/> has been set.
  3209. /// </summary>
  3210. /// <remarks>
  3211. /// Magnitude computation is expensive so we only want to do it once. Also, we sometimes need to compare
  3212. /// a current magnitude to a magnitude value from a previous frame and the magnitude of the control
  3213. /// may have already changed.
  3214. /// </remarks>
  3215. public bool haveMagnitude => (flags & Flags.HaveMagnitude) != 0;
  3216. /// <summary>
  3217. /// Index of the action map in <see cref="maps"/> that contains the binding that triggered.
  3218. /// </summary>
  3219. public int mapIndex
  3220. {
  3221. get => m_MapIndex;
  3222. set
  3223. {
  3224. if (value < 0 || value > kMaxNumMaps)
  3225. throw new NotSupportedException("More than byte.MaxValue InputActionMaps in a single InputActionState");
  3226. m_MapIndex = (byte)value;
  3227. }
  3228. }
  3229. /// <summary>
  3230. /// Index of the control currently driving the action or <see cref="kInvalidIndex"/> if none.
  3231. /// </summary>
  3232. public int controlIndex
  3233. {
  3234. get
  3235. {
  3236. if (m_ControlIndex == kMaxNumControls)
  3237. return kInvalidIndex;
  3238. return m_ControlIndex;
  3239. }
  3240. set
  3241. {
  3242. if (value == kInvalidIndex)
  3243. m_ControlIndex = ushort.MaxValue;
  3244. else
  3245. {
  3246. if (value < 0 || value >= kMaxNumControls)
  3247. throw new NotSupportedException("More than ushort.MaxValue-1 controls in a single InputActionState");
  3248. m_ControlIndex = (ushort)value;
  3249. }
  3250. }
  3251. }
  3252. /// <summary>
  3253. /// Index into <see cref="bindingStates"/> for the binding that triggered.
  3254. /// </summary>
  3255. /// <remarks>
  3256. /// This corresponds 1:1 to an <see cref="InputBinding"/>.
  3257. /// </remarks>
  3258. public int bindingIndex
  3259. {
  3260. get => m_BindingIndex;
  3261. set
  3262. {
  3263. if (value < 0 || value > kMaxNumBindings)
  3264. throw new NotSupportedException("More than ushort.MaxValue bindings in a single InputActionState");
  3265. m_BindingIndex = (ushort)value;
  3266. }
  3267. }
  3268. /// <summary>
  3269. /// Index into <see cref="InputActionState.interactionStates"/> for the interaction that triggered.
  3270. /// </summary>
  3271. /// <remarks>
  3272. /// Is <see cref="InputActionState.kInvalidIndex"/> if there is no interaction present on the binding.
  3273. /// </remarks>
  3274. public int interactionIndex
  3275. {
  3276. get
  3277. {
  3278. if (m_InteractionIndex == ushort.MaxValue)
  3279. return kInvalidIndex;
  3280. return m_InteractionIndex;
  3281. }
  3282. set
  3283. {
  3284. if (value == kInvalidIndex)
  3285. m_InteractionIndex = ushort.MaxValue;
  3286. else
  3287. {
  3288. if (value < 0 || value >= ushort.MaxValue)
  3289. throw new NotSupportedException("More than ushort.MaxValue-1 interactions in a single InputActionState");
  3290. m_InteractionIndex = (ushort)value;
  3291. }
  3292. }
  3293. }
  3294. /// <summary>
  3295. /// Update step count (<see cref="InputUpdate.s_UpdateStepCount"/>) in which action triggered/performed last.
  3296. /// Zero if the action did not trigger yet. Also reset to zero when the action is hard reset.
  3297. /// </summary>
  3298. public uint lastPerformedInUpdate
  3299. {
  3300. get => m_LastPerformedInUpdate;
  3301. set => m_LastPerformedInUpdate = value;
  3302. }
  3303. /// <summary>
  3304. /// Update step count (<see cref="InputUpdate.s_UpdateStepCount"/>) in which action completed last.
  3305. /// Zero if the action did not become completed yet. Also reset to zero when the action is hard reset.
  3306. /// </summary>
  3307. public uint lastCompletedInUpdate
  3308. {
  3309. get => m_LastCompletedInUpdate;
  3310. set => m_LastCompletedInUpdate = value;
  3311. }
  3312. public uint lastCanceledInUpdate
  3313. {
  3314. get => m_LastCanceledInUpdate;
  3315. set => m_LastCanceledInUpdate = value;
  3316. }
  3317. public uint pressedInUpdate
  3318. {
  3319. get => m_PressedInUpdate;
  3320. set => m_PressedInUpdate = value;
  3321. }
  3322. public uint releasedInUpdate
  3323. {
  3324. get => m_ReleasedInUpdate;
  3325. set => m_ReleasedInUpdate = value;
  3326. }
  3327. /// <summary>
  3328. /// Whether the action associated with the trigger state is marked as pass-through.
  3329. /// </summary>
  3330. /// <seealso cref="InputActionType.PassThrough"/>
  3331. public bool isPassThrough
  3332. {
  3333. get => (flags & Flags.PassThrough) != 0;
  3334. set
  3335. {
  3336. if (value)
  3337. flags |= Flags.PassThrough;
  3338. else
  3339. flags &= ~Flags.PassThrough;
  3340. }
  3341. }
  3342. /// <summary>
  3343. /// Whether the action associated with the trigger state is a button-type action.
  3344. /// </summary>
  3345. /// <seealso cref="InputActionType.Button"/>
  3346. public bool isButton
  3347. {
  3348. get => (flags & Flags.Button) != 0;
  3349. set
  3350. {
  3351. if (value)
  3352. flags |= Flags.Button;
  3353. else
  3354. flags &= ~Flags.Button;
  3355. }
  3356. }
  3357. public bool isPressed
  3358. {
  3359. get => (flags & Flags.Pressed) != 0;
  3360. set
  3361. {
  3362. if (value)
  3363. flags |= Flags.Pressed;
  3364. else
  3365. flags &= ~Flags.Pressed;
  3366. }
  3367. }
  3368. /// <summary>
  3369. /// Whether the action may potentially see multiple concurrent actuations from its bindings
  3370. /// and wants them resolved automatically.
  3371. /// </summary>
  3372. /// <remarks>
  3373. /// We use this to gate some of the more expensive checks that are pointless to
  3374. /// perform if we don't have to disambiguate input from concurrent sources.
  3375. ///
  3376. /// Always disabled if <see cref="isPassThrough"/> is true.
  3377. /// </remarks>
  3378. public bool mayNeedConflictResolution
  3379. {
  3380. get => (flags & Flags.MayNeedConflictResolution) != 0;
  3381. set
  3382. {
  3383. if (value)
  3384. flags |= Flags.MayNeedConflictResolution;
  3385. else
  3386. flags &= ~Flags.MayNeedConflictResolution;
  3387. }
  3388. }
  3389. /// <summary>
  3390. /// Whether the action currently has several concurrent actuations from its bindings.
  3391. /// </summary>
  3392. /// <remarks>
  3393. /// This is only used when automatic conflict resolution is enabled (<see cref="mayNeedConflictResolution"/>).
  3394. /// </remarks>
  3395. public bool hasMultipleConcurrentActuations
  3396. {
  3397. get => (flags & Flags.HasMultipleConcurrentActuations) != 0;
  3398. set
  3399. {
  3400. if (value)
  3401. flags |= Flags.HasMultipleConcurrentActuations;
  3402. else
  3403. flags &= ~Flags.HasMultipleConcurrentActuations;
  3404. }
  3405. }
  3406. public bool inProcessing
  3407. {
  3408. get => (flags & Flags.InProcessing) != 0;
  3409. set
  3410. {
  3411. if (value)
  3412. flags |= Flags.InProcessing;
  3413. else
  3414. flags &= ~Flags.InProcessing;
  3415. }
  3416. }
  3417. public Flags flags
  3418. {
  3419. get => (Flags)m_Flags;
  3420. set => m_Flags = (byte)value;
  3421. }
  3422. [Flags]
  3423. public enum Flags
  3424. {
  3425. /// <summary>
  3426. /// Whether <see cref="magnitude"/> has been set.
  3427. /// </summary>
  3428. HaveMagnitude = 1 << 0,
  3429. /// <summary>
  3430. /// Whether the action associated with the trigger state is marked as pass-through.
  3431. /// </summary>
  3432. /// <seealso cref="InputActionType.PassThrough"/>
  3433. PassThrough = 1 << 1,
  3434. /// <summary>
  3435. /// Whether the action has more than one control bound to it.
  3436. /// </summary>
  3437. /// <remarks>
  3438. /// An action may have arbitrary many bindings yet may still resolve only to a single control
  3439. /// at runtime. In that case, this flag is NOT set. We only set it if binding resolution for
  3440. /// an action indeed ended up with multiple controls able to trigger the same action.
  3441. /// </remarks>
  3442. MayNeedConflictResolution = 1 << 2,
  3443. /// <summary>
  3444. /// Whether there are currently multiple bound controls that are actuated.
  3445. /// </summary>
  3446. /// <remarks>
  3447. /// This is only used if <see cref="TriggerState.mayNeedConflictResolution"/> is true.
  3448. /// </remarks>
  3449. HasMultipleConcurrentActuations = 1 << 3,
  3450. InProcessing = 1 << 4,
  3451. /// <summary>
  3452. /// Whether the action associated with the trigger state is a button-type action.
  3453. /// </summary>
  3454. /// <seealso cref="InputActionType.Button"/>
  3455. Button = 1 << 5,
  3456. Pressed = 1 << 6,
  3457. }
  3458. }
  3459. /// <summary>
  3460. /// Tells us where the data for a single action map is found in the
  3461. /// various arrays.
  3462. /// </summary>
  3463. public struct ActionMapIndices
  3464. {
  3465. public int actionStartIndex;
  3466. public int actionCount;
  3467. public int controlStartIndex;
  3468. public int controlCount;
  3469. public int bindingStartIndex;
  3470. public int bindingCount;
  3471. public int interactionStartIndex;
  3472. public int interactionCount;
  3473. public int processorStartIndex;
  3474. public int processorCount;
  3475. public int compositeStartIndex;
  3476. public int compositeCount;
  3477. }
  3478. /// <summary>
  3479. /// Unmanaged memory kept for action maps.
  3480. /// </summary>
  3481. /// <remarks>
  3482. /// Most of the dynamic execution state for actions we keep in a single block of unmanaged memory.
  3483. /// Essentially, only the C# heap objects (like IInputInteraction and such) we keep in managed arrays.
  3484. /// Aside from being able to condense the data into a single block of memory and not having to have
  3485. /// it spread out on the GC heap, we gain the advantage of being able to freely allocate and re-allocate
  3486. /// these blocks without creating garbage on the GC heap.
  3487. ///
  3488. /// The data here is set up by <see cref="InputBindingResolver"/>.
  3489. /// </remarks>
  3490. public struct UnmanagedMemory : IDisposable
  3491. {
  3492. public bool isAllocated => basePtr != null;
  3493. public void* basePtr;
  3494. /// <summary>
  3495. /// Number of action maps and entries in <see cref="mapIndices"/> and <see cref="maps"/>.
  3496. /// </summary>
  3497. public int mapCount;
  3498. /// <summary>
  3499. /// Total number of actions (i.e. from all maps combined) and entries in <see cref="actionStates"/>.
  3500. /// </summary>
  3501. public int actionCount;
  3502. /// <summary>
  3503. /// Total number of interactions and entries in <see cref="interactionStates"/> and <see cref="interactions"/>.
  3504. /// </summary>
  3505. public int interactionCount;
  3506. /// <summary>
  3507. /// Total number of bindings and entries in <see cref="bindingStates"/>.
  3508. /// </summary>
  3509. public int bindingCount;
  3510. /// <summary>
  3511. /// Total number of bound controls and entries in <see cref="controls"/>.
  3512. /// </summary>
  3513. public int controlCount;
  3514. /// <summary>
  3515. /// Total number of composite bindings and entries in <see cref="composites"/>.
  3516. /// </summary>
  3517. public int compositeCount;
  3518. /// <summary>
  3519. /// Total size of allocated unmanaged memory.
  3520. /// </summary>
  3521. public int sizeInBytes =>
  3522. mapCount * sizeof(ActionMapIndices) + // mapIndices
  3523. actionCount * sizeof(TriggerState) + // actionStates
  3524. bindingCount * sizeof(BindingState) + // bindingStates
  3525. interactionCount * sizeof(InteractionState) + // interactionStates
  3526. controlCount * sizeof(float) + // controlMagnitudes
  3527. compositeCount * sizeof(float) + // compositeMagnitudes
  3528. controlCount * sizeof(int) + // controlIndexToBindingIndex
  3529. controlCount * sizeof(ushort) * 2 + // controlGrouping
  3530. actionCount * sizeof(ushort) * 2 + // actionBindingIndicesAndCounts
  3531. bindingCount * sizeof(ushort) + // actionBindingIndices
  3532. (controlCount + 31) / 32 * sizeof(int); // enabledControlsArray
  3533. /// <summary>
  3534. /// Trigger state of all actions added to the state.
  3535. /// </summary>
  3536. /// <remarks>
  3537. /// This array also tells which actions are enabled or disabled. Any action with phase
  3538. /// <see cref="InputActionPhase.Disabled"/> is disabled.
  3539. /// </remarks>
  3540. public TriggerState* actionStates;
  3541. /// <summary>
  3542. /// State of all bindings added to the state.
  3543. /// </summary>
  3544. /// <remarks>
  3545. /// For the most part, this is read-only information set up during resolution.
  3546. /// </remarks>
  3547. public BindingState* bindingStates;
  3548. /// <summary>
  3549. /// State of all interactions on bindings in the action map.
  3550. /// </summary>
  3551. /// <remarks>
  3552. /// Any interaction mentioned on any of the bindings gets its own execution state record
  3553. /// in here. The interactions for any one binding are grouped together.
  3554. /// </remarks>
  3555. public InteractionState* interactionStates;
  3556. /// <summary>
  3557. /// Current remembered level of actuation of each of the controls in <see cref="controls"/>.
  3558. /// </summary>
  3559. /// <remarks>
  3560. /// This array is NOT kept strictly up to date. In fact, we only use it for conflict resolution
  3561. /// between multiple bound controls at the moment. Meaning that in the majority of cases, the magnitude
  3562. /// stored for a control here will NOT be up to date.
  3563. ///
  3564. /// Also note that for controls that are part of composites, this will NOT be the magnitude of the
  3565. /// control but rather be the magnitude of the entire compound.
  3566. /// </remarks>
  3567. public float* controlMagnitudes;
  3568. public float* compositeMagnitudes;
  3569. public int* enabledControls;
  3570. /// <summary>
  3571. /// Array of pair of ints, one pair for each action (same index as <see cref="actionStates"/>). First int
  3572. /// is the index into <see cref="actionBindingIndices"/> where bindings of action are found and second int
  3573. /// is the count of bindings on action.
  3574. /// </summary>
  3575. public ushort* actionBindingIndicesAndCounts;
  3576. /// <summary>
  3577. /// Array of indices into <see cref="bindingStates"/>. The indices for every action are laid out sequentially.
  3578. /// The array slice corresponding to each action can be determined by looking it up in <see cref="actionBindingIndicesAndCounts"/>.
  3579. /// </summary>
  3580. public ushort* actionBindingIndices;
  3581. ////REVIEW: make this an array of shorts rather than ints?
  3582. public int* controlIndexToBindingIndex;
  3583. // Two shorts per control. First one is group number. Second one is complexity count.
  3584. public ushort* controlGroupingAndComplexity;
  3585. public bool controlGroupingInitialized;
  3586. public ActionMapIndices* mapIndices;
  3587. public void Allocate(int mapCount, int actionCount, int bindingCount, int controlCount, int interactionCount, int compositeCount)
  3588. {
  3589. Debug.Assert(basePtr == null, "Memory already allocated! Free first!");
  3590. Debug.Assert(mapCount >= 1, "Map count out of range");
  3591. Debug.Assert(actionCount >= 0, "Action count out of range");
  3592. Debug.Assert(bindingCount >= 0, "Binding count out of range");
  3593. Debug.Assert(interactionCount >= 0, "Interaction count out of range");
  3594. Debug.Assert(compositeCount >= 0, "Composite count out of range");
  3595. this.mapCount = mapCount;
  3596. this.actionCount = actionCount;
  3597. this.interactionCount = interactionCount;
  3598. this.bindingCount = bindingCount;
  3599. this.controlCount = controlCount;
  3600. this.compositeCount = compositeCount;
  3601. var numBytes = sizeInBytes;
  3602. var ptr = (byte*)UnsafeUtility.Malloc(numBytes, 8, Allocator.Persistent);
  3603. UnsafeUtility.MemClear(ptr, numBytes);
  3604. basePtr = ptr;
  3605. // NOTE: This depends on the individual structs being sufficiently aligned in order to not
  3606. // cause any misalignment here. TriggerState, InteractionState, and BindingState all
  3607. // contain doubles so put them first in memory to make sure they get proper alignment.
  3608. actionStates = (TriggerState*)ptr; ptr += actionCount * sizeof(TriggerState);
  3609. interactionStates = (InteractionState*)ptr; ptr += interactionCount * sizeof(InteractionState);
  3610. bindingStates = (BindingState*)ptr; ptr += bindingCount * sizeof(BindingState);
  3611. mapIndices = (ActionMapIndices*)ptr; ptr += mapCount * sizeof(ActionMapIndices);
  3612. controlMagnitudes = (float*)ptr; ptr += controlCount * sizeof(float);
  3613. compositeMagnitudes = (float*)ptr; ptr += compositeCount * sizeof(float);
  3614. controlIndexToBindingIndex = (int*)ptr; ptr += controlCount * sizeof(int);
  3615. controlGroupingAndComplexity = (ushort*)ptr; ptr += controlCount * sizeof(ushort) * 2;
  3616. actionBindingIndicesAndCounts = (ushort*)ptr; ptr += actionCount * sizeof(ushort) * 2;
  3617. actionBindingIndices = (ushort*)ptr; ptr += bindingCount * sizeof(ushort);
  3618. enabledControls = (int*)ptr; ptr += (controlCount + 31) / 32 * sizeof(int);
  3619. }
  3620. public void Dispose()
  3621. {
  3622. if (basePtr == null)
  3623. return;
  3624. UnsafeUtility.Free(basePtr, Allocator.Persistent);
  3625. basePtr = null;
  3626. actionStates = null;
  3627. interactionStates = null;
  3628. bindingStates = null;
  3629. mapIndices = null;
  3630. controlMagnitudes = null;
  3631. compositeMagnitudes = null;
  3632. controlIndexToBindingIndex = null;
  3633. controlGroupingAndComplexity = null;
  3634. actionBindingIndices = null;
  3635. actionBindingIndicesAndCounts = null;
  3636. mapCount = 0;
  3637. actionCount = 0;
  3638. bindingCount = 0;
  3639. controlCount = 0;
  3640. interactionCount = 0;
  3641. compositeCount = 0;
  3642. }
  3643. public void CopyDataFrom(UnmanagedMemory memory)
  3644. {
  3645. Debug.Assert(memory.basePtr != null, "Given struct has no allocated data");
  3646. // Even if a certain array is empty (e.g. we have no controls), we set the pointer
  3647. // in Allocate() to something other than null.
  3648. UnsafeUtility.MemCpy(mapIndices, memory.mapIndices, memory.mapCount * sizeof(ActionMapIndices));
  3649. UnsafeUtility.MemCpy(actionStates, memory.actionStates, memory.actionCount * sizeof(TriggerState));
  3650. UnsafeUtility.MemCpy(bindingStates, memory.bindingStates, memory.bindingCount * sizeof(BindingState));
  3651. UnsafeUtility.MemCpy(interactionStates, memory.interactionStates, memory.interactionCount * sizeof(InteractionState));
  3652. UnsafeUtility.MemCpy(controlMagnitudes, memory.controlMagnitudes, memory.controlCount * sizeof(float));
  3653. UnsafeUtility.MemCpy(compositeMagnitudes, memory.compositeMagnitudes, memory.compositeCount * sizeof(float));
  3654. UnsafeUtility.MemCpy(controlIndexToBindingIndex, memory.controlIndexToBindingIndex, memory.controlCount * sizeof(int));
  3655. UnsafeUtility.MemCpy(controlGroupingAndComplexity, memory.controlGroupingAndComplexity, memory.controlCount * sizeof(ushort) * 2);
  3656. UnsafeUtility.MemCpy(actionBindingIndicesAndCounts, memory.actionBindingIndicesAndCounts, memory.actionCount * sizeof(ushort) * 2);
  3657. UnsafeUtility.MemCpy(actionBindingIndices, memory.actionBindingIndices, memory.bindingCount * sizeof(ushort));
  3658. UnsafeUtility.MemCpy(enabledControls, memory.enabledControls, (memory.controlCount + 31) / 32 * sizeof(int));
  3659. }
  3660. public UnmanagedMemory Clone()
  3661. {
  3662. if (!isAllocated)
  3663. return new UnmanagedMemory();
  3664. var clone = new UnmanagedMemory();
  3665. clone.Allocate(
  3666. mapCount: mapCount,
  3667. actionCount: actionCount,
  3668. controlCount: controlCount,
  3669. bindingCount: bindingCount,
  3670. interactionCount: interactionCount,
  3671. compositeCount: compositeCount);
  3672. clone.CopyDataFrom(this);
  3673. return clone;
  3674. }
  3675. }
  3676. #region Global State
  3677. /// <summary>
  3678. /// Global state containing a list of weak references to all action map states currently in the system.
  3679. /// </summary>
  3680. /// <remarks>
  3681. /// When the control setup in the system changes, we need a way for control resolution that
  3682. /// has already been done to be invalidated and redone. We also want a way to find all
  3683. /// currently enabled actions in the system.
  3684. ///
  3685. /// Both of these needs are served by this global list.
  3686. /// </remarks>
  3687. internal struct GlobalState
  3688. {
  3689. internal InlinedArray<GCHandle> globalList;
  3690. internal CallbackArray<Action<object, InputActionChange>> onActionChange;
  3691. internal CallbackArray<Action<object>> onActionControlsChanged;
  3692. }
  3693. internal static GlobalState s_GlobalState;
  3694. internal static ISavedState SaveAndResetState()
  3695. {
  3696. // Save current state
  3697. var savedState = new SavedStructState<GlobalState>(
  3698. ref s_GlobalState,
  3699. (ref GlobalState state) => s_GlobalState = state, // restore
  3700. () => ResetGlobals()); // static dispose
  3701. // Reset global state
  3702. s_GlobalState = default;
  3703. return savedState;
  3704. }
  3705. private void AddToGlobalList()
  3706. {
  3707. CompactGlobalList();
  3708. var handle = GCHandle.Alloc(this, GCHandleType.Weak);
  3709. s_GlobalState.globalList.AppendWithCapacity(handle);
  3710. }
  3711. private void RemoveMapFromGlobalList()
  3712. {
  3713. var count = s_GlobalState.globalList.length;
  3714. for (var i = 0; i < count; ++i)
  3715. if (s_GlobalState.globalList[i].Target == this)
  3716. {
  3717. s_GlobalState.globalList[i].Free();
  3718. s_GlobalState.globalList.RemoveAtByMovingTailWithCapacity(i);
  3719. break;
  3720. }
  3721. }
  3722. /// <summary>
  3723. /// Remove any entries for states that have been reclaimed by GC.
  3724. /// </summary>
  3725. private static void CompactGlobalList()
  3726. {
  3727. var length = s_GlobalState.globalList.length;
  3728. var head = 0;
  3729. for (var i = 0; i < length; ++i)
  3730. {
  3731. var handle = s_GlobalState.globalList[i];
  3732. if (handle.IsAllocated && handle.Target != null)
  3733. {
  3734. if (head != i)
  3735. s_GlobalState.globalList[head] = handle;
  3736. ++head;
  3737. }
  3738. else
  3739. {
  3740. if (handle.IsAllocated)
  3741. s_GlobalState.globalList[i].Free();
  3742. s_GlobalState.globalList[i] = default;
  3743. }
  3744. }
  3745. s_GlobalState.globalList.length = head;
  3746. }
  3747. internal void NotifyListenersOfActionChange(InputActionChange change)
  3748. {
  3749. for (var i = 0; i < totalMapCount; ++i)
  3750. {
  3751. var map = maps[i];
  3752. if (map.m_SingletonAction != null)
  3753. {
  3754. NotifyListenersOfActionChange(change, map.m_SingletonAction);
  3755. }
  3756. else if (map.m_Asset == null)
  3757. {
  3758. NotifyListenersOfActionChange(change, map);
  3759. }
  3760. else
  3761. {
  3762. NotifyListenersOfActionChange(change, map.m_Asset);
  3763. return;
  3764. }
  3765. }
  3766. }
  3767. internal static void NotifyListenersOfActionChange(InputActionChange change, object actionOrMapOrAsset)
  3768. {
  3769. Debug.Assert(actionOrMapOrAsset != null, "Should have action or action map or asset object to notify about");
  3770. Debug.Assert(actionOrMapOrAsset is InputAction || (actionOrMapOrAsset as InputActionMap)?.m_SingletonAction == null,
  3771. "Must not send notifications for changes made to hidden action maps of singleton actions");
  3772. DelegateHelpers.InvokeCallbacksSafe(ref s_GlobalState.onActionChange, actionOrMapOrAsset, change, "onActionChange");
  3773. if (change == InputActionChange.BoundControlsChanged)
  3774. DelegateHelpers.InvokeCallbacksSafe(ref s_GlobalState.onActionControlsChanged, actionOrMapOrAsset, "onActionControlsChange");
  3775. }
  3776. /// <summary>
  3777. /// Nuke global state we have to keep track of action map states.
  3778. /// </summary>
  3779. private static void ResetGlobals()
  3780. {
  3781. DestroyAllActionMapStates();
  3782. for (var i = 0; i < s_GlobalState.globalList.length; ++i)
  3783. if (s_GlobalState.globalList[i].IsAllocated)
  3784. s_GlobalState.globalList[i].Free();
  3785. s_GlobalState.globalList.length = 0;
  3786. s_GlobalState.onActionChange.Clear();
  3787. s_GlobalState.onActionControlsChanged.Clear();
  3788. }
  3789. // Walk all maps with enabled actions and add all enabled actions to the given list.
  3790. internal static int FindAllEnabledActions(List<InputAction> result)
  3791. {
  3792. var numFound = 0;
  3793. var stateCount = s_GlobalState.globalList.length;
  3794. for (var i = 0; i < stateCount; ++i)
  3795. {
  3796. var handle = s_GlobalState.globalList[i];
  3797. if (!handle.IsAllocated)
  3798. continue;
  3799. var state = (InputActionState)handle.Target;
  3800. if (state == null)
  3801. continue;
  3802. var mapCount = state.totalMapCount;
  3803. var maps = state.maps;
  3804. for (var n = 0; n < mapCount; ++n)
  3805. {
  3806. var map = maps[n];
  3807. if (!map.enabled)
  3808. continue;
  3809. var actions = map.m_Actions;
  3810. var actionCount = actions.Length;
  3811. if (map.m_EnabledActionsCount == actionCount)
  3812. {
  3813. result.AddRange(actions);
  3814. numFound += actionCount;
  3815. }
  3816. else
  3817. {
  3818. var actionStartIndex = state.mapIndices[map.m_MapIndexInState].actionStartIndex;
  3819. for (var k = 0; k < actionCount; ++k)
  3820. {
  3821. if (state.actionStates[actionStartIndex + k].phase != InputActionPhase.Disabled)
  3822. {
  3823. result.Add(actions[k]);
  3824. ++numFound;
  3825. }
  3826. }
  3827. }
  3828. }
  3829. }
  3830. return numFound;
  3831. }
  3832. ////TODO: when re-resolving, we need to preserve InteractionStates and not just reset them
  3833. /// <summary>
  3834. /// Deal with the fact that the control setup in the system may change at any time and can affect
  3835. /// actions that had their controls already resolved.
  3836. /// </summary>
  3837. /// <remarks>
  3838. /// Note that this method can NOT deal with changes other than the control setup in the system
  3839. /// changing. Specifically, it will NOT handle configuration changes in action maps (e.g. bindings
  3840. /// being altered) correctly.
  3841. ///
  3842. /// We get called from <see cref="InputManager"/> directly rather than hooking into <see cref="InputSystem.onDeviceChange"/>
  3843. /// so that we're not adding needless calls for device changes that are not of interest to us.
  3844. /// </remarks>
  3845. internal static void OnDeviceChange(InputDevice device, InputDeviceChange change)
  3846. {
  3847. Debug.Assert(device != null, "Device is null");
  3848. ////REVIEW: should we ignore disconnected devices in InputBindingResolver?
  3849. Debug.Assert(
  3850. change == InputDeviceChange.Added || change == InputDeviceChange.Removed ||
  3851. change == InputDeviceChange.UsageChanged || change == InputDeviceChange.ConfigurationChanged ||
  3852. change == InputDeviceChange.SoftReset || change == InputDeviceChange.HardReset,
  3853. "Should only be called for relevant changes");
  3854. for (var i = 0; i < s_GlobalState.globalList.length; ++i)
  3855. {
  3856. var handle = s_GlobalState.globalList[i];
  3857. if (!handle.IsAllocated || handle.Target == null)
  3858. {
  3859. // Stale entry in the list. State has already been reclaimed by GC. Remove it.
  3860. if (handle.IsAllocated)
  3861. s_GlobalState.globalList[i].Free();
  3862. s_GlobalState.globalList.RemoveAtWithCapacity(i);
  3863. --i;
  3864. continue;
  3865. }
  3866. var state = (InputActionState)handle.Target;
  3867. // If this state is not affected by the change, skip.
  3868. var needsFullResolve = true;
  3869. switch (change)
  3870. {
  3871. case InputDeviceChange.Added:
  3872. if (!state.CanUseDevice(device))
  3873. continue;
  3874. needsFullResolve = false;
  3875. break;
  3876. case InputDeviceChange.Removed:
  3877. if (!state.IsUsingDevice(device))
  3878. continue;
  3879. // If the device is listed in a device mask (on either a map or an asset) in the
  3880. // state, remove it (see Actions_WhenDeviceIsRemoved_DeviceIsRemovedFromDeviceMask).
  3881. for (var n = 0; n < state.totalMapCount; ++n)
  3882. {
  3883. var map = state.maps[n];
  3884. map.m_Devices.Remove(device);
  3885. map.asset?.m_Devices.Remove(device);
  3886. }
  3887. needsFullResolve = false;
  3888. break;
  3889. // NOTE: ConfigurationChanges can affect display names of controls which may make a device usable that
  3890. // we didn't find anything usable on before.
  3891. case InputDeviceChange.ConfigurationChanged:
  3892. case InputDeviceChange.UsageChanged:
  3893. if (!state.IsUsingDevice(device) && !state.CanUseDevice(device))
  3894. continue;
  3895. // Full resolve necessary!
  3896. break;
  3897. // On reset, cancel all actions currently in progress from the device that got reset.
  3898. // If we simply let change monitors trigger, we will respond to things like button releases
  3899. // that are in fact just resets of buttons to their default state.
  3900. case InputDeviceChange.SoftReset:
  3901. case InputDeviceChange.HardReset:
  3902. if (!state.IsUsingDevice(device))
  3903. continue;
  3904. state.ResetActionStatesDrivenBy(device);
  3905. continue; // No re-resolving necessary.
  3906. }
  3907. // Trigger a lazy-resolve on all action maps in the state.
  3908. for (var n = 0; n < state.totalMapCount; ++n)
  3909. {
  3910. if (state.maps[n].LazyResolveBindings(fullResolve: needsFullResolve))
  3911. {
  3912. // Map has chosen to resolve right away. This will resolve bindings for *all*
  3913. // maps in the state, so we're done here.
  3914. break;
  3915. }
  3916. }
  3917. }
  3918. }
  3919. internal static void DeferredResolutionOfBindings()
  3920. {
  3921. ++InputActionMap.s_DeferBindingResolution;
  3922. try
  3923. {
  3924. for (var i = 0; i < s_GlobalState.globalList.length; ++i)
  3925. {
  3926. var handle = s_GlobalState.globalList[i];
  3927. var state = handle.IsAllocated ? (InputActionState)handle.Target : null;
  3928. if (state == null)
  3929. {
  3930. // Stale entry in the list. State has already been reclaimed by GC. Remove it.
  3931. if (handle.IsAllocated)
  3932. s_GlobalState.globalList[i].Free();
  3933. s_GlobalState.globalList.RemoveAtWithCapacity(i);
  3934. --i;
  3935. continue;
  3936. }
  3937. for (var n = 0; n < state.totalMapCount; ++n)
  3938. state.maps[n].ResolveBindingsIfNecessary();
  3939. }
  3940. }
  3941. finally
  3942. {
  3943. --InputActionMap.s_DeferBindingResolution;
  3944. }
  3945. }
  3946. internal static void DisableAllActions()
  3947. {
  3948. for (var i = 0; i < s_GlobalState.globalList.length; ++i)
  3949. {
  3950. var handle = s_GlobalState.globalList[i];
  3951. if (!handle.IsAllocated || handle.Target == null)
  3952. continue;
  3953. var state = (InputActionState)handle.Target;
  3954. var mapCount = state.totalMapCount;
  3955. var maps = state.maps;
  3956. for (var n = 0; n < mapCount; ++n)
  3957. {
  3958. maps[n].Disable();
  3959. Debug.Assert(!maps[n].enabled, "Map is still enabled after calling Disable");
  3960. }
  3961. }
  3962. }
  3963. /// <summary>
  3964. /// Forcibly destroy all states currently on the global list.
  3965. /// </summary>
  3966. /// <remarks>
  3967. /// We do this when exiting play mode in the editor to make sure we are cleaning up our
  3968. /// unmanaged memory allocations.
  3969. /// </remarks>
  3970. internal static void DestroyAllActionMapStates()
  3971. {
  3972. while (s_GlobalState.globalList.length > 0)
  3973. {
  3974. var index = s_GlobalState.globalList.length - 1;
  3975. var handle = s_GlobalState.globalList[index];
  3976. if (!handle.IsAllocated || handle.Target == null)
  3977. {
  3978. // Already destroyed.
  3979. if (handle.IsAllocated)
  3980. s_GlobalState.globalList[index].Free();
  3981. s_GlobalState.globalList.RemoveAtWithCapacity(index);
  3982. continue;
  3983. }
  3984. var state = (InputActionState)handle.Target;
  3985. state.Destroy();
  3986. }
  3987. }
  3988. #endregion
  3989. }
  3990. }