使用坐标计算随机三角形的边界框

时间:2013-03-22 19:04:57

标签: haskell geometry bounding-box

我正在寻找一种合适的方法来计算三角形的矩形边界框,其中三个角为点 - (x1,y1),(x2,y2),(x3,y3)。

以下是我正在使用的数据类型(如建议的那样,我添加了更多构造函数):

data Shape =
     Circle Point Double |
     Rectangle Point Point |
     Triangle Point Point Point

边界框函数的形式应为“bounding :: Shape - > Shape”。 我也尝试了矩形和圆形的边界框:

bounding :: Shape -> Shape
bounding (Rectangle (Point x y) (Point z z1)) = (Rectangle (Point x y) (Point z z1))
bounding (Circle (Point p w) r) = (Rectangle (Point (p-r) (w-r)) (Point (p+r) (w+r)))

如果应该使用图形坐标系(其中(x,y)坐标应该被视为(x,-y)),这些是否正确?

有人可以帮助我吗? 附:不需要图形库。

3 个答案:

答案 0 :(得分:1)

你有什么尝试?你有任何代码吗?

你需要:

 data Shape = Triangle Point Point Point | Rectangle Point Point

假设x向右增加,y增加到向上。左上角将是(min {x1,x2,x3},max {y1,y2,y3}),你需要在右下角。


修改

x应向右增加,y向下增加。我添加了三角形,删除了不必要的括号和派生(Show)以便能够打印Shape数据类型。整个代码:

data Point = Point Double Double deriving (Show)

data Shape =
        Circle Point Double |
        Rectangle Point Point |
        Triangle Point Point Point deriving (Show)

bounding :: Shape -> Shape
bounding (Rectangle (Point x y) (Point z z1)) = Rectangle (Point x y) (Point z z1)
bounding (Circle (Point p w) r) = Rectangle (Point (p-r) (w-r)) (Point (p+r) (w+r))
bounding (Triangle (Point x1 y1) (Point x2 y2) (Point x3 y3)) = Rectangle 
        (Point (minimum [x1, x2, x3]) (minimum [y1, y2, y3])) 
        (Point (maximum [x1, x2, x3]) (maximum [y1, y2, y3]))

答案 1 :(得分:1)

基于@ dave4420的出色观察,我假设Rectangles与x / y轴对齐。

根据您对Circle的规则,显示最小x,y的点首先出现,x {y最大的点在Rectangle中排在第二位。

您应该坚持使用数字后缀xy,而不是发明pwz和{{1}等新名称这非常令人困惑。

z1的边界框是Rectangle本身。

Rectangle的边界框将是Triangle,其中包含来自任意点的最小和最大x,y。

Rectangle

答案 2 :(得分:1)

我只发布这个答案,指出边界框和矩形不是一回事。

data Point = Point Double Double   -- Point x y

data BoundingBox = BoundingBox Double Double Double Double
                            -- top    left   bottom right

data Shape
    = Circle Point Double
    | Rectangle Point Point Double
        -- yes, you need two points and a scalar to specify arbitrary rectangles
    | Triangle Point Point Point

boundingBox :: Shape -> BoundingBox
boundingBox (Circle (Point x y) r) = BoundingBox (y-r) (x-r) (y+r) (x+r)
boundingBox (Rectangle (Point x0 y0) (Point x1 y1) d)
        = BoundingBox (minimum ys) (minimum xs) (maximum ys) (maximum xs) where
    xs = [x0, x1, x1+dx, x0+dx]
    ys = [y0, y1, y1+dy, y0+dy]
    d' = d / ((x0-x1)^^2 + ((y0-y1)^^2)
    dx = d' * (y0-y1)
    dy = d' * (x1-x0)
boundingBox (Triangle (Point x0 y0) (Point x1 y1) (Point x2 y2))
        = BoundingBox (minimum ys) (minimum xs) (maximum ys) (maximum xs) where
    xs = [x0, x1, x2]
    ys = [y0, y1, y2]

作为练习,请考虑RectangleTriangle案例中的公共代码。 (用于查找和修复我在Rectangle案例中发现的任何错误的加分点。)