Exemplo n.º 1
0
        public void update(Point p, bool shiftPressed, bool ctrlPressed)
        {
            Point s = (Point)start;
            segments.Clear();

            if (ctrlPressed)
            {
                // calculate the angle
                double A = p.Y < s.Y ? s.Y - p.Y : -(p.Y - s.Y);
                double B = p.X < s.X ? -(s.X - p.X) : p.X - s.X;
                angle = Math.Tanh(A / B) * 180 / Math.PI;
            }
            else
            {
                end = p;
            }

            Point e = (Point)end;

            Point a = s;
            Point b = new Point(e.X, a.Y);
            Point c = new Point(b.X, e.Y);
            Point d = new Point(a.X, c.Y);

            Segment AB = new Segment(a, b).Rotate(-angle);
            Segment BC = new Segment(b, c).Rotate(-angle).Translate(AB.End);
            Segment CD = new Segment(c, d).Rotate(-angle).Translate(BC.End);
            Segment DA = new Segment(d, a).Rotate(-angle).Translate(CD.End);

            segments.Add(AB);
            segments.Add(BC);
            segments.Add(CD);
            segments.Add(DA);
        }
Exemplo n.º 2
0
        public void ToStartTest()
        {
            Segment container = new Segment(2, 5);

            var aligned = container.AlignToStart(2);
            Assert.Equal(new Segment(2, 4), aligned);
        }
Exemplo n.º 3
0
        public void ToMiddleTest()
        {
            Segment container = new Segment(2, 5);

            var aligned = container.AlignToMiddle(2);
            Assert.Equal(new Segment(2.5, 4.5), aligned);
        }
    // Add a segment, where the first point shows up in the
    // visualization but the second one does not. (Every endpoint is
    // part of two segments, but we want to only show them once.)
    public void addSegment(float x1, float y1, float x2, float y2)
    {
        Segment segment = new Segment();//null;
            //EndPoint p1 = {begin, x, y, angle,segment, visualize};

            //EndPoint p1 = new EndPoint.Init(begin = false, x = 0F, y= 0F, angle = 0F,segment = segment, visualize = true);
            //EndPoint p2 = new EndPoint.Init(begin = false, x = 0F, y= 0F, angle = 0F,segment = segment, visualize = false);

            EndPoint p1 = new EndPoint{begin = false, x = 0F, y = 0F, angle = 0F,segment = segment, visualize = true};
            EndPoint p2 = new EndPoint{begin = false, x = 0F, y = 0F, angle = 0F,segment = segment, visualize = false};
            //EndPoint p2 = {begin: false, x: 0.0, y: 0.0, angle: 0.0,segment: segment, visualize: false};
            //segment = {p1: p1, p2: p2, d: 0.0};
            p1.x = x1; p1.y = y1;
            p2.x = x2; p2.y = y2;
            p1.segment = segment;
            p2.segment = segment;
            segment.p1 = p1;
            segment.p2 = p2;

            segments.Add(segment);	//segments.append(segment);
            endpoints.Add(p1);	//endpoints.append(p1);
            endpoints.Add(p2);	//endpoints.append(p2);

            //Drawline lags one frame behind because off is updated after, no problem
            //Debug.DrawLine(new Vector3(p1.x,0F,p1.y)+off,new Vector3(p2.x,0F,p2.y)+off,new Color(1F,1F,1F,0.5F),0F,false);
    }
Exemplo n.º 5
0
        public void ToMiddleTest2()
        {
            Segment container = new Segment(0, 500);

            var aligned = container.AlignToMiddle(200);
            Assert.Equal(new Segment(150, 350), aligned);
        }
 /// <summary>
 /// Create a new intersection between a segment and a circle.
 /// </summary>
 /// <param name="i">The point of intersection.</param>
 /// <param name="c">The circle.</param>
 /// <param name="s">The segment.</param>
 public CircleSegmentIntersection(Point i, Circle c, Segment s)
     : base()
 {
     intersect = i;
     circle = c;
     segment = s;
 }
Exemplo n.º 7
0
        public void ToEndTest()
        {
            Segment container = new Segment(2, 5);

            var aligned = container.AlignToEnd(2);
            Assert.Equal(new Segment(3, 5), aligned);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Construct a new PatternMatcher using the specified culture.
        /// </summary>
        /// <param name="pattern">The pattern to make the pattern matcher for.</param>
        /// <param name="culture">The culture to use for string searching and comparison.</param>
        /// <param name="verbatimIdentifierPrefixIsWordCharacter">Whether to consider "@" as a word character</param>
        /// <param name="allowFuzzyMatching">Whether or not close matches should count as matches.</param>
        public PatternMatcher(
            string pattern,
            CultureInfo culture,
            bool verbatimIdentifierPrefixIsWordCharacter,
            bool allowFuzzyMatching)
        {
            pattern = pattern.Trim();
            _compareInfo = culture.CompareInfo;
            _allowFuzzyMatching = allowFuzzyMatching;

            _fullPatternSegment = new Segment(pattern, verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching);

            if (pattern.IndexOf('.') < 0)
            {
                // PERF: Avoid string.Split allocations when the pattern doesn't contain a dot.
                _dotSeparatedSegments = pattern.Length > 0
                    ? new Segment[1] { _fullPatternSegment }
                    : Array.Empty<Segment>();
            }
            else
            {
                _dotSeparatedSegments = pattern.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries)
                                                .Select(text => new Segment(text.Trim(), verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching))
                                                .ToArray();
            }

            _invalidPattern = _dotSeparatedSegments.Length == 0 || _dotSeparatedSegments.Any(s => s.IsInvalid);
        }
Exemplo n.º 9
0
 bool isEdge(List<Vector3> processedPoints, Segment edge)
 {
     for(int k = 0; k < processedPoints.Count; k++) {
         if(edge.isLeft(processedPoints[k])) return false;
     }
     return true;
 }
Exemplo n.º 10
0
 public BoneData(Segment s)
 {
     seg = segLast = s;
     xVel = yVel = 0;
     xVel2 = yVel2 = 0;
     timeLastUpdated = DateTime.Now;
 }
Exemplo n.º 11
0
        public SegmentIteratorFrom(Segment firstSegment)
        {
            Contract.Ensures(firstSegment != null);

            _firstSegment = firstSegment;
            Reset();
        }
Exemplo n.º 12
0
 void Start()
 {
     sceneManager = FindObjectOfType<SceneManager>();
     serialData = FindObjectOfType<SerialData>();
     segment = GetComponentInParent<Segment>();
     thisCollider = GetComponent<Collider>();
 }
Exemplo n.º 13
0
        public Segment Insert(TrackObject insertedOject, float distanceFromBegining)
        {
            Segment insertedSegment = new Segment();
            IFirstLastAccessor insertedFLAccessor = FirstLastAccessorFactory.Create(_direction, insertedSegment);
            IFirstLastAccessor segmentFLAccessor = FirstLastAccessorFactory.Create(_direction, _segment);

            insertedFLAccessor.FirstObject = segmentFLAccessor.FirstObject;
            insertedFLAccessor.LastObject = insertedOject;

            segmentFLAccessor.FirstObject = insertedOject;

            Segment prevSegment = segmentFLAccessor.PrevSegment;

            insertedFLAccessor.NextSegment = _segment;
            insertedFLAccessor.PrevSegment = prevSegment;
            segmentFLAccessor.PrevSegment = insertedSegment;

            if (prevSegment != null)
            {
                IFirstLastAccessor prevSegmentFLAccessor = FirstLastAccessorFactory.Create(_direction, prevSegment);
                prevSegmentFLAccessor.NextSegment = insertedSegment;
            }

            float distance = distanceFromBegining - _distanceFull;
            if (distance > 0.0)
            {
                throw new VrException(String.Format("Longer distance '{0}' can't be appended, only appended!", distance));
            }

            float insertedSegmentDistance = _segment.Distance + distance;
            insertedSegment.Distance = insertedSegmentDistance;
            _segment.Distance = _segment.Distance - insertedSegmentDistance;

            return insertedSegment;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Subdivides long segments in ones of smaller length. 
        /// </summary>
        /// <param name="subSegmentLength">An approximate value indicating the length of the individual subsegment.
        /// The segment will be divided into an integer number of parts. 
        ///</param>
        public void Detail(double subSegmentLength)
        {
            List<Segment> detailedSegments = new List<Segment>();

            Vector2D currentPoint = SegmentList[0].StartPoint;
            for (int i = 0; i < SegmentList.Count; i++)
            {
                Segment segment = new Segment(currentPoint, SegmentList[i].EndPoint);
                double length = segment.Length;
                if (length < subSegmentLength / 2) {
                    currentPoint = segment.EndPoint;
                    continue;
                    }
                if (length < 2*subSegmentLength)
                {
                    detailedSegments.Add(segment);
                    currentPoint = segment.EndPoint;
                    continue;
                }

                detailedSegments.AddRange(Segment.Subdivide(segment, (int) Math.Round(length/subSegmentLength)));
                currentPoint = detailedSegments[detailedSegments.Count - 1].EndPoint;
            }

            SegmentList = detailedSegments;
        }
Exemplo n.º 15
0
		public override bool Handle (State previous, Segment prevSegment, Segment newSegment, bool left)
		{
			if (newSegment != null && !newSegment.IsPalette && newSegment.Type != ElementType.None) {

				if (newSegment.Type == ElementType.Coil ||
					newSegment.Type == ElementType.NotCoil || 
					newSegment.Type == ElementType.SetCoil ||
					newSegment.Type == ElementType.ResetCoil) {
					MainClass._main.BindDefaultOutputs ();
				} else {
					MainClass._main.BindDefaultInputs ();
				}

				MainClass._main.BindExistingVariables (newSegment);
				MainClass._main.BindFunction (newSegment);
				AppController.Instance.CheckUserVariables ();

				if (newSegment.Variables.Any ()) {
					int index = 0;
					foreach (var v in newSegment.Variables) {
						MainClass._main.BindElementVariables (v.Type, v.Value, index++);
					}
					for (int i = index; i < 4; i++) {
						MainClass._main.BindElementVariables (VariableType.Default, string.Empty, i);
					}
				}
				MainClass._main.DisableProperties ();
			}

			base.Handle (previous, prevSegment, newSegment, left);
			return true;
		}
Exemplo n.º 16
0
    // Get all vertical segments for the value
    public List<Segment> getVerticalSegmentsForTag(int tag)
    {
        List<Segment> segments = new List<Segment>();
        Segment segment = null;
        for (int x = 0; x < values.GetLength(0); x++) {
            for (int y = 0; y < values.GetLength(1); y++) {
                int value = values[x, y];
                if (value == tag) {
                    // start a new segment
                    if (segment == null) {
                        Point here = new Point(x, y);
                        segment = new Segment(here, 0, false, tag);
                    }
                    // extend current segment
                    else {
                        segment.Length++;
                    }
                }
                else {
                    // end the current segment
                    if (segment != null) {
                        segments.Add(segment);
                        segment = null;
                    }
                }
            }
        }

        // Add the last segment if there is one.
        if (segment != null) {
            segments.Add(segment);
        }

        return segments;
    }
Exemplo n.º 17
0
        private void LoadWildcard(string fileName)
        {
            lock (_LockObj)
            {
                _WildcardList = new List<WildcardInfo>();

                if (!System.IO.File.Exists(fileName))
                {
                    return;
                }

                Segment segment = new Segment();

                using (StreamReader sr = new StreamReader(fileName, Encoding.UTF8))
                {

                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine().Trim();

                        if (string.IsNullOrEmpty(line))
                        {
                            continue;
                        }

                        _WildcardList.Add(new WildcardInfo(line, segment, _Options, _Parameter));
                    }
                }

                _Init = true;
            }
        }
Exemplo n.º 18
0
 private void ToggleCollider(Segment s)
 {
     if (s.sCollider != null)
     {
         //s.sCollider.enabled = !s.sCollider.enabled;
     }
 }
Exemplo n.º 19
0
 private void ToggleRenderer(Segment s)
 {
     if (s.sRenderer != null)
     {
         s.sRenderer.enabled = !s.sRenderer.enabled;
     }
 }
 public Trapezoid(Vertex leftp, Vertex rightp, Segment top, Segment bottom)
 {
     Leftp = leftp;
     Rightp = rightp;
     Top = top;
     Bottom = bottom;
 }
Exemplo n.º 21
0
 /// <summary> Creates a new subpath with the given start point and segments.
 /// 
 /// </summary>
 /// <param name="startX">x coordinate of the start point.
 /// </param>
 /// <param name="startY">y coordinate of the start point.
 /// </param>
 /// <param name="segments">the segments.
 /// </param>
 /// <param name="closed">defines is the subpath closed.
 /// </param>
 public SubPath(float startX, float startY, Segment[] segments, bool closed)
 {
     this.startX = startX;
     this.startY = startY;
     this.segments = segments;
     this.closed = closed;
 }
Exemplo n.º 22
0
		public override void SweptTest(CollisionFunctor cf, Part partA, Part partB, Vector3 delta)
		{
			var a = (SpherePart)partA;
			var b = (CapsulePart)partB;

			Segment path;
			path.P1 = a.World.Center;
			Vector3.Add(ref path.P1, ref delta, out path.P2);

			Capsule cap = b.World;
			cap.Radius += a.World.Radius;
			Segment capSegment = new Segment(b.World.P1, b.World.P2);

			float k;
			Vector3 pa, pb, normal;
			cap.Intersect(ref path, out k, out pa);
			if (k <= 1f)
			{
				capSegment.ClosestPointTo(ref pa, out k, out pb);
				Vector3.Subtract(ref pa, ref pb, out normal);
				normal.Normalize();
				Vector3.Multiply(ref normal, b.World.Radius, out pa);
				Vector3.Add(ref pb, ref pa, out pb);
				Vector3.Multiply(ref normal, -a.World.Radius, out pa);
				Vector3.Add(ref a.World.Center, ref pa, out pa);

				cf.WritePoint(ref pa, ref pb, ref normal);
			}
		}
Exemplo n.º 23
0
 private Segment GetConnectedSegment(Segment segment)
 {
     HingeJoint2D hingeJoint = GetHingeJoint(segment);
     Segment previousSegment = null;
     if (hingeJoint.connectedBody != null) previousSegment = hingeJoint.connectedBody.gameObject.GetComponent<Segment>();
     return previousSegment;
 }
        private void AddSegmentText(SvgDocument document, int index, ComplexLine line,Segment segment, PointF targetPoint, PointF referencePoint)
        {
            //Get midpoint of segment
            PointF location = new PointF(targetPoint.X + ((referencePoint.X - targetPoint.X) / 2), targetPoint.Y + ((referencePoint.Y - targetPoint.Y) / 2));

            if (segment.Label.Text.Trim() == "") return;

            Style style = new Style();

            //Set up text object
            location = OffsetPoint(location, segment.Label.Offset);
            //location = OffsetPoint(location, line.Rectangle.Location);

            Double rotation = Geometry.DegreesFromRadians(Geometry.GetAngle(targetPoint.X, targetPoint.Y, referencePoint.X, referencePoint.Y));

            Text text = new Text();
            text.Label = segment.Label;
            text.LayoutRectangle = new RectangleF(location, new SizeF());

            //Get style
            string classId = null;
            classId = document.AddClass(text.GetStyle());

            //Create fragment and add to document
            XmlDocumentFragment frag = null;
            XmlNode newElementNode = null;

            frag = document.CreateDocumentFragment();
            frag.InnerXml = text.ExtractText(0, 0, line.Key + index.ToString() + "Text", "rotate(" + rotation.ToString() + "," + location.X.ToString() + "," + location.Y.ToString() + ")");
            //frag.InnerXml = text.ExtractText(0, 0, line.Key + index.ToString() + "Text");
            frag.FirstChild.Attributes.GetNamedItem("class").InnerText = classId;
            newElementNode = document.ContainerNode.AppendChild(frag);
        }
Exemplo n.º 25
0
 public Address(Segment segment, long value)
     : this()
 {
     this.Type    = AddressType.Logical;
     this.Value   = value;
     this.Segment = segment;
 }
Exemplo n.º 26
0
        public IRun Create(IComparisonGeneratorsFactory factory)
        {
            var run = new Run(factory);

            var json = JSON.FromStream(Stream);

            run.GameName = json.run_name as string;
            run.AttemptCount = json.run_count;

            var timingMethod = (int)(json.timer_type) == 0 
                ? TimingMethod.RealTime 
                : TimingMethod.GameTime;

            var segments = json.splits as IEnumerable<dynamic>;

            foreach (var segment in segments)
            {
                var segmentName = segment.name as string;
                var pbSplitTime = parseTime((int?)segment.pb_split, timingMethod);
                var bestSegment = parseTime((int?)segment.split_best, timingMethod);

                var parsedSegment = new Segment(segmentName, pbSplitTime, bestSegment);
                run.Add(parsedSegment);
            }

            return run;
        }
Exemplo n.º 27
0
        public Segment AppendToSegment(string segmentId, string[] actorIds)
        {
            Segment segment = new Segment();
            JObject request = new JObject();
            request["user_ids"] = new JArray { actorIds };

            OAuthResponse response = null;

            try
            {
                response = _manager.GetOAuthResponse("POST", "audience/segments/" + segmentId + "/ids", request.ToString());
                if (response.ErrorFlag) throw response.Error;
                else
                {
                    Segment s = JsonConvert.DeserializeObject<Segment>(response.ResponseString);
                    segment = s;
                }
            }
            catch (Exception ex)
            {
                segment.ErrorFlag = true;
                segment.Error = ex;
                if (response != null) segment.ErrorMessage = response.ResponseString;
            }
            return segment;
        }
Exemplo n.º 28
0
 private CustomerOrderChangeLine createChangeLine(Segment lineSeg)
 {
     SegmentCount++;
     string[] arr = GetEls(lineSeg);
     var line = new CustomerOrderChangeLine
     {
         LineNumber = arr[1].CastToInt(),
         RequestedQuantity = arr[3].CastToInt(),
         QtyLeftToReceive = arr[4].CastToInt(),
         RequestedPrice = arr[6].CastToDecimal(),
         ChangeCode = arr[2]
     };
     for (int i = 8; i < arr.Length - 1; i++)
     {
         if (arr[i] == "IN" || arr[i] == "BP")
         {
             line.CustomerPartNumber = arr[i + 1];
         }
         if (arr[i] == "PD")
             line.ItemDescription = arr[i + 1];
         if (arr[i] == "VN" || arr[i] == "VP")
             line.ItemId = arr[i + 1];
     }
     return line;
 }
Exemplo n.º 29
0
        private static string GetAllowableSegmentPart(Segment segment, int pos, 
            int extractStart, int extractLength, bool extractToEnd)
        {
            var segmentMin = pos;
            var segmentMax = pos + segment.Text.Length;
            var extractMax = extractStart + (extractToEnd ? segmentMax : extractLength);
            var startIsInsideSegment = extractStart >= segmentMin && extractStart <= segmentMax;
            var endIsInsideSegment = extractMax >= segmentMin && extractMax <= segmentMax;
            var segmentIsInsideRange = extractStart <= segmentMin && extractMax >= segmentMax;

            if (segmentIsInsideRange)
                return segment.Text;

            if (startIsInsideSegment && endIsInsideSegment)
            {
                var fragmentStart = extractStart - segmentMin;
                var fragmentLength = extractMax - extractStart;
                return segment.Text.Substring(fragmentStart, fragmentLength);
            }

            if (startIsInsideSegment)
                return segment.Text.Substring(extractStart - segmentMin);
            if (endIsInsideSegment)
                return segment.Text.Substring(0, extractMax - segmentMin);

            return null;
        }
Exemplo n.º 30
0
 public CustomerOrderLine CreateLine(Segment lineSeg)
 {
     if (lineSeg.Label == SegmentLabel.PurchaseOrderChange)
         return createChangeLine(lineSeg);
     if (lineSeg.Label != SegmentLabel.PurchaseOrder) return null;
     SegmentCount++;
     string[] arr = GetEls(lineSeg);
     var line = new CustomerOrderLine
                    {
                        LineNumber = arr[1].CastToInt(),
                        RequestedQuantity = arr[2].CastToInt(),
                        RequestedPrice = arr[4].CastToDecimal()
                    };
     for (int i = 6; i < arr.Length - 1; i++)
     {
         if (arr[i] == "IN" || arr[i] == "BP")
         {
             line.CustomerPartNumber = arr[i + 1];
         }
         if (arr[i] == "PD")
             line.ItemDescription = arr[i + 1];
         if (arr[i] == "VN" || arr[i] == "VP")
             line.ItemId = arr[i + 1];
     }
     return line;
 }
Exemplo n.º 31
0
        public static void TestBiSegment()
        {
            List <string> sentence    = new List <string>();
            List <string> description = new List <string>();

            sentence.Add(@"他说的确实在理");
            description.Add(@"普通分词测试");

            sentence.Add(@"张华平3-4月份来北京开会");
            description.Add(@"数字切分");

            sentence.Add(@"1.加强管理");
            description.Add(@"剔除多余的“.”");

            sentence.Add(@"他出生于1980年1月1日10点");
            description.Add(@"日期合并");

            sentence.Add(@"他出生于甲子年");
            description.Add(@"年份识别");

            sentence.Add(@"馆内陈列周恩来和邓颖超生前使用过的物品");
            description.Add(@"姓名识别");

            WordDictionary coreDict = new WordDictionary();

            if (!coreDict.Load(coreDictFile))
            {
                Console.WriteLine("coreDict 字典装入错误!");
                return;
            }

            WordDictionary biDict = new WordDictionary();

            if (!biDict.Load(biDictFile))
            {
                Console.WriteLine("字典装入错误!");
                return;
            }

            string sSentence;
            string sDescription;

            for (int i = 0; i < sentence.Count; i++)
            {
                sSentence    = sentence[i];
                sDescription = description[i];
                Console.WriteLine("\r\n============ {0} ============", sDescription);


                sSentence = Predefine.SENTENCE_BEGIN + sSentence + Predefine.SENTENCE_END;

                List <AtomNode> nodes = Segment.AtomSegment(sSentence);
                Console.WriteLine("原子切分:");
                for (int j = 0; j < nodes.Count; j++)
                {
                    Console.Write("{0}, ", nodes[j].sWord);
                }

                Console.WriteLine("\r\n\r\n实际切分:");
                Segment segment = new Segment(biDict, coreDict);
                segment.BiSegment(sSentence, 0.1, 1);

                for (int k = 0; k < segment.m_pWordSeg.Count; k++)
                {
                    for (int j = 0; j < segment.m_pWordSeg[k].Length; j++)
                    {
                        Console.Write("{0}, ", segment.m_pWordSeg[k][j].sWord);
                    }
                    Console.WriteLine();
                }
            }
        }
Exemplo n.º 32
0
 public static bool IsValid(this Segment s)
 {
     return(s.DepartureDate < s.ArrivalDate);
 }
Exemplo n.º 33
0
        /// <summary>
        /// Merges a surface within this one, using the X axis as the merge orientation
        /// </summary>
        /// <param name="otherSurface"></param>
        public void MergeX(Surface otherSurface)
        {
            List <Segment> toProcess = new List <Segment>(otherSurface.Segments);
            List <Segment> toAdd     = new List <Segment>();

            while (toProcess.Count > 0)
            {
                Segment segment = toProcess[0];
                toProcess.Remove(segment);

                // Reduce this segment according to the existing segments
                foreach (Segment existingSegment in Segments)
                {
                    if (existingSegment.Start <= segment.Start)
                    {
                        if (existingSegment.End < segment.End)
                        {
                            if (existingSegment.End > segment.Start)
                            {
                                // The existing segment reduces the start of this segment
                                segment.Start = existingSegment.End;
                            }
                        }
                        else
                        {
                            // This segment is completely overriden by the existing segment;
                            segment = null;
                            break;
                        }
                    }
                    else
                    {
                        // existingSegment.Start >= segment.Start
                        if (existingSegment.Start < segment.End)
                        {
                            if (existingSegment.End < segment.End)
                            {
                                // This segment splits the current segment in two.
                                Segment newSegment = new Segment(existingSegment.End, segment.End, segment.Graph);
                                toProcess.Insert(0, newSegment);
                            }
                            segment.End = existingSegment.Start;
                        }
                        else
                        {
                            // the existing segment does not impact this segment
                        }
                    }
                }

                if (segment != null)
                {
                    if (segment.Start < segment.End)
                    {
                        toAdd.Add(segment);
                    }
                }
            }

            Segments.AddRange(toAdd);
            Segments.Sort();
        }
Exemplo n.º 34
0
 //Task OnSegmentReceived(ReadOnlySequence<byte> segment)
 public ISegmenter GetSegmenter(MachineType machine, OnSegmentReceived received) =>
 (machine == MachineType.Favero ?
  Segment.StartsWith(0xff).AndIsLength(10) :
  Segment.StartsWith(ControlCharacters.StartOfHeading).AndEndsWith(ControlCharacters.EndOfTransmission).WithMaxLength(100)
 ).WithOptions(SegmentionOptions.SkipInvalidSegment | SegmentionOptions.SecondStartInvalid).ThenDo(received);
        public override void DrawOrMove(ChartPoint previousDrawn, ChartPoint current, int index, ChartCore chart)
        {
            var previosPbv = previousDrawn == null ? null : (VerticalBezierPointView) previousDrawn.View;

            Container.Segments.Remove(Segment);
            Container.Segments.Insert(index, Segment);

            ValidArea = new CoreRectangle(current.ChartLocation.X - 7.5, current.ChartLocation.Y - 7.5, 15, 15);

            if (IsNew)
            {
                if (previosPbv != null && !previosPbv.IsNew)
                {
                    Segment.Point1 = previosPbv.Segment.Point3;
                    Segment.Point2 = previosPbv.Segment.Point3;
                    Segment.Point3 = previosPbv.Segment.Point3;

                    if (DataLabel != null)
                    {
                        Canvas.SetTop(DataLabel, Canvas.GetTop(previosPbv.DataLabel));
                        Canvas.SetLeft(DataLabel, Canvas.GetLeft(previosPbv.DataLabel));
                    }

                    if (Shape != null)
                    {
                        Canvas.SetTop(Shape, Canvas.GetTop(previosPbv.Shape));
                        Canvas.SetLeft(Shape, Canvas.GetLeft(previosPbv.Shape));
                    }
                }
                else
                {
                    Segment.Point1 = new Point(0, Data.Point1.Y);
                    Segment.Point2 = new Point(0, Data.Point2.Y);
                    Segment.Point3 = new Point(0, Data.Point3.Y);

                    if (DataLabel != null)
                    {
                        Canvas.SetTop(DataLabel, current.ChartLocation.Y - DataLabel.ActualHeight*.5);
                        Canvas.SetLeft(DataLabel, 0);
                    }

                    if (Shape != null)
                    {
                        Canvas.SetTop(Shape, current.ChartLocation.Y - Shape.Height*.5);
                        Canvas.SetLeft(Shape, 0);
                    }
                }
            }
            else if (DataLabel != null && double.IsNaN(Canvas.GetLeft(DataLabel)))
            {
                Canvas.SetTop(DataLabel, current.ChartLocation.Y - DataLabel.ActualHeight * .5);
                Canvas.SetLeft(DataLabel, 0);
            }

            #region No Animated

            if (chart.View.DisableAnimations)
            {
                Segment.Point1 = Data.Point1.AsPoint();
                Segment.Point2 = Data.Point2.AsPoint();
                Segment.Point3 = Data.Point3.AsPoint();

                if (HoverShape != null)
                {
                    Canvas.SetLeft(HoverShape, current.ChartLocation.X - HoverShape.Width * .5);
                    Canvas.SetTop(HoverShape, current.ChartLocation.Y - HoverShape.Height * .5);
                }

                if (Shape != null)
                {
                    Canvas.SetLeft(Shape, current.ChartLocation.X - Shape.Width * .5);
                    Canvas.SetTop(Shape, current.ChartLocation.Y - Shape.Height * .5);
                }

                if (DataLabel != null)
                {
                    DataLabel.UpdateLayout();
                    var xl = CorrectXLabel(current.ChartLocation.X - DataLabel.ActualWidth * .5, chart);
                    var yl = CorrectYLabel(current.ChartLocation.Y - DataLabel.ActualHeight * .5, chart);
                    Canvas.SetLeft(DataLabel, xl);
                    Canvas.SetTop(DataLabel, yl);
                }
                return;
            }

            #endregion

            Segment.BeginAnimation(BezierSegment.Point1Property,
                new PointAnimation(Segment.Point1, Data.Point1.AsPoint(), chart.View.AnimationsSpeed));
            Segment.BeginAnimation(BezierSegment.Point2Property,
                new PointAnimation(Segment.Point2, Data.Point2.AsPoint(), chart.View.AnimationsSpeed));
            Segment.BeginAnimation(BezierSegment.Point3Property,
                new PointAnimation(Segment.Point3, Data.Point3.AsPoint(), chart.View.AnimationsSpeed));

            if (Shape != null)
            {
                if (double.IsNaN(Canvas.GetLeft(Shape)))
                {
                    Canvas.SetLeft(Shape, current.ChartLocation.X - Shape.Width * .5);
                    Canvas.SetTop(Shape, current.ChartLocation.Y - Shape.Height * .5);
                }
                else
                {
                    Shape.BeginAnimation(Canvas.LeftProperty,
                   new DoubleAnimation(current.ChartLocation.X - Shape.Width * .5, chart.View.AnimationsSpeed));
                    Shape.BeginAnimation(Canvas.TopProperty,
                        new DoubleAnimation(current.ChartLocation.Y - Shape.Height * .5, chart.View.AnimationsSpeed));
                }
            }

            if (DataLabel != null)
            {
                DataLabel.UpdateLayout();

                var xl = CorrectXLabel(current.ChartLocation.X - DataLabel.ActualWidth * .5, chart);
                var yl = CorrectYLabel(current.ChartLocation.Y - DataLabel.ActualHeight * .5, chart);

                DataLabel.BeginAnimation(Canvas.LeftProperty,
                    new DoubleAnimation(xl, chart.View.AnimationsSpeed));
                DataLabel.BeginAnimation(Canvas.TopProperty,
                    new DoubleAnimation(yl, chart.View.AnimationsSpeed));
            }

            if (HoverShape != null)
            {
                Canvas.SetLeft(HoverShape, current.ChartLocation.X - HoverShape.Width * .5);
                Canvas.SetTop(HoverShape, current.ChartLocation.Y - HoverShape.Height * .5);
            }
        }
Exemplo n.º 36
0
 public static bool IsCurrent(this Segment s)
 {
     return(s.DepartureDate > DateTime.Now);
 }
Exemplo n.º 37
0
        private static Vector3 CalculateNormal(List <Segment> segments, int segIndex, float rotationFrac, bool overrideContinuous)
        {
            Segment seg = segments[segIndex];

            if (seg.RotationStepFraction + seg.Rotation0Fraction >= 1)
            {
                //Single vertex
                var f = seg.ForwardDirection;
                int otherIndex;
                if (segIndex == 0)
                {
                    otherIndex = 1;
                }
                else if (segIndex == segments.Count - 1)
                {
                    otherIndex = segIndex - 1;
                }
                else
                {
                    //In the middle, return (0, 0, 0)
                    return(new Vector3());
                }
                if (f.LengthSquared() == 0)
                {
                    f = segments[otherIndex].ForwardDirection;
                }
                if (otherIndex > segIndex)
                {
                    return(-f);
                }
                return(f);
            }

            //Normal case
            var nn       = new Vector3();
            var surfaceF = new Vector3();

            if (segIndex > 0 && !overrideContinuous)
            {
                surfaceF += CalculateForward(segments, segIndex, rotationFrac);
                nn       += CalculateRingNormal(seg, rotationFrac, true);
            }
            if (overrideContinuous ||
                segIndex < segments.Count - 1 && segments[segIndex].ContinuousNormal)
            {
                surfaceF += CalculateForward(segments, segIndex + 1, rotationFrac);
                nn       += CalculateRingNormal(seg, rotationFrac, false);
            }

            var sflen = surfaceF.Length();

            if (sflen == 0)
            {
                return(new Vector3());
            }
            surfaceF = surfaceF / sflen;

            var realn = nn - Vector3.Dot(nn, surfaceF) * surfaceF;
            var nnlen = realn.Length();

            if (nnlen == 0)
            {
                return(new Vector3());
            }
            realn /= nnlen;
            return(realn);
        }
Exemplo n.º 38
0
 public static TimeSpan GetDuration(this Segment seg)
 {
     return(seg.DepartureDate.Subtract(seg.ArrivalDate));
 }
Exemplo n.º 39
0
 /// <summary>
 /// Intersect a segment with the world. If non-zero the predicate
 /// allows certain skins to be excluded
 /// </summary>
 /// <param name="fracOut"></param>
 /// <param name="skinOut"></param>
 /// <param name="posOut"></param>
 ///  <param name="normalOut"></param>
 ///  <param name="seg"></param>
 ///  <param name="collisionPredicate"></param>
 /// <returns>bool</returns>
 public abstract bool SegmentIntersect(out float fracOut, out CollisionSkin skinOut, out Vector3 posOut, out Vector3 normalOut,
                                       Segment seg, CollisionSkinPredicate1 collisionPredicate);
Exemplo n.º 40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class.
 /// </summary>
 public ConcurrentQueue()
 {
     _crossSegmentLock = new object();
     _tail             = _head = new Segment(InitialSegmentLength);
 }
Exemplo n.º 41
0
        public override void DrawOrMove(ChartPoint previousDrawn, ChartPoint current, int index, ChartCore chart)
        {
            var previosPbv = previousDrawn == null
                ? null
                : (HorizontalBezierPointView)previousDrawn.View;

            var y = chart.DrawMargin.Top + chart.DrawMargin.Height;

            Container.Segments.Remove(Segment);
            Container.Segments.Insert(index, Segment);

            if (IsNew)
            {
                if (previosPbv != null && !previosPbv.IsNew)
                {
                    Segment.Point1 = previosPbv.Segment.Point3;
                    Segment.Point2 = previosPbv.Segment.Point3;
                    Segment.Point3 = previosPbv.Segment.Point3;

                    if (DataLabel != null)
                    {
                        Canvas.SetTop(DataLabel, Canvas.GetTop(previosPbv.DataLabel));
                        Canvas.SetLeft(DataLabel, Canvas.GetLeft(previosPbv.DataLabel));
                    }

                    if (Shape != null)
                    {
                        Canvas.SetTop(Shape, Canvas.GetTop(previosPbv.Shape));
                        Canvas.SetLeft(Shape, Canvas.GetLeft(previosPbv.Shape));
                    }
                }
                else
                {
                    Segment.Point1 = new Point(Data.Point1.X, y);
                    Segment.Point2 = new Point(Data.Point2.X, y);
                    Segment.Point3 = new Point(Data.Point3.X, y);

                    if (DataLabel != null)
                    {
                        Canvas.SetTop(DataLabel, y);
                        Canvas.SetLeft(DataLabel, current.ChartLocation.X - DataLabel.ActualWidth * .5);
                    }

                    if (Shape != null)
                    {
                        Canvas.SetTop(Shape, y);
                        Canvas.SetLeft(Shape, current.ChartLocation.X - Shape.Width * .5);
                    }
                }
            }
            else if (DataLabel != null && double.IsNaN(Canvas.GetLeft(DataLabel)))
            {
                Canvas.SetTop(DataLabel, y);
                Canvas.SetLeft(DataLabel, current.ChartLocation.X - DataLabel.ActualWidth * .5);
            }

            #region No Animated

            if (chart.View.DisableAnimations)
            {
                Segment.Point1 = Data.Point1.AsPoint();
                Segment.Point2 = Data.Point2.AsPoint();
                Segment.Point3 = Data.Point3.AsPoint();

                if (HoverShape != null)
                {
                    Canvas.SetLeft(HoverShape, current.ChartLocation.X - HoverShape.Width * .5);
                    Canvas.SetTop(HoverShape, current.ChartLocation.Y - HoverShape.Height * .5);
                }

                if (Shape != null)
                {
                    Canvas.SetLeft(Shape, current.ChartLocation.X - Shape.Width * .5);
                    Canvas.SetTop(Shape, current.ChartLocation.Y - Shape.Height * .5);
                }

                if (DataLabel != null)
                {
                    DataLabel.UpdateLayout();
                    var xl = CorrectXLabel(current.ChartLocation.X - DataLabel.ActualWidth * .5, chart);
                    var yl = CorrectYLabel(current.ChartLocation.Y - DataLabel.ActualHeight * .5, chart);
                    Canvas.SetLeft(DataLabel, xl);
                    Canvas.SetTop(DataLabel, yl);
                }
                return;
            }

            #endregion

            var animSpeed = chart.View.AnimationsSpeed;

            Segment.BeginPointAnimation(nameof(BezierSegment.Point1), Data.Point1.AsPoint(), animSpeed);
            Segment.BeginPointAnimation(nameof(BezierSegment.Point2), Data.Point2.AsPoint(), animSpeed);
            Segment.BeginPointAnimation(nameof(BezierSegment.Point3), Data.Point3.AsPoint(), animSpeed);

            if (Shape != null)
            {
                if (double.IsNaN(Canvas.GetLeft(Shape)))
                {
                    Canvas.SetLeft(Shape, current.ChartLocation.X - Shape.Width * .5);
                    Canvas.SetTop(Shape, current.ChartLocation.Y - Shape.Height * .5);
                }
                else
                {
                    Shape.CreateCanvasStoryBoardAndBegin(current.ChartLocation.X - Shape.Width * .5,
                                                         current.ChartLocation.Y - Shape.Height * .5, chart.View.AnimationsSpeed);
                }
            }

            if (DataLabel != null)
            {
                DataLabel.UpdateLayout();

                var xl = CorrectXLabel(current.ChartLocation.X - DataLabel.ActualWidth * .5, chart);
                var yl = CorrectYLabel(current.ChartLocation.Y - DataLabel.ActualHeight * .5, chart);

                DataLabel.CreateCanvasStoryBoardAndBegin(xl, yl, chart.View.AnimationsSpeed);
            }

            if (HoverShape != null)
            {
                Canvas.SetLeft(HoverShape, current.ChartLocation.X - HoverShape.Width * .5);
                Canvas.SetTop(HoverShape, current.ChartLocation.Y - HoverShape.Height * .5);
            }
        }
Exemplo n.º 42
0
 /// <summary>
 /// Checks two <see cref="EdiPath"/> for equality
 /// </summary>
 /// <param name="other"></param>
 /// <returns></returns>
 public bool Equals(EdiPath other)
 {
     return(Segment.Equals(other.Segment) && Element.Equals(other.Element) && Component.Equals(other.Component));
 }
Exemplo n.º 43
0
 bool SegmentList <TSegment> .TryGetValue(int index, out Segment <TSegment> segment)
 {
     throw new ValueMissingException("The segment is missing.");
 }
Exemplo n.º 44
0
 public IReadOnlyCollection <dynamic> GetVisitorsInSegmentWithProperties(Segment segment, IReadOnlyDictionary <string, bool> properties)
 {
     // We don't store properties in SQL database. Yet..?
     return(new List <dynamic>().AsReadOnly());
 }
Exemplo n.º 45
0
        // Input when you received a low level packet (eg. UDP packet), call it
        // regular indicates a regular packet has received(not from FEC)
        //
        // 'ackNoDelay' will trigger immediate ACK, but surely it will not be efficient in bandwidth
        public int Input(byte[] data, int index, int size, bool regular, bool ackNoDelay)
        {
            var s_una = snd_una;

            if (size < IKCP_OVERHEAD)
            {
                return(-1);
            }

            Int32  offset = index;
            UInt32 latest = 0;
            int    flag   = 0;
            UInt64 inSegs = 0;

            while (true)
            {
                UInt32 ts     = 0;
                UInt32 sn     = 0;
                UInt32 length = 0;
                UInt32 una    = 0;
                UInt32 conv_  = 0;

                UInt16 wnd = 0;
                byte   cmd = 0;
                byte   frg = 0;

                if (size - (offset - index) < IKCP_OVERHEAD)
                {
                    break;
                }

                offset += ikcp_decode32u(data, offset, ref conv_);

                if (conv != conv_)
                {
                    return(-1);
                }

                offset += ikcp_decode8u(data, offset, ref cmd);
                offset += ikcp_decode8u(data, offset, ref frg);
                offset += ikcp_decode16u(data, offset, ref wnd);
                offset += ikcp_decode32u(data, offset, ref ts);
                offset += ikcp_decode32u(data, offset, ref sn);
                offset += ikcp_decode32u(data, offset, ref una);
                offset += ikcp_decode32u(data, offset, ref length);

                if (size - (offset - index) < length)
                {
                    return(-2);
                }

                switch (cmd)
                {
                case IKCP_CMD_PUSH:
                case IKCP_CMD_ACK:
                case IKCP_CMD_WASK:
                case IKCP_CMD_WINS:
                    break;

                default:
                    return(-3);
                }

                // only trust window updates from regular packets. i.e: latest update
                if (regular)
                {
                    rmt_wnd = wnd;
                }

                parse_una(una);
                shrink_buf();

                if (IKCP_CMD_ACK == cmd)
                {
                    parse_ack(sn);
                    parse_fastack(sn, ts);
                    flag  |= 1;
                    latest = ts;
                }
                else if (IKCP_CMD_PUSH == cmd)
                {
                    var repeat = true;
                    if (_itimediff(sn, rcv_nxt + rcv_wnd) < 0)
                    {
                        ack_push(sn, ts);
                        if (_itimediff(sn, rcv_nxt) >= 0)
                        {
                            var seg = Segment.Get((int)length);
                            seg.conv = conv_;
                            seg.cmd  = (UInt32)cmd;
                            seg.frg  = (UInt32)frg;
                            seg.wnd  = (UInt32)wnd;
                            seg.ts   = ts;
                            seg.sn   = sn;
                            seg.una  = una;
                            seg.data.WriteBytes(data, offset, (int)length);
                            repeat = parse_data(seg);
                        }
                    }
                }
                else if (IKCP_CMD_WASK == cmd)
                {
                    // ready to send back IKCP_CMD_WINS in Ikcp_flush
                    // tell remote my window size
                    probe |= IKCP_ASK_TELL;
                }
                else if (IKCP_CMD_WINS == cmd)
                {
                    // do nothing
                }
                else
                {
                    return(-3);
                }

                inSegs++;
                offset += (int)length;
            }

            // update rtt with the latest ts
            // ignore the FEC packet
            if (flag != 0 && regular)
            {
                var current = currentMS();
                if (_itimediff(current, latest) >= 0)
                {
                    update_ack(_itimediff(current, latest));
                }
            }

            // cwnd update when packet arrived
            if (nocwnd == 0)
            {
                if (_itimediff(snd_una, s_una) > 0)
                {
                    if (cwnd < rmt_wnd)
                    {
                        var _mss = mss;
                        if (cwnd < ssthresh)
                        {
                            cwnd++;
                            incr += _mss;
                        }
                        else
                        {
                            if (incr < _mss)
                            {
                                incr = _mss;
                            }
                            incr += (_mss * _mss) / incr + (_mss) / 16;
                            if ((cwnd + 1) * _mss <= incr)
                            {
                                if (_mss > 0)
                                {
                                    cwnd = (incr + _mss - 1) / _mss;
                                }
                                else
                                {
                                    cwnd = incr + _mss - 1;
                                }
                            }
                        }
                        if (cwnd > rmt_wnd)
                        {
                            cwnd = rmt_wnd;
                            incr = rmt_wnd * _mss;
                        }
                    }
                }
            }

            // ack immediately
            if (ackNoDelay && acklist.Count > 0)
            {
                Flush(true);
            }

            return(0);
        }
 public MtTranslationProviderTagPlacer(Segment _sourceSegment)
 {
     sourceSegment = _sourceSegment;
     dict          = GetSourceTagsDict(); //fills the dictionary and populates our string to send to google
 }
Exemplo n.º 47
0
        // user/upper level send, returns below zero for error
        public int Send(byte[] buffer, int index, int length)
        {
            if (0 == length)
            {
                return(-1);
            }

            if (stream != 0)
            {
                var n = snd_queue.Count;
                if (n > 0)
                {
                    var seg = snd_queue[n - 1];
                    if (seg.data.ReadableBytes < mss)
                    {
                        var capacity = (int)(mss - seg.data.ReadableBytes);
                        var writen   = Math.Min(capacity, length);
                        seg.data.WriteBytes(buffer, index, writen);
                        index  += writen;
                        length -= writen;
                    }
                }
            }

            if (length == 0)
            {
                return(0);
            }

            var count = 0;

            if (length <= mss)
            {
                count = 1;
            }
            else
            {
                count = (int)(((length) + mss - 1) / mss);
            }

            if (count > 255)
            {
                return(-2);
            }

            if (count == 0)
            {
                count = 1;
            }

            for (var i = 0; i < count; i++)
            {
                var size = Math.Min(length, (int)mss);

                var seg = Segment.Get(size);
                seg.data.WriteBytes(buffer, index, size);
                index  += size;
                length -= size;

                seg.frg = (stream == 0 ? (byte)(count - i - 1) : (byte)0);
                snd_queue.Add(seg);
            }

            return(0);
        }
Exemplo n.º 48
0
        // flush pending data
        public UInt32 Flush(bool ackOnly)
        {
            var seg = Segment.Get(32);

            seg.conv = conv;
            seg.cmd  = IKCP_CMD_ACK;
            seg.wnd  = (UInt32)wnd_unused();
            seg.una  = rcv_nxt;

            var writeIndex = reserved;

            Action <int> makeSpace = (space) =>
            {
                if (writeIndex + space > mtu)
                {
                    output(buffer, writeIndex);
                    writeIndex = reserved;
                }
            };

            Action flushBuffer = () =>
            {
                if (writeIndex > reserved)
                {
                    output(buffer, writeIndex);
                }
            };

            // flush acknowledges
            for (var i = 0; i < acklist.Count; i++)
            {
                makeSpace(KCP.IKCP_OVERHEAD);
                var ack = acklist[i];
                if (_itimediff(ack.sn, rcv_nxt) >= 0 || acklist.Count - 1 == i)
                {
                    seg.sn      = ack.sn;
                    seg.ts      = ack.ts;
                    writeIndex += seg.encode(buffer, writeIndex);
                }
            }
            acklist.Clear();

            // flash remain ack segments
            if (ackOnly)
            {
                flushBuffer();
                return(interval);
            }

            uint current = 0;

            // probe window size (if remote window size equals zero)
            if (0 == rmt_wnd)
            {
                current = currentMS();
                if (0 == probe_wait)
                {
                    probe_wait = IKCP_PROBE_INIT;
                    ts_probe   = current + probe_wait;
                }
                else
                {
                    if (_itimediff(current, ts_probe) >= 0)
                    {
                        if (probe_wait < IKCP_PROBE_INIT)
                        {
                            probe_wait = IKCP_PROBE_INIT;
                        }
                        probe_wait += probe_wait / 2;
                        if (probe_wait > IKCP_PROBE_LIMIT)
                        {
                            probe_wait = IKCP_PROBE_LIMIT;
                        }
                        ts_probe = current + probe_wait;
                        probe   |= IKCP_ASK_SEND;
                    }
                }
            }
            else
            {
                ts_probe   = 0;
                probe_wait = 0;
            }

            // flush window probing commands
            if ((probe & IKCP_ASK_SEND) != 0)
            {
                seg.cmd = IKCP_CMD_WASK;
                makeSpace(IKCP_OVERHEAD);
                writeIndex += seg.encode(buffer, writeIndex);
            }

            if ((probe & IKCP_ASK_TELL) != 0)
            {
                seg.cmd = IKCP_CMD_WINS;
                makeSpace(IKCP_OVERHEAD);
                writeIndex += seg.encode(buffer, writeIndex);
            }

            probe = 0;

            // calculate window size
            var cwnd_ = _imin_(snd_wnd, rmt_wnd);

            if (0 == nocwnd)
            {
                cwnd_ = _imin_(cwnd, cwnd_);
            }

            // sliding window, controlled by snd_nxt && sna_una+cwnd
            var newSegsCount = 0;

            for (var k = 0; k < snd_queue.Count; k++)
            {
                if (_itimediff(snd_nxt, snd_una + cwnd_) >= 0)
                {
                    break;
                }

                var newseg = snd_queue[k];
                newseg.conv = conv;
                newseg.cmd  = IKCP_CMD_PUSH;
                newseg.sn   = snd_nxt;
                snd_buf.Add(newseg);
                snd_nxt++;
                newSegsCount++;
            }

            if (newSegsCount > 0)
            {
                snd_queue.RemoveRange(0, newSegsCount);
            }

            // calculate resent
            var resent = (UInt32)fastresend;

            if (fastresend <= 0)
            {
                resent = 0xffffffff;
            }

            // check for retransmissions
            current = currentMS();
            UInt64 change = 0; UInt64 lostSegs = 0; UInt64 fastRetransSegs = 0; UInt64 earlyRetransSegs = 0;
            var    minrto = (Int32)interval;

            for (var k = 0; k < snd_buf.Count; k++)
            {
                var segment  = snd_buf[k];
                var needsend = false;
                if (segment.acked == 1)
                {
                    continue;
                }
                if (segment.xmit == 0)  // initial transmit
                {
                    needsend         = true;
                    segment.rto      = rx_rto;
                    segment.resendts = current + segment.rto;
                }
                else if (segment.fastack >= resent) // fast retransmit
                {
                    needsend         = true;
                    segment.fastack  = 0;
                    segment.rto      = rx_rto;
                    segment.resendts = current + segment.rto;
                    change++;
                    fastRetransSegs++;
                }
                else if (segment.fastack > 0 && newSegsCount == 0) // early retransmit
                {
                    needsend         = true;
                    segment.fastack  = 0;
                    segment.rto      = rx_rto;
                    segment.resendts = current + segment.rto;
                    change++;
                    earlyRetransSegs++;
                }
                else if (_itimediff(current, segment.resendts) >= 0) // RTO
                {
                    needsend = true;
                    if (nodelay == 0)
                    {
                        segment.rto += rx_rto;
                    }
                    else
                    {
                        segment.rto += rx_rto / 2;
                    }
                    segment.fastack  = 0;
                    segment.resendts = current + segment.rto;
                    lostSegs++;
                }

                if (needsend)
                {
                    current = CurrentMS;
                    segment.xmit++;
                    segment.ts  = current;
                    segment.wnd = seg.wnd;
                    segment.una = seg.una;

                    var need = IKCP_OVERHEAD + segment.data.ReadableBytes;
                    makeSpace(need);
                    writeIndex += segment.encode(buffer, writeIndex);
                    Buffer.BlockCopy(segment.data.RawBuffer, segment.data.ReaderIndex, buffer, writeIndex, segment.data.ReadableBytes);
                    writeIndex += segment.data.ReadableBytes;

                    if (segment.xmit >= dead_link)
                    {
                        state = 0xFFFFFFFF;
                    }
                }

                // get the nearest rto
                var _rto = _itimediff(segment.resendts, current);
                if (_rto > 0 && _rto < minrto)
                {
                    minrto = _rto;
                }
            }

            // flash remain segments
            flushBuffer();

            // cwnd update
            if (nocwnd == 0)
            {
                // update ssthresh
                // rate halving, https://tools.ietf.org/html/rfc6937
                if (change > 0)
                {
                    var inflght = snd_nxt - snd_una;
                    ssthresh = inflght / 2;
                    if (ssthresh < IKCP_THRESH_MIN)
                    {
                        ssthresh = IKCP_THRESH_MIN;
                    }
                    cwnd = ssthresh + resent;
                    incr = cwnd * mss;
                }

                // congestion control, https://tools.ietf.org/html/rfc5681
                if (lostSegs > 0)
                {
                    ssthresh = cwnd / 2;
                    if (ssthresh < IKCP_THRESH_MIN)
                    {
                        ssthresh = IKCP_THRESH_MIN;
                    }
                    cwnd = 1;
                    incr = mss;
                }

                if (cwnd < 1)
                {
                    cwnd = 1;
                    incr = mss;
                }
            }

            return((UInt32)minrto);
        }
Exemplo n.º 49
0
 public SearchEngine(IHostingEnvironment hostingEnvironment)
 {
     _hostingEnvironment = hostingEnvironment;
     Segment.Init(PanGuXmlPath);
 }
Exemplo n.º 50
0
        bool parse_data(Segment newseg)
        {
            var sn = newseg.sn;

            if (_itimediff(sn, rcv_nxt + rcv_wnd) >= 0 || _itimediff(sn, rcv_nxt) < 0)
            {
                return(true);
            }

            var n          = rcv_buf.Count - 1;
            var insert_idx = 0;
            var repeat     = false;

            for (var i = n; i >= 0; i--)
            {
                var seg = rcv_buf[i];
                if (seg.sn == sn)
                {
                    repeat = true;
                    break;
                }

                if (_itimediff(sn, seg.sn) > 0)
                {
                    insert_idx = i + 1;
                    break;
                }
            }

            if (!repeat)
            {
                if (insert_idx == n + 1)
                {
                    rcv_buf.Add(newseg);
                }
                else
                {
                    rcv_buf.Insert(insert_idx, newseg);
                }
            }

            // move available data from rcv_buf -> rcv_queue
            var count = 0;

            foreach (var seg in rcv_buf)
            {
                if (seg.sn == rcv_nxt && rcv_queue.Count + count < rcv_wnd)
                {
                    rcv_nxt++;
                    count++;
                }
                else
                {
                    break;
                }
            }

            if (count > 0)
            {
                for (var i = 0; i < count; i++)
                {
                    rcv_queue.Add(rcv_buf[i]);
                }
                rcv_buf.RemoveRange(0, count);
            }
            return(repeat);
        }
Exemplo n.º 51
0
        //TODO: rewrite again
        public Thing AddSegmentFromVision(PointPlus P1, PointPlus P2, ColorInt theColor, bool moved)
        {
            Thing retVal = null;

            Debug.WriteLine("AddSegment: " + P1 + P2 + theColor);
            //determine if the segment is already in the UKS.
            //Correct it if it is there, add it if it is not.
            //FUTURE: detect motion
            if (theColor == 0)
            {
                return(null);
            }
            Segment newSegment = new Segment()
            {
                P1 = P1, P2 = P2, theColor = theColor
            };
            ModuleUKSN UKS = (ModuleUKSN)FindModleu(typeof(ModuleUKSN));

            GetSegmentsFromUKS();
            if (UKS != null)
            {
                //it's easier if we sort by theta
                OrderSegment(newSegment);
                retVal = MostLikelySegment(newSegment);
                if (retVal != null)
                {
                    //UKS.Fire(match);
                    //OrderSegment(match);
                    //Segment s = SegmentFromUKSThing(match);
                    //float newVisualWidth = newSegment.VisualWidth();
                    //float matchVisualWidth = s.VisualWidth();
                    ////if the newVisualWidth is bigger, an adjustment is needed
                    ////this happens if the initial view was occluded but now it is less
                    //Thing match1 = MostLikelyPoint(newSegment.P1, newSegment.theColor);
                    //Thing match2 = MostLikelyPoint(newSegment.P2, newSegment.theColor);
                    //if (match1 != null && match2 != null)
                    //{
                    //    if (newSegment.P1.Conf < s.P1.Conf)
                    //    {
                    //        s.P1.Conf = newSegment.P1.Conf;
                    //        s.P1.R = newSegment.P1.R;
                    //        s.P1.Theta = newSegment.P1.Theta;
                    //    }
                    //    if (newSegment.P2.Conf < s
                    //        .P2.Conf)
                    //    {
                    //        s.P2.Conf = newSegment.P2.Conf;
                    //        s.P2.R = newSegment.P2.R;
                    //        s.P2.Theta = newSegment.P2.Theta;
                    //    }
                    //}

                    ////there is a significant point mismatch...
                    //else
                    //{
                    //    if (match1 == null && newSegment.P1.R > s.P1.R)
                    //    {
                    //        s.P1.Conf = newSegment.P1.Conf;
                    //        s.P1.R = newSegment.P1.R;
                    //        s.P1.Theta = newSegment.P1.Theta;
                    //    }
                    //    if (match2 == null && newSegment.P2.R > s.P2.R)
                    //    {
                    //        s.P2.Conf = newSegment.P2.Conf;
                    //        s.P2.R = newSegment.P2.R;
                    //        s.P2.Theta = newSegment.P2.Theta;
                    //    }
                    //}
                }
                else
                {
                    retVal = AddSegmentToUKS(P1, P2, theColor);
                    UKS.Fire(retVal);
                }
                UpdateDialog();
            }
            return(retVal);
        }
Exemplo n.º 52
0
        // Receive data from kcp state machine
        //
        // Return number of bytes read.
        //
        // Return -1 when there is no readable data.
        //
        // Return -2 if len(buffer) is smaller than kcp.PeekSize().
        public int Recv(byte[] buffer, int index, int length)
        {
            var peekSize = PeekSize();

            if (peekSize < 0)
            {
                return(-1);
            }

            if (peekSize > length)
            {
                return(-2);
            }

            var fast_recover = false;

            if (rcv_queue.Count >= rcv_wnd)
            {
                fast_recover = true;
            }

            // merge fragment.
            var count = 0;
            var n     = index;

            foreach (var seg in rcv_queue)
            {
                // copy fragment data into buffer.
                Buffer.BlockCopy(seg.data.RawBuffer, seg.data.ReaderIndex, buffer, n, seg.data.ReadableBytes);
                n += seg.data.ReadableBytes;

                count++;
                var fragment = seg.frg;
                Segment.Put(seg);
                if (0 == fragment)
                {
                    break;
                }
            }

            if (count > 0)
            {
                rcv_queue.RemoveRange(0, count);
            }

            // move available data from rcv_buf -> rcv_queue
            count = 0;
            foreach (var seg in rcv_buf)
            {
                if (seg.sn == rcv_nxt && rcv_queue.Count + count < rcv_wnd)
                {
                    rcv_queue.Add(seg);
                    rcv_nxt++;
                    count++;
                }
                else
                {
                    break;
                }
            }

            if (count > 0)
            {
                rcv_buf.RemoveRange(0, count);
            }


            // fast recover
            if (rcv_queue.Count < rcv_wnd && fast_recover)
            {
                // ready to send back IKCP_CMD_WINS in ikcp_flush
                // tell remote my window size
                probe |= IKCP_ASK_TELL;
            }

            return(n - index);
        }
Exemplo n.º 53
0
 //Segments consist of two points and a color. Optionally, a segment may have some motion.
 //AddToModel determines whether or not the endpoints are to be modified as Sallie moves so static objects can be stored
 public Thing AddSegmentToUKS(Segment s)
 {
     return(AddSegmentToUKS(s.P1, s.P2, s.theColor));
 }
Exemplo n.º 54
0
        //get input from touch... accurate locations, no color
        public bool AddSegmentFromTouch(PointPlus P1, PointPlus P2, PointPlus motion, int arm)
        {
            //if conf=0, it's a known endpoint. conf=1, not an endpoint
            ModuleUKSN UKS = (ModuleUKSN)FindModleu(typeof(ModuleUKSN));

            if (UKS is null)
            {
                return(false);
            }
            if (UKSSegments is null)
            {
                return(false);
            }
            if (imagining)
            {
                return(false);
            }

            ColorInt theColor   = Utils.ColorToInt(Colors.Wheat);
            Segment  newSegment = new Segment()
            {
                P1 = P1, P2 = P2, theColor = theColor
            };
            //OrderSegment(newSegment);

            Thing t1 = GetNearestThing(newSegment.MidPoint.Theta, out float dist1);

            //TODO: for motion testing
            t1 = UKS.Labeled("s0");
            if (t1 == null)
            {
                //TODO: merge mutliple segments
                //                AddSegmentToUKS(P1, P2, theColor, motion); //don't store motion with the segment (yet)
                AddSegmentToUKS(P1, P2, theColor);
            }

            else if (dist1 < 1)
            {
                Segment   prevSegment  = SegmentFromUKSThing(t1);
                PointPlus prevMidpoint = prevSegment.MidPoint;
                Angle     oldM         = prevSegment.Angle;
                Angle     newM         = newSegment.Angle;
                PointPlus offset       = new PointPlus()
                {
                    R = prevSegment.Length, Theta = newM
                };
                if (P1.Conf == 0 && P2.Conf == 0) //we're given both endpoints
                {
                    prevSegment.P1.P = P1.P; prevSegment.P1.Conf = 0;
                    prevSegment.P2.P = P2.P; prevSegment.P2.Conf = 0;
                }
                else if (P1.Conf == 0)
                {
                    prevSegment.P1.P = P1.P; prevSegment.P1.Conf = 0;
                    prevSegment.P2.P = P1.P - offset.V;
                }
                else if (P2.Conf == 0)
                {
                    prevSegment.P1.P = P2.P; prevSegment.P2.Conf = 0;
                    prevSegment.P2.P = P2.P + offset.V;
                }
                else
                {
                    //we're not near an endpoint--match the modpoint as close as possible & preserve length
                    //make the segment match the two points
                    PointPlus newMidpoint1 = new PointPlus()
                    {
                        P = (Point)GetClosestPointOnLine(P1.V, P2.V, prevMidpoint.V),
                    };
                    //offset is the dietance from the midpoint to each end
                    offset.R = offset.R / 2;
                    PointPlus newP1 = new PointPlus()
                    {
                        P = newMidpoint1.P + offset.V
                    };
                    PointPlus newP2 = new PointPlus()
                    {
                        P = newMidpoint1.P - offset.V
                    };
                    prevSegment.P1.R = newP1.R; prevSegment.P1.Theta = newP1.Theta;
                    prevSegment.P2.R = newP2.R; prevSegment.P2.Theta = newP2.Theta;
                }
                PointPlus newMidpoint = prevSegment.MidPoint;
                newMidpoint.P = newMidpoint.P - prevMidpoint.V;
                if (newMidpoint.R > 0.01 && motion.R != 0)
                {
                    if (prevSegment.Motion == null)
                    {
                        prevSegment.Motion = new PointPlus();
                        Thing tMotion = UKS.AddThing("m" + mCount++, UKS.Labeled("Point"));
                        tMotion.V = prevSegment.Motion;
                        t1.AddReference(tMotion);
                    }
                    prevSegment.Motion.R     = motion.R;
                    prevSegment.Motion.Theta = motion.Theta;
                    prevSegment.Motion.Conf  = newM - oldM;
                }
            }

            UpdateDialog();
            return(false);
        }