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13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Utilities;

////REVIEW: should this enumerate *backwards* in time rather than *forwards*?

////TODO: allow correlating history to frames/updates

////TODO: add ability to grow such that you can set it to e.g. record up to 4 seconds of history and it will automatically keep the buffer size bounded

////REVIEW: should we align the extra memory on a 4 byte boundary?

namespace UnityEngine.InputSystem.LowLevel
{
    /// <summary>
    /// Record a history of state changes applied to one or more controls.
    /// </summary>
    /// <remarks>
    /// This class makes it easy to track input values over time. It will automatically retain input state up to a given
    /// maximum history depth (<see cref="historyDepth"/>). When the history is full, it will start overwriting the oldest
    /// entry each time a new history record is received.
    ///
    /// The class listens to changes on the given controls by adding change monitors (<see cref="IInputStateChangeMonitor"/>)
    /// to each control.
    ///
    /// <example>
    /// <code>
    /// // Track all stick controls in the system.
    /// var history = new InputStateHistory&lt;Vector2&gt;("*/&lt;Stick&gt;");
    /// foreach (var control in history.controls)
    ///     Debug.Log("Capturing input on " + control);
    ///
    /// // Start capturing.
    /// history.StartRecording();
    ///
    /// // Perform a couple artificial value changes.
    /// Gamepad.current.leftStick.QueueValueChange(new Vector2(0.123f, 0.234f));
    /// Gamepad.current.leftStick.QueueValueChange(new Vector2(0.234f, 0.345f));
    /// Gamepad.current.leftStick.QueueValueChange(new Vector2(0.345f, 0.456f));
    /// InputSystem.Update();
    ///
    /// // Every value change will be visible in the history.
    /// foreach (var record in history)
    ///     Debug.Log($"{record.control} changed value to {record.ReadValue()}");
    ///
    /// // Histories allocate unmanaged memory and must be disposed of in order to not leak.
    /// history.Dispose();
    /// </code>
    /// </example>
    /// </remarks>
    public class InputStateHistory : IDisposable, IEnumerable<InputStateHistory.Record>, IInputStateChangeMonitor
    {
        private const int kDefaultHistorySize = 128;

        /// <summary>
        /// Total number of state records currently captured in the history.
        /// </summary>
        /// <value>Number of records in the collection.</value>
        /// <remarks>
        /// This will always be at most <see cref="historyDepth"/>.
        /// </remarks>
        /// <seealso cref="historyDepth"/>
        /// <seealso cref="RecordStateChange(InputControl,InputEventPtr)"/>
        public int Count => m_RecordCount;

        /// <summary>
        /// Current version stamp. Every time a record is stored in the history,
        /// this is incremented by one.
        /// </summary>
        /// <value>Version stamp that indicates the number of mutations.</value>
        /// <seealso cref="RecordStateChange(InputControl,InputEventPtr)"/>
        public uint version => m_CurrentVersion;

        /// <summary>
        /// Maximum number of records that can be recorded in the history.
        /// </summary>
        /// <value>Upper limit on number of records.</value>
        /// <exception cref="ArgumentException"><paramref name="value"/> is negative.</exception>
        /// <remarks>
        /// A fixed size memory block of unmanaged memory will be allocated to store history
        /// records. This property determines TODO
        /// </remarks>
        public int historyDepth
        {
            get => m_HistoryDepth;
            set
            {
                if (value < 0)
                    throw new ArgumentException("History depth cannot be negative", nameof(value));
                if (m_RecordBuffer.IsCreated)
                    throw new NotImplementedException();
                m_HistoryDepth = value;
            }
        }

        public int extraMemoryPerRecord
        {
            get => m_ExtraMemoryPerRecord;
            set
            {
                if (value < 0)
                    throw new ArgumentException("Memory size cannot be negative", nameof(value));
                if (m_RecordBuffer.IsCreated)
                    throw new NotImplementedException();
                m_ExtraMemoryPerRecord = value;
            }
        }

        public InputUpdateType updateMask
        {
            get => m_UpdateMask ?? InputSystem.s_Manager.updateMask & ~InputUpdateType.Editor;
            set
            {
                if (value == InputUpdateType.None)
                    throw new ArgumentException("'InputUpdateType.None' is not a valid update mask", nameof(value));
                m_UpdateMask = value;
            }
        }

        public ReadOnlyArray<InputControl> controls => new ReadOnlyArray<InputControl>(m_Controls, 0, m_ControlCount);

        public unsafe Record this[int index]
        {
            get
            {
                if (index < 0 || index >= m_RecordCount)
                    throw new ArgumentOutOfRangeException(
                        $"Index {index} is out of range for history with {m_RecordCount} entries", nameof(index));

                var recordIndex = UserIndexToRecordIndex(index);
                return new Record(this, recordIndex, GetRecord(recordIndex));
            }
            set
            {
                if (index < 0 || index >= m_RecordCount)
                    throw new ArgumentOutOfRangeException(
                        $"Index {index} is out of range for history with {m_RecordCount} entries", nameof(index));

                var recordIndex = UserIndexToRecordIndex(index);
                new Record(this, recordIndex, GetRecord(recordIndex)).CopyFrom(value);
            }
        }

        public Action<Record> onRecordAdded { get; set; }
        public Func<InputControl, double, InputEventPtr, bool> onShouldRecordStateChange { get; set; }

        public InputStateHistory(int maxStateSizeInBytes)
        {
            if (maxStateSizeInBytes <= 0)
                throw new ArgumentException("State size must be >= 0", nameof(maxStateSizeInBytes));

            m_AddNewControls = true;
            m_StateSizeInBytes = maxStateSizeInBytes.AlignToMultipleOf(4);
        }

        public InputStateHistory(string path)
        {
            using (var controls = InputSystem.FindControls(path))
            {
                m_Controls = controls.ToArray();
                m_ControlCount = m_Controls.Length;
            }
        }

        public InputStateHistory(InputControl control)
        {
            if (control == null)
                throw new ArgumentNullException(nameof(control));

            m_Controls = new[] {control};
            m_ControlCount = 1;
        }

        public InputStateHistory(IEnumerable<InputControl> controls)
        {
            if (controls != null)
            {
                m_Controls = controls.ToArray();
                m_ControlCount = m_Controls.Length;
            }
        }

        ~InputStateHistory()
        {
            Dispose();
        }

        public void Clear()
        {
            m_HeadIndex = 0;
            m_RecordCount = 0;
            ++m_CurrentVersion;

            // NOTE: Won't clear controls that have been added on the fly.
        }

        public unsafe Record AddRecord(Record record)
        {
            var recordPtr = AllocateRecord(out var index);
            var newRecord = new Record(this, index, recordPtr);
            newRecord.CopyFrom(record);
            return newRecord;
        }

        public void StartRecording()
        {
            // We defer allocation until we actually get values on a control.

            foreach (var control in controls)
                InputState.AddChangeMonitor(control, this);
        }

        public void StopRecording()
        {
            foreach (var control in controls)
                InputState.RemoveChangeMonitor(control, this);
        }

        public unsafe Record RecordStateChange(InputControl control, InputEventPtr eventPtr)
        {
            if (eventPtr.IsA<DeltaStateEvent>())
                throw new NotImplementedException();

            if (!eventPtr.IsA<StateEvent>())
                throw new ArgumentException($"Event must be a state event but is '{eventPtr}' instead",
                    nameof(eventPtr));

            var statePtr = (byte*)StateEvent.From(eventPtr)->state - control.device.stateBlock.byteOffset;
            return RecordStateChange(control, statePtr, eventPtr.time);
        }

        public unsafe Record RecordStateChange(InputControl control, void* statePtr, double time)
        {
            var controlIndex = ArrayHelpers.IndexOfReference(m_Controls, control, m_ControlCount);
            if (controlIndex == -1)
            {
                if (m_AddNewControls)
                {
                    if (control.stateBlock.alignedSizeInBytes > m_StateSizeInBytes)
                        throw new InvalidOperationException(
                            $"Cannot add control '{control}' with state larger than {m_StateSizeInBytes} bytes");
                    controlIndex = ArrayHelpers.AppendWithCapacity(ref m_Controls, ref m_ControlCount, control);
                }
                else
                    throw new ArgumentException($"Control '{control}' is not part of InputStateHistory",
                        nameof(control));
            }

            var recordPtr = AllocateRecord(out var index);
            recordPtr->time = time;
            recordPtr->version = ++m_CurrentVersion;
            var stateBufferPtr = recordPtr->statePtrWithoutControlIndex;
            if (m_ControlCount > 1 || m_AddNewControls)
            {
                // If there's multiple controls, write index of control to which the state change
                // pertains as an int before the state memory contents following it.
                recordPtr->controlIndex = controlIndex;
                stateBufferPtr = recordPtr->statePtrWithControlIndex;
            }

            var stateSize = control.stateBlock.alignedSizeInBytes;
            var stateOffset = control.stateBlock.byteOffset;

            UnsafeUtility.MemCpy(stateBufferPtr, (byte*)statePtr + stateOffset, stateSize);

            // Trigger callback.
            var record = new Record(this, index, recordPtr);
            onRecordAdded?.Invoke(record);

            return record;
        }

        public IEnumerator<Record> GetEnumerator()
        {
            return new Enumerator(this);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void Dispose()
        {
            StopRecording();
            Destroy();
            GC.SuppressFinalize(this);
        }

        protected void Destroy()
        {
            if (m_RecordBuffer.IsCreated)
            {
                m_RecordBuffer.Dispose();
                m_RecordBuffer = new NativeArray<byte>();
            }
        }

        private void Allocate()
        {
            // Find max size of state.
            if (!m_AddNewControls)
            {
                m_StateSizeInBytes = 0;
                foreach (var control in controls)
                    m_StateSizeInBytes = (int)Math.Max((uint)m_StateSizeInBytes, control.stateBlock.alignedSizeInBytes);
            }
            else
            {
                Debug.Assert(m_StateSizeInBytes > 0, "State size must be have initialized!");
            }

            // Allocate historyDepth times state blocks of the given max size. For each one
            // add space for the RecordHeader header.
            // NOTE: If we only have a single control, we omit storing the integer control index.
            var totalSizeOfBuffer = bytesPerRecord * m_HistoryDepth;
            m_RecordBuffer = new NativeArray<byte>(totalSizeOfBuffer, Allocator.Persistent,
                NativeArrayOptions.UninitializedMemory);
        }

        protected internal int RecordIndexToUserIndex(int index)
        {
            if (index < m_HeadIndex)
                return m_HistoryDepth - m_HeadIndex + index;
            return index - m_HeadIndex;
        }

        protected internal int UserIndexToRecordIndex(int index)
        {
            return (m_HeadIndex + index) % m_HistoryDepth;
        }

        protected internal unsafe RecordHeader* GetRecord(int index)
        {
            if (!m_RecordBuffer.IsCreated)
                throw new InvalidOperationException("History buffer has been disposed");
            if (index < 0 || index >= m_HistoryDepth)
                throw new ArgumentOutOfRangeException(nameof(index));
            return GetRecordUnchecked(index);
        }

        internal unsafe RecordHeader* GetRecordUnchecked(int index)
        {
            return (RecordHeader*)((byte*)m_RecordBuffer.GetUnsafePtr() + index * bytesPerRecord);
        }

        protected internal unsafe RecordHeader* AllocateRecord(out int index)
        {
            if (!m_RecordBuffer.IsCreated)
                Allocate();

            index = (m_HeadIndex + m_RecordCount) % m_HistoryDepth;

            // If we're full, advance head to make room.
            if (m_RecordCount == m_HistoryDepth)
                m_HeadIndex = (m_HeadIndex + 1) % m_HistoryDepth;
            else
            {
                // We have a fixed max size given by the history depth and will start overwriting
                // older entries once we reached max size.
                ++m_RecordCount;
            }

            return (RecordHeader*)((byte*)m_RecordBuffer.GetUnsafePtr() + bytesPerRecord * index);
        }

        protected unsafe TValue ReadValue<TValue>(RecordHeader* data)
            where TValue : struct
        {
            // Get control. If we only have a single one, the index isn't stored on the data.
            var haveSingleControl = m_ControlCount == 1 && !m_AddNewControls;
            var control = haveSingleControl ? controls[0] : controls[data->controlIndex];
            if (!(control is InputControl<TValue> controlOfType))
                throw new InvalidOperationException(
                    $"Cannot read value of type '{TypeHelpers.GetNiceTypeName(typeof(TValue))}' from control '{control}' with value type '{TypeHelpers.GetNiceTypeName(control.valueType)}'");

            // Grab state memory.
            var statePtr = haveSingleControl ? data->statePtrWithoutControlIndex : data->statePtrWithControlIndex;
            statePtr -= control.stateBlock.byteOffset;
            return controlOfType.ReadValueFromState(statePtr);
        }

        protected unsafe object ReadValueAsObject(RecordHeader* data)
        {
            // Get control. If we only have a single one, the index isn't stored on the data.
            var haveSingleControl = m_ControlCount == 1 && !m_AddNewControls;
            var control = haveSingleControl ? controls[0] : controls[data->controlIndex];

            // Grab state memory.
            var statePtr = haveSingleControl ? data->statePtrWithoutControlIndex : data->statePtrWithControlIndex;
            statePtr -= control.stateBlock.byteOffset;
            return control.ReadValueFromStateAsObject(statePtr);
        }

        unsafe void IInputStateChangeMonitor.NotifyControlStateChanged(InputControl control, double time,
            InputEventPtr eventPtr, long monitorIndex)
        {
            // Ignore state change if it's in an input update we're not interested in.
            var currentUpdateType = InputState.currentUpdateType;
            var updateTypeMask = updateMask;
            if ((currentUpdateType & updateTypeMask) == 0)
                return;

            // Ignore state change if we have a filter and the state change doesn't pass the check.
            if (onShouldRecordStateChange != null && !onShouldRecordStateChange(control, time, eventPtr))
                return;

            RecordStateChange(control, control.currentStatePtr, time);
        }

        // Unused.
        void IInputStateChangeMonitor.NotifyTimerExpired(InputControl control, double time, long monitorIndex,
            int timerIndex)
        {
        }

        internal InputControl[] m_Controls;
        internal int m_ControlCount;
        private NativeArray<byte> m_RecordBuffer;
        private int m_StateSizeInBytes;
        private int m_RecordCount;
        private int m_HistoryDepth = kDefaultHistorySize;
        private int m_ExtraMemoryPerRecord;
        internal int m_HeadIndex;
        internal uint m_CurrentVersion;
        private InputUpdateType? m_UpdateMask;
        internal readonly bool m_AddNewControls;

        internal int bytesPerRecord =>
            (m_StateSizeInBytes +
                m_ExtraMemoryPerRecord +
                (m_ControlCount == 1 && !m_AddNewControls
                    ? RecordHeader.kSizeWithoutControlIndex
                    : RecordHeader.kSizeWithControlIndex)).AlignToMultipleOf(4);

        private struct Enumerator : IEnumerator<Record>
        {
            private readonly InputStateHistory m_History;
            private int m_Index;

            public Enumerator(InputStateHistory history)
            {
                m_History = history;
                m_Index = -1;
            }

            public bool MoveNext()
            {
                if (m_Index + 1 >= m_History.Count)
                    return false;
                ++m_Index;
                return true;
            }

            public void Reset()
            {
                m_Index = -1;
            }

            public Record Current => m_History[m_Index];

            object IEnumerator.Current => Current;

            public void Dispose()
            {
            }
        }

        [StructLayout(LayoutKind.Explicit)]
        protected internal unsafe struct RecordHeader
        {
            [FieldOffset(0)] public double time;
            [FieldOffset(8)] public uint version;
            [FieldOffset(12)] public int controlIndex;

            [FieldOffset(12)] private fixed byte m_StateWithoutControlIndex[1];
            [FieldOffset(16)] private fixed byte m_StateWithControlIndex[1];

            public byte* statePtrWithControlIndex
            {
                get
                {
                    fixed(byte* ptr = m_StateWithControlIndex)
                    return ptr;
                }
            }

            public byte* statePtrWithoutControlIndex
            {
                get
                {
                    fixed(byte* ptr = m_StateWithoutControlIndex)
                    return ptr;
                }
            }

            public const int kSizeWithControlIndex = 16;
            public const int kSizeWithoutControlIndex = 12;
        }

        public unsafe struct Record : IEquatable<Record>
        {
            // We store an index rather than a direct pointer to make this struct safer to use.
            private readonly InputStateHistory m_Owner;
            private readonly int m_IndexPlusOne; // Plus one so that default(int) works for us.
            private uint m_Version;

            internal RecordHeader* header => m_Owner.GetRecord(recordIndex);
            internal int recordIndex => m_IndexPlusOne - 1;
            internal uint version => m_Version;

            public bool valid => m_Owner != default && m_IndexPlusOne != default && header->version == m_Version;

            public InputStateHistory owner => m_Owner;

            public int index
            {
                get
                {
                    CheckValid();
                    return m_Owner.RecordIndexToUserIndex(recordIndex);
                }
            }

            public double time
            {
                get
                {
                    CheckValid();
                    return header->time;
                }
            }

            public InputControl control
            {
                get
                {
                    CheckValid();
                    var controls = m_Owner.controls;
                    if (controls.Count == 1 && !m_Owner.m_AddNewControls)
                        return controls[0];
                    return controls[header->controlIndex];
                }
            }

            public Record next
            {
                get
                {
                    CheckValid();
                    var userIndex = m_Owner.RecordIndexToUserIndex(this.recordIndex);
                    if (userIndex + 1 >= m_Owner.Count)
                        return default;
                    var recordIndex = m_Owner.UserIndexToRecordIndex(userIndex + 1);
                    return new Record(m_Owner, recordIndex, m_Owner.GetRecord(recordIndex));
                }
            }

            public Record previous
            {
                get
                {
                    CheckValid();
                    var userIndex = m_Owner.RecordIndexToUserIndex(this.recordIndex);
                    if (userIndex - 1 < 0)
                        return default;
                    var recordIndex = m_Owner.UserIndexToRecordIndex(userIndex - 1);
                    return new Record(m_Owner, recordIndex, m_Owner.GetRecord(recordIndex));
                }
            }

            internal Record(InputStateHistory owner, int index, RecordHeader* header)
            {
                m_Owner = owner;
                m_IndexPlusOne = index + 1;
                m_Version = header->version;
            }

            public TValue ReadValue<TValue>()
                where TValue : struct
            {
                CheckValid();
                return m_Owner.ReadValue<TValue>(header);
            }

            public object ReadValueAsObject()
            {
                CheckValid();
                return m_Owner.ReadValueAsObject(header);
            }

            public void* GetUnsafeMemoryPtr()
            {
                CheckValid();
                return GetUnsafeMemoryPtrUnchecked();
            }

            internal void* GetUnsafeMemoryPtrUnchecked()
            {
                if (m_Owner.controls.Count == 1 && !m_Owner.m_AddNewControls)
                    return header->statePtrWithoutControlIndex;
                return header->statePtrWithControlIndex;
            }

            public void* GetUnsafeExtraMemoryPtr()
            {
                CheckValid();
                return GetUnsafeExtraMemoryPtrUnchecked();
            }

            internal void* GetUnsafeExtraMemoryPtrUnchecked()
            {
                if (m_Owner.extraMemoryPerRecord == 0)
                    throw new InvalidOperationException("No extra memory has been set up for history records; set extraMemoryPerRecord");
                return (byte*)header + m_Owner.bytesPerRecord - m_Owner.extraMemoryPerRecord;
            }

            public void CopyFrom(Record record)
            {
                if (!record.valid)
                    throw new ArgumentException("Given history record is not valid", nameof(record));
                CheckValid();

                // Find control.
                var control = record.control;
                var controlIndex = m_Owner.controls.IndexOfReference(control);
                if (controlIndex == -1)
                {
                    // We haven't found it. Throw if we can't add it.
                    if (!m_Owner.m_AddNewControls)
                        throw new InvalidOperationException($"Control '{record.control}' is not tracked by target history");

                    controlIndex =
                        ArrayHelpers.AppendWithCapacity(ref m_Owner.m_Controls, ref m_Owner.m_ControlCount, control);
                }

                // Make sure memory sizes match.
                var numBytesForState = m_Owner.m_StateSizeInBytes;
                if (numBytesForState != record.m_Owner.m_StateSizeInBytes)
                    throw new InvalidOperationException(
                        $"Cannot copy record from owner with state size '{record.m_Owner.m_StateSizeInBytes}' to owner with state size '{numBytesForState}'");

                // Copy and update header.
                var thisRecordPtr = header;
                var otherRecordPtr = record.header;
                UnsafeUtility.MemCpy(thisRecordPtr, otherRecordPtr, RecordHeader.kSizeWithoutControlIndex);
                thisRecordPtr->version = ++m_Owner.m_CurrentVersion;
                m_Version = thisRecordPtr->version;

                // Copy state.
                var dstPtr = thisRecordPtr->statePtrWithoutControlIndex;
                if (m_Owner.controls.Count > 1 || m_Owner.m_AddNewControls)
                {
                    thisRecordPtr->controlIndex = controlIndex;
                    dstPtr = thisRecordPtr->statePtrWithControlIndex;
                }
                var srcPtr = record.m_Owner.m_ControlCount > 1 || record.m_Owner.m_AddNewControls
                    ? otherRecordPtr->statePtrWithControlIndex
                    : otherRecordPtr->statePtrWithoutControlIndex;
                UnsafeUtility.MemCpy(dstPtr, srcPtr, numBytesForState);

                // Copy extra memory, but only if the size in the source and target
                // history are identical.
                var numBytesExtraMemory = m_Owner.m_ExtraMemoryPerRecord;
                if (numBytesExtraMemory > 0 && numBytesExtraMemory == record.m_Owner.m_ExtraMemoryPerRecord)
                    UnsafeUtility.MemCpy(GetUnsafeExtraMemoryPtr(), record.GetUnsafeExtraMemoryPtr(),
                        numBytesExtraMemory);

                // Notify.
                m_Owner.onRecordAdded?.Invoke(this);
            }

            internal void CheckValid()
            {
                if (m_Owner == default || m_IndexPlusOne == default)
                    throw new InvalidOperationException("Value not initialized");
                ////TODO: need to check whether memory has been disposed
                if (header->version != m_Version)
                    throw new InvalidOperationException("Record is no longer valid");
            }

            public bool Equals(Record other)
            {
                return ReferenceEquals(m_Owner, other.m_Owner) && m_IndexPlusOne == other.m_IndexPlusOne && m_Version == other.m_Version;
            }

            public override bool Equals(object obj)
            {
                return obj is Record other && Equals(other);
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    var hashCode = m_Owner != null ? m_Owner.GetHashCode() : 0;
                    hashCode = (hashCode * 397) ^ m_IndexPlusOne;
                    hashCode = (hashCode * 397) ^ (int)m_Version;
                    return hashCode;
                }
            }

            public override string ToString()
            {
                if (!valid)
                    return "<Invalid>";

                return $"{{ control={control} value={ReadValueAsObject()} time={time} }}";
            }
        }
    }

    /// <summary>
    /// Records value changes of a given control over time.
    /// </summary>
    /// <typeparam name="TValue"></typeparam>
    public class InputStateHistory<TValue> : InputStateHistory, IReadOnlyList<InputStateHistory<TValue>.Record>
        where TValue : struct
    {
        public InputStateHistory(int? maxStateSizeInBytes = null)
        // Using the size of the value here isn't quite correct but the value is used as an upper
        // bound on stored state size for which the size of the value should be a reasonable guess.
            : base(maxStateSizeInBytes ?? UnsafeUtility.SizeOf<TValue>())
        {
            if (maxStateSizeInBytes < UnsafeUtility.SizeOf<TValue>())
                throw new ArgumentException("Max state size cannot be smaller than sizeof(TValue)", nameof(maxStateSizeInBytes));
        }

        public InputStateHistory(InputControl<TValue> control)
            : base(control)
        {
        }

        public InputStateHistory(string path)
            : base(path)
        {
            // Make sure that the value type of all matched controls is compatible with TValue.
            foreach (var control in controls)
                if (!typeof(TValue).IsAssignableFrom(control.valueType))
                    throw new ArgumentException(
                        $"Control '{control}' matched by '{path}' has value type '{TypeHelpers.GetNiceTypeName(control.valueType)}' which is incompatible with '{TypeHelpers.GetNiceTypeName(typeof(TValue))}'");
        }

        ~InputStateHistory()
        {
            Destroy();
        }

        public unsafe Record AddRecord(Record record)
        {
            var recordPtr = AllocateRecord(out var index);
            var newRecord = new Record(this, index, recordPtr);
            newRecord.CopyFrom(record);
            return newRecord;
        }

        public unsafe Record RecordStateChange(InputControl<TValue> control, TValue value, double time = -1)
        {
            using (StateEvent.From(control.device, out var eventPtr))
            {
                var statePtr = (byte*)StateEvent.From(eventPtr)->state - control.device.stateBlock.byteOffset;
                control.WriteValueIntoState(value, statePtr);
                if (time >= 0)
                    eventPtr.time = time;
                var record = RecordStateChange(control, eventPtr);
                return new Record(this, record.recordIndex, record.header);
            }
        }

        public new IEnumerator<Record> GetEnumerator()
        {
            return new Enumerator(this);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public new unsafe Record this[int index]
        {
            get
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(
                        $"Index {index} is out of range for history with {Count} entries", nameof(index));

                var recordIndex = UserIndexToRecordIndex(index);
                return new Record(this, recordIndex, GetRecord(recordIndex));
            }
            set
            {
                if (index < 0 || index >= Count)
                    throw new ArgumentOutOfRangeException(
                        $"Index {index} is out of range for history with {Count} entries", nameof(index));
                var recordIndex = UserIndexToRecordIndex(index);
                new Record(this, recordIndex, GetRecord(recordIndex)).CopyFrom(value);
            }
        }

        private struct Enumerator : IEnumerator<Record>
        {
            private readonly InputStateHistory<TValue> m_History;
            private int m_Index;

            public Enumerator(InputStateHistory<TValue> history)
            {
                m_History = history;
                m_Index = -1;
            }

            public bool MoveNext()
            {
                if (m_Index + 1 >= m_History.Count)
                    return false;
                ++m_Index;
                return true;
            }

            public void Reset()
            {
                m_Index = -1;
            }

            public Record Current => m_History[m_Index];

            object IEnumerator.Current => Current;

            public void Dispose()
            {
            }
        }

        public new unsafe struct Record : IEquatable<Record>
        {
            private readonly InputStateHistory<TValue> m_Owner;
            private readonly int m_IndexPlusOne;
            private uint m_Version;

            internal RecordHeader* header => m_Owner.GetRecord(recordIndex);
            internal int recordIndex => m_IndexPlusOne - 1;

            public bool valid => m_Owner != default && m_IndexPlusOne != default && header->version == m_Version;

            public InputStateHistory<TValue> owner => m_Owner;

            public int index
            {
                get
                {
                    CheckValid();
                    return m_Owner.RecordIndexToUserIndex(recordIndex);
                }
            }

            public double time
            {
                get
                {
                    CheckValid();
                    return header->time;
                }
            }

            public InputControl<TValue> control
            {
                get
                {
                    CheckValid();
                    var controls = m_Owner.controls;
                    if (controls.Count == 1 && !m_Owner.m_AddNewControls)
                        return (InputControl<TValue>)controls[0];
                    return (InputControl<TValue>)controls[header->controlIndex];
                }
            }

            public Record next
            {
                get
                {
                    CheckValid();
                    var userIndex = m_Owner.RecordIndexToUserIndex(this.recordIndex);
                    if (userIndex + 1 >= m_Owner.Count)
                        return default;
                    var recordIndex = m_Owner.UserIndexToRecordIndex(userIndex + 1);
                    return new Record(m_Owner, recordIndex, m_Owner.GetRecord(recordIndex));
                }
            }

            public Record previous
            {
                get
                {
                    CheckValid();
                    var userIndex = m_Owner.RecordIndexToUserIndex(this.recordIndex);
                    if (userIndex - 1 < 0)
                        return default;
                    var recordIndex = m_Owner.UserIndexToRecordIndex(userIndex - 1);
                    return new Record(m_Owner, recordIndex, m_Owner.GetRecord(recordIndex));
                }
            }

            internal Record(InputStateHistory<TValue> owner, int index, RecordHeader* header)
            {
                m_Owner = owner;
                m_IndexPlusOne = index + 1;
                m_Version = header->version;
            }

            internal Record(InputStateHistory<TValue> owner, int index)
            {
                m_Owner = owner;
                m_IndexPlusOne = index + 1;
                m_Version = default;
            }

            public TValue ReadValue()
            {
                CheckValid();
                return m_Owner.ReadValue<TValue>(header);
            }

            public void* GetUnsafeMemoryPtr()
            {
                CheckValid();
                return GetUnsafeMemoryPtrUnchecked();
            }

            internal void* GetUnsafeMemoryPtrUnchecked()
            {
                if (m_Owner.controls.Count == 1 && !m_Owner.m_AddNewControls)
                    return header->statePtrWithoutControlIndex;
                return header->statePtrWithControlIndex;
            }

            public void* GetUnsafeExtraMemoryPtr()
            {
                CheckValid();
                return GetUnsafeExtraMemoryPtrUnchecked();
            }

            internal void* GetUnsafeExtraMemoryPtrUnchecked()
            {
                if (m_Owner.extraMemoryPerRecord == 0)
                    throw new InvalidOperationException("No extra memory has been set up for history records; set extraMemoryPerRecord");
                return (byte*)header + m_Owner.bytesPerRecord - m_Owner.extraMemoryPerRecord;
            }

            public void CopyFrom(Record record)
            {
                CheckValid();
                if (!record.valid)
                    throw new ArgumentException("Given history record is not valid", nameof(record));
                var temp = new InputStateHistory.Record(m_Owner, recordIndex, header);
                temp.CopyFrom(new InputStateHistory.Record(record.m_Owner, record.recordIndex, record.header));
                m_Version = temp.version;
            }

            private void CheckValid()
            {
                if (m_Owner == default || m_IndexPlusOne == default)
                    throw new InvalidOperationException("Value not initialized");
                if (header->version != m_Version)
                    throw new InvalidOperationException("Record is no longer valid");
            }

            public bool Equals(Record other)
            {
                return ReferenceEquals(m_Owner, other.m_Owner) && m_IndexPlusOne == other.m_IndexPlusOne && m_Version == other.m_Version;
            }

            public override bool Equals(object obj)
            {
                return obj is Record other && Equals(other);
            }

            public override int GetHashCode()
            {
                unchecked
                {
                    var hashCode = m_Owner != null ? m_Owner.GetHashCode() : 0;
                    hashCode = (hashCode * 397) ^ m_IndexPlusOne;
                    hashCode = (hashCode * 397) ^ (int)m_Version;
                    return hashCode;
                }
            }

            public override string ToString()
            {
                if (!valid)
                    return "<Invalid>";

                return $"{{ control={control} value={ReadValue()} time={time} }}";
            }
        }
    }
}