Exemplo n.º 1
0
        public async Task <IEnumerable <TraceHistogram> > GetTraceHistogram(TraceQuery traceQuery)
        {
            traceQuery.Ensure();

            var index = Indices.Index(_indexManager.CreateTracingIndex());

            var query = BuildTracesQuery(traceQuery);

            var timeSpan = traceQuery.FinishTimestamp.Value - traceQuery.StartTimestamp.Value;

            var histogramAggregationsResult = await _elasticClient.SearchAsync <Span>(s => s.Index(index).Size(0).Query(query).
                                                                                      Aggregations(a =>
                                                                                                   a.DateHistogram("data_histogram_startTimestamp", d => d.Field(f => f.StartTimestamp).Interval(DateInterval.Minute).Format("yyyy-MM-dd HH:mm:ss").
                                                                                                                   Aggregations(sub => sub.Cardinality("cardinality_traceId", c => c.Field(f => f.TraceId))))));

            var histogramAggregations = histogramAggregationsResult.Aggregations.FirstOrDefault().Value as BucketAggregate;

            if (histogramAggregations == null || histogramAggregations.Items == null || !histogramAggregations.Items.OfType <DateHistogramBucket>().Any())
            {
                return(new TraceHistogram[0]);
            }

            var traceHistograms = histogramAggregations.Items.OfType <DateHistogramBucket>().Select(x => new TraceHistogram {
                Time = GetHistogramTime((long)x.Key), Count = GetTraceCount(x)
            });

            return(traceHistograms.OrderBy(x => x.Time).ToList());
        }
Exemplo n.º 2
0
        public async Task <PageViewModel <TraceViewModel> > Get(
            [FromQuery] string service, [FromQuery] string tags,
            [FromQuery] DateTime?startTimestamp, [FromQuery] DateTime?finishTimestamp,
            [FromQuery] int?minDuration, [FromQuery] int?maxDuration,
            [FromQuery] int?pageNumber, [FromQuery] int?pageSize)
        {
            var query = new TraceQuery
            {
                Tags              = tags,
                ServiceName       = service,
                StartTimestamp    = startTimestamp?.ToUniversalTime(),
                FinishTimestamp   = finishTimestamp?.ToUniversalTime(),
                MinDuration       = minDuration,
                MaxDuration       = maxDuration,
                CurrentPageNumber = pageNumber.GetValueOrDefault(1),
                PageSize          = pageSize.GetValueOrDefault(10)
            };

            var data = await _spanQuery.GetTraces(query);

            var pageViewModel = _mapper.Map <PageViewModel <TraceViewModel> >(data);

            foreach (var traceViewModel in pageViewModel.Data)
            {
                var trace = data.Data.FirstOrDefault(x => x.TraceId == traceViewModel.TraceId);
                traceViewModel.Services = GetTraceServices(trace);
            }

            return(pageViewModel);
        }
Exemplo n.º 3
0
        public Task <PageResult <Trace> > GetTraces(TraceQuery traceQuery)
        {
            var query = _dbContext.Spans.AsNoTracking().Include(x => x.Tags).OrderByDescending(x => x.StartTimestamp).AsQueryable();

            if (traceQuery.StartTimestamp != null)
            {
                query = query.Where(x => x.StartTimestamp >= traceQuery.StartTimestamp);
            }

            if (traceQuery.FinishTimestamp != null)
            {
                query = query.Where(x => x.FinishTimestamp <= traceQuery.FinishTimestamp);
            }

            var queryTags = BuildQueryTags(traceQuery).ToList();

            if (queryTags.Any())
            {
                var traceIdsQuery = query;

                foreach (var item in queryTags)
                {
                    var tag = item;
                    traceIdsQuery = traceIdsQuery.Where(x => x.Tags.Any(t => t.Key == tag.Key && t.Value == tag.Value));
                }

                var traceIds = traceIdsQuery.Select(x => x.TraceId).Distinct().ToList();

                query = query.Where(x => traceIds.Contains(x.TraceId));
            }

            var queryGroup = query.ToList().GroupBy(x => x.TraceId);

            //todo fix
//            if (traceQuery.MinDuration != null)
//            {
//                queryGroup = queryGroup.Where(x => x.Sum(s => s.Duration) >= traceQuery.MinDuration);
//            }
//
//            if (traceQuery.MaxDuration != null)
//            {
//                queryGroup = queryGroup.Where(x => x.Sum(s => s.Duration) <= traceQuery.MaxDuration);
//            }

            var totalMemberCount = queryGroup.Count();

            queryGroup = queryGroup.Skip((traceQuery.CurrentPageNumber - 1) * traceQuery.PageSize).Take(traceQuery.PageSize);

            return(Task.FromResult(new PageResult <Trace>()
            {
                CurrentPageNumber = traceQuery.CurrentPageNumber,
                PageSize = traceQuery.PageSize,
                TotalMemberCount = totalMemberCount,
                TotalPageCount = (int)Math.Ceiling((double)totalMemberCount / (double)traceQuery.PageSize),
                Data = queryGroup.ToList().Select(x => new Trace()
                {
                    TraceId = x.Key, Spans = _mapper.Map <List <Span> >(x.ToList())
                }).ToList()
            }));
        }
Exemplo n.º 4
0
        private List <Tag> BuildQueryTags(TraceQuery traceQuery)
        {
            var tagList = new List <Tag>();

            if (!string.IsNullOrEmpty(traceQuery.ServiceName))
            {
                tagList.Add(new Tag {
                    Key = QueryConstants.Service, Value = traceQuery.ServiceName
                });
                return(tagList);
            }

            if (!string.IsNullOrEmpty(traceQuery.Tags))
            {
                var tags = traceQuery.Tags.Split('|');
                foreach (var tag in tags)
                {
                    var pair = tag.Split('=');
                    if (pair.Length == 2)
                    {
                        tagList.Add(new Tag {
                            Key = pair[0], Value = pair[1]
                        });
                    }
                }
            }

            return(tagList);
        }
Exemplo n.º 5
0
        public async Task <IEnumerable <TraceHistogram> > GetTraceHistogram(TraceQuery traceQuery)
        {
            var sql = "select TOP (@Limit) cast(StartTimestamp as date) [Date], Datepart(hour, StartTimestamp) [Hour], DATEPART(minute, StartTimestamp) [Minute], Count(1)[Count]"
                      + " from Spans"
                      + " group by cast(StartTimestamp as date), Datepart(hour, StartTimestamp), DATEPART(minute, StartTimestamp)"
                      + " order by 1, 2, 3";

            using (var conn = await GetConnectionAsync())
                using (var cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("Limit", traceQuery.Limit);

                    using (var reader = await cmd.ExecuteReaderAsync())
                    {
                        var histograms = new List <TraceHistogram>();

                        while (await reader.ReadAsync())
                        {
                            var histogram = new TraceHistogram();
                            histogram.Time  = DateTimeOffset.Parse($"{reader.GetDateTime(0).ToShortDateString()} {reader.GetInt32(1):00}:{reader.GetInt32(2):00}");
                            histogram.Count = reader.GetInt32(3);

                            histograms.Add(histogram);
                        }

                        return(histograms);
                    }
                }
        }
Exemplo n.º 6
0
        public async Task <IEnumerable <TraceViewModel> > Get(
            [FromQuery] string service, [FromQuery] string tags,
            [FromQuery] long?startTimestamp, [FromQuery] long?finishTimestamp,
            [FromQuery] int?minDuration, [FromQuery] int?maxDuration, [FromQuery] int?limit)
        {
            var query = new TraceQuery
            {
                Tags            = tags,
                ServiceName     = service,
                StartTimestamp  = TimestampHelpers.Convert(startTimestamp),
                FinishTimestamp = TimestampHelpers.Convert(finishTimestamp),
                MinDuration     = minDuration,
                MaxDuration     = maxDuration,
                Limit           = limit.GetValueOrDefault(10)
            };

            var data = await _spanQuery.GetTraces(query);

            var traceViewModels = _mapper.Map <List <TraceViewModel> >(data);

            foreach (var trace in traceViewModels)
            {
                var item = data.FirstOrDefault(x => x.TraceId == trace.TraceId);
                trace.Services = GetTraceServices(item);
            }

            return(traceViewModels);
        }
Exemplo n.º 7
0
        public async Task <IEnumerable <Trace> > GetTraces(TraceQuery traceQuery)
        {
            var index = Indices.Index(_indexManager.CreateTracingIndex());

            var query = BuildTracesQuery(traceQuery);

            var traceIdsAggregationsResult = await _elasticClient.SearchAsync <Span>(s => s.Index(index).Size(0).Query(query).
                                                                                     Aggregations(a => a.Terms("group_by_traceId",
                                                                                                               t => t.Aggregations(sub => sub.Min("min_startTimestapm", m => m.Field(f => f.StartTimestamp))).Field(f => f.TraceId).Order(o => o.Descending("min_startTimestapm")).Size(traceQuery.Limit))));

            var traceIdsAggregations = traceIdsAggregationsResult.Aggregations.FirstOrDefault().Value as BucketAggregate;

            if (traceIdsAggregations == null)
            {
                return(new Trace[0]);
            }

            var KeyedBuckets = traceIdsAggregations.Items.OfType <KeyedBucket <object> >();

            var traceIds = traceIdsAggregations.Items.OfType <KeyedBucket <object> >().Where(x => x.Key != null).Select(x => x.Key.ToString()).ToList();

            var limit = KeyedBuckets.Sum(x => x.DocCount).Value;

            if (traceIds.Count == 0)
            {
                return(new Trace[0]);
            }

            var spanResult = await _elasticClient.SearchAsync <Span>(s => s.Index(index).Size((int)limit).Query(q => q.ConstantScore(c => c.Filter(filter => filter.Terms(t => t.Field(f => f.TraceId).Terms(traceIds))))));

            return(spanResult.Documents.GroupBy(x => x.TraceId).Select(x => new Trace {
                TraceId = x.Key, Spans = x.ToList()
            }).OrderByDescending(x => x.Spans.Min(s => s.StartTimestamp)).ToList());
        }
Exemplo n.º 8
0
        /// <summary>
        /// Determines whether the player is balancing on an edge.
        /// </summary>
        /// <param name="trA">The result of sensor A.</param>
        /// <param name="trB">The result of sensor B.</param>
        private void DetectBalancing(TraceResult trA, TraceResult trB)
        {
            if (trA.Hit == trB.Hit)
            {
                return;
            }

            var flipped  = _player.FlipHorizontally;
            var position = _player.Position;
            var size     = _player.Size;

            TraceResult tr       = trA.Hit ? trA : trB;
            var         reversed = (trA.Hit && flipped) || (trB.Hit && !flipped);

            double edgeDiff;
            double objectWidth;

            if (tr.Entity == null)
            {
                var tile = tr.Tile;
                objectWidth = tile.Definition.Rect.Size.X;
                edgeDiff    = Math.Abs(position.X - (tile.WorldPosition.X + objectWidth / 2.0));
            }
            else
            {
                var entity = tr.Entity;
                objectWidth = entity.Size.X;
                edgeDiff    = Math.Abs(position.X - entity.Position.X);
            }

            var tq = new TraceQuery
            {
                Line          = new Line(position, new Point(position.X, position.Y + (size.Y / 2.0))),
                CollisionPath = _player.CollisionPath,
                Ignore        = _player,
                Options       = TraceLineOptions.SolidOnly
            };

            var trMiddle = _collisionService.TraceLine(tq);

            if (!trMiddle.Hit)
            {
                if (reversed && (edgeDiff > objectWidth / 2))
                {
                    _balanceState = BalanceState.Backward;
                }
                else if (edgeDiff > (objectWidth / 2) + 6)
                {
                    _balanceState = BalanceState.ForwardVeryEdge;
                }
                else if (edgeDiff > objectWidth / 2)
                {
                    _balanceState = BalanceState.Forward;
                }
            }
        }
Exemplo n.º 9
0
        public bool Trace()
        {
            bool result = default;

            for (int i = 0; i < traceQueries.Length; i++)
            {
                TraceQuery query = traceQueries[i];
                result ^= CurrentPair.scene.Trace(ref query);
            }

            return(result);
        }
Exemplo n.º 10
0
        public BenchmarkBVH()
        {
            Scene scene = new Scene();

            Mesh mesh = new(@"C:\Users\MMXXXVIII\Things\CodingStuff\C#\EchoRenderer\EchoRenderer\Assets\Models\BlenderBMW\BlenderBMW.obj");

            scene.children.Add(new MeshObject(mesh, new Matte()));

            traceQueries   = new TraceQuery[65536];
            occludeQueries = new OccludeQuery[65536];

            IRandom random = new SystemRandom(42);

            const float Radius = 9f;
            const float Height = 5f;

            for (int i = 0; i < traceQueries.Length; i++)
            {
                Float2 point    = new Float2(MathF.Sqrt(random.Next1()) * Radius, random.Next1() * Height);
                Float3 position = point.X_Y.RotateXZ(random.Next1() * 360f);

                Float3 target = Float3.CreateY(0.6f) + random.NextInSphere(0.25f);

                if (random.Next1() < 0.01f)
                {
                    Float3 offset = (target - position) / 2f;

                    target    = position;
                    position += offset;
                }

                Ray ray = new Ray(position, (target - position).Normalized);

                traceQueries[i]   = ray;
                occludeQueries[i] = ray;
            }

            Pairs = new[]
            {
                new Pair(new PreparedScene(scene, new ScenePrepareProfile {
                    AggregatorProfile = new AggregatorProfile {
                        AggregatorType = typeof(BoundingVolumeHierarchy)
                    }
                }), "Regular"),
                new Pair(new PreparedScene(scene, new ScenePrepareProfile {
                    AggregatorProfile = new AggregatorProfile {
                        AggregatorType = typeof(QuadBoundingVolumeHierarchy)
                    }
                }), "Quad")
            };
        }
Exemplo n.º 11
0
        public Task <PageResult <Trace> > GetTraces(TraceQuery traceQuery)
        {
            var query = _dbContext.Spans.AsNoTracking().Include(x => x.Tags).AsQueryable();

            if (traceQuery.ApplicationName != null)
            {
                var traceIds = query.Where(x => x.Tags.Any(t => t.Key == "application" && t.Value == traceQuery.ApplicationName)).Select(x => x.TraceId).ToList();
                query = query.Where(x => traceIds.Contains(x.TraceId));
            }

            if (traceQuery.StartTimestamp != null)
            {
                query = query.Where(x => x.StartTimestamp <= traceQuery.StartTimestamp);
            }

            if (traceQuery.FinishTimestamp != null)
            {
                query = query.Where(x => x.FinishTimestamp >= traceQuery.FinishTimestamp);
            }

            if (traceQuery.MinDuration != null)
            {
                query = query.Where(x => x.Duration >= traceQuery.MinDuration);
            }

            if (traceQuery.MaxDuration != null)
            {
                query = query.Where(x => x.Duration <= traceQuery.MaxDuration);
            }

            var queryGroup = query.GroupBy(x => x.TraceId);

            var totalMemberCount = queryGroup.Count();

            queryGroup = queryGroup.Skip((traceQuery.CurrentPageNumber - 1) * traceQuery.PageSize).Take(traceQuery.PageSize);

            return(Task.FromResult(new PageResult <Trace>()
            {
                CurrentPageNumber = traceQuery.CurrentPageNumber,
                PageSize = traceQuery.PageSize,
                TotalMemberCount = totalMemberCount,
                TotalPageCount = (int)Math.Ceiling((double)totalMemberCount / (double)traceQuery.PageSize),
                Data = queryGroup.ToList().Select(x => new Trace()
                {
                    TraceId = x.Key, Spans = _mapper.Map <List <Span> >(x.ToList())
                }).ToList()
            }));
        }
        /// <summary>
        /// Gets a trace query for use in collision traces during movement.
        /// </summary>
        /// <param name="line">The line to use for the trace..</param>
        /// <returns>A trace query.</returns>
        private TraceQuery GetTraceQuery(Line line)
        {
            var tq = new TraceQuery()
            {
                Line          = line,
                Ignore        = _parent,
                CollisionPath = _parent.CollisionPath,
                Options       = TraceLineOptions.SolidOnly
            };

            if (TerrainOnly)
            {
                tq.Options |= TraceLineOptions.IgnoreEntities;
            }

            return(tq);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Checks whether the player is touching/pushing a wall to the right.
        /// </summary>
        /// <param name="touching">set to <c>true</c> if the player is contacting the wall.</param>
        /// <param name="pushing">set to <c>true</c> is the player is actively pushing agsint the wall.</param>
        private void CheckWallRight(out bool touching, out bool pushing)
        {
            var size = _player.Size;

            const int maxResolveIterations = 10;

            touching = false;
            pushing  = false;

            var    halfWidth = size.X / 2.0;
            double oldX;

            // don't perform iterative resolution if the player is falling
            int iterations = _falling ? 0 : maxResolveIterations;

            do
            {
                var position = _player.Position;
                oldX = position.X;
                var start = new Point(position.X, position.Y + 4.0);
                var end   = new Point(position.X + halfWidth, position.Y + 4.0);
                var tq    = new TraceQuery
                {
                    Line          = new Line(start, end),
                    CollisionPath = _player.CollisionPath,
                    Options       = TraceLineOptions.IgnoreJumpThrough | TraceLineOptions.SolidOnly,
                    Ignore        = _player
                };
                var tr = _collisionService.TraceLine(tq);

                if (tr.Hit)
                {
                    touching = true;

                    if (position.X >= (tr.ContactPoint.X - halfWidth))
                    {
                        _player.Position = new Point(tr.ContactPoint.X - halfWidth, position.Y);

                        if (_xsp > 0.0)
                        {
                            pushing = true;
                        }
                    }
                }
            }while (--iterations > 0 && (oldX != _player.Position.X));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Determines whether the given point is within the bounding box of an entity.
        /// </summary>
        /// <param name="x">The x coordinate.</param>
        /// <param name="y">The y coordinate.</param>
        /// <param name="trace">The trace.</param>
        /// <param name="entity">The entity.</param>
        /// <returns>
        ///   <c>true</c> if [is point in entity] [the specified x]; otherwise, <c>false</c>.
        /// </returns>
        private bool IsPointInEntity(List <GameEntity> entityList, int x, int y, TraceQuery trace, out GameEntity entity)
        {
            entity = null;

            for (var i = 0; i < entityList.Count; i++)
            {
                var ent  = entityList[i];
                var rect = ent.WorldRect;
                if (
                    (x >= rect.Position.X && x <= rect.Position.X + rect.Size.X) &&
                    (y >= rect.Position.Y && y <= rect.Position.Y + rect.Size.Y))
                {
                    entity = ent;
                    break;
                }
            }

            return(entity != null);
        }
Exemplo n.º 15
0
        public IHttpActionResult GetParsedCDFTraceTemplate(int jobId, [FromBody] TraceQuery param)
        {
            string condition = string.Empty;

            if (param.Condition != null)
            {
                IList <string> conditionList = new List <string>();

                if (!string.IsNullOrEmpty(param.Condition.Module))
                {
                    conditionList.Add(" ModuleName = '" + param.Condition.Module + "'");
                }
                if (!string.IsNullOrEmpty(param.Condition.Src))
                {
                    conditionList.Add(" Src = '" + param.Condition.Src + "'");
                }
                if (!string.IsNullOrEmpty(param.Condition.Function))
                {
                    conditionList.Add(" FunctionName = '" + param.Condition.Function + "'");
                }
                if (!string.IsNullOrEmpty(param.Condition.Message))
                {
                    conditionList.Add(" Message LIKE '%" + param.Condition.Message + "%'");
                }
                if (conditionList.Count > 0)
                {
                    condition = string.Format("WHERE {0}", string.Join(" AND ", conditionList));
                }
            }
            string sql =
                @"SELECT [ID],[CPU],[LogTime],[ThreadID],[ThreadName],[ProcessID],
                    [ProcessName],[SessionID],[ModuleName] ,[Src],[LineNum],[FunctionName],
                    [LevelID],[ClassName],[Message],[Comments],[RawTraceID],[NodeID],
                    [CdfModuleID],[IsIssuePattern],[JobID]
                FROM (SELECT ROW_NUMBER() OVER ( ORDER BY LogTime ) AS RowNum, * FROM ParsedCDFTrace_{0} {3})
                AS CDFTrace
                WHERE RowNum >= {1}
                    AND RowNum < {2}
                ORDER BY RowNum";
            List <CDFLine> list = db.Database.SqlQuery <CDFLine>(string.Format(sql, jobId, param.Pagination.startIndex, param.Pagination.endIndex, condition)).ToList <CDFLine>();

            return(Ok(list));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Checks and performs tracking of the prescence of the ground when in floor mode.
        /// </summary>
        private void CheckForGroundFloor()
        {
            var position = _player.Position;
            var size     = _player.Size;

            double groundHeight;
            double halfHeight = (size.Y / 2.0);
            double footLevel  = position.Y + halfHeight;

            // length of A/B sensors
            const double sensorLength = 16.0;

            // A sensor
            var start = new Point(position.X - 9.0, position.Y);
            var end   = new Point(position.X - 9.0, footLevel + sensorLength);
            var tq    = new TraceQuery {
                Line = new Line(start, end), CollisionPath = _player.CollisionPath, Ignore = _player, Options = TraceLineOptions.SolidOnly
            };
            var trA = _collisionService.TraceLine(tq);

            groundHeight = trA.Hit ? trA.ContactPoint.Y : Double.MaxValue;

            // B sensor
            start = new Point(position.X + 9.0, position.Y);
            end   = new Point(position.X + 9.0, footLevel + sensorLength);
            tq    = new TraceQuery {
                Line = new Line(start, end), CollisionPath = _player.CollisionPath, Ignore = _player, Options = TraceLineOptions.SolidOnly
            };
            var trB = _collisionService.TraceLine(tq);

            groundHeight = Math.Min(groundHeight, trB.Hit ? trB.ContactPoint.Y : Double.MaxValue);

            if (!trA.Hit && !trB.Hit)
            {
                Fall();
                return;
            }

            _player.Position = new Point(position.X, groundHeight - halfHeight);
            CalculateGroundAngle(trA, trB, PlayerMovementMode.Floor);
            DetectBalancing(trA, trB);
        }
Exemplo n.º 17
0
        public async Task <PageViewModel <TraceViewModel> > Get(
            [FromQuery] string application,
            [FromQuery] DateTimeOffset?startTimestamp, [FromQuery] DateTimeOffset?finishTimestamp,
            [FromQuery] int?minDuration, [FromQuery] int?maxDuration,
            [FromQuery] int?pageNumber, [FromQuery] int?pageSize)
        {
            var query = new TraceQuery
            {
                ApplicationName   = application,
                StartTimestamp    = startTimestamp,
                FinishTimestamp   = finishTimestamp,
                MinDuration       = minDuration,
                MaxDuration       = maxDuration,
                CurrentPageNumber = pageNumber.GetValueOrDefault(1),
                PageSize          = pageSize.GetValueOrDefault(10)
            };
            var data = await _spanQuery.GetTraces(query);

            return(_mapper.Map <PageViewModel <TraceViewModel> >(data));
        }
Exemplo n.º 18
0
        public async Task <IEnumerable <TraceHistogramViewModel> > GetTraceHistogram(
            [FromQuery] string service, [FromQuery] string tags,
            [FromQuery] long?startTimestamp, [FromQuery] long?finishTimestamp,
            [FromQuery] int?minDuration, [FromQuery] int?maxDuration, [FromQuery] int?limit)
        {
            var query = new TraceQuery
            {
                Tags            = tags,
                ServiceName     = service,
                StartTimestamp  = TimestampHelpers.Convert(startTimestamp),
                FinishTimestamp = TimestampHelpers.Convert(finishTimestamp),
                MinDuration     = minDuration,
                MaxDuration     = maxDuration,
                Limit           = limit.GetValueOrDefault(10)
            };

            var data = await _spanQuery.GetTraceHistogram(query);

            return(_mapper.Map <List <TraceHistogramViewModel> >(data));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Checks and performs tracking of the prescence of the ground when in left wall mode.
        /// </summary>
        private void CheckForGroundLeft()
        {
            var position = _player.Position;
            var size     = _player.Size;

            double groundHeight;
            double halfHeight = (size.Y / 2.0);
            double footLevel  = position.X - halfHeight;

            // length of A/B sensors
            const double sensorLength = 16.0;

            // A sensor
            var start = new Point(position.X, position.Y - 9.0);
            var end   = new Point(footLevel - sensorLength, position.Y - 9.0);
            var tq    = new TraceQuery {
                Line = new Line(start, end), CollisionPath = _player.CollisionPath, Ignore = _player, Options = TraceLineOptions.SolidOnly
            };
            var trA = _collisionService.TraceLine(tq);

            groundHeight = trA.Hit ? trA.ContactPoint.X : footLevel;

            // B sensor
            start = new Point(position.X, position.Y + 9.0);
            end   = new Point(footLevel - sensorLength, position.Y + 9.0);
            tq    = new TraceQuery {
                Line = new Line(start, end), CollisionPath = _player.CollisionPath, Ignore = _player, Options = TraceLineOptions.SolidOnly
            };
            var trB = _collisionService.TraceLine(tq);

            groundHeight = Math.Max(groundHeight, trB.Hit ? trB.ContactPoint.X : footLevel);

            if (!trA.Hit && !trB.Hit)
            {
                Fall();
                return;
            }

            _player.Position = new Point(groundHeight + halfHeight, position.Y);
            CalculateGroundAngle(trA, trB, PlayerMovementMode.LeftWall);
        }
Exemplo n.º 20
0
        public async Task <IEnumerable <Trace> > GetTraces(TraceQuery traceQuery)
        {
            var index = Indices.Index(_indexManager.CreateTracingIndex());

            var query = BuildTracesQuery(traceQuery);

            var traceIdsAggregationsResult = await _elasticClient.SearchAsync <Span>(s => s.Index(index).Size(0).Query(query).
                                                                                     Aggregations(a => a.Terms("group_by_traceId",
                                                                                                               t => t.Aggregations(sub => sub.Min("min_startTimestapm", m => m.Field(f => f.StartTimestamp))).Field(f => f.TraceId).Order(o => o.Descending("min_startTimestapm")).Size(traceQuery.Limit))));

            var traceIdsAggregations = traceIdsAggregationsResult.Aggregations.FirstOrDefault().Value as BucketAggregate;

            if (traceIdsAggregations == null)
            {
                return(new Trace[0]);
            }

            var traces = traceIdsAggregations.Items.OfType <KeyedBucket <object> >().AsParallel().Select(x => GetTrace(x.Key?.ToString(), index)).OrderByDescending(x => x.Spans.Min(s => s.StartTimestamp)).ToList();

            return(traces);
        }
        /// <summary>
        /// Steps the movement of the parent entity by the controller logic.
        /// </summary>
        public override void Move()
        {
            if (_falling || !FallOnce)
            {
                _ysp += Gravity * _varService.DeltaTime;

                var position = _parent.Position;
                var size     = _parent.CollisionBox.GetSize();

                var tq = new TraceQuery()
                {
                    Line          = new Line(position.X, position.Y, position.X, position.Y + size.Y / 2.0),
                    Ignore        = _parent,
                    CollisionPath = _parent.CollisionPath,
                    Options       = TraceLineOptions.SolidOnly
                };

                if (TerrainOnly)
                {
                    tq.Options |= TraceLineOptions.IgnoreEntities;
                }

                var tr = _collisionService.TraceLine(tq);

                if (!tr.Hit)
                {
                    _falling = true;
                    _ysp     = Math.Min(_ysp, MaxFallSpeed);
                }
                else
                {
                    _ysp             = 0.0;
                    _parent.Position = new Point(position.X, tr.ContactPoint.Y - size.Y / 2.0);
                    _falling         = false;
                }
            }

            base.Move();
        }
Exemplo n.º 22
0
        public Task <IEnumerable <Trace> > GetTraces(TraceQuery traceQuery)
        {
            var query = _dbContext.Spans.Include(x => x.Tags).OrderByDescending(x => x.StartTimestamp).AsQueryable();

            if (traceQuery.StartTimestamp != null)
            {
                query = query.Where(x => x.StartTimestamp >= traceQuery.StartTimestamp);
            }

            if (traceQuery.FinishTimestamp != null)
            {
                query = query.Where(x => x.FinishTimestamp <= traceQuery.FinishTimestamp);
            }

            var queryTags = BuildQueryTags(traceQuery).ToList();

            if (queryTags.Any())
            {
                var traceIdsQuery = query;

                foreach (var item in queryTags)
                {
                    var tag = item;
                    traceIdsQuery = traceIdsQuery.Where(x => x.Tags.Any(t => t.Key == tag.Key && t.Value == tag.Value));
                }

                var traceIds = traceIdsQuery.Select(x => x.TraceId).Distinct().ToList();

                query = query.Where(x => traceIds.Contains(x.TraceId));
            }

            var queryGroup = query.ToList().GroupBy(x => x.TraceId).Take(traceQuery.Limit).ToList();

            return(Task.FromResult <IEnumerable <Trace> >(queryGroup.Select(x => new Trace()
            {
                TraceId = x.Key, Spans = _mapper.Map <List <Span> >(x.ToList())
            }).ToList()));
        }
Exemplo n.º 23
0
        private IEnumerable <Tag> BuildQueryTags(TraceQuery traceQuery)
        {
            if (!string.IsNullOrEmpty(traceQuery.ServiceName))
            {
                yield return(new Tag {
                    Key = QueryConstants.Service, Value = traceQuery.ServiceName
                });
            }

            if (!string.IsNullOrEmpty(traceQuery.Tags))
            {
                var tags = traceQuery.Tags.Split('|');
                foreach (var tag in tags)
                {
                    var pair = tag.Split('=');
                    if (pair.Length == 2)
                    {
                        yield return(new Tag {
                            Key = pair[0], Value = pair[1]
                        });
                    }
                }
            }
        }
Exemplo n.º 24
0
        public async Task <IEnumerable <TraceHistogram> > GetTraceHistogram(TraceQuery traceQuery)
        {
            traceQuery.Ensure();

            var query = _dbContext.Spans.AsQueryable();

            if (traceQuery.StartTimestamp != null)
            {
                query = query.Where(x => x.StartTimestamp >= traceQuery.StartTimestamp);
            }

            if (traceQuery.FinishTimestamp != null)
            {
                query = query.Where(x => x.FinishTimestamp <= traceQuery.FinishTimestamp);
            }

            var queryGroup = query.ToList().GroupBy(x => x.TraceId).ToList();

            var histogram = queryGroup.GroupBy(x => x.Min(s => s.StartTimestamp).ToString("yyyy-MM-dd HH:mm")).Select(x => new TraceHistogram {
                Count = x.Count(), Time = DateTimeOffset.Parse(x.Key)
            });

            return(histogram.ToList());
        }
Exemplo n.º 25
0
 public Task <IEnumerable <TraceOperationHistogram> > GetSpanHistogramByOperaionName(TraceQuery traceQuery)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 26
0
        public async Task <IEnumerable <Trace> > GetTraces(TraceQuery traceQuery)
        {
            var sql = "SELECT TOP (@Limit) TraceId, MIN(StartTimestamp) as StartTimestamp, MIN(FinishTimestamp) as FinishTimestamp from Spans";

            if (traceQuery.StartTimestamp.HasValue || traceQuery.FinishTimestamp.HasValue)
            {
                sql += " WHERE";
            }

            if (traceQuery.StartTimestamp.HasValue)
            {
                sql += " StartTimestamp > @StartTimestamp";
            }

            if (traceQuery.StartTimestamp.HasValue && traceQuery.FinishTimestamp.HasValue)
            {
                sql += " AND";
            }

            if (traceQuery.FinishTimestamp.HasValue)
            {
                sql += " FinishTimestamp < @FinishTimestamp";
            }

            if ((traceQuery.StartTimestamp.HasValue || traceQuery.FinishTimestamp.HasValue) && !string.IsNullOrEmpty(traceQuery.ServiceName))
            {
                sql += " AND";
            }

            //TODO: Figure out how to filter on tags...
            //var tags = BuildQueryTags(traceQuery);

            if (!string.IsNullOrEmpty(traceQuery.ServiceName))
            {
                sql += " TraceId IN (SELECT s.traceid FROM Spans s JOIN Tags t ON s.SpanId = t.SpanId WHERE t.[Key] = 'service.name' AND t.Value = @ServiceName)";
            }

            sql += " GROUP BY TraceId"
                   + " ORDER BY starttimestamp DESC";

            var traces = new List <Trace>();

            using (var conn = await GetConnectionAsync())
                using (var cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("Limit", traceQuery.Limit);

                    if (traceQuery.StartTimestamp.HasValue)
                    {
                        cmd.Parameters.AddWithValue("StartTimestamp", traceQuery.StartTimestamp.Value);
                    }

                    if (traceQuery.FinishTimestamp.HasValue)
                    {
                        cmd.Parameters.AddWithValue("FinishTimestamp", traceQuery.FinishTimestamp.Value);
                    }

                    if (!string.IsNullOrEmpty(traceQuery.ServiceName))
                    {
                        cmd.Parameters.AddWithValue("ServiceName", traceQuery.ServiceName);
                    }

                    using (var reader = await cmd.ExecuteReaderAsync())
                    {
                        while (await reader.ReadAsync())
                        {
                            var traceId = reader.GetString(0);

                            var trace = await GetTrace(traceId);

                            traces.Add(trace);
                        }
                    }
                    return(traces);
                }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Checks for the floor or ceiling whilst in the air.
        /// </summary>
        private void CheckForGroundInAir()
        {
            if (!_falling)
            {
                return;
            }

            var position = _player.Position;
            var size     = _player.Size;

            double ceilingHeight, groundHeight;
            double halfHeight = (size.Y / 2.0);
            double footHeight = position.Y + halfHeight;

            // length of C/D sensors
            const double sensorLength = 16.0;

            // A sensor
            var start = new Point(position.X - 7.0, position.Y);
            var end   = new Point(position.X - 7.0, footHeight + sensorLength);
            var tq    = new TraceQuery
            {
                Line          = new Line(start, end),
                CollisionPath = _player.CollisionPath,
                Ignore        = _player,
                Options       = TraceLineOptions.SolidOnly
            };
            var trA = _collisionService.TraceLine(tq);

            groundHeight = trA.Hit ? trA.ContactPoint.Y : Double.MaxValue;

            // B sensor
            start = new Point(position.X + 7.0, position.Y);
            end   = new Point(position.X + 7.0, footHeight + sensorLength);
            tq    = new TraceQuery
            {
                Line          = new Line(start, end),
                CollisionPath = _player.CollisionPath,
                Ignore        = _player,
                Options       = TraceLineOptions.SolidOnly
            };
            var trB = _collisionService.TraceLine(tq);

            groundHeight = Math.Min(groundHeight, trB.Hit ? trB.ContactPoint.Y : Double.MaxValue);

            if (trA.Hit || trB.Hit)
            {
                if (_ysp > 0.0)
                {
                    if (groundHeight - position.Y < halfHeight)
                    {
                        // reaquired the ground

                        // get the ground angle
                        CalculateGroundAngle(trA, trB, PlayerMovementMode.Floor);
                        SetMovementMode();
                        _falling = false;
                        _jumping = false;

                        if ((_controlState & ControllerState.Down) == ControllerState.None)
                        {
                            Unroll();
                        }
                        else if ((_groundAngle != 0.0) || (Math.Abs(_xsp) > 1.03125))
                        {
                            if (RollSound != 0)
                            {
                                _audioService.PlaySoundEffect(RollSound);
                            }
                        }

                        CalculateLandingSpeed();
                    }
                }
            }

            // C sensor
            start = new Point(position.X - 7.0, position.Y);
            end   = new Point(position.X - 7.0, position.Y - halfHeight - sensorLength);
            tq    = new TraceQuery
            {
                Line          = new Line(start, end),
                CollisionPath = _player.CollisionPath,
                Options       = TraceLineOptions.IgnoreJumpThrough | TraceLineOptions.SolidOnly,
                Ignore        = _player
            };
            var trC = _collisionService.TraceLine(tq);

            ceilingHeight = trC.ContactPoint.Y;

            // D sensor
            start = new Point(position.X + 7.0, position.Y);
            end   = new Point(position.X + 7.0, position.Y - halfHeight - sensorLength);
            tq    = new TraceQuery
            {
                Line          = new Line(start, end),
                CollisionPath = _player.CollisionPath,
                Options       = TraceLineOptions.IgnoreJumpThrough | TraceLineOptions.SolidOnly,
                Ignore        = _player
            };
            var trD = _collisionService.TraceLine(tq);

            ceilingHeight = Math.Max(ceilingHeight, trD.ContactPoint.Y);

            if (trC.Hit || trD.Hit)
            {
                if (position.Y - ceilingHeight < halfHeight)
                {
                    _player.Position = new Point(position.X, ceilingHeight + halfHeight);
                    _ysp             = Math.Max(_ysp, 0.0);
                }
            }
        }
Exemplo n.º 28
0
 private Func <QueryContainerDescriptor <Span>, QueryContainer> BuildTracesQuery(TraceQuery traceQuery)
 {
     return(query => query.Bool(b => b.Must(BuildMustQuery(traceQuery))));
 }
Exemplo n.º 29
0
        private IEnumerable <Func <QueryContainerDescriptor <Span>, QueryContainer> > BuildMustQuery(TraceQuery traceQuery)
        {
            if (traceQuery.StartTimestamp != null)
            {
                yield return(q => q.DateRange(d => d.Field(x => x.StartTimestamp).GreaterThanOrEquals(traceQuery.StartTimestamp.Value.DateTime)));
            }

            if (traceQuery.FinishTimestamp != null)
            {
                yield return(q => q.DateRange(d => d.Field(x => x.FinishTimestamp).LessThanOrEquals(traceQuery.FinishTimestamp.Value.DateTime)));
            }

            foreach (var queryTag in BuildQueryTags(traceQuery))
            {
                yield return(q => q.Nested(n => n.Path(x => x.Tags).Query(q1 => q1.Bool(b => b.Must(f => f.Term(new Field("tags.key"), queryTag.Key?.ToLower()), f => f.Term(new Field("tags.value"), queryTag.Value?.ToLower()))))));
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Performs a jump.
        /// </summary>
        private void Jump()
        {
            if (_falling)
            {
                // cant jump whilst in the air
                return;
            }

            var position = _player.Position;
            var size     = _player.Size;

            _jumping = true;

            double deltaX, deltaY;

            switch (_movementMode)
            {
            case PlayerMovementMode.Floor:
                deltaX = 0.0;
                deltaY = -((size.Y / 2) + 5.0);
                break;

            case PlayerMovementMode.Ceiling:
                deltaX = 0.0;
                deltaY = ((size.Y / 2) + 5.0);
                break;

            case PlayerMovementMode.RightWall:
                deltaX = -((size.Y / 2) + 5.0);
                deltaY = 0.0;
                break;

            case PlayerMovementMode.LeftWall:
                deltaX = ((size.Y / 2) + 5.0);
                deltaY = 0.0;
                break;

            default:
                deltaX = 0.0;
                deltaY = 0.0;
                break;
            }

            var tq = new TraceQuery
            {
                Line          = new Line(position.X, position.Y, position.X + deltaX, position.Y + deltaY),
                CollisionPath = _player.CollisionPath,
                Options       = TraceLineOptions.IgnoreJumpThrough | TraceLineOptions.SolidOnly,
                Ignore        = _player
            };
            var tr = _collisionService.TraceLine(tq);

            if (tr.Hit)
            {
                // relative ceiling too low, nowhere to jump
                return;
            }

            _movementMode = PlayerMovementMode.Floor;
            _falling      = true;
            _rolling      = true;
            _player.SetBoundingBox(Player.RollingBox);

            var rad = _groundAngle * (Math.PI / 180.0);

            _xsp -= JumpSpeed * -Math.Sin(rad);
            _ysp -= JumpSpeed * -Math.Cos(rad);

            if (_ysp < JumpSpeed)
            {
                _ysp = JumpSpeed;
            }

            if (JumpSound != 0)
            {
                _audioService.PlaySoundEffect(JumpSound);
            }
        }