Cyrus-Beck线裁剪算法

时间:2014-03-30 20:28:32

标签: python graphics

我尝试为行剪辑实现Cyrus-Beck algorithm。但它不起作用。我无法找到问题......请帮助。

结构:

sign = functools.partial(math.copysign, 1)
mult = lambda a, b: a.x * b.x + a.y * b.y


class Point(object):
    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)


class Line(object):
    def __init__(self, begin, end):
        self.begin = begin
        self.end = end

    @property
    def direction(self):
        return Point(self.end.x - self.begin.x, self.end.y - self.begin.y)

    @property
    def normal(self):
        return Point(self.end.y - self.begin.y, self.begin.x - self.end.x)

这是算法和class Polygon

class Polygon(object):
    def __init__(self, points):
        self.count = len(points)
        self.edges = []
        for i in xrange(self.count-1):
            self.edges.append(Line(points[i], points[i+1]))

        self.edges.append(Line(points[-1], points[0]))
    # algorithm!! 
    def cyruse_beck(self, l):
        t_begin = 0.0
        t_end = 1.0
        dirL = l.direction
        for edge in self.edges:
            dir_edg = edge.direction
            Q = Point(l.begin.x - dir_edg.x, l.begin.y - dir_edg.y)
            N = edge.normal
            Pn = mult(dirL, N)
            Qn = mult(Q, N)
            if Pn == 0:
                if Qn < 0:
                    return False
            else:
                t = -Qn / Pn
                if Pn < 0:
                    if t < t_begin:
                        return False
                    t_end = min(t_end, t)
                else:
                    if t > t_end:
                        return False
                    t_begin = max(t_begin, t)

        if t_end > t_begin:
            if t_begin > 0:
                l.begin = Point(l.begin.x + t_begin * dirL.x, l.begin.y + t_begin * dirL.y)
            if t_end < 1:
                l.end = Point(l.begin.x + t_end * dirL.x, l.begin.y + t_end * dirL.y)
        else:
            return False
        return True

帮我在代码中找到错误。

0 个答案:

没有答案