scene

package
v0.1.18 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 6 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 scene is the display list the ui package paints a frame into and the renderers draw: rounded rectangles with borders and gradients, box shadows, glyphs from a shared atlas, images, effects and clips, in paint order. Geometry is in device pixels with the origin at the top-left corner.

Index

Constants

View Source
const MaxAtlasSize = 4096

MaxAtlasSize is the largest width and height an Atlas grows to.

View Source
const MaxStops = 32

MaxStops is how many stops a gradient has at most, which the shaders loop through.

View Source
const ThinBoost = 0.5

ThinBoost is the contrast Direct2D adds for thin glyphs.

Variables

This section is empty.

Functions

func BlurWeight

func BlurWeight(i int, sigma float32) float32

BlurWeight returns the weight of the texel i texels away in a blur of standard deviation sigma, before the weights are divided by their sum.

func Corners

func Corners(r Rect, radii [4]float32, continuous bool) [4]float32

Corners returns radii as renderers take them: fitted to r (FitRadii), and negative for continuous corners.

func FitRadii

func FitRadii(r Rect, radii [4]float32) [4]float32

FitRadii scales corner radii down so that adjacent ones fit along each side of r, as CSS does; renderers apply it before drawing.

func FoldTranslations

func FoldTranslations()

FoldTranslations makes renderers fold the ops that only translate (TranslationFolder), from the next scene they draw. Package ui calls it as it builds a view, before drawing it, each frame, and wherever it makes a translation, on any goroutine: it sets fold only the first time, and costs a load after.

func GammaRatios

func GammaRatios(gamma float32) [4]float32

GammaRatios returns Direct2D's alpha correction ratios for text blended at a gamma between 1 and 2.2, as Windows Terminal computes them.

func HasBorder

func HasBorder(w [4]float32) bool

HasBorder reports whether any of the widths is positive.

func ImageArea

func ImageArea(src Rect, w, h int) image.Rectangle

ImageArea returns the pixels of an image of w×h that src, a rectangle of them, touches, which a blur of it reads.

func MovedClip added in v0.1.13

func MovedClip(r Rect, m Affine) (Rect, Affine)

MovedClip returns the rectangle of a clip of r under m, and what of m is left to apply to it: nothing when m only moves it, as a pose sliding a panel in or a card lifting under the pointer does. A clip only moved is a rectangle like any other, which renderers cut as they cut those that nothing transforms, rather than with a mask of its transformed shape.

func Oklab

func Oklab(c Color) [3]float32

Oklab returns c, in sRGB, in the Oklab color space, as the renderers mix gradients in it: the CPU's from this, the GPU's from the stops' values it gives them, or from the same math in their shaders.

func Reshaped added in v0.1.17

func Reshaped(s *Scene, op *Op) bool

Reshaped reports whether op of s draws under a transform that does more than move it (scales, turns, skews it or shows it in perspective): its own, or, for glyphs and an effect masked by glyphs, a glyph's. Drawing a transform only moves lies in its clips as it would unmoved, which the GPU's renderers cut in the frame's coordinates whatever the transform, so the clips around it need no mask (gpu.Builder), and damage tracking has them change no more than for drawing not moved (Differ). Clips are the same (MovedClip): a clip pushed under a transform that only moves it reshapes none around it.

func SDRoundRect

func SDRoundRect(r Rect, radii [4]float32, px, py float32) float32

SDRoundRect returns the signed distance from (px, py) to the edge of the rounded rectangle r with radii (fitted), negative inside, as the shaders' sdRoundRect.

func SubpixelCoverage

func SubpixelCoverage(a, c [3]float32, contrast, boost float32, g [4]float32) [3]float32

SubpixelCoverage corrects the coverage of each subpixel of a subpixel glyph of straight color c, as Direct2D blends ClearType text.

func TextCoverage

func TextCoverage(a float32, c [3]float32, contrast, boost float32, g [4]float32) float32

TextCoverage corrects the coverage a of a glyph of straight color c, as Direct2D blends text: it enhances the contrast by contrast, the more the darker c is, plus boost, and corrects for the gamma of the ratios g.

func Uniform

func Uniform(w float32) [4]float32

Uniform returns the widths of a border as wide on every side.

Types

type Affine

type Affine struct {
	A, B, C, D, X, Y float32
	G, H             float32
	Set              bool
	Behind           bool
}

Affine maps drawing coordinates to frame coordinates: an affine map, or, when G or H is set, a projective one, which shows a plane turned in 3D in perspective, x and y going to

((A*x + C*y + X) / w, (B*x + D*y + Y) / w), with w = G*x + H*y + 1,

or, when Behind is set, with w = G*x + H*y - 1. What shows is where w is positive, in front of the viewer. Behind keeps its sign for a plane whose origin, (0, 0), is behind the viewer though what is drawn on it is in front: a card turning over in perspective far from the origin, its horizon between the card and the origin. Behind is set only with G or H.

The zero value is identity; Set distinguishes a singular matrix (including scale zero).

func Matrix

func Matrix(a, b, c, d, x, y float32) Affine

func Projective

func Projective(a, b, c, d, x, y, g, h float32) Affine

Projective returns the projective map of the matrix

| a c x |
| b d y |
| g h 1 |

func Rotation

func Rotation(degrees float32) Affine

func Scaling

func Scaling(x, y float32) Affine

func Translation

func Translation(x, y float32) Affine

func (Affine) Bounds

func (m Affine) Bounds(r Rect) Rect

func (Affine) Inverse

func (m Affine) Inverse() (Affine, bool)

func (Affine) Mul

func (m Affine) Mul(n Affine) Affine

Mul returns m*n: n acts first, then m.

func (Affine) Perspective

func (m Affine) Perspective() bool

Perspective reports whether m is projective, not affine.

func (Affine) Pixels

func (m Affine) Pixels(scale float32) Affine

Pixels expresses a DIP transform in device pixels.

func (Affine) Point

func (m Affine) Point(x, y float32) (float32, float32)

Point returns where m maps (x, y). A point behind the viewer of a projective map (W not positive) goes far away.

func (Affine) Translation

func (m Affine) Translation() (x, y float32, ok bool)

Translation returns how far m moves, when it only translates.

func (Affine) VectorAt

func (m Affine) VectorAt(x, y, dx, dy float32) (float32, float32)

VectorAt returns how far m moves the point (x, y) moved by (dx, dy): the same for every point of an affine map.

func (Affine) W

func (m Affine) W(x, y float32) float32

W returns the projective divisor of (x, y): positive in front of the viewer, as all of an affine map's plane is.

type Atlas

type Atlas struct {
	// BPP is the number of bytes per pixel: 1 for coverage masks, 4 for
	// premultiplied RGBA.
	BPP int
	// W and H are the size in pixels; Pix holds rows of W*BPP bytes.
	W, H int
	Pix  []byte
	// contains filtered or unexported fields
}

Atlas packs small bitmaps, such as rasterized glyphs, into one larger bitmap that renderers keep as a texture. It records which rectangles changed so that renderers upload only those. Main thread only.

Lasting bitmaps fill shelves down from the top. Bitmaps a single frame draws, such as the masks of animated shapes, fill shelves up from the bottom, and ResetTransient frees them all at once, so that they never crowd out the lasting ones.

func NewAtlas

func NewAtlas(bpp, w, h int) *Atlas

NewAtlas returns an empty w×h atlas of bpp bytes per pixel.

func (*Atlas) Alloc

func (a *Atlas) Alloc(w, h int) (x, y int, ok bool)

Alloc reserves a lasting w×h rectangle, keeping a pixel of padding to its right and below it so that filtering never reads a neighbor. It reports false when the atlas is full; the caller then repacks, grows or resets it.

func (*Atlas) AllocTransient

func (a *Atlas) AllocTransient(w, h int) (x, y int, ok bool)

AllocTransient is Alloc for a rectangle needed until ResetTransient.

func (*Atlas) Changes

func (a *Atlas) Changes(gen, version uint64) (rects []image.Rectangle, full bool)

Changes returns the rectangles changed since version, or full when the renderer, which last uploaded version of generation gen, must upload everything.

func (*Atlas) Generation

func (a *Atlas) Generation() uint64

Generation changes when the atlas is resized, reset or repacked, which makes renderers create a new texture and upload all of it.

func (*Atlas) Grow

func (a *Atlas) Grow() bool

Grow doubles the atlas up to MaxAtlasSize, keeping its lasting bitmaps where they are; it frees the transient ones. It reports false when the atlas is already at its largest.

func (*Atlas) Put

func (a *Atlas) Put(x, y, w, h int, src []byte, stride int)

Put copies a w×h bitmap with rows of stride bytes to (x, y), and clears the padding after it, which may hold an earlier bitmap's pixels.

func (*Atlas) Repack

func (a *Atlas) Repack(rects []image.Rectangle) ([]image.Point, bool)

Repack frees the atlas and allocates rects, lasting rectangles of it, again, tallest first, moving their pixels along. It returns where each went, or false, changing nothing, when they do not fit.

func (*Atlas) Reset

func (a *Atlas) Reset()

Reset empties the atlas: every allocation becomes invalid.

func (*Atlas) ResetTransient

func (a *Atlas) ResetTransient()

ResetTransient frees the rectangles AllocTransient reserved.

func (*Atlas) Version

func (a *Atlas) Version() uint64

Version increases with every change.

type Backdrop

type Backdrop struct {
	Area   image.Rectangle
	Down   int
	Sigma  float32
	Radius int
}

Backdrop is what an effect reads of what is behind it: the pixels of Area, averaged over squares of Down pixels a side into a smaller image (Size), which a Gaussian of standard deviation Sigma (BlurWeight) blurs, out to Radius texels each way, first along rows, then along columns. Renderers keep each step in 8 bits a channel, rounded to the nearest, as textures hold them.

func BackdropOf

func BackdropOf(r Rect, blur float32, w, h int) Backdrop

BackdropOf returns the backdrop of a shape r blurred by blur, in a frame of w×h pixels: what the blur reaches around it.

Large blurs are computed at a fraction of the size, as browsers do, a power of two up to 8 that leaves the blur at least 2 texels: the average of each square adds a variance of Down²/12 pixels², which the blur leaves out.

func ImageBlur

func ImageBlur(area image.Rectangle, blur float32) Backdrop

ImageBlur returns how an image's area is blurred by blur, the standard deviation in its pixels (Op.Blur): averaged over squares of Down pixels a side and blurred as a backdrop is (BackdropOf), within the area, which it reads as transparent beyond.

func (Backdrop) ImageSrc

func (b Backdrop) ImageSrc(src Rect) Rect

ImageSrc returns where src, a rectangle of an image's pixels within the area b blurs, lies in the blurred texels.

func (Backdrop) Size

func (b Backdrop) Size() (w, h int)

Size returns the size of the averaged image, in texels.

type BackdropImage

type BackdropImage struct {
	Backdrop
	// Transform maps local sampling coordinates to the frame.
	Transform Affine
	W, H      int
	Pix       []float32
}

BackdropImage is a backdrop as the CPU renderer computes it: W×H texels of premultiplied RGBA, each channel a byte over 255, as a texture reads.

func (*BackdropImage) Sample

func (b *BackdropImage) Sample(x, y float32) [3]float32

Sample returns the backdrop at (x, y), in the frame's pixels, premultiplied RGB, filtered bilinearly from its texels and clamped to its edges, as the shaders' sampleBackdrop.

type ClipCorners added in v0.1.17

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

ClipCorners follows the clips of a scene, op by op, to find those that reach into the rounded corners of a clip around them (Push). The GPU's renderers cut drawing with the innermost clip's shape in the shader and with the scissor rectangles of the others, which cut no corners: drawing in a clip that reaches into those of one around it is cut with a mask of the clips instead (gpu.Builder), whose pixels at the clips' edges differ from the shader's by a unit in the last place (Differ).

func (*ClipCorners) Pop added in v0.1.17

func (c *ClipCorners) Pop()

Pop leaves the innermost clip, at an OpPopClip.

func (*ClipCorners) Push added in v0.1.17

func (c *ClipCorners) Push(op *Op) int

Push enters op, an OpPushClip, and returns the place among the clips open around it (0 the outermost) of the innermost whose rounded corners what op lets through reaches into, or -1 for none.

func (*ClipCorners) Reset added in v0.1.17

func (c *ClipCorners) Reset()

Reset forgets the clips pushed, for a new scene.

type ClipShape

type ClipShape struct {
	Rect       Rect
	Radii      [4]float32
	Transform  Affine
	Continuous bool
	// Paint, unless PaintSolid, is a gradient whose alpha masks the clip,
	// with Gradient, Color, Color2 and Stops, as an OpFill's.
	Paint         Paint
	Gradient      [4]float32
	Color, Color2 Color
	Stops         []Stop
	// Mask, unless nil, is an image whose alpha in MaskSrc, drawn over
	// Rect, masks the clip, as it was at MaskVersion.
	Mask        *Image
	MaskSrc     Rect
	MaskVersion uint64
}

ClipShape is a clip in the coordinate system in which it was pushed.

func ClipShapeOf added in v0.1.17

func ClipShapeOf(op *Op, stops []Stop) ClipShape

ClipShapeOf returns the shape of op, an OpPushClip of a scene with stops, moved as MovedClipOp moves it: its Stops are a part of stops.

func (*ClipShape) Masks added in v0.1.17

func (c *ClipShape) Masks() bool

Masks reports whether a gradient or an image masks the clip, which then lets through less than all of what it holds inside its rounded rectangle.

func (*ClipShape) Same added in v0.1.17

func (c *ClipShape) Same(o *ClipShape) bool

Same reports whether the clips are the same, their stops compared by what they hold.

type Color

type Color struct{ R, G, B, A uint8 }

Color is a straight (not premultiplied) sRGB color.

func (Color) Premul

func (c Color) Premul(opacity float32) [4]float32

Premul returns the color premultiplied by its alpha, with every component between 0 and 1, times opacity.

type Differ

type Differ struct {
	// Reach is how far, in pixels, a renderer draws beyond the geometry of
	// an operation: its antialiased edge, a pixel for the CPU's. Three more
	// are added under a transform, whose quads the GPU's renderers grow by
	// a pixel or two.
	Reach float32
	// Wide compares the colors outside the sRGB gamut (Scene.Wide) too, for
	// a renderer that draws them; others draw their nearest sRGB colors,
	// which the operations hold.
	Wide bool
	// contains filtered or unexported fields
}

A Differ finds where the successive scenes of a window differ, so that a renderer redraws only there: a blinking caret, a ticking clock or a button under the pointer redraws only itself.

It compares the operations of two scenes from both ends, so a change in the middle of the display list damages the boxes of the operations that changed, clipped as they draw, where they drew before and where they draw now. Glyphs whose pixels changed in an atlas, and images whose pixels changed, count as changed.

func (*Differ) AddBackdrops

func (d *Differ) AddBackdrops(s *Scene, damage []image.Rectangle) []image.Rectangle

AddBackdrops adds to damage, rectangles to redraw in s after Diff, the effects of s that read their backdrops it meets, with those backdrops, and returns it: an effect reads its backdrop after drawing the operations before it within the area drawn, which must hold all of it for the backdrop to hold none of what the frame drew before. So the damage becomes rectangles apart from each other.

func (*Differ) Bounds

func (d *Differ) Bounds() []image.Rectangle

Bounds returns where each operation of the scene Diff was given last draws, within the clips around it.

func (*Differ) Diff

func (d *Differ) Diff(s *Scene) ([]image.Rectangle, bool)

Diff compares s with the last scene Remember kept, and returns the rectangles where they differ, at most eight, apart from each other, or false when everything may have: none is kept, s is of another size, or starts with another color, or its atlases were reset. It finds where each operation of s draws as it goes (Bounds). The rectangles are valid until the next Diff.

func (*Differ) Invalidate

func (d *Differ) Invalidate()

Invalidate makes the next Diff find that everything changed.

func (*Differ) Match

func (d *Differ) Match(j int) (int, bool)

Match returns the op of the last scene that op j of the scene Diff was given last stands for, and false for none: the rest of the ops in the same place, when the scenes have as many, that Diff found the same, and those it compared as changed, whose places are in the damage already. A renderer drawing an op that Match finds differently from the last frame (with another pipeline, say) damages its bounds.

func (*Differ) Release

func (d *Differ) Release()

Release forgets the last scene and lets go of what it kept.

func (*Differ) Remember

func (d *Differ) Remember(s *Scene)

Remember keeps what Diff needs of s, which Diff was given last, to compare the next scene with.

type Effect

type Effect struct {
	// Name names the effect in errors.
	Name string
	// Backdrop tells that the effect reads its backdrop.
	Backdrop bool
	// Metal and HLSL are the effect's shader in Metal Shading Language
	// and HLSL, with the code compiled ahead of time from it; GLSL is its
	// shader in GLSL 3.30 and GLSL ES 3.00, which drivers compile.
	Metal, HLSL EffectCode
	GLSL        string
	// Pixels makes what draws the effect on the CPU, one for each
	// renderer.
	Pixels func() EffectPixels
	// Shader is set for an effect that a shader of package ui/shader
	// draws: its code is the shader's (the Fragment of package shaderir's
	// backends, and a function calling it), which reads the words of
	// EffectOp.Uniforms in a buffer laid out as Shader says, and the images
	// of EffectOp.Images. Metal's is a whole library, with a tail of its
	// own (ShaderSource in package metal); the others' go between the
	// effects' head and tail.
	Shader *ShaderLayout
}

Effect is a kind of drawing that a package outside the renderers defines, as the official plugins do (plugins/glass): a fragment shader for each GPU renderer, drawn with a pipeline of its own, and its twin for the CPU renderer, which must compute the same colors. An effect paints the shape of its OpEffect (Rect rounded by Radii) from its parameters, and from its backdrop when it reads one: what the operations before it painted around it, blurred (see Backdrop).

Each shader is the source of a function that the renderer puts between a head and a tail of its own, which declare what it reads and call it (EffectSource in packages metal, d3d11 and gl):

Metal: float4 effect(float2 p, Effect e, texture2d<float> backdrop)
HLSL:  float4 effect(float2 p, Effect e)
GLSL:  vec4 effect(vec2 p, Effect e)

It returns the premultiplied color at the pixel center p, in device pixels, of the shape e.rect rounded by e.radii, from the parameters e.p0 to e.p4 (EffectOp.Params); the renderer multiplies it by how much of the pixel the shape and the clip cover, and by the opacity. The shape's corners may be continuous (Op.Continuous), which the renderer covers as such, while e.radii, positive, has the effect take them as circular. In Metal, e.wide tells that the target keeps colors outside the sRGB gamut, in extended sRGB (Scene.Wide), which the effect may then take from a parameter holding such a color (ui.Painter.EffectColor). sampleBackdrop(e, q) (with the backdrop texture first in Metal) returns the backdrop at q, premultiplied, as BackdropImage.Sample does.

type EffectCode

type EffectCode struct {
	Source   string
	Compiled []byte
	Sum      string
}

EffectCode is an effect's shader in a language: its source, and the code compiled ahead of time from what the renderer makes of it (EffectSource), with the SHA-256 of that (gpu.SourceSum). Renderers compile the source when the sum no longer matches, as when the renderer's head or tail changed since.

type EffectOp

type EffectOp struct {
	Effect *Effect
	// Blur is the standard deviation of the blur of the backdrop, in
	// pixels, for an effect that reads its backdrop.
	Blur float32
	// Params are the effect's own, which its shaders read as e.p0 to e.p4.
	Params [5][4]float32
	// Uniforms and Images are what a shader's effect reads
	// (Effect.Shader): the words of its uniforms' lanes, and up to four
	// images, bitmaps or canvases, nil for none.
	Uniforms []uint32
	Images   [4]*Image
	// WideUniforms, unless nil, are the words of Uniforms that renderers
	// drawing a wide gamut (Scene.Wide) read in its place: colors outside
	// the sRGB gamut in extended sRGB, where Uniforms holds the nearest
	// sRGB ones.
	WideUniforms []uint32
	// Glyphs, unless empty, are the mask glyphs Scene.Glyphs[Glyphs[0]:
	// Glyphs[1]] that a shader's effect paints instead of the rounded
	// rectangle: the shapes of text, paths and icons, which it fills, each
	// pixel's color times the glyph's coverage, corrected as text's is
	// (TextCoverage) for the color the shader returns. Rect then holds
	// them, and Origin is the point its shader's positions start from, the
	// top left corner of the box it fills.
	Glyphs [2]int32
	Origin [2]float32
}

EffectOp is the effect of an OpEffect, with its parameters.

func (*EffectOp) Masked

func (op *EffectOp) Masked() bool

Masked reports whether op paints mask glyphs (Glyphs).

func (*EffectOp) Same

func (op *EffectOp) Same(o *EffectOp) bool

Same reports whether op draws what o does: the same effect with the same parameters, the same uniforms and no images, whose pixels may change. Glyphs are compared by what they point at, which the caller does.

type EffectPixels

type EffectPixels interface {
	// Begin readies drawing op, the shape rect rounded by radii (fitted),
	// before its pixels, which several cores may then ask for at once.
	Begin(op *EffectOp, rect Rect, radii [4]float32)
	// Color returns the premultiplied color of the effect at the pixel
	// center (x, y), as its shaders' effect does, over the backdrop b (nil
	// for an effect reading none).
	Color(x, y float32, b *BackdropImage) [4]float32
}

EffectPixels draws an effect on the CPU, for one renderer.

type GPUAPI added in v0.1.18

type GPUAPI uint8

GPUAPI names the API of a GPU renderer, for a GPUSource.

const (
	// Metal: device is an id<MTLDevice>, the texture an id<MTLTexture>.
	Metal GPUAPI = iota + 1
	// Direct3D11: device is an ID3D11Device*, the texture an
	// ID3D11ShaderResourceView*.
	Direct3D11
	// OpenGL: device is 0, in the renderer's context; the texture is a
	// texture name.
	OpenGL
)

type GPUSource added in v0.1.18

type GPUSource interface {
	// GPUTexture returns a new texture of device, of the API api, that
	// shows the image's pixels now, which the renderer owns, or 0 where it
	// has none for api: the renderer then draws the image's pixels.
	GPUTexture(api GPUAPI, device uintptr) uintptr
}

GPUSource gives renderers a texture showing an image that something draws on the GPU (Image.GPU).

type Glyph

type Glyph struct {
	// Transform is applied before its Op's transform, for inline text.
	Transform Affine
	// X, Y, W and H place the glyph's bitmap, in device pixels.
	X, Y, W, H float32
	// U, V, UW and VH are the bitmap's rectangle in its atlas.
	U, V, UW, VH uint16
	// Color tints mask glyphs; color glyphs take its alpha only.
	Color Color
	// Wide, unless 0, is 1 + the index in Scene.Wide of the glyph's
	// color outside the sRGB gamut, as Op.Wide.
	Wide uint16
	// Colored glyphs come from Scene.ColorAtlas, the others from
	// Scene.MaskAtlas.
	Colored bool
	// Subpixel glyphs come from Scene.ColorAtlas too, but hold the
	// coverage of the red, green and blue subpixels of each pixel
	// (ClearType), each blending its channel of Color.
	Subpixel bool
	// Thin glyphs, of fonts too thin for antialiasing such as Courier New,
	// take half more contrast whatever their color (see TextCoverage), as
	// Direct2D gives them.
	Thin bool
}

Glyph is a glyph mask or color glyph copied from an atlas into a frame.

type Image

type Image struct {

	// W and H are the size in pixels; Pix holds premultiplied RGBA rows of
	// 4*W bytes.
	W, H int
	Pix  []byte
	// Scene, in a canvas (NewCanvas), is what the image shows: renderers
	// draw it into the image's texture whenever the version changes,
	// rather than upload Pix, which the CPU renderer draws it into, and
	// PixVersion is the version Pix holds.
	Scene      *Scene
	PixVersion uint64
	// Transient marks a canvas drawn anew in every frame that shows it,
	// as an element's effect layer: renderers free its texture once
	// frames stop drawing it, rather than once it is collected, which
	// the little memory it takes of Go's heap may put off for minutes.
	Transient bool
	// Restore re-creates Pix when a renderer needs the pixels after an
	// owner dropped them, to upload or to draw them again, and Dropped
	// runs after a renderer uploaded them, to drop them again. Both are
	// nil for images that keep their pixels.
	Restore func() []byte
	Dropped func()
	// GPU, for an image something draws on the GPU (native.Texture),
	// gives GPU renderers a texture of their own showing its pixels with
	// no copy, which they make again as Version changes. A renderer it
	// gives none, as the CPU renderer, draws the pixels Restore reads. An
	// interface its owner implements, so that renderers link no code of
	// it.
	GPU GPUSource
	// Surface, unless nil, is a frame of video that renderers sample where
	// a decoder left it, rather than upload Pix (see Surface); Restore
	// converts it for those that need Pix.
	Surface *Surface
	// contains filtered or unexported fields
}

Image is a bitmap a scene draws. Renderers keep a texture per image and upload it again when its version changes.

func NewCanvas

func NewCanvas(w, h int) *Image

NewCanvas returns a w×h image that renderers draw from a scene of its own, cleared to transparent: render to texture.

func NewImage

func NewImage(img image.Image) *Image

NewImage converts img to a premultiplied RGBA bitmap.

func NewImageRGBA

func NewImageRGBA(w, h int, pix []byte) *Image

NewImageRGBA wraps premultiplied RGBA pixels of a w×h bitmap.

func (*Image) Changed

func (m *Image) Changed()

Changed records that Pix was modified.

func (*Image) ID

func (m *Image) ID() uint64

ID identifies the image for texture caches.

func (*Image) Pixels added in v0.1.13

func (m *Image) Pixels() []byte

Pixels returns the pixels a renderer uploads or draws, re-creating them from Restore when an owner dropped them. The pixels stay then, until the owner drops them again or a renderer's upload does (Uploaded).

func (*Image) Resize

func (m *Image) Resize(w, h int)

Resize keeps the image's texture-cache identity while changing its size. Renderers replace the backing texture on a size change, so an animated clip does not leave a new texture in the cache on every frame.

It reuses the pixels' memory where they fit, unless they take up less than a quarter of it: an image that shrank much doesn't keep its largest size, as a clip mask that turned would (#1407).

func (*Image) Uploaded added in v0.1.13

func (m *Image) Uploaded()

Uploaded tells that a renderer uploaded the pixels, which an owner may drop again.

func (*Image) Version

func (m *Image) Version() uint64

Version changes whenever the pixels change.

type Kind

type Kind uint8

Kind is the kind of an Op.

const (
	// OpFill paints a rounded rectangle with Color, or the Paint of Color
	// and Color2, and, where Border is positive, a border of BorderColor
	// inside its edges, dashed or not.
	OpFill Kind = iota
	// OpShadow paints the blurred shadow of a rounded rectangle: Rect and
	// Radii are the shadow's box, already offset and spread, Blur its blur
	// radius and Color its color. Unless Cast is empty, the shadow shows
	// only outside it, the box casting the shadow, as CSS's box-shadow
	// does. An Inset shadow shows only inside Cast instead, where Rect,
	// the hole it leaves, blurred, does not cover it, as CSS's box-shadow:
	// inset does; Rect may then be empty, which leaves no hole.
	OpShadow
	// OpGlyphs paints Scene.Glyphs[Start:End]. With a gradient Paint, its
	// mask glyphs take the gradient from Color to Color2, times Opacity,
	// instead of their own colors.
	OpGlyphs
	// OpImage paints Src of Image into Rect, clipped to Radii, with
	// Opacity, in shades of gray if Grayscale, tinted by Color unless it
	// is zero (its pixels times its straight color and alpha). A negative
	// Src.W or Src.H flips the image along that axis, Src.X or Src.Y then
	// being its right or bottom edge; nothing outside Src shows.
	OpImage
	// OpPushClip clips the following ops to Rect with Radii, intersected
	// with the clip in effect, until the matching OpPopClip. Unless
	// PaintSolid, the alpha of its Paint, a gradient of Color and Color2
	// or of Stops as an OpFill's, masks what it clips too, as CSS's
	// mask-image does; so does, with Image, the alpha of Image's Src
	// drawn over Rect, as OpImage draws it: a coverage mask, as a path's
	// (ClipShape.Masks).
	OpPushClip
	// OpPopClip restores the clip in effect before the matching OpPushClip.
	OpPopClip
	// OpEffect paints the rounded rectangle Rect with Radii with an effect,
	// Scene.Effects[Start]: shaders of a package outside the renderers (see
	// Effect), with Opacity; or, for a shader's effect, mask glyphs, which
	// Rect then holds (EffectOp.Glyphs).
	OpEffect
	// OpHole makes the rounded rectangle Rect with Radii transparent,
	// within the clip: what the ops before it painted there is gone, and
	// what the window shows under the frame, as a web view, shows through.
	// The ops after it paint over it as over any transparent pixels. Below
	// full Opacity, what the ops before it painted fades by Opacity
	// instead, so what shows through blends over it.
	OpHole
)

type Op

type Op struct {
	Kind Kind
	Rect Rect
	// Transform maps this operation's geometry to frame pixels. Clips
	// retain the transform with which they were pushed.
	Transform Affine
	// Radii are the corner radii: top-left, top-right, bottom-right and
	// bottom-left.
	Radii [4]float32
	// Continuous curves the rounded corners of Rect, and of Cast, the way
	// Apple draws them (Core Animation's continuous corner curve, SwiftUI's
	// rounded rectangles): the curve starts further from the corner and
	// bends gradually, instead of as a quarter circle. Corners that are
	// round in both directions, as a circle's, stay circular. Only the
	// renderers of macOS draw them, the CPU's and Metal's.
	Continuous bool

	Color Color
	// Paint, unless PaintSolid, fills with Color and Color2 as Gradient
	// says.
	Paint  Paint
	Color2 Color
	// Wide, unless 0, is 1 + the index in Scene.Wide of the op's colors
	// outside the sRGB gamut, which the renderers drawing a wide gamut
	// draw in place of Color, Color2 and BorderColor; those hold the
	// nearest sRGB colors, which every other renderer draws. It fits in
	// the room the fields around it leave.
	Wide     uint16
	Gradient [4]float32

	// Border holds the widths of the border on the top, right, bottom and
	// left; Dashed dashes it.
	Border      [4]float32
	BorderColor Color
	Dashed      bool
	// BorderPaint paints an OpFill's border with Paint, its gradient of
	// stops (Paint.HasStops), times BorderColor (opaque white for the
	// gradient as it is), and its inside with plain Color.
	BorderPaint bool

	// Inset makes an OpShadow an inner shadow.
	Inset bool
	// Blur is an OpShadow's blur, and an OpImage's: the standard deviation
	// of a Gaussian blur of the image's Src, in its pixels, before it is
	// drawn, transparent beyond Src, as CSS's filter: blur() is. Large
	// blurs are computed at a fraction of the size, as backdrops' are
	// (BackdropOf).
	Blur float32
	// Cast is the box casting an OpShadow, with CastRadii.
	Cast      Rect
	CastRadii [4]float32

	Start, End int32
	// Stops are a gradient's colors with stops (PaintLinearStops and the
	// others), Scene.Stops[Stops[0]:Stops[1]].
	Stops [2]int32

	Image     *Image
	Src       Rect
	Grayscale bool
	// Pixelated samples an OpImage's nearest pixel, as pixel art draws,
	// where it would interpolate between pixels.
	Pixelated bool
	// Opacity multiplies the op's colors; 0 means 1.
	Opacity float32
}

Op is one drawing operation. Which fields matter depends on Kind.

func MovedClipOp added in v0.1.17

func MovedClipOp(op *Op) Op

MovedClipOp returns op, an OpPushClip, as MovedClip moves it: its rectangle moved, with the points of its gradient, when its transform only moves them, the transform then unset.

type Paint

type Paint uint8

Paint is what fills an OpFill besides plain Color, or the masks of an OpGlyphs (gradients only).

const (
	PaintSolid Paint = iota
	// PaintLinear is a linear gradient from Color at (Gradient[0],
	// Gradient[1]) to Color2 at (Gradient[2], Gradient[3]), mixed in sRGB;
	// PaintOklab mixes them in Oklab. Both mix premultiplied colors, as
	// CSS does.
	PaintLinear
	PaintOklab
	// PaintStripes draws stripes of Color over Color2: Gradient holds the
	// unit vector across the stripes, their width and their period, from
	// the top-left corner of Rect.
	PaintStripes
	// PaintLinearStops is a linear gradient of the op's Stops, from
	// (Gradient[0], Gradient[1]) at 0 to (Gradient[2], Gradient[3]) at 1,
	// mixed in sRGB; PaintLinearStopsOklab mixes them in Oklab.
	PaintLinearStops
	PaintLinearStopsOklab
	// PaintConic is a conic gradient of the op's Stops around
	// (Gradient[0], Gradient[1]), from 0 at the angle Gradient[2], in
	// radians clockwise from upwards, to 1 a turn later, mixed in sRGB, as
	// CSS's conic-gradient() is; PaintConicOklab mixes them in Oklab.
	PaintConic
	PaintConicOklab
	// PaintRadial is a radial gradient of the op's Stops from (Gradient[0],
	// Gradient[1]) at 0 to a circle of radius Gradient[2] around it at 1,
	// mixed in sRGB, as CSS's radial-gradient() is; PaintRadialOklab mixes
	// them in Oklab.
	PaintRadial
	PaintRadialOklab
)

func (Paint) HasStops

func (p Paint) HasStops() bool

HasStops reports whether paint takes its colors from the op's Stops.

type Plane added in v0.1.18

type Plane struct {
	Pix    []byte
	Stride int
}

Plane is a plane of a Surface in memory: rows of Stride bytes.

type Rect

type Rect struct{ X, Y, W, H float32 }

Rect is a rectangle in device pixels.

func InnerRadii

func InnerRadii(r Rect, radii, w [4]float32) (Rect, [4]float32)

InnerRadii returns the radii of the inner edge of a border of widths w (top, right, bottom, left) inside a rounded rectangle r with radii, which FitRadii or Corners already fitted: each corner's less the wider of its two sides, fitted to the inner rectangle, negative as radii are for continuous corners.

func (Rect) Contains

func (r Rect) Contains(x, y float32) bool

Contains reports whether the point is inside r.

func (Rect) Empty

func (r Rect) Empty() bool

Empty reports whether the rectangle has no area.

func (Rect) Intersect

func (r Rect) Intersect(o Rect) Rect

Intersect returns the intersection of r and o.

type Scene

type Scene struct {
	// Width and Height of the frame in device pixels; Scale is how many
	// device pixels a DIP is (0 for 1). Zoom is how much of Scale the
	// content's zoom makes (0 for 1): the screen's own scale is
	// Scale/Zoom.
	Width, Height int
	Scale, Zoom   float32
	// Clear is the color the frame starts with.
	Clear Color
	// Background is the opaque color the content fills the window with,
	// or transparent: what the window shows where no frame of its size
	// shows yet, as while it grows. It draws nothing in the frame.
	Background Color
	Ops        []Op
	Glyphs     []Glyph
	// Stops holds the stops of gradients (Op.Stops).
	Stops []Stop
	// Effects holds the effects of OpEffect operations.
	Effects []EffectOp
	// Words holds the words of the effects' uniforms (EffectOp.Uniforms
	// and WideUniforms), which the frame's painter allocates from
	// (Painter.EffectWords), kept from frame to frame.
	Words []uint32
	// Wide holds the colors outside the sRGB gamut of ops and glyphs (see
	// Op.Wide), and those of the parameters of effects, which no op points
	// at. Without any, the scene draws the same on every renderer.
	Wide []WideColors
	// Text corrects the coverage of mask and subpixel glyphs.
	Text TextParams
	// MaskAtlas holds coverage masks (one byte per pixel), ColorAtlas
	// premultiplied RGBA bitmaps such as emoji, and the coverage of
	// subpixel glyphs.
	MaskAtlas, ColorAtlas *Atlas
	// Canvases are the canvases (NewCanvas) drawn anew for this frame,
	// which renderers draw before it, whether it shows them or not, while
	// the atlases their glyphs point at hold them.
	Canvases []*Image
	// Drawn, unless zero, is the part of a canvas's frame its content
	// takes, from the top left corner, as an effect's layer made larger
	// than its content: backdrops end at its edge (BackdropOf), as at the
	// edge of a canvas of its size, and nothing is drawn beyond it.
	Drawn image.Point
}

Scene is a frame's display list.

func (*Scene) BackdropOf

func (s *Scene) BackdropOf(r Rect, blur float32, w, h int) Backdrop

BackdropOf is BackdropOf in s, a frame of w×h pixels, ending at the edge of the part Drawn says.

func (*Scene) EachCanvas

func (s *Scene) EachCanvas(fn func(*Image))

EachCanvas calls fn with the canvases the scene draws anew or shows, each once, those a canvas shows before it.

func (*Scene) Reset

func (s *Scene) Reset(width, height int, color Color)

Reset empties the scene for another frame, keeping its storage.

type ShaderLayout

type ShaderLayout struct {
	Lanes []int32
	Size  int
}

ShaderLayout is where a shader's uniforms lie in the buffer its code reads: the offset in bytes of each word of EffectOp.Uniforms, and the buffer's size in bytes, a multiple of 16.

func (*ShaderLayout) Pack

func (l *ShaderLayout) Pack(buf []byte, words []uint32) []byte

Pack writes words into buf, grown to the layout's size, as the layout lays them out, and returns it. A lane takes 4 bytes, but for a bool of Metal, which takes 1 and may lie in the last bytes: the bytes that fit are written, little end first, and lanes in ascending order write over what the one before spilled.

type Stop

type Stop struct {
	Color Color
	At    float32
}

Stop is a color of a gradient with stops (Op.Stops), at a place along it from 0 to 1. A gradient shows its first color before its first stop and its last after its last, and mixes premultiplied colors between, as CSS does; stops in order, at most MaxStops of them.

type Surface added in v0.1.18

type Surface struct {
	// Format is how the pixels are laid out: SurfaceNV12's luma, then
	// chroma at half the size both ways, Cb and Cr interleaved, which
	// renderers convert to RGB with Matrix as they sample them; or
	// SurfaceBGRA, opaque or premultiplied as Image's pixels are.
	Format SurfaceFormat
	Matrix YUVMatrix
	// Planes are the frame in memory, for renderers to upload: the luma
	// and the chroma of NV12, or BGRA's one. Nil for a frame only on the
	// GPU, as Native has it.
	Planes [2]Plane
	// Native is the frame on the GPU, as the platform's renderer takes it:
	// a CVPixelBufferRef on macOS, which Metal wraps as textures; on
	// Windows the NT handle of a shared Direct3D 11 texture in BGRA with a
	// keyed mutex, which Direct3D opens on its device once (NativeID) and
	// acquires with key 0 around the frames reading it, as the producer
	// does around writing it; in browsers the number of the video element
	// playing it (media.AddElement), which WebGL uploads from. 0 for
	// none. The producer keeps it valid
	// while the image shows the surface; renderers keep what they made of
	// it until the GPU read it.
	Native uintptr
	// NativeID identifies Native's texture among all those the producers
	// of an app ever share, which renderers open once: a handle's number
	// may name another texture once closed.
	NativeID uint64
}

A Surface is a picture that a system decoder left where it decoded it, a frame of video, which renderers sample where it is rather than upload as RGBA (Image.Surface). The image showing it keeps W and H, and its version changes with each frame; its Pixels, which the CPU renderer draws and blurs read, come from its Restore, which converts the frame.

func (*Surface) RGBA added in v0.1.18

func (s *Surface) RGBA(dst []byte, w, h int) []byte

RGBA converts the surface's planes in memory into premultiplied RGBA, 4×W×H bytes, into dst when it has room, as the shaders sample them: each pixel's chroma bilinear between the chroma samples around it (centered between luma's, as MPEG-1 and JPEG place them). It returns nil without planes.

type SurfaceFormat added in v0.1.18

type SurfaceFormat uint8

SurfaceFormat is the pixel format of a Surface.

const (
	// SurfaceNV12 is 8-bit YCbCr 4:2:0: a plane of luma, a byte a pixel,
	// then a plane of chroma half as wide and high, Cb and Cr a byte each.
	SurfaceNV12 SurfaceFormat = iota
	// SurfaceBGRA is a plane of 8-bit blue, green, red and alpha.
	SurfaceBGRA
)

type TextParams

type TextParams struct {
	// GammaRatios are Direct2D's alpha correction of a gamma (see
	// GammaRatios).
	GammaRatios [4]float32
	// Contrast enhances the contrast of mask glyphs, and SubpixelContrast
	// that of subpixel glyphs, the more the darker their color: DirectWrite's
	// grayscale enhanced contrast and enhanced contrast.
	Contrast, SubpixelContrast float32
}

TextParams corrects the coverage of mask and subpixel glyphs for the gamma and contrast text is blended with, as Direct2D does; the zero value leaves it as it is.

type TranslationFolder

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

TranslationFolder folds the transforms of a scene's ops that only translate (an element's Translate, which animations move) into their geometry, reusing its memory from scene to scene: renderers then draw them as they draw ops without transforms, the GPU's with the shaders of those (gpu.Class), not the general one, and the CPU's without sampling pixels on a grid. Both renderers fold, so that they keep drawing the same pixels.

Renderers fold once FoldTranslations was called, which package ui does where it makes translations: apps that never translate carry none of the code.

func (*TranslationFolder) Fold

func (f *TranslationFolder) Fold(s *Scene) *Scene

Fold returns s, or, when any of its ops only translates, a copy of it with those folded: fills and shadows, and images and glyphs moved by whole pixels, glyphs without transforms of their own (renderers round their places, a glyph's bitmap staying on whole pixels without a transform), and clips: their edges are computed where they fall, as a fill's, rather than rasterized into a mask each frame the clip moves. Effects and holes keep their transforms. The copy holds until the next Fold. Before FoldTranslations, it returns s.

type WideColors

type WideColors struct {
	Color, Color2, Border [4]float32
	Set                   WideSet
}

WideColors are the colors outside the sRGB gamut of an op or a glyph (see Op.Wide): straight RGBA with sRGB-encoded components beyond 0 to 1 (extended sRGB), for those of Color, Color2 and BorderColor a Set bit names, of which a glyph has only Color, times its opacity.

type WideSet

type WideSet uint8

WideSet says which colors of WideColors replace those of the op.

const (
	WideColor WideSet = 1 << iota
	WideColor2
	WideBorder
)

type YUVMatrix added in v0.1.18

type YUVMatrix uint8

YUVMatrix is how a Surface's YCbCr converts to RGB: the coefficients of a standard, and whether the samples take their full range or the limited (video) range, 16 to 235 for luma and 16 to 240 for chroma.

const (
	BT601 YUVMatrix = iota
	BT709
	BT2020
	// FullRange is added to a matrix for samples of the full range.
	FullRange YUVMatrix = 3
)

func (YUVMatrix) YUVToRGB added in v0.1.18

func (m YUVMatrix) YUVToRGB(y, cb, cr float32) (r, g, b float32)

YUVToRGB converts samples y, cb and cr, 0 to 1, to RGB, 0 to 1 and clamped, as the renderers' shaders do (yuvToRGB in each).

Jump to

Keyboard shortcuts

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