826220679@qq.com
15 小时以前 f94b1436d7a28c8e28d010b2cb657ab7c064e353
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
package lujing;
 
import java.util.*;
 
/**
 * 异形草地路径规划 - 凹多边形兼容优化版 V5.0
 * 修复:解决凹多边形扫描线跨越边界的问题,优化路径对齐
 */
public class YixinglujingNoObstacle {
    // 开关:是否强制所有非作业连接沿安全边界行走(避免任何内区直线跨越)
    // 改为可动态设置,自动依据地块形状启用
    private static boolean FORCE_BOUNDARY_TRAVEL = true;
    // 用法说明(无障碍物路径规划):
    // - 方法用途:根据地块边界、割草宽度与安全边距,生成覆盖全区域的割草路径。
    // - 参数:
    //   coordinates:地块边界坐标字符串,格式 "x1,y1;x2,y2;...",至少3个点,单位为米。
    //   widthStr:割草宽度(字符串,单位米),用于确定扫描线间距。
    //   marginStr:安全边距(字符串,单位米),用于将地块边界向内收缩,避免贴边作业。
    // - 返回值:List<PathSegment>,其中 PathSegment.start/end 为坐标点,isMowing 为 true 表示割草段,false 表示空走段。
    // - 失败情况:当边界点不足或内缩后区域过小,返回空列表。
    // - 使用示例:
    //   String boundary = "0,0;20,0;20,15;0,15";
    //   String width = "0.3";
    //   String margin = "0.5";
    //   List<YixinglujingNoObstacle.PathSegment> path =
    //       YixinglujingNoObstacle.planPath(boundary, width, margin);
    public static List<PathSegment> planPath(String coordinates, String widthStr, String marginStr) {
        List<Point> rawPoints = parseCoordinates(coordinates);
        if (rawPoints.size() < 3) return new ArrayList<>();
 
        double mowWidth = Double.parseDouble(widthStr);
        double safeMargin = Double.parseDouble(marginStr);
 
        // 1. 预处理:确保逆时针顺序
        ensureCounterClockwise(rawPoints);
        
        // 2. 生成内缩多边形(安全边界)
        List<Point> boundary = getInsetPolygon(rawPoints, safeMargin);
        if (boundary.size() < 3) return new ArrayList<>();
 
        // 3. 确定最优作业角度
        double bestAngle = findOptimalAngle(boundary);
 
        // 3.1 自动判断是否需要强制沿边界旅行(检测凹部/多段扫描行)
        FORCE_BOUNDARY_TRAVEL = shouldForceBoundaryTravel(boundary, mowWidth, bestAngle);
        
        // 4. 获取首个作业点,用于对齐围边起点
        Point firstScanStart = getFirstScanPoint(boundary, mowWidth, bestAngle);
 
        // 5. 对齐围边:使围边最后结束于靠近扫描起点的位置
        List<Point> alignedBoundary = alignBoundaryStart(boundary, firstScanStart);
 
        List<PathSegment> finalPath = new ArrayList<>();
 
        // 6. 第一阶段:围边路径
        for (int i = 0; i < alignedBoundary.size(); i++) {
            Point pStart = alignedBoundary.get(i);
            Point pEnd = alignedBoundary.get((i + 1) % alignedBoundary.size());
            finalPath.add(new PathSegment(pStart, pEnd, true));
        }
 
        // 7. 第二阶段:生成内部扫描路径(修复凹部空越问题)
        Point lastEdgePos = alignedBoundary.get(0); 
        List<PathSegment> scanPath = generateGlobalScanPath(boundary, mowWidth, bestAngle, lastEdgePos);
        
        finalPath.addAll(scanPath);
 
        // 8. 最终安全净化:确保所有段在内缩边界上或内部(自动贴边阈值)
        sanitizePath(finalPath, boundary, mowWidth, safeMargin);
 
        // 9. 格式化坐标:保留两位小数
        for (PathSegment segment : finalPath) {
            segment.start.x = Math.round(segment.start.x * 100.0) / 100.0;
            segment.start.y = Math.round(segment.start.y * 100.0) / 100.0;
            segment.end.x = Math.round(segment.end.x * 100.0) / 100.0;
            segment.end.y = Math.round(segment.end.y * 100.0) / 100.0;
        }
 
        return finalPath;
    }
 
    // 对所有路径段进行安全净化:
    // - 非作业段:统一沿边界路径替换
    // - 作业段:若端点在外或段与边界相交,吸附端点到边界并向内侧偏移 epsilon
    private static void sanitizePath(List<PathSegment> segments, List<Point> polygon, double width, double margin) {
        double epsilon = computeAutoInnerOffset(polygon, width, margin);
        List<PathSegment> sanitized = new ArrayList<>();
        for (PathSegment s : segments) {
            boolean startInside = isPointInPolygon(s.start, polygon);
            boolean endInside = isPointInPolygon(s.end, polygon);
            boolean intersects = segmentIntersectsBoundary(s.start, s.end, polygon);
            if (!s.isMowing) {
                // 非作业段:若AB直线安全(不跨越边界且中点在内),保留直线;否则沿边界替换
                if (isSegmentSafe(s.start, s.end, polygon)) {
                    sanitized.add(s);
                } else {
                    List<Point> path = getBoundaryPathWithSnap(s.start, s.end, polygon);
                    for (int i = 0; i < path.size() - 1; i++) {
                        sanitized.add(new PathSegment(path.get(i), path.get(i+1), false));
                    }
                }
            } else {
                if (!startInside || !endInside || intersects) {
                    SnapResult s1 = snapToBoundary(s.start, polygon);
                    SnapResult s2 = snapToBoundary(s.end, polygon);
                    Point p1 = pushInsideOnEdge(s1, polygon, epsilon);
                    Point p2 = pushInsideOnEdge(s2, polygon, epsilon);
                    sanitized.add(new PathSegment(p1, p2, true));
                } else {
                    sanitized.add(s);
                }
            }
        }
        segments.clear();
        segments.addAll(sanitized);
    }
 
    private static boolean segmentIntersectsBoundary(Point a, Point b, List<Point> polygon) {
        for (int i = 0; i < polygon.size(); i++) {
            Point c = polygon.get(i);
            Point d = polygon.get((i + 1) % polygon.size());
            // 忽略共享端点的相交
            if (isSamePoint(a, c) || isSamePoint(a, d) || isSamePoint(b, c) || isSamePoint(b, d)) continue;
            if (segmentsIntersect(a, b, c, d)) return true;
        }
        return false;
    }
 
    // 将边界上的投影点向内侧偏移 epsilon
    private static Point pushInsideOnEdge(SnapResult sr, List<Point> poly, double epsilon) {
        int i = sr.edgeIndex;
        Point s = poly.get(i);
        Point e = poly.get((i + 1) % poly.size());
        double dx = e.x - s.x, dy = e.y - s.y;
        double len = Math.hypot(dx, dy);
        if (len < 1e-6) return sr.onEdge;
        // 对于逆时针(CCW)多边形,左转法向量 (-dy, dx) 指向内侧
        double nx = -dy / len, ny = dx / len;
        return new Point(sr.onEdge.x + nx * epsilon, sr.onEdge.y + ny * epsilon);
    }
 
    // 自动计算贴边内偏移阈值 epsilon:根据地块尺度、最短边、割草宽度与安全边距综合估算
    private static double computeAutoInnerOffset(List<Point> polygon, double width, double margin) {
        double minEdge = Double.MAX_VALUE;
        double minX = Double.MAX_VALUE, minY = Double.MAX_VALUE;
        double maxX = -Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
        for (int i = 0; i < polygon.size(); i++) {
            Point a = polygon.get(i);
            Point b = polygon.get((i + 1) % polygon.size());
            minEdge = Math.min(minEdge, Math.hypot(a.x - b.x, a.y - b.y));
            minX = Math.min(minX, a.x); minY = Math.min(minY, a.y);
            maxX = Math.max(maxX, a.x); maxY = Math.max(maxY, a.y);
        }
        double diag = Math.hypot(maxX - minX, maxY - minY);
        // 基础量:数值稳定需要的最小内偏移(取割幅的1%与对角线的0.2%之间的较大值)
        double base = Math.max(width * 0.01, diag * 0.002);
        // 上限:不超过安全边距的20%与割幅的10%
        double upper = Math.min(margin * 0.2, width * 0.1);
        // 受边长约束:不超过最短边的2%
        double edgeLimit = minEdge * 0.02;
        double eps = Math.min(upper, Math.max(base, edgeLimit * 0.5));
        // 下限/上限最终钳位:3mm 到 5cm
        eps = Math.max(0.003, Math.min(eps, 0.05));
        return eps;
    }
 
    // 根据扫描行的交点数量来判断是否存在“多段行”(>=2段),有凹部或窄通道时启用强制沿边界旅行
    private static boolean shouldForceBoundaryTravel(List<Point> polygon, double width, double angle) {
        List<Point> rotatedPoly = new ArrayList<>();
        for (Point p : polygon) rotatedPoly.add(rotatePoint(p, -angle));
        double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
        for (Point p : rotatedPoly) { minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y); }
 
        int multiSegmentRows = 0;
        int totalRows = 0;
        for (double y = minY + width/2; y <= maxY - width/2; y += width) {
            List<Double> xIntersections = getXIntersections(rotatedPoly, y);
            if (xIntersections.size() < 2) continue;
            totalRows++;
            if (xIntersections.size() >= 4) multiSegmentRows++; // 同一行出现两个及以上作业段
        }
        // 只要出现过“多段行”,就强制沿边界旅行;也可按比例阈值触发(例如 >=10%)
        if (multiSegmentRows > 0) return true;
        double ratio = totalRows == 0 ? 0.0 : (double) multiSegmentRows / (double) totalRows;
        return ratio >= 0.1; // 兜底阈值
    }
 
    private static List<PathSegment> generateGlobalScanPath(List<Point> polygon, double width, double angle, Point currentPos) {
        // 先尝试将凹陷处视为两个独立区域,分两次扫描,避免跨区直线连接
        List<PathSegment> all = new ArrayList<>();
        // 第一次扫描:优先处理左侧区域(groupIndex=0)
        List<PathSegment> leftScan = generateScanPathForSide(polygon, width, angle, currentPos, 0);
        all.addAll(leftScan);
        Point posAfterLeft = leftScan.isEmpty() ? currentPos : leftScan.get(leftScan.size() - 1).end;
        // 第二次扫描:处理右侧区域(groupIndex=1),从左侧结束点沿边界到右侧首段
        List<PathSegment> rightScan = generateScanPathForSide(polygon, width, angle, posAfterLeft, 1);
        all.addAll(rightScan);
        return all;
    }
 
    // 仅扫描指定侧(同一条扫描线的第 groupIndex 段),用于将“耳朵”视为独立区域
    private static List<PathSegment> generateScanPathForSide(List<Point> polygon, double width, double angle, Point currentPos, int sideIndex) {
        List<PathSegment> segments = new ArrayList<>();
        List<Point> rotatedPoly = new ArrayList<>();
        for (Point p : polygon) rotatedPoly.add(rotatePoint(p, -angle));
 
        double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
        for (Point p : rotatedPoly) {
            minY = Math.min(minY, p.y);
            maxY = Math.max(maxY, p.y);
        }
 
        boolean leftToRight = true;
        boolean firstSegmentConnected = false;
 
        for (double y = minY + width/2; y <= maxY - width/2; y += width) {
            List<Double> xIntersections = getXIntersections(rotatedPoly, y);
            if (xIntersections.size() < 2) continue;
            Collections.sort(xIntersections);
 
            // 构建本行的作业段(左到右)和组索引
            List<PathSegment> lineSegmentsInRow = new ArrayList<>();
            List<Integer> groupIndices = new ArrayList<>();
            for (int i = 0, g = 0; i < xIntersections.size() - 1; i += 2, g++) {
                Point pS = rotatePoint(new Point(xIntersections.get(i), y), angle);
                Point pE = rotatePoint(new Point(xIntersections.get(i + 1), y), angle);
                lineSegmentsInRow.add(new PathSegment(pS, pE, true));
                groupIndices.add(g);
            }
 
            if (!leftToRight) {
                Collections.reverse(lineSegmentsInRow);
                Collections.reverse(groupIndices);
                for (PathSegment s : lineSegmentsInRow) {
                    Point temp = s.start; s.start = s.end; s.end = temp;
                }
            }
 
            int idxInRow = groupIndices.indexOf(sideIndex);
            if (idxInRow == -1) {
                // 本行不包含该侧的作业段,跳过
                leftToRight = !leftToRight;
                continue;
            }
 
            PathSegment s = lineSegmentsInRow.get(idxInRow);
            // 首次或跨区连接:使用智能换行路径(优先直线最短,必要时沿边界)
            if (Math.hypot(currentPos.x - s.start.x, currentPos.y - s.start.y) > 0.01) {
                addSafeConnection(segments, currentPos, s.start, polygon);
                firstSegmentConnected = true;
            }
            segments.add(s);
            currentPos = s.end;
            leftToRight = !leftToRight;
        }
        return segments;
    }
 
    private static Point getFirstScanPoint(List<Point> polygon, double width, double angle) {
        List<Point> rotatedPoly = new ArrayList<>();
        for (Point p : polygon) rotatedPoly.add(rotatePoint(p, -angle));
        double minY = Double.MAX_VALUE;
        for (Point p : rotatedPoly) minY = Math.min(minY, p.y);
        
        double firstY = minY + width/2;
        List<Double> xInter = getXIntersections(rotatedPoly, firstY);
        if (xInter.isEmpty()) return polygon.get(0);
        Collections.sort(xInter);
        return rotatePoint(new Point(xInter.get(0), firstY), angle);
    }
 
    private static List<Point> alignBoundaryStart(List<Point> boundary, Point targetStart) {
        int bestIdx = 0;
        double minDist = Double.MAX_VALUE;
        for (int i = 0; i < boundary.size(); i++) {
            double d = Math.hypot(boundary.get(i).x - targetStart.x, boundary.get(i).y - targetStart.y);
            if (d < minDist) { minDist = d; bestIdx = i; }
        }
        List<Point> aligned = new ArrayList<>();
        for (int i = 0; i < boundary.size(); i++) {
            aligned.add(boundary.get((bestIdx + i) % boundary.size()));
        }
        return aligned;
    }
 
    private static List<Double> getXIntersections(List<Point> rotatedPoly, double y) {
        List<Double> xIntersections = new ArrayList<>();
        double tolerance = 1e-6;
        
        for (int i = 0; i < rotatedPoly.size(); i++) {
            Point p1 = rotatedPoly.get(i);
            Point p2 = rotatedPoly.get((i + 1) % rotatedPoly.size());
            
            // 跳过水平边(避免与扫描线重合时的特殊情况)
            if (Math.abs(p1.y - p2.y) < tolerance) {
                continue;
            }
            
            // 检查是否相交(使用严格不等式避免顶点重复)
            if ((p1.y < y && p2.y >= y) || (p2.y < y && p1.y >= y)) {
                double x = p1.x + (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y);
                // 简单去重:检查是否已存在相近的点
                boolean isDuplicate = false;
                for (double existingX : xIntersections) {
                    if (Math.abs(x - existingX) < tolerance) {
                        isDuplicate = true;
                        break;
                    }
                }
                if (!isDuplicate) {
                    xIntersections.add(x);
                }
            }
        }
        return xIntersections;
    }
 
    private static double findOptimalAngle(List<Point> polygon) {
        double bestAngle = 0;
        double minHeight = Double.MAX_VALUE;
        for (int i = 0; i < polygon.size(); i++) {
            Point p1 = polygon.get(i), p2 = polygon.get((i + 1) % polygon.size());
            double angle = Math.atan2(p2.y - p1.y, p2.x - p1.x);
            double h = calculateHeightAtAngle(polygon, angle);
            if (h < minHeight) { minHeight = h; bestAngle = angle; }
        }
        return bestAngle;
    }
 
    private static double calculateHeightAtAngle(List<Point> poly, double angle) {
        double minY = Double.MAX_VALUE, maxY = -Double.MAX_VALUE;
        for (Point p : poly) {
            Point rp = rotatePoint(p, -angle);
            minY = Math.min(minY, rp.y); maxY = Math.max(maxY, rp.y);
        }
        return maxY - minY;
    }
 
    public static List<Point> getInsetPolygon(List<Point> points, double margin) {
        List<Point> result = new ArrayList<>();
        int n = points.size();
        for (int i = 0; i < n; i++) {
            Point pPrev = points.get((i - 1 + n) % n);
            Point pCurr = points.get(i);
            Point pNext = points.get((i + 1) % n);
 
            double d1x = pCurr.x - pPrev.x, d1y = pCurr.y - pPrev.y;
            double l1 = Math.hypot(d1x, d1y);
            double d2x = pNext.x - pCurr.x, d2y = pNext.y - pCurr.y;
            double l2 = Math.hypot(d2x, d2y);
 
            if (l1 < 1e-6 || l2 < 1e-6) continue;
 
            // 单位法向量
            double n1x = -d1y / l1, n1y = d1x / l1;
            double n2x = -d2y / l2, n2y = d2x / l2;
 
            // 角平分线方向
            double bisectorX = n1x + n2x, bisectorY = n1y + n2y;
            double bLen = Math.hypot(bisectorX, bisectorY);
            if (bLen < 1e-6) { bisectorX = n1x; bisectorY = n1y; } 
            else { bisectorX /= bLen; bisectorY /= bLen; }
 
            double cosHalfAngle = n1x * bisectorX + n1y * bisectorY;
            double dist = margin / Math.max(cosHalfAngle, 0.1); 
            
            // 限制最大位移量,防止极尖角畸变
            dist = Math.min(dist, margin * 5); 
 
            result.add(new Point(pCurr.x + bisectorX * dist, pCurr.y + bisectorY * dist));
        }
        return result;
    }
 
    private static void addSafeConnection(List<PathSegment> segments, Point start, Point end, List<Point> polygon) {
        // 使用新的智能换行路径算法
        List<PathSegment> connectionPath = generateSmartConnectionPath(start, end, polygon);
        segments.addAll(connectionPath);
    }
 
    /**
     * 智能换行路径生成:根据AB线段与安全边界C的交点,生成混合路径
     * 逻辑:
     * 1. 如果AB线段不穿越边界,直接返回AB直线
     * 2. 如果AB线段穿越边界,找到所有交点(如D, F, G, H),生成路径:
     *    A -> D -> (沿边界D到F) -> F -> G -> (沿边界G到H) -> H -> B
     */
    private static List<PathSegment> generateSmartConnectionPath(Point A, Point B, List<Point> polygon) {
        List<PathSegment> result = new ArrayList<>();
        
        // 1. 检查AB直线是否安全(不穿越边界且中点在内部);与是否强制沿边界无关
        if (isSegmentSafe(A, B, polygon)) {
            result.add(new PathSegment(A, B, false));
            return result;
        }
        
        // 2. 获取AB与边界的所有交点
        List<IntersectionPoint> intersections = getSegmentBoundaryIntersections(A, B, polygon);
        
        // 3. 如果没有交点但不安全,说明整条线都在外部,强制沿边界
        if (intersections.isEmpty()) {
            List<Point> path = getBoundaryPathWithSnap(A, B, polygon);
            for (int i = 0; i < path.size() - 1; i++) {
                result.add(new PathSegment(path.get(i), path.get(i+1), false));
            }
            return result;
        }
        
        // 4. 根据交点成对处理,考虑A/B是否在内侧
        Point currentPos = A;
        boolean startInside = isPointInPolygon(A, polygon);
        boolean endInside = isPointInPolygon(B, polygon);
        
        for (int i = 0; i < intersections.size(); i += 2) {
            IntersectionPoint entry = intersections.get(i);
            
            // 从当前位置到第一个交点:起点在内→直线;起点在外→沿边界到交点
            if (Math.hypot(currentPos.x - entry.point.x, currentPos.y - entry.point.y) > 1e-6) {
                if (startInside) {
                    result.add(new PathSegment(currentPos, entry.point, false));
                } else {
                    List<Point> pathToEntry = getBoundaryPathWithSnap(currentPos, entry.point, polygon);
                    for (int j = 0; j < pathToEntry.size() - 1; j++) {
                        result.add(new PathSegment(pathToEntry.get(j), pathToEntry.get(j+1), false));
                    }
                }
            }
            
            // 检查是否有配对的离开点
            if (i + 1 < intersections.size()) {
                IntersectionPoint exit = intersections.get(i + 1);
                
                // 从进入点D到离开点F:沿边界行走
                List<Point> boundaryPath = getBoundaryPathBetweenPoints(
                    entry.point, entry.edgeIndex,
                    exit.point, exit.edgeIndex,
                    polygon
                );
                
                for (int j = 0; j < boundaryPath.size() - 1; j++) {
                    result.add(new PathSegment(boundaryPath.get(j), boundaryPath.get(j+1), false));
                }
                
                currentPos = exit.point;
                // 之后的起点视为内侧
                startInside = true;
            } else {
                // 如果没有配对的离开点,说明终点在外部,沿边界到B
                List<Point> path = getBoundaryPathWithSnap(entry.point, B, polygon);
                for (int j = 0; j < path.size() - 1; j++) {
                    result.add(new PathSegment(path.get(j), path.get(j+1), false));
                }
                return result;
            }
        }
        
        // 5. 从最后一个离开点到终点B:直线段(在内部)
        if (Math.hypot(currentPos.x - B.x, currentPos.y - B.y) > 1e-6) {
            if (endInside) {
                result.add(new PathSegment(currentPos, B, false));
            } else {
                List<Point> pathToB = getBoundaryPathWithSnap(currentPos, B, polygon);
                for (int j = 0; j < pathToB.size() - 1; j++) {
                    result.add(new PathSegment(pathToB.get(j), pathToB.get(j+1), false));
                }
            }
        }
        
        return result;
    }
 
    /**
     * 在已知边界边索引的情况下,沿边界获取两点之间的最短路径
     */
    private static List<Point> getBoundaryPathBetweenPoints(
        Point start, int startEdgeIdx, 
        Point end, int endEdgeIdx, 
        List<Point> polygon) {
        
        int n = polygon.size();
        
        // 如果在同一条边上,直接连接
        if (startEdgeIdx == endEdgeIdx) {
            return Arrays.asList(start, end);
        }
        
        // 正向路径(顺边)
        List<Point> pathFwd = new ArrayList<>();
        pathFwd.add(start);
        int curr = startEdgeIdx;
        while (curr != endEdgeIdx) {
            pathFwd.add(polygon.get((curr + 1) % n));
            curr = (curr + 1) % n;
        }
        pathFwd.add(end);
 
        // 反向路径(逆边)
        List<Point> pathRev = new ArrayList<>();
        pathRev.add(start);
        curr = startEdgeIdx;
        while (curr != endEdgeIdx) {
            pathRev.add(polygon.get(curr));
            curr = (curr - 1 + n) % n;
        }
        pathRev.add(end);
 
        // 返回几何长度更短的路径
        return getPathLength(pathFwd) <= getPathLength(pathRev) ? pathFwd : pathRev;
    }
 
    // 强制沿边界绕行的连接(不做直线安全判断),用来在同一扫描行的多个作业段之间跳转
    private static void addBoundaryConnection(List<PathSegment> segments, Point start, Point end, List<Point> polygon) {
        List<Point> path = getBoundaryPathWithSnap(start, end, polygon);
        for (int i = 0; i < path.size() - 1; i++) {
            segments.add(new PathSegment(path.get(i), path.get(i+1), false));
        }
    }
 
    // 将任意两点通过“吸附到边界”后沿边界最短路径连接
    private static List<Point> getBoundaryPathWithSnap(Point start, Point end, List<Point> polygon) {
        SnapResult s1 = snapToBoundary(start, polygon);
        SnapResult s2 = snapToBoundary(end, polygon);
        int n = polygon.size();
 
        // 前向路径(顺边)
        List<Point> pathFwd = new ArrayList<>();
        pathFwd.add(start);
        pathFwd.add(s1.onEdge);
        int curr = s1.edgeIndex;
        while (curr != s2.edgeIndex) {
            pathFwd.add(polygon.get((curr + 1) % n));
            curr = (curr + 1) % n;
        }
        pathFwd.add(s2.onEdge);
        pathFwd.add(end);
 
        // 反向路径(逆边)
        List<Point> pathRev = new ArrayList<>();
        pathRev.add(start);
        pathRev.add(s1.onEdge);
        curr = s1.edgeIndex;
        while (curr != s2.edgeIndex) {
            pathRev.add(polygon.get(curr));
            curr = (curr - 1 + n) % n;
        }
        pathRev.add(s2.onEdge);
        pathRev.add(end);
 
        return getPathLength(pathFwd) < getPathLength(pathRev) ? pathFwd : pathRev;
    }
 
    private static class SnapResult {
        Point onEdge;
        int edgeIndex;
        SnapResult(Point p, int idx) { this.onEdge = p; this.edgeIndex = idx; }
    }
 
    // 计算点到边界最近的投影点以及所在边索引
    private static SnapResult snapToBoundary(Point p, List<Point> poly) {
        double minD = Double.MAX_VALUE;
        Point bestProj = p;
        int bestIdx = -1;
        for (int i = 0; i < poly.size(); i++) {
            Point s = poly.get(i);
            Point e = poly.get((i + 1) % poly.size());
            double l2 = (s.x - e.x)*(s.x - e.x) + (s.y - e.y)*(s.y - e.y);
            if (l2 == 0) {
                double d = Math.hypot(p.x - s.x, p.y - s.y);
                if (d < minD) { minD = d; bestProj = s; bestIdx = i; }
                continue;
            }
            double t = ((p.x - s.x) * (e.x - s.x) + (p.y - s.y) * (e.y - s.y)) / l2;
            t = Math.max(0, Math.min(1, t));
            Point proj = new Point(s.x + t * (e.x - s.x), s.y + t * (e.y - s.y));
            double d = Math.hypot(p.x - proj.x, p.y - proj.y);
            if (d < minD) { minD = d; bestProj = proj; bestIdx = i; }
        }
        return new SnapResult(bestProj, bestIdx == -1 ? 0 : bestIdx);
    }
 
    private static boolean isSegmentSafe(Point p1, Point p2, List<Point> polygon) {
        Point mid = new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
        if (!isPointInPolygon(mid, polygon)) return false;
        
        for (int i = 0; i < polygon.size(); i++) {
            Point a = polygon.get(i);
            Point b = polygon.get((i + 1) % polygon.size());
            if (isSamePoint(p1, a) || isSamePoint(p1, b) || isSamePoint(p2, a) || isSamePoint(p2, b)) continue;
            if (segmentsIntersect(p1, p2, a, b)) return false;
        }
        return true;
    }
 
    private static boolean isSamePoint(Point a, Point b) {
        return Math.abs(a.x - b.x) < 1e-4 && Math.abs(a.y - b.y) < 1e-4;
    }
 
    private static boolean segmentsIntersect(Point a, Point b, Point c, Point d) {
        return ccw(a, c, d) != ccw(b, c, d) && ccw(a, b, c) != ccw(a, b, d);
    }
 
    // 获取线段AB与边界多边形的所有交点,按照距离A点的顺序排序
    private static class IntersectionPoint {
        Point point;           // 交点坐标
        int edgeIndex;        // 交点所在的边界边索引
        double distFromStart; // 距离起点A的距离
        boolean isEntry;      // true表示进入边界,false表示离开边界
        
        IntersectionPoint(Point p, int idx, double dist, boolean entry) {
            this.point = p;
            this.edgeIndex = idx;
            this.distFromStart = dist;
            this.isEntry = entry;
        }
    }
 
    // 计算线段AB与多边形边界的所有交点
    private static List<IntersectionPoint> getSegmentBoundaryIntersections(Point A, Point B, List<Point> polygon) {
        List<IntersectionPoint> intersections = new ArrayList<>();
        for (int i = 0; i < polygon.size(); i++) {
            Point C = polygon.get(i);
            Point D = polygon.get((i + 1) % polygon.size());
            Point intersection = getLineSegmentIntersection(A, B, C, D);
            if (intersection != null) {
                if (isSamePoint(intersection, A) || isSamePoint(intersection, B)) continue;
                double dist = Math.hypot(intersection.x - A.x, intersection.y - A.y);
                intersections.add(new IntersectionPoint(intersection, i, dist, false));
            }
        }
        // 距离排序
        Collections.sort(intersections, (i1, i2) -> Double.compare(i1.distFromStart, i2.distFromStart));
        // 去重近似相同交点(顶点双交)
        List<IntersectionPoint> deduped = new ArrayList<>();
        for (IntersectionPoint ip : intersections) {
            boolean dup = false;
            for (IntersectionPoint kept : deduped) {
                if (Math.abs(ip.point.x - kept.point.x) < 1e-6 && Math.abs(ip.point.y - kept.point.y) < 1e-6) { dup = true; break; }
            }
            if (!dup) deduped.add(ip);
        }
        return deduped;
    }
 
    // 计算两条线段的交点(如果存在)
    private static Point getLineSegmentIntersection(Point p1, Point p2, Point p3, Point p4) {
        double x1 = p1.x, y1 = p1.y;
        double x2 = p2.x, y2 = p2.y;
        double x3 = p3.x, y3 = p3.y;
        double x4 = p4.x, y4 = p4.y;
        
        double denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
        if (Math.abs(denom) < 1e-10) return null; // 平行或重合
        
        double t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denom;
        double u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / denom;
        
        // 检查交点是否在两条线段上(使用略微宽松的范围以处理浮点误差)
        double epsilon = 1e-6;
        if (t >= -epsilon && t <= 1 + epsilon && u >= -epsilon && u <= 1 + epsilon) {
            return new Point(x1 + t * (x2 - x1), y1 + t * (y2 - y1));
        }
        
        return null;
    }
 
    private static boolean ccw(Point a, Point b, Point c) {
        return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);
    }
 
    private static boolean isPointInPolygon(Point p, List<Point> polygon) {
        boolean result = false;
        for (int i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++) {
            if ((polygon.get(i).y > p.y) != (polygon.get(j).y > p.y) &&
                (p.x < (polygon.get(j).x - polygon.get(i).x) * (p.y - polygon.get(i).y) / (polygon.get(j).y - polygon.get(i).y) + polygon.get(i).x)) {
                result = !result;
            }
        }
        return result;
    }
 
    private static List<Point> getBoundaryPath(Point start, Point end, List<Point> polygon) {
        int idx1 = getEdgeIndex(start, polygon);
        int idx2 = getEdgeIndex(end, polygon);
        
        if (idx1 == -1 || idx2 == -1 || idx1 == idx2) {
            return Arrays.asList(start, end);
        }
 
        List<Point> path1 = new ArrayList<>();
        path1.add(start);
        int curr = idx1;
        while (curr != idx2) {
            path1.add(polygon.get((curr + 1) % polygon.size()));
            curr = (curr + 1) % polygon.size();
        }
        path1.add(end);
 
        List<Point> pathRev = new ArrayList<>();
        pathRev.add(start);
        curr = idx1;
        while (curr != idx2) {
            pathRev.add(polygon.get(curr));
            curr = (curr - 1 + polygon.size()) % polygon.size();
        }
        pathRev.add(polygon.get((idx2 + 1) % polygon.size()));
        pathRev.add(end);
        
        return getPathLength(path1) < getPathLength(pathRev) ? path1 : pathRev;
    }
 
    private static double getPathLength(List<Point> path) {
        double len = 0;
        for (int i = 0; i < path.size() - 1; i++) {
            len += Math.hypot(path.get(i).x - path.get(i+1).x, path.get(i).y - path.get(i+1).y);
        }
        return len;
    }
 
    private static int getEdgeIndex(Point p, List<Point> poly) {
        int bestIdx = -1;
        double minD = Double.MAX_VALUE;
        for (int i = 0; i < poly.size(); i++) {
            Point p1 = poly.get(i);
            Point p2 = poly.get((i + 1) % poly.size());
            double d = distToSegment(p, p1, p2);
            if (d < minD) {
                minD = d;
                bestIdx = i;
            }
        }
        // 只要找到最近的边即可,放宽阈值以应对浮点误差和旋转变形
        // 如果距离过大(例如超过1米),可能确实不在边界上,但在路径规划上下文中,
        // 这些点是由扫描线生成的,理论上一定在边界上,所以强制吸附是安全的。
        return minD < 1.0 ? bestIdx : -1;
    }
    
    private static double distToSegment(Point p, Point s, Point e) {
        double l2 = (s.x - e.x)*(s.x - e.x) + (s.y - e.y)*(s.y - e.y);
        if (l2 == 0) return Math.hypot(p.x - s.x, p.y - s.y);
        double t = ((p.x - s.x) * (e.x - s.x) + (p.y - s.y) * (e.y - s.y)) / l2;
        t = Math.max(0, Math.min(1, t));
        return Math.hypot(p.x - (s.x + t * (e.x - s.x)), p.y - (s.y + t * (e.y - s.y)));
    }
 
    private static Point rotatePoint(Point p, double angle) {
        double cos = Math.cos(angle), sin = Math.sin(angle);
        return new Point(p.x * cos - p.y * sin, p.x * sin + p.y * cos);
    }
 
    public static void ensureCounterClockwise(List<Point> points) {
        double sum = 0;
        for (int i = 0; i < points.size(); i++) {
            Point p1 = points.get(i), p2 = points.get((i + 1) % points.size());
            sum += (p2.x - p1.x) * (p2.y + p1.y);
        }
        if (sum > 0) Collections.reverse(points);
    }
 
    private static List<Point> parseCoordinates(String coordinates) {
        List<Point> points = new ArrayList<>();
        String[] pairs = coordinates.split(";");
        for (String pair : pairs) {
            String[] xy = pair.split(",");
            if (xy.length == 2) points.add(new Point(Double.parseDouble(xy[0]), Double.parseDouble(xy[1])));
        }
        if (points.size() > 1 && points.get(0).equals(points.get(points.size()-1))) points.remove(points.size()-1);
        return points;
    }
 
    public static class Point {
        public double x, y;
        public Point(double x, double y) { this.x = x; this.y = y; }
        @Override
        public boolean equals(Object o) {
            if (!(o instanceof Point)) return false;
            Point p = (Point) o;
            return Math.abs(x - p.x) < 1e-4 && Math.abs(y - p.y) < 1e-4;
        }
    }
 
    public static class PathSegment {
        public Point start, end;
        public boolean isMowing; // true: 割草中, false: 空载移动
        public PathSegment(Point s, Point e, boolean m) { this.start = s; this.end = e; this.isMowing = m; }
    }
}