feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+164
View File
@@ -0,0 +1,164 @@
package raster
import (
"image"
"runtime"
"sync"
"github.com/egoist/mygo/internal/scene"
)
// blurredImage is an image blurred (Op.Blur), as an op draws it: its
// texels, and where the op's Src lies in them.
type blurredImage struct {
img *scene.Image
src scene.Rect
}
// blurImages returns, for each OpImage of s that blurs its image and
// whose bounds meet area, the image blurred, as the GPU renderers compute
// it; nil when none does. Those missing the area are not drawn.
func (d *drawer) blurImages(s *scene.Scene, area image.Rectangle, bounds []image.Rectangle) []*blurredImage {
var out []*blurredImage
for i := range s.Ops {
op := &s.Ops[i]
if op.Kind != scene.OpImage || op.Blur <= 0 || op.Image == nil || op.Image.W == 0 || op.Image.H == 0 || !bounds[i].Overlaps(area) {
continue
}
if s := op.Image.Surface; s != nil && s.Format == scene.SurfaceNV12 {
continue // drawn unblurred, as the GPU renderers sample its planes
}
if out == nil {
out = make([]*blurredImage, len(s.Ops))
}
out[i] = blurImage(op.Image, op.Src, op.Blur)
}
return out
}
// blurImage returns the pixels of img within src blurred by blur, the
// standard deviation of a Gaussian in its pixels, transparent beyond src:
// averaged over squares, then blurred along rows and along columns, each
// step kept in 8 bits a channel, as a texture holds it, and as the GPU
// renderers' passes "down" and "blur" compute it.
func blurImage(img *scene.Image, src scene.Rect, blur float32) *blurredImage {
b := scene.ImageBlur(scene.ImageArea(src, img.W, img.H), blur)
w, h := b.Size()
out := &blurredImage{img: &scene.Image{W: w, H: h}, src: b.ImageSrc(src)}
pix := img.Pixels()
if w <= 0 || h <= 0 || len(pix) < 4*img.W*img.H {
out.img.W, out.img.H = 0, 0
return out
}
tex := make([]float32, 4*w*h)
k := b.Down
inv := 1 / float32(k*k)
for j := range h {
for i := range w {
var c [4]float32
for dy := range k {
y := b.Area.Min.Y + j*k + dy
if y >= b.Area.Max.Y {
continue // transparent beyond the area
}
for dx := range k {
x := b.Area.Min.X + i*k + dx
if x >= b.Area.Max.X {
continue
}
p := pix[4*(y*img.W+x):][:4]
for ch := range c {
c[ch] += float32(p[ch]) / 255
}
}
}
o := tex[4*(j*w+i):][:4]
for ch := range o {
o[ch] = texel(c[ch] * inv)
}
}
}
if b.Radius > 0 {
weights := make([]float32, b.Radius+1)
sum := float32(0)
for o := range weights {
weights[o] = scene.BlurWeight(o, b.Sigma)
if o == 0 {
sum += weights[o]
} else {
sum += 2 * weights[o]
}
}
tmp := make([]float32, len(tex))
blurLines(tmp, tex, weights, sum, 4, 4*w, w, h)
blurLines(tex, tmp, weights, sum, 4*w, 4, h, w)
}
out.img.Pix = make([]byte, len(tex))
for i, v := range tex {
out.img.Pix[i] = to8(v)
}
return out
}
// blurLines blurs lines of n texels step apart in src into dst, lines
// next apart, those beyond a line's ends transparent: every texel takes
// every weight, divided by their sum. Lines go to several cores when they
// are worth it.
func blurLines(dst, src, weights []float32, sum float32, step, next, n, lines int) {
rad := len(weights) - 1
workers := max(min(runtime.GOMAXPROCS(0), lines*n*(2*rad+1)/texelWork, maxWorkers), 1)
if workers == 1 {
for line := range lines {
blurLine(dst, src, weights, sum, step, line*next, n)
}
return
}
var wg sync.WaitGroup
per := (lines + workers - 1) / workers
for w := range workers {
lo, hi := w*per, min((w+1)*per, lines)
wg.Add(1)
go func() {
defer wg.Done()
for line := lo; line < hi; line++ {
blurLine(dst, src, weights, sum, step, line*next, n)
}
}()
}
wg.Wait()
}
// blurLine blurs the line of n texels step apart from base.
func blurLine(dst, src, weights []float32, sum float32, step, base, n int) {
rad := len(weights) - 1
for i := range n {
p := src[base+i*step:][:4]
w0 := weights[0]
c0, c1, c2, c3 := p[0]*w0, p[1]*w0, p[2]*w0, p[3]*w0
if i >= rad && i+rad < n {
// Far from both ends: every tap is a texel.
for o := 1; o <= rad; o++ {
a, b := src[base+(i-o)*step:][:4], src[base+(i+o)*step:][:4]
wo := weights[o]
c0 += (a[0] + b[0]) * wo
c1 += (a[1] + b[1]) * wo
c2 += (a[2] + b[2]) * wo
c3 += (a[3] + b[3]) * wo
}
} else {
for o := 1; o <= rad; o++ {
wo := weights[o]
if j := i - o; j >= 0 {
a := src[base+j*step:][:4]
c0, c1, c2, c3 = c0+a[0]*wo, c1+a[1]*wo, c2+a[2]*wo, c3+a[3]*wo
}
if j := i + o; j < n {
b := src[base+j*step:][:4]
c0, c1, c2, c3 = c0+b[0]*wo, c1+b[1]*wo, c2+b[2]*wo, c3+b[3]*wo
}
}
}
o := dst[base+i*step:][:4]
o[0], o[1], o[2], o[3] = texel(c0/sum), texel(c1/sum), texel(c2/sum), texel(c3/sum)
}
}
+60
View File
@@ -0,0 +1,60 @@
package raster
import (
"image"
"github.com/egoist/mygo/internal/scene"
)
// canvasScratch is shared by every canvas a renderer redraws. EachCanvas
// visits children before parents, so only one scratch image is needed.
// Keep it separate from the last frame and its differ: drawing a canvas
// must not replace the damage history of the window that shows it.
type canvasScratch struct {
image Image
diff scene.Differ
rs []renderer
}
// drawCanvases draws into their pixels the canvases s draws anew or shows,
// those changed since, each before the canvases and the scene that show
// it.
func (r *Renderer) drawCanvases(s *scene.Scene) {
s.EachCanvas(func(c *scene.Image) {
if c.PixVersion == c.Version() && len(c.Pix) == 4*c.W*c.H {
return
}
cs := c.Scene
cs.Width, cs.Height = c.W, c.H
if r.canvas == nil {
r.canvas = &canvasScratch{}
}
scratch := r.canvas
scratch.image.Resize(c.W, c.H)
scratch.diff.Reach = 1
scratch.diff.Diff(cs)
// Effects and folded ops stay local. Reuse only the band renderers'
// scratch, dropping their scene and image references after the draw.
d := drawer{rs: scratch.rs}
defer func() {
for i := range d.rs {
r := &d.rs[i]
r.s, r.dst, r.blurred = nil, nil, nil
// Popped clips remain in the backing array and can own masks.
clear(r.clips[:cap(r.clips)])
r.clips = r.clips[:0]
}
scratch.rs = d.rs
}()
d.draw(&scratch.image, cs, image.Rect(0, 0, c.W, c.H), scratch.diff.Bounds())
if len(c.Pix) != 4*c.W*c.H {
c.Pix = make([]byte, 4*c.W*c.H)
}
// From BGRA to the RGBA of images.
for i := 0; i+3 < len(scratch.image.Pix); i += 4 {
p := scratch.image.Pix[i : i+4]
c.Pix[i], c.Pix[i+1], c.Pix[i+2], c.Pix[i+3] = p[2], p[1], p[0], p[3]
}
c.PixVersion = c.Version()
})
}
+224
View File
@@ -0,0 +1,224 @@
package raster
import (
"bytes"
"fmt"
"reflect"
"runtime"
"testing"
"weak"
"github.com/egoist/mygo/internal/scene"
)
// A redraw starts transparent, including after a different canvas used the
// renderer, and draws children before their parents. Unchanged canvases keep
// their pixels even when the scene that made them has since been cleared.
func TestCanvasRedraws(t *testing.T) {
for _, incremental := range []bool{false, true} {
t.Run(fmt.Sprintf("incremental=%v", incremental), func(t *testing.T) {
child, parent := scene.NewCanvas(32, 24), scene.NewCanvas(64, 48)
s := &scene.Scene{Width: 80, Height: 64}
var r Renderer
defer r.Release()
for step, size := range [][2]int{{32, 24}, {17, 13}, {96, 60}, {32, 24}} {
child.Resize(size[0], size[1])
child.Scene.Reset(size[0], size[1], scene.Color{})
child.Scene.Ops = append(child.Scene.Ops, scene.Op{Kind: scene.OpFill,
Rect: scene.Rect{X: float32(step) + .25, Y: 2.5, W: 11, H: 8},
Color: scene.Color{R: 230, G: 70, B: 35, A: 140}})
parent.Scene.Reset(parent.W, parent.H, scene.Color{})
parent.Scene.Ops = append(parent.Scene.Ops,
scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 4, Y: 3, W: 32, H: 24},
Src: scene.Rect{W: float32(child.W), H: float32(child.H)}, Image: child},
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 45, Y: 20, W: 8, H: 8},
Color: scene.Color{G: 210, A: 255}})
parent.Changed()
s.Ops = []scene.Op{{Kind: scene.OpImage, Rect: scene.Rect{X: 3, Y: 5, W: 64, H: 48},
Src: scene.Rect{W: 64, H: 48}, Image: parent}}
// Listing a child as well must not draw it twice.
s.Canvases = []*scene.Image{parent, child}
var got []byte
if incremental {
r.Render(s)
got = bytes.Clone(r.Image.Pix)
} else {
dst := NewImage(s.Width, s.Height)
Render(dst, s)
got = dst.Pix
}
// Render each child into fresh memory, independent of scratch
// retained between canvas redraws, then compose the frame.
for _, c := range []*scene.Image{child, parent} {
fresh := NewImage(c.W, c.H)
Render(fresh, c.Scene)
want := fresh.RGBA()
if !bytes.Equal(c.Pix, want) {
t.Fatalf("step %d: canvas %dx%d differs from a fresh render", step, c.W, c.H)
}
if c.PixVersion != c.Version() {
t.Fatal("canvas pixels do not hold its current version")
}
}
want := NewImage(s.Width, s.Height)
Render(want, s)
if !bytes.Equal(got, want.Pix) {
t.Fatalf("step %d: frame differs from a fresh render", step)
}
if step == 2 {
r.Release()
}
}
before := bytes.Clone(parent.Pix)
parent.Scene.Reset(parent.W, parent.H, scene.Color{})
r.Render(s)
if !bytes.Equal(parent.Pix, before) {
t.Fatal("unchanged canvas lost its pixels")
}
})
}
}
func TestCanvasRedrawKeepsWindowDamage(t *testing.T) {
c := scene.NewCanvas(40, 32)
c.Scene.Ops = []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 20, H: 16}, Color: scene.Color{R: 160, A: 255}}}
s := &scene.Scene{Width: 100, Height: 80, Canvases: []*scene.Image{c},
Ops: []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 100, H: 80}, Color: scene.Color{B: 120, A: 255}}}}
var r Renderer
defer r.Release()
r.Render(s)
before := bytes.Clone(r.Image.Pix)
c.Scene.Ops[0].Color.G = 80
c.Changed()
if damage := r.Render(s); len(damage) != 0 {
t.Fatalf("redrawing a canvas the frame does not show damaged it: %v", damage)
}
if !bytes.Equal(r.Image.Pix, before) {
t.Fatal("canvas redraw replaced the window's pixels")
}
if c.Pix[1] != 80 {
t.Fatal("canvas was not redrawn when the window had no damage")
}
// The canvas's temporary BGRA pixels and bounds must leave with the
// window's frame on idle or close, as its main image does.
r.Release()
if !reflect.ValueOf(&r).Elem().IsZero() {
t.Fatal("Release kept rendering scratch memory")
}
}
func TestCanvasRemovalReleasesEffectInputs(t *testing.T) {
var r Renderer
defer r.Release()
s := &scene.Scene{Width: 8, Height: 8}
draw := func() weak.Pointer[scene.Image] {
input := scene.NewImageRGBA(64, 64, make([]byte, 4*64*64))
c := scene.NewCanvas(8, 8)
c.Scene.Effects = []scene.EffectOp{{
Effect: &scene.Effect{Pixels: func() scene.EffectPixels { return &testPixels{} }},
Images: [4]*scene.Image{input},
}}
c.Scene.Ops = []scene.Op{{Kind: scene.OpEffect, Rect: scene.Rect{W: 8, H: 8}}}
s.Canvases = []*scene.Image{c}
r.Render(s)
return weak.Make(input)
}
var inputs []weak.Pointer[scene.Image]
for range 16 {
inputs = append(inputs, draw())
}
s.Reset(8, 8, scene.Color{})
r.Render(s)
runtime.GC()
for i, input := range inputs {
if input.Value() != nil {
t.Fatalf("discarded canvas %d still retains its effect input", i)
}
}
runtime.KeepAlive(&r)
}
func TestCanvasRemovalReleasesBandInputs(t *testing.T) {
old := runtime.GOMAXPROCS(4)
defer runtime.GOMAXPROCS(old)
var r Renderer
defer r.Release()
s := &scene.Scene{Width: 8, Height: 8}
draw := func() weak.Pointer[scene.Image] {
input := scene.NewImageRGBA(8, 8, make([]byte, 4*8*8))
for i := 3; i < len(input.Pix); i += 4 {
input.Pix[i] = 128
}
c := scene.NewCanvas(256, 128)
for range 32 {
c.Scene.Ops = append(c.Scene.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 256, H: 128}, Color: scene.Color{R: 90, A: 100}})
}
c.Scene.Ops = append(c.Scene.Ops,
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{W: 256, H: 128}, Image: input, Src: scene.Rect{W: 8, H: 8}},
scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 10, Y: 10, W: 220, H: 100}, Image: input, Src: scene.Rect{W: 8, H: 8}, Blur: 2},
scene.Op{Kind: scene.OpPopClip})
s.Canvases = []*scene.Image{c}
r.Render(s)
if runtime.GOMAXPROCS(0) > 1 && len(r.canvas.rs) <= 1 {
t.Fatal("canvas did not use band renderers")
}
return weak.Make(input)
}
var inputs []weak.Pointer[scene.Image]
for range 8 {
inputs = append(inputs, draw())
}
s.Reset(8, 8, scene.Color{})
r.Render(s)
runtime.GC()
for i, input := range inputs {
if input.Value() != nil {
t.Fatalf("discarded canvas %d still retains a band input", i)
}
}
runtime.KeepAlive(&r)
}
func TestCanvasRedrawReadsPreviousPixels(t *testing.T) {
c := scene.NewCanvas(16, 8)
c.Scene.Ops = []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 4, H: 8}, Color: scene.Color{R: 190, G: 80, A: 255}}}
s := &scene.Scene{Width: 16, Height: 8, Canvases: []*scene.Image{c}}
var r Renderer
defer r.Release()
r.Render(s)
before := bytes.Clone(c.Pix)
c.Scene.Ops = []scene.Op{{Kind: scene.OpImage, Rect: scene.Rect{X: 4, W: 12, H: 8},
Src: scene.Rect{W: 12, H: 8}, Image: c}}
c.Changed()
r.Render(s)
for y := range c.H {
row := c.Pix[4*y*c.W : 4*(y+1)*c.W]
if !bytes.Equal(row[:16], make([]byte, 16)) || !bytes.Equal(row[16:], before[4*y*c.W:4*(y*c.W+12)]) {
t.Fatalf("row %d: drawing the previous image overwrote its source", y)
}
}
}
func BenchmarkCanvasRedraw(b *testing.B) {
for _, ops := range []int{32, 4096} {
b.Run(fmt.Sprintf("ops=%d", ops), func(b *testing.B) {
c := scene.NewCanvas(1024, 128)
for i := range ops {
c.Scene.Ops = append(c.Scene.Ops, scene.Op{Kind: scene.OpFill,
Rect: scene.Rect{X: float32(i * 13 % 1024), Y: float32(i * 7 % 128), W: 2, H: 7},
Color: scene.Color{R: 90, G: 140, B: 230, A: 180}})
}
s := &scene.Scene{Width: 1024, Height: 128, Canvases: []*scene.Image{c},
Ops: []scene.Op{{Kind: scene.OpImage, Rect: scene.Rect{W: 1024, H: 128},
Src: scene.Rect{W: 1024, H: 128}, Image: c}}}
var r Renderer
defer r.Release()
r.Render(s)
b.ReportAllocs()
for b.Loop() {
c.Changed()
r.Render(s)
}
})
}
}
+206
View File
@@ -0,0 +1,206 @@
package raster
import (
"image"
"math"
"runtime"
"github.com/egoist/mygo/internal/scene"
)
// ClipMask updates a retained coverage image for nested clips in area.
// GPU renderers cache this independently of the content within a clip, so
// moving content under a stationary clip costs no CPU pixel work.
//
// A row works out coverage only near the clips' edges: it is 0 outside a
// clip's bounds and 1 within the span every clip without a transform
// covers entirely, filled a run at a time. Large masks take several cores.
func ClipMask(dst *scene.Image, clips []scene.ClipShape, area image.Rectangle) *scene.Image {
w, h := area.Dx(), area.Dy()
if dst == nil {
dst = scene.NewImageRGBA(w, h, make([]byte, 4*w*h))
} else if dst.W != w || dst.H != h {
dst.Resize(w, h)
}
m := &clipMasker{dst: dst, area: area, clips: make([]maskClip, len(clips))}
for i := range clips {
c := &clips[i]
mc := &m.clips[i]
mc.shape = newShape(c.Rect, scene.Corners(c.Rect, c.Radii, c.Continuous))
mc.transform = c.Transform
mc.inverse, mc.valid = c.Transform.Inverse()
mc.mask, mc.masked = newClipMasking(c), c.Masks()
b := c.Rect
if c.Transform.Set {
b = c.Transform.Bounds(c.Rect)
}
// Continuous corners antialias up to 2 pixels out.
const margin = 3
mc.x0, mc.x1 = int(math.Floor(float64(b.X)))-margin, int(math.Ceil(float64(b.X+b.W)))+margin
mc.y0, mc.y1 = int(math.Floor(float64(b.Y)))-margin, int(math.Ceil(float64(b.Y+b.H)))+margin
if c.Transform.Perspective() {
// What is behind the viewer has no useful bounds.
mc.x0, mc.x1, mc.y0, mc.y1 = math.MinInt, math.MaxInt, math.MinInt, math.MaxInt
}
m.transformed = m.transformed || c.Transform.Set || mc.masked
}
workers := max(min(runtime.GOMAXPROCS(0), w*h/workArea, maxWorkers), 1)
if workers == 1 {
for y := range h {
m.row(0, y)
}
} else {
var t team
t.do = m.row
t.run(workers, h)
}
dst.Changed()
return dst
}
type clipMasker struct {
dst *scene.Image
area image.Rectangle
clips []maskClip
// transformed tells that a clip is transformed or masked, so no run
// is solid.
transformed bool
}
type maskClip struct {
shape
transform, inverse scene.Affine
valid bool
mask clipMasking
masked bool
// x0, x1, y0 and y1 bound the frame pixels the clip covers at all.
x0, x1, y0, y1 int
}
// row writes row y of the mask, from area.Min.Y.
func (m *clipMasker) row(_, y int) {
w := m.area.Dx()
pix := m.dst.Pix[4*y*w:][:4*w]
fy := y + m.area.Min.Y
// [lo, hi) are the frame pixels any clip covers, [slo, shi) those
// every clip without a transform covers entirely.
lo, hi := m.area.Min.X, m.area.Max.X
slo, shi := lo, hi
for i := range m.clips {
c := &m.clips[i]
if !c.valid || fy < c.y0 || fy >= c.y1 {
lo, hi = 0, 0
break
}
lo, hi = max(lo, c.x0), min(hi, c.x1)
if c.transform.Set || c.masked {
continue
}
a, b := solidSpan(&c.shape, float32(fy), float32(fy+1))
slo, shi = max(slo, a), min(shi, b)
}
if lo >= hi {
clear(pix)
return
}
clear(pix[:4*(lo-m.area.Min.X)])
clear(pix[4*(hi-m.area.Min.X):])
wy := float32(fy) + 0.5
for x := lo; x < hi; x++ {
at := 4 * (x - m.area.Min.X)
if x >= slo && x < shi && !m.transformed {
// Every clip covers the rest of the run entirely.
n := 4 * (shi - x)
fillAlpha(pix[at:at+n], 255)
x = shi - 1
continue
}
wx := float32(x) + 0.5
cov := float32(1)
for i := range m.clips {
c := &m.clips[i]
if !c.transform.Set && !c.masked && x >= slo && x < shi {
continue
}
cov *= transformedCoverage(&c.shape, c.transform, c.inverse, wx, wy)
if c.masked && cov > 0 {
cov *= c.mask.atFrame(c.transform, c.inverse, wx, wy)
}
if cov == 0 {
break
}
}
pix[at], pix[at+1], pix[at+2], pix[at+3] = 0, 0, 0, to8(cov)
}
}
// fillAlpha sets RGBA pixels to transparent black with alpha a.
func fillAlpha(pix []byte, a byte) {
if len(pix) == 0 {
return
}
pix[0], pix[1], pix[2], pix[3] = 0, 0, 0, a
for n := 4; n < len(pix); n *= 2 {
copy(pix[n:], pix[:n])
}
}
// clipMasking is what masks a clip besides its rounded rectangle
// (scene.ClipShape.Masks): the alpha of a gradient, and of an image.
type clipMasking struct {
paint painter
img *scene.Image
src, dst scene.Rect
}
func newClipMasking(c *scene.ClipShape) clipMasking {
var m clipMasking
if c.Paint != scene.PaintSolid {
op := scene.Op{Rect: c.Rect, Paint: c.Paint, Gradient: c.Gradient, Color: c.Color, Color2: c.Color2}
if c.Paint.HasStops() {
op.Stops = [2]int32{0, int32(len(c.Stops))}
}
m.paint = newPainter(&op, 1, c.Stops)
}
if c.Mask != nil && c.Mask.W > 0 && c.Mask.H > 0 {
m.img, m.src, m.dst = c.Mask, c.MaskSrc, c.Rect
}
return m
}
// at returns how much the gradient and the image let through at (x, y),
// in the clip's coordinates: the alpha of each, the gradient's at the
// point, the image's sampled there, nothing outside its rectangle.
func (m *clipMasking) at(x, y float32) float32 {
a := float32(1)
if !m.paint.solid() {
a = m.paint.at(x, y)[3]
}
if m.img != nil {
d := m.dst
if d.W <= 0 || d.H <= 0 || x < d.X || y < d.Y || x >= d.X+d.W || y >= d.Y+d.H {
return 0
}
u := m.src.X + (x-d.X)*m.src.W/d.W
v := m.src.Y + (y-d.Y)*m.src.H/d.H
a *= sample(m.img, u, v, unflipped(m.src))[3]
}
return a
}
// atFrame is at for the frame's pixel centered at (x, y), which m (inv its
// inverse) maps the clip to, when set: what lies behind the viewer lets
// nothing through.
func (m *clipMasking) atFrame(t, inv scene.Affine, x, y float32) float32 {
if !t.Set {
return m.at(x, y)
}
if !inv.Set {
return 0
}
lx, ly := inv.Point(x, y)
if t.Perspective() && t.W(lx, ly) <= 0 {
return 0
}
return m.at(lx, ly)
}
+114
View File
@@ -0,0 +1,114 @@
package raster
import (
"bytes"
"image"
"math/rand/v2"
"testing"
"github.com/egoist/mygo/internal/scene"
)
// referenceClipMask is ClipMask as one coverage test per pixel and clip,
// which ClipMask must match exactly.
func referenceClipMask(clips []scene.ClipShape, area image.Rectangle) []byte {
w, h := area.Dx(), area.Dy()
pix := make([]byte, 4*w*h)
for y := range h {
for x := range w {
wx, wy := float32(x+area.Min.X)+0.5, float32(y+area.Min.Y)+0.5
cov := float32(1)
for _, c := range clips {
s := newShape(c.Rect, scene.Corners(c.Rect, c.Radii, c.Continuous))
inv, ok := c.Transform.Inverse()
if !ok {
cov = 0
break
}
cov *= transformedCoverage(&s, c.Transform, inv, wx, wy)
if cov == 0 {
break
}
}
pix[4*(y*w+x)+3] = to8(cov)
}
}
return pix
}
func TestClipMaskMatchesPerPixelCoverage(t *testing.T) {
rng := rand.New(rand.NewPCG(1, 255))
f := func(lo, hi float32) float32 { return lo + rng.Float32()*(hi-lo) }
shape := func() scene.ClipShape {
r := scene.Rect{X: f(-20, 120), Y: f(-20, 100), W: f(0, 160), H: f(0, 130)}
c := scene.ClipShape{Rect: r, Continuous: rng.IntN(2) == 0}
if rng.IntN(4) > 0 {
rad := f(0, 40)
c.Radii = [4]float32{rad, rad * f(0, 1), rad, f(0, 30)}
}
switch rng.IntN(5) {
case 0:
c.Transform = scene.Translation(f(-30, 30), f(-30, 30)).Mul(scene.Rotation(f(-45, 45)))
case 1:
s := f(0.5, 2)
c.Transform = scene.Scaling(s, s)
case 2:
c.Transform = scene.Scaling(0, 1)
case 3:
c.Transform = scene.Translation(f(0, 40), f(0, 40))
c.Transform.G, c.Transform.H = f(-0.004, 0.004), f(-0.004, 0.004)
}
return c
}
area := image.Rect(-10, -5, 190, 150)
for i := range 400 {
clips := make([]scene.ClipShape, 1+rng.IntN(3))
for j := range clips {
clips[j] = shape()
}
want := referenceClipMask(clips, area)
got := ClipMask(nil, clips, area)
if !bytes.Equal(got.Pix, want) {
for k := range want {
if got.Pix[k] != want[k] {
px := k / 4
t.Fatalf("case %d, %+v: pixel (%d, %d) is %d, want %d", i, clips,
px%area.Dx()+area.Min.X, px/area.Dx()+area.Min.Y, got.Pix[k], want[k])
}
}
}
}
}
func TestClipMaskReusesAndResizesItsImage(t *testing.T) {
clips := []scene.ClipShape{{Rect: scene.Rect{X: 2, Y: 2, W: 40, H: 30}, Radii: [4]float32{8, 8, 8, 8}}}
img := ClipMask(nil, clips, image.Rect(0, 0, 50, 40))
for i := range img.Pix {
img.Pix[i] = 0xff
}
again := ClipMask(img, clips, image.Rect(0, 0, 60, 40))
if again != img || !bytes.Equal(again.Pix, referenceClipMask(clips, image.Rect(0, 0, 60, 40))) {
t.Fatal("a reused mask kept stale pixels")
}
}
func BenchmarkClipMaskRoundedCard(b *testing.B) {
// The rounded card of #255 at 2x, a list row's cell nested in it.
card := scene.ClipShape{Rect: scene.Rect{X: 32, Y: 136, W: 3400, H: 2000}, Radii: [4]float32{22, 22, 22, 22}}
cell := scene.ClipShape{Rect: scene.Rect{X: 32, Y: 200, W: 1900, H: 64}}
for _, bc := range []struct {
name string
clips []scene.ClipShape
area image.Rectangle
}{
{"card", []scene.ClipShape{card}, image.Rect(32, 136, 3432, 2136)},
{"cell", []scene.ClipShape{card, cell}, image.Rect(32, 200, 1932, 264)},
} {
b.Run(bc.name, func(b *testing.B) {
img := ClipMask(nil, bc.clips, bc.area)
for b.Loop() {
ClipMask(img, bc.clips, bc.area)
}
})
}
}
+118
View File
@@ -0,0 +1,118 @@
package raster
import "math"
// Continuous corners are Core Animation's, the corners macOS shows for
// CALayer's continuous corner curve and SwiftUI's rounded rectangles,
// computed as its shaders compute them (QuartzCore's supercircle_sdf),
// which a capture of the screen matches within a few 255ths a pixel.
//
// In a corner's own terms, u and v are how far a point is inside its
// vertical and horizontal edges, r its radius and e = contExtent·r
// how far from the corner the curve leaves the edges. With a = max(0,
// 1 − (u, v)/e) the point's place in the box of the curve, and ρ the ratio
// of a's smaller coordinate to its larger, the curve is where
//
// |a| + 1 − 1/(1 − ρ²·min(|a|, 1)·P(ρ)) = 1,
//
// P a quartic: a quarter circle of radius r around the diagonal, which
// bends less and less toward the edges. Where a side is too short for both
// of its corners' curves, the curves blend along it toward the quarter
// circles by the side's clamp factor: 0 while the curves fit, 1 once the
// side is no longer than two of their mean radius, as a pill's ends; a
// circle's corners, clamped both ways, are quarter circles. The shape is
// the intersection of its corners' (the largest of their values), so a
// curve may reach past the middle of a side whose other corner is smaller,
// and edges are antialiased by the value over the sum of its derivatives
// (fwidth). The shaders compute the same.
const contExtent = 1.528665
// contCorner is a continuous corner of radius r, whose curve leaves the
// edges e from the corner, blended toward a quarter circle by cx along
// its horizontal edge and cy along its vertical one; eff is where the
// curve's box ends as clamped.
type contCorner struct{ r, e, eff, cx, cy float32 }
// newContCorner returns the corner of radius r of a rectangle w×h whose
// horizontal edge it shares with a corner of radius rh, and its vertical
// one with one of radius rv.
func newContCorner(r, rh, rv, w, h float32) contCorner {
clamp := func(side, ra, rb float32) float32 {
return clamp01((contExtent - side/(ra+rb)) / (contExtent - 1))
}
c := contCorner{r: r, e: contExtent * r, cx: clamp(w, r, rh), cy: clamp(h, r, rv)}
c.eff = c.e + (r-c.e)*max(c.cx, c.cy)
return c
}
// dist returns the corner's value at the point u inside its vertical edge
// and v inside its horizontal one: about the signed distance to its edge
// near it, positive outside.
func (c *contCorner) dist(u, v float32) float32 {
ax, ay := max(0, 1-u/c.e), max(0, 1-v/c.e)
l := float32(math.Sqrt(float64(ax*ax + ay*ay)))
hi, lo := max(ax, ay), min(ax, ay)
var rho float32
if hi > 0 {
rho = min(lo/hi, 1)
}
p := (((-0.926054*rho+3.15601)*rho-3.64122)*rho+1.26803)*rho + 0.268531
f1 := l + 1 - 1/(1-rho*rho*min(l, 1)*p)
qx := max(0, ax*contExtent-(contExtent-1))
qy := max(0, ay*contExtent-(contExtent-1))
f2 := float32(math.Sqrt(float64(qx*qx+qy*qy)))*0.654166 + 0.345834
// The clamp along the edge the point is nearer to, blended across the
// diagonal.
s := float32(-1)
if ay > ax {
s = 1
}
w := clamp01(0.5 - s + s*rho)
fx, fy := f1+(f2-f1)*c.cx, f1+(f2-f1)*c.cy
f := fx + (fy-fx)*w
return min(max(c.eff-u, c.eff-v), 0) + c.e*(f-1)
}
// inset returns how far inside its vertical edge the corner's edge is v
// inside its horizontal one, and a bound at least as far: where dist is 0,
// which lies between the quarter circles of radius r and e, found by
// regula falsi (Illinois) within a hundredth of a pixel at radii of a few
// hundred.
func (c *contCorner) inset(v float32) (at, bound float32) {
if v >= c.e || c.r <= 0 {
return 0, 0
}
circle := func(r float32) float32 {
if v >= r {
return 0
}
return r - float32(math.Sqrt(float64(v*(2*r-v))))
}
lo, hi := circle(c.r), circle(c.e)
dlo, dhi := c.dist(lo, v), c.dist(hi, v)
if dlo <= 0 {
return lo, lo
}
if dhi >= 0 {
return hi, hi
}
side := 0
for range 5 {
m := (lo*dhi - hi*dlo) / (dhi - dlo)
dm := c.dist(m, v)
if dm > 0 {
lo, dlo = m, dm
if side == 1 {
dhi /= 2
}
side = 1
} else {
hi, dhi = m, dm
if side == -1 {
dlo /= 2
}
side = -1
}
}
return (lo*dhi - hi*dlo) / (dhi - dlo), hi
}
+99
View File
@@ -0,0 +1,99 @@
package raster
import (
"image"
"runtime"
"github.com/egoist/mygo/internal/scene"
)
// Renderer draws the successive scenes of a window into Image, redrawing
// only where a scene differs from the one before (scene.Differ): a
// blinking caret, a ticking clock or a button under the pointer redraws
// only itself.
type Renderer struct {
// Image holds the last scene drawn, in mem.
Image Image
mem *pixels
// d draws the bands of large damage.
d drawer
diff scene.Differ
damage []image.Rectangle
// canvas is allocated only when a canvas needs drawing in memory,
// reused between its redraws, and dropped with the frame by Release.
canvas *canvasScratch
}
// Render draws s, and returns the rectangles of Image it changed. s may
// change once Render returns.
func (r *Renderer) Render(s *scene.Scene) []image.Rectangle {
r.drawCanvases(s)
if r.whole(s) || r.Image.W != s.Width || r.Image.H != s.Height {
// A new size, or Image was released (Release).
r.resize(s.Width, s.Height)
r.damage = append(r.damage[:0], image.Rect(0, 0, s.Width, s.Height))
}
bounds := r.diff.Bounds()
for _, d := range r.damage {
r.d.draw(&r.Image, s, d, bounds)
}
r.diff.Remember(s)
return r.damage
}
// pixels is the memory of a Renderer's image (allocPixels).
type pixels struct {
b []byte
mapped bool
cleanup runtime.Cleanup
}
// resize makes Image w×h, reusing its memory when it can.
func (r *Renderer) resize(w, h int) {
n := 4 * w * h
if r.mem == nil || len(r.mem.b) < n {
r.mem.free()
r.mem = allocPixels(n)
}
r.Image = Image{W: w, H: h, Stride: 4 * w, Pix: r.mem.b[:n]}
}
// Release frees the image and what Render remembers: the next Render
// draws everything. Image must not be used meanwhile.
func (r *Renderer) Release() {
r.mem.free()
*r = Renderer{}
}
func area(rects []image.Rectangle) int {
n := 0
for _, d := range rects {
n += d.Dx() * d.Dy()
}
return n
}
// whole sets the damage of s against the last scene, and reports whether
// s must be drawn whole: there is none, or s changes too much of it.
func (r *Renderer) whole(s *scene.Scene) bool {
r.diff.Reach = 1 // a pixel's antialiased edge
damage, ok := r.diff.Diff(s)
if !ok {
return true
}
r.damage = r.diff.AddBackdrops(s, append(r.damage[:0], damage...))
// Past half the window, drawing it whole costs about the same.
return area(r.damage)*2 >= s.Width*s.Height
}
// Invalidate makes the next Render draw everything.
func (r *Renderer) Invalidate() { r.diff.Invalidate() }
// opBounds returns where each operation of s draws, within the clips
// around it, for a renderer without a last scene.
func (r *Renderer) opBounds(s *scene.Scene) []image.Rectangle {
r.diff.Reach = 1
r.diff.Diff(s)
return r.diff.Bounds()
}
+252
View File
@@ -0,0 +1,252 @@
package raster
import (
"bytes"
"fmt"
"image"
"math/rand/v2"
"testing"
"github.com/egoist/mygo/internal/scene"
)
// sceneMaker builds random scenes and changes them a little at a time.
type sceneMaker struct {
rnd *rand.Rand
atlas *scene.Atlas
img *scene.Image
// masks are rectangles of the atlas holding something.
masks [][4]uint16
// effects has op make effects too.
effects bool
}
func newSceneMaker(seed uint64) *sceneMaker {
m := &sceneMaker{rnd: rand.New(rand.NewPCG(seed, 7)), atlas: scene.NewAtlas(1, 128, 128)}
for range 6 {
w, h := 4+m.rnd.IntN(12), 4+m.rnd.IntN(12)
x, y, ok := m.atlas.Alloc(w, h)
if !ok {
break
}
m.atlas.Put(x, y, w, h, m.pixels(w*h), w)
m.masks = append(m.masks, [4]uint16{uint16(x), uint16(y), uint16(w), uint16(h)})
}
m.img = scene.NewImageRGBA(8, 8, m.pixels(8*8*4))
return m
}
func (m *sceneMaker) pixels(n int) []byte {
p := make([]byte, n)
for i := range p {
p[i] = byte(m.rnd.IntN(256))
}
return p
}
func (m *sceneMaker) color() scene.Color {
return scene.Color{R: uint8(m.rnd.IntN(256)), G: uint8(m.rnd.IntN(256)), B: uint8(m.rnd.IntN(256)), A: uint8(64 + m.rnd.IntN(192))}
}
func (m *sceneMaker) rect() scene.Rect {
return scene.Rect{X: m.rnd.Float32()*150 - 10, Y: m.rnd.Float32()*110 - 10, W: 2 + m.rnd.Float32()*60, H: 2 + m.rnd.Float32()*50}
}
// op returns a random operation that draws.
func (m *sceneMaker) op(s *scene.Scene) scene.Op {
if m.effects && m.rnd.IntN(4) == 0 {
r := m.rnd.Float32() * 20
fx := scene.EffectOp{Effect: lensEffect, Blur: float32(m.rnd.IntN(4)) * 3}
if m.rnd.IntN(3) == 0 {
fx.Effect = tintEffect
}
fx.Params[0] = [4]float32{m.rnd.Float32() * 4}
c := m.color()
fx.Params[1] = [4]float32{float32(c.R) / 255, float32(c.G) / 255, float32(c.B) / 255, float32(c.A) / 255}
s.Effects = append(s.Effects, fx)
return scene.Op{Kind: scene.OpEffect, Rect: m.rect(), Radii: [4]float32{r, r, r, r}, Start: int32(len(s.Effects) - 1)}
}
switch m.rnd.IntN(4) {
case 0:
r := m.rnd.Float32() * 12
return scene.Op{Kind: scene.OpFill, Rect: m.rect(), Radii: [4]float32{r, r, r, r}, Color: m.color(),
Border: scene.Uniform(float32(m.rnd.IntN(3))), BorderColor: m.color()}
case 1:
return scene.Op{Kind: scene.OpShadow, Rect: m.rect(), Radii: [4]float32{4, 4, 4, 4}, Color: m.color(), Blur: m.rnd.Float32() * 16}
case 2:
start := int32(len(s.Glyphs))
for range 1 + m.rnd.IntN(3) {
k := m.masks[m.rnd.IntN(len(m.masks))]
s.Glyphs = append(s.Glyphs, scene.Glyph{X: float32(m.rnd.IntN(150)), Y: float32(m.rnd.IntN(110)),
W: float32(k[2]), H: float32(k[3]), U: k[0], V: k[1], UW: k[2], VH: k[3], Color: m.color()})
}
return scene.Op{Kind: scene.OpGlyphs, Start: start, End: int32(len(s.Glyphs))}
default:
return scene.Op{Kind: scene.OpImage, Rect: m.rect(), Image: m.img, Src: scene.Rect{W: 8, H: 8}}
}
}
func (m *sceneMaker) scene() *scene.Scene {
s := &scene.Scene{Width: 160, Height: 120, Clear: scene.Color{R: 250, G: 250, B: 250, A: 255}, MaskAtlas: m.atlas}
for range 8 {
s.Ops = append(s.Ops, m.op(s))
}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: m.rect(), Radii: [4]float32{6, 6, 6, 6}})
for range 5 {
s.Ops = append(s.Ops, m.op(s))
}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
for range 4 {
s.Ops = append(s.Ops, m.op(s))
}
return s
}
// change changes s a little, as a frame of an app would, and says how.
func (m *sceneMaker) change(s *scene.Scene) string {
// Drawing operations, which can change freely, unlike clips.
var drawing []int
for i, op := range s.Ops {
if op.Kind != scene.OpPushClip && op.Kind != scene.OpPopClip {
drawing = append(drawing, i)
}
}
i := drawing[m.rnd.IntN(len(drawing))]
switch m.rnd.IntN(8) {
case 0:
s.Ops[i].Color = m.color()
return "color"
case 1:
if s.Ops[i].Kind == scene.OpGlyphs {
g := &s.Glyphs[s.Ops[i].Start]
g.X += 3
return "glyph moved"
}
s.Ops[i].Rect.X += m.rnd.Float32()*20 - 10
return "moved"
case 2:
s.Ops = append(s.Ops[:i+1], s.Ops[i:]...)
s.Ops[i] = m.op(s)
return "inserted"
case 3:
if len(drawing) > 4 {
s.Ops = append(s.Ops[:i], s.Ops[i+1:]...)
return "deleted"
}
return "nothing"
case 4:
for j := range s.Ops {
if s.Ops[j].Kind == scene.OpPushClip {
s.Ops[j].Rect = m.rect()
}
}
return "clip moved"
case 5:
// New pixels where glyphs are, as a transient mask of the next
// frame takes the place of the last one's.
k := m.masks[m.rnd.IntN(len(m.masks))]
m.atlas.Put(int(k[0]), int(k[1]), int(k[2]), int(k[3]), m.pixels(int(k[2])*int(k[3])), int(k[2]))
return "atlas pixels"
case 6:
copy(m.img.Pix, m.pixels(len(m.img.Pix)))
m.img.Changed()
return "image pixels"
default:
return "nothing"
}
}
func TestRendererRedrawsWhatChanged(t *testing.T) {
testRedraws(t, false)
}
// TestRendererRedrawsEffects checks that effects, and what is under those
// reading their backdrops, show however little of the window changes.
func TestRendererRedrawsEffects(t *testing.T) {
testRedraws(t, true)
}
func testRedraws(t *testing.T, effects bool) {
for seed := range uint64(40) {
m := newSceneMaker(seed)
m.effects = effects
s := m.scene()
var r Renderer
full := NewImage(s.Width, s.Height)
var partial int
for step := range 30 {
what := "first"
if step > 0 {
what = m.change(s)
}
damage := r.Render(s)
Render(full, s)
if !bytes.Equal(r.Image.Pix, full.Pix) {
writePNG(t, fmt.Sprintf("damage-%d-%d", seed, step), &r.Image)
writePNG(t, fmt.Sprintf("damage-%d-%d-want", seed, step), full)
t.Fatalf("seed %d, step %d (%s): the redrawn %v differs from a whole drawing", seed, step, what, damage)
}
if step > 0 && (len(damage) != 1 || damage[0].Dx() != s.Width || damage[0].Dy() != s.Height) {
partial++
}
}
if partial == 0 {
t.Errorf("seed %d: every frame was drawn whole", seed)
}
}
}
func TestRendererSkipsUnchangedScenes(t *testing.T) {
m := newSceneMaker(1)
s := m.scene()
var r Renderer
r.Render(s)
if damage := r.Render(s); len(damage) != 0 {
t.Errorf("an unchanged scene redrew %v", damage)
}
s.Ops[3].Color = scene.Color{R: 1, A: 255}
damage := r.Render(s)
if len(damage) != 1 || damage[0].Dx()*damage[0].Dy() >= s.Width*s.Height/2 {
t.Errorf("one changed operation redrew %v", damage)
}
}
// TestBandsDrawAsOne checks that a large area drawn in bands on several
// cores, leaving out the operations each band misses, has the pixels of
// the area drawn at once with every operation.
func TestBandsDrawAsOne(t *testing.T) {
m := newSceneMaker(3)
for i := range 6 {
s := scaled(m.scene(), 8)
got := NewImage(s.Width, s.Height)
Render(got, s)
all := make([]image.Rectangle, len(s.Ops))
for j := range all {
all[j] = image.Rect(0, 0, s.Width, s.Height)
}
want := NewImage(s.Width, s.Height)
var r renderer
r.render(want, s, image.Rect(0, 0, s.Width, s.Height), all, 0, len(s.Ops), nil, nil)
if !bytes.Equal(got.Pix, want.Pix) {
t.Errorf("scene %d: drawn in bands, its pixels differ", i)
}
}
}
// scaled returns s k times as large, its glyphs as large as they were.
func scaled(s *scene.Scene, k float32) *scene.Scene {
s.Width, s.Height = s.Width*int(k), s.Height*int(k)
for i := range s.Ops {
op := &s.Ops[i]
op.Rect = scene.Rect{X: op.Rect.X * k, Y: op.Rect.Y * k, W: op.Rect.W * k, H: op.Rect.H * k}
op.Blur *= k
for j := range op.Radii {
op.Radii[j] *= k
}
}
for i := range s.Glyphs {
s.Glyphs[i].X *= k
s.Glyphs[i].Y *= k
}
return s
}
+275
View File
@@ -0,0 +1,275 @@
package raster
import (
"bytes"
"fmt"
"image"
"runtime"
"sync/atomic"
"testing"
"github.com/egoist/mygo/internal/scene"
)
func shortScene(count int, dense bool) *scene.Scene {
s := &scene.Scene{Width: 1024, Height: 105, Clear: scene.Color{R: 20, G: 30, B: 40, A: 127}}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: .25, Y: .5, W: 1023.5, H: 104}, Radii: [4]float32{6, 9, 12, 3}})
for i := range count {
r := scene.Rect{X: float32(i * 13 % 1024), Y: float32(i * 7 % 105), W: 2, H: 7}
if dense {
r.Y, r.W, r.H = -.25, 3.5, 106
}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: r, Color: scene.Color{R: 90, G: 140, B: 230, A: 80}})
}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
return s
}
func TestDenseShortTargetDrawsAsOne(t *testing.T) {
old := runtime.GOMAXPROCS(4)
defer runtime.GOMAXPROCS(old)
s := shortScene(4096, true)
for _, area := range []image.Rectangle{image.Rect(0, 0, s.Width, s.Height), image.Rect(19, 11, 997, 99)} {
var r Renderer
defer r.Release()
got, want := NewImage(s.Width, s.Height), NewImage(s.Width, s.Height)
bounds := r.opBounds(s)
r.d.draw(got, s, area, bounds)
// Browser builds keep GOMAXPROCS at one, even after a request for
// four. They still check the same pixels through the serial path.
if runtime.GOMAXPROCS(0) > 1 && (len(r.d.rs) <= 1 || r.d.bands.parts <= 1) {
t.Fatal("dense short target used only one renderer")
}
var one renderer
one.render(want, s, area, bounds, 0, len(s.Ops), nil, nil)
if !bytes.Equal(got.Pix, want.Pix) {
t.Fatalf("drawing %v in bands changed pixels", area)
}
}
}
func TestDamagePaddingDoesNotMakeDisjointFillsDense(t *testing.T) {
old := runtime.GOMAXPROCS(4)
defer runtime.GOMAXPROCS(old)
for _, clipped := range []bool{false, true} {
t.Run(fmt.Sprint("clipped=", clipped), func(t *testing.T) {
s := &scene.Scene{Width: 16, Height: 8192}
for y := range s.Height {
for x := 0; x < s.Width; x += 2 {
rc := scene.Rect{X: float32(x), Y: float32(y), W: 1, H: 1}
if clipped {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: rc})
rc = scene.Rect{W: 16, H: 8192}
}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: rc, Color: scene.Color{R: 37, G: 99, B: 235, A: 255}})
if clipped {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
}
}
}
var r Renderer
defer r.Release()
r.Render(s)
if len(r.d.rs) != 1 {
t.Fatalf("disjoint fills used %d renderers", len(r.d.rs))
}
for y := range s.Height {
for x := range s.Width {
want := [4]byte{}
if x%2 == 0 {
want = [4]byte{37, 99, 235, 255}
}
if got := pixel(&r.Image, x, y); got != want {
t.Fatalf("pixel (%d, %d) = %v, want %v", x, y, got, want)
}
}
}
})
}
}
func TestDenseTallTargetBoundsBandCount(t *testing.T) {
old := runtime.GOMAXPROCS(4)
defer runtime.GOMAXPROCS(old)
s := &scene.Scene{Width: 16, Height: 8192}
for i := range 8 {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 16, H: 8192}, Color: scene.Color{R: byte(i), A: 255}})
}
var r Renderer
defer r.Release()
r.Render(s)
if runtime.GOMAXPROCS(0) > 1 && (len(r.d.rs) <= 1 || r.d.bands.parts <= 1) {
t.Fatal("dense tall target did not split its work")
}
if r.d.bands.parts > 2*runtime.GOMAXPROCS(0) {
t.Fatalf("tall target traversed its scene in %d bands", r.d.bands.parts)
}
for y := range s.Height {
for x := range s.Width {
if got := pixel(&r.Image, x, y); got != [4]byte{7, 0, 0, 255} {
t.Fatalf("pixel (%d, %d) = %v", x, y, got)
}
}
}
}
func TestDenseMixedTargetDrawsAsOne(t *testing.T) {
old := runtime.GOMAXPROCS(4)
defer runtime.GOMAXPROCS(old)
s := shortScene(4096, true)
m := newSceneMaker(42)
s.MaskAtlas = m.atlas
k := m.masks[0]
s.Glyphs = []scene.Glyph{{X: 354.25, Y: 22.5, W: float32(k[2]), H: float32(k[3]), U: k[0], V: k[1], UW: k[2], VH: k[3], Color: scene.Color{R: 220, G: 90, A: 170}}}
s.Ops = append(s.Ops,
scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: 20.25, Y: 4.5, W: 120, H: 94}, Image: m.img, Src: scene.Rect{W: 8, H: 8}},
scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 160.25, Y: 10.5, W: 64, H: 70}, Radii: scene.Uniform(6), Color: scene.Color{A: 120}, Blur: 6},
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 250.5, Y: 3.25, W: 70, H: 94}, Paint: scene.PaintLinear, Color: scene.Color{R: 210, A: 180}, Color2: scene.Color{B: 230, A: 90}, Gradient: [4]float32{250, 3, 320, 97}},
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 350.25, Y: 3.5, W: 100, H: 96}, Image: m.img, Src: scene.Rect{W: 8, H: 8}},
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 350, W: 100, H: 105}, Color: scene.Color{G: 180, A: 160}},
scene.Op{Kind: scene.OpGlyphs, Start: 0, End: 1},
scene.Op{Kind: scene.OpPopClip})
for _, area := range []image.Rectangle{image.Rect(0, 0, s.Width, s.Height), image.Rect(19, 11, 997, 99)} {
var r Renderer
defer r.Release()
got, want := NewImage(s.Width, s.Height), NewImage(s.Width, s.Height)
bounds := r.opBounds(s)
r.d.draw(got, s, area, bounds)
if runtime.GOMAXPROCS(0) > 1 && (len(r.d.rs) <= 1 || r.d.bands.parts <= 1) {
t.Fatal("mixed target did not split its work")
}
var one renderer
one.render(want, s, area, bounds, 0, len(s.Ops), nil, nil)
if !bytes.Equal(got.Pix, want.Pix) {
t.Fatalf("drawing mixed operations in %v changed pixels", area)
}
}
}
func TestShortSparseTargetStaysOnOneCore(t *testing.T) {
old := runtime.GOMAXPROCS(4)
defer runtime.GOMAXPROCS(old)
for _, count := range []int{32, 4096} {
s := shortScene(count, false)
// Borders visit their edges, not their transparent interiors.
for i := range 6 {
inset := float32(i)
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill,
Rect: scene.Rect{X: inset, Y: inset, W: 1024 - 2*inset, H: 105 - 2*inset},
Border: scene.Uniform(1), BorderColor: scene.Color{R: 255, A: 255}})
}
// Clip bounds are not work: clips that enclose no paint must not
// make an otherwise cheap target wake more workers.
for range 32 {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{W: 1024, H: 105}}, scene.Op{Kind: scene.OpPopClip})
}
var r Renderer
r.Render(s)
if len(r.d.rs) != 1 {
t.Fatalf("sparse target with %d operations used %d renderers", count, len(r.d.rs))
}
r.Release()
}
}
func TestDenseFillsPreserveEffectBands(t *testing.T) {
old := runtime.GOMAXPROCS(8)
defer runtime.GOMAXPROCS(old)
s := &scene.Scene{Width: 256, Height: 2048, Effects: []scene.EffectOp{{Effect: tintEffect}}}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpEffect, Rect: scene.Rect{Y: 32, W: 256, H: 64}})
for range 4 {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 256, H: 2048}, Color: scene.Color{R: 37, G: 99, B: 235, A: 80}})
}
var r Renderer
defer r.Release()
var effectBands atomic.Int32
r.d.bands.do = func(member, part int) {
j := &r.d.job
first := j.area.Min.Y + part*j.rows
if j.px != nil && first < 96 && first+j.rows > 32 {
effectBands.Add(1)
}
r.d.band(member, part)
}
r.Render(s)
if runtime.GOMAXPROCS(0) > 1 && effectBands.Load() < 4 {
t.Fatalf("dense fills reduced the effect to %d nonempty bands", effectBands.Load())
}
}
func TestDenseFillsPreserveParallelSchedule(t *testing.T) {
old := runtime.GOMAXPROCS(8)
defer runtime.GOMAXPROCS(old)
s := &scene.Scene{Width: 256, Height: 2048}
for range 8 {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 256, H: 2048}, Color: scene.Color{R: 37, G: 99, B: 235, A: 80}})
}
var r Renderer
defer r.Release()
r.Render(s)
want := min(runtime.GOMAXPROCS(0), 4)
if len(r.d.rs) != want {
t.Fatalf("already-parallel target used %d renderers, want %d", len(r.d.rs), want)
}
if want > 1 && r.d.bands.parts != s.Height/bandRows {
t.Fatalf("already-parallel target changed its %d-row bands", bandRows)
}
}
func localizedOverdraw() *scene.Scene {
s := &scene.Scene{Width: 16, Height: 8192}
for range 4096 {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 16, H: 16}, Color: scene.Color{R: 99, A: 255}})
}
return s
}
func TestLocalizedOverdrawStaysOnOneCore(t *testing.T) {
old := runtime.GOMAXPROCS(8)
defer runtime.GOMAXPROCS(old)
var r Renderer
defer r.Release()
r.Render(localizedOverdraw())
if len(r.d.rs) != 1 {
t.Fatalf("overdraw confined to one band used %d renderers", len(r.d.rs))
}
}
func BenchmarkLocalizedOverdraw(b *testing.B) {
s := localizedOverdraw()
var r Renderer
defer r.Release()
r.Render(s)
b.ReportAllocs()
for b.Loop() {
r.Invalidate()
r.Render(s)
}
}
func BenchmarkShortTarget(b *testing.B) {
for _, dense := range []bool{false, true} {
for _, canvas := range []bool{false, true} {
b.Run(fmt.Sprintf("dense=%t/canvas=%t", dense, canvas), func(b *testing.B) {
s := shortScene(4096, dense)
var c *scene.Image
if canvas {
c = scene.NewCanvas(s.Width, s.Height)
*c.Scene = *s
s = &scene.Scene{Width: c.W, Height: c.H, Canvases: []*scene.Image{c}, Ops: []scene.Op{{Kind: scene.OpImage, Rect: scene.Rect{W: float32(c.W), H: float32(c.H)}, Src: scene.Rect{W: float32(c.W), H: float32(c.H)}, Image: c}}}
}
var r Renderer
defer r.Release()
r.Render(s)
b.ReportAllocs()
for b.Loop() {
if c != nil {
c.Changed()
}
r.Invalidate()
r.Render(s)
}
})
}
}
}
+312
View File
@@ -0,0 +1,312 @@
package raster
import (
"math"
"runtime"
"github.com/egoist/mygo/internal/scene"
)
// drawer is what draw keeps from scene to scene: the renderers of the
// bands and the team drawing them, the backdrop of an effect, and the
// effects' CPU twins.
type drawer struct {
rs []renderer
bands team
job bandJob
bd backdrop
fx map[*scene.Effect]scene.EffectPixels
// blurred holds, by op, the images of the scene drawn that blur theirs
// (blurImages).
blurred []*blurredImage
fold scene.TranslationFolder
inst instancer
// over draws over what the image holds (Layer.Over).
over bool
}
// pixels returns what draws e on the CPU, made the first time, or nil for
// an effect without.
func (d *drawer) pixels(e *scene.Effect) scene.EffectPixels {
if e == nil || e.Pixels == nil {
return nil
}
px := d.fx[e]
if px == nil {
if d.fx == nil {
d.fx = map[*scene.Effect]scene.EffectPixels{}
}
px = e.Pixels()
d.fx[e] = px
}
return px
}
// backdrop computes the backdrop of an effect, as the GPU renderers do in
// textures, rounded to 8 bits at each step.
type backdrop struct {
img scene.BackdropImage
// tmp holds the rows blurred, before the columns are.
tmp []float32
weights []float32
// lines does the passes of read on several cores, each line of pass
// over dst (line).
lines team
dst *Image
pass int
}
// The passes of backdrop.read.
const (
averagePass = iota
rowsPass
columnsPass
)
// texelWork is how many texels times taps are worth waking other cores
// for.
const texelWork = 64 << 10
// read computes the backdrop b of dst.
func (bd *backdrop) read(dst *Image, b scene.Backdrop) {
img := &bd.img
img.Backdrop = b
img.W, img.H = b.Size()
n := 4 * img.W * img.H
if cap(img.Pix) < n {
img.Pix, bd.tmp = make([]float32, n), make([]float32, n)
}
img.Pix, bd.tmp = img.Pix[:n], bd.tmp[:n]
if n == 0 {
return
}
bd.dst = dst
k := b.Down
bd.run(averagePass, img.H, img.W*k*k)
if b.Radius == 0 {
return
}
bd.weights = bd.weights[:0]
for i := 0; i <= b.Radius; i++ {
bd.weights = append(bd.weights, scene.BlurWeight(i, b.Sigma))
}
taps := 2*b.Radius + 1
bd.run(rowsPass, img.H, img.W*taps)
bd.run(columnsPass, img.W, img.H*taps)
}
// run does lines 0 to n-1 of pass, each work texels times taps, on
// several cores when they are worth it.
func (bd *backdrop) run(pass, n, work int) {
bd.pass = pass
workers := max(min(runtime.GOMAXPROCS(0), n*work/texelWork, maxWorkers), 1)
if workers == 1 {
for i := range n {
bd.line(0, i)
}
return
}
if bd.lines.do == nil {
bd.lines.do = bd.line
}
bd.lines.run(workers, n)
}
// line does line i of the pass.
func (bd *backdrop) line(_, i int) {
img := &bd.img
switch bd.pass {
case averagePass:
bd.average(bd.dst, i)
case rowsPass:
bd.blur(bd.tmp, img.Pix, 4, 4*img.W, img.W, i)
default:
bd.blur(img.Pix, bd.tmp, 4*img.W, 4, img.H, i)
}
}
// average computes row j of the texels: the average of each square of
// the area, those along its far edges repeating its last pixels, as a
// texture's edges do.
func (bd *backdrop) average(dst *Image, j int) {
img := &bd.img
k := img.Down
inv := 1 / float32(k*k)
for i := range img.W {
var c [4]float32
for dy := range k {
y := min(img.Area.Min.Y+j*k+dy, img.Area.Max.Y-1)
row := dst.Pix[y*dst.Stride:]
for dx := range k {
x := min(img.Area.Min.X+i*k+dx, img.Area.Max.X-1)
p := row[4*x : 4*x+4]
// BGRA to RGBA.
c[0] += float32(p[2]) / 255
c[1] += float32(p[1]) / 255
c[2] += float32(p[0]) / 255
c[3] += float32(p[3]) / 255
}
}
o := img.Pix[4*(j*img.W+i):][:4]
for ch := range o {
o[ch] = texel(c[ch] * inv)
}
}
}
// texel returns v as an 8-bit channel of a texture holds it.
func texel(v float32) float32 { return float32(to8(v)) / 255 }
// blur blurs line of src into dst: n texels step apart, from line×next,
// clamping at its ends.
func (bd *backdrop) blur(dst, src []float32, step, next, n, line int) {
rad := bd.img.Radius
w := bd.weights
// Every texel takes every weight, those past the ends on the last
// texel.
sum := w[0]
for o := 1; o <= rad; o++ {
sum += 2 * w[o]
}
base := line * next
for i := range n {
p := src[base+i*step:][:4]
c0, c1, c2, c3 := p[0]*w[0], p[1]*w[0], p[2]*w[0], p[3]*w[0]
if i >= rad && i+rad < n {
for o := 1; o <= rad; o++ {
a, b := src[base+(i-o)*step:][:4], src[base+(i+o)*step:][:4]
wo := w[o]
c0 += (a[0] + b[0]) * wo
c1 += (a[1] + b[1]) * wo
c2 += (a[2] + b[2]) * wo
c3 += (a[3] + b[3]) * wo
}
} else {
for o := 1; o <= rad; o++ {
a, b := src[base+max(i-o, 0)*step:][:4], src[base+min(i+o, n-1)*step:][:4]
wo := w[o]
c0 += (a[0] + b[0]) * wo
c1 += (a[1] + b[1]) * wo
c2 += (a[2] + b[2]) * wo
c3 += (a[3] + b[3]) * wo
}
}
d := dst[base+i*step:][:4]
d[0], d[1], d[2], d[3] = texel(c0/sum), texel(c1/sum), texel(c2/sum), texel(c3/sum)
}
}
// effect draws an effect with px, which Begin readied for op, over its
// backdrop b (nil for an effect reading none), within its shape, whose
// corners are continuous when the op's are, while the effect works with
// circular ones.
func (r *renderer) effect(op *scene.Op, px scene.EffectPixels, b *scene.BackdropImage) {
if op.Rect.Empty() {
return
}
opacity := op.Opacity
if opacity == 0 {
opacity = 1
}
radii := scene.Corners(op.Rect, op.Radii, op.Continuous)
box := newShape(op.Rect, radii)
round := hasRadii(radii)
x0, y0, x1, y1 := r.pixelBounds(op.Rect)
for y := y0; y < y1; y++ {
row := r.dst.Pix[y*r.dst.Stride:]
py := float32(y) + 0.5
cl, ch := r.clipSolid(y)
ol, oh := solidSpan(&box, float32(y), float32(y+1))
for x := x0; x < x1; x++ {
px0 := float32(x) + 0.5
cov := opacity
if x < ol || x >= oh || !round {
cov *= coverage(&box, px0, py)
}
if x < cl || x >= ch {
cov *= r.clipCoverage(x, y)
}
if cov <= 0 {
continue
}
c := px.Color(px0, py, b)
p := row[4*x : 4*x+4]
if cov >= 1 && c[3] >= 1 {
// Opaque.
p[0], p[1], p[2], p[3] = to8(c[2]), to8(c[1]), to8(c[0]), 255
continue
}
blend(p, c, cov)
}
}
}
// maskedEffect draws a shader's effect filling mask glyphs (fx.Glyphs) with
// px, as glyphs draws mask glyphs: each pixel the shader's color times the
// glyph's coverage, corrected for that color.
func (r *renderer) maskedEffect(op *scene.Op, fx *scene.EffectOp, px scene.EffectPixels) {
atlas := r.s.MaskAtlas
if atlas == nil {
return
}
opacity := opacityOf(op.Opacity)
text := r.s.Text
for _, g := range r.s.Glyphs[fx.Glyphs[0]:fx.Glyphs[1]] {
if g.Colored || g.Subpixel {
continue
}
boost := float32(0)
if g.Thin {
boost = scene.ThinBoost
}
box := scene.Rect{X: float32(math.Round(float64(g.X))), Y: float32(math.Round(float64(g.Y))), W: float32(g.UW), H: float32(g.VH)}
m := op.Transform.Mul(g.Transform)
if !m.Set {
gx, gy := int(box.X), int(box.Y)
x0, y0 := max(gx, r.x0), max(gy, r.y0)
x1, y1 := min(gx+int(g.UW), r.x1), min(gy+int(g.VH), r.y1)
for y := y0; y < y1; y++ {
row := r.dst.Pix[y*r.dst.Stride:]
cl, ch := r.clipSolid(y)
ay := int(g.V) + y - gy
for x := x0; x < x1; x++ {
mk := atlas.Pix[ay*atlas.W+int(g.U)+x-gx]
if mk == 0 {
continue
}
cov := opacity
if x < cl || x >= ch {
if cov *= r.clipCoverage(x, y); cov == 0 {
continue
}
}
c := px.Color(float32(x)+0.5, float32(y)+0.5, nil)
a := scene.TextCoverage(float32(mk)/255, unpremul(c), text.Contrast, boost, text.GammaRatios)
blend(row[4*x:4*x+4], c, cov*a)
}
}
continue
}
inv, ok := m.Inverse()
if !ok {
continue
}
shape := newShape(box, [4]float32{})
x0, y0, x1, y1 := r.pixelBounds(m.Bounds(box))
for y := y0; y < y1; y++ {
for x := x0; x < x1; x++ {
wx, wy := float32(x)+0.5, float32(y)+0.5
cov := r.clipCoverage(x, y) * transformedCoverage(&shape, m, inv, wx, wy) * opacity
if cov <= 0 {
continue
}
lx, ly := inv.Point(wx, wy)
s := atlasSample(atlas, float32(g.U)+lx-box.X, float32(g.V)+ly-box.Y, int(g.U), int(g.V), int(g.UW), int(g.VH))
c := px.Color(lx, ly, nil)
a := scene.TextCoverage(s[0], unpremul(c), text.Contrast, boost, text.GammaRatios)
blend(r.dst.Pix[y*r.dst.Stride+4*x:][:4], c, cov*a)
}
}
}
}
+34
View File
@@ -0,0 +1,34 @@
package raster
import "github.com/egoist/mygo/internal/scene"
// Effects for tests: lensEffect shows its backdrop, sampled further in
// near its edge by Params[0][0] pixels a pixel, mixed with the color
// Params[1] by its alpha; tintEffect paints Params[1] alone.
var (
lensEffect = &scene.Effect{Name: "lens", Backdrop: true, Pixels: func() scene.EffectPixels { return &testPixels{} }}
tintEffect = &scene.Effect{Name: "tint", Pixels: func() scene.EffectPixels { return &testPixels{} }}
)
type testPixels struct {
op *scene.EffectOp
rect scene.Rect
radii [4]float32
}
func (t *testPixels) Begin(op *scene.EffectOp, rect scene.Rect, radii [4]float32) {
t.op, t.rect, t.radii = op, rect, radii
}
func (t *testPixels) Color(x, y float32, b *scene.BackdropImage) [4]float32 {
tint := t.op.Params[1]
if b == nil {
return [4]float32{tint[0] * tint[3], tint[1] * tint[3], tint[2] * tint[3], tint[3]}
}
d := max(8+scene.SDRoundRect(t.rect, t.radii, x, y), 0) * t.op.Params[0][0]
c := b.Sample(x+d, y)
for i := range c {
c[i] += (tint[i] - c[i]) * tint[3]
}
return [4]float32{c[0], c[1], c[2], 1}
}
+54
View File
@@ -0,0 +1,54 @@
package raster
import "github.com/egoist/mygo/internal/scene"
// imagePixels draws an unscaled image on whole pixels without bilinear
// sampling: every sample is exactly one texel. Clips and opacity still
// apply, and translucent pixels use the same blend as sampled images.
func (r *renderer) imagePixels(op *scene.Op, opacity float32) bool {
img, src, dst := op.Image, op.Src, op.Rect
if img.Surface != nil || op.Grayscale || op.Pixelated || op.Color != (scene.Color{}) ||
op.Radii != ([4]float32{}) || src.W != dst.W || src.H != dst.H ||
src.W <= 0 || src.H <= 0 || src.X < 0 || src.Y < 0 ||
src.X+src.W > float32(img.W) || src.Y+src.H > float32(img.H) || len(img.Pix) < 4*img.W*img.H {
return false
}
// Keep pixel centres exactly representable through the sampled path's
// float32 subtractions and additions too. Very large coordinates keep
// that path's rounding rather than changing it to integer arithmetic.
whole := func(v float32) bool { return v > -(1<<22) && v < 1<<22 && v == float32(int(v)) }
if !whole(dst.X) || !whole(dst.Y) || !whole(dst.W) || !whole(dst.H) ||
!whole(src.X) || !whole(src.Y) || !whole(src.X+src.W) || !whole(src.Y+src.H) {
return false
}
x0, y0, x1, y1 := r.pixelBounds(dst)
if x0 >= x1 || y0 >= y1 {
return true
}
dx, dy := int(src.X)-int(dst.X), int(src.Y)-int(dst.Y)
for y := y0; y < y1; y++ {
from := img.Pix[4*((y+dy)*img.W+x0+dx) : 4*((y+dy)*img.W+x1+dx)]
to := r.dst.Pix[y*r.dst.Stride+4*x0 : y*r.dst.Stride+4*x1]
cl, ch := r.clipSolid(y)
for i := 0; i < len(from); i += 4 {
p := from[i : i+4]
if p[3] == 0 {
continue
}
cov := opacity
if x := x0 + i/4; x < cl || x >= ch {
cov *= r.clipCoverage(x, y)
}
if cov <= 0 {
continue
}
q := to[i : i+4]
if p[3] == 255 && cov == 1 {
q[0], q[1], q[2], q[3] = p[2], p[1], p[0], 255
} else {
blend(q, [4]float32{float32(p[0]) / 255, float32(p[1]) / 255, float32(p[2]) / 255, float32(p[3]) / 255}, cov)
}
}
}
return true
}
+145
View File
@@ -0,0 +1,145 @@
package raster
import (
"bytes"
"fmt"
"image"
"testing"
"github.com/egoist/mygo/internal/scene"
)
func imagePixelsFixture(w, h int) *scene.Image {
pixels := make([]byte, 4*w*h)
for i := 0; i < w*h; i++ {
a := []int{0, 63, 128, 255}[i%4]
pixels[4*i], pixels[4*i+1], pixels[4*i+2], pixels[4*i+3] = byte(i*13%(a+1)), byte(i*7%(a+1)), byte(i*23%(a+1)), byte(a)
}
return scene.NewImageRGBA(w, h, pixels)
}
// At 1:1, FilterPixelated and bilinear filtering both sample pixel centres.
// Pixelated deliberately stays on the general path, giving these cases a
// reference that still samples and computes coverage for every pixel.
func TestImagePixelsMatchSampling(t *testing.T) {
img := imagePixelsFixture(23, 17)
clips := [][]scene.Op{
nil,
{{Kind: scene.OpPushClip, Rect: scene.Rect{X: 3.25, Y: 2.75, W: 19.5, H: 16.5}}},
{{Kind: scene.OpPushClip, Rect: scene.Rect{X: 2, Y: 1, W: 22, H: 20}, Radii: scene.Uniform(6), Continuous: true},
{Kind: scene.OpPushClip, Rect: scene.Rect{X: 4.5, Y: 3.25, W: 15, H: 14}, Radii: scene.Uniform(3)}},
{{Kind: scene.OpPushClip, Rect: scene.Rect{W: 21, H: 18}, Transform: scene.Translation(7, 2).Mul(scene.Rotation(12))}},
{{Kind: scene.OpPushClip, Rect: scene.Rect{W: 30, H: 24}, Color: scene.Color{A: 255}, Color2: scene.Color{}, Paint: scene.PaintLinear, Gradient: [4]float32{0, 0, 30, 24}}},
}
for clip, ops := range clips {
for _, opacity := range []float32{0, .15, .5, 1, 1.25} {
for _, origin := range [][2]float32{{0, 0}, {5, 4}, {-5, -3}, {28, 20}} {
t.Run(fmt.Sprintf("clip=%d/opacity=%g/origin=%v", clip, opacity, origin), func(t *testing.T) {
s := &scene.Scene{Width: 32, Height: 26, Clear: scene.Color{R: 47, G: 90, B: 130, A: 170}}
s.Ops = append(s.Ops, ops...)
idx := len(s.Ops)
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpImage, Rect: scene.Rect{X: origin[0], Y: origin[1], W: 17, H: 12},
Src: scene.Rect{X: 3, Y: 2, W: 17, H: 12}, Image: img, Opacity: opacity})
for range ops {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
}
got, want := NewImage(s.Width, s.Height), NewImage(s.Width, s.Height)
Render(got, s)
s.Ops[idx].Pixelated = true
Render(want, s)
if !bytes.Equal(got.Pix, want.Pix) {
for i := range got.Pix {
if got.Pix[i] != want.Pix[i] {
t.Fatalf("byte %d: got %d, sampled %d", i, got.Pix[i], want.Pix[i])
}
}
}
})
}
}
}
}
func TestImagePixelsRejectsFilteredCases(t *testing.T) {
img := imagePixelsFixture(23, 17)
base := scene.Op{Kind: scene.OpImage, Image: img, Rect: scene.Rect{W: 20, H: 12}, Src: scene.Rect{W: 20, H: 12}}
for name, change := range map[string]func(*scene.Op){
"scaled": func(op *scene.Op) { op.Rect.W = 21 },
"fractional": func(op *scene.Op) { op.Rect.X = .25 },
"source": func(op *scene.Op) { op.Src.X = .5 },
"extent": func(op *scene.Op) { op.Rect.W, op.Src.W = 19.5, 19.5 },
"flipped": func(op *scene.Op) { op.Src.X, op.Src.W = 20, -20 },
"out-of-range": func(op *scene.Op) { op.Src.Y = 10 },
"tinted": func(op *scene.Op) { op.Color = scene.Color{R: 160, A: 255} },
"gray": func(op *scene.Op) { op.Grayscale = true },
"pixelated": func(op *scene.Op) { op.Pixelated = true },
"rounded": func(op *scene.Op) { op.Radii = scene.Uniform(4) },
"large": func(op *scene.Op) { op.Rect.X = 1 << 24 },
"surface": func(op *scene.Op) { copy := *img; copy.Surface = &scene.Surface{}; op.Image = &copy },
"no-pixels": func(op *scene.Op) { copy := *img; copy.Pix = nil; op.Image = &copy },
} {
t.Run(name, func(t *testing.T) {
op := base
change(&op)
var r renderer
if r.imagePixels(&op, 1) {
t.Fatal("filtered image took the direct pixel path")
}
})
}
}
func TestImagePixelsRestoreAndDamage(t *testing.T) {
img := imagePixelsFixture(23, 17)
pix := bytes.Clone(img.Pix)
img.Restore = func() []byte { return bytes.Clone(pix) }
img.Pix = nil
s := &scene.Scene{Width: 80, Height: 48, Ops: []scene.Op{{Kind: scene.OpImage, Image: img,
Rect: scene.Rect{X: 3, Y: 5, W: 23, H: 17}, Src: scene.Rect{W: 23, H: 17}}}}
var r Renderer
defer r.Release()
r.Render(s)
if len(img.Pix) != len(pix) {
t.Fatal("image pixels were not restored")
}
s.Ops[0].Rect.X++
r.Render(s)
want := NewImage(s.Width, s.Height)
s.Ops[0].Pixelated = true
Render(want, s)
if !bytes.Equal(r.Image.Pix, want.Pix) {
t.Fatal("incremental image differs from a sampled frame")
}
}
func BenchmarkImagePixels(b *testing.B) {
for _, kind := range []string{"opaque", "translucent", "sparse", "scaled"} {
b.Run(kind, func(b *testing.B) {
const w, h = 1024, 128
img := imagePixelsFixture(w, h)
for i := 0; i < len(img.Pix); i += 4 {
switch kind {
case "opaque":
img.Pix[i+3] = 255
case "sparse":
if i/4%32 != 0 {
clear(img.Pix[i : i+4])
} else {
img.Pix[i+3] = 255
}
}
}
op := scene.Op{Kind: scene.OpImage, Image: img, Rect: scene.Rect{W: w, H: h}, Src: scene.Rect{W: w, H: h}}
if kind == "scaled" {
op.Rect.W = w - .5
}
dst := NewImage(w, h)
r := renderer{dst: dst, area: image.Rect(0, 0, w, h)}
r.updateBounds()
b.ReportAllocs()
for b.Loop() {
r.image(&op)
}
})
}
}
+103
View File
@@ -0,0 +1,103 @@
package raster
import (
"image"
"math"
"sync/atomic"
"github.com/egoist/mygo/internal/scene"
)
// instancer gives each quad of the effects of a scene that paint quads
// (scene.EffectOp.Instances) an effect op of its own, reusing its memory
// from scene to scene.
type instancer struct {
s scene.Scene
ops []scene.Op
effects []scene.EffectOp
bounds []image.Rectangle
}
// split is instancer.split once EnableInstances was called.
var split atomic.Pointer[func(in *instancer, s *scene.Scene, bounds []image.Rectangle) (*scene.Scene, []image.Rectangle)]
// EnableInstances makes renderers draw the effects that paint quads
// (scene.EffectOp.Instances), which they leave out before. Package ui calls
// it as it paints one (Painter.ShaderInstances), on any goroutine: apps
// that never do carry none of the code.
func EnableInstances() {
if split.Load() == nil {
f := (*instancer).split
split.CompareAndSwap(nil, &f)
}
}
// Split is split once EnableInstances was called, and s and bounds before.
func (in *instancer) Split(s *scene.Scene, bounds []image.Rectangle) (*scene.Scene, []image.Rectangle) {
if f := split.Load(); f != nil {
return (*f)(in, s, bounds)
}
return s, bounds
}
// split returns s and bounds, where each op of s draws, or, when an effect
// of s paints quads, copies of them with an effect op for each quad in
// its place, holding it alone (scene.EffectOp.Instance), with its bounds:
// the CPU renderer readies an effect for each op it draws (EffectPixels),
// so it draws each quad as a shader drawing it alone would. Quads beyond
// the op's bounds are left out. The copies hold until the next split.
func (in *instancer) split(s *scene.Scene, bounds []image.Rectangle) (*scene.Scene, []image.Rectangle) {
first := -1
for i := range s.Ops {
if instanced(s, &s.Ops[i]) {
first = i
break
}
}
if first < 0 {
return s, bounds
}
in.ops = append(in.ops[:0], s.Ops[:first]...)
in.bounds = append(in.bounds[:0], bounds[:first]...)
in.effects = append(in.effects[:0], s.Effects...)
for i := first; i < len(s.Ops); i++ {
op := s.Ops[i]
if !instanced(s, &op) {
in.ops, in.bounds = append(in.ops, op), append(in.bounds, bounds[i])
continue
}
fx := s.Effects[op.Start]
n := int(fx.InstanceWords)
for k := range fx.InstanceCount() {
quad, _ := fx.InstanceRect(k)
b := bounds[i].Intersect(quadBounds(op.Transform, quad))
if quad.Empty() || b.Empty() {
continue
}
one := fx
one.Instances = fx.Instances[k*n : (k+1)*n : (k+1)*n]
one.Instance = fx.Instance + int32(k)
q := op
q.Rect, q.Start = quad, int32(len(in.effects))
in.effects = append(in.effects, one)
in.ops, in.bounds = append(in.ops, q), append(in.bounds, b)
}
}
in.s = *s
in.s.Ops, in.s.Effects = in.ops, in.effects
return &in.s, in.bounds
}
// instanced reports whether op of s is an effect painting quads.
func instanced(s *scene.Scene, op *scene.Op) bool {
return op.Kind == scene.OpEffect && op.Start >= 0 && int(op.Start) < len(s.Effects) && s.Effects[op.Start].InstanceCount() > 0
}
// quadBounds returns the pixels a quad under m may draw, with a few to
// spare for antialiasing, as the bounds of ops have.
func quadBounds(m scene.Affine, quad scene.Rect) image.Rectangle {
r := m.Bounds(quad)
const spare = 4
return image.Rect(int(math.Floor(float64(r.X)))-spare, int(math.Floor(float64(r.Y)))-spare,
int(math.Ceil(float64(r.X+r.W)))+spare, int(math.Ceil(float64(r.Y+r.H)))+spare)
}
+25
View File
@@ -0,0 +1,25 @@
package raster
import (
"image"
"github.com/egoist/mygo/internal/scene"
)
// Layer draws scenes over what an image holds already, one after another,
// where Render draws a scene over its clear color: a layer that takes
// what it draws in parts, as the paths a frame's mask atlas has no room
// for, each part a scene of the masks of an atlas that the next one
// reuses. It keeps the memory it draws with from one part to the next.
type Layer struct {
d drawer
diff scene.Differ
}
// Over draws s within area over what dst, s.Width×s.Height, holds.
func (l *Layer) Over(dst *Image, s *scene.Scene, area image.Rectangle) {
l.diff.Reach = 1
l.diff.Diff(s)
l.d.over = true
l.d.draw(dst, s, area, l.diff.Bounds())
}
+66
View File
@@ -0,0 +1,66 @@
package raster
import (
"bytes"
"image"
"testing"
"github.com/egoist/mygo/internal/scene"
)
// TestLayerDrawsOverWhatItHolds draws the ops of a scene, translucent
// fills and masks, in two parts with Layer.Over, the second over the
// first, as a layer of paths draws an atlas of masks after another: the
// pixels are those of the scene drawn whole, and Over leaves what lies
// outside the area it draws.
func TestLayerDrawsOverWhatItHolds(t *testing.T) {
a := scene.NewAtlas(1, 64, 64)
disc := make([]byte, 20*20)
for y := range 20 {
for x := range 20 {
if dx, dy := x-10, y-10; dx*dx+dy*dy < 81 {
disc[y*20+x] = 200
}
}
}
x, y, _ := a.AllocTransient(20, 20)
a.Put(x, y, 20, 20, disc, 20)
s := &scene.Scene{Width: 80, Height: 60, MaskAtlas: a}
s.Glyphs = []scene.Glyph{
{X: 10, Y: 10, W: 20, H: 20, U: uint16(x), V: uint16(y), UW: 20, VH: 20, Color: scene.Color{R: 20, G: 60, B: 230, A: 200}},
{X: 18, Y: 14, W: 20, H: 20, U: uint16(x), V: uint16(y), UW: 20, VH: 20, Color: scene.Color{R: 230, G: 40, B: 20, A: 160}},
}
s.Ops = []scene.Op{
{Kind: scene.OpFill, Rect: scene.Rect{X: 5, Y: 5, W: 50, H: 30}, Color: scene.Color{R: 40, G: 200, B: 60, A: 120}},
{Kind: scene.OpGlyphs, Start: 0, End: 1},
{Kind: scene.OpGlyphs, Start: 1, End: 2},
}
whole := NewImage(80, 60)
Render(whole, s)
parts := NewImage(80, 60)
for i := range parts.Pix {
parts.Pix[i] = 7 // what Over must leave outside its area
}
area := image.Rect(0, 0, 60, 40)
for y := area.Min.Y; y < area.Max.Y; y++ {
clear(parts.Pix[y*parts.Stride : y*parts.Stride+4*area.Max.X])
}
ops := s.Ops
var l Layer
for _, part := range [][]scene.Op{ops[:2], ops[2:]} {
s.Ops = part
l.Over(parts, s, area)
}
for y := range 60 {
for x := range 80 {
i := y*parts.Stride + 4*x
want := whole.Pix[i : i+4]
if !image.Pt(x, y).In(area) {
want = []byte{7, 7, 7, 7}
}
if got := parts.Pix[i : i+4]; !bytes.Equal(got, want) {
t.Fatalf("(%d, %d) is %v, not %v", x, y, got, want)
}
}
}
}
+185
View File
@@ -0,0 +1,185 @@
package raster
import (
"bytes"
"image"
"math/rand/v2"
"testing"
"github.com/egoist/mygo/internal/scene"
)
// A clip masked by a gradient lets through, at each pixel, the alpha of
// the gradient there: all of it where the gradient is opaque, none where
// it is transparent, half halfway, of everything it clips; outside its
// rectangle, nothing.
func TestClipMaskedByGradient(t *testing.T) {
white, red := scene.Color{R: 255, G: 255, B: 255, A: 255}, scene.Color{R: 255, A: 255}
black := scene.Color{A: 255}
for _, c := range []struct {
name string
clip scene.Op
}{
{"linear", scene.Op{Paint: scene.PaintLinear, Color: black, Gradient: [4]float32{20, 0, 120, 0}}},
{"linear stops", scene.Op{Paint: scene.PaintLinearStops, Gradient: [4]float32{20, 0, 120, 0}, Stops: [2]int32{0, 2}}},
{"linear stops, Oklab", scene.Op{Paint: scene.PaintLinearStopsOklab, Gradient: [4]float32{20, 0, 120, 0}, Stops: [2]int32{0, 2}}},
} {
s := &scene.Scene{Width: 140, Height: 40, Clear: white,
Stops: []scene.Stop{{Color: black, At: 0}, {Color: scene.Color{}, At: 1}}}
clip := c.clip
clip.Kind, clip.Rect = scene.OpPushClip, scene.Rect{X: 10, Y: 10, W: 120, H: 20}
s.Ops = []scene.Op{clip,
{Kind: scene.OpFill, Rect: scene.Rect{W: 140, H: 40}, Color: red},
{Kind: scene.OpPopClip}}
dst := NewImage(s.Width, s.Height)
Render(dst, s)
writePNG(t, "gradient-mask", dst)
for _, w := range []struct {
x, y int
g byte // how much green and blue are left of the white
}{
{5, 20, 255}, {12, 20, 0}, {19, 20, 0}, {69, 20, 127}, {119, 20, 254}, {125, 20, 255}, {69, 5, 255}, {69, 35, 255},
} {
if p := pixel(dst, w.x, w.y); p[0] != 255 || !near(p[1], w.g) || p[1] != p[2] {
t.Errorf("%s: pixel (%d, %d) is %v, want green and blue %d", c.name, w.x, w.y, p, w.g)
}
}
}
}
// A clip masked by an image, as a path's coverage, lets through the
// image's alpha, bilinearly sampled where a transform maps it, and nothing
// outside the image.
func TestClipMaskedByImage(t *testing.T) {
const n = 8
pix := make([]byte, 4*n*n)
for y := range n {
for x := range n {
if x >= 2 && x < 6 && y >= 2 && y < 6 {
pix[4*(y*n+x)+3] = 255
}
}
}
img := scene.NewImageRGBA(n, n, pix)
s := &scene.Scene{Width: 40, Height: 40, Clear: scene.Color{}}
s.Ops = []scene.Op{
{Kind: scene.OpPushClip, Rect: scene.Rect{X: 10, Y: 10, W: n, H: n}, Image: img, Src: scene.Rect{W: n, H: n}},
{Kind: scene.OpFill, Rect: scene.Rect{W: 40, H: 40}, Color: scene.Color{B: 255, A: 255}},
{Kind: scene.OpPopClip},
}
dst := NewImage(s.Width, s.Height)
Render(dst, s)
for y := range 40 {
for x := range 40 {
want := byte(0)
if x >= 12 && x < 16 && y >= 12 && y < 16 {
want = 255
}
if p := pixel(dst, x, y); p[3] != want || p[2] != want {
t.Fatalf("pixel (%d, %d) is %v, want blue of alpha %d", x, y, p, want)
}
}
}
// Twice as large: the image's pixels sampled between them.
s.Ops[0].Rect = scene.Rect{X: 10, Y: 10, W: 2 * n, H: 2 * n}
Render(dst, s)
if p := pixel(dst, 19, 19); p[3] != 255 {
t.Errorf("inside the image's square, scaled: %v", p)
}
if p := pixel(dst, 12, 19); p[3] != 0 {
t.Errorf("outside the image's square, scaled: %v", p)
}
if p := pixel(dst, 13, 19); p[3] == 0 || p[3] == 255 {
t.Errorf("on the edge of the image's square, scaled: %v, want part of it", p)
}
}
// A masked clip only moved by its transform draws as the clip moved by
// hand, its gradient's points with it, as renderers fold it
// (scene.TranslationFolder) or not.
func TestMovedMaskedClip(t *testing.T) {
scene.FoldTranslations()
black := scene.Color{A: 255}
build := func(dx, dy float32, m scene.Affine) *scene.Scene {
s := &scene.Scene{Width: 80, Height: 60, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}}
s.Ops = []scene.Op{
{Kind: scene.OpPushClip, Rect: scene.Rect{X: 10 + dx, Y: 10 + dy, W: 50, H: 30}, Radii: scene.Uniform(6), Paint: scene.PaintLinear,
Color: black, Gradient: [4]float32{10 + dx, 10 + dy, 60 + dx, 40 + dy}, Transform: m},
{Kind: scene.OpFill, Rect: scene.Rect{W: 80, H: 60}, Color: scene.Color{G: 128, A: 255}},
{Kind: scene.OpPopClip},
}
return s
}
want := NewImage(80, 60)
Render(want, build(7, 5, scene.Affine{}))
got := NewImage(80, 60)
Render(got, build(0, 0, scene.Translation(7, 5)))
if !bytes.Equal(got.Pix, want.Pix) {
t.Error("a masked clip translated draws apart from the same clip moved")
}
}
// Where a clip lets a part through, a fill's border goes over the fill
// before both are blended, as the shaders do: the fill does not show
// through an opaque border.
func TestBorderOverFillUnderMask(t *testing.T) {
s := &scene.Scene{Width: 40, Height: 40, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}}
s.Ops = []scene.Op{
{Kind: scene.OpPushClip, Rect: scene.Rect{W: 40, H: 40}, Paint: scene.PaintLinear,
Color: scene.Color{A: 128}, Color2: scene.Color{A: 128}, Gradient: [4]float32{0, 0, 40, 0}},
{Kind: scene.OpFill, Rect: scene.Rect{X: 5, Y: 5, W: 30, H: 30}, Color: scene.Color{R: 255, A: 255},
Border: scene.Uniform(4), BorderColor: scene.Color{B: 255, A: 255}},
{Kind: scene.OpPopClip},
}
dst := NewImage(40, 40)
Render(dst, s)
// Half blue over white, without red.
if p := pixel(dst, 6, 20); p[0] != p[1] || !near(p[1], 127) || p[2] != 255 {
t.Errorf("on the border: %v, want half blue over white", p)
}
}
// ClipMask, which the GPU's renderers sample, lets through what the CPU
// renderer's clips do, masks of gradients and images too, exactly.
func TestClipMaskMatchesMaskedClips(t *testing.T) {
rng := rand.New(rand.NewPCG(3, 1100))
f := func(lo, hi float32) float32 { return lo + rng.Float32()*(hi-lo) }
const n = 16
pix := make([]byte, 4*n*n)
for i := range n * n {
pix[4*i+3] = byte(rng.IntN(256))
}
img := scene.NewImageRGBA(n, n, pix)
stops := []scene.Stop{{Color: scene.Color{A: 255}, At: 0.2}, {Color: scene.Color{A: 40}, At: 0.5}, {Color: scene.Color{}, At: 0.9}}
for i := range 200 {
op := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: f(-10, 60), Y: f(-10, 50), W: f(0, 80), H: f(0, 70)}}
switch rng.IntN(4) {
case 0:
op.Paint, op.Color, op.Color2 = scene.PaintLinear, scene.Color{A: 255}, scene.Color{A: byte(rng.IntN(256))}
op.Gradient = [4]float32{f(0, 100), f(0, 80), f(0, 100), f(0, 80)}
case 1:
op.Paint, op.Stops, op.Gradient = scene.PaintRadial, [2]int32{0, 3}, [4]float32{f(0, 100), f(0, 80), f(1, 60), 0}
case 2:
op.Paint, op.Stops, op.Gradient = scene.PaintConicOklab, [2]int32{0, 3}, [4]float32{f(0, 100), f(0, 80), f(0, 6), 0}
case 3:
op.Image, op.Src = img, scene.Rect{W: n, H: n}
}
switch rng.IntN(3) {
case 0:
op.Transform = scene.Translation(f(-20, 20), f(-20, 20)).Mul(scene.Rotation(f(-30, 30)))
case 1:
op.Transform = scene.Translation(f(-5, 5), f(-5, 5))
}
s := &scene.Scene{Width: 100, Height: 80, Stops: stops, Ops: []scene.Op{op,
{Kind: scene.OpFill, Rect: scene.Rect{W: 100, H: 80}, Color: scene.Color{A: 255}}, {Kind: scene.OpPopClip}}}
dst := NewImage(s.Width, s.Height)
Render(dst, s)
shape := scene.ClipShapeOf(&op, stops)
mask := ClipMask(nil, []scene.ClipShape{shape}, image.Rect(0, 0, s.Width, s.Height))
for k := 3; k < len(mask.Pix); k += 4 {
if d := int(mask.Pix[k]) - int(dst.Pix[k]); d < -1 || d > 1 {
t.Fatalf("case %d, %+v: pixel (%d, %d) is %d in the mask, %d drawn", i, op, k/4%s.Width, k/4/s.Width, mask.Pix[k], dst.Pix[k])
}
}
}
}
+40
View File
@@ -0,0 +1,40 @@
package raster
import (
"testing"
"github.com/egoist/mygo/internal/scene"
)
// A sidebar-sized gradient, mixed in Oklab and in sRGB.
func BenchmarkLinearStopsOklab(b *testing.B) {
s := &scene.Scene{Width: 460, Height: 900}
s.Stops = []scene.Stop{
{Color: scene.Color{R: 30, G: 60, B: 120, A: 255}, At: 0},
{Color: scene.Color{R: 180, G: 60, B: 200, A: 255}, At: 0.5},
{Color: scene.Color{R: 250, G: 200, B: 80, A: 255}, At: 1},
}
s.Ops = []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 460, H: 900}, Paint: scene.PaintLinearStopsOklab,
Gradient: [4]float32{0, 0, 0, 900}, Stops: [2]int32{0, 3}}}
img := NewImage(460, 900)
b.ReportAllocs()
for b.Loop() {
Render(img, s)
}
}
func BenchmarkLinearStopsSRGB(b *testing.B) {
s := &scene.Scene{Width: 460, Height: 900}
s.Stops = []scene.Stop{
{Color: scene.Color{R: 30, G: 60, B: 120, A: 255}, At: 0},
{Color: scene.Color{R: 180, G: 60, B: 200, A: 255}, At: 0.5},
{Color: scene.Color{R: 250, G: 200, B: 80, A: 255}, At: 1},
}
s.Ops = []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 460, H: 900}, Paint: scene.PaintLinearStops,
Gradient: [4]float32{0, 0, 0, 900}, Stops: [2]int32{0, 3}}}
img := NewImage(460, 900)
b.ReportAllocs()
for b.Loop() {
Render(img, s)
}
}
+42
View File
@@ -0,0 +1,42 @@
package raster
import (
"math"
"testing"
)
// Pixelated sampling lands on a pixel's center, but within one pixel of the
// frame from its edge, where it blends with the next across that pixel.
func TestPixelated(t *testing.T) {
for _, scale := range []float32{2, 2.5, 3, 4.75} {
d := 1 / scale
blended := 0
for x := range 40 {
u := (float32(x) + 0.5) * d // the image's coordinate of pixel x
p := pixelated(u, d)
// Within rounding of a pixel's center.
frac := p - 0.5 - float32(math.Round(float64(p-0.5)))
if math.Abs(float64(frac)) < 1e-4 {
// The center of the pixel under u.
if c := float32(math.Floor(float64(u))) + 0.5; math.Abs(float64(p-c)) > 1e-4 {
t.Errorf("scale %v, pixel %d: %v, want %v", scale, x, p, c)
}
continue
}
blended++
// Blending: u is within half a frame pixel of an edge.
edge := float32(math.Round(float64(u)))
if math.Abs(float64(u-edge)) > float64(d)/2+1e-4 {
t.Errorf("scale %v, pixel %d blends %v away from an edge", scale, x, u-edge)
}
}
// Whole scales put no pixel of the frame across an edge.
if whole := scale == float32(math.Trunc(float64(scale))); whole != (blended == 0) {
t.Errorf("scale %v blends %d pixels", scale, blended)
}
}
// Shown smaller, it is bilinear.
if p := pixelated(3.3, 2); p != 3.3 {
t.Errorf("at half the size: %v", p)
}
}
+11
View File
@@ -0,0 +1,11 @@
//go:build !(darwin && !ios) && !(linux && !android) && !windows
package raster
func allocPixels(n int) *pixels { return &pixels{b: make([]byte, n)} }
func (p *pixels) free() {
if p != nil {
p.b = nil
}
}
+33
View File
@@ -0,0 +1,33 @@
//go:build (darwin && !ios) || (linux && !android)
package raster
import (
"runtime"
"syscall"
)
// allocPixels returns n bytes for the image of a Renderer, mapped outside
// the Go heap: the GC would keep about as much again beside a frame it
// holds, and only slowly give back one it freed.
func allocPixels(n int) *pixels {
b, err := syscall.Mmap(-1, 0, n, syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_ANON|syscall.MAP_PRIVATE)
if err != nil {
return &pixels{b: make([]byte, n)}
}
p := &pixels{b: b, mapped: true}
p.cleanup = runtime.AddCleanup(p, func(b []byte) { syscall.Munmap(b) }, b)
return p
}
// free gives the memory back at once.
func (p *pixels) free() {
if p == nil {
return
}
if p.mapped {
p.cleanup.Stop()
syscall.Munmap(p.b)
}
p.b = nil
}
+54
View File
@@ -0,0 +1,54 @@
//go:build windows
package raster
import (
"runtime"
"syscall"
"unsafe"
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll") // a KnownDLL
procVirtualAlloc = kernel32.NewProc("VirtualAlloc")
procVirtualFree = kernel32.NewProc("VirtualFree")
)
const (
memCommit = 0x1000
memReserve = 0x2000
memRelease = 0x8000
pageReadWrite = 0x04
)
// allocPixels returns n bytes for the image of a Renderer, in a
// VirtualAlloc of their own outside the Go heap: as on Unix, the GC would
// keep about as much again beside a frame, and GDI's SetDIBitsToDevice
// draws nothing of a frame whose memory spans two of the heap's 4 MB
// reservations (arenas), which a frame of a few MB nearly always does.
func allocPixels(n int) *pixels {
if n <= 0 {
return &pixels{b: make([]byte, n)}
}
a, _, _ := procVirtualAlloc.Call(0, uintptr(n), memCommit|memReserve, pageReadWrite)
if a == 0 {
return &pixels{b: make([]byte, n)}
}
// Memory outside the Go heap: converted as vet allows.
b := unsafe.Slice((*byte)(*(*unsafe.Pointer)(unsafe.Pointer(&a))), n)
p := &pixels{b: b, mapped: true}
p.cleanup = runtime.AddCleanup(p, func(a uintptr) { procVirtualFree.Call(a, 0, memRelease) }, a)
return p
}
// free gives the memory back at once.
func (p *pixels) free() {
if p == nil {
return
}
if p.mapped {
p.cleanup.Stop()
procVirtualFree.Call(uintptr(unsafe.Pointer(unsafe.SliceData(p.b))), 0, memRelease)
}
p.b = nil
}
+50
View File
@@ -0,0 +1,50 @@
//go:build windows
package raster
import (
"testing"
"unsafe"
)
// memoryBasicInformation is MEMORY_BASIC_INFORMATION.
type memoryBasicInformation struct {
BaseAddress uintptr
AllocationBase uintptr
AllocationProtect uint32
PartitionId uint16
RegionSize uintptr
State uint32
Protect uint32
Type uint32
}
// TestAllocPixelsOneReservation checks that a frame larger than a heap
// arena lies in one VirtualAlloc, which SetDIBitsToDevice needs (#690).
func TestAllocPixelsOneReservation(t *testing.T) {
procVirtualQuery := kernel32.NewProc("VirtualQuery")
for range 3 {
n := 4 * 1264 * 812 * 2 // past 4 MB
p := allocPixels(n)
if !p.mapped || len(p.b) != n {
t.Fatalf("allocPixels(%d): mapped %v, %d bytes", n, p.mapped, len(p.b))
}
for i := range p.b {
p.b[i] = byte(i)
}
base := uintptr(unsafe.Pointer(&p.b[0]))
var mbi memoryBasicInformation
if r, _, err := procVirtualQuery.Call(base, uintptr(unsafe.Pointer(&mbi)), unsafe.Sizeof(mbi)); r == 0 {
t.Fatalf("VirtualQuery: %v", err)
}
if mbi.AllocationBase != base || mbi.RegionSize < uintptr(n) {
t.Fatalf("frame at %#x, %d bytes: region from %#x of %d bytes", base, n, mbi.AllocationBase, mbi.RegionSize)
}
p.free()
if p.b != nil {
t.Fatal("free kept the slice")
}
}
var nilp *pixels
nilp.free()
}
File diff suppressed because it is too large. Load diff
+270
View File
@@ -0,0 +1,270 @@
package raster
import (
"bytes"
"image"
"image/png"
"math"
"os"
"testing"
"github.com/egoist/mygo/internal/scene"
"github.com/egoist/mygo/internal/text"
)
// writePNG saves an image for inspection when MYGO_RASTER_PNG names a
// directory.
func writePNG(t *testing.T, name string, m *Image) {
dir := os.Getenv("MYGO_RASTER_PNG")
if dir == "" {
return
}
img := &image.RGBA{Pix: m.RGBA(), Stride: 4 * m.W, Rect: image.Rect(0, 0, m.W, m.H)}
f, err := os.Create(dir + "/" + name + ".png")
if err != nil {
t.Fatal(err)
}
defer f.Close()
if err := png.Encode(f, img); err != nil {
t.Fatal(err)
}
}
func pixel(m *Image, x, y int) [4]byte {
p := m.Pix[y*m.Stride+4*x:]
return [4]byte{p[2], p[1], p[0], p[3]} // RGBA
}
func near(a, b byte) bool { return a >= b-2 && a <= b+2 || a == b }
func TestRenderShapes(t *testing.T) {
s := &scene.Scene{Width: 200, Height: 120, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}}
s.Ops = append(s.Ops,
scene.Op{Kind: scene.OpShadow, Rect: scene.Rect{X: 20, Y: 24, W: 80, H: 60}, Radii: [4]float32{12, 12, 12, 12}, Color: scene.Color{R: 0, G: 0, B: 0, A: 80}, Blur: 16},
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 20, Y: 20, W: 80, H: 60}, Radii: [4]float32{12, 12, 12, 12}, Color: scene.Color{R: 37, G: 99, B: 235, A: 255}, Border: scene.Uniform(2), BorderColor: scene.Color{R: 0, G: 0, B: 0, A: 255}},
scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 120, Y: 20, W: 60, H: 60}, Radii: [4]float32{30, 30, 30, 30}},
scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: 110, Y: 10, W: 80, H: 80}, Color: scene.Color{R: 220, G: 38, B: 38, A: 255}, Color2: scene.Color{R: 250, G: 204, B: 21, A: 255}, Paint: scene.PaintLinear, Gradient: [4]float32{110, 10, 190, 90}},
scene.Op{Kind: scene.OpPopClip},
)
dst := NewImage(s.Width, s.Height)
Render(dst, s)
writePNG(t, "shapes", dst)
if p := pixel(dst, 60, 50); p != [4]byte{37, 99, 235, 255} {
t.Errorf("inside the rectangle: %v", p)
}
if p := pixel(dst, 20, 50); p[0] > 40 || p[2] > 40 {
t.Errorf("on the border: %v", p)
}
if p := pixel(dst, 21, 21); p[0] < 200 {
t.Errorf("outside the rounded corner: %v", p)
}
if p := pixel(dst, 60, 90); p[0] > 250 || p[0] < 150 {
t.Errorf("in the shadow below: %v", p)
}
if p := pixel(dst, 150, 50); p[3] != 255 || p[0] < 200 {
t.Errorf("in the clipped gradient: %v", p)
}
if p := pixel(dst, 122, 22); p != [4]byte{255, 255, 255, 255} {
t.Errorf("outside the round clip: %v", p)
}
}
func TestRenderText(t *testing.T) {
sys := text.Shared()
l := sys.Layout(text.Params{Text: "Hello, MyGo", Style: text.Style{Size: 20}})
s := &scene.Scene{Width: 160, Height: 40, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}, MaskAtlas: sys.MaskAtlas, ColorAtlas: sys.ColorAtlas}
start := len(s.Glyphs)
for _, g := range l.Lines[0].Glyphs {
gi := sys.Glyph(g.Font, g.ID, 1, 0, 0, false)
if !gi.OK {
continue
}
s.Glyphs = append(s.Glyphs, scene.Glyph{X: 8 + g.X + gi.Left, Y: 4 + g.Y + gi.Top, W: float32(gi.W), H: float32(gi.H), U: gi.X, V: gi.Y, UW: gi.W, VH: gi.H, Color: scene.Color{R: 17, G: 24, B: 39, A: 255}})
}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpGlyphs, Start: int32(start), End: int32(len(s.Glyphs))})
dst := NewImage(s.Width, s.Height)
Render(dst, s)
writePNG(t, "text", dst)
dark := 0
for y := 0; y < dst.H; y++ {
for x := 0; x < dst.W; x++ {
if pixel(dst, x, y)[0] < 100 {
dark++
}
}
}
if dark < 100 {
t.Errorf("%d dark pixels", dark)
}
}
// Opaque mask text must blend as the floating-point path does, including
// over translucent destinations. Rounding differs by at most one byte.
func TestOpaqueMaskCoverage(t *testing.T) {
colors := []scene.Color{{A: 255}, {R: 255, G: 255, B: 255, A: 255}, {R: 37, G: 99, B: 235, A: 255}}
for _, c := range colors {
for m := range 256 {
for dst := range 256 {
p := [4]byte{byte(dst), byte(dst), byte(dst), byte(dst)}
want := p
blend(want[:], c.Premul(1), float32(m)/255)
p[0], p[1], p[2], p[3] = mixMask(c.B, p[0], uint32(m)), mixMask(c.G, p[1], uint32(m)), mixMask(c.R, p[2], uint32(m)), over(byte(m), p[3], uint32(255-m))
for i := range p {
if d := int(p[i]) - int(want[i]); d < -1 || d > 1 {
t.Fatalf("color %+v, mask %d, destination %d: %v, want %v", c, m, dst, p, want)
}
}
}
}
}
}
// BenchmarkRenderFullFrame renders a frame of 1600×1000 pixels with twenty
// tall rounded boxes on the CPU.
func BenchmarkRenderFullFrame(b *testing.B) {
s := &scene.Scene{Width: 1600, Height: 1000, Clear: scene.Color{R: 250, G: 250, B: 250, A: 255}}
for i := 0; i < 20; i++ {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(40 + i*60), Y: 40, W: 50, H: 900}, Radii: [4]float32{8, 8, 8, 8}, Color: scene.Color{R: 37, G: 99, B: 235, A: 255}, Border: scene.Uniform(1), BorderColor: scene.Color{R: 0, G: 0, B: 0, A: 40}})
}
dst := NewImage(s.Width, s.Height)
b.ResetTimer()
for i := 0; i < b.N; i++ {
Render(dst, s)
}
}
// shadowAt is the blurred rounded box of Evan Wallace, computed for every
// pixel with the exact error function: what shadow approximates.
func shadowAt(px, py, hx, hy, sigma, corner float64) float64 {
low, high := py-hy, py+hy
start := math.Min(math.Max(-3*sigma, low), high)
end := math.Min(math.Max(3*sigma, low), high)
step := (end - start) / 4
y := start + step/2
var v float64
for range 4 {
delta := math.Min(hy-corner-math.Abs(py-y), 0)
curved := hx - corner + math.Sqrt(math.Max(0, corner*corner-delta*delta))
k := math.Sqrt(0.5) / sigma
g := math.Exp(-y*y/(2*sigma*sigma)) / (math.Sqrt(2*math.Pi) * sigma)
v += 0.5 * (math.Erf((px+curved)*k) - math.Erf((px-curved)*k)) * g * step
y += step
}
return v
}
func TestShadowShowsOutsideItsCast(t *testing.T) {
r4 := func(r float32) [4]float32 { return [4]float32{r, r, r, r} }
for _, c := range []struct {
shadow, cast scene.Rect
radius, blur float32
clip bool
}{
{scene.Rect{X: 40, Y: 46, W: 120, H: 80}, scene.Rect{X: 40, Y: 40, W: 120, H: 80}, 12, 16, false},
{scene.Rect{X: 63.5, Y: 70.25, W: 50, H: 40}, scene.Rect{X: 60.5, Y: 60.25, W: 56, H: 46}, 20, 9, true},
{scene.Rect{X: 30, Y: 30, W: 200, H: 20}, scene.Rect{X: 100, Y: 20, W: 40, H: 80}, 0, 30, false},
{scene.Rect{X: 52, Y: 54, W: 60, H: 30}, scene.Rect{X: 50, Y: 50, W: 60, H: 30}, 8, 0, true},
} {
render := func(cast scene.Rect) *Image {
s := &scene.Scene{Width: 240, Height: 160, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}}
if c.clip {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 20, Y: 20, W: 110.5, H: 100}, Radii: r4(10)})
}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpShadow, Rect: c.shadow, Radii: r4(c.radius), Color: scene.Color{A: 255},
Blur: c.blur, Cast: cast, CastRadii: r4(c.radius)})
if c.clip {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
}
m := NewImage(s.Width, s.Height)
Render(m, s)
return m
}
plain, cut := render(scene.Rect{}), render(c.cast)
cast := newShape(c.cast, scene.FitRadii(c.cast, r4(c.radius)))
worst := 0.0
for y := range 160 {
for x := range 240 {
out := 1 - float64(coverage(&cast, float32(x)+0.5, float32(y)+0.5))
want := 255 - (255-float64(pixel(plain, x, y)[0]))*out
worst = math.Max(worst, math.Abs(float64(pixel(cut, x, y)[0])-want))
}
}
if worst > 2 {
t.Errorf("%+v: off by %.1f of 255", c, worst)
}
}
}
func TestShadowMatchesItsFormula(t *testing.T) {
for _, c := range []struct {
rect scene.Rect
radius, blur float32
}{
{scene.Rect{X: 40, Y: 30, W: 200, H: 120}, 16, 24},
{scene.Rect{X: 60, Y: 50, W: 120, H: 40}, 4, 6},
{scene.Rect{X: 30.5, Y: 20.25, W: 50, H: 180}, 30, 60},
{scene.Rect{X: 80, Y: 80, W: 10, H: 10}, 0, 40},
} {
s := &scene.Scene{Width: 320, Height: 240, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpShadow, Rect: c.rect, Radii: [4]float32{c.radius, c.radius, c.radius, c.radius},
Color: scene.Color{A: 255}, Blur: c.blur})
m := NewImage(s.Width, s.Height)
Render(m, s)
cx, cy := float64(c.rect.X+c.rect.W/2), float64(c.rect.Y+c.rect.H/2)
corner := float64(min(c.radius, c.rect.W/2, c.rect.H/2))
worst := 0.0
for y := range s.Height {
for x := range s.Width {
v := shadowAt(float64(x)+0.5-cx, float64(y)+0.5-cy, float64(c.rect.W/2), float64(c.rect.H/2), float64(c.blur/2), corner)
want := 255 * (1 - math.Min(v, 1))
got := float64(pixel(m, x, y)[0])
worst = math.Max(worst, math.Abs(got-want))
}
}
if worst > 3 {
t.Errorf("%+v: off by %.1f of 255", c, worst)
}
}
}
// TestThinLineCoverage checks that boxes with square corners cover pixels
// by area, as lines thinner than a pixel need: 0.7 of a pixel inside one
// row, and a fifth and a half across two.
func TestThinLineCoverage(t *testing.T) {
m := NewImage(10, 10)
s := &scene.Scene{Width: 10, Height: 10, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}, Ops: []scene.Op{
{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 2.2, W: 10, H: 0.7}, Color: scene.Color{A: 255}},
{Kind: scene.OpFill, Rect: scene.Rect{X: 0, Y: 5.8, W: 10, H: 0.7}, Color: scene.Color{A: 255}},
}}
Render(m, s)
for _, c := range []struct {
y int
want float64
}{{2, 0.7}, {5, 0.2}, {6, 0.5}} {
if got := 1 - float64(pixel(m, 5, c.y)[0])/255; math.Abs(got-c.want) > 0.01 {
t.Errorf("row %d covered %.3f, want %.3f", c.y, got, c.want)
}
}
}
func TestMovedClipDrawsAsPlaced(t *testing.T) {
// A rounded clip moved by a translation covers what the same clip
// placed there covers, to the pixel.
draw := func(clip scene.Op) *Image {
s := &scene.Scene{Width: 120, Height: 100, Clear: scene.Color{R: 255, G: 255, B: 255, A: 255}, Ops: []scene.Op{
clip,
{Kind: scene.OpFill, Rect: scene.Rect{W: 120, H: 100}, Color: scene.Color{R: 37, G: 99, B: 235, A: 255}},
{Kind: scene.OpPopClip},
}}
dst := NewImage(s.Width, s.Height)
Render(dst, s)
return dst
}
radii := [4]float32{14, 14, 14, 14}
moved := draw(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 10, Y: 10, W: 60, H: 40}, Radii: radii, Transform: scene.Translation(20.25, 15.5), Continuous: true})
placed := draw(scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 30.25, Y: 25.5, W: 60, H: 40}, Radii: radii, Continuous: true})
if !bytes.Equal(moved.Pix, placed.Pix) {
t.Fatal("a moved clip draws otherwise than the same clip placed there")
}
}
+167
View File
@@ -0,0 +1,167 @@
package raster
import (
"bytes"
"fmt"
"image"
"testing"
"github.com/egoist/mygo/internal/scene"
)
// referenceFills computes coverage for every pixel, without solid spans. Its
// scenes contain plain fills and clips, including fractional and curved edges.
func referenceFills(s *scene.Scene) *Image {
dst := NewImage(s.Width, s.Height)
r := renderer{dst: dst, s: s, area: image.Rect(0, 0, s.Width, s.Height)}
r.clear(s.Clear)
r.updateBounds()
for i := range s.Ops {
op := &s.Ops[i]
switch op.Kind {
case scene.OpPushClip:
cs := scene.ClipShapeOf(op, s.Stops)
c := clip{shape: newShape(cs.Rect, scene.Corners(cs.Rect, cs.Radii, cs.Continuous)), spans: -1}
c.round = hasRadii(c.radii)
c.transform = cs.Transform
c.inverse, c.valid = cs.Transform.Inverse()
if c.masked = cs.Masks(); c.masked {
c.mask = newClipMasking(&cs)
}
r.clips = append(r.clips, c)
r.updateBounds()
case scene.OpPopClip:
r.clips = r.clips[:len(r.clips)-1]
r.updateBounds()
case scene.OpFill:
shape := newShape(op.Rect, scene.Corners(op.Rect, op.Radii, op.Continuous))
ink := op.Color.Premul(1)
x0, y0, x1, y1 := r.pixelBounds(op.Rect)
for y := y0; y < y1; y++ {
for x := x0; x < x1; x++ {
cov := coverage(&shape, float32(x)+.5, float32(y)+.5) * r.clipCoverage(x, y)
at := y*dst.Stride + 4*x
blend(dst.Pix[at:at+4], ink, cov)
}
}
}
}
return dst
}
func TestFillSpansMatchPerPixelCoverage(t *testing.T) {
for _, size := range [][2]int{{83, 71}, {520, 600}} {
for _, phase := range []float32{0, .125, .5, .875} {
s := &scene.Scene{Width: size[0], Height: size[1], Clear: scene.Color{R: 19, G: 37, B: 53, A: 127}}
outer := scene.Rect{X: 3 + phase, Y: 5 + phase, W: float32(size[0]) - 7.5, H: float32(size[1]) - 11.25}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: outer})
// Popping one sibling must discard its cached rows before another
// clip at the same depth reuses the scratch space.
for j := range 4 {
inner := scene.Rect{X: 9 - phase, Y: 7 + float32(j)*11 + phase, W: outer.W - 13.25, H: outer.H - 19.5}
clipOp := scene.Op{Kind: scene.OpPushClip, Rect: inner}
if j > 0 {
clipOp.Radii = [4]float32{8, 4, 11, 3}
clipOp.Continuous = j == 2
}
if j == 3 {
clipOp.Transform = scene.Translation(6.25, -3.5).Mul(scene.Rotation(3))
}
s.Ops = append(s.Ops, clipOp)
for k := range 5 {
r := scene.Rect{X: float32(k*13) - .5 + phase, Y: float32(k) + phase, W: 24.5, H: float32(size[1])}
// Opaque ink avoids the existing one-level difference between
// integer span blending and floating-point edge blending.
op := scene.Op{Kind: scene.OpFill, Rect: r, Color: scene.Color{R: byte(37 + 19*k), G: 99, B: 235, A: 255}}
if k == 3 {
op.Radii = [4]float32{3, 2, 1, 4}
}
s.Ops = append(s.Ops, op)
}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
want := referenceFills(s)
var r Renderer
for range 2 {
r.Invalidate()
r.Render(s)
if !bytes.Equal(r.Image.Pix, want.Pix) {
for i, v := range want.Pix {
if r.Image.Pix[i] != v {
t.Fatalf("size %v phase %g, byte %d: got %d, want %d", size, phase, i, r.Image.Pix[i], v)
}
}
}
}
r.Release()
}
}
}
func TestWideClipSpans(t *testing.T) {
for _, radius := range []float32{0, 3e9} {
s := &scene.Scene{Width: 8, Height: 8, Ops: []scene.Op{
{Kind: scene.OpPushClip, Rect: scene.Rect{W: 8e9, H: 8e9}, Radii: [4]float32{radius, radius, radius, radius}},
{Kind: scene.OpFill, Rect: scene.Rect{W: 8, H: 8}, Color: scene.Color{R: 255, A: 255}},
{Kind: scene.OpFill, Rect: scene.Rect{W: 8, H: 8}, Color: scene.Color{R: 255, A: 255}},
{Kind: scene.OpPopClip},
}}
want := referenceFills(s)
got := NewImage(8, 8)
Render(got, s)
if !bytes.Equal(got.Pix, want.Pix) {
t.Fatalf("clip radius %g changed pixels when reused", radius)
}
}
}
// Many small clipped groups must not initialize full-height row caches.
func BenchmarkSmallClipGroups(b *testing.B) {
s := &scene.Scene{Width: 1024, Height: 1024}
for y := 0; y < s.Height; y += 16 {
for x := 0; x < s.Width; x += 16 {
rc := scene.Rect{X: float32(x), Y: float32(y), W: 16, H: 16}
s.Ops = append(s.Ops,
scene.Op{Kind: scene.OpPushClip, Rect: rc},
scene.Op{Kind: scene.OpFill, Rect: rc, Color: scene.Color{R: 37, G: 99, B: 235, A: 255}},
scene.Op{Kind: scene.OpPopClip})
}
}
var r Renderer
defer r.Release()
r.Render(s)
b.ReportAllocs()
for b.Loop() {
r.Invalidate()
r.Render(s)
}
}
func BenchmarkClippedFills(b *testing.B) {
for _, count := range []int{32, 4096} {
for _, kind := range []string{"square", "round", "continuous"} {
b.Run(fmt.Sprintf("%s/%d", kind, count), func(b *testing.B) {
s := &scene.Scene{Width: 1024, Height: 128}
c := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: .25, Y: .5, W: 1023.5, H: 127}}
if kind != "square" {
c.Radii = [4]float32{12, 12, 12, 12}
c.Continuous = kind == "continuous"
}
s.Ops = append(s.Ops, c)
for i := range count {
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{X: float32(i%1024) + .25, W: 2, H: 128}, Color: scene.Color{R: 37, G: 99, B: 235, A: 80}})
}
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
var r Renderer
defer r.Release()
r.Render(s)
b.ReportAllocs()
for b.Loop() {
r.Invalidate()
r.Render(s)
}
})
}
}
}
+259
View File
@@ -0,0 +1,259 @@
package raster
import (
"math"
"testing"
"github.com/egoist/mygo/internal/scene"
)
var (
red = scene.Color{R: 255, A: 255}
green = scene.Color{G: 255, A: 255}
blue = scene.Color{B: 255, A: 255}
)
// at returns the RGBA of pixel (x, y) of a BGRA image.
func at(img *Image, x, y int) [4]byte {
p := img.Pix[y*img.Stride+4*x:][:4]
return [4]byte{p[2], p[1], p[0], p[3]}
}
func nearRGBA(a, b [4]byte, tol int) bool {
for i := range a {
if d := int(a[i]) - int(b[i]); d > tol || d < -tol {
return false
}
}
return true
}
// A conic gradient starts at its angle, clockwise from upwards, and goes
// once round its center: its stops at their fractions of the turn.
func TestConic(t *testing.T) {
s := &scene.Scene{Width: 100, Height: 100}
s.Stops = []scene.Stop{{Color: red, At: 0}, {Color: green, At: 0.25}, {Color: blue, At: 0.5}, {Color: red, At: 1}}
s.Ops = []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 100, H: 100}, Paint: scene.PaintConic,
Gradient: [4]float32{50, 50, 0, 0}, Stops: [2]int32{0, 4}}}
img := NewImage(100, 100)
Render(img, s)
for _, c := range []struct {
x, y int
want [4]byte
}{
{90, 50, [4]byte{0, 255, 0, 255}}, // right: a quarter turn
{50, 90, [4]byte{0, 0, 255, 255}}, // down: half
{10, 50, [4]byte{128, 0, 128, 255}}, // left: halfway from blue to red
{50, 10, [4]byte{255, 0, 0, 255}}, // up, just right of the start
{90, 10, [4]byte{128, 128, 0, 255}}, // up-right: an eighth, halfway to green
} {
if got := at(img, c.x, c.y); !nearRGBA(got, c.want, 6) {
t.Errorf("(%d, %d) = %v, want %v", c.x, c.y, got, c.want)
}
}
// Turned a quarter, green is up.
s.Ops[0].Gradient[2] = -math.Pi / 2
Render(img, s)
if got := at(img, 50, 10); !nearRGBA(got, [4]byte{0, 255, 0, 255}, 6) {
t.Errorf("turned a quarter back, up = %v, want green", got)
}
}
// A radial gradient spreads from its center, its stops at their fractions
// of its radius: its first color at the center, its last past the radius,
// and between them the sRGB mix, or the Oklab one, which is lighter.
func TestRadial(t *testing.T) {
s := &scene.Scene{Width: 100, Height: 100}
s.Stops = []scene.Stop{{Color: red, At: 0}, {Color: blue, At: 1}}
s.Ops = []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 100, H: 100}, Paint: scene.PaintRadial,
Gradient: [4]float32{50, 50, 40, 0}, Stops: [2]int32{0, 2}}}
img := NewImage(100, 100)
Render(img, s)
for _, c := range []struct {
x, y int
want [4]byte
}{
{50, 50, [4]byte{251, 0, 4, 255}}, // the center
{70, 50, [4]byte{125, 0, 130, 255}}, // halfway out, to the right
{50, 29, [4]byte{125, 0, 130, 255}}, // and up: a circle
{95, 50, [4]byte{0, 0, 255, 255}}, // past the radius
{2, 2, [4]byte{0, 0, 255, 255}}, // the corner
} {
if got := at(img, c.x, c.y); !nearRGBA(got, c.want, 4) {
t.Errorf("(%d, %d) = %v, want %v", c.x, c.y, got, c.want)
}
}
// Off center, with the radius as far as the right edge.
s.Ops[0].Gradient = [4]float32{20, 50, 80, 0}
Render(img, s)
if got := at(img, 20, 50); !nearRGBA(got, [4]byte{253, 0, 2, 255}, 4) {
t.Errorf("the center moved left %v, want red", got)
}
if got := at(img, 59, 50); !nearRGBA(got, [4]byte{128, 0, 127, 255}, 4) {
t.Errorf("halfway to the right edge %v, want the mix", got)
}
mid := at(img, 59, 50)
s.Ops[0].Paint = scene.PaintRadialOklab
Render(img, s)
ok := at(img, 59, 50)
if int(ok[0])+int(ok[1])+int(ok[2]) <= int(mid[0])+int(mid[1])+int(mid[2]) {
t.Errorf("the Oklab mix %v is no lighter than the sRGB one %v", ok, mid)
}
if got := at(img, 20, 50); got[0] < 245 || got[1] > 20 || got[2] > 20 || got[3] != 255 {
t.Errorf("the Oklab center %v, want red", got)
}
}
// A linear gradient with stops shows its first color before its first
// stop and its last after its last, and mixes in sRGB, or in Oklab, whose
// middle between red and blue is lighter.
func TestLinearStops(t *testing.T) {
s := &scene.Scene{Width: 100, Height: 10}
s.Stops = []scene.Stop{{Color: red, At: 0.2}, {Color: blue, At: 0.8}}
s.Ops = []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 100, H: 10}, Paint: scene.PaintLinearStops,
Gradient: [4]float32{0, 0, 100, 0}, Stops: [2]int32{0, 2}}}
img := NewImage(100, 10)
Render(img, s)
if got := at(img, 5, 5); got != [4]byte{255, 0, 0, 255} {
t.Errorf("before the first stop %v, want red", got)
}
if got := at(img, 95, 5); got != [4]byte{0, 0, 255, 255} {
t.Errorf("after the last stop %v, want blue", got)
}
mid := at(img, 50, 5)
if !nearRGBA(mid, [4]byte{126, 0, 129, 255}, 3) {
t.Errorf("between the stops %v, want the sRGB mix", mid)
}
s.Ops[0].Paint = scene.PaintLinearStopsOklab
Render(img, s)
ok := at(img, 50, 5)
if int(ok[0])+int(ok[1])+int(ok[2]) <= int(mid[0])+int(mid[1])+int(mid[2]) {
t.Errorf("the Oklab mix %v is no lighter than the sRGB one %v", ok, mid)
}
}
// A fill whose border takes its gradient (BorderPaint) paints the border
// with it, times BorderColor, and its inside with plain Color.
func TestBorderPaint(t *testing.T) {
s := &scene.Scene{Width: 100, Height: 100}
s.Stops = []scene.Stop{{Color: red, At: 0}, {Color: blue, At: 1}}
s.Ops = []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 100, H: 100}, Paint: scene.PaintLinearStops,
Gradient: [4]float32{0, 0, 100, 0}, Stops: [2]int32{0, 2}, Color: green,
Border: scene.Uniform(10), BorderColor: scene.Color{R: 255, G: 255, B: 255, A: 255}, BorderPaint: true}}
img := NewImage(100, 100)
Render(img, s)
if got := at(img, 2, 50); !nearRGBA(got, [4]byte{248, 0, 6, 255}, 3) {
t.Errorf("the border on the left %v, want red", got)
}
if got := at(img, 97, 50); !nearRGBA(got, [4]byte{6, 0, 248, 255}, 3) {
t.Errorf("the border on the right %v, want blue", got)
}
if got := at(img, 50, 50); got != [4]byte{0, 255, 0, 255} {
t.Errorf("the inside %v, want green", got)
}
// Half transparent white halves it.
s.Ops[0].BorderColor.A = 128
s.Ops[0].Color = scene.Color{}
Render(img, s)
if got := at(img, 50, 2); got[3] < 120 || got[3] > 135 {
t.Errorf("the border at half %v, want alpha about 128", got)
}
}
// A blurred image spreads its pixels as a Gaussian of the blur, keeping
// their total, transparent beyond its Src; a blur large enough to be
// averaged first (BackdropOf) spreads as wide.
func TestImageBlur(t *testing.T) {
for _, sigma := range []float32{3, 12} {
const n = 160
src := &scene.Image{W: n, H: n, Pix: make([]byte, 4*n*n)}
// A white square in the middle.
for y := 70; y < 90; y++ {
for x := 70; x < 90; x++ {
copy(src.Pix[4*(y*n+x):], []byte{255, 255, 255, 255})
}
}
s := &scene.Scene{Width: n, Height: n}
s.Ops = []scene.Op{{Kind: scene.OpImage, Rect: scene.Rect{W: n, H: n}, Image: src, Src: scene.Rect{W: n, H: n}, Blur: sigma}}
img := NewImage(n, n)
Render(img, s)
total := 0.0
for y := range n {
for x := range n {
total += float64(at(img, x, y)[3]) / 255
}
}
if total < 400*0.95 || total > 400*1.05 {
t.Errorf("blur %v: alpha in all %.1f, want about 400, the square's", sigma, total)
}
// Across the middle row, the coverage of a square of 20 blurred.
for _, x := range []int{60, 70, 80} {
want := 0.5 * (math.Erf((90-float64(x)-0.5)/(float64(sigma)*math.Sqrt2)) - math.Erf((70-float64(x)-0.5)/(float64(sigma)*math.Sqrt2)))
wantY := 0.5 * (math.Erf(10/(float64(sigma)*math.Sqrt2)) - math.Erf(-10/(float64(sigma)*math.Sqrt2)))
got := float64(at(img, x, 80)[3]) / 255
if math.Abs(got-want*wantY) > 0.06 {
t.Errorf("blur %v: alpha at (%d, 80) %.3f, want %.3f", sigma, x, got, want*wantY)
}
}
if got := at(img, 2, 2); got[3] != 0 {
t.Errorf("blur %v: the corner %v, want transparent", sigma, got)
}
}
}
// The sRGB table that Oklab mixes convert with is toSRGB within the
// rounding of a channel, and nothing else.
func TestSRGBTable(t *testing.T) {
for c := float32(-0.5); c <= 1; c += 1.0 / 100003 {
if got, want := srgb(c), toSRGB(c); math.Abs(float64(got-want))*255 > 0.001 {
t.Fatalf("srgb(%v) = %v, toSRGB %v: %v of 255 off", c, got, want, math.Abs(float64(got-want))*255)
}
}
if got := srgb(2); got != srgbTable[srgbSteps] || got > 1 {
t.Errorf("srgb(2) = %v, want white: %v", got, srgbTable[srgbSteps])
}
if got := srgb(-1); got != -12.92 {
t.Errorf("srgb(-1) = %v, want the linear part", got)
}
}
// An Oklab mix converts through the table, and is what fromOklab gives
// with toSRGB, a channel within 1 of 255: each pixel's center mixes the
// stops at its own fraction of the gradient.
func TestOklabFillMatchesToSRGB(t *testing.T) {
s := &scene.Scene{Width: 256, Height: 8}
s.Stops = []scene.Stop{{Color: scene.Color{R: 255, G: 64, A: 255}, At: 0}, {Color: scene.Color{B: 200, G: 255, A: 255}, At: 1}}
s.Ops = []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 256, H: 8}, Paint: scene.PaintLinearStopsOklab,
Gradient: [4]float32{0, 0, 256, 0}, Stops: [2]int32{0, 2}}}
img := NewImage(256, 8)
Render(img, s)
lab := [][3]float32{oklab(s.Stops[0].Color), oklab(s.Stops[1].Color)}
for x := range 256 {
k := (float32(x) + 0.5) / 256
var l [3]float32
for i := range l {
l[i] = lab[0][i]*(1-k) + lab[1][i]*k
}
want := exactOklab(l)
got := at(img, x, 4)
for ch, name := range []string{"red", "green", "blue"} {
d := int(got[ch]) - int(math.Round(float64(want[ch])*255))
if got[3] != 255 || d > 1 || d < -1 {
t.Errorf("at %d, %s is %d, want %v: %v", x, name, got[ch], want[ch]*255, got)
}
}
}
}
// exactOklab is fromOklab with toSRGB, as it was before the table.
func exactOklab(lab [3]float32) [3]float32 {
l := lab[0] + 0.3963377774*lab[1] + 0.2158037573*lab[2]
m := lab[0] - 0.1055613458*lab[1] - 0.0638541728*lab[2]
s := lab[0] - 0.0894841775*lab[1] - 1.2914855480*lab[2]
l, m, s = l*l*l, m*m*m, s*s*s
return [3]float32{
toSRGB(4.0767416621*l - 3.3077115913*m + 0.2309699292*s),
toSRGB(-1.2684380046*l + 2.6097574011*m - 0.3413193965*s),
toSRGB(-0.0041960863*l - 0.7034186147*m + 1.7076147010*s),
}
}
+79
View File
@@ -0,0 +1,79 @@
package raster
import (
"sync"
"sync/atomic"
)
// A team does a piece of work on several cores: the goroutine asking for
// it, and helpers waiting for work, started the first time they are needed
// and kept, shared by every team. Its parts are taken in turn, as they
// differ in cost. A frame drawn on several cores so allocates nothing, as
// goroutines started for each area did (a closure each, and what they
// shared).
type team struct {
// do does a part of the work as a member, 0 for the goroutine asking:
// set once, as a method value allocates. It must not run a team.
do func(member, part int)
parts int
next atomic.Int32
wg sync.WaitGroup
// shares are what the helpers of a run get, a member each.
shares [maxWorkers]share
}
type share struct {
t *team
member int
}
var (
// helped are the shares of runs, which helpers take.
helped = make(chan *share, maxWorkers)
helpers atomic.Int32
hiring sync.Mutex
)
// run does parts parts of the work on members cores at most.
func (t *team) run(members, parts int) {
members = max(min(members, parts, maxWorkers), 1)
t.parts = parts
t.next.Store(0)
hire(members - 1)
t.wg.Add(members - 1)
for m := 1; m < members; m++ {
t.shares[m] = share{t, m}
helped <- &t.shares[m]
}
t.work(0)
t.wg.Wait()
}
// work does parts until none is left.
func (t *team) work(member int) {
for p := int(t.next.Add(1)) - 1; p < t.parts; p = int(t.next.Add(1)) - 1 {
t.do(member, p)
}
}
// hire starts helpers until there are n.
func hire(n int) {
if int(helpers.Load()) >= n {
return
}
hiring.Lock()
defer hiring.Unlock()
for int(helpers.Load()) < n {
helpers.Add(1)
go help()
}
}
// help does the shares of runs, as long as the program runs.
func help() {
for s := range helped {
s.t.work(s.member)
s.t.wg.Done()
}
}
+306
View File
@@ -0,0 +1,306 @@
package raster
import (
"github.com/egoist/mygo/internal/scene"
"math"
)
// Contains tests the interior of a rounded clip, using the same continuous
// corner geometry as rendering. Hit testing uses the shape's edge, without
// the pixel coverage used to smooth that edge on screen.
func Contains(r scene.Rect, radii [4]float32, continuous bool, x, y float32) bool {
if !r.Contains(x, y) {
return false
}
s := newShape(r, scene.Corners(r, radii, continuous))
if s.continuous {
d, _ := s.contDist(x, y)
return d <= 0
}
return scene.SDRoundRect(r, s.radii, x, y) <= 0
}
// transformedCoverage integrates a shape that m transforms (inv its
// inverse) over a device pixel. Interior pixels take one distance test;
// edges use a grid in device space. What a projective map puts behind the
// viewer covers nothing.
func transformedCoverage(s *shape, m, inv scene.Affine, x, y float32) float32 {
if !inv.Set {
return coverage(s, x, y)
}
lx, ly := inv.Point(x, y)
if m.Perspective() && m.W(lx, ly) <= 0 {
return 0
}
d := scene.SDRoundRect(s.r, s.radii, lx, ly)
if s.continuous {
d, _ = s.contDist(lx, ly)
}
rx, ry := inv.VectorAt(x, y, 0.5, 0.5)
sx, sy := inv.VectorAt(x, y, 0.5, -0.5)
reach := max(abs(rx)+abs(ry), abs(sx)+abs(sy)) * 2
if d < -reach {
return 1
}
if d > reach {
return 0
}
const samples = 4
n := 0
for j := range samples {
for i := range samples {
px, py := inv.Point(x+(float32(i)+0.5)/samples-0.5, y+(float32(j)+0.5)/samples-0.5)
v := scene.SDRoundRect(s.r, s.radii, px, py)
if s.continuous {
v, _ = s.contDist(px, py)
}
if v <= 0 {
n++
}
}
}
return float32(n) / (samples * samples)
}
// transformed inverse maps pixels into the operation's coordinates.
// Identity operations retain the existing span renderer.
func (r *renderer) transformed(op *scene.Op, px scene.EffectPixels, b *scene.BackdropImage) {
inv, ok := op.Transform.Inverse()
inset := op.Kind == scene.OpShadow && op.Inset
if !ok || !inset && op.Rect.Empty() || inset && op.Cast.Empty() {
return
}
// An image whose owner dropped its pixels (Bitmap.ReleasePixels) has
// them made again here, once for the whole operation, as the op reads
// them directly; without them it draws nothing.
var image *scene.Image
if op.Kind == scene.OpImage {
if op.Image == nil || op.Image.W == 0 || op.Image.H == 0 || unflipped(op.Src).Empty() || op.Image.Pixels() == nil {
return
}
image = op.Image
}
radii := scene.Corners(op.Rect, op.Radii, op.Continuous)
outer := newShape(op.Rect, radii)
inner := outer
bw := op.Border
if op.BorderColor.A == 0 {
bw = [4]float32{}
}
hasBorder := scene.HasBorder(bw)
if hasBorder {
inner = newShape(scene.InnerRadii(op.Rect, radii, bw))
}
pt, bp := borderPainter(op, opacityOf(op.Opacity), r.s.Stops)
border := op.BorderColor.Premul(opacityOf(op.Opacity))
box := op.Rect
if inset {
box = op.Cast
} else if op.Kind == scene.OpShadow {
e := 1.5*op.Blur + 1
box = scene.Rect{X: box.X - e, Y: box.Y - e, W: box.W + 2*e, H: box.H + 2*e}
}
box = op.Transform.Bounds(box)
x0, y0, x1, y1 := r.pixelBounds(box)
for y := y0; y < y1; y++ {
for x := x0; x < x1; x++ {
clip := r.clipCoverage(x, y)
if clip <= 0 {
continue
}
wx, wy := float32(x)+0.5, float32(y)+0.5
lx, ly := inv.Point(wx, wy)
if op.Transform.Perspective() && op.Transform.W(lx, ly) <= 0 {
continue // behind the viewer
}
p := r.dst.Pix[y*r.dst.Stride+4*x:][:4]
if inset {
// Inside the box, what the hole, blurred, leaves.
caster := newShape(op.Cast, scene.Corners(op.Cast, op.CastRadii, op.Continuous))
cov := transformedCoverage(&caster, op.Transform, inv, wx, wy)
if !op.Rect.Empty() {
hole := transformedShadowAt(op, &outer, lx, ly)
if op.Blur < 1 {
hole = transformedCoverage(&outer, op.Transform, inv, wx, wy)
}
cov *= 1 - hole
}
blend(p, op.Color.Premul(opacityOf(op.Opacity)), cov*clip)
continue
}
if op.Kind == scene.OpShadow {
cov := transformedShadowAt(op, &outer, lx, ly)
if op.Blur < 1 {
cov = transformedCoverage(&outer, op.Transform, inv, wx, wy)
}
if !op.Cast.Empty() {
caster := newShape(op.Cast, scene.Corners(op.Cast, op.CastRadii, op.Continuous))
cov *= 1 - transformedCoverage(&caster, op.Transform, inv, wx, wy)
}
blend(p, op.Color.Premul(opacityOf(op.Opacity)), cov*clip)
continue
}
cov := transformedCoverage(&outer, op.Transform, inv, wx, wy)
if cov <= 0 {
continue
}
switch op.Kind {
case scene.OpFill:
var fc [4]float32
if pt.visible() {
fc = pt.at(lx, ly)
}
if !hasBorder {
blend(p, fc, cov*clip)
continue
}
ic := float32(0)
if !inner.r.Empty() {
ic = transformedCoverage(&inner, op.Transform, inv, wx, wy)
}
bc := max(cov-ic, 0)
if op.Dashed {
bc *= dash(op.Rect, bw, lx, ly)
}
blendFilled(p, fc, cov, borderAt(bp, border, op.BorderColor, lx, ly), bc, clip)
case scene.OpImage:
if image == nil {
continue
}
// How far a pixel of the frame reaches in the image's,
// as the GPU's fwidth.
sx, sy := op.Src.W/op.Rect.W, op.Src.H/op.Rect.H
ax, ay := inv.VectorAt(wx, wy, 1, 0)
bx, by := inv.VectorAt(wx, wy, 0, 1)
c := sampleOp(op, op.Src.X+(lx-op.Rect.X)*sx, op.Src.Y+(ly-op.Rect.Y)*sy,
(abs32(ax)+abs32(bx))*abs32(sx), (abs32(ay)+abs32(by))*abs32(sy))
blend(p, c, cov*clip*opacityOf(op.Opacity))
case scene.OpEffect:
if px != nil {
blend(p, px.Color(lx, ly, b), cov*clip*opacityOf(op.Opacity))
}
case scene.OpHole:
erase(p, cov*clip*opacityOf(op.Opacity))
}
}
}
}
func opacityOf(v float32) float32 {
if v == 0 {
return 1
}
return v
}
func transformedShadowAt(op *scene.Op, box *shape, x, y float32) float32 {
sigma := op.Blur / 2
if sigma < 0.5 {
return coverage(box, x, y)
}
hx, hy := op.Rect.W/2, op.Rect.H/2
x, y = x-op.Rect.X-hx, y-op.Rect.Y-hy
ext := 3 * sigma
start, end := min(max(-ext, y-hy), y+hy), min(max(ext, y-hy), y+hy)
step := (end - start) / 4
k := float32(math.Sqrt(0.5)) / sigma
corner := max(box.radii[0], box.radii[1], box.radii[2], box.radii[3])
cc := newContCorner(corner, corner, corner, op.Rect.W, op.Rect.H)
var v float32
for i := range 4 {
yy := start + (float32(i)+0.5)*step
half := hx
if box.continuous {
at, _ := cc.inset(hy - abs(y-yy))
half -= at
} else if delta := min(hy-corner-abs(y-yy), 0); delta < 0 {
half = hx - corner + float32(math.Sqrt(float64(max(0, corner*corner-delta*delta))))
}
v += gaussian(yy, sigma) * step * 0.5 * (erf((x+half)*k) - erf((x-half)*k))
}
return v
}
func (r *renderer) transformedGlyphs(op *scene.Op) {
var pt *painter
if op.Paint == scene.PaintLinear || op.Paint == scene.PaintOklab || op.Paint.HasStops() {
p := newPainter(op, opacityOf(op.Opacity), r.s.Stops)
pt = &p
}
for _, g := range r.s.Glyphs[op.Start:op.End] {
m := op.Transform.Mul(g.Transform)
inv, ok := m.Inverse()
if !ok {
continue
}
atlas := r.s.MaskAtlas
if g.Colored || g.Subpixel {
atlas = r.s.ColorAtlas
}
if atlas == nil {
continue
}
box := scene.Rect{X: float32(math.Round(float64(g.X))), Y: float32(math.Round(float64(g.Y))), W: float32(g.UW), H: float32(g.VH)}
shape := newShape(box, [4]float32{})
x0, y0, x1, y1 := r.pixelBounds(m.Bounds(box))
for y := y0; y < y1; y++ {
for x := x0; x < x1; x++ {
wx, wy := float32(x)+0.5, float32(y)+0.5
cov := r.clipCoverage(x, y) * transformedCoverage(&shape, m, inv, wx, wy)
if cov <= 0 {
continue
}
lx, ly := inv.Point(wx, wy)
a := atlasSample(atlas, float32(g.U)+lx-box.X, float32(g.V)+ly-box.Y, int(g.U), int(g.V), int(g.UW), int(g.VH))
tint := g.Color.Premul(1)
if pt != nil {
tint = pt.at(lx, ly)
}
p := r.dst.Pix[y*r.dst.Stride+4*x:][:4]
if g.Colored {
for i := range a {
a[i] *= float32(g.Color.A) / 255
}
blend(p, a, cov)
continue
}
contrast, boost := r.s.Text.Contrast, float32(0)
if g.Thin {
boost = scene.ThinBoost
}
if g.Subpixel {
a[0] = (a[0] + a[1] + a[2]) / 3
contrast = r.s.Text.SubpixelContrast
}
coverage := scene.TextCoverage(a[0], unpremul(tint), contrast, boost, r.s.Text.GammaRatios)
blend(p, tint, cov*coverage)
}
}
}
}
func atlasSample(a *scene.Atlas, u, v float32, ax, ay, w, h int) [4]float32 {
u, v = u-0.5, v-0.5
x, y := int(math.Floor(float64(u))), int(math.Floor(float64(v)))
tx, ty := u-float32(x), v-float32(y)
var c [4]float32
for j := range 2 {
for i := range 2 {
sx, sy := min(max(x+i, ax), ax+w-1), min(max(y+j, ay), ay+h-1)
weight := (1 - tx) * (1 - ty)
if i == 1 {
weight = tx * (1 - ty)
}
if j == 1 {
weight = (1 - tx) * ty
if i == 1 {
weight = tx * ty
}
}
for k := range a.BPP {
c[k] += float32(a.Pix[(sy*a.W+sx)*a.BPP+k]) / 255 * weight
}
}
}
return c
}
+80
View File
@@ -0,0 +1,80 @@
package raster
import (
"bytes"
"github.com/egoist/mygo/internal/scene"
"testing"
)
func TestTransformedSceneDamageAndNestedClips(t *testing.T) {
s := &scene.Scene{Width: 150, Height: 100}
m := scene.Translation(70, 20).Mul(scene.Rotation(90))
s.Ops = []scene.Op{
{Kind: scene.OpPushClip, Rect: scene.Rect{W: 60, H: 40}, Transform: m},
{Kind: scene.OpPushClip, Rect: scene.Rect{X: 5, Y: 5, W: 30, H: 20}, Transform: m, Radii: [4]float32{4, 4, 4, 4}},
{Kind: scene.OpFill, Rect: scene.Rect{W: 100, H: 100}, Color: scene.Color{R: 255, A: 255}, Transform: m},
{Kind: scene.OpPopClip}, {Kind: scene.OpPopClip},
}
var r Renderer
defer r.Release()
r.Render(s)
p := r.Image.Pix[35*r.Image.Stride+4*55:][:4]
if p[2] != 255 || p[3] != 255 {
t.Fatalf("transformed clip interior: %v", p)
}
p = r.Image.Pix[30*r.Image.Stride+4*35:][:4]
if p[3] != 0 {
t.Fatal("paint escaped rotated clips")
}
if damage := r.Render(s); len(damage) != 0 {
t.Fatalf("unchanged scene damaged %v", damage)
}
for i := range s.Ops {
s.Ops[i].Transform = scene.Translation(20, 0).Mul(s.Ops[i].Transform)
}
r.Render(s)
want := NewImage(s.Width, s.Height)
Render(want, s)
if !bytes.Equal(r.Image.Pix, want.Pix) {
t.Fatal("incremental transformed drawing differs from full drawing")
}
}
func TestTransformedThinBorderGradientAndImage(t *testing.T) {
s := &scene.Scene{Width: 100, Height: 100}
s.Ops = []scene.Op{{Kind: scene.OpFill, Rect: scene.Rect{W: 10, H: 10}, Color: scene.Color{R: 255, A: 255}, Color2: scene.Color{B: 255, A: 255}, Paint: scene.PaintLinear, Gradient: [4]float32{0, 0, 10, 0}, Border: scene.Uniform(1), BorderColor: scene.Color{G: 255, A: 255}, Transform: scene.Translation(20, 20).Mul(scene.Scaling(3, 2))}}
m := NewImage(100, 100)
Render(m, s)
at := func(x, y int) []byte { return m.Pix[y*m.Stride+4*x:][:4] }
if at(21, 30)[1] != 255 {
t.Fatalf("scaled border: %v", at(21, 30))
}
if p := at(35, 30); p[0] < 100 || p[2] < 100 || p[1] != 0 {
t.Fatalf("gradient not sampled locally: %v", p)
}
img := scene.NewImageRGBA(2, 1, []byte{255, 0, 0, 255, 0, 0, 255, 255})
s.Ops = []scene.Op{{Kind: scene.OpImage, Rect: scene.Rect{W: 20, H: 10}, Src: scene.Rect{W: 2, H: 1}, Image: img, Transform: scene.Translation(50, 20).Mul(scene.Rotation(90))}}
Render(m, s)
if at(45, 21)[2] < 240 || at(45, 38)[0] < 240 {
t.Fatalf("rotated image colors: %v %v", at(45, 21), at(45, 38))
}
}
// TestTransformedImageDrawsReleasedPixels checks that an image whose owner
// dropped its pixels (Bitmap.ReleasePixels) still draws with a transform:
// the op reads Pix, which the renderer must make again, as it does for an
// image drawn without one.
func TestTransformedImageDrawsReleasedPixels(t *testing.T) {
s := &scene.Scene{Width: 100, Height: 100}
img := scene.NewImageRGBA(2, 1, []byte{255, 0, 0, 255, 0, 0, 255, 255})
img.Restore = func() []byte { return []byte{255, 0, 0, 255, 0, 0, 255, 255} }
img.Dropped = func() { img.Pix = nil }
img.Dropped()
s.Ops = []scene.Op{{Kind: scene.OpImage, Rect: scene.Rect{W: 20, H: 10}, Src: scene.Rect{W: 2, H: 1}, Image: img, Transform: scene.Translation(50, 20).Mul(scene.Rotation(90))}}
m := NewImage(100, 100)
Render(m, s)
at := func(x, y int) []byte { return m.Pix[y*m.Stride+4*x:][:4] }
if at(45, 21)[2] < 240 || at(45, 38)[0] < 240 {
t.Fatalf("rotated image colors: %v %v", at(45, 21), at(45, 38))
}
}