张世豪
昨天 45a35805eb1e59972ad9a9c80815f2c030dc69bb
src/lujing/YixinglujingHaveObstacel.java
@@ -6,8 +6,11 @@
import java.util.List;
/**
 * 异形草地路径规划 - 避障增强版 V7.0
 * 优化:增加了多边形外扩稳定性、障碍物碰撞预判以及冗余路径消除。
 * 异形草地路径规划 - 避障增强版 V8.0
 * 修复说明:
 * 1. 修正了地块内缩和障碍物外扩的正负逻辑。
 * 2. 优化了多边形偏移算法,确保逆时针点序下正值内缩,负值外扩。
 * 3. 增强了障碍物解析的健壮性。
 */
public class YixinglujingHaveObstacel {
@@ -18,32 +21,99 @@
        double mowWidth = Double.parseDouble(widthStr);
        double safeMargin = Double.parseDouble(marginStr);
        // 1. 预处理地块(确保逆时针)
        // 1. 预处理地块(确保逆时针顺序)
        ensureCounterClockwise(rawPoints);
        List<Point> boundary = getOffsetPolygon(rawPoints, -safeMargin); // 内缩
        // 【核心修复】:对于逆时针多边形,正数是向内偏移(Inset)
        List<Point> boundary = getOffsetPolygon(rawPoints, safeMargin);
        if (boundary.size() < 3) return new ArrayList<>();
        // 2. 规划基础路径 (无障碍物状态)
        // 2. 确定最优角度并规划基础路径
        double bestAngle = findOptimalAngle(boundary);
        Point firstScanStart = getFirstScanPoint(boundary, mowWidth, bestAngle);
        List<Point> alignedBoundary = alignBoundaryStart(boundary, firstScanStart);
        List<PathSegment> baseLines = new ArrayList<>();
        // 第一阶段:围边
        // 第一阶段:围边路径
        for (int i = 0; i < alignedBoundary.size(); i++) {
            baseLines.add(new PathSegment(alignedBoundary.get(i), alignedBoundary.get((i + 1) % alignedBoundary.size()), true));
        }
        // 第二阶段:内部扫描
        // 第二阶段:生成内部扫描路径
        Point lastEdgePos = alignedBoundary.get(0);
        baseLines.addAll(generateGlobalScanPath(boundary, mowWidth, bestAngle, lastEdgePos));
        // 3. 处理障碍物:解析并执行外扩 (障碍物需向外扩 margin)
        // 3. 处理障碍物:解析并执行【外扩】
        // 【核心修复】:对于逆时针障碍物,负数是向外偏移(Outset)
        List<Obstacle> obstacles = parseObstacles(obstaclesStr, safeMargin);
        // 4. 路径裁剪与优化连接
        return optimizeAndClipPath(baseLines, obstacles);
    }
    private static List<Obstacle> parseObstacles(String obsStr, double margin) {
        List<Obstacle> obstacles = new ArrayList<>();
        if (obsStr == null || obsStr.trim().isEmpty()) return obstacles;
        for (String group : obsStr.split("\\$")) {
            List<Point> pts = parseCoordinates(group);
            if (pts.isEmpty()) continue;
            if (pts.size() == 2) {
                // 圆形障碍物:第一个点心,第二个点上一点,半径增加 margin
                double r = Math.hypot(pts.get(0).x - pts.get(1).x, pts.get(0).y - pts.get(1).y);
                obstacles.add(new CircleObstacle(pts.get(0), r + margin));
            } else if (pts.size() > 2) {
                // 多边形障碍物:确保逆时针,然后使用负 margin 进行【外扩】
                ensureCounterClockwise(pts);
                obstacles.add(new PolyObstacle(getOffsetPolygon(pts, -margin)));
            }
        }
        return obstacles;
    }
    /**
     * 多边形偏移算法:基于角平分线偏移
     * 在逆时针顺序下:offset > 0 为内缩,offset < 0 为外扩
     */
    private static List<Point> getOffsetPolygon(List<Point> points, double offset) {
        List<Point> result = new ArrayList<>();
        int n = points.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);
            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 < 1e-6 || l2 < 1e-6) continue;
            // 获取两条边的法向量(向左偏移)
            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-6) {
                bx = n1x; by = n1y;
            } else {
                bx /= bl; by /= bl;
            }
            // 计算偏移长度修正系数:1/sin(theta/2)
            double cosHalf = n1x * bx + n1y * by;
            double d = offset / Math.max(cosHalf, 0.1); // 避免分母过小导致无穷大
            // 限制最大位移量,防止极尖角畸变
            d = Math.signum(offset) * Math.min(Math.abs(d), Math.abs(offset) * 5);
            result.add(new Point(p2.x + bx * d, p2.y + by * d));
        }
        return result;
    }
    private static List<PathSegment> optimizeAndClipPath(List<PathSegment> originalPath, List<Obstacle> obstacles) {
        List<PathSegment> result = new ArrayList<>();
        Point currentPos = null;
@@ -52,6 +122,7 @@
            List<PathSegment> clipped = new ArrayList<>();
            clipped.add(segment);
            // 用每一个障碍物依次裁剪
            for (Obstacle obs : obstacles) {
                List<PathSegment> nextIter = new ArrayList<>();
                for (PathSegment s : clipped) {
@@ -61,11 +132,11 @@
            }
            for (PathSegment s : clipped) {
                // 优化点:消除长度几乎为0的无效线段
                // 剔除微小段
                if (Math.hypot(s.start.x - s.end.x, s.start.y - s.end.y) < 1e-4) continue;
                // 如果新段的起点与上段的终点不连贯,添加空走(非割草)路径
                if (currentPos != null && Math.hypot(currentPos.x - s.start.x, currentPos.y - s.start.y) > 0.01) {
                    // 添加空载路径
                    result.add(new PathSegment(currentPos, s.start, false));
                }
                result.add(s);
@@ -75,7 +146,7 @@
        return result;
    }
    // --- 障碍物模型 ---
    // --- 障碍物类定义 ---
    abstract static class Obstacle {
        abstract boolean isInside(Point p);
        abstract List<PathSegment> clipSegment(PathSegment seg);
@@ -87,7 +158,6 @@
        public PolyObstacle(List<Point> pts) {
            this.points = pts;
            // 预计算 AABB 边界框提升效率
            minX = minY = Double.MAX_VALUE;
            maxX = maxY = -Double.MAX_VALUE;
            for (Point p : pts) {
@@ -121,6 +191,7 @@
            for (int i = 0; i < ts.size() - 1; i++) {
                Point s = interpolate(seg.start, seg.end, ts.get(i));
                Point e = interpolate(seg.start, seg.end, ts.get(i + 1));
                // 检查中点是否在障碍物内
                if (!isInside(new Point((s.x + e.x) / 2, (s.y + e.y) / 2))) {
                    res.add(new PathSegment(s, e, seg.isMowing));
                }
@@ -162,57 +233,7 @@
        }
    }
    // --- 算法工具类 ---
    private static List<Obstacle> parseObstacles(String obsStr, double margin) {
        List<Obstacle> obstacles = new ArrayList<>();
        if (obsStr == null || obsStr.trim().isEmpty()) return obstacles;
        for (String group : obsStr.split("\\$")) {
            List<Point> pts = parseCoordinates(group);
            if (pts.size() == 2) {
                double r = Math.hypot(pts.get(0).x - pts.get(1).x, pts.get(0).y - pts.get(1).y);
                obstacles.add(new CircleObstacle(pts.get(0), r + margin));
            } else if (pts.size() > 2) {
                ensureCounterClockwise(pts);
                // 多边形外扩:offset 为正
                obstacles.add(new PolyObstacle(getOffsetPolygon(pts, margin)));
            }
        }
        return obstacles;
    }
    /**
     * 优化后的多边形外扩/内缩算法
     * @param offset 正数为外扩,负数为内缩
     */
    private static List<Point> getOffsetPolygon(List<Point> points, double offset) {
        List<Point> result = new ArrayList<>();
        int n = points.size();
        for (int i = 0; i < n; i++) {
            Point p1 = points.get((i - 1 + n) % n), p2 = points.get(i), p3 = points.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 < 1e-6 || l2 < 1e-6) continue;
            // 法向量
            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-6) { bx = n1x; by = n1y; } else { bx /= bl; by /= bl; }
            // 修正距离
            double sinHalf = n1x * bx + n1y * by;
            double d = offset / Math.max(sinHalf, 0.1);
            result.add(new Point(p2.x + bx * d, p2.y + by * d));
        }
        return result;
    }
    // --- 内部算法与数学支持 ---
    private static List<PathSegment> generateGlobalScanPath(List<Point> polygon, double width, double angle, Point currentPos) {
        List<PathSegment> segments = new ArrayList<>();
@@ -250,7 +271,6 @@
        return segments;
    }
    // --- 基础数学函数 ---
    private static double getIntersectionT(Point a, Point b, Point c, Point d) {
        double ux = b.x - a.x, uy = b.y - a.y, vx = d.x - c.x, vy = d.y - c.y;
        double det = vx * uy - vy * ux;
@@ -263,7 +283,8 @@
    }
    private static Point rotatePoint(Point p, double ang) {
        return new Point(p.x * Math.cos(ang) - p.y * Math.sin(ang), p.x * Math.sin(ang) + p.y * Math.cos(ang));
        double cos = Math.cos(ang), sin = Math.sin(ang);
        return new Point(p.x * cos - p.y * sin, p.x * sin + p.y * cos);
    }
    private static List<Double> getXIntersections(List<Point> poly, double y) {
@@ -304,20 +325,22 @@
        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 = 0, miY = Double.MAX_VALUE, maY = -Double.MAX_VALUE;
            double miY = Double.MAX_VALUE, maY = -Double.MAX_VALUE;
            for (Point p : poly) {
                Point r = rotatePoint(p, -a);
                miY = Math.min(miY, r.y); maY = Math.max(maY, r.y);
            }
            h = maY - miY;
            if (h < minH) { minH = h; bestA = a; }
            if (maY - miY < minH) { minH = maY - miY; bestA = a; }
        }
        return bestA;
    }
    private static void ensureCounterClockwise(List<Point> pts) {
        double s = 0;
        for (int i = 0; i < pts.size(); i++) s += (pts.get((i + 1) % pts.size()).x - pts.get(i).x) * (pts.get((i + 1) % pts.size()).y + pts.get(i).y);
        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);
    }