Skip to content

Commit

Permalink
mipmap: Bug fix: Scale could be Inf/0 and caused a forever loop
Browse files Browse the repository at this point in the history
  • Loading branch information
hajimehoshi committed Oct 21, 2020
1 parent 3202826 commit 02094c2
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
21 changes: 21 additions & 0 deletions image_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2253,3 +2253,24 @@ func TestImageZeroTriangle(t *testing.T) {
is := []uint16{}
dst.DrawTriangles(vs, is, src, nil)
}

// Issue #1398
func TestImageDrawImageTooBigScale(t *testing.T) {
dst, _ := NewImage(1, 1, FilterDefault)
src, _ := NewImage(1, 1, FilterDefault)

op := &DrawImageOptions{}
op.GeoM.Scale(1e20, 1e20)
dst.DrawImage(src, op)
}

// Issue #1398
func TestImageDrawImageTooSmallScale(t *testing.T) {
dst, _ := NewImage(1, 1, FilterDefault)
src, _ := NewImage(1, 1, FilterDefault)

op := &DrawImageOptions{}
op.Filter = FilterLinear
op.GeoM.Scale(1e-10, 1e-10)
dst.DrawImage(src, op)
}
25 changes: 20 additions & 5 deletions internal/mipmap/mipmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,8 @@ func (m *Mipmap) disposeMipmaps() {

// mipmapLevel returns an appropriate mipmap level for the given distance.
func mipmapLevelFromDistance(dx0, dy0, dx1, dy1, sx0, sy0, sx1, sy1 float32, filter driver.Filter) int {
const maxScale = 6

if filter == driver.FilterScreen {
return 0
}
Expand All @@ -288,6 +290,19 @@ func mipmapLevelFromDistance(dx0, dy0, dx1, dy1, sx0, sy0, sx1, sy1 float32, fil
}
scale := d / s

// Scale can be infinite when the specified scale is extremely big (#1398).
if math.IsInf(float64(scale), 0) {
if filter == driver.FilterNearest {
return -maxScale
}
return 0
}

// Scale can be zero when the specified scale is extremely small (#1398).
if scale == 0 {
return 0
}

// Use 'negative' mipmap to render edges correctly (#611, #907).
// It looks like 128 is the enlargement factor that causes edge missings to pass the test TestImageStretch,
// but we use 32 here for environments where the float precision is low (#1044, #1270).
Expand Down Expand Up @@ -316,10 +331,10 @@ func mipmapLevelFromDistance(dx0, dy0, dx1, dy1, sx0, sy0, sx1, sy1 float32, fil
}
}

// If tooBigScale is 64, level -6 means that the maximum scale is 64 * 2^6 = 4096. This should be
// If tooBigScale is 32, level -6 means that the maximum scale is 32 * 2^6 = 2048. This should be
// enough.
if level < -6 {
level = -6
if level < -maxScale {
level = -maxScale
}
return level
}
Expand Down Expand Up @@ -352,8 +367,8 @@ func mipmapLevelFromDistance(dx0, dy0, dx1, dy1, sx0, sy0, sx1, sy1 float32, fil
}
}

if level > 6 {
level = 6
if level > maxScale {
level = maxScale
}

return level
Expand Down

0 comments on commit 02094c2

Please sign in to comment.