< Summary

Class:Itinero.Routes.Builders.RouteBuilder
Assembly:Itinero
File(s):/home/runner/work/routing2/routing2/src/Itinero/Routes/Builders/RouteBuilder.cs
Covered lines:128
Uncovered lines:9
Coverable lines:137
Total lines:236
Line coverage:93.4% (128 of 137)
Covered branches:33
Total branches:36
Branch coverage:91.6% (33 of 36)
Tag:284_38118444584

Metrics

MethodBranch coverage Cyclomatic complexity Line coverage
.cctor()100%1100%
get_Default()100%1100%
.ctor(...)100%1100%
Build(...)90.62%3291.74%
AddBranches(...)100%4100%

File(s)

/home/runner/work/routing2/routing2/src/Itinero/Routes/Builders/RouteBuilder.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Threading;
 5using Itinero.Network;
 6using Itinero.Network.Enumerators.Edges;
 7using Itinero.Profiles;
 8using Itinero.Routes.Paths;
 9
 10namespace Itinero.Routes.Builders;
 11
 12/// <summary>
 13///     Default route builder implementation.
 14/// </summary>
 15public class RouteBuilder : IRouteBuilder
 16{
 17    private readonly Func<IEnumerable<(string, string)>, bool, double, RoutingNetworkEdgeEnumerator, IEnumerable<(string
 2318    private static readonly ThreadLocal<RouteBuilder> DefaultLazy = new(() => new RouteBuilder());
 19
 20    /// <summary>
 21    ///     Gets the default instance (for the local thread).
 22    /// </summary>
 1170623    public static RouteBuilder Default => DefaultLazy.Value;
 24
 25    /// <summary>
 26    /// </summary>
 27    /// <param name="calculateExtraAttributes">
 28    /// If this callback is given, it will be executed on every segment to inject extra attributes into the ShapeMeta.
 29    /// The parameters are:
 30    /// - attributes:be a reference to the attributes which the edgeEnumerator gave
 31    /// - direction: if we are travelling in forward direction over the edge
 32    /// - distance: the length we are travelling on the edge
 33    /// - edgeEnumerator: the current edgeEnumerator
 34    /// </param>
 2235    public RouteBuilder(Func<IEnumerable<(string, string)>, bool, double, RoutingNetworkEdgeEnumerator, IEnumerable<(str
 2236    {
 2237        _calculateExtraAttributes = calculateExtraAttributes;
 2238    }
 39
 40    /// <inheritdoc />
 41    public Result<Route> Build(RoutingNetwork routingNetwork, Profile profile, Path path)
 5642    {
 5643        var edgeEnumerator = routingNetwork.GetEdgeEnumerator();
 5644        var profileCached = routingNetwork.GetCachedProfile(profile);
 45
 46        // SpareEnumerator is used in the branch-calculation. IT offers no guarantees about the state
 5647        var spareEnumerator = routingNetwork.GetEdgeEnumerator();
 5648        var route = new Route { Profile = profile.Name };
 5649        var branches = new List<Route.Branch>();
 5650        var seenEdges = 0;
 51
 5652        var allEdgeIds = new HashSet<EdgeId>();
 143653        foreach (var edge in path)
 63454        {
 63455            allEdgeIds.Add(edge.edge);
 63456        }
 57
 143658        foreach (var (edge, direction, offset1, offset2) in path)
 63459        {
 63460            if (route.Shape.Count == 0)
 5661            {
 62                // This is the first edge of the route - we have to check for branches at the start loction
 63                bool firstEdgeIsFullyContained;
 5664                if (direction)
 4165                {
 66                    // Forward: we look to offset1
 4167                    firstEdgeIsFullyContained = offset1 == 0;
 4168                }
 69                else
 1570                {
 1571                    firstEdgeIsFullyContained = offset2 == ushort.MaxValue;
 1572                }
 73
 5674                if (firstEdgeIsFullyContained)
 4075                {
 76                    // We check for branches
 4077                    edgeEnumerator.MoveTo(edge, direction);
 4078                    this.AddBranches(edgeEnumerator.Tail, edgeEnumerator, spareEnumerator, 0, branches, allEdgeIds);
 4079                }
 5680            }
 81
 63482            edgeEnumerator.MoveTo(edge, direction);
 83
 63484            var attributes = edgeEnumerator.Attributes;
 63485            var factor = profileCached.Factor(edgeEnumerator);
 63486            var distance = edgeEnumerator.EdgeLength();
 63487            distance = (offset2 - offset1) / (double)ushort.MaxValue * distance;
 63488            route.TotalDistance += distance;
 89
 63490            if (_calculateExtraAttributes != null)
 091            {
 092                attributes = attributes.Concat(_calculateExtraAttributes(attributes, direction, distance, edgeEnumerator
 093            }
 63494            var speed = factor.ForwardSpeedMeterPerSecond;
 63495            if (speed <= 0)
 096            {
 097                speed = 10;
 98                // Something is wrong here
 99                // throw new ArgumentException("Speed is zero! Route is not possible with the given profile.");
 0100            }
 101
 634102            var time = distance / speed;
 634103            route.TotalTime += time;
 104
 105
 106            // add shape points to route.
 634107            using var shapeBetween = edgeEnumerator.GetShapeBetween(offset1, offset2).GetEnumerator();
 108            // skip first coordinate if there are already previous edges.
 634109            if (route.Shape.Count > 0 && offset1 == 0)
 578110            {
 578111                shapeBetween.MoveNext();
 578112            }
 113
 114
 2228115            while (shapeBetween.MoveNext())
 1594116            {
 1594117                route.Shape.Add(shapeBetween.Current);
 1594118            }
 119
 634120            if (route.Shape.Count == 0)
 0121            {
 0122                route.Shape.Add(edgeEnumerator.LocationOnEdge(offset2));
 0123            }
 124
 634125            if (offset1 != 0 ||
 634126                offset2 != ushort.MaxValue)
 43127            {
 43128                attributes = attributes.Concat(new (string key, string value)[]
 43129                {
 43130                        ("_segment_offset1",
 43131                            (offset1 / (double)ushort.MaxValue).ToString(System.Globalization.CultureInfo
 43132                                .InvariantCulture)),
 43133                        ("_segment_offset2",
 43134                            (offset2 / (double)ushort.MaxValue).ToString(System.Globalization.CultureInfo
 43135                                .InvariantCulture)),
 43136                });
 43137            }
 138
 634139            attributes = attributes.Concat(new (string key, string value)[]
 634140            {
 634141                    ("_segment_forward", direction.ToString())
 634142            });
 143
 634144            route.ShapeMeta.Add(new Route.Meta
 634145            {
 634146                Shape = route.Shape.Count - 1,
 634147                Attributes = attributes,
 634148                AttributesAreForward = direction,
 634149                Distance = distance,
 634150                Profile = profile.Name,
 634151                Time = time
 634152            });
 153
 154            // Intermediate points of an edge will never have branches
 155            // So, to calculate branches, it is enough to only look at the last point of the edge
 156            // (and the first point of the first edge - a true edge case)
 157            // (Also note that the first and last edge might not be needed entirely, so that means we possible can ignor
 158
 159            // What is the end vertex? Add its branches...
 634160            if (seenEdges + 1 == path.Count)
 56161            {
 162                // Hmm, this is the last edge
 163                // We should add the branches of it, but only if the edge is completely contained
 164                bool lastEdgeIsFullyContained;
 56165                if (!direction)
 12166                {
 167                    // Backward: we look to offset1
 12168                    lastEdgeIsFullyContained = offset1 == 0;
 12169                }
 170                else
 44171                {
 44172                    lastEdgeIsFullyContained = offset2 == ushort.MaxValue;
 44173                }
 174
 56175                if (lastEdgeIsFullyContained)
 34176                {
 34177                    this.AddBranches(edgeEnumerator.Head,
 34178                        edgeEnumerator, spareEnumerator, route.Shape.Count - 1, branches, allEdgeIds);
 34179                }
 56180            }
 181            else
 578182            {
 578183                this.AddBranches(edgeEnumerator.Head, edgeEnumerator, spareEnumerator, route.Shape.Count - 1, branches,
 578184                    allEdgeIds);
 578185            }
 186
 634187            seenEdges++;
 634188        }
 189
 56190        route.Branches = branches.ToArray();
 191
 56192        return route;
 56193    }
 194
 195    /// <summary>
 196    ///     Calculate all the branches of 'centralVertexid'
 197    /// </summary>
 198    /// <param name="edgeEnumerator">The edge enumerator, moved to the point of which the branches should be added</para
 199    /// <param name="spareEnumerator">An extra enumerator to use. Will be moved during the call</param>
 200    /// <param name="centralVertexId">The vertex id of the point under consideration</param>
 201    /// <param name="shapeIndex">The index of the shape of the current vertex</param>
 202    /// <param name="addTo">All the branches are collected into this collection</param>
 203    /// <param name="branchBlacklist">Edges in this list won't be used as branches</param>
 204    private void AddBranches(VertexId centralVertexId, RoutingNetworkEdgeEnumerator edgeEnumerator,
 205        RoutingNetworkEdgeEnumerator spareEnumerator, int shapeIndex,
 206        ICollection<Route.Branch> addTo, HashSet<EdgeId> branchBlacklist)
 652207    {
 652208        edgeEnumerator.MoveTo(centralVertexId);
 2614209        while (edgeEnumerator.MoveNext())
 1962210        {
 211            // Iterates over all edges of the endvertex
 212
 1962213            if (branchBlacklist.Contains(edgeEnumerator.EdgeId))
 1247214            {
 215                // We make sure not to pick the current nor the next edge of the path
 216                // This is simple as we have a hashset containing _all_ the edge ids ¯\_(ツ)_/¯
 1247217                continue;
 218            }
 219
 220            // If the vertex of the crossroads are the same as the from, we would walk forward over the branch if we wou
 715221            var isForward = edgeEnumerator.Forward;
 715222            spareEnumerator.MoveTo(edgeEnumerator.EdgeId, isForward);
 715223            using var shapeEnum = spareEnumerator.GetShapeBetween(includeVertices: false).GetEnumerator();
 715224            shapeEnum.MoveNext(); // Init enumerator at first value
 715225            shapeEnum.MoveNext();
 715226            var branch = new Route.Branch
 715227            {
 715228                Attributes = edgeEnumerator.Attributes,
 715229                Shape = shapeIndex,
 715230                AttributesAreForward = isForward,
 715231                Coordinate = shapeEnum.Current
 715232            };
 715233            addTo.Add(branch);
 715234        }
 652235    }
 236}