internal/bsp: Fix algorithm

This commit is contained in:
Hajime Hoshi 2018-02-26 11:20:20 +09:00
parent ccfa8f7ef8
commit ed2bd6defc
2 changed files with 22 additions and 9 deletions

View File

@ -50,6 +50,19 @@ func (n *Node) Region() (x, y, width, height int) {
return n.x, n.y, n.width, n.height
}
// square returns a float value indicating how much the given rectangle is close to a square.
// If the given rectangle is square, this return 1 (maximum value).
// Otherwise, this returns a value in [0, 1).
func square(width, height int) float64 {
if width == 0 && height == 0 {
return 0
}
if width <= height {
return float64(width) / float64(height)
}
return float64(height) / float64(width)
}
func (n *Node) alloc(width, height int) *Node {
if n.width < width || n.height < height {
return nil
@ -62,7 +75,7 @@ func (n *Node) alloc(width, height int) *Node {
n.used = true
return n
}
if n.height == height || (n.width != width && width <= height) {
if square(n.width-width, n.height) >= square(n.width, n.height-height) {
// Split vertically
n.child0 = &Node{
x: n.x,

View File

@ -91,9 +91,9 @@ func TestBSP(t *testing.T) {
{0, 400, 50, 50},
{100, 0, 200, 200},
nil,
{300, 0, 500, 500},
{100, 200, 500, 500},
nil,
{100, 200, 100, 100},
{0, 450, 100, 100},
nil,
{0, 200, 100, 200},
},
@ -129,17 +129,17 @@ func TestBSP(t *testing.T) {
{0, 768, 256, 256},
{256, 0, 256, 256},
{512, 0, 256, 256},
{768, 0, 256, 256},
{256, 256, 256, 256},
{256, 512, 256, 256},
{256, 768, 256, 256},
{512, 0, 256, 256},
{512, 256, 256, 256},
{768, 256, 256, 256},
{512, 512, 256, 256},
{512, 768, 256, 256},
{768, 0, 256, 256},
{768, 256, 256, 256},
{768, 512, 256, 256},
{768, 768, 256, 256},
@ -164,9 +164,9 @@ func TestBSP(t *testing.T) {
{0, 300, 300, 300},
{0, 600, 300, 300},
{300, 0, 300, 300},
{600, 0, 300, 300},
{300, 300, 300, 300},
{300, 600, 300, 300},
{600, 0, 300, 300},
{600, 300, 300, 300},
{600, 600, 300, 300},
nil,