如何使用python来证明两个线段是否在AutoCAD中相交

时间:2019-06-18 15:08:59

标签: python autocad

如果有两条线段(不是线段),我怎么知道它们是否被python相交?线方程定义了那些线段相交,即使它们彼此不接触也是如此,因为线方程不断延伸线。

example

段是否彼此到达,下面的代码返回“相交”。

def intersection(s1, s2):
    segment_endpoints = []
    left = max(min(s1[0], s1[2]), min(s2[0], s2[2]))
    right = min(max(s1[0], s1[2]), max(s2[0], s2[2]))
    top = max(min(s1[1], s1[3]), min(s2[1], s2[3]))
    bottom = min(max(s1[1], s1[3]), max(s2[1], s2[3]))
    if top > bottom or left > right:
        segment_endpoints = []
    elif top == bottom and left == right:
        segment_endpoints.append(left)
        segment_endpoints.append(top)
    else:
        segment_endpoints.append(left)
        segment_endpoints.append(bottom)
        segment_endpoints.append(right)
        segment_endpoints.append(top)
    return segment_endpoints


def intersectLines(pt1, pt2, ptA, ptB):
    DET_TOLERANCE = 0.00000001

    # the first line is pt1 + r*(pt2-pt1)
    # in component form:
    x1, y1 = pt1;
    x2, y2 = pt2
    dx1 = x2 - x1;
    dy1 = y2 - y1

    # the second line is ptA + s*(ptB-ptA)
    x, y = ptA;
    xB, yB = ptB;
    dx = xB - x;
    dy = yB - y;

    DET = (-dx1 * dy + dy1 * dx)

    if math.fabs(DET) < DET_TOLERANCE: return (0, 0, 0, 0, 0)

    # now, the determinant should be OK
    DETinv = 1.0 / DET

    # find the scalar amount along the "self" segment
    r = DETinv * (-dy * (x - x1) + dx * (y - y1))

    # find the scalar amount along the input line
    s = DETinv * (-dy1 * (x - x1) + dx1 * (y - y1))

    # return the average of the two descriptions
    xi = (x1 + r * dx1 + x + s * dx) / 2.0
    yi = (y1 + r * dy1 + y + s * dy) / 2.0
    return (xi, yi, 1, r, s)



line_list = [object for object in acad.iter_objects() if(object.objectName == "AcDbLine")]
print("Line_list:", len(line_list))


c = 0
for x in range(len(line_list)):
    for y in range(len(line_list)):
        if x == y: continue
        c += 1
        s1 = line_list[x].startpoint[:2] + line_list[x].endpoint[:2]
        s2 = line_list[y].startpoint[:2] + line_list[y].endpoint[:2]

        print(c, "x:", x, "y:", y, "s1:", s1, "s2:", s2)
        print(intersectLines(line_list[x].startpoint[:2] , line_list[x].endpoint[:2], line_list[y].startpoint[:2] , line_list[y].endpoint[:2] ))

1 个答案:

答案 0 :(得分:1)

我认为您只是错过了检查交点pt是否在两个部分的边界框内的检查,即xi必须在x1和x2之间。 y相同-对于两个段。考虑两条线x = y和y =1。它们在1,1相交。但是,如果您的细分是从(0,0),(0.5,0.5)定义的,则它不会相交。