gl

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 23 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package gl is the OpenGL backend of the GPU renderer: a gpu.Device that executes internal/render/gpu frames with OpenGL 3.3 core and a presenter that shows them in a GTK3 GtkGLArea.

It calls OpenGL through purego without cgo. On Linux the GL entry points come from libepoxy (libepoxy.so.0), which dispatches to GLX or EGL, whichever context is current; headless devices (tests, readback) create an EGL surfaceless context through libEGL.so.1. On darwin a CGL context on OpenGL.framework (4.1 core) serves tests and local verification only: applications on macOS render with internal/render/gpu/metal. The quad shader (internal/render/gpu/gen.QuadGLSLVertex and QuadGLSLFragment) is compiled by the driver at run time.

Every GL object and the function table belong to a context: nothing GL is kept in package variables, so a lost context (Android's EGL_CONTEXT_LOST) is replaced by creating a new context and device. GL calls run only on the thread the context is current on: a headless context owns a goroutine locked to its OS thread and runs every call there.

The backend exists on linux and darwin. Everywhere else NewDevice fails with ErrUnsupported.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnsupported is returned on platforms without the OpenGL backend
	// (anything but linux and darwin).
	ErrUnsupported = errors.New("gl: OpenGL is not available on this platform")
	// ErrNoDevice is wrapped by the error returned when no OpenGL 3.3 core
	// context could be created: libepoxy, libEGL or the driver is missing,
	// or the driver offers less than OpenGL 3.3. Use the CPU renderer.
	ErrNoDevice = errors.New("gl: no OpenGL 3.3 device")
	// ErrClosed is returned by calls on a device or presenter after Close.
	ErrClosed = errors.New("gl: use after Close")
)

Functions

func NewPresenter

func NewPresenter(glarea uintptr) (r paint.Renderer, present func(size image.Point, scale float32) error, err error)

NewPresenter attaches a GPU renderer to a GtkGLArea obtained from platform.CanvasGL.UseGLArea. Main thread (the GTK thread) only. On other platforms it returns an error wrapping ErrUnsupported.

It makes the area's context current, loads its GL functions, creates a Device on it (failing with an error wrapping ErrNoDevice without libgtk-3, libepoxy or OpenGL 3.3, and with the driver's info log when the shader does not compile) and connects the area's "render" signal. r is a gpu.Renderer over the Device; it also implements interface{ Close() error }, which disconnects the signal, deletes the GL objects when the area still has the Device's context (see above) and drops the reference to the area (main thread, idempotent; r and present fail with ErrClosed afterwards), and interface{ GLRenderer() string }, which returns the context's GL_RENDERER string as read in NewPresenter (e.g. "llvmpipe (LLVM 15.0.6, 128 bits)" for Mesa's software rasterizer; uihost keeps windows on the CPU on software renderers).

present(size, scale) shows the frame r rendered last: size is the area's size in device pixels, round(Size*Scale) (scale is informational). It returns nil without presenting when size is empty; otherwise it queues a render of the area, in which the frame is blitted (see above). It returns the error of a failed blit, and an error wrapping gpu.ErrDeviceLost once the device is unusable — after which r.Render fails with gpu.ErrDeviceLost too, and the caller should go back to the CPU renderer.

Types

type Device

type Device struct {
	// contains filtered or unexported fields
}

Device executes gpu.Frames with OpenGL 3.3 core into a persistent offscreen GL_RGBA8 texture attached to a framebuffer object (premultiplied alpha), recreated when Frame.Size changes. It follows internal/render/gpu/metal's Device (the reference for every behaviour below); the differences come from OpenGL itself. The target stores row 0 at the top (the quad vertex shader flips y), so glViewport, glScissor and glReadPixels take the frame contract's top-left coordinates unchanged.

Threads. GL calls run only on the thread the device's context is current on: every method hands its GL work to the run function the device was built with — for NewDevice the goroutine, locked to its OS thread, of the device's own headless context; for a presenter its caller's thread with the context made current. Every GL object belongs to the device (nothing GL lives in package variables), so a lost context is replaced by a new context and a new device.

Synchronization. GL executes a context's commands in the order they are issued. Execute issues a frame and calls glFlush without waiting (the CPU work of the next frame overlaps the GPU work of this one, as with Metal's commit); ReadPixels waits through glReadPixels. A buffer or texture the CPU writes while earlier commands still read it is renamed or waited for by the driver, and a deleted object lives on until the commands using it ran.

Uploads. Each upload is a glTexSubImage2D into its texture, issued in command order: Frame.Uploads, then for every batch its Uploads followed by its draw, so a later batch's upload never changes what an earlier batch sampled (Metal gets this with blits between render passes). Rows are GL_UNPACK_ROW_LENGTH = Stride/bpp texels apart (GL_UNPACK_ALIGNMENT 1). A (re)created texture's contents are undefined until uploaded; the Renderer re-uploads everything it samples when MaskSize/ColorSize/RampSize change.

Instances. All of a frame's instances are written into one array buffer, orphaned first with glBufferData(nil) (fresh storage while the previous frame's draws may still read the old) and filled with glBufferSubData, one call per batch. Each batch points the vertex attributes (divisor 1) at its first instance and draws a 4-vertex triangle strip per instance with glDrawArraysInstanced, scissored to its Scissor (empty: the whole target), with the viewport its target's size, blending with glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA). A partial frame's clearing quads follow the batches' instances.

Images. Each gpu.ImageUpload creates a GL_RGBA8 texture of its own from its pixels (replacing one of the same ID), kept in d.images until Frame.ImageFrees names it (deleted first; GL keeps a deleted texture until the draws already issued that sample it have run). Every batch binds its Batch.Image texture to unit TexImage, or a 1×1 transparent placeholder.

Layers. Each gpu.Frame.Layers entry is drawn into a GL_RGBA8 texture with a framebuffer of its own, from a pool (layerPool, layers.go: Metal's assignLayers with the same reuse rule, 128 MiB budget and 120-frame idle release). A layer's first bind clears it to transparent. Switching framebuffers first binds the placeholder to the image and layer units, so a pooled texture is never bound for sampling while it is the render target (a feedback loop, undefined in GL; a pooled texture may have been sampled by an earlier batch under another layer number), and GL orders the new draws after the ones that sampled it. Batches drawing into a layer run with ViewSize its texture's size and Origin its Bounds.Min; composites sampling a larger pooled texture get their UVs rescaled (devkit.RescaleComposites). The frame's target is never bound for sampling.

Backdrop grabs (gpu.Batch.Grab) are a glBlitFramebuffer (GL_NEAREST, equal sizes) from the source target's framebuffer into the grab layer's, with the image and layer units on the placeholder (grab, device.go).

Partial frames (gpu.Frame.Dirty). The target persists between frames, so the device is a gpu.Retainer. A partial frame is refused with gpu.ErrNotRetained unless the target holds the last frame (not recreated, no failure since that may have drawn into it, the device not lost). Its Copies go first: every source is blitted (glBlitFramebuffer, GL_NEAREST) into a scratch texture, then from there to its destination (overlapping blits within one framebuffer are undefined). The target is not cleared: each dirty rectangle gets one quad drawn without blending, scissored to it, in Frame.Clear; every batch drawing into the target is then drawn once per dirty rectangle with its scissor intersected with it. Layers are cleared and drawn as always. A full frame's target is cleared to Frame.Clear with glClear.

Failures. GL reports errors through glGetError, read (until it returns GL_NO_ERROR) at the end of every frame, and through glGetGraphicsResetStatus where the context offers it (OpenGL 4.5, GL_KHR_robustness or GL_ARB_robustness). A frame ending with a GL error, or whose new render target makes an incomplete framebuffer, is a failure: it may have drawn part of the frame, so the target holds no frame (ReadPixels fails, Retained is false) until the next successful one; so does a failure creating a layer or scratch framebuffer, found before anything is drawn, as Metal's failures before encoding. maxFailures failed frames in a row with no successful one in between, a GL_OUT_OF_MEMORY, or a context reset mark the device lost: from then on every call returns an error wrapping gpu.ErrDeviceLost, and the caller should switch to the CPU renderer (with a new device on a new context GL may work again). A frame whose textures exceed the limit (min(GL_MAX_TEXTURE_SIZE, 16384)) is rejected up front with gpu.ErrTargetTooLarge, as an invalid frame (an unknown or out-of-range upload) is with a plain error: nothing is allocated or issued, and neither is a failure, counted, or able to lose the device.

Methods are serialized by a mutex; a Device serves one Renderer.

func NewDevice

func NewDevice() (*Device, error)

NewDevice creates a headless device: an OpenGL 3.3 core context of its own (EGL surfaceless on Linux, CGL on darwin, where it serves tests only) on a dedicated OS thread, and the quad shader compiled for it. It fails with an error wrapping ErrNoDevice when no such context can be created, and with the driver's info log when the shader does not compile or link; the caller then uses the CPU renderer.

func (*Device) Close

func (d *Device) Close()

Close deletes every GL object of the device and, for a device from NewDevice, its context and thread. It is safe to call more than once.

func (*Device) Execute

func (d *Device) Execute(fr *gpu.Frame) error

Execute implements gpu.Device. A frame without pixels is skipped without issuing anything.

func (*Device) ReadPixels

func (d *Device) ReadPixels() (*image.RGBA, error)

ReadPixels waits for the last frame and returns a copy of the render target: RGBA8, premultiplied alpha, Frame.Size of that frame, row 0 at the top. It fails before the first frame with pixels, after a failed frame, and with an error wrapping gpu.ErrDeviceLost once the device is lost.

func (*Device) Retained

func (d *Device) Retained(size image.Point) bool

Retained implements gpu.Retainer: the target holds the last frame executed at size, and nothing since recreated it, failed a frame that may have drawn into it, or lost or closed the device.

Directories

Path Synopsis
Package nativewindow is the hand-over point between a platform canvas that owns a native window (an Android ANativeWindow) and the OpenGL ES presenter that draws into it (gl.NewPresenterAndroid).
Package nativewindow is the hand-over point between a platform canvas that owns a native window (an Android ANativeWindow) and the OpenGL ES presenter that draws into it (gl.NewPresenterAndroid).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL