gametest

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 16 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 gametest provides deterministic software rendering of nsgo Canvas draw operations, golden PNG comparison, and visual diff generation for tests.

Index

Examples

Constants

View Source
const DefaultGoldenDir = "testdata/golden"

DefaultGoldenDir is the relative directory used by AssertGolden and AssertOpsGolden.

Variables

This section is empty.

Functions

func AssertGolden

func AssertGolden(t testing.TB, name string, got image.Image)

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

func AssertGoldenAt(t testing.TB, goldenPath string, got image.Image)

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, ops []core.DrawOp, opts ...RenderOptions)

AssertOpsGolden rasterizes ops with RenderOps and asserts the resulting image matches testdata/golden/<name>.png.

func AssertSameImages

func AssertSameImages(t testing.TB, got, want []core.DrawOp)

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 CompareGolden

func CompareGolden(got image.Image, goldenPath string, update bool) (*image.RGBA, int, error)

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).Ops)
	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

func DiffImage(got, want image.Image) (diff *image.RGBA, mismatchedPixels int)

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).Ops)
	after := gametest.RenderOps(8, 2, draw(1).Ops)
	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

func GoldenPath(dir, name string) string

GoldenPath returns the standard golden PNG file path under dir for name.

func ReadPNG

func ReadPNG(path string) (image.Image, error)

ReadPNG opens and decodes a PNG image from path.

func RenderOps

func RenderOps(width, height int, ops []core.DrawOp, opts ...RenderOptions) *image.RGBA

RenderOps deterministically rasterizes recorded core.DrawOp operations into an RGBA image of size width by height pixels.

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 and DrawAtlas.

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() {
	ops := (&core.Drawing{}).
		SetFillColor(core.RGB(0xff0000)).
		FillRect(2, 2, 4, 4).Ops
	img := gametest.RenderOps(8, 8, ops, 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 WritePNG

func WritePNG(path string, img image.Image) error

WritePNG encodes img as a PNG file at path, creating parent directories as needed.

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

func ImageDraws(ops []core.DrawOp) []ImageDraw

ImageDraws replays the state that ops 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.

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
}

RenderOptions configures optional inputs for RenderOps.

Jump to

Keyboard shortcuts

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