Exemplo n.º 1
0
                        /// <summary>
                        /// Called from Frame Sequencer clocks
                        /// </summary>
                        public void FreqTimerStep( )
                        {
                            m_timer -= 4;

                            if (m_timer <= 0)
                            {
                                // Note: shifts of 14 and 15 have no operation
                                if (m_shiftFreq < 14)
                                {
                                    int result = (m_linearShiftReg & 0x1) ^ ((m_linearShiftReg >> 1) & 0x1);
                                    m_linearShiftReg >>= 1;
                                    m_linearShiftReg  |= result << 14;
                                    if (m_stepsMode == 1)
                                    {
                                        m_linearShiftReg &= ~0x40; // clear bit 6
                                        m_linearShiftReg |= result << 6;
                                    }
                                }

                                // Reload Frequency
                                m_timer += CalcFrequency();
                            }


                            // Update filter buffer
                            m_samplesToFilterL.Dequeue();
                            m_samplesToFilterL.Enqueue(SampleL());

                            m_samplesToFilterR.Dequeue();
                            m_samplesToFilterR.Enqueue(SampleR());
                        }
Exemplo n.º 2
0
 private void ResetBuffer()
 {
     for (int i = 0; i < FrameSamples; i++)
     {
         _buffer.Enqueue(Time.fixedDeltaTime);
     }
 }
Exemplo n.º 3
0
 public void Print(string line)
 {
     string[] array = line.Split(new char[]
     {
         '\n'
     });
     string[] array2 = array;
     for (int i = 0; i < array2.Length; i++)
     {
         string text  = array2[i];
         string text2 = text;
         while (text2.Length > maxLineWidth)
         {
             int num = text2.LastIndexOf(' ', maxLineWidth);
             if (num >= maxLineWidth / 2)
             {
                 lines.Enqueue(text2.Substring(0, num));
                 text2 = text2.Substring(num + 1);
             }
             else
             {
                 lines.Enqueue(text2.Substring(0, maxLineWidth));
                 text2 = text2.Substring(maxLineWidth + 1);
             }
         }
         lines.Enqueue(text2);
     }
 }
Exemplo n.º 4
0
    private void ProcessData()
    {
        Array.Copy(readStreams[curMemIndex], curMemPos, lenByts, 0, 4);
        curMemPos = curMemPos + 4;
        //读出的协议的长度,
        long msgLen = BitConverter.ToInt64(lenByts, 0);

        var tmp = new byte[msgLen];

        //当前流包含了完整的协议信息

        //TODO:一下代码做了一个假设,当在一个缓冲中没有读取完的消息,在下一个缓冲中一定能读取成功,可能在某些极限情况下会出现bug
        if (msgLen + curMemPos < streamLimit)
        {
            Array.Copy(readStreams[curMemIndex], curMemPos, tmp, 0, msgLen);
            //设置当前的字节位置
            curMemPos = curMemPos + msgLen;

            //TODO:如果单次处理的协议过多,可能会导致环形缓冲溢出,这里也需要注意
            msgCache.Enqueue(new ByteBuffer(tmp, 4));
        }
        else
        {
            //复制当前缓冲中剩余的字节
            Array.Copy(readStreams[curMemIndex], curMemPos, tmp, 0, streamLimit - curMemPos);
            //切换到另一个字节数组
            curMemIndex = curMemIndex == 0 ? 1 : 0;
            msgLen      = msgLen - (streamLimit - curMemPos);
            Array.Copy(readStreams[curMemIndex], 0, tmp, streamLimit - curMemPos, msgLen);
            curMemPos = msgLen;

            msgCache.Enqueue(new ByteBuffer(tmp, 4));
        }
    }
Exemplo n.º 5
0
        public void Pop()
        {
            const int size = 10;
            var       buff = new CircularBuffer <int>(size);

            for (int i = 0; i < size; i++)
            {
                buff.Enqueue(i);
                Assert.Equal(i + 1, buff.Length);
            }

            int popped;

            for (int i = size; i < 10_000; i++)
            {
                popped = buff.Pop();
                Assert.Equal(i - 1, popped);
                Assert.Equal(size - 1, buff.Length);

                buff.Enqueue(i);
                Assert.Equal(size, buff.Length);
            }

            popped = buff.Pop();
            Assert.Equal(9_999, popped);

            for (int i = 8; i >= 0; i--)
            {
                popped = buff.Pop();
                Assert.Equal(i, popped);
                Assert.Equal(i, buff.Length);
            }
        }
Exemplo n.º 6
0
        public void RemoveAtTest()
        {
            var buffer = new CircularBuffer <long>(5);

            Assert.AreEqual(default(long), buffer.Enqueue(1));
            Assert.AreEqual(default(long), buffer.Enqueue(2));
            Assert.AreEqual(default(long), buffer.Enqueue(3));
            Assert.AreEqual(default(long), buffer.Enqueue(4));
            Assert.AreEqual(default(long), buffer.Enqueue(5));
            buffer.RemoveAt(buffer.IndexOf(2));
            buffer.RemoveAt(buffer.IndexOf(4));
            Assert.AreEqual(3, buffer.Count);
            Assert.AreEqual(1, buffer.Dequeue());
            Assert.AreEqual(3, buffer.Dequeue());
            Assert.AreEqual(5, buffer.Dequeue());
            Assert.AreEqual(0, buffer.Count);
            Assert.AreEqual(default(long), buffer.Enqueue(1));
            Assert.AreEqual(default(long), buffer.Enqueue(2));
            Assert.AreEqual(default(long), buffer.Enqueue(3));
            Assert.AreEqual(default(long), buffer.Enqueue(4));
            Assert.AreEqual(default(long), buffer.Enqueue(5));
            buffer.RemoveAt(buffer.IndexOf(1));
            buffer.RemoveAt(buffer.IndexOf(3));
            buffer.RemoveAt(buffer.IndexOf(5));
            Assert.AreEqual(2, buffer.Count);
            Assert.AreEqual(2, buffer.Dequeue());
            Assert.AreEqual(4, buffer.Dequeue());
            Assert.AreEqual(0, buffer.Count);
        }
        public void TestAddNode3()
        {
            var pop           = CreateNeatPopulation();
            var genomeBuilder = NeatGenomeBuilderFactory <double> .Create(pop.MetaNeatGenome);

            var genome = pop.GenomeList[0];

            var strategy = new AddNodeStrategy <double>(
                pop.MetaNeatGenome, genomeBuilder,
                pop.GenomeIdSeq, pop.InnovationIdSeq, pop.GenerationSeq,
                pop.AddedNodeBuffer);

            IRandomSource rng = RandomDefaults.CreateRandomSource();

            CircularBuffer <NeatGenome <double> > genomeRing = new CircularBuffer <NeatGenome <double> >(10);

            genomeRing.Enqueue(genome);

            for (int i = 0; i < 5000; i++)
            {
                NeatGenome <double> childGenome = CreateAndTestChildGenome(genome, strategy, rng);

                // Add the new child genome to the ring.
                genomeRing.Enqueue(childGenome);

                // Take the genome at the tail of the ring for the next parent.
                genome = genomeRing[0];
            }
        }
Exemplo n.º 8
0
        public void IndexSetterThrowsIfOutOfBoundsTest()
        {
            var cb = new CircularBuffer <int>(2);

            cb.Enqueue(1);
            cb.Enqueue(2);
            Assert.Throws <ArgumentOutOfRangeException>(() => { cb[2] = 5; });
        }
Exemplo n.º 9
0
 public void Reclaim()
 {
     _availables.Clear();
     foreach (var item in _backup)
     {
         _availables.Enqueue(item);
     }
 }
Exemplo n.º 10
0
        private void Update()
        {
            UpdateInput();

            CorrectDeadzone();

            CheckButtonState(HVRButtons.Grip, ref GripButtonState);
            CheckButtonState(HVRButtons.Trigger, ref TriggerButtonState);
            CheckButtonState(HVRButtons.JoystickButton, ref JoystickButtonState);
            CheckButtonState(HVRButtons.TrackPadButton, ref TrackpadButtonState);
            CheckButtonState(HVRButtons.Primary, ref PrimaryButtonState);
            CheckButtonState(HVRButtons.Secondary, ref SecondaryButtonState);
            CheckButtonState(HVRButtons.Menu, ref MenuButtonState);
            CheckButtonState(HVRButtons.PrimaryTouch, ref PrimaryTouchButtonState);
            CheckButtonState(HVRButtons.SecondaryTouch, ref SecondaryTouchButtonState);
            CheckButtonState(HVRButtons.JoystickTouch, ref JoystickTouchState);
            CheckButtonState(HVRButtons.TrackPadTouch, ref TrackPadTouchState);
            CheckButtonState(HVRButtons.TriggerTouch, ref TriggerTouchState);
            CheckButtonState(HVRButtons.ThumbTouch, ref ThumbTouchState);
            CheckButtonState(HVRButtons.TriggerNearTouch, ref TriggerNearTouchState);
            CheckButtonState(HVRButtons.ThumbNearTouch, ref ThumbNearTouchState);

            CheckButtonState(HVRButtons.TrackPadUp, ref TrackPadUp);
            CheckButtonState(HVRButtons.TrackPadLeft, ref TrackPadLeft);
            CheckButtonState(HVRButtons.TrackPadRight, ref TrackPadRight);
            CheckButtonState(HVRButtons.TrackPadDown, ref TrackPadDown);



            RecentVelocities.Enqueue(Velocity.magnitude);

            Device.TryGetFeatureValue(CommonUsages.deviceVelocity, out Velocity);
            Device.TryGetFeatureValue(CommonUsages.deviceAngularVelocity, out AngularVelocity);

            AngularVelocityMagnitude = AngularVelocity.magnitude;
            VelocityMagnitude        = Velocity.magnitude;

            if (!IsSteamVR)
            {
                UpdateThumbWeight();
                UpdateIndexWeight();
                UpdateGripFingers();
            }

            var curls = LeftFingerCurls;

            if (XRNode == XRNode.RightHand)
            {
                curls = RightFingerCurls;
            }

            for (int i = 0; i < 5; i++)
            {
                curls[i] = FingerCurls[i];
            }

            AfterInputUpdate();
        }
        public void ShouldSaveWithoutWrap()
        {
            var buffer = new CircularBuffer <int>(5);

            buffer.Enqueue(1);
            buffer.Enqueue(2);
            buffer.Enqueue(3);
            CollectionAssert.AreEquivalent(new [] { 1, 2, 3 }, buffer);
        }
Exemplo n.º 12
0
        public void RemoveAtInvalidThrowsTest()
        {
            var cb = new CircularBuffer <int>();

            cb.Enqueue(1);
            cb.Enqueue(2);
            cb.Enqueue(3);
            cb.Enqueue(4);
            Assert.Throws <ArgumentOutOfRangeException>(() => cb.RemoveAt(4));
        }
Exemplo n.º 13
0
        public void IndexOfNonExistentReturnsMinusOneTest()
        {
            var cb = new CircularBuffer <int>(2);

            cb.Enqueue(1);
            cb.Enqueue(2);
            Assert.That(cb.IndexOf(1) == 0);
            Assert.That(cb.IndexOf(2) == 1);
            Assert.That(cb.IndexOf(5) == -1);
        }
Exemplo n.º 14
0
        public void ShouldDetectOverflow()
        {
            var buffer = new CircularBuffer <int>(3);

            for (var i = 0; i < 3; i++)
            {
                Assert.IsTrue(buffer.Enqueue(i));
            }
            Assert.IsFalse(buffer.Enqueue(3));
        }
Exemplo n.º 15
0
    public void EnqueueThreeFloats()
    {
        CircularBuffer <float> queue = new CircularBuffer <float>(5);

        queue.Enqueue(1);
        queue.Enqueue(2);
        queue.Enqueue(3);

        Assert.AreEqual(queue.Length, 3);
    }
 public void TestEnumerationWhenFull()
 {
     var buffer = new CircularBuffer<long>(3);
     Assert.AreEqual(default(long), buffer.Enqueue(1));
     Assert.AreEqual(default(long), buffer.Enqueue(2));
     Assert.AreEqual(default(long), buffer.Enqueue(3));
     var i = 0;
     foreach (var value in buffer)
         Assert.AreEqual(++i, value);
     Assert.AreEqual(i, 3);
 }
Exemplo n.º 17
0
        public void SetCapacitySameDoesNothingTest()
        {
            var cb = new CircularBuffer <int>(2);

            cb.Enqueue(1);
            cb.Enqueue(2);
            Assert.That(cb.Capacity == 2);
            cb.Capacity = 2;
            Assert.That(cb[0] == 1);
            Assert.That(cb[1] == 2);
        }
Exemplo n.º 18
0
        public void ShouldNotDetectOverflow()
        {
            var buffer = new CircularBuffer <int>(3);

            for (var i = 0; i < 3; i++)
            {
                buffer.Enqueue(i);
            }
            buffer.TryDequeue(out var _);
            Assert.IsTrue(buffer.Enqueue(2));
        }
Exemplo n.º 19
0
    public void EnqueuingWhenFull()
    {
        CircularBuffer <float> queue = new CircularBuffer <float>(3);

        queue.Enqueue(1);
        queue.Enqueue(2);
        queue.Enqueue(3);
        queue.Enqueue(4);

        Assert.AreEqual(queue.GetTailIndex, 1);
    }
Exemplo n.º 20
0
        public void ClearTest()
        {
            var cb = new CircularBuffer <int>(2);

            cb.Enqueue(1);
            cb.Enqueue(2);
            Assert.That(cb.Count == 2);
            Assert.That(cb.Capacity == 2);
            cb.Clear();
            Assert.That(cb.Capacity == 2);
            Assert.That(cb.Count == 0);
        }
Exemplo n.º 21
0
        public void SetSmallerCapacityDestroysOnlyTailsElementsTest()
        {
            var cb = new CircularBuffer <int>(2);

            cb.Enqueue(1);
            cb.Enqueue(2);
            Assert.That(cb.Capacity == 2);
            Assert.That(cb.Count == 2);
            cb.Capacity = 1;
            Assert.That(cb.Count == 1);
            Assert.That(cb[0] == 1);
        }
 public void TestUnderwrite()
 {
     var buffer = new CircularBuffer<long>(5);
     Assert.AreEqual(default(long), buffer.Enqueue(1));
     Assert.AreEqual(default(long), buffer.Enqueue(2));
     Assert.AreEqual(default(long), buffer.Enqueue(3));
     Assert.AreEqual(3, buffer.Count);
     Assert.AreEqual(1, buffer.Dequeue());
     Assert.AreEqual(2, buffer.Dequeue());
     Assert.AreEqual(3, buffer.Dequeue());
     Assert.AreEqual(0, buffer.Count);
 }
 public void TestDecreaseCapacityWhenFull()
 {
     var buffer = new CircularBuffer<long>(3);
     Assert.AreEqual(default(long), buffer.Enqueue(1));
     Assert.AreEqual(default(long), buffer.Enqueue(2));
     Assert.AreEqual(default(long), buffer.Enqueue(3));
     Assert.AreEqual(3, buffer.Count);
     buffer.Capacity = 2;
     Assert.AreEqual(2, buffer.Count);
     Assert.AreEqual(1, buffer.Dequeue());
     Assert.AreEqual(2, buffer.Dequeue());
     Assert.AreEqual(0, buffer.Count);
 }
Exemplo n.º 24
0
        public void SetLargerCapacityIsNonDestructiveTest()
        {
            var cb = new CircularBuffer <int>(2);

            cb.Enqueue(1);
            cb.Enqueue(2);
            Assert.That(cb.Capacity == 2);
            Assert.That(cb.Count == 2);
            cb.Capacity = 3;
            Assert.That(cb.Count == 2);
            Assert.That(cb[0] == 1);
            Assert.That(cb[1] == 2);
        }
Exemplo n.º 25
0
        public void IterationTest()
        {
            var cb = new CircularBuffer <int>(2);

            cb.Enqueue(1);
            cb.Enqueue(2);
            IEnumerator enumerator = cb.GetEnumerator();

            while (enumerator.MoveNext())
            {
                var tmp = enumerator.Current;
            }
        }
Exemplo n.º 26
0
        public void UnderwriteTest()
        {
            var buffer = new CircularBuffer <long>(5);

            Assert.AreEqual(default(long), buffer.Enqueue(1));
            Assert.AreEqual(default(long), buffer.Enqueue(2));
            Assert.AreEqual(default(long), buffer.Enqueue(3));
            Assert.AreEqual(3, buffer.Count);
            Assert.AreEqual(1, buffer.Dequeue());
            Assert.AreEqual(2, buffer.Dequeue());
            Assert.AreEqual(3, buffer.Dequeue());
            Assert.AreEqual(0, buffer.Count);
        }
Exemplo n.º 27
0
        public void CircularBuffer_Enqueue()
        {
            var buffer = new CircularBuffer<string>(10);
            buffer.Enqueue("test");
            buffer.Enqueue("string");

            CollectionAssert.AreEqual(new[] { "test", "string" }, buffer.ToArray());
            Assert.AreEqual(2, buffer.Count);
            Assert.AreEqual(10, buffer.Capacity);
            Assert.AreEqual(0, buffer.Head);
            Assert.AreEqual(2, buffer.Tail);
            Assert.IsTrue(buffer.Contains("string"));
            Assert.IsFalse(buffer.Contains("other string"));
        }
        public void TestEnumerationWhenPartiallyFull()
        {
            var buffer = new CircularBuffer <long>(3);

            Assert.AreEqual(default(long), buffer.Enqueue(1));
            Assert.AreEqual(default(long), buffer.Enqueue(2));
            var i = 0;

            foreach (var value in buffer)
            {
                Assert.AreEqual(++i, value);
            }
            Assert.AreEqual(i, 2);
        }
Exemplo n.º 29
0
        public void DecreaseCapacityWhenFullTest()
        {
            var buffer = new CircularBuffer <long>(3);

            Assert.AreEqual(default(long), buffer.Enqueue(1));
            Assert.AreEqual(default(long), buffer.Enqueue(2));
            Assert.AreEqual(default(long), buffer.Enqueue(3));
            Assert.AreEqual(3, buffer.Count);
            buffer.Capacity = 2;
            Assert.AreEqual(2, buffer.Count);
            Assert.AreEqual(1, buffer.Dequeue());
            Assert.AreEqual(2, buffer.Dequeue());
            Assert.AreEqual(0, buffer.Count);
        }
        public void EnqueueFullBuffer()
        {
            CircularBuffer <int> testData = new CircularBuffer <int>(3);
            int item1 = 6;
            int item2 = 8;
            int item3 = 22;
            int item4 = 13;

            testData.Enqueue(item1);
            testData.Enqueue(item2);
            testData.Enqueue(item3);
            bool actual = testData.Enqueue(item4);

            Assert.False(actual);
        }
        public void EnqueueThreeDequeueOneReturnValue()
        {
            CircularBuffer <int> testData = new CircularBuffer <int>(16);
            int item1 = 6;
            int item2 = 8;
            int item3 = 22;

            testData.Enqueue(item1);
            testData.Enqueue(item2);
            testData.Enqueue(item3);
            int actual   = testData.Dequeue();
            int expected = 6;

            Assert.Equal(expected, actual);
        }
Exemplo n.º 32
0
        public void Enqueue_Single()
        {
            var buffer = new CircularBuffer <int>(5);

            buffer.Enqueue(1);
            buffer.Enqueue(2);
            Assert.False(buffer.IsEmpty);
            Assert.False(buffer.IsFull);
            Assert.True(buffer.TryDeque(out var value));
            Assert.Equal(1, value);
            Assert.False(buffer.IsEmpty);
            Assert.False(buffer.IsFull);
            Assert.True(buffer.TryDeque(out var value2));
            Assert.Equal(2, value2);
        }
Exemplo n.º 33
0
    public void DequeueThreeFloats()
    {
        CircularBuffer <float> queue = new CircularBuffer <float>(5);

        queue.Enqueue(1);
        queue.Enqueue(2);
        queue.Enqueue(3);

        while (!queue.IsEmpty)
        {
            queue.Dequeue();
        }

        Assert.AreEqual(queue.Length, 0);
    }
Exemplo n.º 34
0
        private async Task FallTest()
        {
            CircularBuffer <double> AccelAmps = new CircularBuffer <double>(2000 / SAMPLING_FREQ); //pamietamy wartosci z akcelometra przez ostatnie dwie sekundy
            CircularBuffer <double> GyroAmps  = new CircularBuffer <double>(2000 / SAMPLING_FREQ); //pamietamy wartosci z gyroskopu przez ostatnie dwie sekund
            {
                while (true)
                {
                    await Task.Delay(SAMPLING_FREQ);

                    AccelAmps.Enqueue(Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2) + Math.Pow(z, 2)));                                                     // amplituda przyspieszen x,y,z w accelometrze
                    GyroAmps.Enqueue(Math.Sqrt(Math.Pow(gyroX, 2) + Math.Pow(gyroY, 2) + Math.Pow(gyroZ, 2)));                                          // amplituda prędkości x,y,z w żyroskopie
                    if (AccelAmps.q.Min() < LOWER_ACCEL_BOUNDRY && AccelAmps.q.Max() > UPPER_ACCEL_BOUNDRY && AccelAmps.q.Max() > MAX_ANGULAR_VELOCITY) // Sprawdzenie czy zostaly przekroczone dolne i gorne progi przyspieszenia, oraz gorny prog prędkości kątowej gyroskopu
                    {
                        for (int i = 0; i < 3000 / SAMPLING_FREQ; i++)
                        {
                            await Task.Delay(SAMPLING_FREQ);

                            AccelAmps.Enqueue(Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2) + Math.Pow(z, 2)));            // amplituda przyspieszen x,y,z w accelometrze
                            GyroAmps.Enqueue(Math.Sqrt(Math.Pow(gyroX, 2) + Math.Pow(gyroY, 2) + Math.Pow(gyroZ, 2))); // amplituda prędkości x,y,z w żyroskopie
                        }
                        if (Math.Abs(AccelAmps.q.Min() - AccelAmps.q.Max()) < MAX_RESTING_AMPLITUDE)                   // i sprawdzamy czy telefon byl nieruchomy przez ostatnie dwie aby potwierdzic
                        {
                            /************************************ UPADEK ******************************/
                            CrossSensors.Proximity.WhenReadingTaken().Subscribe(async reading =>
                            {
                                if (reading == true)
                                {
                                    await FallDetectedAsync();
                                }
                            });
                        }

                        //await Task.Delay(3000);                                              // po mozliwym upadku czekamy trzy sekundy
                        //if (Math.Abs(AccelAmps.q .Min() - AccelAmps.q.Max()) < MAX_RESTING_AMPLITUDE) // i sprawdzamy czy telefon byl nieruchomy przez ostatnie dwie aby potwierdzic
                        //{
                        //    /************************************ UPADEK ******************************/
                        //    await FallDetectedAsync();
                        //    //CrossSensors.Proximity.WhenReadingTaken().Subscribe(async reading => {
                        //    //    if (reading == true)
                        //    //    {

                        //    //    }
                        //    //});
                        //}
                    }
                }
            }
        }
Exemplo n.º 35
0
        public void CircularBuffer_EnqueueAfterTrimExcess()
        {
            var buffer = new CircularBuffer<string>(10);
            buffer.EnqueueRange(new[] { "a", "b", "c" }, 0, 3);

            buffer.TrimExcess();
            buffer.Enqueue("z");

            CollectionAssert.AreEqual(new[] { "z", "b", "c" }, buffer.ToArray());
            Assert.AreEqual(3, buffer.Count);
            Assert.AreEqual(3, buffer.Capacity);
            Assert.AreEqual(0, buffer.Head);
            Assert.AreEqual(1, buffer.Tail);
            Assert.IsTrue(buffer.Contains("z"));
            Assert.IsFalse(buffer.Contains("a"));
        }
Exemplo n.º 36
0
        private UnitOracle(WoWUnit unit, Watch watchFlags)
        {
            if (unit != null) {
                this.Unit = unit;

                Flags = watchFlags;

                if (instances.ContainsKey(unit.Guid))
                    throw new NotSupportedException();

                instances[unit.Guid] = this;

                if ((Flags & Watch.HealthVariance) == Watch.HealthVariance) {
                    health = new CircularBuffer<double>(WINDOW_SIZE);
                    for (var i = 0; i < WINDOW_SIZE; i++)
                        health.Enqueue((double)Unit.CurrentHealth);
                }
            }
        }
Exemplo n.º 37
0
 public void Close()
 {
     _log.Debug("Running: BlockingEnqueue");
     const int size = 10;
     _buf = new CircularBuffer<Object>(size);
     // add size element anc check that the size +1 add blocks 
     for (int i = 1; i < size; i++)
     {
         _buf.Enqueue(new object());
     }
     // check tha the buffer is now full 
     Thread t = new Thread(Go);
     t.Start();
     Thread.Sleep(1000);
     // the trhead t should block until the buffer is closed             
     Assert.IsTrue(t.ThreadState == ThreadState.WaitSleepJoin);
     _buf.Close();
     Thread.Sleep(100);
     // t should now be stopped 
     Assert.IsTrue(t.ThreadState == ThreadState.Stopped);           
 }
Exemplo n.º 38
0
 public void CircularBuffer_EnqueueOverwriteNotAllowed()
 {
     int[] data = { 1, 2, 3, 4, 5 };
     var buffer = new CircularBuffer<int>(data.Length, false);
     buffer.EnqueueRange(data, 0, data.Length);
     buffer.Enqueue(10);
 }
Exemplo n.º 39
0
		/// <summary>
		/// Start Playback
		/// </summary>
		/// <param name="res"></param>
		public void InitPlayback(VideoBuffer videoBuffer) {
			if (videoBuffer == null) {
				throw new ArgumentNullException("videoBufferDescription");
			}
			VerifyAccess();
			
			TimeSpan renderinterval;
			try {
				int fps = AppDefaults.visualSettings.ui_video_rendering_fps;
				fps = (fps <= 0 || fps > 100) ? 100 : fps;
				renderinterval = TimeSpan.FromMilliseconds(1000 / fps);
			} catch {
				renderinterval = TimeSpan.FromMilliseconds(1000 / 30);
			}

			var cancellationTokenSource = new CancellationTokenSource();
			renderSubscription.Disposable = Disposable.Create(() => {
				cancellationTokenSource.Cancel();
			});
			var bitmap = PrepareForRendering(videoBuffer);
			var cancellationToken = cancellationTokenSource.Token;
			var dispatcher = Application.Current.Dispatcher;
			var renderingTask = Task.Factory.StartNew(() => {
				var statistics = new CircularBuffer<long>(100);
				using (videoBuffer.Lock()) {
					try {
						//start rendering loop
						while (!cancellationToken.IsCancellationRequested) {
							using (var processingEvent = new ManualResetEventSlim(false)) {
								dispatcher.BeginInvoke(() => {
									using (Disposable.Create(() => processingEvent.Set())) {
										if (!cancellationToken.IsCancellationRequested) {
											//update statisitc info
											statistics.Enqueue(Stopwatch.GetTimestamp());
											//evaluate averange rendering fps
											var ticksEllapsed = statistics.last - statistics.first;
											double avgFps = 0;
											if (ticksEllapsed > 0) {
												avgFps = ((double)statistics.length * (double)Stopwatch.Frequency) / (double)ticksEllapsed;
											}
											//render farme to screen
											DrawFrame(bitmap, videoBuffer, avgFps);
										}
									}
								});
								processingEvent.Wait(cancellationToken);
							}
							cancellationToken.WaitHandle.WaitOne(renderinterval);
						}
					} catch (OperationCanceledException) {
						//swallow exception
					} catch (Exception error) {
						dbg.Error(error);
					}
				}
			}, cancellationToken);
			
		}
        public void UsageExample()
        {
            // Create a buffer with a capacity of 5 items.
            var buffer = new CircularBuffer<long>(5);

            // Add three.
            foreach (var i in Enumerable.Range(1, 3))
                buffer.Enqueue(i);
            Debug.WriteLine(buffer);
            // Capacity=5, Count=3, Buffer=[1,2,3]

            // Add three more.
            foreach (var i in Enumerable.Range(4, 3))
                buffer.Enqueue(i);
            Debug.WriteLine(buffer);
            // Capacity=5, Count=5, Buffer=[2,3,4,5,6]

            // Remove the third.
            var value = buffer[3];
            buffer.RemoveAt(3);
            Debug.WriteLine(buffer);
            // Capacity=5, Count=4, Buffer=[2,3,4,6]

            // Re-insert it.
            buffer.Insert(3, value);
            Debug.WriteLine(buffer);
            // Capacity=5, Count=5, Buffer=[2,3,4,5,6]

            // Dequeue.
            Debug.Print("Value = {0}", buffer.Dequeue());
            // Value = 2
            Debug.WriteLine(buffer);
            // Capacity=5, Count=4, Buffer=[3,4,5,6]

            // Increase the capacity.
            buffer.Capacity = 6;
            Debug.WriteLine(buffer);
            // Capacity=6, Count=4, Buffer=[3,4,5,6]

            // Add three more.
            foreach (var i in Enumerable.Range(7, 3))
                buffer.Enqueue(i);
            Debug.WriteLine(buffer);
            // Capacity=6, Count=6, Buffer=[4,5,6,7,8,9]

            // Reduce the capacity.
            buffer.Capacity = 4;
            Debug.WriteLine(buffer);
            // Capacity=4, Count=4, Buffer=[4,5,6,7]

            // Clear the buffer.
            buffer.Clear();
            Debug.WriteLine(buffer);
            // Capacity=4, Count=0, Buffer=[]
        }
Exemplo n.º 41
0
        public void CircularBuffer_EnqueueOverwriteAllowed()
        {
            string[] data = { "a", "b", "c", "d" };
            var buffer = new CircularBuffer<string>(data.Length);
            buffer.EnqueueRange(data, 0, data.Length);

            buffer.Enqueue("z");

            CollectionAssert.AreEqual(new[] { "z", "b", "c", "d" }, buffer.ToArray());
            Assert.AreEqual(data.Length, buffer.Count);
            Assert.AreEqual(data.Length, buffer.Capacity);
            Assert.AreEqual(0, buffer.Head);
            Assert.AreEqual(1, buffer.Tail);
            Assert.IsTrue(buffer.Contains("z"));
            Assert.IsFalse(buffer.Contains("a"));
        }
 public void TestRemoveAt()
 {
     var buffer = new CircularBuffer<long>(5);
     Assert.AreEqual(default(long), buffer.Enqueue(1));
     Assert.AreEqual(default(long), buffer.Enqueue(2));
     Assert.AreEqual(default(long), buffer.Enqueue(3));
     Assert.AreEqual(default(long), buffer.Enqueue(4));
     Assert.AreEqual(default(long), buffer.Enqueue(5));
     buffer.RemoveAt(buffer.IndexOf(2));
     buffer.RemoveAt(buffer.IndexOf(4));
     Assert.AreEqual(3, buffer.Count);
     Assert.AreEqual(1, buffer.Dequeue());
     Assert.AreEqual(3, buffer.Dequeue());
     Assert.AreEqual(5, buffer.Dequeue());
     Assert.AreEqual(0, buffer.Count);
     Assert.AreEqual(default(long), buffer.Enqueue(1));
     Assert.AreEqual(default(long), buffer.Enqueue(2));
     Assert.AreEqual(default(long), buffer.Enqueue(3));
     Assert.AreEqual(default(long), buffer.Enqueue(4));
     Assert.AreEqual(default(long), buffer.Enqueue(5));
     buffer.RemoveAt(buffer.IndexOf(1));
     buffer.RemoveAt(buffer.IndexOf(3));
     buffer.RemoveAt(buffer.IndexOf(5));
     Assert.AreEqual(2, buffer.Count);
     Assert.AreEqual(2, buffer.Dequeue());
     Assert.AreEqual(4, buffer.Dequeue());
     Assert.AreEqual(0, buffer.Count);
 }