Skip to content
go-gfxPublic

About

Pure-Go CGO=0 2D graphics foundation: geometry, color, raster buffers, high-quality resampling, image codecs, and vector rasterization. Shared substrate under go-images, go-widgets/painter, go-webengine.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

93 Commits

Folders and files

Repository files navigation

gfx — pure-Go 2D graphics foundation

github.com/go-gfx/gfx is a pure-Go, CGO=0 2D graphics foundation: the shared substrate that sits below the fleet's image-processing and rendering libraries.

It is not an image-processing library (that is go-images, the scikit-image analogue) and not a widget toolkit (that is go-widgets). It is the common layer both stand on: pixel buffers, colour science, high-quality resampling, image codecs, and vector rasterization — each usable on its own, with no third-party dependencies.

Packages

Package Purpose
geometry points, rectangles, affine transforms
color full colour science: HSV/HSL/HWB, XYZ/Lab/LCh/Luv/OKLab/OKLCH, Y′CbCr, CMYK, D65↔D50 Bradford, ΔE (76/94/2000/OK), separable + non-separable blends, premultiplied alpha
raster shared pixel-buffer / pixel-format substrate
resample high-quality resizing: box/area, bicubic (Catmull-Rom), Lanczos
codec image decoders/encoders: png, jpeg, gif, webp, tiff, bmp, ico, icns, jpeg 2000, jbig2, netpbm, qoi
vector paths, a path-data parser shared by SVG/ODF/OpenXPS, anti-aliased fill/stroke rasterizer (round joins & caps, non-zero / even-odd), linear/radial gradients, source-over compositing
iso isometric projection (project / unproject / depth-sort) and shaded pixel primitives — cube, brick, pyramid, slope, line, side — composited into a depth-ordered scene (the pure-Go obelisk.js)

Consumers

  • go-images — image processing/analysis, built on raster/color/resample.
  • go-widgets/painter — tri-backend renderer, built on vector/raster/color.
  • go-webengine — HTML/CSS → image, built on resample/codec/vector.
  • go-widgets/desktop — icon & thumbnail rendering.

What an SVG may ask for

An SVG is text, and two of the numbers in it decide allocations: the document's own width/height, and the dimensions an embedded <image href="data:…"> declares in its header. A surface is four bytes a pixel.

⛔ Measured before svg.Options.MaxPixels existed:

input before after
~110 bytes of text declaring width="40000" height="40000" 6103.5 MiB allocated, rasterised without complaint 0.0 MiB, "a surface of 40000x40000 is 1600000000 pixels, past the 40000000 allowed"
a 246-byte SVG whose <image> claims 20000×20000 1526.1 MiB held, then drawn into a 100×100 surface 0.0 MiB, skipped

Both are bounded by Options.MaxPixels, whose zero value is svg.DefaultMaxPixels — forty million pixels, a hundred and sixty million bytes, the same ceiling go-pdfkit/render uses. A service rendering documents from strangers should set it to what its own pages need rather than inherit that.

The embedded picture is refused from its header, through image.DecodeConfig, before anything is decoded: ⛔ a ceiling enforced after the allocation it bounds is not a ceiling, it is a comment. Scale counts towards it, because the surface is the product and only one of the two numbers is ours.

Untrusted input: every limit an SVG meets

svg.Rasterize, svg.RasterizeMask and svg.Walk accept documents from strangers (a server-supplied logo, an upload). Everything the document controls has a ceiling, and a document past one is refused with a *svg.LimitError (errors.Is(err, svg.ErrLimit); .What names the resource) — never truncated and never drawn "as far as it got". A document that is not an SVG at all still returns the plain "no parseable <svg> root" error, and a shape this subset cannot draw is still skipped.

resource default option
surface (width×height×Scale), and an embedded <image> 40 000 000 pixels MaxPixels
document text 8 MiB MaxBytes
XML elements 100 000 MaxElements
element nesting 256 MaxDepth
path commands, summed over the document 1 000 000 MaxSegments
pixel work: every painted box, clip, opacity layer and image counts its area 64 full surfaces, never under 16 777 216 MaxWork
<stop> elements per gradient 256 fixed
stroke-dasharray entries 64 fixed
dashes one stroke is cut into (estimated from its control polygon) 1 048 576 fixed
any device-space coordinate or stroke width, in pixels (NaN and ±Inf included) ±10 000 000 fixed
cached clip masks 16 surfaces' worth of bytes fixed
open opacity groups (deeper ones draw without their own opacity) 8 fixed

Notes for a service that renders strangers' files:

  • Set the options to what your own pages need; the defaults suit a large map, not a 24-px icon. Options{MaxPixels: 1 << 18, MaxBytes: 1 << 20, MaxElements: 5000} is plenty for a logo.
  • The renderer has no <use>, gradient href, <mask> or nested clip-path resolution, so a reference cycle is inert: nothing follows it. The limits above are what keep a document that does fit the grammar cheap.
  • encoding/xml never expands the entities a DTD declares and never fetches a DTD, so there is no entity bomb; the element and depth counts are taken in a first pass before the tree is built.
  • There is no context: bound wall-clock time at the call site as well.
  • svg/fuzz_test.go holds FuzzParse, with a committed corpus in svg/testdata/fuzz/FuzzParse; limits_test.go holds the bomb tests, which assert the refusal under a memory limit and a deadline.

opacity is group compositing

svg.Rasterize honours the opacity attribute on <g>, on shapes, on <image>, on a nested <svg> and on the root. Following SVG 1.1 §14.5 ("Object and group opacity") and CSS Color 4, the element is drawn whole into an offscreen buffer, which is then blended onto what is beneath once — it is not a multiplication of each child's fill-opacity. Two opaque rects in <g opacity="0.5"> therefore overlap at alpha 128, not 191. opacity is not inherited; nested groups multiply.

Each open opacity group is one more surface of W×H×4 bytes, so the nesting that is honoured is capped at 8 levels; a group nested deeper is drawn without its own opacity. Buffers are recycled, and a document with no opacity allocates nothing extra. svg.Walk has no surface: it reports "opacity" among the features it could not hand over.

One path-data parser, three formats

vector.ParseData reads the syntax of SVG's d attribute and returns the outline, with a geometry.Matrix applied on the way. It lives in vector rather than in svg because three formats write the same syntax, and the arc maths and the smooth-curve reflection are worth transcribing once:

SVG d ODF draw:path OpenXPS abbreviated geometry
commands M L H V C S Q T A Z the same (svg:d) the same, minus T
arc operands rx ry rot large sweep x y the same the same order
sweep sense positive-angle the same FLAG2 == 1 ? Clockwise — the same
fill rule on the shape on the shape an F0/F1 prefix on the data

The sources are SVG 1.1 §8.3 and ECMA-388 Annex C, which gives the XPS syntax as an algorithm. The F0/F1 prefix is deliberately not handled here: the fill rule belongs to the shape, not to the outline, so an XPS reader strips it and chooses EvenOdd or NonZero itself.

⛔ The six numbers are not a row-major matrix. SVG's matrix(), XPS's RenderTransform, ODF's draw:transform and PDF's cm all write an affine as [a b c d e f], mapping (x, y) to (a*x + c*y + e, b*x + d*y + f). Reading them row-major swaps b with c, which leaves every unrotated drawing correct and every rotated one mirrored.

ParseData therefore takes a geometry.Matrix, whose entries are named (Xx, Yx, X0 / Xy, Yy, Y0) rather than positional, so the transposition is not expressible. A caller converting from the flat form writes Xx: a, Yx: c, X0: e, Xy: b, Yy: d, Y0: f, where b and c are not even adjacent.

That is not hypothetical. Planting exactly that swap:

verdict
the whole of svg's suite green — every drawing in it is axis-aligned, so b == c == 0
a differential run against the parser as it stood before the move 57 518 points differ

So the move was proved against a control rather than against the suite: the old parser and the new one over 20 030 inputs × 6 matrices including a rotation, a shear and a mirror, compared with math.Float64bits — exact, because the move was meant to reorder no arithmetic. 115 518 agreed, 4 662 both refused, 0 differed. TestAShearedTransformTellsBFromC now keeps that witness in the repository, with b = 0.25 and c = 0.75.

ok is false both when the data cannot be read and when it draws nothing — a lone move, or a move and a close. Returning an empty path would let a caller paint nothing while believing it had painted something.

What an ICO directory may ask for

A reference decoder stays in codec only while what it allocates is bounded by the dimensions its header reports (a pixel ceiling can then stop it). The .ico reference, sergeymakinen/go-ico, was not, so ICO is now decoded here, DIB representations included:

input go-ico now
65535 directory entries pointing at one 512×512 PNG decodes and keeps all 65535 (68.7 GB by arithmetic) decodes the chosen one: under 16 MiB, tested
an entry whose size field says 4 GB, from a reader that cannot seek back allocates the 4 GB before reading every entry is a slice of the input; nothing is allocated from a size field
a 32-bit icon whose alpha bytes are all 0 fully transparent (measured) opaque, AND mask applied (Chromium's rule)
a 32-bit icon with real alpha alpha, then masked again alpha, mask skipped

A DIB must hold every byte its header implies (colour table, colour rows, mask rows) before its raster is allocated. A 256×256 32-bit icon decodes in 4 allocations and 262 KB, against go-ico's 20 and 596 KB. Fuzzed: FuzzDecodeICO.

What a Netpbm or QOI header may ask for

codec parses Netpbm (P1–P6) and QOI itself. Both refuse a header that describes more raster than the file holds: a binary Netpbm sample is one or two bytes, an ASCII one at least a byte, and one QOI chunk byte stands for at most 62 pixels. That is a property of the format, not a policy, so no limit is needed.

⛔ Measured before the check:

input before after
a 14-byte QOI header claiming 2²⁰×2²⁰ 4.4 TB asked of the allocator refused, nothing allocated
a 23-byte P5 header claiming 100000×100000 40 GB asked of the allocator refused
a P6 header whose width × height wraps to 0 panic (index out of range) refused

Both parsers are fuzzed (FuzzDecodePNM, FuzzDecodeQOI).

What any image header may ask for

A compressed format describes a large image in a few bytes: a 1×1 PNG whose header says 100000×100000 is a 40 GB decode. Since v0.37.0 every format is refused from its header, before its decoder allocates, above a pixel ceiling:

img, err := codec.DecodeWith(data, codec.Options{MaxPixels: 4_000_000})
if errors.Is(err, codec.ErrTooLarge) { … }

Decode and DecodeBest apply codec.DefaultMaxPixels, forty million pixels (152 MiB of RGBA), the ceiling svg and go-pdfkit/render use. ⚠ That is a change: a photograph from a 50-megapixel camera now needs Options{MaxPixels: …}. A service decoding files from strangers should set the ceiling to what it actually needs.

The ceiling is a bound because every decoder behind it allocates within the size its header reports (audited in their sources; see ico_decode.go). JPEG 2000 needs one more number: a codestream may declare 16384 components, so codec also hands go-images/jpeg2000 (v0.14.0) a sample ceiling of four per pixel.

Status

Landed: geometry (float64 point / axis-aligned rect / 2-D affine matrix — translate, scale, rotate, shear, compose, invert, transform point & rect), raster (pixel substrate), color (a complete colour-science layer: premultiplied alpha; the sRGB and generic-gamma transfer functions; the cylindrical sRGB models HSV/HSL/HWB; the CIE hub XYZ with D65 and D50 white points and Bradford D65↔D50 adaptation; CIE L*a*b*/LCh, L*u*v*/LCh(uv), Ottosson OKLab/OKLCH; Y′CbCr BT.601/709 and naive CMYK; the ΔE colour-difference metrics ΔE76, ΔE94, CIEDE2000 and ΔE-OK; the W3C separable and non-separable blend modes; and a second, scikit-image-byte-compatible sRGB↔XYZ↔Lab regime so go-images can share one colour library — all numerically checked against the colour-science oracle and the published CIE / W3C / Sharma reference values), resample (nearest, bilinear, box/area, bicubic, Lanczos — each with a premultiplied-alpha variant), and vector (2-D path builder + anti-aliased scanline fill/stroke rasterizer, extracted verbatim from go-widgets/painter and proven pixel-identical to it, now with linear/radial gradients and source-over compositing of any paint through a coverage grid). Colour-science and blend results match the published CIE / W3C reference values. Pure-Go, CGO=0, 100% covered, six-arch CI, numeric parity with Pillow. See docs/perf.md.

Known issue: loong64 with Go 1.27.0 or 1.27.1

golang/go#81000 is a loong64 code-generation fault that this package's own test suite found, and the upstream report is this repository's color test run on real LoongArch silicon (cfarm401), not under emulation. On loong64 the rule (Cvt64Fto32 x) => (TRUNCDW x) leaves an integer result in a floating-point register, so spilling it emits an 8-byte store; when the destination slot is narrower, that store reaches the live stack slots beside it.

affected GOARCH=loong64 built with go1.27.0 or go1.27.1
not affected go1.26.x, and every other architecture
fixed in Go 1.28 (CL 820040)
backport golang/go#81147, still open for 1.27.2 — and no go1.27.2 is released

go.mod declares a floor, so nothing stops you building this library with an affected toolchain. If you target loong64, build with go1.26.x until the backport lands.

What we have measured, and what we have not. Scanning the emitted loong64 code of every package here under go1.27.1 finds 64 of these conversions in shipped code, one of them spilled, and that one into an 8-aligned 8-byte int slot — a store that fills its own slot and reaches no neighbour. The corrupting shape appears only in two of our test frames, where a test's register pressure spills a uint8 onto consecutive bytes. So we know of no library path that is wrong today.

That is a bound, not a guarantee: inlining and register allocation are decided per build, so a program that compiles this library into a larger binary can create pressure these frames do not have. The scan and its controls are cmd/truncspill and the figures are in issue #13.

Our own loong64 CI lane is pinned to go1.26.4 for this reason, which is written out at the pin in .github/workflows/ci.yml with the condition for removing it.

License

BSD-3-Clause — see LICENSE. Copyright the go-gfx authors.

About

Pure-Go CGO=0 2D graphics foundation: geometry, color, raster buffers, high-quality resampling, image codecs, and vector rasterization. Shared substrate under go-images, go-widgets/painter, go-webengine.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages