internal/atlas: add TestGCShader

Updates #2897
This commit is contained in:
Hajime Hoshi 2024-01-29 23:14:12 +09:00
parent f74d66e89a
commit 872ffc148d
2 changed files with 35 additions and 7 deletions

View File

@ -38,18 +38,20 @@ func NewShader(ir *shaderir.Program) *Shader {
}
}
func (s *Shader) finalize() {
// A function from finalizer must not be blocked, but disposing operation can be blocked.
// Defer this operation until it becomes safe. (#913)
appendDeferred(func() {
s.deallocate()
})
}
func (s *Shader) ensureShader() *graphicscommand.Shader {
if s.shader != nil {
return s.shader
}
s.shader = graphicscommand.NewShader(s.ir)
runtime.SetFinalizer(s, func(shader *Shader) {
// A function from finalizer must not be blocked, but disposing operation can be blocked.
// Defer this operation until it becomes safe. (#913)
appendDeferred(func() {
shader.deallocate()
})
})
runtime.SetFinalizer(s, (*Shader).finalize)
return s.shader
}

View File

@ -17,6 +17,7 @@ package atlas_test
import (
"image"
"image/color"
"runtime"
"testing"
"github.com/hajimehoshi/ebiten/v2/internal/atlas"
@ -78,3 +79,28 @@ func TestImageDrawTwice(t *testing.T) {
t.Errorf("got: %v, want: %v", got, want)
}
}
func TestGCShader(t *testing.T) {
s := atlas.NewShader(etesting.ShaderProgramFill(0xff, 0xff, 0xff, 0xff))
// Use the shader to initialize it.
const w, h = 1, 1
dst := atlas.NewImage(w, h, atlas.ImageTypeRegular)
vs := quadVertices(w, h, 0, 0, 1)
is := graphics.QuadIndices()
dr := image.Rect(0, 0, w, h)
dst.DrawTriangles([graphics.ShaderImageCount]*atlas.Image{}, vs, is, graphicsdriver.BlendCopy, dr, [graphics.ShaderImageCount]image.Rectangle{}, s, nil, graphicsdriver.FillAll)
// Ensure other objects are GCed, as GC appends deferred functions for collected objects.
runtime.GC()
// Get the difference of the number of deferred functions before and after s is GCed.
c := atlas.DeferredFuncCountForTesting()
runtime.KeepAlive(s)
runtime.GC()
diff := atlas.DeferredFuncCountForTesting() - c
if got, want := diff, 1; got != want {
t.Errorf("got: %d, want: %d", got, want)
}
}