feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+86
@@ -0,0 +1,86 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// BenchmarkRenderSprites draws frames of a 2D game at 1280×720 (gputest's
|
||||
// SpriteScene, tiles 2 times as large: about 1,800 sprites of one sheet)
|
||||
// and reads each back, which waits for it. Where no GPU runs it, Mesa's
|
||||
// llvmpipe draws on the CPU, so the time is mostly its own.
|
||||
func BenchmarkRenderSprites(b *testing.B) {
|
||||
benchRender(b, gputest.SpriteScene(1280, 720, 2, 3, 300))
|
||||
}
|
||||
|
||||
// BenchmarkRenderEmpty draws frames of nothing at 1280×720: what the
|
||||
// sprites' frames spend besides them.
|
||||
func BenchmarkRenderEmpty(b *testing.B) {
|
||||
benchRender(b, &scene.Scene{Width: 1280, Height: 720, Clear: scene.Color{A: 255}})
|
||||
}
|
||||
|
||||
func benchRender(b *testing.B, s *scene.Scene) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
o, err := NewOffscreen(false, s.Width, s.Height)
|
||||
if err != nil {
|
||||
b.Skip(err)
|
||||
}
|
||||
defer o.Release()
|
||||
for b.Loop() {
|
||||
if _, err := o.Render(s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkVideoFrameRGBA draws a new 1920×1080 frame of video each
|
||||
// frame the way video drew before frames had surfaces: converted to RGBA
|
||||
// on the CPU (as a decoder in Go would, or the CPU renderer does) and
|
||||
// uploaded, 8 MB a frame.
|
||||
func BenchmarkVideoFrameRGBA(b *testing.B) {
|
||||
img := gputest.NV12Frame(1920, 1080, scene.BT709)
|
||||
rgb := scene.NewImageRGBA(1920, 1080, nil)
|
||||
s := videoBenchScene(rgb)
|
||||
benchVideo(b, s, func() {
|
||||
rgb.Pix = img.Surface.RGBA(rgb.Pix, 1920, 1080)
|
||||
rgb.Changed()
|
||||
})
|
||||
}
|
||||
|
||||
// BenchmarkVideoFrameNV12 draws a new 1920×1080 frame of video each frame
|
||||
// from its NV12 planes, as GStreamer leaves them: 3 MB uploaded, and
|
||||
// converted in the shader.
|
||||
func BenchmarkVideoFrameNV12(b *testing.B) {
|
||||
img := gputest.NV12Frame(1920, 1080, scene.BT709)
|
||||
s := videoBenchScene(img)
|
||||
benchVideo(b, s, img.Changed)
|
||||
}
|
||||
|
||||
func videoBenchScene(img *scene.Image) *scene.Scene {
|
||||
return &scene.Scene{Width: 1280, Height: 720, Clear: scene.Color{A: 255}, Ops: []scene.Op{{
|
||||
Kind: scene.OpImage, Rect: scene.Rect{W: 1280, H: 720}, Image: img, Src: scene.Rect{W: 1920, H: 1080},
|
||||
}}}
|
||||
}
|
||||
|
||||
func benchVideo(b *testing.B, s *scene.Scene, next func()) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
o, err := NewOffscreen(false, s.Width, s.Height)
|
||||
if err != nil {
|
||||
b.Skip(err)
|
||||
}
|
||||
defer o.Release()
|
||||
b.SetBytes(1920 * 1080 * 4)
|
||||
for b.Loop() {
|
||||
next()
|
||||
if _, err := o.Render(s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Canvases draw into textures as the CPU renderer draws them into pixels,
|
||||
// shown the right way up although GL's rows go up, and once each.
|
||||
func TestCanvases(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
s := gputest.CanvasScene()
|
||||
read := offscreen(t, api.es, s.Width, s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
for frame := range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-canvas", read(), s.Width*4, s)
|
||||
if frame == 0 {
|
||||
s.Canvases = nil
|
||||
}
|
||||
}
|
||||
if len(r.canvases) != 3 {
|
||||
t.Errorf("%d canvas textures, want 3", len(r.canvases))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A transient canvas's texture stays while frames draw it, and goes once
|
||||
// they stop, though the canvas is still about; another canvas's stays
|
||||
// until it is collected.
|
||||
func TestTransientCanvas(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
offscreen(t, api.es, 64, 64)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
layer, kept := scene.NewCanvas(64, 64), scene.NewCanvas(64, 64)
|
||||
layer.Transient = true
|
||||
s := &scene.Scene{Width: 64, Height: 64, Canvases: []*scene.Image{layer, kept}}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.sweep()
|
||||
if r.canvases[layer.ID()] == nil || r.canvases[kept.ID()] == nil {
|
||||
t.Fatal("a sweep after the frame that drew them freed a canvas's texture")
|
||||
}
|
||||
r.frame++ // a frame that draws neither
|
||||
r.sweep()
|
||||
if r.canvases[layer.ID()] != nil || r.canvases[kept.ID()] == nil {
|
||||
t.Errorf("transient canvas kept %v, other kept %v", r.canvases[layer.ID()] != nil, r.canvases[kept.ID()] != nil)
|
||||
}
|
||||
runtime.KeepAlive(layer)
|
||||
runtime.KeepAlive(kept)
|
||||
})
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// TestPartialFramesMatchWhole draws random scenes changing a little at a
|
||||
// time into a framebuffer that keeps what was drawn, as a GtkGLArea's,
|
||||
// each frame only where it changed, and requires the bytes of each frame
|
||||
// drawn whole, over an opaque color and a translucent one. Now and then
|
||||
// the framebuffer loses what it held, as GTK makes the area's buffers
|
||||
// anew, which Invalidate tells.
|
||||
func TestPartialFramesMatchWhole(t *testing.T) {
|
||||
seeds := uint64(12)
|
||||
if testing.Short() {
|
||||
seeds = 6
|
||||
}
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
read := offscreen(t, api.es, 320, 240)
|
||||
var outer int32
|
||||
glGetIntegerv(glFramebufferBinding, &outer)
|
||||
// The frames drawn whole go into a framebuffer of their own.
|
||||
tex := newTexture(glRGBA8, glRGBA, 320, 240, nil, 0)
|
||||
var fb uint32
|
||||
glGenFramebuffers(1, &fb)
|
||||
glBindFramebuffer(glFramebuffer, fb)
|
||||
glFramebufferTexture2D(glFramebuffer, glColorAttachment0, glTexture2D, tex, 0)
|
||||
defer func() {
|
||||
glDeleteFramebuffers(1, &fb)
|
||||
glDeleteTextures(1, &tex)
|
||||
}()
|
||||
frames, partial := 0, 0
|
||||
for seed := range seeds {
|
||||
m := gputest.NewChanging(seed)
|
||||
if seed%3 == 2 {
|
||||
m.Clear = scene.Color{R: 20, G: 40, B: 200, A: 77}
|
||||
}
|
||||
s := m.Scene()
|
||||
// Renderers of their own, as each scene has an atlas of its own.
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Partial = true
|
||||
whole, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for step := range 30 {
|
||||
what := "first"
|
||||
if step > 0 {
|
||||
what = m.Change(s)
|
||||
}
|
||||
if step%11 == 10 {
|
||||
// GTK made the buffers anew: what they hold is undefined.
|
||||
glBindFramebuffer(glFramebuffer, uint32(outer))
|
||||
glClearColor(1, 0, 1, 1)
|
||||
glClear(glColorBufferBit)
|
||||
r.Invalidate()
|
||||
what += ", invalidated"
|
||||
}
|
||||
glBindFramebuffer(glFramebuffer, uint32(outer))
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := read()
|
||||
frames++
|
||||
part := "whole"
|
||||
if r.redrew != redrewWhole {
|
||||
partial++
|
||||
part = r.part.String()
|
||||
}
|
||||
glBindFramebuffer(glFramebuffer, fb)
|
||||
if err := whole.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := read()
|
||||
if !bytes.Equal(got, want) {
|
||||
n := 0
|
||||
for i := range got {
|
||||
if got[i] != want[i] {
|
||||
n++
|
||||
}
|
||||
}
|
||||
t.Fatalf("seed %d, step %d (%s), redrew %s: %d bytes differ from the frame drawn whole", seed, step, what, part, n)
|
||||
}
|
||||
}
|
||||
r.Release()
|
||||
whole.Release()
|
||||
}
|
||||
if partial < frames/3 {
|
||||
t.Errorf("%d frames of %d drawn in part", partial, frames)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestPartialFramesApart checks that two changes in opposite corners, a
|
||||
// spinner's and a progress bar's, redraw two rectangles, not all between,
|
||||
// and the bytes of the frame drawn whole.
|
||||
func TestPartialFramesApart(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
read := offscreen(t, api.es, 320, 240)
|
||||
s := gputest.NewChanging(5).Scene()
|
||||
s.Ops = append(s.Ops,
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 4, Y: 4, W: 12, H: 12}, Radii: scene.Uniform(6), Color: scene.Color{R: 200, A: 255}},
|
||||
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 250, Y: 226, W: 60, H: 6}, Radii: scene.Uniform(3), Color: scene.Color{B: 200, A: 255}})
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
r.Partial = true
|
||||
whole, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer whole.Release()
|
||||
for step := range 4 {
|
||||
if step > 0 {
|
||||
n := len(s.Ops)
|
||||
s.Ops[n-2].Color.G += 60
|
||||
s.Ops[n-1].Rect.W -= 7
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := read()
|
||||
if step > 0 && (r.redrew != redrewPart || len(r.part.Rects) != 2) {
|
||||
t.Errorf("step %d redrew %v: %s", step, r.redrew, r.part.String())
|
||||
}
|
||||
if err := whole.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, read()) {
|
||||
t.Fatalf("step %d, redrew %s: differs from the frame drawn whole", step, r.part.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
// The head and the tail of an effect's fragment shader (scene.Effect):
|
||||
// after shader.glsl with EFFECT defined, the head declares what an effect
|
||||
// reads, the effect's source follows, then the tail, after the line
|
||||
// "// effect", draws its instances with it.
|
||||
|
||||
uniform sampler2D uBackdrop;
|
||||
|
||||
// What an effect reads of its instance.
|
||||
struct Effect {
|
||||
vec4 rect; // x, y, width, height in pixels
|
||||
vec4 radii; // top-left, top-right, bottom-right, bottom-left, circular
|
||||
vec4 p0, p1, p2, p3, p4;
|
||||
vec4 area; // where the backdrop's area starts in the frame, and its size in texels
|
||||
float down; // the size of the squares the backdrop averages
|
||||
vec4 transform0, transform1, transform2;
|
||||
};
|
||||
|
||||
vec2 framePoint(Effect e, vec2 q) {
|
||||
vec3 h = vec3(dot(e.transform0.xyz, vec3(q, 1.0)), dot(e.transform1.xyz, vec3(q, 1.0)),
|
||||
dot(vec3(e.transform2.xy, 1.0 - 2.0 * e.transform2.z), vec3(q, 1.0)));
|
||||
return h.xy / h.z;
|
||||
}
|
||||
|
||||
vec3 backdropAt(ivec2 p, ivec2 size) { return texelFetch(uBackdrop, clamp(p, ivec2(0), size - 1), 0).rgb; }
|
||||
|
||||
// sampleBackdrop returns the backdrop at q, in the frame's pixels,
|
||||
// premultiplied, filtered bilinearly from its texels as
|
||||
// scene.BackdropImage.Sample does.
|
||||
vec3 sampleBackdrop(Effect e, vec2 q) {
|
||||
q = framePoint(e, q);
|
||||
vec2 u = (q - e.area.xy) / e.down - 0.5;
|
||||
vec2 f = floor(u);
|
||||
vec2 w = u - f;
|
||||
ivec2 p = ivec2(f);
|
||||
ivec2 size = ivec2(e.area.zw);
|
||||
vec3 top = backdropAt(p, size) * (1.0 - w.x) + backdropAt(p + ivec2(1, 0), size) * w.x;
|
||||
vec3 bot = backdropAt(p + ivec2(0, 1), size) * (1.0 - w.x) + backdropAt(p + ivec2(1, 1), size) * w.x;
|
||||
return top * (1.0 - w.y) + bot * w.y;
|
||||
}
|
||||
|
||||
// effect
|
||||
|
||||
void main() {
|
||||
Frame fr = frameOf();
|
||||
vec2 p = vPoint.xy;
|
||||
Effect e = Effect(vRect, abs(vRadii), vInner, vColor, vColor2, vBorder, vGrad, vWidths, vParams.z,
|
||||
vTransform0, vTransform1, vTransform2);
|
||||
if (vParams.y > 0.5) {
|
||||
// A mask glyph a shader fills (scene.EffectOp.Glyphs), as the
|
||||
// renderer's own shader draws one, its paint the shader's color.
|
||||
vec4 c = effect(p, e);
|
||||
float glyphCov = vTransform0.w > 0.5 ? localCoverage(p, vRect, vec4(0.0), 1.0, fr) : 1.0;
|
||||
fragColor = c * (textCoverage(sampleLocal(uMask, vPoint.zw, vWidths, vTransform0.w).r, unpremul(c), vInner.x,
|
||||
vInner.y, vRadii) *
|
||||
glyphCov * clipCoverage() * vParams.w);
|
||||
} else {
|
||||
fragColor = effect(p, e) * (localCoverage(p, vRect, vRadii, vTransform0.w, fr) * clipCoverage() * vParams.w);
|
||||
}
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package gl
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// EGL's functions, which make the contexts of OpenGL ES and the surfaces
|
||||
// of the windows they draw into, on Android.
|
||||
var (
|
||||
eglGetDisplay func(id uintptr) uintptr
|
||||
eglInitialize func(display uintptr, major, minor *int32) uint32
|
||||
eglChooseConfig func(display uintptr, attribs *int32, configs *uintptr, size int32, n *int32) uint32
|
||||
eglCreateContext func(display, config, share uintptr, attribs *int32) uintptr
|
||||
eglCreateWindowSurface func(display, config, window uintptr, attribs *int32) uintptr
|
||||
eglMakeCurrent func(display, draw, read, context uintptr) uint32
|
||||
eglSwapBuffers func(display, surface uintptr) uint32
|
||||
eglDestroySurface func(display, surface uintptr) uint32
|
||||
eglDestroyContext func(display, context uintptr) uint32
|
||||
eglGetCurrentContext func() uintptr
|
||||
eglGetError func() int32
|
||||
)
|
||||
|
||||
const (
|
||||
eglNone = 0x3038
|
||||
eglRenderableType = 0x3040
|
||||
eglOpenGLES3Bit = 0x40
|
||||
eglSurfaceType = 0x3033
|
||||
eglWindowBit = 0x4
|
||||
eglRedSize = 0x3024
|
||||
eglGreenSize = 0x3023
|
||||
eglBlueSize = 0x3022
|
||||
eglAlphaSize = 0x3021
|
||||
eglContextVersion = 0x3098
|
||||
)
|
||||
|
||||
func loadEGL() error {
|
||||
lib, err := purego.Dlopen("libEGL.so", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("gl: cannot load libEGL: %w", err)
|
||||
}
|
||||
for name, f := range map[string]any{
|
||||
"eglGetDisplay": &eglGetDisplay, "eglInitialize": &eglInitialize, "eglChooseConfig": &eglChooseConfig,
|
||||
"eglCreateContext": &eglCreateContext, "eglCreateWindowSurface": &eglCreateWindowSurface,
|
||||
"eglMakeCurrent": &eglMakeCurrent, "eglSwapBuffers": &eglSwapBuffers, "eglDestroySurface": &eglDestroySurface,
|
||||
"eglDestroyContext": &eglDestroyContext, "eglGetCurrentContext": &eglGetCurrentContext, "eglGetError": &eglGetError,
|
||||
} {
|
||||
sym, err := purego.Dlsym(lib, name)
|
||||
if err != nil || sym == 0 {
|
||||
return fmt.Errorf("gl: libEGL lacks %s", name)
|
||||
}
|
||||
purego.RegisterFunc(f, sym)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Window is a window's surface (an ANativeWindow) and the context of
|
||||
// OpenGL ES 3 that draws into it.
|
||||
type Window struct {
|
||||
display, context, surface uintptr
|
||||
}
|
||||
|
||||
// NewWindow makes a context and a surface for an ANativeWindow, the
|
||||
// context current.
|
||||
func NewWindow(native uintptr) (*Window, error) {
|
||||
if native == 0 {
|
||||
return nil, errors.New("gl: no window")
|
||||
}
|
||||
if err := load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w := &Window{display: eglGetDisplay(0)}
|
||||
if w.display == 0 || eglInitialize(w.display, nil, nil) == 0 {
|
||||
return nil, fmt.Errorf("gl: EGL has no display (%#x)", eglGetError())
|
||||
}
|
||||
attribs := []int32{eglRenderableType, eglOpenGLES3Bit, eglSurfaceType, eglWindowBit,
|
||||
eglRedSize, 8, eglGreenSize, 8, eglBlueSize, 8, eglAlphaSize, 8, eglNone}
|
||||
var config uintptr
|
||||
var n int32
|
||||
if eglChooseConfig(w.display, &attribs[0], &config, 1, &n) == 0 || n == 0 {
|
||||
return nil, fmt.Errorf("gl: EGL has no configuration of OpenGL ES 3 (%#x)", eglGetError())
|
||||
}
|
||||
ctxAttribs := []int32{eglContextVersion, 3, eglNone}
|
||||
if w.context = eglCreateContext(w.display, config, 0, &ctxAttribs[0]); w.context == 0 {
|
||||
return nil, fmt.Errorf("gl: EGL cannot make a context (%#x)", eglGetError())
|
||||
}
|
||||
if w.surface = eglCreateWindowSurface(w.display, config, native, nil); w.surface == 0 {
|
||||
eglDestroyContext(w.display, w.context)
|
||||
return nil, fmt.Errorf("gl: EGL cannot make a window's surface (%#x)", eglGetError())
|
||||
}
|
||||
if !w.MakeCurrent() {
|
||||
w.Release()
|
||||
return nil, fmt.Errorf("gl: EGL cannot make the context current (%#x)", eglGetError())
|
||||
}
|
||||
return w, nil
|
||||
}
|
||||
|
||||
// MakeCurrent makes the window's context current on this thread, drawing
|
||||
// into its surface.
|
||||
func (w *Window) MakeCurrent() bool {
|
||||
return eglMakeCurrent(w.display, w.surface, w.surface, w.context) != 0
|
||||
}
|
||||
|
||||
// Swap shows the frame drawn into the surface.
|
||||
func (w *Window) Swap() error {
|
||||
if eglSwapBuffers(w.display, w.surface) == 0 {
|
||||
return fmt.Errorf("gl: EGL cannot show the frame (%#x)", eglGetError())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Release lets go of the surface and the context; the ANativeWindow stays
|
||||
// its owner's.
|
||||
func (w *Window) Release() {
|
||||
if w.display == 0 {
|
||||
return
|
||||
}
|
||||
eglMakeCurrent(w.display, 0, 0, 0)
|
||||
if w.surface != 0 {
|
||||
eglDestroySurface(w.display, w.surface)
|
||||
}
|
||||
if w.context != 0 {
|
||||
eglDestroyContext(w.display, w.context)
|
||||
}
|
||||
*w = Window{}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// The shared builder's culling and scissors must preserve every pixel with
|
||||
// both GL APIs, including nested clip masks and canvases drawn into textures.
|
||||
func TestGeometryOptimizationsPreservePixels(t *testing.T) {
|
||||
type fixture struct {
|
||||
name string
|
||||
s *scene.Scene
|
||||
}
|
||||
var cases []fixture
|
||||
for _, c := range gputest.CullCases() {
|
||||
cases = append(cases, fixture{"cull/" + c.Name, c.Scene})
|
||||
}
|
||||
for _, c := range gputest.RingCases() {
|
||||
cases = append(cases, fixture{"ring/" + c.Name, c.Scene})
|
||||
}
|
||||
for i, c := range gputest.ShadowCases() {
|
||||
cases = append(cases, fixture{fmt.Sprintf("shadow/%d", i), gputest.ShadowPanelScene(c)})
|
||||
}
|
||||
for _, c := range gputest.MaskedCases() {
|
||||
cases = append(cases, fixture{"masked/" + c.Name, c.Scene})
|
||||
}
|
||||
cases = append(cases,
|
||||
fixture{"transformed", gputest.TransformedScene()},
|
||||
fixture{"perspective", gputest.PerspectiveScene()},
|
||||
fixture{"translated", gputest.TranslatedScenes()[0]},
|
||||
fixture{"translated-between-pixels", gputest.TranslatedScenes()[1]},
|
||||
fixture{"masked-clips", gputest.MaskedClipScene()},
|
||||
fixture{"corner-clips", gputest.CornerClipScene()},
|
||||
fixture{"wide-colors", gputest.WideScene()},
|
||||
fixture{"canvases", gputest.CanvasScene()},
|
||||
)
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
read := offscreen(t, api.es, c.s.Width, c.s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
if err := r.Render(c.s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := read()
|
||||
r.b.NoCull, r.b.NoShadowSplit, r.b.NoRingSplit = true, true, true
|
||||
for _, canvas := range r.canvases {
|
||||
canvas.b.NoCull, canvas.b.NoShadowSplit, canvas.b.NoRingSplit = true, true, true
|
||||
}
|
||||
// Render every canvas again under the reference policy, rather
|
||||
// than comparing against its already optimized cached texture.
|
||||
c.s.EachCanvas(func(img *scene.Image) { img.Changed() })
|
||||
if err := r.Render(c.s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := read(); !bytes.Equal(got, want) {
|
||||
t.Fatal("culling or split scissors changed pixels")
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+1394
File diff suppressed because it is too large.
Load diff
+144
@@ -0,0 +1,144 @@
|
||||
//go:build js
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"slices"
|
||||
"syscall/js"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// canvas makes the WebGL 2 context of a w×h canvas current, or skips t
|
||||
// where there is no page (Node) or no WebGL 2. read returns its pixels as
|
||||
// the CPU renderer draws them.
|
||||
func canvas(t *testing.T, w, h int) (c *Context, read func() []byte) {
|
||||
doc := js.Global().Get("document")
|
||||
if doc.IsUndefined() {
|
||||
t.Skip("no page to draw in")
|
||||
}
|
||||
el := doc.Call("createElement", "canvas")
|
||||
el.Set("width", w)
|
||||
el.Set("height", h)
|
||||
c, err := NewContext(el)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
c.MakeCurrent()
|
||||
t.Log(versionString(), "dual-source blending:", c.dual)
|
||||
return c, func() []byte {
|
||||
pix, err := ReadFramebuffer(w, h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pix
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebGLDrawsAsTheCPURenderer(t *testing.T) {
|
||||
// Browsers without WEBGL_blend_func_extended blend with one color,
|
||||
// which cannot cover the channels of subpixel glyphs apart: the text
|
||||
// of browsers has none (package text's canvas engine).
|
||||
for _, dual := range []bool{true, false} {
|
||||
name := "dual-source blending"
|
||||
if !dual {
|
||||
name = "one color"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
s := gputest.Scene()
|
||||
if !dual {
|
||||
withoutSubpixelGlyphs(s)
|
||||
}
|
||||
c, read := canvas(t, s.Width, s.Height)
|
||||
if dual && !c.dual {
|
||||
t.Skip("no WEBGL_blend_func_extended")
|
||||
}
|
||||
c.dual = dual
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
if !r.es || r.dual != dual {
|
||||
t.Fatalf("the renderer takes WebGL 2 for OpenGL ES %v, with dual-source blending %v", r.es, r.dual)
|
||||
}
|
||||
// Twice: the second frame updates what the first uploaded.
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "webgl", read(), s.Width*4, s)
|
||||
}
|
||||
for name, s := range map[string]*scene.Scene{"webgl-affine": gputest.TransformedScene(), "webgl-perspective": gputest.PerspectiveScene(), "webgl-behind-origin": gputest.BehindOriginScene(), "webgl-masked-clips": gputest.MaskedClipScene(), "webgl-corner-clips": gputest.CornerClipScene()} {
|
||||
if !dual {
|
||||
withoutSubpixelGlyphs(s)
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, name, read(), s.Width*4, s)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebGLPresentsFramesDrawnInMemory(t *testing.T) {
|
||||
s := gputest.Scene()
|
||||
_, read := canvas(t, s.Width, s.Height)
|
||||
want := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(want, s)
|
||||
var p Presenter
|
||||
// Twice: the second frame reuses the texture.
|
||||
for range 2 {
|
||||
if err := p.Present(want.Pix, want.Stride, want.W, want.H); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := read(); !bytes.Equal(got, want.Pix[:len(got)]) {
|
||||
t.Fatal("the frame presented differs from the frame drawn")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A renewed context, as after the browser restored a lost one, has the
|
||||
// renderer make its objects again.
|
||||
func TestWebGLRenewedContext(t *testing.T) {
|
||||
s := gputest.Scene()
|
||||
c, read := canvas(t, s.Width, s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.Renew()
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "webgl-renewed", read(), s.Width*4, s)
|
||||
}
|
||||
|
||||
// withoutSubpixelGlyphs leaves the subpixel glyphs out of s.
|
||||
func withoutSubpixelGlyphs(s *scene.Scene) {
|
||||
ops := s.Ops[:0]
|
||||
for _, op := range s.Ops {
|
||||
if op.Kind == scene.OpGlyphs {
|
||||
gs := s.Glyphs[op.Start:op.End]
|
||||
if !slices.ContainsFunc(gs, func(g scene.Glyph) bool { return !g.Subpixel }) {
|
||||
continue
|
||||
}
|
||||
for i := range gs {
|
||||
if gs[i].Subpixel {
|
||||
gs[i].Color = scene.Color{}
|
||||
}
|
||||
}
|
||||
}
|
||||
ops = append(ops, op)
|
||||
}
|
||||
s.Ops = ops
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
)
|
||||
|
||||
// apis are the APIs the renderer draws with: OpenGL 3.3 and OpenGL ES 3.0.
|
||||
var apis = []struct {
|
||||
name string
|
||||
es bool
|
||||
}{{"OpenGL", false}, {"OpenGL ES", true}}
|
||||
|
||||
// offscreen makes a context current on the calling thread, without a
|
||||
// window, with a framebuffer of w×h pixels (see Offscreen), or skips t.
|
||||
// read returns its pixels as the CPU renderer draws them.
|
||||
func offscreen(t *testing.T, es bool, w, h int) (read func() []byte) {
|
||||
runtime.LockOSThread()
|
||||
t.Cleanup(runtime.UnlockOSThread)
|
||||
o, err := NewOffscreen(es, w, h)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
t.Cleanup(o.Release)
|
||||
t.Log(o.Info())
|
||||
return func() []byte {
|
||||
pix, err := ReadFramebuffer(w, h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pix
|
||||
}
|
||||
}
|
||||
|
||||
func TestDrawsAsTheCPURenderer(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
s := gputest.Scene()
|
||||
read := offscreen(t, api.es, s.Width, s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
if r.es != api.es {
|
||||
t.Fatalf("the renderer takes the context for OpenGL ES: %v", r.es)
|
||||
}
|
||||
// Twice: the second frame updates what the first uploaded.
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl", read(), s.Width*4, s)
|
||||
}
|
||||
|
||||
s = gputest.TransformedScene()
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-affine", read(), s.Width*4, s)
|
||||
}
|
||||
s = gputest.PerspectiveScene()
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-perspective", read(), s.Width*4, s)
|
||||
}
|
||||
s = gputest.BehindOriginScene()
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix := read()
|
||||
gputest.Compare(t, "gl-behind-origin", pix, s.Width*4, s)
|
||||
if p := pix[370*s.Width*4+160*4:][:4]; p[1] > 100 {
|
||||
t.Errorf("the card turned far from its origin does not show: %v at its center", p)
|
||||
}
|
||||
}
|
||||
for i, s := range gputest.TranslatedScenes() {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-translated"+[]string{"", "-between-pixels"}[i], read(), s.Width*4, s)
|
||||
}
|
||||
s = gputest.MaskedClipScene()
|
||||
// Twice: the second frame finds the clips' masks it made.
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-masked-clips", read(), s.Width*4, s)
|
||||
}
|
||||
s = gputest.CornerClipScene()
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-corner-clips", read(), s.Width*4, s)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBorderedCardDrawsAsTheCPURenderer draws the card of #531 (a large
|
||||
// opaque card with a border of 2 pixels at scale 2, and a small button like
|
||||
// it) with round corners, as OpenGL draws continuous ones, and requires the
|
||||
// CPU renderer's pixels along their straight edges, exactly.
|
||||
func TestBorderedCardDrawsAsTheCPURenderer(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
s := gputest.BorderedCardScene(false)
|
||||
read := offscreen(t, api.es, s.Width, s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
for range 2 {
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.CompareStraightEdges(t, "gl-bordered-card", read(), s.Width*4, s)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPresentsFramesDrawnInMemory(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
s := gputest.Scene()
|
||||
read := offscreen(t, api.es, s.Width, s.Height)
|
||||
want := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(want, s)
|
||||
var p Presenter
|
||||
// Twice: the second frame reuses the texture.
|
||||
for range 2 {
|
||||
if err := p.Present(want.Pix, want.Stride, want.W, want.H); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := read(); !bytes.Equal(got, want.Pix[:len(got)]) {
|
||||
t.Fatal("the frame presented differs from the frame drawn")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDrawsVideoAsTheCPURenderer draws frames of video in NV12 from their
|
||||
// planes, which the shader converts as the CPU renderer does.
|
||||
func TestDrawsVideoAsTheCPURenderer(t *testing.T) {
|
||||
for _, api := range apis {
|
||||
t.Run(api.name, func(t *testing.T) {
|
||||
s := gputest.VideoScene()
|
||||
read := offscreen(t, api.es, s.Width, s.Height)
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Release()
|
||||
// Twice: the second frame updates the planes in place.
|
||||
for i := range 2 {
|
||||
for _, op := range s.Ops {
|
||||
op.Image.Changed()
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gputest.Compare(t, "gl-video", read(), s.Width*4, s)
|
||||
if i == 0 {
|
||||
for _, op := range s.Ops {
|
||||
if t := r.images[op.Image.ID()]; t == nil || t.chroma == 0 {
|
||||
panic("a frame of video drew from RGBA, not its planes")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
package gl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// The functions of OpenGL ES 3 this package calls, from Android's
|
||||
// libGLESv3, and EGL's, which makes the contexts (egl_android.go).
|
||||
var (
|
||||
loadOnce sync.Once
|
||||
errLoad error
|
||||
|
||||
glGetString func(name uint32) uintptr
|
||||
glGetError func() uint32
|
||||
glGetIntegerv func(name uint32, data *int32)
|
||||
glCreateShader func(typ uint32) uint32
|
||||
glShaderSource func(shader uint32, count int32, sources **byte, lengths *int32)
|
||||
glCompileShader func(shader uint32)
|
||||
glGetShaderiv func(shader, name uint32, out *int32)
|
||||
glGetShaderInfoLog func(shader uint32, size int32, length *int32, log *byte)
|
||||
glDeleteShader func(shader uint32)
|
||||
glCreateProgram func() uint32
|
||||
glAttachShader func(program, shader uint32)
|
||||
glLinkProgram func(program uint32)
|
||||
glGetProgramiv func(program, name uint32, out *int32)
|
||||
glGetProgramInfoLog func(program uint32, size int32, length *int32, log *byte)
|
||||
glUseProgram func(program uint32)
|
||||
glDeleteProgram func(program uint32)
|
||||
glGetUniformLocation func(program uint32, name string) int32
|
||||
glGetUniformBlockIndex func(program uint32, name string) uint32
|
||||
glUniformBlockBinding func(program, index, binding uint32)
|
||||
glBindBufferBase func(target, index, buffer uint32)
|
||||
glUniform1i func(location, v int32)
|
||||
glUniform2f func(location int32, x, y float32)
|
||||
glUniform1f func(location int32, v float32)
|
||||
glUniform2i func(location, x, y int32)
|
||||
glUniform4i func(location, x, y, z, w int32)
|
||||
glCopyTexSubImage2D func(target uint32, level, xoff, yoff, x, y, w, h int32)
|
||||
glGenVertexArrays func(n int32, out *uint32)
|
||||
glBindVertexArray func(array uint32)
|
||||
glDeleteVertexArrays func(n int32, arrays *uint32)
|
||||
glGenBuffers func(n int32, out *uint32)
|
||||
glBindBuffer func(target, buffer uint32)
|
||||
glBufferData func(target uint32, size int, data unsafe.Pointer, usage uint32)
|
||||
glDeleteBuffers func(n int32, buffers *uint32)
|
||||
glEnableVertexAttrib func(index uint32)
|
||||
glVertexAttribPointer func(index uint32, size int32, typ uint32, normalized bool, stride int32, offset uintptr)
|
||||
glVertexAttribDivisor func(index, divisor uint32)
|
||||
glGenTextures func(n int32, out *uint32)
|
||||
glBindTexture func(target, texture uint32)
|
||||
glActiveTexture func(unit uint32)
|
||||
glTexImage2D func(target uint32, level, internalFormat, w, h, border int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glTexSubImage2D func(target uint32, level, x, y, w, h int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glTexParameteri func(target, name uint32, v int32)
|
||||
glDeleteTextures func(n int32, textures *uint32)
|
||||
glPixelStorei func(name uint32, v int32)
|
||||
glViewport func(x, y, w, h int32)
|
||||
glScissor func(x, y, w, h int32)
|
||||
glEnable func(cap uint32)
|
||||
glDisable func(cap uint32)
|
||||
glBlendFunc func(src, dst uint32)
|
||||
glBlendFuncSeparate func(srcRGB, dstRGB, srcAlpha, dstAlpha uint32)
|
||||
glClearColor func(r, g, b, a float32)
|
||||
glClear func(mask uint32)
|
||||
glDrawArraysInstanced func(mode uint32, first, count, instances int32)
|
||||
glReadPixels func(x, y, w, h int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glGenFramebuffers func(n int32, out *uint32)
|
||||
glBindFramebuffer func(target, fb uint32)
|
||||
glFramebufferTexture2D func(target, attachment, texTarget, texture uint32, level int32)
|
||||
glCheckFramebufferState func(target uint32) uint32
|
||||
glDeleteFramebuffers func(n int32, fbs *uint32)
|
||||
glBlitFramebuffer func(sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1 int32, mask, filter uint32)
|
||||
)
|
||||
|
||||
// glExtensions is GL_EXTENSIONS, for glGetString.
|
||||
const glExtensions = 0x1F03
|
||||
|
||||
func load() error {
|
||||
loadOnce.Do(func() {
|
||||
lib, err := purego.Dlopen("libGLESv3.so", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
errLoad = fmt.Errorf("gl: cannot load libGLESv3: %w", err)
|
||||
return
|
||||
}
|
||||
var missing []string
|
||||
gl := func(f any, name string) {
|
||||
sym, err := purego.Dlsym(lib, name)
|
||||
if err != nil || sym == 0 {
|
||||
missing = append(missing, name)
|
||||
return
|
||||
}
|
||||
purego.RegisterFunc(f, sym)
|
||||
}
|
||||
gl(&glGetString, "glGetString")
|
||||
gl(&glGetError, "glGetError")
|
||||
gl(&glGetIntegerv, "glGetIntegerv")
|
||||
gl(&glCreateShader, "glCreateShader")
|
||||
gl(&glShaderSource, "glShaderSource")
|
||||
gl(&glCompileShader, "glCompileShader")
|
||||
gl(&glGetShaderiv, "glGetShaderiv")
|
||||
gl(&glGetShaderInfoLog, "glGetShaderInfoLog")
|
||||
gl(&glDeleteShader, "glDeleteShader")
|
||||
gl(&glCreateProgram, "glCreateProgram")
|
||||
gl(&glAttachShader, "glAttachShader")
|
||||
gl(&glLinkProgram, "glLinkProgram")
|
||||
gl(&glGetProgramiv, "glGetProgramiv")
|
||||
gl(&glGetProgramInfoLog, "glGetProgramInfoLog")
|
||||
gl(&glUseProgram, "glUseProgram")
|
||||
gl(&glDeleteProgram, "glDeleteProgram")
|
||||
gl(&glGetUniformLocation, "glGetUniformLocation")
|
||||
gl(&glGetUniformBlockIndex, "glGetUniformBlockIndex")
|
||||
gl(&glUniformBlockBinding, "glUniformBlockBinding")
|
||||
gl(&glBindBufferBase, "glBindBufferBase")
|
||||
gl(&glUniform1i, "glUniform1i")
|
||||
gl(&glUniform2f, "glUniform2f")
|
||||
gl(&glUniform1f, "glUniform1f")
|
||||
gl(&glUniform2i, "glUniform2i")
|
||||
gl(&glUniform4i, "glUniform4i")
|
||||
gl(&glCopyTexSubImage2D, "glCopyTexSubImage2D")
|
||||
gl(&glGenVertexArrays, "glGenVertexArrays")
|
||||
gl(&glBindVertexArray, "glBindVertexArray")
|
||||
gl(&glDeleteVertexArrays, "glDeleteVertexArrays")
|
||||
gl(&glGenBuffers, "glGenBuffers")
|
||||
gl(&glBindBuffer, "glBindBuffer")
|
||||
gl(&glBufferData, "glBufferData")
|
||||
gl(&glDeleteBuffers, "glDeleteBuffers")
|
||||
gl(&glEnableVertexAttrib, "glEnableVertexAttribArray")
|
||||
gl(&glVertexAttribPointer, "glVertexAttribPointer")
|
||||
gl(&glVertexAttribDivisor, "glVertexAttribDivisor")
|
||||
gl(&glGenTextures, "glGenTextures")
|
||||
gl(&glBindTexture, "glBindTexture")
|
||||
gl(&glActiveTexture, "glActiveTexture")
|
||||
gl(&glTexImage2D, "glTexImage2D")
|
||||
gl(&glTexSubImage2D, "glTexSubImage2D")
|
||||
gl(&glTexParameteri, "glTexParameteri")
|
||||
gl(&glDeleteTextures, "glDeleteTextures")
|
||||
gl(&glPixelStorei, "glPixelStorei")
|
||||
gl(&glViewport, "glViewport")
|
||||
gl(&glScissor, "glScissor")
|
||||
gl(&glEnable, "glEnable")
|
||||
gl(&glDisable, "glDisable")
|
||||
gl(&glBlendFunc, "glBlendFunc")
|
||||
gl(&glBlendFuncSeparate, "glBlendFuncSeparate")
|
||||
gl(&glClearColor, "glClearColor")
|
||||
gl(&glClear, "glClear")
|
||||
gl(&glDrawArraysInstanced, "glDrawArraysInstanced")
|
||||
gl(&glReadPixels, "glReadPixels")
|
||||
gl(&glGenFramebuffers, "glGenFramebuffers")
|
||||
gl(&glBindFramebuffer, "glBindFramebuffer")
|
||||
gl(&glFramebufferTexture2D, "glFramebufferTexture2D")
|
||||
gl(&glCheckFramebufferState, "glCheckFramebufferStatus")
|
||||
gl(&glDeleteFramebuffers, "glDeleteFramebuffers")
|
||||
gl(&glBlitFramebuffer, "glBlitFramebuffer")
|
||||
if len(missing) > 0 {
|
||||
errLoad = fmt.Errorf("gl: libGLESv3 lacks %s", strings.Join(missing, ", "))
|
||||
return
|
||||
}
|
||||
errLoad = loadEGL()
|
||||
})
|
||||
return errLoad
|
||||
}
|
||||
|
||||
func currentContext() uintptr {
|
||||
if eglGetCurrentContext == nil {
|
||||
return 0
|
||||
}
|
||||
return eglGetCurrentContext()
|
||||
}
|
||||
|
||||
func goString(p uintptr) string {
|
||||
if p == 0 {
|
||||
return ""
|
||||
}
|
||||
var b []byte
|
||||
for i := uintptr(0); ; i++ {
|
||||
c := *(*byte)(unsafe.Add(*(*unsafe.Pointer)(unsafe.Pointer(&p)), i))
|
||||
if c == 0 {
|
||||
return string(b)
|
||||
}
|
||||
b = append(b, c)
|
||||
}
|
||||
}
|
||||
|
||||
// contextVersion returns the version of the current context, major × 10 +
|
||||
// minor: always OpenGL ES on Android, as "OpenGL ES 3.2 ...".
|
||||
func contextVersion() (version int32, es bool) {
|
||||
v := strings.TrimPrefix(versionString(), "OpenGL ES ")
|
||||
var major, minor int32
|
||||
fmt.Sscanf(v, "%d.%d", &major, &minor)
|
||||
return major*10 + minor, true
|
||||
}
|
||||
|
||||
// hasExtension reports whether the current context has an extension.
|
||||
func hasExtension(name string) bool {
|
||||
for _, e := range strings.Fields(goString(glGetString(glExtensions))) {
|
||||
if e == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// hasContext reports whether a context is current.
|
||||
func hasContext() bool { return currentContext() != 0 }
|
||||
|
||||
// versionString describes the current context's version, for errors.
|
||||
func versionString() string { return goString(glGetString(glVersion)) }
|
||||
|
||||
// rendererString names the current context's renderer.
|
||||
func rendererString() string { return goString(glGetString(glRenderer)) }
|
||||
|
||||
// setShaderSource sets the source of a shader.
|
||||
func setShaderSource(s uint32, src string) {
|
||||
b := append([]byte(src), 0)
|
||||
p := &b[0]
|
||||
glShaderSource(s, 1, &p, nil)
|
||||
}
|
||||
|
||||
// shaderLog and programLog return what compiling a shader or linking a
|
||||
// program logged.
|
||||
func shaderLog(s uint32) string { return infoLog(s, glGetShaderiv, glGetShaderInfoLog) }
|
||||
func programLog(p uint32) string { return infoLog(p, glGetProgramiv, glGetProgramInfoLog) }
|
||||
|
||||
func infoLog(obj uint32, get func(uint32, uint32, *int32), read func(uint32, int32, *int32, *byte)) string {
|
||||
var n int32
|
||||
get(obj, glInfoLogLength, &n)
|
||||
if n <= 1 {
|
||||
return "no log"
|
||||
}
|
||||
buf := make([]byte, n)
|
||||
read(obj, n, nil, &buf[0])
|
||||
return strings.TrimSpace(string(buf[:n-1]))
|
||||
}
|
||||
|
||||
// uploadElement is for browsers' video elements, which Android has none of.
|
||||
func uploadElement(uintptr) bool { return false }
|
||||
+396
@@ -0,0 +1,396 @@
|
||||
//go:build js
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"syscall/js"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/media"
|
||||
)
|
||||
|
||||
// Context is the WebGL 2 context of a canvas, which renderers draw with
|
||||
// while it is current (MakeCurrent), as a GL context on Linux. WebGL names
|
||||
// its objects by JavaScript objects, GL by numbers: the package numbers
|
||||
// them, and the functions GL's renderer calls (glCreateShader, …) take and
|
||||
// return those numbers.
|
||||
type Context struct {
|
||||
v js.Value
|
||||
id uintptr
|
||||
// dual tells that the context has WEBGL_blend_func_extended, enabled.
|
||||
dual bool
|
||||
// The pixel store's unpacking, which uploads read Go's pixels by.
|
||||
unpackAlign, unpackRow int32
|
||||
// scratch is a Uint8Array that Go's bytes are copied into for WebGL
|
||||
// to read, grown as needed.
|
||||
scratch js.Value
|
||||
size int
|
||||
}
|
||||
|
||||
var (
|
||||
// cur is the current context.
|
||||
cur *Context
|
||||
// objects are the WebGL objects by their numbers, which their
|
||||
// property objectKey holds too; locations the uniform locations.
|
||||
objects = map[uint32]js.Value{}
|
||||
locations = []js.Value{}
|
||||
lastName uint32
|
||||
lastID uintptr
|
||||
// errLoad is load's error on Linux; the browser has nothing to load.
|
||||
errLoad error
|
||||
)
|
||||
|
||||
// objectKey is the property of a WebGL object holding its number.
|
||||
const objectKey = "__mygo"
|
||||
|
||||
// NewContext makes the WebGL 2 context of canvas, which draws premultiplied
|
||||
// colors without depth, stencil or antialiasing, as frames need: the
|
||||
// renderer cuts shapes' edges itself. Its drawing buffer keeps what was
|
||||
// drawn, so that frames draw only what changed (Renderer.Partial). It
|
||||
// fails where the browser has no WebGL 2, or will not make a context for
|
||||
// the canvas.
|
||||
func NewContext(canvas js.Value) (*Context, error) {
|
||||
attrs := map[string]any{
|
||||
"alpha": true, "premultipliedAlpha": true, "antialias": false, "depth": false, "stencil": false,
|
||||
"preserveDrawingBuffer": true, "powerPreference": "default",
|
||||
}
|
||||
v := canvas.Call("getContext", "webgl2", attrs)
|
||||
if v.IsNull() || v.IsUndefined() {
|
||||
return nil, errors.New("gl: the browser has no WebGL 2")
|
||||
}
|
||||
c := &Context{v: v, unpackAlign: 4}
|
||||
c.Renew()
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Renew numbers the context anew, as after the browser restored it once it
|
||||
// was lost: renderers then make their objects again, the old ones gone
|
||||
// with the context.
|
||||
func (c *Context) Renew() {
|
||||
lastID++
|
||||
c.id = lastID
|
||||
c.dual = !c.v.Call("getExtension", "WEBGL_blend_func_extended").IsNull()
|
||||
c.unpackAlign, c.unpackRow = 4, 0
|
||||
}
|
||||
|
||||
// ID returns the context's number, which changes with Renew.
|
||||
func (c *Context) ID() uintptr { return c.id }
|
||||
|
||||
// Lost reports whether the browser took the context away.
|
||||
func (c *Context) Lost() bool { return c.v.Call("isContextLost").Bool() }
|
||||
|
||||
// MakeCurrent makes c the context renderers draw with.
|
||||
func (c *Context) MakeCurrent() { cur = c }
|
||||
|
||||
func load() error {
|
||||
if cur == nil {
|
||||
return errors.New("gl: no WebGL context is current")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func currentContext() uintptr {
|
||||
if cur == nil {
|
||||
return 0
|
||||
}
|
||||
return cur.id
|
||||
}
|
||||
|
||||
func hasContext() bool { return cur != nil }
|
||||
|
||||
func contextVersion() (version int32, es bool) { return 30, true }
|
||||
|
||||
func hasExtension(name string) bool {
|
||||
return name == "GL_EXT_blend_func_extended" && cur.dual
|
||||
}
|
||||
|
||||
func versionString() string { return cur.v.Call("getParameter", glVersion).String() }
|
||||
|
||||
// rendererString names the context's renderer: as the browser names it
|
||||
// (Firefox, the GPU's, sanitized), or, where that is WebGL's own name
|
||||
// (Chrome and Safari), as the GPU's driver does, should the browser tell
|
||||
// (WEBGL_debug_renderer_info, which Firefox deprecates).
|
||||
func rendererString() string {
|
||||
const unmaskedRenderer = 0x9246
|
||||
name := cur.v.Call("getParameter", glRenderer).String()
|
||||
if name == "WebKit WebGL" && !cur.v.Call("getExtension", "WEBGL_debug_renderer_info").IsNull() {
|
||||
if v := cur.v.Call("getParameter", unmaskedRenderer); v.Type() == js.TypeString {
|
||||
return v.String()
|
||||
}
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func call(name string, args ...any) js.Value { return cur.v.Call(name, args...) }
|
||||
|
||||
// name numbers a new WebGL object.
|
||||
func name(v js.Value) uint32 {
|
||||
if v.IsNull() {
|
||||
return 0
|
||||
}
|
||||
lastName++
|
||||
objects[lastName] = v
|
||||
v.Set(objectKey, lastName)
|
||||
return lastName
|
||||
}
|
||||
|
||||
// object returns the WebGL object of a number, null for 0.
|
||||
func object(n uint32) js.Value {
|
||||
if n == 0 {
|
||||
return js.Null()
|
||||
}
|
||||
if v, ok := objects[n]; ok {
|
||||
return v
|
||||
}
|
||||
return js.Null()
|
||||
}
|
||||
|
||||
// number returns the number of a WebGL object, 0 for null.
|
||||
func number(v js.Value) uint32 {
|
||||
if v.IsNull() || v.IsUndefined() {
|
||||
return 0
|
||||
}
|
||||
return uint32(v.Get(objectKey).Int())
|
||||
}
|
||||
|
||||
func deleteObjects(fn string, n int32, names *uint32) {
|
||||
for _, k := range unsafe.Slice(names, n) {
|
||||
if v, ok := objects[k]; ok {
|
||||
call(fn, v)
|
||||
delete(objects, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func genObjects(fn string, n int32, out *uint32) {
|
||||
names := unsafe.Slice(out, n)
|
||||
for i := range names {
|
||||
names[i] = name(call(fn))
|
||||
}
|
||||
}
|
||||
|
||||
// jsBytes copies n bytes at p into the scratch array, for WebGL to read.
|
||||
func jsBytes(p unsafe.Pointer, n int) js.Value {
|
||||
c := cur
|
||||
if c.size < n {
|
||||
c.size = max(n, 2*c.size, 1<<16)
|
||||
c.scratch = js.Global().Get("Uint8Array").New(c.size)
|
||||
}
|
||||
js.CopyBytesToJS(c.scratch, unsafe.Slice((*byte)(p), n))
|
||||
return c.scratch
|
||||
}
|
||||
|
||||
// uploadSize returns how many bytes an upload of w×h pixels reads, with
|
||||
// the pixel store's unpacking.
|
||||
func uploadSize(w, h int32, format uint32) int {
|
||||
bpp := int32(4)
|
||||
switch format {
|
||||
case glRed:
|
||||
bpp = 1
|
||||
case glRG:
|
||||
bpp = 2
|
||||
}
|
||||
row := w
|
||||
if cur.unpackRow > 0 {
|
||||
row = cur.unpackRow
|
||||
}
|
||||
a := cur.unpackAlign
|
||||
stride := (row*bpp + a - 1) / a * a
|
||||
return int((h-1)*stride + w*bpp)
|
||||
}
|
||||
|
||||
func setShaderSource(s uint32, src string) { call("shaderSource", object(s), src) }
|
||||
|
||||
func shaderLog(s uint32) string { return call("getShaderInfoLog", object(s)).String() }
|
||||
func programLog(p uint32) string { return call("getProgramInfoLog", object(p)).String() }
|
||||
|
||||
func glGetError() uint32 { return uint32(call("getError").Int()) }
|
||||
|
||||
func glGetIntegerv(param uint32, data *int32) {
|
||||
v := call("getParameter", param)
|
||||
switch param {
|
||||
case glFramebufferBinding:
|
||||
*data = int32(number(v))
|
||||
default:
|
||||
*data = int32(v.Int())
|
||||
}
|
||||
}
|
||||
|
||||
func glCreateShader(typ uint32) uint32 { return name(call("createShader", typ)) }
|
||||
func glCompileShader(s uint32) { call("compileShader", object(s)) }
|
||||
func glDeleteShader(s uint32) { deleteObjects("deleteShader", 1, &s) }
|
||||
|
||||
func glGetShaderiv(s, param uint32, out *int32) {
|
||||
*out = boolInt(call("getShaderParameter", object(s), param).Truthy())
|
||||
}
|
||||
|
||||
func glCreateProgram() uint32 { return name(call("createProgram")) }
|
||||
func glAttachShader(program, s uint32) { call("attachShader", object(program), object(s)) }
|
||||
func glLinkProgram(program uint32) { call("linkProgram", object(program)) }
|
||||
func glUseProgram(program uint32) { call("useProgram", object(program)) }
|
||||
func glDeleteProgram(program uint32) { deleteObjects("deleteProgram", 1, &program) }
|
||||
func glBindVertexArray(array uint32) { call("bindVertexArray", object(array)) }
|
||||
func glBindBuffer(target, buffer uint32) { call("bindBuffer", target, object(buffer)) }
|
||||
|
||||
func glGetProgramiv(program, param uint32, out *int32) {
|
||||
*out = boolInt(call("getProgramParameter", object(program), param).Truthy())
|
||||
}
|
||||
|
||||
func glGetUniformLocation(program uint32, uniform string) int32 {
|
||||
v := call("getUniformLocation", object(program), uniform)
|
||||
if v.IsNull() {
|
||||
return -1
|
||||
}
|
||||
locations = append(locations, v)
|
||||
return int32(len(locations) - 1)
|
||||
}
|
||||
|
||||
func glGetUniformBlockIndex(program uint32, block string) uint32 {
|
||||
return uint32(call("getUniformBlockIndex", object(program), block).Int())
|
||||
}
|
||||
|
||||
func glUniformBlockBinding(program, index, binding uint32) {
|
||||
call("uniformBlockBinding", object(program), index, binding)
|
||||
}
|
||||
|
||||
func glBindBufferBase(target, index, buffer uint32) {
|
||||
call("bindBufferBase", target, index, object(buffer))
|
||||
}
|
||||
|
||||
func location(l int32) js.Value {
|
||||
if l < 0 || int(l) >= len(locations) {
|
||||
return js.Null()
|
||||
}
|
||||
return locations[l]
|
||||
}
|
||||
|
||||
func glUniform1i(l, v int32) { call("uniform1i", location(l), v) }
|
||||
func glUniform2f(l int32, x, y float32) { call("uniform2f", location(l), x, y) }
|
||||
func glUniform1f(l int32, v float32) { call("uniform1f", location(l), v) }
|
||||
func glUniform2i(l, x, y int32) { call("uniform2i", location(l), x, y) }
|
||||
func glUniform4i(l, x, y, z, w int32) { call("uniform4i", location(l), x, y, z, w) }
|
||||
|
||||
func glCopyTexSubImage2D(target uint32, level, xoff, yoff, x, y, w, h int32) {
|
||||
call("copyTexSubImage2D", target, level, xoff, yoff, x, y, w, h)
|
||||
}
|
||||
|
||||
func glGenVertexArrays(n int32, out *uint32) { genObjects("createVertexArray", n, out) }
|
||||
func glDeleteVertexArrays(n int32, arrays *uint32) { deleteObjects("deleteVertexArray", n, arrays) }
|
||||
func glGenBuffers(n int32, out *uint32) { genObjects("createBuffer", n, out) }
|
||||
func glDeleteBuffers(n int32, buffers *uint32) { deleteObjects("deleteBuffer", n, buffers) }
|
||||
func glGenTextures(n int32, out *uint32) { genObjects("createTexture", n, out) }
|
||||
func glDeleteTextures(n int32, textures *uint32) { deleteObjects("deleteTexture", n, textures) }
|
||||
func glGenFramebuffers(n int32, out *uint32) { genObjects("createFramebuffer", n, out) }
|
||||
func glDeleteFramebuffers(n int32, fbs *uint32) { deleteObjects("deleteFramebuffer", n, fbs) }
|
||||
|
||||
func glBufferData(target uint32, size int, data unsafe.Pointer, usage uint32) {
|
||||
if data == nil {
|
||||
call("bufferData", target, size, usage)
|
||||
return
|
||||
}
|
||||
call("bufferData", target, jsBytes(data, size), usage, 0, size)
|
||||
}
|
||||
|
||||
func glEnableVertexAttrib(index uint32) { call("enableVertexAttribArray", index) }
|
||||
|
||||
func glVertexAttribPointer(index uint32, size int32, typ uint32, normalized bool, stride int32, offset uintptr) {
|
||||
call("vertexAttribPointer", index, size, typ, normalized, stride, offset)
|
||||
}
|
||||
|
||||
func glVertexAttribDivisor(index, divisor uint32) { call("vertexAttribDivisor", index, divisor) }
|
||||
func glBindTexture(target, texture uint32) { call("bindTexture", target, object(texture)) }
|
||||
func glActiveTexture(unit uint32) { call("activeTexture", unit) }
|
||||
|
||||
func glTexImage2D(target uint32, level, internalFormat, w, h, border int32, format, typ uint32, pix unsafe.Pointer) {
|
||||
if pix == nil {
|
||||
call("texImage2D", target, level, internalFormat, w, h, border, format, typ, js.Null())
|
||||
return
|
||||
}
|
||||
call("texImage2D", target, level, internalFormat, w, h, border, format, typ, jsPixels(pix, w, h, format, typ), 0)
|
||||
}
|
||||
|
||||
func glTexSubImage2D(target uint32, level, x, y, w, h int32, format, typ uint32, pix unsafe.Pointer) {
|
||||
call("texSubImage2D", target, level, x, y, w, h, format, typ, jsPixels(pix, w, h, format, typ), 0)
|
||||
}
|
||||
|
||||
// jsPixels returns the pixels of an upload as WebGL takes them: bytes, or
|
||||
// for floats (glFloat) a Float32Array over them.
|
||||
func jsPixels(pix unsafe.Pointer, w, h int32, format, typ uint32) js.Value {
|
||||
n := uploadSize(w, h, format)
|
||||
if typ != glFloat {
|
||||
return jsBytes(pix, n)
|
||||
}
|
||||
b := jsBytes(pix, 4*n)
|
||||
return js.Global().Get("Float32Array").New(b.Get("buffer"), 0, n)
|
||||
}
|
||||
|
||||
func glTexParameteri(target, param uint32, v int32) { call("texParameteri", target, param, v) }
|
||||
|
||||
func glPixelStorei(param uint32, v int32) {
|
||||
switch param {
|
||||
case glUnpackAlignment:
|
||||
cur.unpackAlign = v
|
||||
case glUnpackRowLength:
|
||||
cur.unpackRow = v
|
||||
}
|
||||
call("pixelStorei", param, v)
|
||||
}
|
||||
|
||||
func glViewport(x, y, w, h int32) { call("viewport", x, y, w, h) }
|
||||
func glScissor(x, y, w, h int32) { call("scissor", x, y, w, h) }
|
||||
func glEnable(capability uint32) { call("enable", capability) }
|
||||
func glDisable(capability uint32) { call("disable", capability) }
|
||||
func glBlendFunc(src, dst uint32) { call("blendFunc", src, dst) }
|
||||
func glClearColor(r, g, b, a float32) { call("clearColor", r, g, b, a) }
|
||||
func glClear(mask uint32) { call("clear", mask) }
|
||||
func glBindFramebuffer(target, fb uint32) { call("bindFramebuffer", target, object(fb)) }
|
||||
func glCheckFramebufferState(target uint32) uint32 {
|
||||
return uint32(call("checkFramebufferStatus", target).Int())
|
||||
}
|
||||
|
||||
func glBlendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha uint32) {
|
||||
call("blendFuncSeparate", srcRGB, dstRGB, srcAlpha, dstAlpha)
|
||||
}
|
||||
|
||||
func glDrawArraysInstanced(mode uint32, first, count, instances int32) {
|
||||
call("drawArraysInstanced", mode, first, count, instances)
|
||||
}
|
||||
|
||||
func glReadPixels(x, y, w, h int32, format, typ uint32, pix unsafe.Pointer) {
|
||||
bpp := int32(4)
|
||||
if format == glRed {
|
||||
bpp = 1
|
||||
}
|
||||
n := int(w * h * bpp)
|
||||
arr := js.Global().Get("Uint8Array").New(n)
|
||||
call("readPixels", x, y, w, h, format, typ, arr)
|
||||
js.CopyBytesToGo(unsafe.Slice((*byte)(pix), n), arr)
|
||||
}
|
||||
|
||||
func glFramebufferTexture2D(target, attachment, texTarget, texture uint32, level int32) {
|
||||
call("framebufferTexture2D", target, attachment, texTarget, object(texture), level)
|
||||
}
|
||||
|
||||
func glBlitFramebuffer(sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1 int32, mask, filter uint32) {
|
||||
call("blitFramebuffer", sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1, mask, filter)
|
||||
}
|
||||
|
||||
func boolInt(b bool) int32 {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// uploadElement uploads the picture of the video element of a surface's
|
||||
// Native into the bound texture, of its size, GPU to GPU, reporting
|
||||
// whether there was one.
|
||||
func uploadElement(native uintptr) bool {
|
||||
el := media.ElementOf(native)
|
||||
if el.IsUndefined() || el.Get("readyState").Int() < 2 { // HAVE_CURRENT_DATA
|
||||
return false
|
||||
}
|
||||
call("texSubImage2D", glTexture2D, 0, 0, 0, glRGBA, glUnsignedByte, el)
|
||||
return true
|
||||
}
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !android
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// The functions of libepoxy and GL this package calls.
|
||||
var (
|
||||
loadOnce sync.Once
|
||||
errLoad error
|
||||
|
||||
epoxyGLVersion func() int32
|
||||
epoxyIsDesktopGL func() bool
|
||||
epoxyHasExtension func(name string) bool
|
||||
currentGDKContext func() uintptr // gdk_gl_context_get_current, when GDK is loaded
|
||||
|
||||
// GTK's functions of a GtkGLArea's context, when GTK is loaded
|
||||
// (MakeAreaCurrent).
|
||||
gdkClearCurrent func() // gdk_gl_context_clear_current
|
||||
gtkAreaContext func(area uintptr) uintptr // gtk_gl_area_get_context
|
||||
gtkAreaMakeCurrent func(area uintptr) // gtk_gl_area_make_current
|
||||
gtkAreaAttach func(area uintptr) // gtk_gl_area_attach_buffers
|
||||
|
||||
glGetString func(name uint32) uintptr
|
||||
glGetError func() uint32
|
||||
glGetIntegerv func(name uint32, data *int32)
|
||||
glCreateShader func(typ uint32) uint32
|
||||
glShaderSource func(shader uint32, count int32, sources **byte, lengths *int32)
|
||||
glCompileShader func(shader uint32)
|
||||
glGetShaderiv func(shader, name uint32, out *int32)
|
||||
glGetShaderInfoLog func(shader uint32, size int32, length *int32, log *byte)
|
||||
glDeleteShader func(shader uint32)
|
||||
glCreateProgram func() uint32
|
||||
glAttachShader func(program, shader uint32)
|
||||
glLinkProgram func(program uint32)
|
||||
glGetProgramiv func(program, name uint32, out *int32)
|
||||
glGetProgramInfoLog func(program uint32, size int32, length *int32, log *byte)
|
||||
glUseProgram func(program uint32)
|
||||
glDeleteProgram func(program uint32)
|
||||
glGetUniformLocation func(program uint32, name string) int32
|
||||
glGetUniformBlockIndex func(program uint32, name string) uint32
|
||||
glUniformBlockBinding func(program, index, binding uint32)
|
||||
glBindBufferBase func(target, index, buffer uint32)
|
||||
glUniform1i func(location, v int32)
|
||||
glUniform2f func(location int32, x, y float32)
|
||||
glUniform1f func(location int32, v float32)
|
||||
glUniform2i func(location, x, y int32)
|
||||
glUniform4i func(location, x, y, z, w int32)
|
||||
glCopyTexSubImage2D func(target uint32, level, xoff, yoff, x, y, w, h int32)
|
||||
glGenVertexArrays func(n int32, out *uint32)
|
||||
glBindVertexArray func(array uint32)
|
||||
glDeleteVertexArrays func(n int32, arrays *uint32)
|
||||
glGenBuffers func(n int32, out *uint32)
|
||||
glBindBuffer func(target, buffer uint32)
|
||||
glBufferData func(target uint32, size int, data unsafe.Pointer, usage uint32)
|
||||
glDeleteBuffers func(n int32, buffers *uint32)
|
||||
glEnableVertexAttrib func(index uint32)
|
||||
glVertexAttribPointer func(index uint32, size int32, typ uint32, normalized bool, stride int32, offset uintptr)
|
||||
glVertexAttribDivisor func(index, divisor uint32)
|
||||
glGenTextures func(n int32, out *uint32)
|
||||
glBindTexture func(target, texture uint32)
|
||||
glActiveTexture func(unit uint32)
|
||||
glTexImage2D func(target uint32, level, internalFormat, w, h, border int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glTexSubImage2D func(target uint32, level, x, y, w, h int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glTexParameteri func(target, name uint32, v int32)
|
||||
glDeleteTextures func(n int32, textures *uint32)
|
||||
glPixelStorei func(name uint32, v int32)
|
||||
glViewport func(x, y, w, h int32)
|
||||
glScissor func(x, y, w, h int32)
|
||||
glEnable func(cap uint32)
|
||||
glDisable func(cap uint32)
|
||||
glBlendFunc func(src, dst uint32)
|
||||
glBlendFuncSeparate func(srcRGB, dstRGB, srcAlpha, dstAlpha uint32)
|
||||
glClearColor func(r, g, b, a float32)
|
||||
glClear func(mask uint32)
|
||||
glDrawArraysInstanced func(mode uint32, first, count, instances int32)
|
||||
glReadPixels func(x, y, w, h int32, format, typ uint32, pix unsafe.Pointer)
|
||||
glGenFramebuffers func(n int32, out *uint32)
|
||||
glBindFramebuffer func(target, fb uint32)
|
||||
glFramebufferTexture2D func(target, attachment, texTarget, texture uint32, level int32)
|
||||
glCheckFramebufferState func(target uint32) uint32
|
||||
glDeleteFramebuffers func(n int32, fbs *uint32)
|
||||
glBlitFramebuffer func(sx0, sy0, sx1, sy1, dx0, dy0, dx1, dy1 int32, mask, filter uint32)
|
||||
)
|
||||
|
||||
func load() error {
|
||||
loadOnce.Do(func() {
|
||||
lib, err := purego.Dlopen("libepoxy.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
errLoad = fmt.Errorf("gl: cannot load libepoxy: %w", err)
|
||||
return
|
||||
}
|
||||
var missing []string
|
||||
fn := func(f any, name string) {
|
||||
sym, err := purego.Dlsym(lib, name)
|
||||
if err != nil || sym == 0 {
|
||||
missing = append(missing, name)
|
||||
return
|
||||
}
|
||||
purego.RegisterFunc(f, sym)
|
||||
}
|
||||
// libepoxy exports a pointer for each GL function, to a stub that
|
||||
// finds the function of the current context when first called.
|
||||
gl := func(f any, name string) {
|
||||
sym, err := purego.Dlsym(lib, "epoxy_"+name)
|
||||
if err != nil || sym == 0 {
|
||||
missing = append(missing, name)
|
||||
return
|
||||
}
|
||||
purego.RegisterFunc(f, **(**uintptr)(unsafe.Pointer(&sym)))
|
||||
}
|
||||
fn(&epoxyGLVersion, "epoxy_gl_version")
|
||||
fn(&epoxyIsDesktopGL, "epoxy_is_desktop_gl")
|
||||
fn(&epoxyHasExtension, "epoxy_has_gl_extension")
|
||||
gl(&glGetString, "glGetString")
|
||||
gl(&glGetError, "glGetError")
|
||||
gl(&glGetIntegerv, "glGetIntegerv")
|
||||
gl(&glCreateShader, "glCreateShader")
|
||||
gl(&glShaderSource, "glShaderSource")
|
||||
gl(&glCompileShader, "glCompileShader")
|
||||
gl(&glGetShaderiv, "glGetShaderiv")
|
||||
gl(&glGetShaderInfoLog, "glGetShaderInfoLog")
|
||||
gl(&glDeleteShader, "glDeleteShader")
|
||||
gl(&glCreateProgram, "glCreateProgram")
|
||||
gl(&glAttachShader, "glAttachShader")
|
||||
gl(&glLinkProgram, "glLinkProgram")
|
||||
gl(&glGetProgramiv, "glGetProgramiv")
|
||||
gl(&glGetProgramInfoLog, "glGetProgramInfoLog")
|
||||
gl(&glUseProgram, "glUseProgram")
|
||||
gl(&glDeleteProgram, "glDeleteProgram")
|
||||
gl(&glGetUniformLocation, "glGetUniformLocation")
|
||||
gl(&glGetUniformBlockIndex, "glGetUniformBlockIndex")
|
||||
gl(&glUniformBlockBinding, "glUniformBlockBinding")
|
||||
gl(&glBindBufferBase, "glBindBufferBase")
|
||||
gl(&glUniform1i, "glUniform1i")
|
||||
gl(&glUniform2f, "glUniform2f")
|
||||
gl(&glUniform1f, "glUniform1f")
|
||||
gl(&glUniform2i, "glUniform2i")
|
||||
gl(&glUniform4i, "glUniform4i")
|
||||
gl(&glCopyTexSubImage2D, "glCopyTexSubImage2D")
|
||||
gl(&glGenVertexArrays, "glGenVertexArrays")
|
||||
gl(&glBindVertexArray, "glBindVertexArray")
|
||||
gl(&glDeleteVertexArrays, "glDeleteVertexArrays")
|
||||
gl(&glGenBuffers, "glGenBuffers")
|
||||
gl(&glBindBuffer, "glBindBuffer")
|
||||
gl(&glBufferData, "glBufferData")
|
||||
gl(&glDeleteBuffers, "glDeleteBuffers")
|
||||
gl(&glEnableVertexAttrib, "glEnableVertexAttribArray")
|
||||
gl(&glVertexAttribPointer, "glVertexAttribPointer")
|
||||
gl(&glVertexAttribDivisor, "glVertexAttribDivisor")
|
||||
gl(&glGenTextures, "glGenTextures")
|
||||
gl(&glBindTexture, "glBindTexture")
|
||||
gl(&glActiveTexture, "glActiveTexture")
|
||||
gl(&glTexImage2D, "glTexImage2D")
|
||||
gl(&glTexSubImage2D, "glTexSubImage2D")
|
||||
gl(&glTexParameteri, "glTexParameteri")
|
||||
gl(&glDeleteTextures, "glDeleteTextures")
|
||||
gl(&glPixelStorei, "glPixelStorei")
|
||||
gl(&glViewport, "glViewport")
|
||||
gl(&glScissor, "glScissor")
|
||||
gl(&glEnable, "glEnable")
|
||||
gl(&glDisable, "glDisable")
|
||||
gl(&glBlendFunc, "glBlendFunc")
|
||||
gl(&glBlendFuncSeparate, "glBlendFuncSeparate")
|
||||
gl(&glClearColor, "glClearColor")
|
||||
gl(&glClear, "glClear")
|
||||
gl(&glDrawArraysInstanced, "glDrawArraysInstanced")
|
||||
gl(&glReadPixels, "glReadPixels")
|
||||
gl(&glGenFramebuffers, "glGenFramebuffers")
|
||||
gl(&glBindFramebuffer, "glBindFramebuffer")
|
||||
gl(&glFramebufferTexture2D, "glFramebufferTexture2D")
|
||||
gl(&glCheckFramebufferState, "glCheckFramebufferStatus")
|
||||
gl(&glDeleteFramebuffers, "glDeleteFramebuffers")
|
||||
gl(&glBlitFramebuffer, "glBlitFramebuffer")
|
||||
if len(missing) > 0 {
|
||||
errLoad = fmt.Errorf("gl: libepoxy lacks %s", strings.Join(missing, ", "))
|
||||
return
|
||||
}
|
||||
direct(lib)
|
||||
// GDK is loaded in apps, where its context tells when GTK
|
||||
// realized the area again; tests make contexts of their own.
|
||||
if sym, err := purego.Dlsym(purego.RTLD_DEFAULT, "gdk_gl_context_get_current"); err == nil && sym != 0 {
|
||||
purego.RegisterFunc(¤tGDKContext, sym)
|
||||
}
|
||||
gtk := map[string]any{
|
||||
"gdk_gl_context_clear_current": &gdkClearCurrent, "gtk_gl_area_get_context": >kAreaContext,
|
||||
"gtk_gl_area_make_current": >kAreaMakeCurrent, "gtk_gl_area_attach_buffers": >kAreaAttach,
|
||||
}
|
||||
for name, f := range gtk {
|
||||
sym, err := purego.Dlsym(purego.RTLD_DEFAULT, name)
|
||||
if err != nil || sym == 0 {
|
||||
gdkClearCurrent = nil // all or none
|
||||
break
|
||||
}
|
||||
purego.RegisterFunc(f, sym)
|
||||
}
|
||||
})
|
||||
return errLoad
|
||||
}
|
||||
|
||||
// direct calls the GL functions a frame calls for each batch with
|
||||
// purego.SyscallN, through libepoxy's pointer to each: a function
|
||||
// RegisterFunc made builds its arguments with reflection on every call,
|
||||
// which cost more than the call itself, and a frame makes hundreds.
|
||||
func direct(lib uintptr) {
|
||||
ptr := func(name string) *uintptr {
|
||||
sym, err := purego.Dlsym(lib, "epoxy_"+name)
|
||||
if err != nil || sym == 0 {
|
||||
return nil
|
||||
}
|
||||
return *(**uintptr)(unsafe.Pointer(&sym))
|
||||
}
|
||||
b := func(v bool) uintptr {
|
||||
if v {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
if p := ptr("glVertexAttribPointer"); p != nil {
|
||||
glVertexAttribPointer = func(index uint32, size int32, typ uint32, normalized bool, stride int32, offset uintptr) {
|
||||
purego.SyscallN(*p, uintptr(index), uintptr(size), uintptr(typ), b(normalized), uintptr(stride), offset)
|
||||
}
|
||||
}
|
||||
if p := ptr("glScissor"); p != nil {
|
||||
glScissor = func(x, y, w, h int32) { purego.SyscallN(*p, uintptr(x), uintptr(y), uintptr(w), uintptr(h)) }
|
||||
}
|
||||
if p := ptr("glDrawArraysInstanced"); p != nil {
|
||||
glDrawArraysInstanced = func(mode uint32, first, count, instances int32) {
|
||||
purego.SyscallN(*p, uintptr(mode), uintptr(first), uintptr(count), uintptr(instances))
|
||||
}
|
||||
}
|
||||
if p := ptr("glActiveTexture"); p != nil {
|
||||
glActiveTexture = func(unit uint32) { purego.SyscallN(*p, uintptr(unit)) }
|
||||
}
|
||||
if p := ptr("glBindTexture"); p != nil {
|
||||
glBindTexture = func(target, texture uint32) { purego.SyscallN(*p, uintptr(target), uintptr(texture)) }
|
||||
}
|
||||
if p := ptr("glUseProgram"); p != nil {
|
||||
glUseProgram = func(program uint32) { purego.SyscallN(*p, uintptr(program)) }
|
||||
}
|
||||
if p := ptr("glBindBuffer"); p != nil {
|
||||
glBindBuffer = func(target, buffer uint32) { purego.SyscallN(*p, uintptr(target), uintptr(buffer)) }
|
||||
}
|
||||
if p := ptr("glEnable"); p != nil {
|
||||
glEnable = func(c uint32) { purego.SyscallN(*p, uintptr(c)) }
|
||||
}
|
||||
if p := ptr("glDisable"); p != nil {
|
||||
glDisable = func(c uint32) { purego.SyscallN(*p, uintptr(c)) }
|
||||
}
|
||||
if p := ptr("glBlendFunc"); p != nil {
|
||||
glBlendFunc = func(src, dst uint32) { purego.SyscallN(*p, uintptr(src), uintptr(dst)) }
|
||||
}
|
||||
if p := ptr("glBlendFuncSeparate"); p != nil {
|
||||
glBlendFuncSeparate = func(srcRGB, dstRGB, srcAlpha, dstAlpha uint32) {
|
||||
purego.SyscallN(*p, uintptr(srcRGB), uintptr(dstRGB), uintptr(srcAlpha), uintptr(dstAlpha))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MakeAreaCurrent makes the context of a GtkGLArea current again, with the
|
||||
// area's framebuffer bound, when it no longer is during the area's render
|
||||
// signal, and reports whether OpenGL has a current context after. GTK
|
||||
// makes the area's context current before the signal, but what a frame
|
||||
// runs before it draws, as a window that a button's action creates, shows
|
||||
// or hides, can leave another context current, or none: GDK's
|
||||
// gdk_window_hide clears the current context of the window it hides, and
|
||||
// disposing a context makes EGL's current one none. GDK remembers the
|
||||
// context it last made current and does nothing when asked for it again,
|
||||
// so the area's context is made current again past that memory: cleared
|
||||
// first, then made current.
|
||||
func MakeAreaCurrent(area uintptr) bool {
|
||||
if load() != nil {
|
||||
return false
|
||||
}
|
||||
if area == 0 || gdkClearCurrent == nil || currentGDKContext == nil {
|
||||
return hasContext()
|
||||
}
|
||||
ctx, has := gtkAreaContext(area), hasContext()
|
||||
if !needsRestore(ctx, currentGDKContext(), has) {
|
||||
return has
|
||||
}
|
||||
gdkClearCurrent()
|
||||
gtkAreaMakeCurrent(area)
|
||||
gtkAreaAttach(area)
|
||||
return hasContext()
|
||||
}
|
||||
|
||||
// needsRestore reports whether the context of a GtkGLArea, area, must be
|
||||
// made current again before drawing into the area: GDK has another
|
||||
// context current, current, or OpenGL none at all, has false, whatever
|
||||
// GDK thinks. An area without a context has none to make current.
|
||||
func needsRestore(area, current uintptr, has bool) bool {
|
||||
return area != 0 && (current != area || !has)
|
||||
}
|
||||
|
||||
func currentContext() uintptr {
|
||||
if currentGDKContext == nil {
|
||||
return 0
|
||||
}
|
||||
return currentGDKContext()
|
||||
}
|
||||
|
||||
func goString(p uintptr) string {
|
||||
if p == 0 {
|
||||
return ""
|
||||
}
|
||||
var b []byte
|
||||
for i := uintptr(0); ; i++ {
|
||||
c := *(*byte)(unsafe.Add(*(*unsafe.Pointer)(unsafe.Pointer(&p)), i))
|
||||
if c == 0 {
|
||||
return string(b)
|
||||
}
|
||||
b = append(b, c)
|
||||
}
|
||||
}
|
||||
|
||||
// contextVersion returns the version of the current context, major × 10 +
|
||||
// minor, and whether it is OpenGL ES.
|
||||
func contextVersion() (version int32, es bool) { return epoxyGLVersion(), !epoxyIsDesktopGL() }
|
||||
|
||||
// hasExtension reports whether the current context has an extension.
|
||||
func hasExtension(name string) bool { return epoxyHasExtension(name) }
|
||||
|
||||
// hasContext reports whether a context is current, which GDK may think one
|
||||
// is when OpenGL does not: libepoxy aborts the first call of most GL
|
||||
// functions without one. glGetString it finds without.
|
||||
func hasContext() bool { return glGetString(glVersion) != 0 }
|
||||
|
||||
// versionString describes the current context's version, for errors.
|
||||
func versionString() string { return goString(glGetString(glVersion)) }
|
||||
|
||||
// rendererString names the current context's renderer.
|
||||
func rendererString() string { return goString(glGetString(glRenderer)) }
|
||||
|
||||
// setShaderSource sets the source of a shader.
|
||||
func setShaderSource(s uint32, src string) {
|
||||
b := append([]byte(src), 0)
|
||||
p := &b[0]
|
||||
glShaderSource(s, 1, &p, nil)
|
||||
}
|
||||
|
||||
// shaderLog and programLog return what compiling a shader or linking a
|
||||
// program logged.
|
||||
func shaderLog(s uint32) string { return infoLog(s, glGetShaderiv, glGetShaderInfoLog) }
|
||||
func programLog(p uint32) string { return infoLog(p, glGetProgramiv, glGetProgramInfoLog) }
|
||||
|
||||
func infoLog(obj uint32, get func(uint32, uint32, *int32), read func(uint32, int32, *int32, *byte)) string {
|
||||
var n int32
|
||||
get(obj, glInfoLogLength, &n)
|
||||
if n <= 1 {
|
||||
return "no log"
|
||||
}
|
||||
buf := make([]byte, n)
|
||||
read(obj, n, nil, &buf[0])
|
||||
return strings.TrimSpace(string(buf[:n-1]))
|
||||
}
|
||||
|
||||
// uploadElement is for browsers' video elements, which Linux has none of.
|
||||
func uploadElement(uintptr) bool { return false }
|
||||
@@ -0,0 +1,40 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !android
|
||||
|
||||
package gl
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNeedsRestore(t *testing.T) {
|
||||
const area, other = 0x10, 0x20
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
area, current uintptr
|
||||
has, want bool
|
||||
}{
|
||||
{"the area's, current", area, area, true, false},
|
||||
{"another window's", area, other, true, true},
|
||||
{"none, cleared", area, 0, false, true},
|
||||
{"GDK's, stale", area, area, false, true},
|
||||
{"none in GDK alone", area, 0, true, true},
|
||||
{"an area without a context", 0, other, false, false},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := needsRestore(c.area, c.current, c.has); got != c.want {
|
||||
t.Errorf("needsRestore = %v, want %v", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Without GTK, as in tests, MakeAreaCurrent changes nothing.
|
||||
func TestMakeAreaCurrentWithoutGTK(t *testing.T) {
|
||||
if err := load(); err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
if gdkClearCurrent != nil {
|
||||
t.Skip("GTK is loaded")
|
||||
}
|
||||
if MakeAreaCurrent(0x10) {
|
||||
t.Error("a context is current without one made")
|
||||
}
|
||||
}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// EGL enumerations.
|
||||
const (
|
||||
eglPlatformSurfaceless = 0x31DD // EGL_PLATFORM_SURFACELESS_MESA
|
||||
eglNone = 0x3038
|
||||
eglRenderableType = 0x3040
|
||||
eglOpenGLBit = 0x0008
|
||||
eglSurfaceType = 0x3033
|
||||
eglPbufferBit = 0x0001
|
||||
eglOpenGLAPI = 0x30A2
|
||||
eglOpenGLESAPI = 0x30A0
|
||||
eglOpenGLES3Bit = 0x0040 // EGL_OPENGL_ES3_BIT_KHR
|
||||
eglContextMajorVersion = 0x3098
|
||||
eglContextMinorVersion = 0x30FB
|
||||
eglContextProfileMask = 0x30FD
|
||||
eglContextCoreProfileBit = 0x1
|
||||
)
|
||||
|
||||
// Offscreen is a GL context without a window, current on the thread that
|
||||
// made it, which must stay locked to it, with a framebuffer bound: for
|
||||
// drawing scenes in tests, as packages drawing effects do. EGL makes it
|
||||
// with Mesa's surfaceless platform, which draws with llvmpipe without a
|
||||
// GPU.
|
||||
type Offscreen struct {
|
||||
display, context uintptr
|
||||
fb, tex uint32
|
||||
w, h int
|
||||
release func()
|
||||
r *Renderer
|
||||
// scratch holds the framebuffer's rows as GL reads them (Read).
|
||||
scratch []byte
|
||||
}
|
||||
|
||||
// NewOffscreen makes an OpenGL 3.3 context, or with es an OpenGL ES 3.0
|
||||
// one, current on the calling thread, and binds a framebuffer of w×h
|
||||
// pixels.
|
||||
func NewOffscreen(es bool, w, h int) (_ *Offscreen, err error) {
|
||||
lib, err := purego.Dlopen("libEGL.so.1", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("gl: no EGL: %w", err)
|
||||
}
|
||||
var (
|
||||
getPlatformDisplay func(platform uint32, native uintptr, attribs unsafe.Pointer) uintptr
|
||||
initialize func(display uintptr, major, minor *int32) uint32
|
||||
bindAPI func(api uint32) uint32
|
||||
chooseConfig func(display uintptr, attribs *int32, configs *uintptr, size int32, n *int32) uint32
|
||||
createContext func(display, config, share uintptr, attribs *int32) uintptr
|
||||
makeCurrent func(display, draw, read, context uintptr) uint32
|
||||
destroyContext func(display, context uintptr) uint32
|
||||
terminate func(display uintptr) uint32
|
||||
)
|
||||
for name, fn := range map[string]any{
|
||||
"eglGetPlatformDisplay": &getPlatformDisplay, "eglInitialize": &initialize, "eglBindAPI": &bindAPI,
|
||||
"eglChooseConfig": &chooseConfig, "eglCreateContext": &createContext, "eglMakeCurrent": &makeCurrent,
|
||||
"eglDestroyContext": &destroyContext, "eglTerminate": &terminate,
|
||||
} {
|
||||
sym, err := purego.Dlsym(lib, name)
|
||||
if err != nil || sym == 0 {
|
||||
return nil, fmt.Errorf("gl: EGL has no %s", name)
|
||||
}
|
||||
purego.RegisterFunc(fn, sym)
|
||||
}
|
||||
// A variable of its own, not a named result: returning an error would
|
||||
// set that to nil before the undoing below runs.
|
||||
off := &Offscreen{w: w, h: h}
|
||||
var undo []func()
|
||||
off.release = func() {
|
||||
for i := len(undo) - 1; i >= 0; i-- {
|
||||
undo[i]()
|
||||
}
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
off.release()
|
||||
}
|
||||
}()
|
||||
display := getPlatformDisplay(eglPlatformSurfaceless, 0, nil)
|
||||
if display == 0 || initialize(display, nil, nil) == 0 {
|
||||
return nil, errors.New("gl: no surfaceless EGL display")
|
||||
}
|
||||
undo = append(undo, func() { terminate(display) })
|
||||
api, bit, contextAttribs := uint32(eglOpenGLAPI), int32(eglOpenGLBit), []int32{eglContextMajorVersion, 3, eglContextMinorVersion, 3, eglContextProfileMask, eglContextCoreProfileBit, eglNone}
|
||||
if es {
|
||||
api, bit, contextAttribs = eglOpenGLESAPI, eglOpenGLES3Bit, []int32{eglContextMajorVersion, 3, eglContextMinorVersion, 0, eglNone}
|
||||
}
|
||||
bindAPI(api)
|
||||
// Configurations are for windows unless asked otherwise.
|
||||
configAttribs := []int32{eglRenderableType, bit, eglSurfaceType, eglPbufferBit, eglNone}
|
||||
var config uintptr
|
||||
var n int32
|
||||
if chooseConfig(display, &configAttribs[0], &config, 1, &n) == 0 || n == 0 {
|
||||
return nil, errors.New("gl: no EGL configuration for the API")
|
||||
}
|
||||
context := createContext(display, config, 0, &contextAttribs[0])
|
||||
if context == 0 {
|
||||
return nil, errors.New("gl: no context of the version")
|
||||
}
|
||||
undo = append(undo, func() {
|
||||
makeCurrent(display, 0, 0, 0)
|
||||
destroyContext(display, context)
|
||||
})
|
||||
if makeCurrent(display, 0, 0, context) == 0 {
|
||||
return nil, errors.New("gl: cannot make the context current without a surface")
|
||||
}
|
||||
if err := load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
off.tex = newTexture(glRGBA8, glRGBA, w, h, nil, 0)
|
||||
glGenFramebuffers(1, &off.fb)
|
||||
glBindFramebuffer(glFramebuffer, off.fb)
|
||||
glFramebufferTexture2D(glFramebuffer, glColorAttachment0, glTexture2D, off.tex, 0)
|
||||
undo = append(undo, func() {
|
||||
if off.r != nil {
|
||||
off.r.Release()
|
||||
}
|
||||
glBindFramebuffer(glFramebuffer, 0)
|
||||
glDeleteFramebuffers(1, &off.fb)
|
||||
glDeleteTextures(1, &off.tex)
|
||||
})
|
||||
if status := glCheckFramebufferState(glFramebuffer); status != glFramebufferDone {
|
||||
return nil, fmt.Errorf("gl: framebuffer incomplete: %#x", status)
|
||||
}
|
||||
return off, nil
|
||||
}
|
||||
|
||||
// Info names the context's version and renderer.
|
||||
func (o *Offscreen) Info() string {
|
||||
return goString(glGetString(glVersion)) + ", " + goString(glGetString(glRenderer))
|
||||
}
|
||||
|
||||
// Render draws s, which must be as large as the framebuffer, with a
|
||||
// renderer of its own, and returns its pixels as the CPU renderer draws
|
||||
// them: premultiplied BGRA rows from the top.
|
||||
func (o *Offscreen) Render(s *scene.Scene) ([]byte, error) {
|
||||
if o.r == nil {
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
o.r = r
|
||||
}
|
||||
if err := o.r.Render(s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ReadFramebuffer(o.w, o.h)
|
||||
}
|
||||
|
||||
// Draw draws s, which must be as large as the framebuffer, with a
|
||||
// renderer of its own, without reading it back: Read does, for videos
|
||||
// (plugins/render), which build the next frame meanwhile.
|
||||
func (o *Offscreen) Draw(s *scene.Scene) error {
|
||||
if o.r == nil {
|
||||
r, err := New()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
o.r = r
|
||||
}
|
||||
if err := o.r.Render(s); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Read copies the framebuffer into dst, as the CPU renderer draws:
|
||||
// premultiplied BGRA rows from the top, 4×width bytes each.
|
||||
func (o *Offscreen) Read(dst []byte) error {
|
||||
n := 4 * o.w * o.h
|
||||
if len(dst) < n {
|
||||
return errors.New("gl: too small a buffer")
|
||||
}
|
||||
if len(o.scratch) != n {
|
||||
o.scratch = make([]byte, n)
|
||||
}
|
||||
glPixelStorei(glPackAlignment, 1)
|
||||
glReadPixels(0, 0, int32(o.w), int32(o.h), glRGBA, glUnsignedByte, unsafe.Pointer(&o.scratch[0]))
|
||||
glPixelStorei(glPackAlignment, 4)
|
||||
if e := glGetError(); e != glNoError {
|
||||
return fmt.Errorf("gl: reading the framebuffer failed (error %#x)", e)
|
||||
}
|
||||
// GL's rows go up, and its bytes are RGBA.
|
||||
row := 4 * o.w
|
||||
for y := range o.h {
|
||||
src, out := o.scratch[row*(o.h-1-y):][:row], dst[row*y:][:row]
|
||||
for x := 0; x < row; x += 4 {
|
||||
out[x], out[x+1], out[x+2], out[x+3] = src[x+2], src[x+1], src[x], src[x+3]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Release deletes the context and what it holds.
|
||||
func (o *Offscreen) Release() { o.release() }
|
||||
@@ -0,0 +1,26 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestNewOffscreenFailsWithItsError checks that a setup failing after EGL
|
||||
// loaded returns its error, rather than panicking as it undoes what it
|
||||
// did: a framebuffer of 0×0 is incomplete, and without libepoxy loading
|
||||
// fails, both after the display and the context.
|
||||
func TestNewOffscreenFailsWithItsError(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
o, err := NewOffscreen(false, 0, 0)
|
||||
if err == nil {
|
||||
o.Release()
|
||||
t.Skip("a framebuffer of 0×0 is complete here")
|
||||
}
|
||||
if o != nil {
|
||||
t.Errorf("NewOffscreen returned %v with the error %v", o, err)
|
||||
}
|
||||
t.Log(err)
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
//go:build (linux && !android && (amd64 || arm64)) || js || android
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// errNoContext is the error of drawing without a current context.
|
||||
var errNoContext = errors.New("gl: no current context")
|
||||
|
||||
// Presenter shows frames drawn in memory in the bound framebuffer: what a
|
||||
// GtkGLArea shows when its content draws on the CPU after all, as when the
|
||||
// GL renderer fails. GTK shows only what OpenGL draws into a GtkGLArea.
|
||||
type Presenter struct {
|
||||
context uintptr
|
||||
tex, fb uint32
|
||||
w, h int
|
||||
rgba []byte
|
||||
}
|
||||
|
||||
// Present copies premultiplied BGRA rows of stride bytes, width×height
|
||||
// pixels, into the bound framebuffer, which is that size. The context
|
||||
// current must be the one of the last call, or a new one.
|
||||
func (p *Presenter) Present(pix []byte, stride, width, height int) error {
|
||||
if err := load(); err != nil {
|
||||
return err
|
||||
}
|
||||
if width <= 0 || height <= 0 || len(pix) < stride*(height-1)+4*width {
|
||||
return nil
|
||||
}
|
||||
if !hasContext() {
|
||||
return errNoContext
|
||||
}
|
||||
if c := currentContext(); c != p.context {
|
||||
// A new context: the old one took the texture with it.
|
||||
p.context, p.tex, p.fb, p.w, p.h = c, 0, 0, 0, 0
|
||||
}
|
||||
// GL reads RGBA; frames in memory are BGRA.
|
||||
n := 4 * width * height
|
||||
if cap(p.rgba) < n {
|
||||
p.rgba = make([]byte, n)
|
||||
}
|
||||
rgba := p.rgba[:n]
|
||||
for y := range height {
|
||||
src, dst := pix[y*stride:][:4*width], rgba[4*width*y:][:4*width]
|
||||
for x := 0; x < 4*width; x += 4 {
|
||||
dst[x], dst[x+1], dst[x+2], dst[x+3] = src[x+2], src[x+1], src[x], src[x+3]
|
||||
}
|
||||
}
|
||||
var target int32
|
||||
glGetIntegerv(glFramebufferBinding, &target)
|
||||
if p.tex == 0 || p.w != width || p.h != height {
|
||||
if p.tex != 0 {
|
||||
glDeleteTextures(1, &p.tex)
|
||||
}
|
||||
p.tex = newTexture(glRGBA8, glRGBA, width, height, nil, 0)
|
||||
if p.fb == 0 {
|
||||
glGenFramebuffers(1, &p.fb)
|
||||
}
|
||||
glBindFramebuffer(glReadFramebuffer, p.fb)
|
||||
glFramebufferTexture2D(glReadFramebuffer, glColorAttachment0, glTexture2D, p.tex, 0)
|
||||
p.w, p.h = width, height
|
||||
}
|
||||
glActiveTexture(glTexture0)
|
||||
glBindTexture(glTexture2D, p.tex)
|
||||
unpack(4*width, glRGBA8)
|
||||
glTexSubImage2D(glTexture2D, 0, 0, 0, int32(width), int32(height), glRGBA, glUnsignedByte, unsafe.Pointer(&rgba[0]))
|
||||
unpackReset()
|
||||
glBindTexture(glTexture2D, 0)
|
||||
glBindFramebuffer(glReadFramebuffer, p.fb)
|
||||
glBindFramebuffer(glDrawFramebuffer, uint32(target))
|
||||
glDisable(glScissorTest)
|
||||
// Rows go down in memory and up in GL: the copy flips them.
|
||||
w, h := int32(width), int32(height)
|
||||
glBlitFramebuffer(0, 0, w, h, 0, h, w, 0, glColorBufferBit, glNearest)
|
||||
glBindFramebuffer(glFramebuffer, uint32(target))
|
||||
if e := glGetError(); e != glNoError {
|
||||
return fmt.Errorf("gl: presenting a frame failed (error %#x)", e)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
//go:build (linux && !android && (amd64 || arm64)) || js || android
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// ReadFramebuffer returns the pixels of the bound framebuffer, width×height,
|
||||
// as the CPU renderer draws them: premultiplied BGRA rows from the top. Tests
|
||||
// compare them.
|
||||
func ReadFramebuffer(width, height int) ([]byte, error) {
|
||||
if err := load(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if width <= 0 || height <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
pix := make([]byte, 4*width*height)
|
||||
glPixelStorei(glPackAlignment, 1)
|
||||
glReadPixels(0, 0, int32(width), int32(height), glRGBA, glUnsignedByte, unsafe.Pointer(&pix[0]))
|
||||
glPixelStorei(glPackAlignment, 4)
|
||||
if e := glGetError(); e != glNoError {
|
||||
return nil, fmt.Errorf("gl: reading the framebuffer failed (error %#x)", e)
|
||||
}
|
||||
// GL's rows go up, and its bytes are RGBA.
|
||||
out := make([]byte, len(pix))
|
||||
for y := range height {
|
||||
src, dst := pix[4*width*(height-1-y):][:4*width], out[4*width*y:][:4*width]
|
||||
for x := 0; x < 4*width; x += 4 {
|
||||
dst[x], dst[x+1], dst[x+2], dst[x+3] = src[x+2], src[x+1], src[x], src[x+3]
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
+741
@@ -0,0 +1,741 @@
|
||||
// The one shader of the OpenGL renderer, as shader.metal is the Metal one
|
||||
// and shader.hlsl the Direct3D one: every scene op is an instanced quad,
|
||||
// and the fragment shader computes the coverage of rounded rectangles,
|
||||
// borders, gradients, stripes and shadows from signed distances, as the
|
||||
// CPU renderer (internal/raster) does. Colors are straight (not premultiplied)
|
||||
// and blending happens in sRGB space, as in browsers. The renderer
|
||||
// compiles it when it starts, as GLSL 3.30 or GLSL ES 3.00, with VERTEX or
|
||||
// FRAGMENT defined, and the passes computing the backdrops of effects with
|
||||
// PASS_VERTEX and DOWN or BLUR. The fragment shaders of effects
|
||||
// (scene.Effect) take the start of its fragment part, with EFFECT
|
||||
// defined, before effect.glsl.
|
||||
|
||||
#ifdef VERTEX
|
||||
|
||||
// One instance per op, as internal/gpu builds them.
|
||||
layout(location = 0) in vec4 aRect; // x, y, width, height in pixels
|
||||
layout(location = 1) in vec4 aRadii; // top-left, top-right, bottom-right, bottom-left
|
||||
layout(location = 2) in vec4 aInner; // radii of the border's inner edge, of the box casting a shadow, or of an inner shadow's hole
|
||||
layout(location = 3) in vec4 aColor;
|
||||
layout(location = 4) in vec4 aColor2; // gradient end
|
||||
layout(location = 5) in vec4 aBorder; // border color
|
||||
layout(location = 6) in vec4 aGrad; // gradient start and end points, or stripes
|
||||
layout(location = 7) in vec4 aUV; // texture rectangle, normalized, border widths, the box casting a shadow, or an inner shadow's hole
|
||||
layout(location = 8) in vec4 aClip; // the innermost clip rectangle
|
||||
layout(location = 9) in vec4 aClipRadii;
|
||||
layout(location = 10) in vec4 aParams; // kind, dashed or grayscale, sigma or paint, opacity
|
||||
|
||||
layout(location = 11) in vec4 aTransform0;
|
||||
layout(location = 12) in vec4 aTransform1;
|
||||
layout(location = 13) in vec4 aTransform2; // the projective row's g and h, and 1 where its constant is -1
|
||||
|
||||
uniform vec2 uSize;
|
||||
|
||||
// The frame point times its projective divisor, and the divisor: they
|
||||
// interpolate in perspective to what divides into the frame point.
|
||||
out vec3 vWorld;
|
||||
flat out vec4 vTransform0;
|
||||
flat out vec4 vTransform1;
|
||||
flat out vec4 vTransform2;
|
||||
out vec4 vPoint; // the position in pixels, and the texture coordinates
|
||||
flat out vec4 vRect;
|
||||
flat out vec4 vRadii;
|
||||
flat out vec4 vInner;
|
||||
flat out vec4 vColor;
|
||||
flat out vec4 vColor2;
|
||||
flat out vec4 vBorder;
|
||||
flat out vec4 vGrad;
|
||||
flat out vec4 vWidths;
|
||||
flat out vec4 vClip;
|
||||
flat out vec4 vClipRadii;
|
||||
flat out vec4 vParams;
|
||||
|
||||
// frameH returns the frame point of local p, in homogeneous coordinates.
|
||||
vec3 frameH(vec2 p) {
|
||||
return vec3(dot(aTransform0.xyz, vec3(p, 1.0)), dot(aTransform1.xyz, vec3(p, 1.0)),
|
||||
dot(vec3(aTransform2.xy, 1.0 - 2.0 * aTransform2.z), vec3(p, 1.0)));
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec2 corner = vec2(float(gl_VertexID & 1), float(gl_VertexID >> 1));
|
||||
vec4 r = aRect;
|
||||
float kind = aParams.x;
|
||||
if (kind < 0.5 || kind > 5.5) { // fills and effects
|
||||
r = vec4(r.xy - 1.0, r.zw + 2.0);
|
||||
} else if (kind < 1.5) {
|
||||
float e = 3.0 * aParams.z + 1.0;
|
||||
r = vec4(r.xy - e, r.zw + 2.0 * e);
|
||||
}
|
||||
vec3 h = frameH(r.xy + corner * r.zw);
|
||||
if (aTransform0.w > 0.5 && h.z > 0.0) {
|
||||
// A pixel's reach at this corner, by the map's Jacobian there.
|
||||
vec2 s = h.xy / h.z;
|
||||
float a = (aTransform0.x - s.x * aTransform2.x) / h.z, c = (aTransform0.y - s.x * aTransform2.y) / h.z;
|
||||
float b = (aTransform1.x - s.y * aTransform2.x) / h.z, d = (aTransform1.y - s.y * aTransform2.y) / h.z;
|
||||
vec2 e = vec2(abs(d) + abs(c), abs(b) + abs(a)) / abs(a * d - b * c);
|
||||
r = vec4(r.xy - e, r.zw + 2.0 * e);
|
||||
}
|
||||
vec2 p = r.xy + corner * r.zw;
|
||||
h = frameH(p);
|
||||
gl_Position = vec4(h.xy / uSize * vec2(2.0, -2.0) + h.z * vec2(-1.0, 1.0), 0.0, h.z);
|
||||
vPoint = vec4(p, aUV.xy + (p - aRect.xy) / aRect.zw * (aUV.zw - aUV.xy));
|
||||
vWorld = h;
|
||||
vTransform0 = aTransform0;
|
||||
vTransform1 = aTransform1;
|
||||
vTransform2 = aTransform2;
|
||||
vRect = aRect;
|
||||
vRadii = aRadii;
|
||||
vInner = aInner;
|
||||
vColor = aColor;
|
||||
vColor2 = aColor2;
|
||||
vBorder = aBorder;
|
||||
vGrad = aGrad;
|
||||
vWidths = aUV;
|
||||
vClip = aClip;
|
||||
vClipRadii = aClipRadii;
|
||||
vParams = aParams;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#if defined(FRAGMENT) || defined(EFFECT)
|
||||
|
||||
in vec3 vWorld;
|
||||
flat in vec4 vTransform0;
|
||||
flat in vec4 vTransform1;
|
||||
flat in vec4 vTransform2;
|
||||
in vec4 vPoint;
|
||||
flat in vec4 vRect;
|
||||
flat in vec4 vRadii;
|
||||
flat in vec4 vInner;
|
||||
flat in vec4 vColor;
|
||||
flat in vec4 vColor2;
|
||||
flat in vec4 vBorder;
|
||||
flat in vec4 vGrad;
|
||||
flat in vec4 vWidths;
|
||||
flat in vec4 vClip;
|
||||
flat in vec4 vClipRadii;
|
||||
flat in vec4 vParams;
|
||||
|
||||
uniform sampler2D uMask;
|
||||
uniform sampler2D uColor;
|
||||
uniform sampler2D uImage;
|
||||
uniform sampler2D uClipMask;
|
||||
// The stops of the frame's gradients (gpu.Builder.Stops): two texels each,
|
||||
// the color, straight sRGB, then its place and its color in Oklab.
|
||||
uniform highp sampler2D uStops;
|
||||
uniform vec2 uSize; // the frame's size in pixels
|
||||
|
||||
// The color and, for dual-source blending, the source's alpha of each
|
||||
// channel. Without it, subpixel glyphs take the mean of their subpixels.
|
||||
#ifdef DUAL
|
||||
layout(location = 0, index = 0) out vec4 fragColor;
|
||||
layout(location = 0, index = 1) out vec4 fragAlpha;
|
||||
#else
|
||||
out vec4 fragColor;
|
||||
#endif
|
||||
|
||||
float sdRoundRect(vec2 p, vec4 rect, vec4 radii) {
|
||||
vec2 h = rect.zw * 0.5;
|
||||
vec2 q = p - rect.xy - h;
|
||||
float r = q.x < 0.0 ? (q.y < 0.0 ? radii.x : radii.w) : (q.y < 0.0 ? radii.y : radii.z);
|
||||
vec2 a = abs(q) - h + r;
|
||||
return length(max(a, vec2(0.0))) + min(max(a.x, a.y), 0.0) - r;
|
||||
}
|
||||
|
||||
float coverage(float d) { return clamp(0.5 - d, 0.0, 1.0); }
|
||||
|
||||
// rectCoverage returns how much of the pixel at p a rounded rectangle
|
||||
// covers: by the distance to its edge near rounded corners, and exactly,
|
||||
// the area of the pixel inside it, near square ones.
|
||||
float rectCoverage(vec2 p, vec4 rect, vec4 radii) {
|
||||
vec2 q = p - rect.xy - rect.zw * 0.5;
|
||||
float r = q.x < 0.0 ? (q.y < 0.0 ? radii.x : radii.w) : (q.y < 0.0 ? radii.y : radii.z);
|
||||
if (r > 0.0) {
|
||||
return coverage(sdRoundRect(p, rect, radii));
|
||||
}
|
||||
vec2 c = clamp(min(rect.xy + rect.zw, p + 0.5) - max(rect.xy, p - 0.5), 0.0, 1.0);
|
||||
return c.x * c.y;
|
||||
}
|
||||
|
||||
// Frame is where a fragment is in the frame, s, and, when its instance's
|
||||
// map is projective (persp), the columns of the map back, up to a factor.
|
||||
struct Frame {
|
||||
vec2 s;
|
||||
vec3 c0, c1, c2;
|
||||
bool persp;
|
||||
};
|
||||
Frame frameOf() {
|
||||
Frame f;
|
||||
f.persp = any(notEqual(vTransform2.xy, vec2(0.0)));
|
||||
// In perspective, the pixel's center, as interpolating drifts: the
|
||||
// frame's y goes down, the window's up.
|
||||
f.s = f.persp ? vec2(gl_FragCoord.x, uSize.y - gl_FragCoord.y) : vWorld.xy / vWorld.z;
|
||||
vec3 r0 = vTransform0.xyz, r1 = vTransform1.xyz, r2 = vec3(vTransform2.xy, 1.0 - 2.0 * vTransform2.z);
|
||||
f.c0 = cross(r1, r2);
|
||||
f.c1 = cross(r2, r0);
|
||||
f.c2 = cross(r0, r1);
|
||||
return f;
|
||||
}
|
||||
// localOf returns the point of the instance that shows at the frame's s.
|
||||
vec2 localOf(Frame f, vec2 s) {
|
||||
vec3 q = f.c0 * s.x + f.c1 * s.y + f.c2;
|
||||
return q.xy / q.z;
|
||||
}
|
||||
// perspectiveCoverage is localCoverage in perspective: each sample where
|
||||
// the CPU renderer takes it.
|
||||
float perspectiveCoverage(vec4 rect, vec4 radii, Frame fr) {
|
||||
vec2 p = localOf(fr, fr.s);
|
||||
vec2 a = localOf(fr, fr.s + vec2(0.5, 0.5)) - p, b = localOf(fr, fr.s + vec2(0.5, -0.5)) - p;
|
||||
float reach = max(abs(a.x) + abs(a.y), abs(b.x) + abs(b.y)) * 2.0;
|
||||
float d = sdRoundRect(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1.0;
|
||||
if (d > reach)
|
||||
return 0.0;
|
||||
float n = 0.0;
|
||||
for (int y = 0; y < 4; y++)
|
||||
for (int x = 0; x < 4; x++) {
|
||||
vec2 q = localOf(fr, fr.s + vec2((float(x) + 0.5) / 4.0 - 0.5, (float(y) + 0.5) / 4.0 - 0.5));
|
||||
n += sdRoundRect(q, rect, radii) <= 0.0 ? 1.0 : 0.0;
|
||||
}
|
||||
return n / 16.0;
|
||||
}
|
||||
float localCoverage(vec2 p, vec4 rect, vec4 radii, float affine, Frame fr) {
|
||||
if (affine < 0.5)
|
||||
return rectCoverage(p, rect, radii);
|
||||
vec2 dx = dFdx(p), dy = dFdy(p), a = (dx + dy) * 0.5, b = (dx - dy) * 0.5;
|
||||
if (fr.persp)
|
||||
return perspectiveCoverage(rect, radii, fr);
|
||||
float reach = max(abs(a.x) + abs(a.y), abs(b.x) + abs(b.y)) * 2.0;
|
||||
float d = sdRoundRect(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1.0;
|
||||
if (d > reach)
|
||||
return 0.0;
|
||||
float n = 0.0;
|
||||
for (int y = 0; y < 4; y++)
|
||||
for (int x = 0; x < 4; x++) {
|
||||
vec2 q = p + dx * ((float(x) + 0.5) / 4.0 - 0.5) + dy * ((float(y) + 0.5) / 4.0 - 0.5);
|
||||
n += sdRoundRect(q, rect, radii) <= 0.0 ? 1.0 : 0.0;
|
||||
}
|
||||
return n / 16.0;
|
||||
}
|
||||
float clipCoverage() {
|
||||
Frame fr = frameOf();
|
||||
vec2 world = fr.s;
|
||||
if (vTransform1.w < 0.5)
|
||||
return rectCoverage(world, vClip, vClipRadii);
|
||||
if (vTransform1.w > 1.5)
|
||||
return localCoverage(vPoint.xy, vClip, vec4(0.0), vTransform0.w, fr) *
|
||||
texture(uClipMask, (world - vClipRadii.xy) / vClipRadii.zw).a;
|
||||
return texture(uClipMask, (world - vClip.xy) / vClip.zw).a;
|
||||
}
|
||||
vec4 sampleLocal(sampler2D t, vec2 uv, vec4 src, float affine) {
|
||||
if (affine > 0.5) {
|
||||
vec2 halfPixel = 0.5 / vec2(textureSize(t, 0));
|
||||
uv = clamp(uv, src.xy + halfPixel, src.zw - halfPixel);
|
||||
}
|
||||
return texture(t, uv);
|
||||
}
|
||||
|
||||
// sampleImage samples an image held inside src, which is reversed along
|
||||
// an axis it flips, so that a part of a sheet shows none of its
|
||||
// neighbors; where pixelated is set, as pixel art draws, each texel a
|
||||
// square of its color whose edges blend with the next only across the
|
||||
// pixel they cross (Ebitengine's FilterPixelated): nearest where it shows
|
||||
// at whole multiples of its size, and texels of even widths with smooth
|
||||
// edges at any other. dtex is the fwidth of uv, taken where every
|
||||
// fragment of the quad takes it.
|
||||
vec4 sampleImage(sampler2D t, vec2 uv, vec4 src, float pixelated, vec2 dtex) {
|
||||
vec2 size = vec2(textureSize(t, 0));
|
||||
vec2 lo = min(src.xy, src.zw), hi = max(src.xy, src.zw);
|
||||
if (pixelated > 0.5) {
|
||||
vec2 tc = uv * size - 0.5;
|
||||
vec2 i = floor(tc);
|
||||
vec2 f = clamp((tc - i - 0.5) / clamp(dtex * size, 1e-5, 1.0) + 0.5, 0.0, 1.0);
|
||||
uv = (i + f + 0.5) / size;
|
||||
}
|
||||
return texture(t, clamp(uv, lo + 0.5 / size, hi - 0.5 / size));
|
||||
}
|
||||
|
||||
// tint multiplies premultiplied c by straight color t.
|
||||
vec4 tint(vec4 c, vec4 t) { return c * vec4(t.rgb * t.a, t.a); }
|
||||
|
||||
vec4 premul(vec4 c) { return vec4(c.rgb * c.a, c.a); }
|
||||
|
||||
vec3 unpremul(vec4 c) { return c.a > 0.0 ? c.rgb / c.a : vec3(0.0); }
|
||||
|
||||
// textCoverage corrects the coverage a of a glyph of straight color c as
|
||||
// Direct2D blends text (scene.TextCoverage): it enhances the contrast,
|
||||
// the more the darker c is, and corrects for gamma with the ratios g.
|
||||
float textCoverage(float a, vec3 c, float contrast, float boost, vec4 g) {
|
||||
float k = contrast * clamp(3.0 - 4.0 * dot(c, vec3(0.30, 0.59, 0.11)), 0.0, 1.0) + boost;
|
||||
a = a * (k + 1.0) / (a * k + 1.0);
|
||||
float f = dot(c, vec3(0.25, 0.5, 0.25));
|
||||
return clamp(a + a * (1.0 - a) * ((g.x * f + g.y) * a + (g.z * f + g.w)), 0.0, 1.0);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
// What follows is the renderer's own; effects (effect.glsl) take what is
|
||||
// above.
|
||||
#ifdef FRAGMENT
|
||||
|
||||
// The chroma of an image that is a frame of video in NV12, whose luma
|
||||
// uImage holds (gpu.ImageYUV).
|
||||
uniform sampler2D uChroma;
|
||||
|
||||
// yuvToRGB converts the samples of a frame of video in YCbCr to RGB, as
|
||||
// scene.YUVMatrix.YUVToRGB does: m is the matrix, 0 to 2 for BT.601, 709
|
||||
// and 2020 in the limited range, plus 3 for the full range.
|
||||
vec3 yuvToRGB(float y, vec2 c, float m) {
|
||||
float full = m > 2.5 ? 1.0 : 0.0;
|
||||
float std = m - 3.0 * full;
|
||||
vec2 k = std < 0.5 ? vec2(0.299, 0.114) : std < 1.5 ? vec2(0.2126, 0.0722) : vec2(0.2627, 0.0593);
|
||||
c -= 128.0 / 255.0;
|
||||
if (full < 0.5) {
|
||||
y = (y - 16.0 / 255.0) * (255.0 / 219.0);
|
||||
c *= 255.0 / 224.0;
|
||||
}
|
||||
float r = y + 2.0 * (1.0 - k.x) * c.y;
|
||||
float b = y + 2.0 * (1.0 - k.y) * c.x;
|
||||
float g = (y - k.x * r - k.y * b) / (1.0 - k.x - k.y);
|
||||
return clamp(vec3(r, g, b), 0.0, 1.0);
|
||||
}
|
||||
|
||||
// subpixelCoverage does the same for each subpixel of a subpixel glyph.
|
||||
vec3 subpixelCoverage(vec3 a, vec3 c, float contrast, float boost, vec4 g) {
|
||||
float k = contrast * clamp(3.0 - 4.0 * dot(c, vec3(0.30, 0.59, 0.11)), 0.0, 1.0) + boost;
|
||||
a = a * (k + 1.0) / (a * k + 1.0);
|
||||
return clamp(a + a * (1.0 - a) * ((g.x * c + g.y) * a + (g.z * c + g.w)), vec3(0.0), vec3(1.0));
|
||||
}
|
||||
|
||||
// erf2 approximates the error function (Abramowitz and Stegun 7.1.27).
|
||||
vec2 erf2(vec2 x) {
|
||||
vec2 s = sign(x);
|
||||
vec2 a = abs(x);
|
||||
x = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
|
||||
x *= x;
|
||||
return s - s / (x * x);
|
||||
}
|
||||
|
||||
float gaussian(float x, float sigma) {
|
||||
return exp(-(x * x) / (2.0 * sigma * sigma)) / (2.50662827463 * sigma);
|
||||
}
|
||||
|
||||
// The blurred rounded box of Evan Wallace: exact along x, four samples
|
||||
// along y.
|
||||
float shadowX(float x, float y, float sigma, float corner, vec2 h) {
|
||||
float delta = min(h.y - corner - abs(y), 0.0);
|
||||
float curved = h.x - corner + sqrt(max(0.0, corner * corner - delta * delta));
|
||||
vec2 integral = 0.5 + 0.5 * erf2((x + vec2(-curved, curved)) * (sqrt(0.5) / sigma));
|
||||
return integral.y - integral.x;
|
||||
}
|
||||
|
||||
float boxShadow(vec2 p, vec4 rect, float sigma, float corner) {
|
||||
vec2 h = rect.zw * 0.5;
|
||||
p -= rect.xy + h;
|
||||
float low = p.y - h.y;
|
||||
float high = p.y + h.y;
|
||||
float y0 = clamp(-3.0 * sigma, low, high);
|
||||
float y1 = clamp(3.0 * sigma, low, high);
|
||||
float dy = (y1 - y0) / 4.0;
|
||||
float y = y0 + dy * 0.5;
|
||||
float v = 0.0;
|
||||
for (int k = 0; k < 4; k++) {
|
||||
v += shadowX(p.x, p.y - y, sigma, corner, h) * gaussian(y, sigma) * dy;
|
||||
y += dy;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
vec3 toLinear(vec3 c) {
|
||||
return mix(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, lessThanEqual(c, vec3(0.04045)));
|
||||
}
|
||||
|
||||
vec3 toSRGB(vec3 c) {
|
||||
return mix(1.055 * pow(max(c, vec3(0.0)), vec3(1.0 / 2.4)) - 0.055, c * 12.92,
|
||||
lessThanEqual(c, vec3(0.0031308)));
|
||||
}
|
||||
|
||||
vec3 cbrt3(vec3 v) { return sign(v) * pow(abs(v), vec3(1.0 / 3.0)); }
|
||||
|
||||
vec3 oklab(vec3 srgb) {
|
||||
vec3 c = toLinear(srgb);
|
||||
vec3 lms = cbrt3(vec3(0.4122214708 * c.r + 0.5363325363 * c.g + 0.0514459929 * c.b,
|
||||
0.2119034982 * c.r + 0.6806995451 * c.g + 0.1073969566 * c.b,
|
||||
0.0883024619 * c.r + 0.2817188376 * c.g + 0.6299787005 * c.b));
|
||||
return vec3(0.2104542553 * lms.x + 0.7936177850 * lms.y - 0.0040720468 * lms.z,
|
||||
1.9779984951 * lms.x - 2.4285922050 * lms.y + 0.4505937099 * lms.z,
|
||||
0.0259040371 * lms.x + 0.7827717662 * lms.y - 0.8086757660 * lms.z);
|
||||
}
|
||||
|
||||
vec3 fromOklab(vec3 lab) {
|
||||
vec3 lms = vec3(lab.x + 0.3963377774 * lab.y + 0.2158037573 * lab.z,
|
||||
lab.x - 0.1055613458 * lab.y - 0.0638541728 * lab.z,
|
||||
lab.x - 0.0894841775 * lab.y - 1.2914855480 * lab.z);
|
||||
lms = lms * lms * lms;
|
||||
return toSRGB(vec3(4.0767416621 * lms.x - 3.3077115913 * lms.y + 0.2309699292 * lms.z,
|
||||
-1.2684380046 * lms.x + 2.6097574011 * lms.y - 0.3413193965 * lms.z,
|
||||
-0.0041960863 * lms.x - 0.7034186147 * lms.y + 1.7076147010 * lms.z));
|
||||
}
|
||||
|
||||
// stop returns texel k of the stops.
|
||||
vec4 stop(int k) {
|
||||
return texelFetch(uStops, ivec2(k % 1024, k / 1024), 0);
|
||||
}
|
||||
|
||||
// stopsAt returns the color at t of the gradient whose stops uStops holds
|
||||
// from first, n of them (gpu.Builder.Stops): the first stop's before it,
|
||||
// the last's after it, and between two the colors of both mixed,
|
||||
// premultiplied, in sRGB, or in Oklab, as internal/raster's stopsAt.
|
||||
vec4 stopsAt(vec4 c2, float t, bool lab) {
|
||||
int first = int(c2.x);
|
||||
int n = int(c2.y);
|
||||
if (n <= 0) {
|
||||
return vec4(0.0);
|
||||
}
|
||||
vec4 a = stop(2 * first);
|
||||
vec4 ap = stop(2 * first + 1);
|
||||
if (t <= ap.x) {
|
||||
return premul(a);
|
||||
}
|
||||
vec4 last = stop(2 * (first + n - 1));
|
||||
vec4 lastp = stop(2 * (first + n - 1) + 1);
|
||||
if (t >= lastp.x) {
|
||||
return premul(last);
|
||||
}
|
||||
vec4 b = last;
|
||||
vec4 bp = lastp;
|
||||
for (int i = 1; i < n - 1; i++) {
|
||||
vec4 c = stop(2 * (first + i));
|
||||
vec4 cp = stop(2 * (first + i) + 1);
|
||||
if (t < cp.x) {
|
||||
b = c;
|
||||
bp = cp;
|
||||
break;
|
||||
}
|
||||
a = c;
|
||||
ap = cp;
|
||||
}
|
||||
float f = clamp((t - ap.x) / max(bp.x - ap.x, 1e-6), 0.0, 1.0);
|
||||
float alpha = mix(a.a, b.a, f);
|
||||
if (!lab) {
|
||||
return vec4(mix(a.rgb * a.a, b.rgb * b.a, f), alpha);
|
||||
}
|
||||
if (alpha <= 0.0) {
|
||||
return vec4(0.0);
|
||||
}
|
||||
return vec4(clamp(fromOklab(mix(ap.yzw * a.a, bp.yzw * b.a, f) / alpha), 0.0, 1.0) * alpha, alpha);
|
||||
}
|
||||
|
||||
// paint returns the premultiplied color at p of plain color, a gradient
|
||||
// mixed in sRGB (1) or Oklab (2), stripes (3), or a gradient of stops,
|
||||
// linear (4, 5), conic (6, 7) or radial (8, 9), mixed in sRGB or in
|
||||
// Oklab, as scene.Paint says.
|
||||
vec4 paint(vec2 p, float mode, vec4 rect, vec4 c1, vec4 c2, vec4 g) {
|
||||
if (mode < 0.5) {
|
||||
return premul(c1);
|
||||
}
|
||||
if (mode > 3.5) {
|
||||
float t;
|
||||
if (mode < 5.5) {
|
||||
vec2 d = g.zw - g.xy;
|
||||
t = dot(p - g.xy, d) / max(dot(d, d), 0.0001);
|
||||
} else if (mode < 7.5) {
|
||||
vec2 d = p - g.xy;
|
||||
t = (atan(d.x, -d.y) - g.z) * 0.15915494309189535;
|
||||
t -= floor(t);
|
||||
} else {
|
||||
t = length(p - g.xy) / max(g.z, 0.0001);
|
||||
}
|
||||
return stopsAt(c2, t, mode > 4.5 && mode < 5.5 || mode > 6.5 && mode < 7.5 || mode > 8.5);
|
||||
}
|
||||
if (mode < 2.5) {
|
||||
vec2 d = g.zw - g.xy;
|
||||
float t = clamp(dot(p - g.xy, d) / max(dot(d, d), 0.0001), 0.0, 1.0);
|
||||
float a = mix(c1.a, c2.a, t);
|
||||
if (mode < 1.5) {
|
||||
return vec4(mix(c1.rgb * c1.a, c2.rgb * c2.a, t), a);
|
||||
}
|
||||
vec3 lab = mix(oklab(c1.rgb) * c1.a, oklab(c2.rgb) * c2.a, t);
|
||||
return a > 0.0 ? vec4(clamp(fromOklab(lab / a), 0.0, 1.0) * a, a) : vec4(0.0);
|
||||
}
|
||||
float s = dot(p - rect.xy, g.xy);
|
||||
float phase = s - g.w * floor(s / g.w);
|
||||
float cov = coverage(min(max(-phase, phase - g.z), g.w - phase));
|
||||
return premul(c1) * cov + premul(c2) * (1.0 - cov);
|
||||
}
|
||||
|
||||
// dash returns how much of a dashed border shows at p: each side, which
|
||||
// the pixel belongs to when it is nearest that side's edge in widths of
|
||||
// its border, has an odd number of dashes and gaps of equal length, about
|
||||
// three widths, starting and ending with a dash.
|
||||
float dash(vec2 p, vec4 rect, vec4 w) {
|
||||
vec2 q = p - rect.xy;
|
||||
float dt = w.x > 0.0 ? q.y / w.x : 1e9;
|
||||
float dr = w.y > 0.0 ? (rect.z - q.x) / w.y : 1e9;
|
||||
float db = w.z > 0.0 ? (rect.w - q.y) / w.z : 1e9;
|
||||
float dl = w.w > 0.0 ? q.x / w.w : 1e9;
|
||||
float s;
|
||||
float len;
|
||||
float bw;
|
||||
if (dt <= dr && dt <= db && dt <= dl) {
|
||||
s = q.x;
|
||||
len = rect.z;
|
||||
bw = w.x;
|
||||
} else if (dr <= db && dr <= dl) {
|
||||
s = q.y;
|
||||
len = rect.w;
|
||||
bw = w.y;
|
||||
} else if (db <= dl) {
|
||||
s = rect.z - q.x;
|
||||
len = rect.z;
|
||||
bw = w.z;
|
||||
} else {
|
||||
s = rect.w - q.y;
|
||||
len = rect.w;
|
||||
bw = w.w;
|
||||
}
|
||||
// n - 1 is how many periods of a dash and a gap, six widths, fit in
|
||||
// len: GPUs divide less exactly than CPUs, and may count one too few
|
||||
// or too many where len is a whole number of periods, as sides often
|
||||
// are, so the count is checked by multiplying back.
|
||||
float n = max(1.0, floor((len / (3.0 * bw) + 1.0) * 0.5 + 0.5));
|
||||
float period = 6.0 * bw;
|
||||
n += n * period <= len ? 1.0 : 0.0;
|
||||
n -= (n - 1.0) * period > len ? 1.0 : 0.0;
|
||||
float seg = len / (2.0 * n - 1.0);
|
||||
float k = floor(s / seg);
|
||||
float f = s - k * seg;
|
||||
float edge = min(f, seg - f);
|
||||
return coverage(k - 2.0 * floor(k * 0.5) < 0.5 ? -edge : edge);
|
||||
}
|
||||
|
||||
void main() {
|
||||
Frame fr = frameOf();
|
||||
vec2 p = vPoint.xy;
|
||||
vec2 tex = vPoint.zw;
|
||||
vec2 dtex = fwidth(tex);
|
||||
float kind = vParams.x;
|
||||
vec4 res;
|
||||
float glyphCov = vTransform0.w > 0.5 ? localCoverage(p, vRect, vec4(0.0), 1.0, fr) : 1.0;
|
||||
float clip = clipCoverage();
|
||||
// The dispatch below is a chain of ifs with early returns, not one else-if chain:
|
||||
// an else-if chain here fails to link in ANGLE's D3D11 backend on Windows (an
|
||||
// empty info log, and every WebGL context in the page is lost; Firefox's headless
|
||||
// build exits at the link). See https://issues.chromium.org/issues/573007971 and
|
||||
// https://bugzilla.mozilla.org/show_bug.cgi?id=2081240. The shape is load-bearing.
|
||||
if (kind < 0.5) {
|
||||
float outer = localCoverage(p, vRect, vRadii, vTransform0.w, fr);
|
||||
// vParams.y: 1 dashes the border, 2 paints it with the gradient (the
|
||||
// inside with plain color), 3 both.
|
||||
bool borderPaint = vParams.y > 1.5;
|
||||
vec4 pc = paint(p, vParams.z, vRect, vColor, vColor2, vGrad);
|
||||
res = (borderPaint ? premul(vColor) : pc) * outer;
|
||||
vec4 bw = vWidths; // top, right, bottom, left
|
||||
if (any(greaterThan(bw, vec4(0.0)))) {
|
||||
vec4 ir = vec4(vRect.xy + bw.wx, vRect.zw - bw.yz - bw.wx);
|
||||
float innerCov = (ir.z > 0.0 && ir.w > 0.0) ? localCoverage(p, ir, vInner, vTransform0.w, fr) : 0.0;
|
||||
float bc = clamp(outer - innerCov, 0.0, 1.0);
|
||||
float dashed = vParams.y - (borderPaint ? 2.0 : 0.0);
|
||||
if (dashed > 0.5) {
|
||||
bc *= dash(p, vRect, bw);
|
||||
}
|
||||
vec4 b = (borderPaint ? pc * vec4(vBorder.rgb * vBorder.a, vBorder.a) : premul(vBorder)) * bc;
|
||||
res = b + res * (1.0 - b.a);
|
||||
}
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (kind < 1.5 && vParams.y > 0.5) {
|
||||
// An inner shadow: inside the box, what the hole, blurred, leaves.
|
||||
float sigma = vParams.z;
|
||||
float hole = 0.0;
|
||||
if (vWidths.z > 0.0 && vWidths.w > 0.0) {
|
||||
float corner = max(max(vInner.x, vInner.y), max(vInner.z, vInner.w));
|
||||
hole = sigma > 0.0 ? boxShadow(p, vWidths, sigma, corner) : localCoverage(p, vWidths, vInner, vTransform0.w, fr);
|
||||
}
|
||||
res = premul(vColor) * (localCoverage(p, vRect, vRadii, vTransform0.w, fr) * (1.0 - hole));
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (kind < 1.5) {
|
||||
float sigma = vParams.z;
|
||||
float corner = max(max(vRadii.x, vRadii.y), max(vRadii.z, vRadii.w));
|
||||
float s =
|
||||
sigma > 0.0 ? boxShadow(p, vRect, sigma, corner) : localCoverage(p, vRect, vRadii, vTransform0.w, fr);
|
||||
if (vWidths.z > 0.0 && vWidths.w > 0.0) {
|
||||
s *= 1.0 - localCoverage(p, vWidths, vInner, vTransform0.w, fr); // outside the box casting it
|
||||
}
|
||||
res = premul(vColor) * s;
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (kind < 2.5) {
|
||||
vec4 c = paint(p, vParams.z, vRect, vColor, vColor2, vGrad);
|
||||
res = c *
|
||||
textCoverage(sampleLocal(uMask, tex, vWidths, vTransform0.w).r, unpremul(c), vInner.x, vInner.y,
|
||||
vRadii) *
|
||||
glyphCov;
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (kind < 3.5) {
|
||||
res = sampleLocal(uColor, tex, vWidths, vTransform0.w) * vColor.a * glyphCov;
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
if (kind < 4.5) {
|
||||
if (vParams.y > 1.5) {
|
||||
// A frame of video: its luma and its chroma, converted.
|
||||
float code = vParams.y - 2.0;
|
||||
float gray = code > 7.5 ? 1.0 : 0.0;
|
||||
// The chroma covers twice its size in luma, a column or row
|
||||
// more than an odd size has.
|
||||
vec2 cs = vec2(textureSize(uImage, 0)) / (2.0 * vec2(textureSize(uChroma, 0)));
|
||||
res = vec4(yuvToRGB(sampleImage(uImage, tex, vWidths, vParams.z, dtex).r,
|
||||
sampleImage(uChroma, tex * cs, vWidths * cs.xyxy, vParams.z, dtex * cs).rg,
|
||||
code - 8.0 * gray),
|
||||
1.0);
|
||||
if (gray > 0.5) {
|
||||
res.rgb = vec3(dot(res.rgb, vec3(0.2126, 0.7152, 0.0722)));
|
||||
}
|
||||
} else {
|
||||
res = sampleImage(uImage, tex, vWidths, vParams.z, dtex);
|
||||
if (vParams.y > 0.5) {
|
||||
res.rgb = vec3(dot(res.rgb, vec3(0.2126, 0.7152, 0.0722)));
|
||||
}
|
||||
}
|
||||
res = tint(res, vColor) * localCoverage(p, vRect, vRadii, vTransform0.w, fr);
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
{
|
||||
vec4 c = paint(p, vParams.z, vRect, vColor, vColor2, vGrad);
|
||||
vec3 straight = unpremul(c);
|
||||
if (vTransform0.w > 0.5) {
|
||||
vec3 rgb = sampleLocal(uColor, tex, vWidths, 1.0).rgb;
|
||||
res = c * textCoverage((rgb.r + rgb.g + rgb.b) / 3.0, straight, vInner.x, vInner.y, vRadii) *
|
||||
glyphCov;
|
||||
fragColor = res * clip * vParams.w;
|
||||
#ifdef DUAL
|
||||
fragAlpha = fragColor.aaaa;
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
vec3 a = subpixelCoverage(sampleLocal(uColor, tex, vWidths, vTransform0.w).rgb, straight, vInner.x,
|
||||
vInner.y, vRadii);
|
||||
vec3 w = a * c.a * clip * vParams.w;
|
||||
float wa = (w.r + w.g + w.b) / 3.0;
|
||||
#ifdef DUAL
|
||||
fragColor = vec4(straight * w, wa);
|
||||
fragAlpha = vec4(w, wa);
|
||||
#else
|
||||
fragColor = vec4(straight * wa, wa);
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
// The passes computing the backdrop of an effect draw a quad over their
|
||||
// target, scissored to the texels they compute, and address texels by
|
||||
// their index in memory, so that the rows of their textures go down as
|
||||
// the frame's rows do.
|
||||
#ifdef PASS_VERTEX
|
||||
|
||||
void main() {
|
||||
vec2 corner = vec2(float(gl_VertexID & 1), float(gl_VertexID >> 1));
|
||||
gl_Position = vec4(corner * 2.0 - 1.0, 0.0, 1.0);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef DOWN
|
||||
|
||||
// down averages the square of the area that texel stands for, repeating
|
||||
// the area's last pixels past its far edges, or, for an image blurred
|
||||
// (uMode & 1), reading them as transparent. The area of the frame (from
|
||||
// uOrigin to uLimit) is copied to uSrc from the bottom row up: the row y
|
||||
// of the frame is uShift.y - y there, and the column x is x - uShift.x;
|
||||
// an image whose rows go down (uMode & 2) has its row y at y - uShift.y.
|
||||
uniform sampler2D uSrc;
|
||||
uniform ivec2 uOrigin;
|
||||
uniform ivec2 uLimit;
|
||||
uniform ivec2 uShift;
|
||||
uniform int uDown;
|
||||
uniform int uMode;
|
||||
|
||||
out vec4 passColor;
|
||||
|
||||
void main() {
|
||||
ivec2 o = uOrigin + ivec2(gl_FragCoord.xy) * uDown;
|
||||
vec4 c = vec4(0.0);
|
||||
for (int y = 0; y < uDown; y++) {
|
||||
for (int x = 0; x < uDown; x++) {
|
||||
ivec2 at = o + ivec2(x, y);
|
||||
if ((uMode & 1) != 0 && (at.x > uLimit.x || at.y > uLimit.y)) {
|
||||
continue;
|
||||
}
|
||||
at = min(at, uLimit);
|
||||
int row = (uMode & 2) != 0 ? at.y - uShift.y : uShift.y - at.y;
|
||||
c += texelFetch(uSrc, ivec2(at.x - uShift.x, row), 0);
|
||||
}
|
||||
}
|
||||
passColor = c * (1.0 / float(uDown * uDown));
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef BLUR
|
||||
|
||||
// blur blurs along a row or a column, clamping at its ends, or, for an
|
||||
// image blurred (uMode & 1), transparent beyond them.
|
||||
uniform sampler2D uSrc;
|
||||
uniform ivec2 uLimit;
|
||||
uniform ivec2 uDir;
|
||||
uniform int uRadius;
|
||||
uniform float uSigma;
|
||||
uniform int uMode;
|
||||
|
||||
out vec4 passColor;
|
||||
|
||||
void main() {
|
||||
ivec2 at = ivec2(gl_FragCoord.xy);
|
||||
vec4 c = vec4(0.0);
|
||||
float sum = 0.0;
|
||||
for (int o = -uRadius; o <= uRadius; o++) {
|
||||
float x = float(o);
|
||||
float w = uSigma > 0.0 ? exp(-(x * x) / (2.0 * uSigma * uSigma)) : 1.0;
|
||||
ivec2 q = at + uDir * o;
|
||||
sum += w;
|
||||
if ((uMode & 1) != 0 && (any(lessThan(q, ivec2(0))) || any(greaterThan(q, uLimit)))) {
|
||||
continue;
|
||||
}
|
||||
c += texelFetch(uSrc, clamp(q, ivec2(0), uLimit), 0) * w;
|
||||
}
|
||||
passColor = c / sum;
|
||||
}
|
||||
|
||||
#endif
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package gl
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
)
|
||||
|
||||
// GLX's functions UnsyncGLXSwaps calls, through libepoxy's pointers, as GDK
|
||||
// calls them; nil where libepoxy has no GLX.
|
||||
var glx struct {
|
||||
once sync.Once
|
||||
currentDisplay *uintptr // glXGetCurrentDisplay
|
||||
currentContext *uintptr // glXGetCurrentContext
|
||||
currentDrawn *uintptr // glXGetCurrentDrawable
|
||||
queryContext *uintptr // glXQueryContext
|
||||
intervalEXT *uintptr // glXSwapIntervalEXT
|
||||
intervalMESA *uintptr // glXSwapIntervalMESA
|
||||
hasExtension func(dpy uintptr, screen int32, ext string) bool
|
||||
}
|
||||
|
||||
// glxScreen is GLX_SCREEN, which glXQueryContext tells.
|
||||
const glxScreen = 0x800C
|
||||
|
||||
// UnsyncGLXSwaps sets the swap interval of the GLX drawable current to 0,
|
||||
// so that its swaps wait for no vertical blank, for frames uncapped
|
||||
// (MYGO_UNCAPPED): the backend calls it as GDK paints a window it
|
||||
// composites with OpenGL on X11, with the window's paint context current.
|
||||
// GDK sets 1 there on a display without a compositor, which holds frames
|
||||
// to the display's refreshes, and 0 under a compositor, which paces the
|
||||
// window itself (gdk/x11/gdkglcontext-x11.c); GDK's EGL, on Wayland, swaps
|
||||
// with 0 already. It sets the interval with GLX_EXT_swap_control, else
|
||||
// GLX_MESA_swap_control (GLX_SGI_swap_control takes no 0), and does
|
||||
// nothing without either, or without a context current. GDK sets its own
|
||||
// interval again only when a compositor starts or stops, so a call each
|
||||
// paint keeps 0, which costs nothing once set.
|
||||
func UnsyncGLXSwaps() {
|
||||
if load() != nil {
|
||||
return
|
||||
}
|
||||
g := &glx
|
||||
g.once.Do(func() {
|
||||
lib, err := purego.Dlopen("libepoxy.so.0", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ptr := func(name string) *uintptr {
|
||||
sym, err := purego.Dlsym(lib, "epoxy_"+name)
|
||||
if err != nil || sym == 0 {
|
||||
return nil
|
||||
}
|
||||
return *(**uintptr)(unsafe.Pointer(&sym))
|
||||
}
|
||||
if sym, err := purego.Dlsym(lib, "epoxy_has_glx_extension"); err == nil && sym != 0 {
|
||||
purego.RegisterFunc(&g.hasExtension, sym)
|
||||
}
|
||||
g.currentDisplay, g.currentContext, g.currentDrawn = ptr("glXGetCurrentDisplay"), ptr("glXGetCurrentContext"), ptr("glXGetCurrentDrawable")
|
||||
g.queryContext, g.intervalEXT, g.intervalMESA = ptr("glXQueryContext"), ptr("glXSwapIntervalEXT"), ptr("glXSwapIntervalMESA")
|
||||
})
|
||||
if g.hasExtension == nil || g.currentDisplay == nil || g.currentContext == nil || g.currentDrawn == nil || g.queryContext == nil {
|
||||
return
|
||||
}
|
||||
dpy, _, _ := purego.SyscallN(*g.currentDisplay)
|
||||
ctx, _, _ := purego.SyscallN(*g.currentContext)
|
||||
drawable, _, _ := purego.SyscallN(*g.currentDrawn)
|
||||
if dpy == 0 || ctx == 0 || drawable == 0 {
|
||||
return
|
||||
}
|
||||
var screen int32
|
||||
if r, _, _ := purego.SyscallN(*g.queryContext, dpy, ctx, glxScreen, uintptr(unsafe.Pointer(&screen))); r != 0 {
|
||||
return // not Success
|
||||
}
|
||||
switch {
|
||||
case g.intervalEXT != nil && g.hasExtension(dpy, screen, "GLX_EXT_swap_control"):
|
||||
purego.SyscallN(*g.intervalEXT, dpy, drawable, 0)
|
||||
case g.intervalMESA != nil && g.hasExtension(dpy, screen, "GLX_MESA_swap_control"):
|
||||
purego.SyscallN(*g.intervalMESA, 0)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user