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

namespace Rcs.Infrastructure.PathFinding.Services;

/// <summary>
/// ๆ‰ซๆŽ ้ข่ฆ†็›–่ต„ๆบๅฑ•ๅผ€ๅ™จ๏ผšๅฐ†่ฝจ่ฟนไธญๅฟƒ็บฟๅ’Œๅค–ๆ‰ฉๅŠๅพ„ๆ˜ ๅฐ„ไธบ่ฆ†็›–็š„่Š‚็‚น/่พน็ผ–็ ้›†ๅˆใ€‚
/// </summary>
public static class SweptAreaCoverageResolver
{
    public const double DefaultWidth = 0.6d;
    public const double DefaultLength = 1.0d;
    public const double DefaultSafetyDistance = 0.1d;

    private const double Epsilon = 1e-6d;
    private const double CurveSamplingStep = 0.2d;
    private const int MinCurveSamples = 8;
    private const int MaxCurveSamples = 128;

    public static RobotSweepDimensions ResolveDimensions(
        double? width,
        double? length,
        double? safetyDistance,
        double coordinateScale)
    {
        var scale = coordinateScale > 0 ? coordinateScale : 1d;

        var useDefaultWidth = !width.HasValue || width.Value <= 0;
        var useDefaultLength = !length.HasValue || length.Value <= 0;
        var useDefaultSafety = !safetyDistance.HasValue || safetyDistance.Value < 0;

        var resolvedWidth = useDefaultWidth ? DefaultWidth * scale : width!.Value;
        var resolvedLength = useDefaultLength ? DefaultLength * scale : length!.Value;
        var resolvedSafety = useDefaultSafety ? DefaultSafetyDistance * scale : safetyDistance!.Value;

        return new RobotSweepDimensions(
            Width: resolvedWidth,
            Length: resolvedLength,
            SafetyDistance: resolvedSafety,
            UseDefaultWidth: useDefaultWidth,
            UseDefaultLength: useDefaultLength,
            UseDefaultSafetyDistance: useDefaultSafety);
    }

    public static double CalculateSweepRadius(double length, double width, double safetyDistance)
    {
        var halfLength = Math.Max(length, 0d) / 2d + Math.Max(safetyDistance, 0d);
        var halfWidth = Math.Max(width, 0d) / 2d + Math.Max(safetyDistance, 0d);
        return Math.Sqrt(halfLength * halfLength + halfWidth * halfWidth);
    }

    public static Dictionary<string, SweepPoint> BuildNodeLookup(MapCacheData mapData)
    {
        return mapData.Nodes
            .Where(n => n.Active && !string.IsNullOrWhiteSpace(n.NodeCode))
            .GroupBy(n => n.NodeCode, StringComparer.OrdinalIgnoreCase)
            .ToDictionary(
                g => g.Key,
                g =>
                {
                    var node = g.First();
                    return new SweepPoint(node.X, node.Y);
                },
                StringComparer.OrdinalIgnoreCase);
    }

    public static Dictionary<string, SweepPoint> BuildNodeLookup(PathGraph graph)
    {
        return graph.Nodes.Values
            .Where(n => n.Active && !string.IsNullOrWhiteSpace(n.NodeCode))
            .GroupBy(n => n.NodeCode, StringComparer.OrdinalIgnoreCase)
            .ToDictionary(
                g => g.Key,
                g =>
                {
                    var node = g.First();
                    return new SweepPoint(node.X, node.Y);
                },
                StringComparer.OrdinalIgnoreCase);
    }

    public static Dictionary<string, List<SweepPoint>> BuildEdgePolylineLookup(PathGraph graph)
    {
        var result = new Dictionary<string, List<SweepPoint>>(StringComparer.OrdinalIgnoreCase);
        foreach (var edge in graph.Edges.Values.Where(e => e.Active && !string.IsNullOrWhiteSpace(e.EdgeCode)))
        {
            if (!graph.Nodes.TryGetValue(edge.FromNodeId, out var fromNode) ||
                !graph.Nodes.TryGetValue(edge.ToNodeId, out var toNode))
            {
                continue;
            }

            var fromPoint = new SweepPoint(fromNode.X, fromNode.Y);
            var toPoint = new SweepPoint(toNode.X, toNode.Y);
            result[edge.EdgeCode] = BuildEdgePolyline(
                edge.CurveType,
                edge.Radius,
                edge.CenterX,
                edge.CenterY,
                edge.ControlPoints,
                edge.Degree,
                edge.Weights,
                edge.Knots,
                fromPoint,
                toPoint);
        }

        return result;
    }

    public static List<SweepPoint> BuildPolylineFromSegments(
        IEnumerable<PathSegmentWithCode> segments,
        IReadOnlyDictionary<string, SweepPoint> nodeLookupByCode,
        IReadOnlyDictionary<string, List<SweepPoint>>? edgePolylineLookupByCode = null)
    {
        var result = new List<SweepPoint>();

        foreach (var segment in segments)
        {
            if (string.IsNullOrWhiteSpace(segment.FromNodeCode) || string.IsNullOrWhiteSpace(segment.ToNodeCode))
            {
                continue;
            }

            if (!nodeLookupByCode.TryGetValue(segment.FromNodeCode, out var fromPoint) ||
                !nodeLookupByCode.TryGetValue(segment.ToNodeCode, out var toPoint))
            {
                continue;
            }

            List<SweepPoint> segmentPolyline;
            if (edgePolylineLookupByCode != null &&
                !string.IsNullOrWhiteSpace(segment.EdgeCode) &&
                edgePolylineLookupByCode.TryGetValue(segment.EdgeCode, out var edgePolyline) &&
                edgePolyline.Count > 0)
            {
                segmentPolyline = EnsureEdgePolylineEndpoints(edgePolyline, fromPoint, toPoint);
            }
            else
            {
                segmentPolyline = new List<SweepPoint> { fromPoint, toPoint };
            }

            AppendPolyline(result, segmentPolyline);
        }

        return result;
    }

    public static SweptAreaCoverageResult ExpandFromMap(
        MapCacheData mapData,
        IReadOnlyList<SweepPoint> centerLine,
        double radius)
    {
        var result = new SweptAreaCoverageResult();
        if (mapData.Nodes.Count == 0 || centerLine.Count == 0 || radius < 0)
        {
            return result;
        }

        var nodeById = mapData.Nodes
            .Where(n => n.Active)
            .ToDictionary(n => n.NodeId);

        foreach (var node in nodeById.Values)
        {
            if (string.IsNullOrWhiteSpace(node.NodeCode))
            {
                continue;
            }

            if (DistancePointToPolyline(node.X, node.Y, centerLine) <= radius + Epsilon)
            {
                result.NodeCodes.Add(node.NodeCode);
            }
        }

        foreach (var edge in mapData.Edges.Where(e => e.Active && !string.IsNullOrWhiteSpace(e.EdgeCode)))
        {
            if (!nodeById.TryGetValue(edge.FromNode, out var fromNode) ||
                !nodeById.TryGetValue(edge.ToNode, out var toNode))
            {
                continue;
            }

            var edgePolyline = BuildEdgePolyline(
                edge.CurveType,
                edge.Radius,
                edge.CenterX,
                edge.CenterY,
                edge.ControlPoints,
                edge.Degree,
                edge.Weights,
                edge.Knots,
                new SweepPoint(fromNode.X, fromNode.Y),
                new SweepPoint(toNode.X, toNode.Y));

            var distance = DistancePolylineToPolyline(edgePolyline, centerLine);
            if (distance <= radius + Epsilon)
            {
                result.EdgeCodes.Add(edge.EdgeCode);
            }
        }

        return result;
    }

    public static SweptAreaCoverageResult ExpandFromGraph(
        PathGraph graph,
        IReadOnlyList<SweepPoint> centerLine,
        double radius)
    {
        var result = new SweptAreaCoverageResult();
        if (graph.Nodes.Count == 0 || centerLine.Count == 0 || radius < 0)
        {
            return result;
        }

        foreach (var node in graph.Nodes.Values.Where(n => n.Active && !string.IsNullOrWhiteSpace(n.NodeCode)))
        {
            if (DistancePointToPolyline(node.X, node.Y, centerLine) <= radius + Epsilon)
            {
                result.NodeCodes.Add(node.NodeCode);
            }
        }

        foreach (var edge in graph.Edges.Values.Where(e => e.Active && !string.IsNullOrWhiteSpace(e.EdgeCode)))
        {
            if (!graph.Nodes.TryGetValue(edge.FromNodeId, out var fromNode) ||
                !graph.Nodes.TryGetValue(edge.ToNodeId, out var toNode))
            {
                continue;
            }

            var edgePolyline = BuildEdgePolyline(
                edge.CurveType,
                edge.Radius,
                edge.CenterX,
                edge.CenterY,
                edge.ControlPoints,
                edge.Degree,
                edge.Weights,
                edge.Knots,
                new SweepPoint(fromNode.X, fromNode.Y),
                new SweepPoint(toNode.X, toNode.Y));

            var distance = DistancePolylineToPolyline(edgePolyline, centerLine);
            if (distance <= radius + Epsilon)
            {
                result.EdgeCodes.Add(edge.EdgeCode);
            }
        }

        return result;
    }

    private static List<SweepPoint> BuildEdgePolyline(
        MapEdgeCurveType curveType,
        double? radius,
        double? centerX,
        double? centerY,
        IReadOnlyList<PointCache>? controlPoints,
        int? degree,
        IReadOnlyList<double>? weights,
        IReadOnlyList<double>? knots,
        SweepPoint fromPoint,
        SweepPoint toPoint)
    {
        if (curveType == MapEdgeCurveType.Straight)
        {
            return new List<SweepPoint> { fromPoint, toPoint };
        }

        if (curveType == MapEdgeCurveType.Arc &&
            TrySampleArc(fromPoint, toPoint, radius, centerX, centerY, out var arcPoints))
        {
            return arcPoints;
        }

        if (controlPoints == null || controlPoints.Count < 2)
        {
            return new List<SweepPoint> { fromPoint, toPoint };
        }

        if (TrySampleNurbs(controlPoints, degree, weights, knots, out var nurbsPoints))
        {
            return EnsureEdgePolylineEndpoints(nurbsPoints, fromPoint, toPoint);
        }

        if (TrySampleRationalBezier(controlPoints, weights, out var rationalBezierPoints))
        {
            return EnsureEdgePolylineEndpoints(rationalBezierPoints, fromPoint, toPoint);
        }

        if (TrySampleBezier(controlPoints, out var bezierPoints))
        {
            return EnsureEdgePolylineEndpoints(bezierPoints, fromPoint, toPoint);
        }

        var fallback = controlPoints.Select(p => new SweepPoint(p.X, p.Y)).ToList();
        return EnsureEdgePolylineEndpoints(fallback, fromPoint, toPoint);
    }

    private static bool TrySampleArc(
        SweepPoint fromPoint,
        SweepPoint toPoint,
        double? radius,
        double? centerX,
        double? centerY,
        out List<SweepPoint> points)
    {
        points = new List<SweepPoint>();
        if (!centerX.HasValue || !centerY.HasValue)
        {
            return false;
        }

        var cx = centerX.Value;
        var cy = centerY.Value;
        var r = radius.GetValueOrDefault();
        if (r <= Epsilon)
        {
            r = DistancePointToPoint(fromPoint.X, fromPoint.Y, cx, cy);
        }

        if (r <= Epsilon)
        {
            return false;
        }

        var startAngle = Math.Atan2(fromPoint.Y - cy, fromPoint.X - cx);
        var endAngle = Math.Atan2(toPoint.Y - cy, toPoint.X - cx);
        var cross = (fromPoint.X - cx) * (toPoint.Y - cy) - (fromPoint.Y - cy) * (toPoint.X - cx);

        double delta;
        if (cross >= 0)
        {
            delta = NormalizePositiveAngle(endAngle - startAngle);
        }
        else
        {
            delta = -NormalizePositiveAngle(startAngle - endAngle);
        }

        var arcLength = Math.Abs(delta) * r;
        var sampleCount = Math.Clamp((int)Math.Ceiling(arcLength / CurveSamplingStep), MinCurveSamples, MaxCurveSamples);
        points = new List<SweepPoint>(sampleCount + 1);
        for (var i = 0; i <= sampleCount; i++)
        {
            var t = i / (double)sampleCount;
            var angle = startAngle + delta * t;
            points.Add(new SweepPoint(cx + r * Math.Cos(angle), cy + r * Math.Sin(angle)));
        }

        points[0] = fromPoint;
        points[^1] = toPoint;
        return true;
    }

    private static double NormalizePositiveAngle(double angle)
    {
        var twoPi = Math.PI * 2d;
        var normalized = angle % twoPi;
        if (normalized < 0)
        {
            normalized += twoPi;
        }

        return normalized;
    }

    private static bool TrySampleBezier(IReadOnlyList<PointCache> controlPoints, out List<SweepPoint> points)
    {
        points = new List<SweepPoint>();
        if (controlPoints.Count < 2)
        {
            return false;
        }

        var cps = controlPoints.Select(p => new SweepPoint(p.X, p.Y)).ToList();
        var sampleCount = ResolveSampleCount(cps);
        points = new List<SweepPoint>(sampleCount + 1);

        for (var i = 0; i <= sampleCount; i++)
        {
            var t = i / (double)sampleCount;
            points.Add(EvaluateBezier(cps, t));
        }

        return points.Count >= 2;
    }

    private static bool TrySampleRationalBezier(
        IReadOnlyList<PointCache> controlPoints,
        IReadOnlyList<double>? weights,
        out List<SweepPoint> points)
    {
        points = new List<SweepPoint>();
        if (controlPoints.Count < 2 || weights == null || weights.Count != controlPoints.Count)
        {
            return false;
        }

        var cps = controlPoints.Select(p => new SweepPoint(p.X, p.Y)).ToList();
        var sampleCount = ResolveSampleCount(cps);
        points = new List<SweepPoint>(sampleCount + 1);
        var n = cps.Count - 1;

        for (var i = 0; i <= sampleCount; i++)
        {
            var t = i / (double)sampleCount;
            double numeratorX = 0d;
            double numeratorY = 0d;
            double denominator = 0d;

            for (var j = 0; j <= n; j++)
            {
                var basis = Bernstein(n, j, t);
                var weightedBasis = basis * weights[j];
                numeratorX += weightedBasis * cps[j].X;
                numeratorY += weightedBasis * cps[j].Y;
                denominator += weightedBasis;
            }

            if (Math.Abs(denominator) <= Epsilon)
            {
                return false;
            }

            points.Add(new SweepPoint(numeratorX / denominator, numeratorY / denominator));
        }

        return points.Count >= 2;
    }

    private static bool TrySampleNurbs(
        IReadOnlyList<PointCache> controlPoints,
        int? degree,
        IReadOnlyList<double>? weights,
        IReadOnlyList<double>? knots,
        out List<SweepPoint> points)
    {
        points = new List<SweepPoint>();

        if (controlPoints.Count < 2 || knots == null || knots.Count == 0)
        {
            return false;
        }

        var n = controlPoints.Count - 1;
        var p = Math.Clamp(degree ?? Math.Min(3, n), 1, n);
        var expectedKnotCount = n + p + 2;
        if (knots.Count != expectedKnotCount)
        {
            return false;
        }

        var curveWeights = weights != null && weights.Count == controlPoints.Count
            ? weights.ToArray()
            : Enumerable.Repeat(1d, controlPoints.Count).ToArray();

        var uStart = knots[p];
        var uEnd = knots[n + 1];
        if (uEnd - uStart <= Epsilon)
        {
            return false;
        }

        var cps = controlPoints.Select(cp => new SweepPoint(cp.X, cp.Y)).ToArray();
        var sampleCount = ResolveSampleCount(cps);
        points = new List<SweepPoint>(sampleCount + 1);

        for (var i = 0; i <= sampleCount; i++)
        {
            var u = i == sampleCount
                ? uEnd - Epsilon
                : uStart + (uEnd - uStart) * i / sampleCount;

            if (!TryEvaluateNurbsPoint(cps, curveWeights, knots, p, u, out var point))
            {
                return false;
            }

            points.Add(point);
        }

        return points.Count >= 2;
    }

    private static bool TryEvaluateNurbsPoint(
        IReadOnlyList<SweepPoint> controlPoints,
        IReadOnlyList<double> weights,
        IReadOnlyList<double> knots,
        int degree,
        double u,
        out SweepPoint point)
    {
        point = default;
        var n = controlPoints.Count - 1;
        var span = FindKnotSpan(n, degree, u, knots);
        if (span < degree || span > n)
        {
            return false;
        }

        var d = new (double Xw, double Yw, double W)[degree + 1];
        for (var j = 0; j <= degree; j++)
        {
            var idx = span - degree + j;
            var weight = weights[idx];
            d[j] = (controlPoints[idx].X * weight, controlPoints[idx].Y * weight, weight);
        }

        for (var r = 1; r <= degree; r++)
        {
            for (var j = degree; j >= r; j--)
            {
                var i = span - degree + j;
                var left = knots[i];
                var right = knots[i + degree - r + 1];
                var denominator = right - left;
                var alpha = Math.Abs(denominator) <= Epsilon ? 0d : (u - left) / denominator;

                d[j] = (
                    (1d - alpha) * d[j - 1].Xw + alpha * d[j].Xw,
                    (1d - alpha) * d[j - 1].Yw + alpha * d[j].Yw,
                    (1d - alpha) * d[j - 1].W + alpha * d[j].W);
            }
        }

        var final = d[degree];
        if (Math.Abs(final.W) <= Epsilon)
        {
            return false;
        }

        point = new SweepPoint(final.Xw / final.W, final.Yw / final.W);
        return true;
    }

    private static int FindKnotSpan(int n, int degree, double u, IReadOnlyList<double> knots)
    {
        if (u >= knots[n + 1] - Epsilon)
        {
            return n;
        }

        if (u <= knots[degree] + Epsilon)
        {
            return degree;
        }

        var low = degree;
        var high = n + 1;
        var mid = (low + high) / 2;

        while (u < knots[mid] || u >= knots[mid + 1])
        {
            if (u < knots[mid])
            {
                high = mid;
            }
            else
            {
                low = mid;
            }

            mid = (low + high) / 2;
        }

        return mid;
    }

    private static List<SweepPoint> EnsureEdgePolylineEndpoints(
        IReadOnlyList<SweepPoint> polyline,
        SweepPoint fromPoint,
        SweepPoint toPoint)
    {
        if (polyline.Count == 0)
        {
            return new List<SweepPoint> { fromPoint, toPoint };
        }

        var result = polyline.ToList();
        if (result.Count == 1)
        {
            if (!ArePointsEqual(result[0], fromPoint))
            {
                result.Insert(0, fromPoint);
            }

            if (!ArePointsEqual(result[^1], toPoint))
            {
                result.Add(toPoint);
            }

            return result;
        }

        result[0] = fromPoint;
        result[^1] = toPoint;
        return result;
    }

    private static int ResolveSampleCount(IReadOnlyList<SweepPoint> points)
    {
        var length = 0d;
        for (var i = 1; i < points.Count; i++)
        {
            length += DistancePointToPoint(points[i - 1].X, points[i - 1].Y, points[i].X, points[i].Y);
        }

        if (length <= Epsilon)
        {
            return MinCurveSamples;
        }

        var samples = (int)Math.Ceiling(length / CurveSamplingStep);
        return Math.Clamp(samples, MinCurveSamples, MaxCurveSamples);
    }

    private static SweepPoint EvaluateBezier(IReadOnlyList<SweepPoint> controlPoints, double t)
    {
        var work = controlPoints.ToArray();
        for (var r = 1; r < work.Length; r++)
        {
            for (var i = 0; i < work.Length - r; i++)
            {
                work[i] = new SweepPoint(
                    (1d - t) * work[i].X + t * work[i + 1].X,
                    (1d - t) * work[i].Y + t * work[i + 1].Y);
            }
        }

        return work[0];
    }

    private static double Bernstein(int n, int i, double t)
    {
        var coefficient = BinomialCoefficient(n, i);
        return coefficient * Math.Pow(t, i) * Math.Pow(1d - t, n - i);
    }

    private static double BinomialCoefficient(int n, int k)
    {
        if (k < 0 || k > n)
        {
            return 0d;
        }

        if (k == 0 || k == n)
        {
            return 1d;
        }

        k = Math.Min(k, n - k);
        var result = 1d;
        for (var i = 1; i <= k; i++)
        {
            result *= (n - (k - i));
            result /= i;
        }

        return result;
    }

    private static void AppendPolyline(List<SweepPoint> target, IReadOnlyList<SweepPoint> source)
    {
        if (source.Count == 0)
        {
            return;
        }

        if (target.Count == 0)
        {
            target.AddRange(source);
            return;
        }

        var startIndex = ArePointsEqual(target[^1], source[0]) ? 1 : 0;
        for (var i = startIndex; i < source.Count; i++)
        {
            target.Add(source[i]);
        }
    }

    private static bool ArePointsEqual(SweepPoint a, SweepPoint b)
    {
        return Math.Abs(a.X - b.X) <= Epsilon && Math.Abs(a.Y - b.Y) <= Epsilon;
    }

    private static double DistancePointToPolyline(double x, double y, IReadOnlyList<SweepPoint> polyline)
    {
        if (polyline.Count == 0)
        {
            return double.MaxValue;
        }

        if (polyline.Count == 1)
        {
            var point = polyline[0];
            return DistancePointToPoint(x, y, point.X, point.Y);
        }

        var minDistance = double.MaxValue;
        for (var i = 1; i < polyline.Count; i++)
        {
            var p1 = polyline[i - 1];
            var p2 = polyline[i];
            var distance = DistancePointToSegment(x, y, p1.X, p1.Y, p2.X, p2.Y);
            if (distance < minDistance)
            {
                minDistance = distance;
            }
        }

        return minDistance;
    }

    private static double DistancePolylineToPolyline(
        IReadOnlyList<SweepPoint> polylineA,
        IReadOnlyList<SweepPoint> polylineB)
    {
        if (polylineA.Count == 0 || polylineB.Count == 0)
        {
            return double.MaxValue;
        }

        if (polylineA.Count == 1)
        {
            var p = polylineA[0];
            return DistancePointToPolyline(p.X, p.Y, polylineB);
        }

        if (polylineB.Count == 1)
        {
            var p = polylineB[0];
            return DistancePointToPolyline(p.X, p.Y, polylineA);
        }

        var minDistance = double.MaxValue;
        for (var i = 1; i < polylineA.Count; i++)
        {
            var a1 = polylineA[i - 1];
            var a2 = polylineA[i];

            for (var j = 1; j < polylineB.Count; j++)
            {
                var b1 = polylineB[j - 1];
                var b2 = polylineB[j];
                var distance = DistanceSegmentToSegment(a1.X, a1.Y, a2.X, a2.Y, b1.X, b1.Y, b2.X, b2.Y);
                if (distance < minDistance)
                {
                    minDistance = distance;
                }
            }
        }

        return minDistance;
    }

    private static double DistanceSegmentToSegment(
        double ax1,
        double ay1,
        double ax2,
        double ay2,
        double bx1,
        double by1,
        double bx2,
        double by2)
    {
        if (SegmentsIntersect(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2))
        {
            return 0d;
        }

        var d1 = DistancePointToSegment(ax1, ay1, bx1, by1, bx2, by2);
        var d2 = DistancePointToSegment(ax2, ay2, bx1, by1, bx2, by2);
        var d3 = DistancePointToSegment(bx1, by1, ax1, ay1, ax2, ay2);
        var d4 = DistancePointToSegment(bx2, by2, ax1, ay1, ax2, ay2);

        return Math.Min(Math.Min(d1, d2), Math.Min(d3, d4));
    }

    private static bool SegmentsIntersect(
        double ax1,
        double ay1,
        double ax2,
        double ay2,
        double bx1,
        double by1,
        double bx2,
        double by2)
    {
        var o1 = Orientation(ax1, ay1, ax2, ay2, bx1, by1);
        var o2 = Orientation(ax1, ay1, ax2, ay2, bx2, by2);
        var o3 = Orientation(bx1, by1, bx2, by2, ax1, ay1);
        var o4 = Orientation(bx1, by1, bx2, by2, ax2, ay2);

        if (o1 * o2 < 0 && o3 * o4 < 0)
        {
            return true;
        }

        if (Math.Abs(o1) <= Epsilon && IsPointOnSegment(bx1, by1, ax1, ay1, ax2, ay2)) return true;
        if (Math.Abs(o2) <= Epsilon && IsPointOnSegment(bx2, by2, ax1, ay1, ax2, ay2)) return true;
        if (Math.Abs(o3) <= Epsilon && IsPointOnSegment(ax1, ay1, bx1, by1, bx2, by2)) return true;
        if (Math.Abs(o4) <= Epsilon && IsPointOnSegment(ax2, ay2, bx1, by1, bx2, by2)) return true;

        return false;
    }

    private static double Orientation(
        double ax,
        double ay,
        double bx,
        double by,
        double cx,
        double cy)
    {
        return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
    }

    private static bool IsPointOnSegment(
        double px,
        double py,
        double x1,
        double y1,
        double x2,
        double y2)
    {
        if (Math.Abs(Orientation(x1, y1, x2, y2, px, py)) > Epsilon)
        {
            return false;
        }

        var minX = Math.Min(x1, x2) - Epsilon;
        var maxX = Math.Max(x1, x2) + Epsilon;
        var minY = Math.Min(y1, y2) - Epsilon;
        var maxY = Math.Max(y1, y2) + Epsilon;
        return px >= minX && px <= maxX && py >= minY && py <= maxY;
    }

    private static double DistancePointToSegment(
        double px,
        double py,
        double x1,
        double y1,
        double x2,
        double y2)
    {
        var dx = x2 - x1;
        var dy = y2 - y1;
        if (Math.Abs(dx) < Epsilon && Math.Abs(dy) < Epsilon)
        {
            return DistancePointToPoint(px, py, x1, y1);
        }

        var t = ((px - x1) * dx + (py - y1) * dy) / (dx * dx + dy * dy);
        t = Math.Clamp(t, 0d, 1d);
        var projectionX = x1 + t * dx;
        var projectionY = y1 + t * dy;
        return DistancePointToPoint(px, py, projectionX, projectionY);
    }

    private static double DistancePointToPoint(double x1, double y1, double x2, double y2)
    {
        var dx = x1 - x2;
        var dy = y1 - y2;
        return Math.Sqrt(dx * dx + dy * dy);
    }
}

public readonly record struct SweepPoint(double X, double Y);

public readonly record struct RobotSweepDimensions(
    double Width,
    double Length,
    double SafetyDistance,
    bool UseDefaultWidth,
    bool UseDefaultLength,
    bool UseDefaultSafetyDistance);

public sealed class SweptAreaCoverageResult
{
    public HashSet<string> NodeCodes { get; } = new(StringComparer.OrdinalIgnoreCase);
    public HashSet<string> EdgeCodes { get; } = new(StringComparer.OrdinalIgnoreCase);
}