张世豪
昨天 f0d6cefec73492c29d8323e66fb92ee6bbb60cd2
src/lujing/YixinglujingHaveObstacel.java
@@ -1,394 +1,194 @@
package lujing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.*;
import java.util.regex.*;
/**
 * 异形草地路径规划 - 障碍物裁剪优化版 V9.0
 * 核心逻辑:先生成全覆盖扫描路径,再利用外扩后的障碍物对路径进行裁剪。
 * 异形草地路径规划 - 凹多边形修复版 V12.0
 * 修改说明:
 * 1. 按照用户要求,先生成无障碍物的完整路径(围边+扫描+连接)。
 * 2. 对完整路径进行障碍物裁剪。
 * 3. 对裁剪产生的断点,尝试沿障碍物边界进行连接。
 */
public class YixinglujingHaveObstacel {
    /**
     * 规划路径主入口
     */
    private static final double EPS = 1e-8;
    private static final double MIN_SEG_LEN = 0.02; // 忽略小于2cm的碎线
    public static List<PathSegment> planPath(String coordinates, String obstaclesStr, String widthStr, String marginStr) {
        // 1. 解析参数
        List<Point> rawPoints = parseCoordinates(coordinates);
        if (rawPoints.size() < 3) return new ArrayList<>();
        double mowWidth = Double.parseDouble(widthStr);
        double safeMargin = Double.parseDouble(marginStr);
        // 2. 预处理地块边界 (确保逆时针)
        ensureCounterClockwise(rawPoints);
        // 1. 统一多边形方向为逆时针 (CCW)
        ensureCCW(rawPoints);
        
        // 3. 生成地块内缩的安全作业边界 (Inset)
        List<Point> mowingBoundary = getOffsetPolygon(rawPoints, safeMargin); // 正数内缩
        // 2. 生成作业内缩边界
        List<Point> mowingBoundary = getOffsetPolygon(rawPoints, safeMargin);
        if (mowingBoundary.size() < 3) return new ArrayList<>();
        // 4. 第一步:生成“无视障碍物”的全覆盖扫描路径
        // 直接使用扫描线算法生成填满整个内缩边界的路径
        List<PathSegment> rawPath = generateFullCoveragePath(mowingBoundary, mowWidth);
        // 5. 解析障碍物并进行外扩 (Outset)
        // 注意:障碍物外扩距离 = 割草机安全边距,确保不发生碰撞
        // 3. 解析并外扩障碍物
        List<Obstacle> obstacles = parseObstacles(obstaclesStr, safeMargin);
        // 6. 第二步:使用障碍物裁剪路径 (核心步骤)
        return clipPathWithObstacles(rawPath, obstacles);
        // 4. 生成全覆盖路径(不考虑障碍物)
        List<PathSegment> fullPath = generateFullPath(mowingBoundary, mowWidth);
        // 5. 裁剪并连接
        return processObstacles(fullPath, obstacles);
    }
    /**
     * 使用障碍物集合裁剪原始路径
     * 生成全覆盖路径(围边 + 扫描 + 连接),不考虑障碍物
     */
    private static List<PathSegment> clipPathWithObstacles(List<PathSegment> rawPath, List<Obstacle> obstacles) {
        List<PathSegment> finalPath = new ArrayList<>();
        Point currentPos = (rawPath.isEmpty()) ? new Point(0,0) : rawPath.get(0).start;
    private static List<PathSegment> generateFullPath(List<Point> boundary, double width) {
        List<PathSegment> path = new ArrayList<>();
        for (PathSegment segment : rawPath) {
            // 将当前这一段路径,拿去跟所有障碍物进行碰撞检测和裁剪
            // 初始时,这一段是完整的
            List<PathSegment> segmentsToProcess = new ArrayList<>();
            segmentsToProcess.add(segment);
            for (Obstacle obs : obstacles) {
                List<PathSegment> nextIterSegments = new ArrayList<>();
                for (PathSegment seg : segmentsToProcess) {
                    // 如果是割草路径,需要裁剪;如果是空走路径,通常也需要避障,
                    // 但这里主要处理扫描线的裁剪。
                    if (seg.isMowing) {
                        nextIterSegments.addAll(obs.clip(seg));
                    } else {
                        // 空走路径暂时保留(高级避障需要A*算法,此处简化为保留)
                        nextIterSegments.add(seg);
                    }
                }
                segmentsToProcess = nextIterSegments;
        // A. 围边路径(首圈)
        for (int i = 0; i < boundary.size(); i++) {
            path.add(new PathSegment(boundary.get(i), boundary.get((i + 1) % boundary.size()), true));
            }
            // 将裁剪后剩余的线段加入最终路径
            for (PathSegment s : segmentsToProcess) {
                // 过滤掉因为裁剪产生的极短线段
                if (distance(s.start, s.end) < 0.05) continue;
                // 如果当前点和线段起点不连贯,加入连接路径(空走)
                if (distance(currentPos, s.start) > 0.05) {
                    finalPath.add(new PathSegment(currentPos, s.start, false));
                }
                finalPath.add(s);
                currentPos = s.end;
            }
        }
        return finalPath;
    }
    // --- 路径生成核心算法 (移植自 NoObstacle 类) ---
    private static List<PathSegment> generateFullCoveragePath(List<Point> boundary, double width) {
        // 1. 寻找最优角度
        // B. 扫描路径生成
        double angle = findOptimalAngle(boundary);
        // 2. 旋转多边形以对齐坐标轴
        List<Point> rotatedPoly = new ArrayList<>();
        for (Point p : boundary) rotatedPoly.add(rotatePoint(p, -angle));
        List<Point> rotPoly = rotatePoints(boundary, -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);
        }
        for (Point p : rotPoly) { minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y); }
        // 3. 生成扫描线
        List<PathSegment> segments = new ArrayList<>();
        boolean l2r = true;
        // 围边路径先生成
        Point scanStartPoint = null;
        // 这里我们先计算扫描线,最后再决定围边起点以减少空走
        List<List<PathSegment>> scanRows = new ArrayList<>();
        List<PathSegment> scanSegments = new ArrayList<>();
        for (double y = minY + width/2; y <= maxY - width/2; y += width) {
            List<Double> xInters = getXIntersections(rotatedPoly, y);
            List<Double> xInters = getXIntersections(rotPoly, y);
            if (xInters.size() < 2) continue;
            Collections.sort(xInters);
            List<PathSegment> row = new ArrayList<>();
            // 两两配对形成线段
            // 凹多边形核心:成对取出交点,跳过中间的空洞
            for (int i = 0; i < xInters.size() - 1; i += 2) {
                Point s = rotatePoint(new Point(xInters.get(i), y), angle);
                Point e = rotatePoint(new Point(xInters.get(i + 1), y), angle);
                row.add(new PathSegment(s, e, true));
            }
            // 蛇形排序
            if (!l2r) {
                Collections.reverse(row);
                for (PathSegment s : row) {
                    Point tmp = s.start; s.start = s.end; s.end = tmp;
                for (PathSegment s : row) { Point t = s.start; s.start = s.end; s.end = t; }
                }
            }
            scanRows.add(row);
            if (scanStartPoint == null && !row.isEmpty()) scanStartPoint = row.get(0).start;
            scanSegments.addAll(row);
            l2r = !l2r;
        }
        // 4. 生成围边路径 (对齐到第一个扫描点)
        List<Point> alignedBoundary = alignBoundaryStart(boundary, scanStartPoint);
        for (int i = 0; i < alignedBoundary.size(); i++) {
            segments.add(new PathSegment(alignedBoundary.get(i), alignedBoundary.get((i+1)%alignedBoundary.size()), true));
        // C. 连接扫描线
        if (!scanSegments.isEmpty()) {
            Point currentPos = path.isEmpty() ? scanSegments.get(0).start : path.get(path.size() - 1).end;
            for (PathSegment seg : scanSegments) {
                if (distance(currentPos, seg.start) > MIN_SEG_LEN) {
                    path.add(new PathSegment(currentPos, seg.start, false));
        }
        // 5. 加入扫描路径
        for (List<PathSegment> row : scanRows) {
            segments.addAll(row);
        }
        return segments;
    }
    // --- 障碍物处理类 ---
    private static List<Obstacle> parseObstacles(String obsStr, double margin) {
        List<Obstacle> list = new ArrayList<>();
        if (obsStr == null || obsStr.trim().isEmpty()) return list;
        // 处理格式 (x,y;...)(x,y;...) 或 $ 分隔
        String cleanStr = obsStr.replaceAll("\\s+", "");
        String[] parts;
        if (cleanStr.contains("(") && cleanStr.contains(")")) {
            List<String> matches = new ArrayList<>();
            java.util.regex.Matcher m = java.util.regex.Pattern.compile("\\(([^)]+)\\)").matcher(cleanStr);
            while (m.find()) matches.add(m.group(1));
            parts = matches.toArray(new String[0]);
        } else {
            parts = cleanStr.split("\\$");
        }
        for (String pStr : parts) {
            List<Point> pts = parseCoordinates(pStr);
            if (pts.isEmpty()) continue;
            if (pts.size() == 2) {
                // 圆形障碍物
                double r = distance(pts.get(0), pts.get(1));
                list.add(new CircleObstacle(pts.get(0), r + margin)); // 半径增加margin
            } else {
                // 多边形障碍物
                ensureCounterClockwise(pts);
                // 外扩障碍物 (Offset Out)
                // 注意:在通用偏移算法中,逆时针多边形,负数通常表示外扩,或者使用特定算法
                // 这里我们复用 getOffsetPolygon,并传入负的margin来实现外扩
                // *但在本类目前的 getOffsetPolygon 实现中(基于角平分线),如果是逆时针:
                // 正数是向左(内缩),负数是向右(外扩)*
                List<Point> expanded = getOffsetPolygon(pts, -margin);
                list.add(new PolyObstacle(expanded));
                path.add(seg);
                currentPos = seg.end;
            }
        }
        return list;
        return path;
    }
    abstract static class Obstacle {
        // 返回裁剪后的线段列表(即保留在障碍物外部的线段)
        abstract List<PathSegment> clip(PathSegment seg);
    }
    static class CircleObstacle extends Obstacle {
        Point c; double r;
        CircleObstacle(Point c, double r) { this.c = c; this.r = r; }
        @Override
        List<PathSegment> clip(PathSegment seg) {
            // 计算直线与圆的交点 t值 (0..1)
            double dx = seg.end.x - seg.start.x;
            double dy = seg.end.y - seg.start.y;
            double fx = seg.start.x - c.x;
            double fy = seg.start.y - c.y;
            double A = dx*dx + dy*dy;
            double B = 2*(fx*dx + fy*dy);
            double C = (fx*fx + fy*fy) - r*r;
            double delta = B*B - 4*A*C;
    /**
     * 处理障碍物:裁剪路径并生成绕行连接
     */
    private static List<PathSegment> processObstacles(List<PathSegment> fullPath, List<Obstacle> obstacles) {
            List<PathSegment> result = new ArrayList<>();
            if (delta < 0) {
                // 无交点,全保留或全剔除
                if (!isInside(seg.start)) result.add(seg);
                return result;
        if (fullPath.isEmpty()) return result;
        Point currentPos = fullPath.get(0).start;
        for (PathSegment seg : fullPath) {
            // 裁剪单条线段
            List<PathSegment> pieces = clipSegment(seg, obstacles);
            for (PathSegment piece : pieces) {
                // 如果有断点,尝试连接
                if (distance(currentPos, piece.start) > MIN_SEG_LEN) {
                    List<PathSegment> detour = findDetour(currentPos, piece.start, obstacles);
                    result.addAll(detour);
            }
            double t1 = (-B - Math.sqrt(delta)) / (2*A);
            double t2 = (-B + Math.sqrt(delta)) / (2*A);
            List<Double> ts = new ArrayList<>();
            ts.add(0.0);
            if (t1 > 0 && t1 < 1) ts.add(t1);
            if (t2 > 0 && t2 < 1) ts.add(t2);
            ts.add(1.0);
            Collections.sort(ts);
            for (int i = 0; i < ts.size()-1; i++) {
                double midT = (ts.get(i) + ts.get(i+1)) / 2;
                Point mid = interpolate(seg.start, seg.end, midT);
                if (!isInside(mid)) {
                    result.add(new PathSegment(interpolate(seg.start, seg.end, ts.get(i)),
                                               interpolate(seg.start, seg.end, ts.get(i+1)),
                                               seg.isMowing));
                result.add(piece);
                currentPos = piece.end;
                }
            }
            return result;
        }
        boolean isInside(Point p) {
            return (p.x-c.x)*(p.x-c.x) + (p.y-c.y)*(p.y-c.y) < r*r;
    private static List<PathSegment> findDetour(Point p1, Point p2, List<Obstacle> obstacles) {
        // 检查断点是否在同一个障碍物上
        for (Obstacle obs : obstacles) {
            if (obs.isOnBoundary(p1) && obs.isOnBoundary(p2)) {
                return obs.getBoundaryPath(p1, p2);
        }
    }
        // 如果不在同一个障碍物上(理论上较少见,除非跨越了多个障碍物),直接连接
        List<PathSegment> res = new ArrayList<>();
        res.add(new PathSegment(p1, p2, false));
        return res;
    }
    static class PolyObstacle extends Obstacle {
        List<Point> points;
        double minX, maxX, minY, maxY;
        PolyObstacle(List<Point> pts) {
            this.points = pts;
            updateBounds();
        }
        void updateBounds() {
            minX = minY = Double.MAX_VALUE;
            maxX = maxY = -Double.MAX_VALUE;
            for (Point p : points) {
                minX = Math.min(minX, p.x); maxX = Math.max(maxX, p.x);
                minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y);
            }
        }
        boolean isInside(Point p) {
            if (p.x < minX || p.x > maxX || p.y < minY || p.y > maxY) return false;
            boolean result = false;
            for (int i = 0, j = points.size() - 1; i < points.size(); j = i++) {
                if ((points.get(i).y > p.y) != (points.get(j).y > p.y) &&
                    (p.x < (points.get(j).x - points.get(i).x) * (p.y - points.get(i).y) / (points.get(j).y - points.get(i).y) + points.get(i).x)) {
                    result = !result;
                }
            }
            return result;
        }
        @Override
        List<PathSegment> clip(PathSegment seg) {
            List<Double> ts = new ArrayList<>();
            ts.add(0.0);
            ts.add(1.0);
            // 计算线段与障碍物每一条边的交点
            for (int i = 0; i < points.size(); i++) {
                Point p1 = points.get(i);
                Point p2 = points.get((i+1)%points.size());
                double t = getIntersectionT(seg.start, seg.end, p1, p2);
                if (t > 1e-6 && t < 1 - 1e-6) {
                    ts.add(t);
                }
            }
            Collections.sort(ts);
    private static List<PathSegment> clipSegment(PathSegment seg, List<Obstacle> obstacles) {
            List<PathSegment> result = new ArrayList<>();
            // 检查每一小段的中点是否在障碍物内
            for (int i = 0; i < ts.size() - 1; i++) {
                double tMid = (ts.get(i) + ts.get(i+1)) / 2.0;
                // 如果两点极其接近,跳过
                if (ts.get(i+1) - ts.get(i) < 1e-6) continue;
                Point mid = interpolate(seg.start, seg.end, tMid);
                if (!isInside(mid)) {
                    // 在外部,保留
                    Point s = interpolate(seg.start, seg.end, ts.get(i));
                    Point e = interpolate(seg.start, seg.end, ts.get(i+1));
                    result.add(new PathSegment(s, e, seg.isMowing));
        result.add(seg);
        for (Obstacle obs : obstacles) {
            List<PathSegment> next = new ArrayList<>();
            for (PathSegment s : result) {
                next.addAll(obs.clip(s));
                }
            result = next;
            }
            return result;
        }
    // --- 几何修正算法 ---
    /**
     * 修正后的方向判定:鞋带公式 Sum (x2-x1)(y2+y1)
     * 在标准笛卡尔坐标系中,Sum < 0 为逆时针
     */
    private static void ensureCCW(List<Point> pts) {
        double s = 0;
        for (int i = 0; i < pts.size(); i++) {
            Point p1 = pts.get(i), p2 = pts.get((i + 1) % pts.size());
            s += (p2.x - p1.x) * (p2.y + p1.y);
        }
        if (s > 0) Collections.reverse(pts);
    }
    // --- 通用几何算法 ---
    private static List<Point> getOffsetPolygon(List<Point> points, double offset) {
    private static List<Point> getOffsetPolygon(List<Point> pts, double offset) {
        List<Point> result = new ArrayList<>();
        int n = points.size();
        int n = pts.size();
        for (int i = 0; i < n; i++) {
            Point p1 = points.get((i - 1 + n) % n);
            Point p2 = points.get(i);
            Point p3 = points.get((i + 1) % n);
            // 向量 p1->p2 和 p2->p3
            Point p1 = pts.get((i - 1 + n) % n), p2 = pts.get(i), p3 = pts.get((i + 1) % n);
            double v1x = p2.x - p1.x, v1y = p2.y - p1.y;
            double v2x = p3.x - p2.x, v2y = p3.y - p2.y;
            double l1 = Math.hypot(v1x, v1y), l2 = Math.hypot(v2x, v2y);
            if (l1 < EPS || l2 < EPS) continue;
            
            if (l1 < 1e-5 || l2 < 1e-5) continue;
            // 法向量 (向左转90度: -y, x)
            // 法向量偏移(逆时针向左偏移即为内缩)
            double n1x = -v1y / l1, n1y = v1x / l1;
            double n2x = -v2y / l2, n2y = v2x / l2;
            // 角平分线
            double bx = n1x + n2x, by = n1y + n2y;
            double bl = Math.hypot(bx, by);
            if (bl < 1e-5) { bx = n1x; by = n1y; }
            else { bx /= bl; by /= bl; }
            // 修正长度 offset / sin(theta/2) = offset / dot(n1, b)
            double dot = n1x * bx + n1y * by;
            double dist = offset / Math.max(Math.abs(dot), 0.1); // 防止尖角过长
            // 阈值限制,防止自交或畸变过大
            dist = Math.signum(offset) * Math.min(Math.abs(dist), Math.abs(offset) * 3);
            if (bl < EPS) { bx = n1x; by = n1y; } else { bx /= bl; by /= bl; }
            double dist = offset / Math.max(Math.abs(n1x * bx + n1y * by), 0.1);
            result.add(new Point(p2.x + bx * dist, p2.y + by * dist));
        }
        return result;
    }
    private static double findOptimalAngle(List<Point> poly) {
        double bestA = 0, minH = Double.MAX_VALUE;
        for (int i = 0; i < poly.size(); i++) {
            Point p1 = poly.get(i), p2 = poly.get((i + 1) % poly.size());
            double a = Math.atan2(p2.y - p1.y, p2.x - p1.x);
            double h = calcHeight(poly, a);
            if (h < minH) { minH = h; bestA = a; }
        }
        return bestA;
    }
    private static double calcHeight(List<Point> poly, double ang) {
        double min = Double.MAX_VALUE, max = -Double.MAX_VALUE;
        for (Point p : poly) {
            Point r = rotatePoint(p, -ang);
            min = Math.min(min, r.y); max = Math.max(max, r.y);
        }
        return max - min;
    }
    private static double getIntersectionT(Point a, Point b, Point c, Point d) {
        double ux = b.x - a.x, uy = b.y - a.y;
        double vx = d.x - c.x, vy = d.y - c.y;
        double det = vx * uy - vy * ux;
        if (Math.abs(det) < 1e-8) return -1;
        double wx = c.x - a.x, wy = c.y - a.y;
        double t = (vx * wy - vy * wx) / det;
        double u = (ux * wy - uy * wx) / det;
        if (u >= 0 && u <= 1) return t; // 只保证交点在线段CD上,t是AB上的比例
        return -1;
    }
    private static List<Double> getXIntersections(List<Point> poly, double y) {
        List<Double> res = new ArrayList<>();
        for (int i = 0; i < poly.size(); i++) {
            Point p1 = poly.get(i), p2 = poly.get((i + 1) % poly.size());
            // 标准相交判断:一开一闭避免重复计算顶点
            if ((p1.y <= y && p2.y > y) || (p2.y <= y && p1.y > y)) {
                res.add(p1.x + (y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y));
            }
@@ -396,63 +196,269 @@
        return res;
    }
    private static List<Point> alignBoundaryStart(List<Point> poly, Point target) {
        if (target == null) return poly;
        int idx = 0; double minD = Double.MAX_VALUE;
        for (int i = 0; i < poly.size(); i++) {
            double d = distance(poly.get(i), target);
            if (d < minD) { minD = d; idx = i; }
    // --- 障碍物模型 ---
    abstract static class Obstacle {
        abstract List<PathSegment> clip(PathSegment seg);
        abstract boolean isInside(Point p);
        abstract boolean isOnBoundary(Point p);
        abstract List<PathSegment> getBoundaryPath(Point p1, Point p2);
        }
        List<Point> res = new ArrayList<>();
        for (int i = 0; i < poly.size(); i++) res.add(poly.get((idx + i) % poly.size()));
    static class PolyObstacle extends Obstacle {
        List<Point> pts;
        PolyObstacle(List<Point> p) { this.pts = p; }
        @Override
        boolean isInside(Point p) {
            boolean in = false;
            for (int i = 0, j = pts.size() - 1; i < pts.size(); j = i++) {
                if (((pts.get(i).y > p.y) != (pts.get(j).y > p.y)) &&
                    (p.x < (pts.get(j).x - pts.get(i).x) * (p.y - pts.get(i).y) / (pts.get(j).y - pts.get(i).y) + pts.get(i).x)) {
                    in = !in;
                }
            }
            return in;
        }
        @Override
        List<PathSegment> clip(PathSegment seg) {
            List<Double> ts = new ArrayList<>(Arrays.asList(0.0, 1.0));
            for (int i = 0; i < pts.size(); i++) {
                double t = getIntersectT(seg.start, seg.end, pts.get(i), pts.get((i + 1) % pts.size()));
                if (t > EPS && t < 1.0 - EPS) ts.add(t);
            }
            Collections.sort(ts);
            List<PathSegment> res = new ArrayList<>();
            for (int i = 0; i < ts.size() - 1; i++) {
                double tMid = (ts.get(i) + ts.get(i + 1)) / 2.0;
                if (!isInside(interpolate(seg.start, seg.end, tMid))) {
                    res.add(new PathSegment(interpolate(seg.start, seg.end, ts.get(i)),
                                            interpolate(seg.start, seg.end, ts.get(i+1)), seg.isMowing));
                }
            }
        return res;
    }
    private static void ensureCounterClockwise(List<Point> pts) {
        double s = 0;
        @Override
        boolean isOnBoundary(Point p) {
        for (int i = 0; i < pts.size(); i++) {
            Point p1 = pts.get(i), p2 = pts.get((i + 1) % pts.size());
            s += (p2.x - p1.x) * (p2.y + p1.y);
                if (distToSegment(p, pts.get(i), pts.get((i + 1) % pts.size())) < 1e-4) return true;
        }
        if (s > 0) Collections.reverse(pts); // 假设屏幕坐标系Y向下?通常多边形面积公式s>0是顺时针(Y向下)或逆时针(Y向上)
        // 此处沿用您代码的逻辑:如果Sum>0 则反转。
            return false;
        }
        @Override
        List<PathSegment> getBoundaryPath(Point p1, Point p2) {
            // 寻找最近的顶点索引
            int idx1 = -1, idx2 = -1;
            double minD1 = Double.MAX_VALUE, minD2 = Double.MAX_VALUE;
            for (int i = 0; i < pts.size(); i++) {
                double d1 = distToSegment(p1, pts.get(i), pts.get((i + 1) % pts.size()));
                if (d1 < minD1) { minD1 = d1; idx1 = i; }
                double d2 = distToSegment(p2, pts.get(i), pts.get((i + 1) % pts.size()));
                if (d2 < minD2) { minD2 = d2; idx2 = i; }
    }
    private static Point rotatePoint(Point p, double a) {
        double c = Math.cos(a), s = Math.sin(a);
        return new Point(p.x * c - p.y * s, p.x * s + p.y * c);
            List<Point> pathPoints = new ArrayList<>();
            pathPoints.add(p1);
            // 简单策略:沿多边形顶点移动。由于是障碍物,我们选择较短路径
            // 顺时针和逆时针比较
            List<Point> ccw = new ArrayList<>();
            int curr = idx1;
            while (curr != idx2) {
                curr = (curr + 1) % pts.size();
                ccw.add(pts.get(curr));
    }
    
    private static Point interpolate(Point a, Point b, double t) {
        return new Point(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
            List<Point> cw = new ArrayList<>();
            curr = (idx1 + 1) % pts.size(); // idx1 is the start of edge containing p1
            // Wait, idx1 is index of point? No, index of edge start.
            // Edge i is pts[i] -> pts[i+1]
            // If p1 is on edge idx1, p2 is on edge idx2.
            // Let's simplify: collect all vertices in order
            // Path 1: p1 -> pts[idx1+1] -> ... -> pts[idx2] -> p2
            // Path 2: p1 -> pts[idx1] -> ... -> pts[idx2+1] -> p2
            // Calculate lengths and choose shortest
            List<PathSegment> res = new ArrayList<>();
            // For now, just return straight line to avoid complexity bugs in blind coding
            // But user wants to avoid obstacle.
            // Let's implement a simple vertex traversal
            // CCW path (pts order)
            List<Point> path1 = new ArrayList<>();
            path1.add(p1);
            int i = idx1;
            while (i != idx2) {
                i = (i + 1) % pts.size();
                path1.add(pts.get(i));
            }
            path1.add(pts.get((idx2 + 1) % pts.size())); // End of edge idx2? No.
            // If p2 is on edge idx2 (pts[idx2]->pts[idx2+1])
            // We arrive at pts[idx2], then go to p2? No.
            // If we go CCW: p1 -> pts[idx1+1] -> pts[idx1+2] ... -> pts[idx2] -> p2
            // Let's rebuild path1 correctly
            List<Point> p1List = new ArrayList<>();
            p1List.add(p1);
            int k = idx1;
            while (k != idx2) {
                k = (k + 1) % pts.size();
                p1List.add(pts.get(k));
            }
            p1List.add(p2); // Finally to p2 (which is on edge idx2)
            // CW path
            List<Point> p2List = new ArrayList<>();
            p2List.add(p1);
            k = idx1; // Start at edge idx1
            // Go backwards: p1 -> pts[idx1] -> pts[idx1-1] ... -> pts[idx2+1] -> p2
            p2List.add(pts.get(k));
            k = (k - 1 + pts.size()) % pts.size();
            while (k != idx2) {
                p2List.add(pts.get(k));
                k = (k - 1 + pts.size()) % pts.size();
            }
            p2List.add(pts.get((idx2 + 1) % pts.size()));
            p2List.add(p2);
            double len1 = getPathLen(p1List);
            double len2 = getPathLen(p2List);
            List<Point> best = (len1 < len2) ? p1List : p2List;
            for (int j = 0; j < best.size() - 1; j++) {
                res.add(new PathSegment(best.get(j), best.get(j+1), false));
            }
            return res;
        }
        private double getPathLen(List<Point> ps) {
            double l = 0;
            for(int i=0;i<ps.size()-1;i++) l+=distance(ps.get(i), ps.get(i+1));
            return l;
        }
    }
    private static double distance(Point a, Point b) {
        return Math.hypot(a.x - b.x, a.y - b.y);
    static class CircleObstacle extends Obstacle {
        Point c; double r;
        CircleObstacle(Point c, double r) { this.c = c; this.r = r; }
        @Override
        boolean isInside(Point p) { return distance(p, c) < r - EPS; }
        @Override
        List<PathSegment> clip(PathSegment seg) {
            double dx = seg.end.x - seg.start.x, dy = seg.end.y - seg.start.y;
            double fx = seg.start.x - c.x, fy = seg.start.y - c.y;
            double A = dx*dx + dy*dy, B = 2*(fx*dx + fy*dy), C = fx*fx + fy*fy - r*r;
            double delta = B*B - 4*A*C;
            List<Double> ts = new ArrayList<>(Arrays.asList(0.0, 1.0));
            if (delta > 0) {
                double t1 = (-B-Math.sqrt(delta))/(2*A), t2 = (-B+Math.sqrt(delta))/(2*A);
                if (t1 > 0 && t1 < 1) ts.add(t1); if (t2 > 0 && t2 < 1) ts.add(t2);
            }
            Collections.sort(ts);
            List<PathSegment> res = new ArrayList<>();
            for (int i = 0; i < ts.size()-1; i++) {
                if (!isInside(interpolate(seg.start, seg.end, (ts.get(i)+ts.get(i+1))/2.0)))
                    res.add(new PathSegment(interpolate(seg.start, seg.end, ts.get(i)), interpolate(seg.start, seg.end, ts.get(i+1)), seg.isMowing));
            }
            return res;
        }
        @Override
        boolean isOnBoundary(Point p) {
            return Math.abs(distance(p, c) - r) < 1e-4;
        }
        @Override
        List<PathSegment> getBoundaryPath(Point p1, Point p2) {
            List<PathSegment> res = new ArrayList<>();
            double a1 = Math.atan2(p1.y - c.y, p1.x - c.x);
            double a2 = Math.atan2(p2.y - c.y, p2.x - c.x);
            double da = a2 - a1;
            while (da <= -Math.PI) da += 2*Math.PI;
            while (da > Math.PI) da -= 2*Math.PI;
            // Choose shorter arc
            // If da is positive, CCW is shorter? No, da is signed diff.
            // We just interpolate angles.
            int steps = 10;
            Point prev = p1;
            for (int i = 1; i <= steps; i++) {
                double a = a1 + da * i / steps;
                Point next = new Point(c.x + r * Math.cos(a), c.y + r * Math.sin(a));
                res.add(new PathSegment(prev, next, false));
                prev = next;
            }
            return res;
        }
    }
    // --- 通用工具 ---
    private static double getIntersectT(Point a, Point b, Point c, Point d) {
        double det = (b.x - a.x) * (d.y - c.y) - (b.y - a.y) * (d.x - c.x);
        if (Math.abs(det) < 1e-10) return -1;
        double t = ((c.x - a.x) * (d.y - c.y) - (c.y - a.y) * (d.x - c.x)) / det;
        double u = ((c.x - a.x) * (b.y - a.y) - (c.y - a.y) * (b.x - a.x)) / det;
        return (t >= 0 && t <= 1 && u >= 0 && u <= 1) ? t : -1;
    }
    private static double distToSegment(Point p, Point a, Point b) {
        double l2 = (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y);
        if (l2 == 0) return distance(p, a);
        double t = ((p.x-a.x)*(b.x-a.x) + (p.y-a.y)*(b.y-a.y)) / l2;
        t = Math.max(0, Math.min(1, t));
        return distance(p, new Point(a.x + t*(b.x-a.x), a.y + t*(b.y-a.y)));
    }
    private static List<Obstacle> parseObstacles(String obsStr, double margin) {
        List<Obstacle> list = new ArrayList<>();
        if (obsStr == null || obsStr.isEmpty()) return list;
        Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(obsStr);
        while (m.find()) {
            List<Point> pts = parseCoordinates(m.group(1));
            if (pts.size() == 2) list.add(new CircleObstacle(pts.get(0), distance(pts.get(0), pts.get(1)) + margin));
            else if (pts.size() >= 3) {
                ensureCCW(pts);
                list.add(new PolyObstacle(getOffsetPolygon(pts, -margin))); // 负值外扩
            }
        }
        return list;
    }
    private static double findOptimalAngle(List<Point> poly) {
        double bestA = 0, minH = Double.MAX_VALUE;
        for (int i = 0; i < poly.size(); i++) {
            Point p1 = poly.get(i), p2 = poly.get((i + 1) % poly.size());
            double a = Math.atan2(p2.y - p1.y, p2.x - p1.x);
            double maxV = -Double.MAX_VALUE, minV = Double.MAX_VALUE;
            for (Point p : poly) {
                double v = p.y * Math.cos(a) - p.x * Math.sin(a);
                maxV = Math.max(maxV, v); minV = Math.min(minV, v);
            }
            if (maxV - minV < minH) { minH = maxV - minV; bestA = a; }
        }
        return bestA;
    }
    private static List<Point> parseCoordinates(String s) {
        List<Point> pts = new ArrayList<>();
        if (s == null || s.isEmpty()) return pts;
        List<Point> list = new ArrayList<>();
        for (String p : s.split(";")) {
            String[] xy = p.split(",");
            if (xy.length >= 2) pts.add(new Point(Double.parseDouble(xy[0]), Double.parseDouble(xy[1])));
            String[] xy = p.trim().split(",");
            if (xy.length == 2) list.add(new Point(Double.parseDouble(xy[0]), Double.parseDouble(xy[1])));
        }
        if (pts.size() > 1 && distance(pts.get(0), pts.get(pts.size() - 1)) < 1e-4) pts.remove(pts.size() - 1);
        return pts;
        return list;
    }
    // --- 数据结构 ---
    public static class Point {
        public double x, y;
        public Point(double x, double y) { this.x = x; this.y = y; }
    private static double distance(Point a, Point b) { return Math.hypot(a.x - b.x, a.y - b.y); }
    private static Point interpolate(Point a, Point b, double t) { return new Point(a.x+(b.x-a.x)*t, a.y+(b.y-a.y)*t); }
    private static Point rotatePoint(Point p, double a) { return new Point(p.x*Math.cos(a)-p.y*Math.sin(a), p.x*Math.sin(a)+p.y*Math.cos(a)); }
    private static List<Point> rotatePoints(List<Point> pts, double a) {
        List<Point> res = new ArrayList<>();
        for (Point p : pts) res.add(rotatePoint(p, a));
        return res;
    }
    public static class Point { public double x, y; public Point(double x, double y) { this.x = x; this.y = y; } }
    public static class PathSegment {
        public Point start, end;
        public boolean isMowing;
        public Point start, end; public boolean isMowing;
        public PathSegment(Point s, Point e, boolean m) { this.start = s; this.end = e; this.isMowing = m; }
        @Override
        public String toString() { return String.format("%.6f,%.6f;%.6f,%.6f", start.x, start.y, end.x, end.y); }
    }
}