Documentation
¶
Overview ¶
Package gametest is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package gametest provides deterministic software rendering of nsgo Canvas draw operations, golden PNG comparison, and visual diff generation for tests.
Index ¶
- Constants
- func ApplyColorVision(img image.Image, mode a11y.ColorVision, severity float64, correct bool) *image.RGBA
- func AssertColorDistinguishable(t testing.TB, mode a11y.ColorVision, a, b core.Color, minDistance float64)
- func AssertGolden(t testing.TB, name string, got image.Image)
- func AssertGoldenAt(t testing.TB, goldenPath string, got image.Image)
- func AssertOpsGolden(t testing.TB, name string, width, height int, d *core.Drawing, ...)
- func AssertPhotosensitivity(t testing.TB, frames []image.Image, opts PhotosensitivityOptions)
- func AssertRegionsDistinguishable(t testing.TB, img image.Image, regionA, regionB image.Rectangle, ...)
- func AssertSameImages(t testing.TB, got, want *core.Drawing)
- func AverageRegionColor(img image.Image, region image.Rectangle) core.Color
- func ColorDistance(a, b core.Color) float64
- func CompareGolden(got image.Image, goldenPath string, update bool) (*image.RGBA, int, error)
- func DiffImage(got, want image.Image) (diff *image.RGBA, mismatchedPixels int)
- func GoldenPath(dir, name string) string
- func ReadPNG(path string) (image.Image, error)
- func RenderOps(width, height int, d *core.Drawing, opts ...RenderOptions) *image.RGBA
- func ShouldUpdateGolden() bool
- func SimulateColorVision(img image.Image, mode a11y.ColorVision, severity float64) *image.RGBA
- func WritePNG(path string, img image.Image) error
- type ClipStep
- type ImageDraw
- type Photosensitivity
- func (p *Photosensitivity) Add(frame image.Image)
- func (p *Photosensitivity) AddDrawing(width, height int, d *core.Drawing, opts ...RenderOptions) *image.RGBA
- func (p *Photosensitivity) Assert(t testing.TB)
- func (p *Photosensitivity) AssertGoldenAt(t testing.TB, goldenPath string, got image.Image)
- func (p *Photosensitivity) FrameCount() int
- func (p *Photosensitivity) Report() PhotosensitivityReport
- type PhotosensitivityFailure
- type PhotosensitivityOptions
- type PhotosensitivityReport
- type RenderOptions
Examples ¶
Constants ¶
const ( // EnvFlashRecording is the environment variable set by `game check flashes` // to the absolute path of a `.replay.yaml` input recording when delegating // replay photosensitivity checks to project tests. EnvFlashRecording = "NSGO_FLASH_RECORDING" // EnvFlashFPS is the optional environment variable set by `game check flashes` // to the target frame rate in Hz when delegating to project tests. EnvFlashFPS = "NSGO_FLASH_FPS" )
const DefaultGoldenDir = "testdata/golden"
DefaultGoldenDir is the relative directory used by AssertGolden and AssertOpsGolden.
Variables ¶
This section is empty.
Functions ¶
func ApplyColorVision ¶
func ApplyColorVision(img image.Image, mode a11y.ColorVision, severity float64, correct bool) *image.RGBA
ApplyColorVision filters img through postfx.ColorVisionEffect for mode at severity in [0, 1] (clamped, with NaN treated as 0). When correct is false, it simulates the deficiency; when correct is true, it applies daltonization correction. The input image is not mutated.
func AssertColorDistinguishable ¶
func AssertColorDistinguishable(t testing.TB, mode a11y.ColorVision, a, b core.Color, minDistance float64)
AssertColorDistinguishable simulates a and b under mode and fails t if their Euclidean sRGB distance is smaller than minDistance.
func AssertGolden ¶
AssertGolden compares got against testdata/golden/<name>.png and fails t on mismatch, writing <name>.got.png and <name>.diff.png beside the golden (or under GOLDEN_DIFF_DIR when set) so they outlive the test for inspection.
func AssertGoldenAt ¶
AssertGoldenAt compares got against goldenPath and fails t on mismatch, writing <name>.got.png and <name>.diff.png beside goldenPath (or under GOLDEN_DIFF_DIR when set) so they remain on disk after the test ends. On a passing or updating run, any stale failure images at those paths are removed.
func AssertOpsGolden ¶
func AssertOpsGolden(t testing.TB, name string, width, height int, d *core.Drawing, opts ...RenderOptions)
AssertOpsGolden rasterizes d with RenderOps and asserts the resulting image matches testdata/golden/<name>.png.
func AssertPhotosensitivity ¶
func AssertPhotosensitivity(t testing.TB, frames []image.Image, opts PhotosensitivityOptions)
AssertPhotosensitivity analyzes frames and fails t if any flash, red-flash, or stripe-pattern failure is detected.
func AssertRegionsDistinguishable ¶
func AssertRegionsDistinguishable(t testing.TB, img image.Image, regionA, regionB image.Rectangle, mode a11y.ColorVision, minDistance float64)
AssertRegionsDistinguishable simulates img under mode (when mode is not VisionNormal) and fails t if the average colors of regionA and regionB have Euclidean sRGB distance less than minDistance.
func AssertSameImages ¶
AssertSameImages fails t unless got and want draw the same image rectangles, in the same order, to the same places with the same alpha, composite, tint, sampling and clip, their numbers within 1e-3.
Unlike comparing the operations themselves, it holds however the images were recorded, such as one DrawImageFrom per sprite against one DrawAtlas. It compares only images, as ImageDraws reads them: a test whose recordings also fill, stroke or write text checks those on its own.
func AverageRegionColor ¶
AverageRegionColor returns the mean straight sRGB color of opaque/translucent pixels inside region (intersected with img's bounds). Returns core.Transparent when the region is empty or fully transparent.
func ColorDistance ¶
ColorDistance returns the Euclidean sRGB distance between a and b in 8-bit channel units [0, 441.67], ignoring alpha.
func CompareGolden ¶
CompareGolden compares got against the PNG stored at goldenPath.
When update is true, got is written to goldenPath and CompareGolden returns (nil, 0, nil). When update is false, CompareGolden decodes goldenPath, round-trips got through PNG encoding and decoding so comparison runs in the space stored on disk, and returns DiffImage(gotPNG, want).
Example ¶
CompareGolden checks a frame against a PNG under testdata/golden; update writes the PNG instead, as running tests with the update flag does through AssertGolden.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/nsgo-dev/game/pkg/gametest"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
dir, err := os.MkdirTemp("", "golden")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
path := gametest.GoldenPath(dir, "title screen")
fmt.Println(filepath.Base(path))
img := gametest.RenderOps(4, 4, (&core.Drawing{}).SetFillColor(core.RGB(0x2a9d8f)).FillRect(0, 0, 4, 4))
if _, _, err := gametest.CompareGolden(img, path, true); err != nil {
fmt.Println(err)
return
}
_, mismatched, err := gametest.CompareGolden(img, path, false)
fmt.Println(mismatched, err)
}
Output: title screen.png 0 <nil>
func DiffImage ¶
DiffImage compares got and want pixel by pixel and returns a visual diff image along with the count of mismatched pixels.
Matching pixels are rendered as a dimmed grayscale context; mismatched pixels (including pixels outside either image's bounds when dimensions differ) are highlighted in solid magenta (#ff00ff).
Example ¶
DiffImage counts the pixels that differ between two frames and marks them in a diff image.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/gametest"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
draw := func(x float32) *core.Drawing {
return (&core.Drawing{}).SetFillColor(core.RGB(0xffffff)).FillRect(x, 0, 2, 2)
}
before := gametest.RenderOps(8, 2, draw(0))
after := gametest.RenderOps(8, 2, draw(1))
diff, mismatched := gametest.DiffImage(after, before)
fmt.Println(mismatched, diff.RGBAAt(0, 0), diff.RGBAAt(1, 0))
}
Output: 4 {255 0 255 255} {85 85 85 255}
func GoldenPath ¶
GoldenPath returns the standard golden PNG file path under dir for name.
func RenderOps ¶
RenderOps deterministically rasterizes the operations a core.Drawing records into an RGBA image of size width by height pixels. It supports source-over and additive CompositeLighter blending, and bitmap FillText and StrokeText with recorded alignment and baseline offsets. Other composite modes currently follow source-over.
Supported operations include Save, Restore, Translate, Scale, Rotate, Transform, SetTransform, SetAlpha, SetFillColor, SetStrokeColor, SetLineWidth, Clear, Rect + Fill/Stroke (including FillRect and StrokeRect), polygon paths (MoveTo, LineTo, ClosePath + Fill/Stroke), DrawImage / DrawImageIn / DrawImageFrom, DrawAtlas, and DrawVertices. Images and atlas sprites resolve against the drawing's own buffers, as the DrawOp.ImageIndex and DrawOp.SpriteStart indexes require.
Example ¶
RenderOps rasterizes recorded drawing operations without a window or GPU, so a test can check pixels.
package main
import (
"fmt"
"image/color"
"github.com/nsgo-dev/game/pkg/gametest"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
d := (&core.Drawing{}).
SetFillColor(core.RGB(0xff0000)).
FillRect(2, 2, 4, 4)
img := gametest.RenderOps(8, 8, d, gametest.RenderOptions{Background: color.RGBA{A: 255}})
fmt.Println(img.Bounds().Dx(), img.Bounds().Dy())
fmt.Println(img.RGBAAt(3, 3), img.RGBAAt(0, 0))
}
Output: 8 8 {255 0 0 255} {0 0 0 255}
func ShouldUpdateGolden ¶
func ShouldUpdateGolden() bool
ShouldUpdateGolden reports whether golden updates are enabled via the -update-golden flag or the UPDATE_GOLDEN environment variable.
func SimulateColorVision ¶
SimulateColorVision returns a copy of img filtered through color-vision deficiency simulation for mode at severity in [0, 1]. Passing severity == 1.0 matches full dichromacy simulation (a11y.Simulate).
Types ¶
type ClipStep ¶
type ClipStep struct {
// Op is the path operation (MoveTo, LineTo, QuadTo, CubicTo, Arc, Rect, RoundRect, Ellipse or ClosePath) or the Clip.
Op core.DrawOp
// Transform is the drawing's transform then, as the arguments a, b, c, d, e, f of Drawing.Transform.
Transform [6]float32
}
ClipStep is one operation of a clipping path, or the Clip that ends one, with the drawing's transform when it was recorded.
type ImageDraw ¶
type ImageDraw struct {
// Image is the image drawn from.
Image core.ImageSource
// SX, SY, SW and SH are the rectangle of the image drawn, in the image's points; SW and SH are 0 when the operation draws the whole image.
SX, SY, SW, SH float32
// Corners are where the drawn rectangle's top left, top right, bottom right and bottom left land on the canvas, after the drawing's transform. An image drawn at its natural size (DrawImage, DrawTintedImage) takes the size of its source rectangle, or of the whole image when the source sets Size or Pixels; with neither, its size is unknown and all four corners are its top left.
Corners [4]core.Point
// Alpha is the opacity it draws with: the drawing's alpha, times the sprite's own for a DrawAtlas sprite.
Alpha float32
// Composite is how it mixes with what is under it.
Composite core.CompositeOp
// Tinted reports whether the image's channels are multiplied by Tint, as DrawTintedImage records; a DrawAtlas sprite is never tinted.
Tinted bool
// Tint is the color a tinted image is multiplied by.
Tint core.Color
// Sampling is how the image's texels are sampled.
Sampling core.ImageSampling
// Clip is the clipping in effect, outermost first: the operations of each clipping path, each followed by the Clip that used it. It is empty when nothing clips the image.
Clip []ClipStep
}
ImageDraw is one rectangle of an image that recorded operations put on the canvas: a DrawImage, DrawImageIn or DrawImageFrom, or one sprite of a DrawAtlas.
func ImageDraws ¶
ImageDraws replays the state that d's operations set (Save, Restore, Translate, Scale, Rotate, Transform, SetTransform, SetAlpha, SetComposite and clipping paths) and returns every image rectangle they draw, in order. It reads only images: fills, strokes, texts and meshes are left out.
It lets a test check where sprites land and what they show however they were recorded: one DrawImageFrom per sprite, or many sprites in one DrawAtlas, as sprite.Batch draws them. Images and atlas sprites resolve against the drawing's own buffers, as the DrawOp.ImageIndex and DrawOp.SpriteStart indexes require.
type Photosensitivity ¶
type Photosensitivity struct {
// contains filtered or unexported fields
}
Photosensitivity analyzes a stream of rendered frames incrementally for photosensitive general luminance flashes, saturated-red flashes, and high-contrast stripe patterns (WCAG 2.3.1 / XAG 118).
Use NewPhotosensitivity to feed frames from a test loop (via Add, AddDrawing, or AssertGoldenAt) without retaining all frames in memory, then call Report or Assert.
func NewPhotosensitivity ¶
func NewPhotosensitivity(opts PhotosensitivityOptions) *Photosensitivity
NewPhotosensitivity returns a streaming analyzer configured by opts. FrameRate defaults to 60 when <= 0.
func (*Photosensitivity) Add ¶
func (p *Photosensitivity) Add(frame image.Image)
Add analyzes frame as the next frame in the sequence.
func (*Photosensitivity) AddDrawing ¶
func (p *Photosensitivity) AddDrawing(width, height int, d *core.Drawing, opts ...RenderOptions) *image.RGBA
AddDrawing rasterizes d with RenderOps, records the resulting frame for photosensitivity analysis, and returns the rendered image.
func (*Photosensitivity) Assert ¶
func (p *Photosensitivity) Assert(t testing.TB)
Assert fails t if any photosensitivity failures were recorded.
func (*Photosensitivity) AssertGoldenAt ¶
AssertGoldenAt records got for photosensitivity analysis and compares it against goldenPath via AssertGoldenAt.
func (*Photosensitivity) FrameCount ¶
func (p *Photosensitivity) FrameCount() int
FrameCount returns the number of frames added so far.
func (*Photosensitivity) Report ¶
func (p *Photosensitivity) Report() PhotosensitivityReport
Report returns the failures collected so far.
type PhotosensitivityFailure ¶
type PhotosensitivityFailure struct {
// Kind is "flash" for more than three general luminance flashes in one second,
// "red_flash" for more than three saturated-red flashes in one second,
// or "pattern" for a high-contrast stripe pattern.
Kind string
// FirstFrame is the index of the first frame of the failing range.
FirstFrame int
// LastFrame is the index of the last frame of the failing range.
LastFrame int
// Summary describes the failure for a test log.
Summary string
}
PhotosensitivityFailure describes a detected flash, saturated-red flash, or high-contrast pattern.
func (PhotosensitivityFailure) String ¶
func (f PhotosensitivityFailure) String() string
String formats f for test logs and CLI diagnostics.
type PhotosensitivityOptions ¶
type PhotosensitivityOptions struct{ FrameRate float64 }
PhotosensitivityOptions controls frame analysis. FrameRate defaults to 60 when zero.
type PhotosensitivityReport ¶
type PhotosensitivityReport struct {
// Failures lists the first general flash failure, the first red-flash failure (if any),
// and every frame with a high-contrast stripe pattern.
Failures []PhotosensitivityFailure
}
PhotosensitivityReport contains failures found in a sequence of rendered frames.
func AnalyzePhotosensitivity ¶
func AnalyzePhotosensitivity(frames []image.Image, opts PhotosensitivityOptions) PhotosensitivityReport
AnalyzePhotosensitivity checks rendered frames for repeated general flashes, repeated saturated-red flashes, and high-contrast stripe patterns.
A general flash is a pair of opposing changes in relative luminance of at least 0.1 where the darker state is below 0.8 (sRGB decoded to linear light). A saturated-red flash is a pair of opposing transitions involving saturated red (R/(R+G+B) >= 0.8) whose red-excess change |max(0, R-G-B)_1 - max(0, R-G-B)_2| is at least 20/320. More than three flashes of either kind within one second across at least 20% of the frame area fail, and only the first failing second of each kind is reported. A frame whose horizontally or vertically adjacent pixels differ in relative luminance by at least 0.5 across 20% of the frame fails as a pattern.
func (PhotosensitivityReport) OK ¶
func (r PhotosensitivityReport) OK() bool
OK reports whether no photosensitivity failures were detected.
type RenderOptions ¶
type RenderOptions struct {
// Background fills the output image before replaying ops.
// The zero value leaves the canvas transparent.
Background color.RGBA
// Images resolves core.ImageSource.URI values referenced by DrawImage ops
// when neither Pixels nor Data is set on the ImageSource.
Images map[string]image.Image
// ColorVision, when set to a non-normal mode (such as a11y.VisionProtanopia,
// a11y.VisionDeuteranopia, or a11y.VisionTritanopia), passes the rasterized
// frame through the color-vision filter so tests can render goldens under
// deficiency simulation or daltonization correction.
ColorVision a11y.ColorVision
// ColorVisionSeverity sets the filter strength in [0, 1]. When zero and
// ColorVision is active, it defaults to 1.0 (full deficiency).
ColorVisionSeverity float64
// ColorVisionCorrect applies daltonization correction instead of simulation
// when ColorVision is active.
ColorVisionCorrect bool
}
RenderOptions configures optional inputs for RenderOps.