forked from AllenDang/giu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Texture.go
79 lines (63 loc) · 1.94 KB
/
Texture.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package giu
import (
"fmt"
"image"
"runtime"
"github.com/AllenDang/imgui-go"
"github.com/faiface/mainthread"
)
// Texture represents imgui.TextureID.
// It is base unit of images in imgui.
type Texture struct {
id imgui.TextureID
}
type textureLoadRequest struct {
img image.Image
cb func(*Texture)
}
type loadImageResult struct {
id imgui.TextureID
err error
}
// EnqueueNewTextureFromRgba adds loading texture request to loading queue
// it allows us to run this method in main loop
// NOTE: remember to call it after NewMasterWindow!
func EnqueueNewTextureFromRgba(rgba image.Image, loadCb func(t *Texture)) {
Assert((Context.textureLoadingQueue != nil), "", "EnqueueNewTextureFromRgba", "you need to call EnqueueNewTextureFromRgba after giu.NewMasterWindow call!")
Context.textureLoadingQueue.Add(textureLoadRequest{rgba, loadCb})
}
// NewTextureFromRgba creates a new texture from image.Image and, when it is done, calls loadCallback(loadedTexture).
func NewTextureFromRgba(rgba image.Image, loadCallback func(*Texture)) {
loadTexture(rgba, loadCallback)
}
func loadTexture(rgba image.Image, loadCallback func(*Texture)) {
go func() {
Update()
result := mainthread.CallVal(func() any {
texID, err := Context.renderer.LoadImage(ImageToRgba(rgba))
return &loadImageResult{id: texID, err: err}
})
tid, ok := result.(*loadImageResult)
switch {
case !ok:
panic("giu: NewTextureFromRgba: unexpected error occurred")
case tid.err != nil:
panic(fmt.Sprintf("giu: NewTextureFromRgba: error loading texture: %v", tid.err))
}
texture := Texture{id: tid.id}
// Set finalizer
runtime.SetFinalizer(&texture, (*Texture).release)
// execute callback
loadCallback(&texture)
}()
}
// ToTexture converts imgui.TextureID to Texture.
func ToTexture(textureID imgui.TextureID) *Texture {
return &Texture{id: textureID}
}
func (t *Texture) release() {
Update()
mainthread.Call(func() {
Context.renderer.ReleaseImage(t.id)
})
}