python中点线裁剪算法

时间:2014-03-28 21:29:14

标签: python algorithm graphics geometry

python(2.7)中的这个中点算法不起作用。他不会退出递归。哪里出错了?请帮帮我。

# Where is point
def vcode(rect, p):
    value = 0
    if p.x < rect.x_min:
        value += LEFT
    if p.x >= rect.x_max:
        value += RIGHT
    if p.y < rect.y_min:
        value += BOT
    if p.y >= rect.y_max:
        value += TOP

    return value

# algorithm
def average_point(rect, p1, p2, count=0):
    code_a = vcode(rect, p1)
    code_b = vcode(rect, p2)
    if math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)) < EPS:
        return
    if not (code_a | code_b):
        return
    if code_a & code_b:
        return
    mid = Point((p2.x+p1.x)/2.0, (p2.y+p1.y)/2.0)
    count += 1
    average_point(rect, p1, mid, count)
    mid.x = mid.x+1
    mid.y = mid.y+1
    average_point(rect, mid, p2, count)
    return count


p1,p2是Point( class, fields(x, y));

rect是Rectangle( class, fields(x_min, y_min, x_max, y_max));

1 个答案:

答案 0 :(得分:1)

你的代码工作正常,除了它在第一次调用方法时返回count的最终值。因此,count始终为1.要更正此问题,您需要将count设置为average_point的返回值。然后,您的代码将如下所示:

# algorithm
def average_point(rect, p1, p2, count=0):
    returnArray = []
    code_a = vcode(rect, p1)
    code_b = vcode(rect, p2)
    if math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)) < EPS:
        returnArray.append(count)
        returnArray.append(p1)
        returnArray.append(p2)
        return returnArray
    if not (code_a | code_b):
        returnArray.append(count)
        returnArray.append(p1)
        returnArray.append(p2)
        return returnArray
    if code_a & code_b:
        returnArray.append(count)
        returnArray.append(p1)
        returnArray.append(p2)
        return returnArray
    mid = Point((p2.x+p1.x)/2.0, (p2.y+p1.y)/2.0)
    count += 1
    returnArray = average_point(rect, p1, mid, count)
    mid.x = mid.x+1
    mid.y = mid.y+1
    returnArray = average_point(rect, mid, p2, count)
    return returnArray

这将在每次迭代时替换count值,并且确保添加return count,否则它将无法获得正确的值。

这也包括索引1和2中的点,因为在python中你可以在数组中有多个“类型”,这样你就可以返回两个点和计数。