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:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
@@ -0,0 +1,107 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Fractional viewports can remove whole card corners without a mask, while overlapping antialiasing must keep its original pixel coverage.
|
||||
func TestReducedClipCoverageMatchesCPU(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
hwnd, err := newHiddenWindow(256, 224)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer destroyWindow(hwnd)
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
t.Skip("Direct3D 11 unavailable:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for _, name := range []string{"lyrics", "left", "top", "right", "bottom", "asymmetric", "opaque-rounded-parent", "duplicate-fractional", "near-fractional", "outside-fractional", "cuts-corner", "duplicate-rounded", "continuous-card", "continuous-cut", "asymmetric-midpoint"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
card := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 20, Y: 20, W: 200, H: 160}, Radii: [4]float32{10, 10, 10, 10}}
|
||||
hard := scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{W: 256, H: 224}}
|
||||
wantMask := false
|
||||
switch name {
|
||||
case "continuous-card":
|
||||
card.Continuous, wantMask = true, true
|
||||
case "lyrics":
|
||||
// The measured opening card and lyrics viewport, scaled by 1/8.
|
||||
card.Rect, card.Radii = scene.Rect{X: 26.25, Y: 73.25, W: 175.875, H: 118.125}, [4]float32{0.8283625, 0.8283625, 0.8283625, 0.8283625}
|
||||
hard.Rect = scene.Rect{X: 120.25, Y: 27.189285, W: 153.5, H: 159.25}
|
||||
case "left":
|
||||
hard.Rect.X, hard.Rect.W = 50.25, 200
|
||||
case "top":
|
||||
hard.Rect.Y, hard.Rect.H = 50.25, 170
|
||||
case "right":
|
||||
hard.Rect.W = 180.25
|
||||
case "bottom":
|
||||
hard.Rect.H = 140.25
|
||||
case "asymmetric":
|
||||
card.Radii, hard.Rect.X = [4]float32{8, 12, 16, 20}, 70.25
|
||||
case "opaque-rounded-parent":
|
||||
card.Rect, card.Radii = scene.Rect{W: 256, H: 224}, [4]float32{10, 10, 10, 10}
|
||||
hard.Rect, hard.Radii = scene.Rect{X: 50.25, Y: 50.25, W: 150, H: 100}, [4]float32{8, 8, 8, 8}
|
||||
case "duplicate-fractional", "near-fractional", "outside-fractional":
|
||||
card.Rect.X, hard.Rect.X, wantMask = 20.25, 20.25, true
|
||||
if name == "near-fractional" {
|
||||
hard.Rect.X = 20.5
|
||||
} else if name == "outside-fractional" {
|
||||
hard.Rect.X = 20.125
|
||||
}
|
||||
case "cuts-corner":
|
||||
hard.Rect.X, wantMask = 25.25, true
|
||||
case "duplicate-rounded":
|
||||
hard, wantMask = card, true
|
||||
case "continuous-cut":
|
||||
card.Continuous, hard.Rect.X, wantMask = true, 70.25, true
|
||||
case "asymmetric-midpoint":
|
||||
card.Radii, hard.Rect.W, wantMask = [4]float32{70, 0, 0, 0}, 140.25, true
|
||||
}
|
||||
for _, transform := range []scene.Affine{{}, scene.Scaling(1.01, 1.01), scene.Rotation(11), scene.Projective(1, 0, 0, 1, 0, 0, 0.001, 0.0004)} {
|
||||
if name == "continuous-card" && !transform.Set {
|
||||
continue // the existing untransformed path uses the shader
|
||||
}
|
||||
s := &scene.Scene{Width: 256, Height: 224, Clear: scene.Color{A: 255}, Ops: []scene.Op{card, hard,
|
||||
{Kind: scene.OpFill, Rect: scene.Rect{X: -200, Y: -200, W: 2000, H: 2000}, Color: scene.Color{R: 255, G: 255, B: 255, A: 255}, Transform: transform},
|
||||
{Kind: scene.OpPopClip}, {Kind: scene.OpPopClip},
|
||||
}}
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if (len(r.images) > 0) != wantMask {
|
||||
t.Fatalf("transform=%v: mask textures=%d, want mask=%t", transform, len(r.images), wantMask)
|
||||
}
|
||||
pix, stride, err := r.read()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(ref, s)
|
||||
maxDiff, total := 0, 0
|
||||
for y := range s.Height {
|
||||
for x := range s.Width {
|
||||
diff := int(pix[y*stride+4*x]) - int(ref.Pix[y*ref.Stride+4*x])
|
||||
if diff < 0 {
|
||||
diff = -diff
|
||||
}
|
||||
maxDiff, total = max(maxDiff, diff), total+diff
|
||||
}
|
||||
}
|
||||
if maxDiff > 2 || float64(total)/float64(s.Width*s.Height) > 0.03 {
|
||||
t.Fatalf("transform=%v: clip coverage differs from CPU: max=%d mean=%f", transform, maxDiff, float64(total)/float64(s.Width*s.Height))
|
||||
}
|
||||
if err := r.present(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/raster"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// A stationary or translated rounded card clips its content and hard children without uploading a whole-card mask.
|
||||
func TestRoundedCardClipsTransformedContentWithoutMask(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
hwnd, err := newHiddenWindow(192, 160)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer destroyWindow(hwnd)
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
t.Skip("Direct3D 11 unavailable:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for _, moved := range []bool{false, true} {
|
||||
move := scene.Affine{}
|
||||
if moved {
|
||||
move = scene.Translation(5, 7)
|
||||
}
|
||||
for _, inner := range []bool{false, true} {
|
||||
for _, transform := range []scene.Affine{{}, scene.Scaling(1.01, 1.01), scene.Rotation(11), scene.Projective(1, 0, 0, 1, 20, 15, 0.001, 0.0004)} {
|
||||
s := &scene.Scene{Width: 192, Height: 160, Clear: scene.Color{A: 255}}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 13, Y: 11, W: 133, H: 117}, Radii: [4]float32{19, 19, 19, 19}, Transform: move})
|
||||
if inner {
|
||||
// #1418: a hard child reaching into its rounded parent's
|
||||
// bottom corners must retain those corners; #1420 also
|
||||
// folds a shared translation into the clips' frame positions.
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPushClip, Rect: scene.Rect{X: 13, Y: 70, W: 133, H: 58}, Transform: move})
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpFill, Rect: scene.Rect{W: 190, H: 150}, Color: scene.Color{R: 255, G: 255, B: 255, A: 255}, Transform: transform})
|
||||
if inner {
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
}
|
||||
s.Ops = append(s.Ops, scene.Op{Kind: scene.OpPopClip})
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(r.images) != 0 {
|
||||
t.Fatalf("moved=%t inner=%t transform=%v: rounded card uploaded %d mask textures", moved, inner, transform, len(r.images))
|
||||
}
|
||||
pix, stride, err := r.read()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref := raster.NewImage(s.Width, s.Height)
|
||||
raster.Render(ref, s)
|
||||
maxDiff, totalDiff := 0, 0
|
||||
for y := range s.Height {
|
||||
for x := range s.Width {
|
||||
// This grayscale fixture has equal RGB channels in BGRA and RGBA.
|
||||
d := int(pix[y*stride+4*x]) - int(ref.Pix[y*ref.Stride+4*x])
|
||||
if d < 0 {
|
||||
d = -d
|
||||
}
|
||||
maxDiff = max(maxDiff, d)
|
||||
totalDiff += d
|
||||
}
|
||||
}
|
||||
if maxDiff > 20 || float64(totalDiff)/float64(s.Width*s.Height) > 0.2 {
|
||||
t.Fatalf("moved=%t inner=%t transform=%v: rounded coverage differs from CPU: max=%d mean=%f", moved, inner, transform, maxDiff, float64(totalDiff)/float64(s.Width*s.Height))
|
||||
}
|
||||
if err := r.present(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// BenchmarkRenderSprites draws frames of a 2D game at 1920×1080
|
||||
// (gputest's SpriteScene: 1,872 sprites of one sheet) and reads each
|
||||
// back, which waits for it; with WARP where no GPU runs it, as on CI.
|
||||
func BenchmarkRenderSprites(b *testing.B) {
|
||||
benchRender(b, gputest.SpriteScene(1920, 1080, 3, 3, 300))
|
||||
}
|
||||
|
||||
// BenchmarkRenderEmpty draws frames of nothing at 1920×1080: what the
|
||||
// sprites' frames spend besides them.
|
||||
func BenchmarkRenderEmpty(b *testing.B) {
|
||||
benchRender(b, &scene.Scene{Width: 1920, Height: 1080, Clear: scene.Color{A: 255}})
|
||||
}
|
||||
|
||||
func benchRender(b *testing.B, s *scene.Scene) {
|
||||
hwnd, err := newHiddenWindow(s.Width, s.Height)
|
||||
if err != nil {
|
||||
b.Skip(err)
|
||||
}
|
||||
defer destroyWindow(hwnd)
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
b.Skip(err)
|
||||
}
|
||||
defer r.Release()
|
||||
for b.Loop() {
|
||||
if err := r.draw(s); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
if _, _, err := r.read(); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Canvases draw into textures as the CPU renderer draws them into pixels,
|
||||
// once each: the second frame draws none anew, and shows them the same.
|
||||
func TestCanvases(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.CanvasScene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for frame := range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-canvas", pix, stride, s)
|
||||
if err := r.present(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if frame == 0 {
|
||||
s.Canvases = nil
|
||||
}
|
||||
}
|
||||
if len(r.canvases) != 3 {
|
||||
t.Errorf("%d canvas textures, want 3", len(r.canvases))
|
||||
}
|
||||
}
|
||||
|
||||
// A transient canvas's texture stays while frames draw it, and goes once
|
||||
// they stop, though the canvas is still about; another canvas's stays
|
||||
// until it is collected.
|
||||
func TestTransientCanvas(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
r, err := New(hiddenWindow(t, 64, 64))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
layer, kept := scene.NewCanvas(64, 64), scene.NewCanvas(64, 64)
|
||||
layer.Transient = true
|
||||
s := &scene.Scene{Width: 64, Height: 64, Canvases: []*scene.Image{layer, kept}}
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.sweep()
|
||||
if r.canvases[layer.ID()] == nil || r.canvases[kept.ID()] == nil {
|
||||
t.Fatal("a sweep after the frame that drew them freed a canvas's texture")
|
||||
}
|
||||
r.frame++ // a frame that draws neither
|
||||
r.sweep()
|
||||
if r.canvases[layer.ID()] != nil || r.canvases[kept.ID()] == nil {
|
||||
t.Errorf("transient canvas kept %v, other kept %v", r.canvases[layer.ID()] != nil, r.canvases[kept.ID()] != nil)
|
||||
}
|
||||
runtime.KeepAlive(layer)
|
||||
runtime.KeepAlive(kept)
|
||||
}
|
||||
|
||||
// Frames that present sweep the textures of earlier frames' transient
|
||||
// canvases even when every frame between them changes nothing: those
|
||||
// count as frames too, and sweeping only at multiples of 120 frames, an
|
||||
// animation that drew every other frame presented none of them, and kept
|
||||
// a texture for each of its frames' canvases.
|
||||
func TestSweepBetweenUnchangedFrames(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
r, err := New(hiddenWindow(t, 64, 64))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for range 3 * sweepEvery {
|
||||
c := scene.NewCanvas(16, 16)
|
||||
c.Transient = true
|
||||
s := &scene.Scene{Width: 64, Height: 64, Canvases: []*scene.Image{c}}
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.present(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.frame++ // a frame that changes nothing, and presents nothing
|
||||
}
|
||||
if n := len(r.canvases); n > sweepEvery {
|
||||
t.Errorf("%d canvas textures after %d frames drawn, want at most %d", n, 3*sweepEvery, sweepEvery)
|
||||
}
|
||||
}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
// The shaders of the classes of batches (gpu.Class), after shader.hlsl, whose
|
||||
// functions they share, with CLASSES defined, a bit (1 << gpu.Class) for each
|
||||
// class they draw, and PLAIN, FILL, SHADOW, GLYPH, SUBPIXEL and IMAGE, each 1 if
|
||||
// they draw it, as FXC's preprocessor cannot test the bits. A class's instances
|
||||
// are not transformed, so these leave out the general shader's coordinates, and
|
||||
// pass on only what their paths read; flow control skips what a fragment needs
|
||||
// not, and only subpixel glyphs write a second color for dual-source blending:
|
||||
// the others blend by their alpha, which is that color for them. They draw the
|
||||
// pixels the general shader does.
|
||||
//
|
||||
// `go generate` compiles them to DXBC (shaders.go) on Windows.
|
||||
|
||||
struct ClassOut {
|
||||
float4 pos : SV_Position;
|
||||
float4 pt : PIXEL; // the position in pixels, and the texture coordinates
|
||||
#if PLAIN || FILL || SHADOW || IMAGE
|
||||
nointerpolation float4 rect : RECT;
|
||||
#endif
|
||||
nointerpolation float4 radii : RADII;
|
||||
#if FILL || SHADOW || GLYPH || SUBPIXEL
|
||||
nointerpolation float4 inner : INNER;
|
||||
#endif
|
||||
nointerpolation float4 color : COLOR0;
|
||||
#if FILL || GLYPH || SUBPIXEL
|
||||
nointerpolation float4 color2 : COLOR1;
|
||||
nointerpolation float4 grad : GRAD;
|
||||
#endif
|
||||
#if FILL
|
||||
nointerpolation float4 border : COLOR2;
|
||||
#endif
|
||||
#if FILL || SHADOW || IMAGE
|
||||
nointerpolation float4 widths : WIDTHS;
|
||||
#endif
|
||||
nointerpolation float4 clip : CLIP;
|
||||
nointerpolation float4 clipRadii : CLIPR;
|
||||
// The kind, plus 8 times how the clip applies (gpu.Instance's
|
||||
// Transform1.w); the rest as gpu.Instance's Params.
|
||||
nointerpolation float4 params : PARAMS;
|
||||
};
|
||||
|
||||
ClassOut classvs(uint vid : SV_VertexID, Inst i) {
|
||||
float2 corner = float2(vid & 1, vid >> 1);
|
||||
float kind = i.params.x;
|
||||
float e = kind < 0.5 ? 1 : kind < 1.5 ? 3 * i.params.z + 1 : 0;
|
||||
float4 r = float4(i.rect.xy - e, i.rect.zw + 2 * e);
|
||||
float2 p = r.xy + corner * r.zw;
|
||||
ClassOut o;
|
||||
o.pos = float4(p / viewport * float2(2, -2) + float2(-1, 1), 0, 1);
|
||||
o.pt.xy = p;
|
||||
o.pt.zw = i.uv.xy + (p - i.rect.xy) / i.rect.zw * (i.uv.zw - i.uv.xy);
|
||||
#if PLAIN || FILL || SHADOW || IMAGE
|
||||
o.rect = i.rect;
|
||||
#endif
|
||||
o.radii = i.radii;
|
||||
#if FILL || SHADOW || GLYPH || SUBPIXEL
|
||||
o.inner = i.inner;
|
||||
#endif
|
||||
o.color = i.color;
|
||||
#if FILL || GLYPH || SUBPIXEL
|
||||
o.color2 = i.color2;
|
||||
o.grad = i.grad;
|
||||
#endif
|
||||
#if FILL
|
||||
o.border = i.border;
|
||||
#endif
|
||||
#if FILL || SHADOW || IMAGE
|
||||
o.widths = i.uv;
|
||||
#endif
|
||||
o.clip = i.clip;
|
||||
o.clipRadii = i.clipRadii;
|
||||
// A square clip holding the whole quad, and what a fragment's pixel reaches
|
||||
// beyond it, covers its fragments by 1: none computes that (3).
|
||||
float mode = i.transform1.w;
|
||||
if (mode < 0.5 && !any(i.clipRadii) && all(i.clip.xy <= r.xy - 1) && all(i.clip.xy + i.clip.zw >= r.xy + r.zw + 1)) {
|
||||
mode = 3;
|
||||
}
|
||||
o.params = float4(kind + 8 * mode, i.params.yzw);
|
||||
return o;
|
||||
}
|
||||
|
||||
struct ClassPS {
|
||||
float4 color : SV_Target0;
|
||||
#if SUBPIXEL
|
||||
float4 alpha : SV_Target1;
|
||||
#endif
|
||||
};
|
||||
|
||||
// classClip returns how much of the fragment the clip covers, mode saying how
|
||||
// it applies.
|
||||
float classClip(ClassOut i, float mode) {
|
||||
float2 p = i.pt.xy;
|
||||
[branch] if (mode > 2.5) {
|
||||
return 1;
|
||||
} else if (mode < 0.5) {
|
||||
return rectCoverage(p, i.clip, i.clipRadii);
|
||||
} else if (mode > 1.5) {
|
||||
return rectCoverage(p, i.clip, float4(0, 0, 0, 0)) * clipTex.SampleLevel(samp, (p - i.clipRadii.xy) / i.clipRadii.zw, 0).a;
|
||||
}
|
||||
return clipTex.SampleLevel(samp, (p - i.clip.xy) / i.clip.zw, 0).a;
|
||||
}
|
||||
|
||||
// IS tells whether an instance of class c is one a test finds, which needs no
|
||||
// test when the shader draws only that class.
|
||||
#define IS(c, test) (CLASSES == (1 << c) || (test))
|
||||
|
||||
ClassPS classps(ClassOut i) {
|
||||
float2 p = i.pt.xy;
|
||||
float mode = floor(i.params.x / 8);
|
||||
float kind = i.params.x - 8 * mode;
|
||||
float4 res = float4(0, 0, 0, 0);
|
||||
ClassPS o;
|
||||
#if IMAGE
|
||||
float2 dtex = fwidth(i.pt.zw);
|
||||
#endif
|
||||
#if FILL
|
||||
[branch] if (kind < 0.5) { // plain ones as well, when the shader draws both
|
||||
float outer = rectCoverage(p, i.rect, i.radii);
|
||||
// params.y: 1 dashes the border, 2 paints it with the gradient (the
|
||||
// inside with plain color), 3 both.
|
||||
bool borderPaint = i.params.y > 1.5;
|
||||
float4 pc = paint(p, i.params.z, i.rect, i.color, i.color2, i.grad);
|
||||
res = (borderPaint ? premul(i.color) : pc) * outer;
|
||||
float4 bw = i.widths; // top, right, bottom, left
|
||||
[branch] if (any(bw > 0)) {
|
||||
float4 ir = float4(i.rect.xy + bw.wx, i.rect.zw - bw.yz - bw.wx);
|
||||
float innerCov = 0;
|
||||
if (ir.z > 0 && ir.w > 0) {
|
||||
innerCov = rectCoverage(p, ir, i.inner);
|
||||
}
|
||||
float bc = saturate(outer - innerCov);
|
||||
float dashed = i.params.y - (borderPaint ? 2 : 0);
|
||||
[branch] if (dashed > 0.5) {
|
||||
bc *= dash(p, i.rect, bw);
|
||||
}
|
||||
float4 b = (borderPaint ? pc * float4(i.border.rgb * i.border.a, i.border.a) : premul(i.border)) * bc;
|
||||
res = b + res * (1 - b.a);
|
||||
}
|
||||
}
|
||||
#elif PLAIN
|
||||
[branch] if (IS(1, kind < 0.5)) {
|
||||
res = premul(i.color) * rectCoverage(p, i.rect, i.radii);
|
||||
}
|
||||
#endif
|
||||
#if SHADOW
|
||||
[branch] if (IS(3, kind > 0.5 && kind < 1.5)) {
|
||||
float sigma = i.params.z;
|
||||
[branch] if (i.params.y > 0.5) {
|
||||
// An inner shadow: inside the box, what the hole, blurred, leaves.
|
||||
float hole = 0;
|
||||
[branch] if (i.widths.z > 0 && i.widths.w > 0) {
|
||||
float corner = max(max(i.inner.x, i.inner.y), max(i.inner.z, i.inner.w));
|
||||
[branch] if (sigma > 0) {
|
||||
hole = boxShadow(p, i.widths, sigma, corner);
|
||||
} else {
|
||||
hole = rectCoverage(p, i.widths, i.inner);
|
||||
}
|
||||
}
|
||||
res = premul(i.color) * (rectCoverage(p, i.rect, i.radii) * (1 - hole));
|
||||
} else {
|
||||
// Outside the box casting it, where the blur is worth computing.
|
||||
float outside = 1;
|
||||
[branch] if (i.widths.z > 0 && i.widths.w > 0) {
|
||||
outside = 1 - rectCoverage(p, i.widths, i.inner);
|
||||
}
|
||||
float s = 0;
|
||||
[branch] if (outside > 0) {
|
||||
float corner = max(max(i.radii.x, i.radii.y), max(i.radii.z, i.radii.w));
|
||||
[branch] if (sigma > 0) {
|
||||
s = boxShadow(p, i.rect, sigma, corner);
|
||||
} else {
|
||||
s = rectCoverage(p, i.rect, i.radii);
|
||||
}
|
||||
}
|
||||
res = premul(i.color) * (s * outside);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#if GLYPH
|
||||
[branch] if (IS(4, kind > 1.5 && kind < 2.5)) {
|
||||
float4 c = premul(i.color);
|
||||
[branch] if (i.params.z > 0.5) {
|
||||
c = paint(p, i.params.z, float4(0, 0, 0, 0), i.color, i.color2, i.grad);
|
||||
}
|
||||
res = c * textCoverage(maskTex.SampleLevel(samp, i.pt.zw, 0).r, unpremul(c), i.inner.x, i.inner.y, i.radii);
|
||||
}
|
||||
#endif
|
||||
#if IMAGE
|
||||
[branch] if (kind > 2.5 && kind < 3.5) {
|
||||
res = colorTex.SampleLevel(samp, i.pt.zw, 0) * i.color.a;
|
||||
} else if (kind > 3.5 && kind < 4.5) {
|
||||
[branch] if (i.params.y > 1.5) {
|
||||
// A frame of video: its luma and its chroma, converted.
|
||||
float code = i.params.y - 2;
|
||||
float gray = code > 7.5 ? 1 : 0;
|
||||
float2 cs = chromaScale();
|
||||
res = float4(yuvToRGB(sampleImage(imageTex, i.pt.zw, i.widths, i.params.z, dtex).r,
|
||||
sampleImage(chromaTex, i.pt.zw * cs, i.widths * cs.xyxy, i.params.z, dtex * cs).rg,
|
||||
code - 8 * gray),
|
||||
1);
|
||||
if (gray > 0.5) {
|
||||
res.rgb = dot(res.rgb, float3(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
} else {
|
||||
res = sampleImage(imageTex, i.pt.zw, i.widths, i.params.z, dtex);
|
||||
if (i.params.y > 0.5) {
|
||||
res.rgb = dot(res.rgb, float3(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
}
|
||||
res = tint(res, i.color) * rectCoverage(p, i.rect, i.radii);
|
||||
}
|
||||
#endif
|
||||
#if SUBPIXEL
|
||||
[branch] if (IS(5, kind > 4.5)) {
|
||||
float4 c = premul(i.color);
|
||||
[branch] if (i.params.z > 0.5) {
|
||||
c = paint(p, i.params.z, float4(0, 0, 0, 0), i.color, i.color2, i.grad);
|
||||
}
|
||||
float3 straight = unpremul(c);
|
||||
float3 a = subpixelCoverage(colorTex.SampleLevel(samp, i.pt.zw, 0).rgb, straight, i.inner.x, i.inner.y, i.radii);
|
||||
float3 w = a * c.a * classClip(i, mode) * i.params.w;
|
||||
float wa = (w.r + w.g + w.b) / 3;
|
||||
o.color = float4(straight * w, wa);
|
||||
o.alpha = float4(w, wa);
|
||||
return o;
|
||||
}
|
||||
#endif
|
||||
o.color = res * (classClip(i, mode) * i.params.w);
|
||||
#if SUBPIXEL
|
||||
o.alpha = o.color.aaaa;
|
||||
#endif
|
||||
return o;
|
||||
}
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
)
|
||||
|
||||
// drawClasses draws s with a new renderer that set changes, and returns its
|
||||
// pixels.
|
||||
func drawClasses(t *testing.T, s *scene.Scene, set func(r *Renderer)) []byte {
|
||||
t.Helper()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
set(r)
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, _ := r.readBack(t)
|
||||
return pix
|
||||
}
|
||||
|
||||
// compareToGeneral fails when a channel of pix differs from the general
|
||||
// shader's by more than a level: compilers round a result at a tie either way.
|
||||
func compareToGeneral(t *testing.T, name string, pix, general []byte) {
|
||||
t.Helper()
|
||||
for i := range pix {
|
||||
if d := int(pix[i]) - int(general[i]); d < -1 || d > 1 {
|
||||
t.Fatalf("%s: byte %d is %d, and %d with the general shader", name, i, pix[i], general[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestClassesDrawAsTheGeneralShader draws scenes with the shaders of the
|
||||
// classes of their batches and with the general shader, and with each class
|
||||
// drawn by the shader holding them all, which tells kinds apart.
|
||||
func TestClassesDrawAsTheGeneralShader(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
for _, sc := range []struct {
|
||||
name string
|
||||
s *scene.Scene
|
||||
}{{"scene", gputest.Scene()}, {"card", gputest.BorderedCardScene(false)}} {
|
||||
general := drawClasses(t, sc.s, func(r *Renderer) { r.b.NoClasses = true })
|
||||
compareToGeneral(t, sc.name, drawClasses(t, sc.s, func(r *Renderer) {}), general)
|
||||
compareToGeneral(t, sc.name+" joined", drawClasses(t, sc.s, func(r *Renderer) {
|
||||
all := r.classPipeFor(classShaders[len(classShaders)-1].classes)
|
||||
for c := gpu.ClassPlain; c < gpu.NumClasses; c++ {
|
||||
r.classes[1<<c] = all
|
||||
}
|
||||
}), general)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClassPipelines checks what batches draw with: only the shaders holding
|
||||
// subpixel glyphs blend with a second color, and the shaders of a set of
|
||||
// classes are those of the first set holding it.
|
||||
func TestClassPipelines(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
r, err := New(hiddenWindow(t, 16, 16))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
vs, ps, blend := r.pipeline(&gpu.Batch{Class: gpu.ClassPlain})
|
||||
if vs == r.vs || ps == r.ps || blend != r.overBlend {
|
||||
t.Fatal("a plain fill does not draw with its class's shaders, blended by its alpha")
|
||||
}
|
||||
if _, _, blend := r.pipeline(&gpu.Batch{Class: gpu.ClassPlain, Hole: true}); blend != r.overHoleBlend {
|
||||
t.Fatal("a plain hole does not blend by its alpha")
|
||||
}
|
||||
if _, _, blend := r.pipeline(&gpu.Batch{Class: gpu.ClassSubpixel}); blend != r.blend {
|
||||
t.Fatal("a subpixel glyph does not blend with a second color")
|
||||
}
|
||||
if vs, ps, blend := r.pipeline(&gpu.Batch{}); vs != r.vs || ps != r.ps || blend != r.blend {
|
||||
t.Fatal("the general class does not draw with the general shader")
|
||||
}
|
||||
if _, ps, _ := r.pipeline(&gpu.Batch{Joined: 1<<gpu.ClassPlain | 1<<gpu.ClassShadow}); ps == r.ps {
|
||||
t.Fatal("joined batches draw with the general shader")
|
||||
}
|
||||
// A set no shaders are made for draws with those of the set holding all.
|
||||
_, ps1, blend1 := r.pipeline(&gpu.Batch{Joined: 1<<gpu.ClassFill | 1<<gpu.ClassGlyph})
|
||||
_, ps2, _ := r.pipeline(&gpu.Batch{Joined: 1<<gpu.ClassImage | 1<<gpu.ClassShadow})
|
||||
if ps1 == r.ps || ps1 != ps2 || blend1 != r.blend {
|
||||
t.Fatal("the set holding all classes does not draw what no other holds")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFrameCostFits checks that a frame that takes much of a refresh has the
|
||||
// next ones build ahead, and that later ones of little cost end that.
|
||||
func TestFrameCostFits(t *testing.T) {
|
||||
c := frameCost{period: 16 * time.Millisecond}
|
||||
if !c.fits() {
|
||||
t.Fatal("no frames yet, and frames do not fit")
|
||||
}
|
||||
c.add(2 * time.Millisecond)
|
||||
if !c.fits() {
|
||||
t.Fatal("a frame of 2 ms of 16 does not fit")
|
||||
}
|
||||
c.add(14 * time.Millisecond)
|
||||
if c.fits() {
|
||||
t.Fatal("a frame of 14 ms of 16 fits")
|
||||
}
|
||||
frames := 0
|
||||
for ; !c.fits(); frames++ {
|
||||
c.add(2 * time.Millisecond)
|
||||
}
|
||||
if frames < 2 || frames > 60 {
|
||||
t.Fatalf("%d frames after a heavy one until frames fit", frames)
|
||||
}
|
||||
unknown := frameCost{}
|
||||
if unknown.refreshPeriod() != minRefresh {
|
||||
t.Fatal("no default refresh period")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFrameCostWithoutReady checks that a frame no Ready started, as a resize's
|
||||
// drawn at once, counts no main-thread time: counted from the last frame Ready
|
||||
// started, a drag of seconds would have frames build ahead long after it.
|
||||
func TestFrameCostWithoutReady(t *testing.T) {
|
||||
var c frameCost
|
||||
c.start = time.Now().Add(-3 * time.Second)
|
||||
if d := c.took(); d < 3*time.Second {
|
||||
t.Fatalf("a frame Ready started took %v", d)
|
||||
}
|
||||
if d := c.took(); d >= 0 {
|
||||
t.Fatalf("the next frame, which no Ready started, took %v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFittingFrameWaitsForComposition checks a frame that fits: it presents at
|
||||
// once, with nothing left pending, and the next waits for the window manager's
|
||||
// composition, whose end wakes it, once the screen has room.
|
||||
func TestFittingFrameWaitsForComposition(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
defer func(f func(_, _ time.Duration)) { awaitRefresh = f }(awaitRefresh)
|
||||
composed := make(chan struct{})
|
||||
bounds := make(chan [2]time.Duration, 1)
|
||||
awaitRefresh = func(least, most time.Duration) {
|
||||
bounds <- [2]time.Duration{least, most}
|
||||
<-composed
|
||||
}
|
||||
defer func(ms uintptr) { latencyTimeout = ms }(latencyTimeout)
|
||||
latencyTimeout = 50 // a window that never shows signals no room
|
||||
|
||||
s := gputest.NewChanging(1).Scene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
posted := make(chan func(), 4)
|
||||
r.SetPost(func(f func()) { posted <- f })
|
||||
r.cost.period = 16 * time.Millisecond
|
||||
// However the first frame got there, the second is what the test is about.
|
||||
for r.lat.ready(); !r.lat.ready(); {
|
||||
r.lat.waitThen(func() { posted <- func() {} })
|
||||
wait.For(t, "room", posted)()
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.pending {
|
||||
t.Fatal("a frame that fits waits to present")
|
||||
}
|
||||
if b := wait.For(t, "the wait for the composition", bounds); b != [2]time.Duration{8 * time.Millisecond, 32 * time.Millisecond} {
|
||||
t.Fatalf("waits within %v", b)
|
||||
}
|
||||
woke := make(chan struct{}, 1)
|
||||
if r.Ready(func() { woke <- struct{}{} }) {
|
||||
t.Fatal("the next frame is ready before the composition")
|
||||
}
|
||||
close(composed)
|
||||
for len(woke) == 0 {
|
||||
wait.For(t, "the composition's end, then room", posted)()
|
||||
}
|
||||
r.cost.estimate = time.Hour // the second frame builds ahead
|
||||
if !r.Ready(func() {}) {
|
||||
t.Fatal("a frame that does not fit waits before it builds")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFrameThatWaitedDoesNotKeepNextOnesWaiting checks that a frame that fits but
|
||||
// waited to present, as the screen had no room as it drew, has the next wait for
|
||||
// the composition: woken at once, that would draw before the screen has room and
|
||||
// wait too, and so would every one after it, each a refresh late for good.
|
||||
func TestFrameThatWaitedDoesNotKeepNextOnesWaiting(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
defer func(f func(_, _ time.Duration)) { awaitRefresh = f }(awaitRefresh)
|
||||
composed := make(chan struct{})
|
||||
awaitRefresh = func(_, _ time.Duration) { <-composed }
|
||||
defer func(ms uintptr) { latencyTimeout = ms }(latencyTimeout)
|
||||
latencyTimeout = 50 // a window that never shows signals no room
|
||||
|
||||
s := gputest.NewChanging(1).Scene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
posted := make(chan func(), 4)
|
||||
r.SetPost(func(f func()) { posted <- f })
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
woke := make(chan struct{}, 1)
|
||||
r.wake = func() { woke <- struct{}{} }
|
||||
r.pending = true
|
||||
r.presentPending()
|
||||
if !r.refreshing {
|
||||
t.Fatal("the next frame does not wait for the composition")
|
||||
}
|
||||
if len(woke) != 0 {
|
||||
t.Fatal("the next frame woke before the composition")
|
||||
}
|
||||
close(composed)
|
||||
for len(woke) == 0 {
|
||||
wait.For(t, "the composition's end, then room", posted)()
|
||||
}
|
||||
}
|
||||
|
||||
// TestDwmFlushedShared checks that waits for a refresh share the call under
|
||||
// way: at most one thread waits, whatever frames come meanwhile.
|
||||
func TestDwmFlushedShared(t *testing.T) {
|
||||
a, b := dwmFlushed(), dwmFlushed()
|
||||
if a != b {
|
||||
// The first may have returned at once: then the next is a new wait.
|
||||
select {
|
||||
case <-a:
|
||||
default:
|
||||
t.Fatal("two calls under way")
|
||||
}
|
||||
}
|
||||
wait.For(t, "the window manager", a)
|
||||
}
|
||||
+2002
File diff suppressed because it is too large.
Load diff
+444
@@ -0,0 +1,444 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"slices"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
)
|
||||
|
||||
// hiddenWindow creates a window that never shows, for a swap chain.
|
||||
func hiddenWindow(t *testing.T, w, h int) uintptr {
|
||||
hwnd, err := newHiddenWindow(w, h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { destroyWindow(hwnd) })
|
||||
return hwnd
|
||||
}
|
||||
|
||||
// readBack copies the back buffer to memory: BGRA rows and their stride.
|
||||
func (r *Renderer) readBack(t *testing.T) ([]byte, int) {
|
||||
pix, stride, err := r.read()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pix, stride
|
||||
}
|
||||
|
||||
func TestDrawsAsTheCPURenderer(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
// With the shaders compiled ahead of time, and with those compiled
|
||||
// from shader.hlsl when the renderer starts, as when they are older.
|
||||
for _, compile := range []bool{false, true} {
|
||||
compileShaders = compile
|
||||
s := gputest.Scene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
compileShaders = false
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
// Twice: the second frame updates what the first uploaded.
|
||||
for frame := range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11", pix, stride, s)
|
||||
if err := r.present(1); err != nil {
|
||||
t.Fatalf("frame %d: %v", frame, err)
|
||||
}
|
||||
}
|
||||
|
||||
s = gputest.TransformedScene()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-affine", pix, stride, s)
|
||||
}
|
||||
s = gputest.PerspectiveScene()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-perspective", pix, stride, s)
|
||||
}
|
||||
s = gputest.BehindOriginScene()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-behind-origin", pix, stride, s)
|
||||
}
|
||||
for i, s := range gputest.TranslatedScenes() {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-translated"+[]string{"", "-between-pixels"}[i], pix, stride, s)
|
||||
}
|
||||
s = gputest.MaskedClipScene()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-masked-clips", pix, stride, s)
|
||||
}
|
||||
s = gputest.CornerClipScene()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-corner-clips", pix, stride, s)
|
||||
}
|
||||
r.Release()
|
||||
}
|
||||
}
|
||||
|
||||
// TestBorderedCardDrawsAsTheCPURenderer draws the card of #531 (a large
|
||||
// opaque card with a border of 2 pixels at scale 2, and a small button like
|
||||
// it) with round corners, as Direct3D draws continuous ones, and requires the
|
||||
// CPU renderer's pixels along their straight edges, exactly.
|
||||
func TestBorderedCardDrawsAsTheCPURenderer(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.BorderedCardScene(false)
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for range 2 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.CompareStraightEdges(t, "d3d11-bordered-card", pix, stride, s)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResizeSettles checks that while the window changes size the swap
|
||||
// chain draws into part of larger buffers, resized only when the window
|
||||
// outgrows them, and that once the settle timer asked for a frame, the
|
||||
// frame gives it buffers of the window's size again. A swap chain that
|
||||
// stretches its frames over the window shows that part of its buffers; one
|
||||
// for composition or an unscaled one (#855), which would stretch the part
|
||||
// over the buffers' size, magnifying the frame (#892), shows them whole,
|
||||
// and an unscaled one the content's background beyond the frame.
|
||||
func TestResizeSettles(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
defer func(d time.Duration) { settleDelay = d }(settleDelay)
|
||||
settleDelay = 50 * time.Millisecond
|
||||
for _, newRenderer := range []func(uintptr) (*Renderer, error){New, NewComposed} {
|
||||
r, err := newRenderer(hiddenWindow(t, 200, 150))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
resizeSettles(t, r)
|
||||
r.Release()
|
||||
}
|
||||
}
|
||||
|
||||
func resizeSettles(t *testing.T, r *Renderer) {
|
||||
t.Helper()
|
||||
kind := "window"
|
||||
if r.composed {
|
||||
kind = "composition"
|
||||
}
|
||||
bg := scene.Color{R: 24, G: 24, B: 27, A: 255}
|
||||
frame := func(w, h int) {
|
||||
t.Helper()
|
||||
if err := r.draw(&scene.Scene{Width: w, Height: h, Background: bg}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.unscaled {
|
||||
// What the buffers hold beyond the frame shows where the
|
||||
// window grows before the next frame presents.
|
||||
pix, stride, err := r.readPart(r.bw, r.bh)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, p := range [][2]int{{r.bw - 1, r.bh - 1}, {w, 0}, {r.bw - 1, 0}, {0, h}, {w - 1, r.bh - 1}} {
|
||||
if p[0] < w && p[1] < h || p[0] >= r.bw || p[1] >= r.bh {
|
||||
continue // in the frame, or beyond the buffers
|
||||
}
|
||||
px := pix[p[1]*stride+p[0]*4:]
|
||||
if got := [3]byte{px[2], px[1], px[0]}; got != [3]byte{bg.R, bg.G, bg.B} {
|
||||
t.Fatalf("%s: a %dx%d frame in %dx%d buffers: pixel %v beyond it is %v; want the background %v", kind, w, h, r.bw, r.bh, p, got, bg)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := r.present(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.swapChain2 == 0 {
|
||||
return
|
||||
}
|
||||
const scGetSourceSize = 30 // IDXGISwapChain2
|
||||
var sw, sh uint32
|
||||
call(r.swapChain2, scGetSourceSize, uintptr(unsafe.Pointer(&sw)), uintptr(unsafe.Pointer(&sh)))
|
||||
want := [2]int{r.w, r.h}
|
||||
if r.composed || r.unscaled {
|
||||
want = [2]int{r.bw, r.bh}
|
||||
}
|
||||
if got := [2]int{int(sw), int(sh)}; got != want {
|
||||
t.Fatalf("%s: a %dx%d frame in %dx%d buffers shows %dx%d of them; want %dx%d", kind, w, h, r.bw, r.bh, sw, sh, want[0], want[1])
|
||||
}
|
||||
}
|
||||
frame(200, 150)
|
||||
if r.swapChain2 == 0 {
|
||||
t.Skip("no IDXGISwapChain2")
|
||||
}
|
||||
if r.bw != 200 || r.bh != 150 || r.resizing {
|
||||
t.Fatalf("%s: first frame: buffers %dx%d, resizing %v; want 200x150 and not resizing", kind, r.bw, r.bh, r.resizing)
|
||||
}
|
||||
frame(220, 160)
|
||||
bw, bh := r.bw, r.bh
|
||||
if !r.resizing || bw <= 220 || bh <= 160 {
|
||||
t.Fatalf("%s: resized: buffers %dx%d, resizing %v; want larger than 220x160 and resizing", kind, bw, bh, r.resizing)
|
||||
}
|
||||
frame(230, 155)
|
||||
if r.bw != bw || r.bh != bh || r.w != 230 || r.h != 155 {
|
||||
t.Fatalf("%s: resized within the buffers: buffers %dx%d drawing %dx%d; want %dx%d drawing 230x155", kind, r.bw, r.bh, r.w, r.h, bw, bh)
|
||||
}
|
||||
// The timer fires as messages are dispatched.
|
||||
user32 := syscall.NewLazyDLL("user32.dll")
|
||||
peek, dispatch := user32.NewProc("PeekMessageW"), user32.NewProc("DispatchMessageW")
|
||||
var msg [64]byte
|
||||
for deadline := time.Now().Add(wait.Guard); settling[r.hwnd]; time.Sleep(time.Millisecond) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("%s: the settle timer did not fire", kind)
|
||||
}
|
||||
for {
|
||||
if ok, _, _ := peek.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0, 1); ok == 0 {
|
||||
break
|
||||
}
|
||||
dispatch.Call(uintptr(unsafe.Pointer(&msg)))
|
||||
}
|
||||
}
|
||||
frame(230, 155)
|
||||
if r.bw != 230 || r.bh != 155 || r.resizing {
|
||||
t.Fatalf("%s: settled: buffers %dx%d, resizing %v; want 230x155 and not resizing", kind, r.bw, r.bh, r.resizing)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBeyondFrame checks the parts of a swap chain's buffers beyond the
|
||||
// frame, which an unscaled one fills with the content's background.
|
||||
func TestBeyondFrame(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
w, h, bw, bh int
|
||||
want []gpu.Scissor
|
||||
}{
|
||||
{200, 150, 200, 150, nil},
|
||||
{200, 150, 314, 251, []gpu.Scissor{{Left: 200, Right: 314, Bottom: 251}, {Top: 150, Right: 200, Bottom: 251}}},
|
||||
{200, 150, 200, 251, []gpu.Scissor{{Top: 150, Right: 200, Bottom: 251}}},
|
||||
{200, 150, 314, 150, []gpu.Scissor{{Left: 200, Right: 314, Bottom: 150}}},
|
||||
} {
|
||||
parts, n := beyondFrame(c.w, c.h, c.bw, c.bh)
|
||||
if got := parts[:n]; !slices.Equal(got, c.want) {
|
||||
t.Errorf("beyondFrame(%d, %d, %d, %d) = %v; want %v", c.w, c.h, c.bw, c.bh, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSwapChainBackground checks that the window's swap chain shows its
|
||||
// frames unscaled, and the scene's background beyond them (#222): where the
|
||||
// window grew before the frame of its size presents, DWM shows that, not
|
||||
// black.
|
||||
func TestSwapChainBackground(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
r, err := New(hiddenWindow(t, 200, 150))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
const scGetDesc1, scGetBackgroundColor = 18, 26 // IDXGISwapChain1
|
||||
for _, bg := range []scene.Color{{R: 255, G: 255, B: 255, A: 255}, {R: 24, G: 24, B: 27, A: 255}, {}} {
|
||||
if err := r.draw(&scene.Scene{Width: 200, Height: 150, Background: bg}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var desc swapChainDesc1
|
||||
call(r.swapChain, scGetDesc1, uintptr(unsafe.Pointer(&desc)))
|
||||
if desc.Scaling != scalingNone {
|
||||
t.Fatalf("the swap chain scales frames as %d; want DXGI_SCALING_NONE", desc.Scaling)
|
||||
}
|
||||
var got [4]float32
|
||||
call(r.swapChain, scGetBackgroundColor, uintptr(unsafe.Pointer(&got)))
|
||||
want := [4]float32{float32(bg.R) / 255, float32(bg.G) / 255, float32(bg.B) / 255, 1}
|
||||
if bg.A == 0 {
|
||||
want = [4]float32{0, 0, 0, 1}
|
||||
}
|
||||
for i := range 3 {
|
||||
if d := got[i] - want[i]; d < -0.002 || d > 0.002 {
|
||||
t.Fatalf("background %v: the swap chain shows %v beyond the frame; want %v", bg, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// releaseImages arms every image of a scene to keep only the renderer's
|
||||
// copy of its pixels: the restore re-makes them from a copy it took, and
|
||||
// dropped counts the uploads and drops them again.
|
||||
func releaseImages(s *scene.Scene, restores, drops *int) int {
|
||||
armed := 0
|
||||
for i := range s.Ops {
|
||||
if img := s.Ops[i].Image; img != nil && img.Scene == nil && img.Restore == nil {
|
||||
pix := slices.Clone(img.Pix)
|
||||
img.Restore = func() []byte { *restores++; return pix }
|
||||
img.Dropped = func() { *drops++; img.Pix = nil }
|
||||
armed++
|
||||
}
|
||||
}
|
||||
return armed
|
||||
}
|
||||
|
||||
// TestReleasedImageUploadsFromItsRestore checks issue #664's contract with
|
||||
// the renderer: an image whose pixels an owner dropped uploads them again
|
||||
// from the restore, drawing as before, as a renderer that lost or evicted
|
||||
// its texture does. The first draw takes the new-texture path, which an
|
||||
// eviction after 240 frames takes too.
|
||||
func TestReleasedImageUploadsFromItsRestore(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.Scene()
|
||||
restores, drops := 0, 0
|
||||
armed := releaseImages(s, &restores, &drops)
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if restores != 0 {
|
||||
t.Fatalf("%d restores for pixels the first draw had", restores)
|
||||
}
|
||||
if drops != armed {
|
||||
t.Fatalf("%d drops of %d images", drops, armed)
|
||||
}
|
||||
// The CPU renderer the comparison draws with re-makes the pixels of
|
||||
// the images it draws.
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11 released", pix, stride, s)
|
||||
if restores != armed {
|
||||
t.Fatalf("%d restores of %d images in the CPU render", restores, armed)
|
||||
}
|
||||
// The textures stay for the frames that follow: the restore runs no
|
||||
// more, and the dropped pixels go.
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if restores != armed || drops != armed {
|
||||
t.Fatalf("%d restores, %d drops after a frame with the textures live", restores, drops)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReleasedImageWithNewRenderer uploads from the restore again in a
|
||||
// renderer of its own, as a device that was made again does.
|
||||
func TestReleasedImageWithNewRenderer(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.Scene()
|
||||
restores, drops := 0, 0
|
||||
armed := releaseImages(s, &restores, &drops)
|
||||
for i := range 2 {
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
if err := r.draw(s); err != nil {
|
||||
r.Release()
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The first renderer uploaded the pixels it had; the second
|
||||
// found them dropped by the first and re-made them.
|
||||
if want := i * armed; restores != want {
|
||||
t.Fatalf("renderer %d: %d restores, want %d", i, restores, want)
|
||||
}
|
||||
if drops != (i+1)*armed {
|
||||
t.Fatalf("renderer %d: %d drops, want %d", i, drops, (i+1)*armed)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11 released, new renderer", pix, stride, s)
|
||||
r.Release()
|
||||
}
|
||||
}
|
||||
|
||||
// TestShaderBytecode checks that the shaders compiled ahead of time come
|
||||
// from shader.hlsl as it is, and that the compiler renderers fall back to
|
||||
// compiles it.
|
||||
func TestShaderBytecode(t *testing.T) {
|
||||
if sourceSum() != shaderSum {
|
||||
t.Fatal("shader.hlsl changed since shaders.go was generated: run go generate ./internal/gpu/d3d11 on Windows")
|
||||
}
|
||||
for _, s := range []struct{ entry, target string }{{"vs", "vs_4_0"}, {"ps", "ps_4_0"}} {
|
||||
code, err := compileShader(s.entry, s.target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// DXBC starts with its magic.
|
||||
if len(code) < 4 || string(code[:4]) != "DXBC" {
|
||||
t.Errorf("%s: not DXBC", s.entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestComposed draws into a swap chain for DirectComposition, which shows
|
||||
// on the window with its alpha: frames draw as into the window's own, what
|
||||
// a scene leaves transparent stays so, and once a renderer is released
|
||||
// another composes the window, as after a GPU failure: a window has one
|
||||
// DirectComposition target at most.
|
||||
func TestComposed(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.Scene()
|
||||
hwnd := hiddenWindow(t, s.Width, s.Height)
|
||||
for i := range 2 {
|
||||
r, err := NewComposed(hwnd)
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
if err := r.draw(s); err != nil {
|
||||
r.Release()
|
||||
t.Fatalf("renderer %d: %v", i, err)
|
||||
}
|
||||
if r.target == 0 || r.visual == 0 {
|
||||
t.Fatalf("renderer %d: the swap chain shows through no DirectComposition target", i)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11 composed", pix, stride, s)
|
||||
if err := r.present(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A frame of another size, transparent.
|
||||
if err := r.draw(&scene.Scene{Width: s.Width + 20, Height: s.Height + 10}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pix, _ := r.readBack(t); len(pix) < 4 || pix[0]|pix[1]|pix[2]|pix[3] != 0 {
|
||||
t.Errorf("renderer %d: a transparent frame reads %v", i, pix[:min(len(pix), 4)])
|
||||
}
|
||||
if err := r.present(0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Release()
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// changingScenes calls frame with the steps of random scenes changing a
|
||||
// little at a time, over an opaque color and a translucent one, each with
|
||||
// a renderer drawing in part and one drawing whole, both new: each scene
|
||||
// has an atlas of its own.
|
||||
func changingScenes(t *testing.T, seeds uint64, frame func(r, whole *Renderer, s *scene.Scene, step int, what string)) {
|
||||
for seed := range seeds {
|
||||
m := gputest.NewChanging(seed)
|
||||
if seed%3 == 2 {
|
||||
m.Clear = scene.Color{R: 20, G: 40, B: 200, A: 77}
|
||||
}
|
||||
s := m.Scene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
if r.ctx1 == 0 {
|
||||
r.Release()
|
||||
t.Skip("no Direct3D 11.1")
|
||||
}
|
||||
whole, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
whole.ctx1 = 0 // never in part
|
||||
// No subtests: the windows take their messages on this thread.
|
||||
for step := range 30 {
|
||||
what := fmt.Sprintf("seed %d", seed)
|
||||
if step > 0 {
|
||||
what += ", " + m.Change(s)
|
||||
}
|
||||
frame(r, whole, s, step, what)
|
||||
}
|
||||
r.Release()
|
||||
whole.Release()
|
||||
}
|
||||
}
|
||||
|
||||
// TestPartialFramesMatchWhole draws random scenes changing a little at a
|
||||
// time into a back buffer that keeps what was drawn, as DXGI completes
|
||||
// one presented in part with the last frame, each frame only where it
|
||||
// changed, and requires the bytes of each frame drawn whole.
|
||||
func TestPartialFramesMatchWhole(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
seeds := uint64(20)
|
||||
if testing.Short() {
|
||||
seeds = 5
|
||||
}
|
||||
frames, partial := 0, 0
|
||||
changingScenes(t, seeds, func(r, whole *Renderer, s *scene.Scene, step int, what string) {
|
||||
drawn, err := r.drawFrame(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.held = drawn || r.held // as presenting it does
|
||||
frames++
|
||||
part := "whole"
|
||||
switch r.redrew {
|
||||
case redrewPart:
|
||||
partial++
|
||||
part = r.part.String()
|
||||
case redrewNothing:
|
||||
part = "nothing"
|
||||
}
|
||||
got, _ := r.readBack(t)
|
||||
if err := whole.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, _ := whole.readBack(t)
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("step %d (%s), redrew %s: %d bytes differ from the frame drawn whole", step, what, part, differing(got, want))
|
||||
}
|
||||
})
|
||||
if partial < frames/3 {
|
||||
t.Errorf("%d frames of %d drawn in part", partial, frames)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPresentsInPart presents random scenes changing a little at a time,
|
||||
// each drawn only where it changed, with that as the dirty rectangle, in a
|
||||
// window that shows: DXGI copies the rest from the last frame into the
|
||||
// buffer presented. Once the swap chain flipped again, that buffer, back,
|
||||
// must hold the frame drawn whole.
|
||||
func TestPresentsInPart(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
seeds := uint64(6)
|
||||
if testing.Short() {
|
||||
seeds = 2
|
||||
}
|
||||
// presented holds the frames presented, drawn whole.
|
||||
var presented [][]byte
|
||||
partial := 0
|
||||
changingScenes(t, seeds, func(r, whole *Renderer, s *scene.Scene, step int, what string) {
|
||||
if step == 0 {
|
||||
const swShowNoActivate = 4
|
||||
user32.NewProc("ShowWindow").Call(r.hwnd, swShowNoActivate)
|
||||
presented = presented[:0]
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch r.redrew {
|
||||
case redrewNothing:
|
||||
return // nothing presented: the swap chain did not flip
|
||||
case redrewPart:
|
||||
partial++
|
||||
}
|
||||
if err := whole.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, _ := whole.readBack(t)
|
||||
presented = append(presented, want)
|
||||
// The back buffer now holds the frame presented before, as DXGI
|
||||
// completed it.
|
||||
if n := len(presented); n >= 2 {
|
||||
if got, _ := r.readBack(t); !bytes.Equal(got, presented[n-2]) {
|
||||
t.Fatalf("step %d (%s): the frame before, presented, differs in %d bytes from it drawn whole", step, what, differing(got, presented[n-2]))
|
||||
}
|
||||
}
|
||||
})
|
||||
if partial == 0 {
|
||||
t.Error("no frame was presented in part")
|
||||
}
|
||||
}
|
||||
|
||||
func differing(a, b []byte) (n int) {
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//go:build windows
|
||||
|
||||
// Package device creates Direct3D 11 devices: the device of package d3d11's
|
||||
// renderer, and that of the Windows backend, which shows the controls of
|
||||
// windows with a material through DirectComposition without the renderer.
|
||||
// It depends on nothing of MyGo, so apps that draw no native UI link none
|
||||
// of the renderer.
|
||||
package device
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var procD3D11CreateDevice = syscall.NewLazyDLL(SystemDir() + `\d3d11.dll`).NewProc("D3D11CreateDevice")
|
||||
|
||||
// SystemDir returns the system directory, which system DLLs load from,
|
||||
// never from the application directory or the search path.
|
||||
func SystemDir() string {
|
||||
buf := make([]uint16, 260)
|
||||
n, _, _ := syscall.NewLazyDLL("kernel32.dll").NewProc("GetSystemDirectoryW").Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
|
||||
if n == 0 || int(n) > len(buf) {
|
||||
return `C:\Windows\System32`
|
||||
}
|
||||
return syscall.UTF16ToString(buf[:n])
|
||||
}
|
||||
|
||||
// New creates a Direct3D 11 device and its immediate context, on the GPU
|
||||
// or, when there is none, with Windows' software rasterizer (WARP), which
|
||||
// software reports. The caller releases the device and the context.
|
||||
func New() (device, context uintptr, software bool, err error) {
|
||||
return create(0, hardware, warp)
|
||||
}
|
||||
|
||||
// NewOnGPU is New for a device on the GPU only: it fails where New would
|
||||
// make one with WARP.
|
||||
func NewOnGPU() (device, context uintptr, err error) {
|
||||
device, context, _, err = create(0, hardware)
|
||||
return device, context, err
|
||||
}
|
||||
|
||||
// NewForVideo is New for a device that decodes and converts video, as
|
||||
// Media Foundation's: one that supports Direct3D's video API where the
|
||||
// GPU has it, else as New.
|
||||
func NewForVideo() (device, context uintptr, software bool, err error) {
|
||||
const videoSupport = 0x800
|
||||
if d, c, sw, err := create(videoSupport, hardware, warp); err == nil {
|
||||
return d, c, sw, nil
|
||||
}
|
||||
return create(0, hardware, warp)
|
||||
}
|
||||
|
||||
// The drivers create tries, in order.
|
||||
const hardware, warp = 1, 5
|
||||
|
||||
func create(flags uintptr, drivers ...uintptr) (device, context uintptr, software bool, err error) {
|
||||
if err := procD3D11CreateDevice.Find(); err != nil {
|
||||
return 0, 0, false, err
|
||||
}
|
||||
levels := []uint32{0xb000, 0xa100, 0xa000} // 11_0, 10_1, 10_0
|
||||
const bgraSupport = 0x20
|
||||
var hr uintptr
|
||||
for _, driver := range drivers {
|
||||
var level uint32
|
||||
hr, _, _ = procD3D11CreateDevice.Call(0, driver, 0, bgraSupport|flags,
|
||||
uintptr(unsafe.Pointer(&levels[0])), uintptr(len(levels)), 7,
|
||||
uintptr(unsafe.Pointer(&device)), uintptr(unsafe.Pointer(&level)), uintptr(unsafe.Pointer(&context)))
|
||||
if int32(uint32(hr)) >= 0 {
|
||||
return device, context, driver == warp, nil
|
||||
}
|
||||
}
|
||||
return 0, 0, false, fmt.Errorf("d3d11: cannot create a device: %#x", uint32(hr))
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
//go:build windows
|
||||
|
||||
package device
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"testing"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// IID_IDXGIDevice
|
||||
var iidIDXGIDevice = [16]byte{0xfa, 0x77, 0xec, 0x54, 0x77, 0x13, 0xe6, 0x44, 0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c}
|
||||
|
||||
// call calls method i of the COM interface obj.
|
||||
func call(obj uintptr, i int, args ...uintptr) uintptr {
|
||||
vtbl := *(*uintptr)(*(*unsafe.Pointer)(unsafe.Pointer(&obj)))
|
||||
fn := *(*uintptr)(unsafe.Add(*(*unsafe.Pointer)(unsafe.Pointer(&vtbl)), i*int(unsafe.Sizeof(uintptr(0)))))
|
||||
r, _, _ := syscall.SyscallN(fn, append([]uintptr{obj}, args...)...)
|
||||
return r
|
||||
}
|
||||
|
||||
// TestNew checks that New gives a device and a context, and that the device
|
||||
// is a DXGI device, which DirectComposition needs.
|
||||
func TestNew(t *testing.T) {
|
||||
device, context, software, err := New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer call(device, 2)
|
||||
defer call(context, 2)
|
||||
if device == 0 || context == 0 {
|
||||
t.Fatalf("device %#x, context %#x", device, context)
|
||||
}
|
||||
var dxgi uintptr
|
||||
if hr := call(device, 0, uintptr(unsafe.Pointer(&iidIDXGIDevice)), uintptr(unsafe.Pointer(&dxgi))); int32(uint32(hr)) < 0 {
|
||||
t.Fatalf("the device is no DXGI device: %#x", uint32(hr))
|
||||
}
|
||||
call(dxgi, 2)
|
||||
t.Logf("software (WARP): %v", software)
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
// The head and the tail of an effect's pixel shader (scene.Effect): after
|
||||
// shader.hlsl with EFFECT defined, the head declares what an effect reads,
|
||||
// the effect's source follows, then the tail, after the line "// effect",
|
||||
// draws its instances with it (effectps): the rounded rectangle, or, with
|
||||
// 1 in params.y, a mask glyph a shader's effect fills.
|
||||
|
||||
Texture2D backdropTex : register(t3);
|
||||
|
||||
// What an effect reads of its instance.
|
||||
struct Effect {
|
||||
float4 rect; // x, y, width, height in pixels
|
||||
float4 radii; // top-left, top-right, bottom-right, bottom-left, circular
|
||||
float4 p0, p1, p2, p3, p4;
|
||||
float4 area; // where the backdrop's area starts in the frame, and its size in texels
|
||||
float down; // the size of the squares the backdrop averages
|
||||
float4 transform0, transform1, transform2;
|
||||
};
|
||||
|
||||
float2 framePoint(Effect e, float2 q) {
|
||||
float3 h = float3(dot(e.transform0.xyz, float3(q, 1.0)), dot(e.transform1.xyz, float3(q, 1.0)),
|
||||
dot(float3(e.transform2.xy, 1.0 - 2.0 * e.transform2.z), float3(q, 1.0)));
|
||||
return h.xy / h.z;
|
||||
}
|
||||
|
||||
float3 backdropAt(int2 p, int2 size) { return backdropTex.Load(int3(clamp(p, int2(0, 0), size - 1), 0)).rgb; }
|
||||
|
||||
// sampleBackdrop returns the backdrop at q, in the frame's pixels,
|
||||
// premultiplied, filtered bilinearly from its texels as
|
||||
// scene.BackdropImage.Sample does.
|
||||
float3 sampleBackdrop(Effect e, float2 q) {
|
||||
q = framePoint(e, q);
|
||||
float2 u = (q - e.area.xy) / e.down - 0.5;
|
||||
float2 f = floor(u);
|
||||
float2 w = u - f;
|
||||
int2 p = int2(f);
|
||||
int2 size = int2(e.area.zw);
|
||||
float3 top = backdropAt(p, size) * (1 - w.x) + backdropAt(p + int2(1, 0), size) * w.x;
|
||||
float3 bot = backdropAt(p + int2(0, 1), size) * (1 - w.x) + backdropAt(p + int2(1, 1), size) * w.x;
|
||||
return top * (1 - w.y) + bot * w.y;
|
||||
}
|
||||
|
||||
// effect
|
||||
|
||||
PSOut effectps(VSOut i) {
|
||||
Frame fr = frameOf(i);
|
||||
Effect e;
|
||||
e.rect = i.rect;
|
||||
e.radii = abs(i.radii);
|
||||
e.p0 = i.inner;
|
||||
e.p1 = i.color;
|
||||
e.p2 = i.color2;
|
||||
e.p3 = i.border;
|
||||
e.p4 = i.grad;
|
||||
e.area = i.widths;
|
||||
e.down = i.params.z;
|
||||
e.transform0 = i.transform0;
|
||||
e.transform1 = i.transform1;
|
||||
e.transform2 = i.transform2;
|
||||
float4 res;
|
||||
if (i.params.y > 0.5) {
|
||||
// A mask glyph a shader fills (scene.EffectOp.Glyphs), as ps
|
||||
// draws one, its paint the shader's color.
|
||||
float4 c = effect(i.pt.xy, e);
|
||||
float glyphCov = i.transform0.w > 0.5 ? localCoverage(i.pt.xy, i.rect, float4(0, 0, 0, 0), 1, fr) : 1;
|
||||
res = c * (textCoverage(sampleLocal(maskTex, i.pt.zw, i.widths, i.transform0.w).r, unpremul(c), i.inner.x,
|
||||
i.inner.y, i.radii) *
|
||||
glyphCov * clipCoverage(i) * i.params.w);
|
||||
} else {
|
||||
res = effect(i.pt.xy, e) *
|
||||
(localCoverage(i.pt.xy, i.rect, i.radii, i.transform0.w, fr) * clipCoverage(i) * i.params.w);
|
||||
}
|
||||
PSOut o;
|
||||
o.color = res;
|
||||
o.alpha = res.aaaa;
|
||||
return o;
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
)
|
||||
|
||||
// PrecompileEffect starts compiling the pixel shader of an effect whose
|
||||
// shader is src, which nothing compiled ahead of time, on a goroutine of
|
||||
// its own: the renderers then draw it with that code, waiting for the
|
||||
// compilation if it has not finished, rather than each compiling it on
|
||||
// its first draw. The code is kept on disk too, for the next launches.
|
||||
// Package ui/shader calls it as it compiles a shader, which links the
|
||||
// cache into apps that draw shaders only.
|
||||
func PrecompileEffect(src string) {
|
||||
effects.once.Do(func() {
|
||||
effects.byKey = map[string]*effectEntry{}
|
||||
effects.sem = make(chan struct{}, max(1, runtime.NumCPU()-1))
|
||||
effects.dir = effectCacheDir()
|
||||
code := effects.code
|
||||
sharedEffectCode.Store(&code)
|
||||
})
|
||||
e := effects.entry(src)
|
||||
go func() {
|
||||
effects.sem <- struct{}{}
|
||||
defer func() { <-effects.sem }()
|
||||
e.run()
|
||||
}()
|
||||
}
|
||||
|
||||
// sharedEffectCode returns the code of an effect's pixel shader from the
|
||||
// cache, once PrecompileEffect made it, from any goroutine.
|
||||
var sharedEffectCode atomic.Pointer[func(src string) ([]byte, error)]
|
||||
|
||||
// compileEffectCode compiles the pixel shader of an effect whose code
|
||||
// compiled ahead of time does not match its source: CompileEffect, until
|
||||
// PrecompileEffect shares the code between the renderers.
|
||||
func compileEffectCode(src string) ([]byte, error) {
|
||||
if f := sharedEffectCode.Load(); f != nil {
|
||||
return (*f)(src)
|
||||
}
|
||||
return CompileEffect(src)
|
||||
}
|
||||
|
||||
// effectCache is the code of effects' pixel shaders, by their source.
|
||||
type effectCache struct {
|
||||
once sync.Once
|
||||
mu sync.Mutex
|
||||
byKey map[string]*effectEntry
|
||||
sem chan struct{} // the compilations on goroutines of their own
|
||||
dir string // where the code is kept, "" for nowhere
|
||||
}
|
||||
|
||||
// effects is the cache PrecompileEffect and the renderers share.
|
||||
var effects effectCache
|
||||
|
||||
// effectEntry is the code of an effect's pixel shader, compiled once.
|
||||
type effectEntry struct {
|
||||
c *effectCache
|
||||
src string
|
||||
once sync.Once
|
||||
code []byte
|
||||
err error
|
||||
}
|
||||
|
||||
// entry returns the entry of src, created the first time.
|
||||
func (c *effectCache) entry(src string) *effectEntry {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if e := c.byKey[src]; e != nil {
|
||||
return e
|
||||
}
|
||||
e := &effectEntry{c: c, src: src}
|
||||
c.byKey[src] = e
|
||||
return e
|
||||
}
|
||||
|
||||
// code returns the code of src, compiling it unless a goroutine is, then
|
||||
// waiting for it.
|
||||
func (c *effectCache) code(src string) ([]byte, error) {
|
||||
e := c.entry(src)
|
||||
e.run()
|
||||
return e.code, e.err
|
||||
}
|
||||
|
||||
// effectFlags names how effects' code compiles in the names of the files
|
||||
// keeping it: the target and the flags of compile.
|
||||
const effectFlags = "ps_4_0 effectps O3 IEEE\n"
|
||||
|
||||
// run compiles e once, or reads its code from the disk.
|
||||
func (e *effectEntry) run() {
|
||||
e.once.Do(func() {
|
||||
full := EffectSource(e.src)
|
||||
var path string
|
||||
if e.c.dir != "" {
|
||||
path = filepath.Join(e.c.dir, gpu.SourceSum(effectFlags+full)+".dxbc")
|
||||
if b, err := os.ReadFile(path); err == nil && validDXBC(b) {
|
||||
now := time.Now()
|
||||
os.Chtimes(path, now, now) // the least recently used go first
|
||||
e.code = b
|
||||
return
|
||||
}
|
||||
}
|
||||
e.code, e.err = compile(full, "effectps", "ps_4_0")
|
||||
if e.err == nil && path != "" {
|
||||
saveEffectCode(path, e.code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// validDXBC reports whether b looks like whole DXBC bytecode: its magic,
|
||||
// and the size its header gives. Direct3D checks its checksum.
|
||||
func validDXBC(b []byte) bool {
|
||||
return len(b) >= 32 && string(b[:4]) == "DXBC" && int(binary.LittleEndian.Uint32(b[24:])) == len(b)
|
||||
}
|
||||
|
||||
// effectCacheDir returns the directory keeping effects' code: one for the
|
||||
// user, as Windows' own shader cache (D3DSCache) is, since the files'
|
||||
// names are the SHA-256 of what they compiled from.
|
||||
func effectCacheDir() string {
|
||||
dir, err := os.UserCacheDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(dir, "MyGo", "ShaderCache")
|
||||
}
|
||||
|
||||
// effectCacheSize is how much code the cache keeps, in bytes, before it
|
||||
// removes the files least recently used, as sources change while an app
|
||||
// is developed.
|
||||
const effectCacheSize = 32 << 20
|
||||
|
||||
// saveEffectCode writes code to path, through a temporary file renamed
|
||||
// as another process may be reading it, and trims the cache. It does
|
||||
// without the cache on any error.
|
||||
func saveEffectCode(path string, code []byte) {
|
||||
dir := filepath.Dir(path)
|
||||
if os.MkdirAll(dir, 0o755) != nil {
|
||||
return
|
||||
}
|
||||
f, err := os.CreateTemp(dir, "*.tmp")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = f.Write(code)
|
||||
if f.Close() != nil || err != nil || os.Rename(f.Name(), path) != nil {
|
||||
os.Remove(f.Name())
|
||||
return
|
||||
}
|
||||
trimEffectCache(dir)
|
||||
}
|
||||
|
||||
// trimEffectCache removes the files of dir least recently used while
|
||||
// they weigh more than effectCacheSize.
|
||||
func trimEffectCache(dir string) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
type file struct {
|
||||
name string
|
||||
size int64
|
||||
used time.Time
|
||||
}
|
||||
var files []file
|
||||
var total int64
|
||||
for _, de := range entries {
|
||||
info, err := de.Info()
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
continue
|
||||
}
|
||||
files = append(files, file{de.Name(), info.Size(), info.ModTime()})
|
||||
total += info.Size()
|
||||
}
|
||||
sort.Slice(files, func(i, j int) bool { return files[i].used.Before(files[j].used) })
|
||||
for _, f := range files {
|
||||
if total <= effectCacheSize {
|
||||
break
|
||||
}
|
||||
if os.Remove(filepath.Join(dir, f.name)) == nil {
|
||||
total -= f.size
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const testEffect = "float4 effect(float2 p, Effect e) { return float4(e.p0.rgb, 1); }\n"
|
||||
|
||||
// TestEffectCache checks that an effect's code compiles once for all its
|
||||
// users, as CompileEffect compiles it, and that a later launch reads it
|
||||
// from the disk.
|
||||
func TestEffectCache(t *testing.T) {
|
||||
want, err := CompileEffect(testEffect)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
c := &effectCache{byKey: map[string]*effectEntry{}, dir: dir}
|
||||
got, err := c.code(testEffect)
|
||||
if err != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("code: %d bytes, %v; want %d bytes", len(got), err, len(want))
|
||||
}
|
||||
if again, _ := c.code(testEffect); &again[0] != &got[0] {
|
||||
t.Error("the code compiled again")
|
||||
}
|
||||
files, _ := filepath.Glob(filepath.Join(dir, "*.dxbc"))
|
||||
if len(files) != 1 {
|
||||
t.Fatalf("files kept: %v", files)
|
||||
}
|
||||
// A file that is not whole compiles again.
|
||||
os.WriteFile(files[0], want[:len(want)/2], 0o644)
|
||||
if got, _ := (&effectCache{byKey: map[string]*effectEntry{}, dir: dir}).code(testEffect); !bytes.Equal(got, want) {
|
||||
t.Error("a broken file was read")
|
||||
}
|
||||
// The next launch reads the file.
|
||||
marked := append([]byte(nil), want...)
|
||||
marked[len(marked)-1] ^= 1
|
||||
os.WriteFile(files[0], marked, 0o644)
|
||||
if got, _ := (&effectCache{byKey: map[string]*effectEntry{}, dir: dir}).code(testEffect); !bytes.Equal(got, marked) {
|
||||
t.Error("the file was not read")
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrimEffectCache checks that the cache removes the files least
|
||||
// recently used beyond its size.
|
||||
func TestTrimEffectCache(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
big := make([]byte, effectCacheSize/2)
|
||||
for i, name := range []string{"a", "b", "c"} {
|
||||
path := filepath.Join(dir, name)
|
||||
os.WriteFile(path, big, 0o644)
|
||||
at := time.Unix(int64(1000*(3-i)), 0) // a is the newest
|
||||
os.Chtimes(path, at, at)
|
||||
}
|
||||
trimEffectCache(dir)
|
||||
for name, kept := range map[string]bool{"a": true, "b": true, "c": false} {
|
||||
if _, err := os.Stat(filepath.Join(dir, name)); (err == nil) != kept {
|
||||
t.Errorf("%s: kept %v, want %v", name, err == nil, kept)
|
||||
}
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
//go:build ignore
|
||||
|
||||
// Gen compiles shader.hlsl and classes.hlsl to DXBC with the system's d3dcompiler_47.dll
|
||||
// and writes shaders.go, so that apps need no shader compiler. It runs on
|
||||
// Windows: go generate ./internal/gpu/d3d11
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"log"
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
)
|
||||
|
||||
// classSets are the classes that get shaders of their own, from those holding
|
||||
// least: each class, what small batches join most (shadows with the fills
|
||||
// casting them, fills with labels), and everything, for the rest.
|
||||
var classSets = []uint32{
|
||||
set(gpu.ClassPlain),
|
||||
set(gpu.ClassImage),
|
||||
set(gpu.ClassShadow),
|
||||
set(gpu.ClassPlain, gpu.ClassShadow),
|
||||
set(gpu.ClassGlyph),
|
||||
set(gpu.ClassSubpixel),
|
||||
set(gpu.ClassPlain, gpu.ClassGlyph),
|
||||
set(gpu.ClassPlain, gpu.ClassSubpixel),
|
||||
set(gpu.ClassFill),
|
||||
set(gpu.ClassPlain, gpu.ClassFill, gpu.ClassShadow, gpu.ClassGlyph, gpu.ClassSubpixel, gpu.ClassImage),
|
||||
}
|
||||
|
||||
func set(classes ...gpu.Class) (s uint32) {
|
||||
for _, c := range classes {
|
||||
s |= 1 << c
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// classDefines is that of shader.go, which this program cannot import, as it
|
||||
// makes a file of its package.
|
||||
func classDefines(cl uint32) string {
|
||||
s := fmt.Sprintf("#define CLASSES %d\n", cl)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
class gpu.Class
|
||||
}{{"PLAIN", gpu.ClassPlain}, {"FILL", gpu.ClassFill}, {"SHADOW", gpu.ClassShadow}, {"GLYPH", gpu.ClassGlyph}, {"SUBPIXEL", gpu.ClassSubpixel}, {"IMAGE", gpu.ClassImage}} {
|
||||
s += fmt.Sprintf("#define %s %d\n", c.name, cl>>c.class&1)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func main() {
|
||||
src, err := os.ReadFile("shader.hlsl")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
classes, err := os.ReadFile("classes.hlsl")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
compiler := syscall.NewLazyDLL("d3dcompiler_47.dll").NewProc("D3DCompile")
|
||||
compile := func(src []byte, entry, target string) []byte {
|
||||
var blob, errs uintptr
|
||||
name, _ := syscall.BytePtrFromString("shader.hlsl")
|
||||
e, _ := syscall.BytePtrFromString(entry)
|
||||
t, _ := syscall.BytePtrFromString(target)
|
||||
// IEEE strictness avoids the native optimizer's stack overflow on
|
||||
// transformed coverage sampling while retaining level 3 optimization.
|
||||
const optimize3IEEE = 1<<15 | 1<<13
|
||||
hr, _, _ := compiler.Call(uintptr(unsafe.Pointer(&src[0])), uintptr(len(src)), uintptr(unsafe.Pointer(name)),
|
||||
0, 0, uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(t)), optimize3IEEE, 0,
|
||||
uintptr(unsafe.Pointer(&blob)), uintptr(unsafe.Pointer(&errs)))
|
||||
if int32(hr) < 0 {
|
||||
msg := "unknown error"
|
||||
if errs != 0 {
|
||||
msg = string(blobBytes(errs))
|
||||
}
|
||||
log.Fatalf("%s: %s", entry, msg)
|
||||
}
|
||||
return append([]byte(nil), blobBytes(blob)...)
|
||||
}
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "// Code generated by gen.go from shader.hlsl and classes.hlsl; DO NOT EDIT.\n\n//go:build windows\n\npackage d3d11\n\n")
|
||||
fmt.Fprintf(&b, "// shaderSum is the SHA-256 of the shader.hlsl and the classes.hlsl\n// the shaders were compiled from.\nconst shaderSum = %q\n\n", gpu.SourceSum(string(src)+string(classes)))
|
||||
for _, s := range []struct{ name, entry, target string }{{"vertexShader", "vs", "vs_4_0"}, {"pixelShader", "ps", "ps_4_0"},
|
||||
{"passVertexShader", "passvs", "vs_4_0"}, {"downShader", "downps", "ps_4_0"}, {"blurShader", "blurps", "ps_4_0"}} {
|
||||
b.WriteString(gpu.GoBytes(s.name, compile(src, s.entry, s.target)) + "\n")
|
||||
}
|
||||
b.WriteString("// classShaders are the shaders of classes.hlsl, from those holding least: a\n// batch draws with the first that holds its classes.\nvar classShaders = []classShader{\n")
|
||||
var vars bytes.Buffer
|
||||
for _, cl := range classSets {
|
||||
full := append([]byte(classDefines(cl)+string(src)+"\n"), classes...)
|
||||
fmt.Fprintf(&vars, "%s\n%s\n", gpu.GoBytes(fmt.Sprintf("classVS%d", cl), compile(full, "classvs", "vs_4_0")), gpu.GoBytes(fmt.Sprintf("classPS%d", cl), compile(full, "classps", "ps_4_0")))
|
||||
fmt.Fprintf(&b, "\t{%d, classVS%d, classPS%d},\n", cl, cl, cl)
|
||||
}
|
||||
b.WriteString("}\n\n")
|
||||
b.Write(vars.Bytes())
|
||||
out, err := format.Source(b.Bytes())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile("shaders.go", out, 0o644); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// blobBytes returns the contents of an ID3DBlob.
|
||||
func blobBytes(blob uintptr) []byte {
|
||||
call := func(i int) uintptr {
|
||||
vtbl := *(*uintptr)(unsafe.Pointer(blob))
|
||||
fn := *(*uintptr)(unsafe.Pointer(vtbl + uintptr(i)*unsafe.Sizeof(uintptr(0))))
|
||||
r, _, _ := syscall.SyscallN(fn, blob)
|
||||
return r
|
||||
}
|
||||
p, n := call(3), call(4)
|
||||
return unsafe.Slice((*byte)(unsafe.Pointer(p)), n)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// The shared builder's culling and scissors must preserve every pixel,
|
||||
// including nested clip masks and canvases drawn into textures, as with
|
||||
// OpenGL (see the gl package's test of the same name).
|
||||
func TestGeometryOptimizationsPreservePixels(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
type fixture struct {
|
||||
name string
|
||||
s *scene.Scene
|
||||
}
|
||||
var cases []fixture
|
||||
for _, c := range gputest.CullCases() {
|
||||
cases = append(cases, fixture{"cull/" + c.Name, c.Scene})
|
||||
}
|
||||
for _, c := range gputest.RingCases() {
|
||||
cases = append(cases, fixture{"ring/" + c.Name, c.Scene})
|
||||
}
|
||||
for i, c := range gputest.ShadowCases() {
|
||||
cases = append(cases, fixture{fmt.Sprintf("shadow/%d", i), gputest.ShadowPanelScene(c)})
|
||||
}
|
||||
for _, c := range gputest.MaskedCases() {
|
||||
cases = append(cases, fixture{"masked/" + c.Name, c.Scene})
|
||||
}
|
||||
cases = append(cases,
|
||||
fixture{"transformed", gputest.TransformedScene()},
|
||||
fixture{"perspective", gputest.PerspectiveScene()},
|
||||
fixture{"translated", gputest.TranslatedScenes()[0]},
|
||||
fixture{"translated-between-pixels", gputest.TranslatedScenes()[1]},
|
||||
fixture{"masked-clips", gputest.MaskedClipScene()},
|
||||
fixture{"corner-clips", gputest.CornerClipScene()},
|
||||
fixture{"wide-colors", gputest.WideScene()},
|
||||
fixture{"canvases", gputest.CanvasScene()},
|
||||
)
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
r, err := New(hiddenWindow(t, c.s.Width, c.s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
if err := r.draw(c.s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want, _ := r.readBack(t)
|
||||
if err := r.present(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.b.NoCull, r.b.NoShadowSplit, r.b.NoRingSplit = true, true, true
|
||||
for _, canvas := range r.canvases {
|
||||
canvas.b.NoCull, canvas.b.NoShadowSplit, canvas.b.NoRingSplit = true, true, true
|
||||
}
|
||||
// Draw every canvas again under the reference policy, rather
|
||||
// than comparing against its already optimized texture.
|
||||
c.s.EachCanvas(func(img *scene.Image) { img.Changed() })
|
||||
if err := r.draw(c.s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := r.readBack(t); !bytes.Equal(got, want) {
|
||||
t.Fatal("culling or split scissors changed pixels")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11/device"
|
||||
)
|
||||
|
||||
// The swap chain's frame latency object keeps one frame waiting ahead of
|
||||
// the screen without Present blocking the main thread: DXGI signals it as
|
||||
// the screen takes a frame, and a frame presents only once a wait on it
|
||||
// succeeded. A frame drawn when it is not signaled yet presents later
|
||||
// (pending), as a goroutine waiting on it has the main thread present it,
|
||||
// rather than block in Present until the screen takes the last; frames
|
||||
// paced by the display wait meanwhile (Ready), as they would have. Every
|
||||
// present takes one wait's success, its token, so the object's count
|
||||
// stays that of the frames the screen can take.
|
||||
//
|
||||
// All that keeps a frame a refresh or more from the screen, built ahead and
|
||||
// queued. So frames that the last ones show will make the refresh without
|
||||
// (frameCost.fits) build once the window manager composed the last (DwmFlush) and
|
||||
// the screen has room, and present at once, with sync interval 0, to show at its
|
||||
// next composition: none queues, and input shows about a refresh sooner. Heavier
|
||||
// frames build ahead, as the one the GPU draws meanwhile leaves the main thread
|
||||
// free to build the next: they keep the display's pace, a refresh later.
|
||||
|
||||
// frameCost estimates what a frame costs from when it may start to when the GPU
|
||||
// has drawn it, by the time the main thread took to draw it and the GPU's
|
||||
// timestamps of it, which come in a frame or so later.
|
||||
type frameCost struct {
|
||||
// queries holds the timestamps of the last frames: next is where the next
|
||||
// frame's go, and each is busy until it was read.
|
||||
queries [4]frameQuery
|
||||
next int
|
||||
// start is when the frame being built could start, and estimate the costs
|
||||
// of the last frames, the highest held and fading.
|
||||
start time.Time
|
||||
estimate time.Duration
|
||||
// period is the display's refresh period.
|
||||
period time.Duration
|
||||
}
|
||||
|
||||
type frameQuery struct {
|
||||
disjoint, t0, t1 uintptr
|
||||
busy bool
|
||||
// main is the main thread's part of the frame, or -1 when no Ready started
|
||||
// it, as a resize's frame drawn at once: its cost is not known.
|
||||
main time.Duration
|
||||
}
|
||||
|
||||
// A frame that takes more of a refresh than fitShare may miss it when building
|
||||
// late; its estimate fades by costFade a frame.
|
||||
const (
|
||||
fitShare = 3.0 / 4
|
||||
costFade = 0.95
|
||||
)
|
||||
|
||||
// fits reports whether frames take little enough of a refresh to build once the
|
||||
// screen has room for them.
|
||||
func (c *frameCost) fits() bool {
|
||||
return float64(c.estimate) < fitShare*float64(c.refreshPeriod())
|
||||
}
|
||||
|
||||
// refreshPeriod returns the display's refresh period, a 60 Hz one when it is not
|
||||
// known.
|
||||
func (c *frameCost) refreshPeriod() time.Duration {
|
||||
if c.period == 0 {
|
||||
return minRefresh
|
||||
}
|
||||
return c.period
|
||||
}
|
||||
|
||||
// makeQueries makes the queries, reporting whether it could: frames otherwise
|
||||
// count as not fitting.
|
||||
func (c *frameCost) makeQueries(device uintptr) bool {
|
||||
const queryTimestamp, queryTimestampDisjoint = 2, 3
|
||||
make1 := func(kind uint32, out *uintptr) bool {
|
||||
desc := [2]uint32{kind, 0}
|
||||
return !failed(call(device, devCreateQuery, uintptr(unsafe.Pointer(&desc)), uintptr(unsafe.Pointer(out))))
|
||||
}
|
||||
for i := range c.queries {
|
||||
q := &c.queries[i]
|
||||
if !make1(queryTimestampDisjoint, &q.disjoint) || !make1(queryTimestamp, &q.t0) || !make1(queryTimestamp, &q.t1) {
|
||||
c.release()
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *frameCost) release() {
|
||||
for i := range c.queries {
|
||||
q := &c.queries[i]
|
||||
free(&q.t1)
|
||||
free(&q.t0)
|
||||
free(&q.disjoint)
|
||||
q.busy = false
|
||||
}
|
||||
}
|
||||
|
||||
// begin notes that the GPU starts drawing a frame, unless all queries wait to be
|
||||
// read, which skips timing it. It comes after the frame's clear: the GPU reaches
|
||||
// that once the window manager gave the buffer back, which is no work of the
|
||||
// frame's, up to a refresh after the last.
|
||||
func (c *frameCost) begin(ctx uintptr) *frameQuery {
|
||||
q := &c.queries[c.next]
|
||||
if q.disjoint == 0 || q.busy {
|
||||
return nil
|
||||
}
|
||||
call(ctx, ctxBegin, q.disjoint)
|
||||
call(ctx, ctxEnd, q.t0)
|
||||
return q
|
||||
}
|
||||
|
||||
// end notes that the GPU finishes drawing the frame of q and, for its main
|
||||
// thread's part, that it took since start, which only this frame takes.
|
||||
func (c *frameCost) end(ctx uintptr, q *frameQuery) {
|
||||
call(ctx, ctxEnd, q.t1)
|
||||
call(ctx, ctxEnd, q.disjoint)
|
||||
q.busy = true
|
||||
q.main = c.took()
|
||||
c.next = (c.next + 1) % len(c.queries)
|
||||
}
|
||||
|
||||
// took returns how long the main thread took on the frame since start, and
|
||||
// forgets start: a frame no Ready started, as the ones a resize draws at once,
|
||||
// would count all the time since the last that one did, seconds of a drag, and
|
||||
// have frames build ahead long after. Its cost is not known (-1).
|
||||
func (c *frameCost) took() time.Duration {
|
||||
if c.start.IsZero() {
|
||||
return -1
|
||||
}
|
||||
d := time.Since(c.start)
|
||||
c.start = time.Time{}
|
||||
return d
|
||||
}
|
||||
|
||||
// read takes in the timestamps that came, oldest first, without waiting.
|
||||
func (c *frameCost) read(ctx uintptr) {
|
||||
const doNotFlush = 1
|
||||
for range c.queries {
|
||||
// The oldest is the one after the last begun.
|
||||
q := &c.queries[c.next]
|
||||
for i := range c.queries {
|
||||
q = &c.queries[(c.next+i)%len(c.queries)]
|
||||
if q.busy {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !q.busy {
|
||||
return
|
||||
}
|
||||
var clock struct {
|
||||
Frequency uint64
|
||||
Disjoint int32
|
||||
_ int32
|
||||
}
|
||||
var t0, t1 uint64
|
||||
if call(ctx, ctxGetData, q.disjoint, uintptr(unsafe.Pointer(&clock)), unsafe.Sizeof(clock), doNotFlush) != 0 ||
|
||||
call(ctx, ctxGetData, q.t0, uintptr(unsafe.Pointer(&t0)), 8, doNotFlush) != 0 ||
|
||||
call(ctx, ctxGetData, q.t1, uintptr(unsafe.Pointer(&t1)), 8, doNotFlush) != 0 {
|
||||
return
|
||||
}
|
||||
q.busy = false
|
||||
if q.main >= 0 && clock.Disjoint == 0 && clock.Frequency != 0 && t1 >= t0 {
|
||||
c.add(q.main + time.Duration(float64(t1-t0)/float64(clock.Frequency)*float64(time.Second)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// add takes in what a frame cost.
|
||||
func (c *frameCost) add(cost time.Duration) {
|
||||
c.estimate = max(cost, time.Duration(float64(c.estimate)*costFade))
|
||||
}
|
||||
|
||||
// readPeriod reads the display's refresh period from the window manager; it
|
||||
// stays what it was when that fails.
|
||||
func (c *frameCost) readPeriod() {
|
||||
if p := dwmPeriod(); p != 0 {
|
||||
c.period = p
|
||||
}
|
||||
}
|
||||
|
||||
// dwmPeriod returns the display's refresh period as the window manager
|
||||
// tells it, 0 when it does not; tests replace it.
|
||||
var dwmPeriod = func() time.Duration {
|
||||
// DWM_TIMING_INFO, packed: its size, then the refresh rate's numerator and
|
||||
// denominator.
|
||||
var info [292]byte
|
||||
*(*uint32)(unsafe.Pointer(&info[0])) = uint32(len(info))
|
||||
if hr, _, _ := procDwmGetCompositionTimingInfo.Call(0, uintptr(unsafe.Pointer(&info[0]))); failed(hr) {
|
||||
return 0
|
||||
}
|
||||
num, den := *(*uint32)(unsafe.Pointer(&info[4])), *(*uint32)(unsafe.Pointer(&info[8]))
|
||||
if num == 0 || den == 0 {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(float64(time.Second) * float64(den) / float64(num))
|
||||
}
|
||||
|
||||
var (
|
||||
kernel32 = syscall.NewLazyDLL(device.SystemDir() + `\kernel32.dll`)
|
||||
procWaitForObject = kernel32.NewProc("WaitForSingleObject")
|
||||
procCloseHandle = kernel32.NewProc("CloseHandle")
|
||||
)
|
||||
|
||||
// latencyTimeout is the longest a wait on the object takes, in
|
||||
// milliseconds: the screen takes a frame each refresh, but takes none while
|
||||
// the window shows nowhere, when a frame presents without its token.
|
||||
var latencyTimeout uintptr = 1000
|
||||
|
||||
const (
|
||||
waitObject0 = 0
|
||||
// swapChainWaitable is DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT.
|
||||
swapChainWaitable = 0x40
|
||||
)
|
||||
|
||||
type latency struct {
|
||||
// handle is the object, 0 without one: frames then present at once.
|
||||
handle uintptr
|
||||
|
||||
mu sync.Mutex
|
||||
// token tells that a wait succeeded that no present took yet; waiting
|
||||
// that a goroutine waits on the object, which done tells the end of,
|
||||
// and then what it calls; lapsed that the goroutine's wait timed out,
|
||||
// so the present it calls on does not wait again, on the main thread.
|
||||
token, waiting, lapsed bool
|
||||
done chan struct{}
|
||||
then func()
|
||||
}
|
||||
|
||||
// waitObject waits on the object, at most ms milliseconds, and reports
|
||||
// whether it was signaled.
|
||||
func (l *latency) waitObject(ms uintptr) bool {
|
||||
r, _, _ := procWaitForObject.Call(l.handle, ms)
|
||||
return r == waitObject0
|
||||
}
|
||||
|
||||
// ready reports whether a present can take its token at once, waiting for
|
||||
// nothing.
|
||||
func (l *latency) ready() bool {
|
||||
if l.handle == 0 {
|
||||
return true
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if !l.token && !l.waiting {
|
||||
l.token = l.waitObject(0)
|
||||
}
|
||||
// A wait that lapsed is a present that waits for nothing (take).
|
||||
return l.token || l.lapsed
|
||||
}
|
||||
|
||||
// waitThen has a goroutine wait for the object and call then, on its own
|
||||
// goroutine, once it is signaled (or after latencyTimeout).
|
||||
func (l *latency) waitThen(then func()) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.then = then
|
||||
if l.waiting {
|
||||
return
|
||||
}
|
||||
l.waiting, l.done = true, make(chan struct{})
|
||||
go func() {
|
||||
signaled := l.waitObject(latencyTimeout)
|
||||
l.mu.Lock()
|
||||
l.token = l.token || signaled
|
||||
l.lapsed = !l.token
|
||||
l.waiting = false
|
||||
then := l.then
|
||||
l.then = nil
|
||||
close(l.done)
|
||||
l.mu.Unlock()
|
||||
if then != nil {
|
||||
then()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// take takes the token a present needs, waiting for it on the calling
|
||||
// thread (a resize's frame, one waited for): at most latencyTimeout, after
|
||||
// which the frame presents without one. A present whose goroutine's wait
|
||||
// timed out already waited as long, while the window shows nowhere, and
|
||||
// presents without waiting again.
|
||||
func (l *latency) take() {
|
||||
if l.handle == 0 {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
done, waiting := l.done, l.waiting
|
||||
l.mu.Unlock()
|
||||
if waiting {
|
||||
<-done
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if !l.token && !l.lapsed {
|
||||
l.waitObject(latencyTimeout)
|
||||
}
|
||||
l.token, l.lapsed = false, false
|
||||
}
|
||||
|
||||
// release waits for a goroutine waiting on the object and closes it.
|
||||
func (l *latency) release() {
|
||||
if l.handle == 0 {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
done, waiting := l.done, l.waiting
|
||||
l.then = nil
|
||||
l.mu.Unlock()
|
||||
if waiting {
|
||||
<-done
|
||||
}
|
||||
procCloseHandle.Call(l.handle)
|
||||
l.handle, l.token = 0, false
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
)
|
||||
|
||||
var (
|
||||
procCreateSemaphore = kernel32.NewProc("CreateSemaphoreW")
|
||||
procReleaseSemaphore = kernel32.NewProc("ReleaseSemaphore")
|
||||
)
|
||||
|
||||
// TestFrameLatencyTokens checks the frame latency object's tokens, with a
|
||||
// semaphore standing in for DXGI's: a present is ready when the object is
|
||||
// signaled, holding its token until a present takes it; otherwise a
|
||||
// goroutine waits for it and calls on; a present drawn at once waits for
|
||||
// that goroutine; and each present takes one, so the count stays the
|
||||
// frames the screen can take.
|
||||
func TestFrameLatencyTokens(t *testing.T) {
|
||||
h, _, err := procCreateSemaphore.Call(0, 0, 8, 0)
|
||||
if h == 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l := latency{handle: h}
|
||||
defer l.release()
|
||||
signal := func() { procReleaseSemaphore.Call(h, 1, 0) }
|
||||
|
||||
if l.ready() {
|
||||
t.Fatal("ready before the screen took a frame")
|
||||
}
|
||||
woke := make(chan struct{}, 2)
|
||||
l.waitThen(func() { woke <- struct{}{} })
|
||||
l.waitThen(func() { woke <- struct{}{} }) // the same wait
|
||||
if l.ready() {
|
||||
t.Fatal("ready while waiting")
|
||||
}
|
||||
signal()
|
||||
wait.For(t, "the wait's end", woke)
|
||||
if len(woke) != 0 {
|
||||
t.Fatal("one wait called on twice")
|
||||
}
|
||||
if !l.ready() || !l.ready() {
|
||||
t.Fatal("not ready with the token")
|
||||
}
|
||||
// A present takes it: the next is not ready.
|
||||
l.take()
|
||||
if l.ready() {
|
||||
t.Fatal("ready after a present took the token")
|
||||
}
|
||||
// A present drawn at once waits for the goroutine waiting.
|
||||
l.waitThen(nil)
|
||||
go signal()
|
||||
l.take()
|
||||
if l.token || l.waiting {
|
||||
t.Fatalf("after a present drawn at once: token %v, waiting %v", l.token, l.waiting)
|
||||
}
|
||||
// Signaled when asked: ready at once, with no goroutine.
|
||||
signal()
|
||||
if !l.ready() || l.waiting {
|
||||
t.Fatal("not ready at once when signaled")
|
||||
}
|
||||
l.take()
|
||||
// Every success taken: the count is back to none.
|
||||
if l.waitObject(0) {
|
||||
t.Fatal("the object's count drifted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestLapsedWaitPresentsAtOnce checks that a present whose goroutine's
|
||||
// wait on the object timed out, as it does while the window shows
|
||||
// nowhere, takes no token and does not wait for one again on the main
|
||||
// thread, which would stall it a whole timeout more for each such frame.
|
||||
func TestLapsedWaitPresentsAtOnce(t *testing.T) {
|
||||
defer func(ms uintptr) { latencyTimeout = ms }(latencyTimeout)
|
||||
latencyTimeout = 400
|
||||
h, _, err := procCreateSemaphore.Call(0, 0, 8, 0)
|
||||
if h == 0 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l := latency{handle: h}
|
||||
defer l.release()
|
||||
|
||||
woke := make(chan struct{}, 1)
|
||||
l.waitThen(func() { woke <- struct{}{} })
|
||||
wait.For(t, "the wait's timeout", woke)
|
||||
start := time.Now()
|
||||
l.take()
|
||||
if d := time.Since(start); d >= 200*time.Millisecond {
|
||||
t.Fatalf("the present waited %v again after a lapsed wait", d)
|
||||
}
|
||||
if l.token || l.lapsed {
|
||||
t.Fatalf("after the present: token %v, lapsed %v", l.token, l.lapsed)
|
||||
}
|
||||
// The next present that the screen has room for takes its token as
|
||||
// before.
|
||||
procReleaseSemaphore.Call(h, 1, 0)
|
||||
if !l.ready() {
|
||||
t.Fatal("not ready when signaled")
|
||||
}
|
||||
l.take()
|
||||
if l.waitObject(0) {
|
||||
t.Fatal("the object's count drifted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnchangedFrameWaitsForRefresh checks that a frame that changes
|
||||
// nothing, and so presents nothing, still has the next wait for the
|
||||
// display (Ready), until the refresh it waits for comes: an animation
|
||||
// whose frames move less than a pixel keeps the display's pace rather
|
||||
// than draw as fast as the main thread can (#608).
|
||||
func TestUnchangedFrameWaitsForRefresh(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
refresh := make(chan struct{})
|
||||
defer func(f func(_, _ time.Duration)) { awaitRefresh = f }(awaitRefresh)
|
||||
awaitRefresh = func(_, _ time.Duration) { <-refresh }
|
||||
|
||||
s := gputest.NewChanging(1).Scene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
if r.ctx1 == 0 {
|
||||
t.Skip("no Direct3D 11.1")
|
||||
}
|
||||
posted := make(chan func(), 4)
|
||||
r.SetPost(func(f func()) { posted <- f })
|
||||
r.cost.estimate = time.Hour // frames that go through the frame latency object
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for r.pending {
|
||||
wait.For(t, "the first frame's present", posted)() // once the screen has room
|
||||
}
|
||||
if !r.Ready(func() {}) {
|
||||
t.Fatal("not ready after a frame presented")
|
||||
}
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.redrew != redrewNothing {
|
||||
t.Fatal("the same scene drew again")
|
||||
}
|
||||
woke := make(chan struct{}, 2)
|
||||
if r.Ready(func() { woke <- struct{}{} }) {
|
||||
t.Fatal("ready at once after a frame that changed nothing")
|
||||
}
|
||||
// The next frame that changes nothing waits for the same refresh.
|
||||
if err := r.Render(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refresh <- struct{}{}
|
||||
wait.For(t, "the refresh's end", posted)()
|
||||
wait.For(t, "the wake", woke)
|
||||
if !r.Ready(func() { woke <- struct{}{} }) {
|
||||
t.Fatal("not ready after the refresh")
|
||||
}
|
||||
if len(woke) != 0 || len(posted) != 0 {
|
||||
t.Fatal("woken twice")
|
||||
}
|
||||
}
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// RenderOffscreen draws s with a renderer of its own into a window that
|
||||
// never shows, and returns the premultiplied BGRA rows of its back buffer
|
||||
// and their stride: for tests, as packages drawing effects have.
|
||||
func RenderOffscreen(s *scene.Scene) ([]byte, int, error) {
|
||||
hwnd, err := newHiddenWindow(s.Width, s.Height)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer destroyWindow(hwnd)
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer r.Release()
|
||||
if err := r.draw(s); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return r.read()
|
||||
}
|
||||
|
||||
// newHiddenWindow creates a window that never shows, for a swap chain.
|
||||
func newHiddenWindow(w, h int) (uintptr, error) {
|
||||
class, _ := syscall.UTF16PtrFromString("STATIC")
|
||||
const wsPopup = 0x80000000
|
||||
hwnd, _, err := user32.NewProc("CreateWindowExW").Call(0, uintptr(unsafe.Pointer(class)), 0, wsPopup, 0, 0, uintptr(w), uintptr(h), 0, 0, 0, 0)
|
||||
if hwnd == 0 {
|
||||
return 0, fmt.Errorf("d3d11: cannot create a window: %w", err)
|
||||
}
|
||||
return hwnd, nil
|
||||
}
|
||||
|
||||
func destroyWindow(hwnd uintptr) { user32.NewProc("DestroyWindow").Call(hwnd) }
|
||||
|
||||
// read copies the back buffer to memory: BGRA rows and their stride.
|
||||
func (r *Renderer) read() ([]byte, int, error) { return r.readPart(r.w, r.h) }
|
||||
|
||||
// readPart copies the w×h pixels at the top left of the back buffer to
|
||||
// memory, as read.
|
||||
func (r *Renderer) readPart(w, h int) ([]byte, int, error) {
|
||||
var back, staging uintptr
|
||||
if hr := call(r.swapChain, scGetBuffer, 0, uintptr(unsafe.Pointer(&iidID3D11Texture2D)), uintptr(unsafe.Pointer(&back))); failed(hr) {
|
||||
return nil, 0, fmt.Errorf("d3d11: no back buffer: %#x", uint32(hr))
|
||||
}
|
||||
defer free(&back)
|
||||
const usageStaging, cpuAccessRead, mapRead, ctxCopyResource = 3, 0x20000, 1, 47
|
||||
desc := texture2DDesc{Width: uint32(r.bw), Height: uint32(r.bh), MipLevels: 1, ArraySize: 1, Format: formatB8G8R8A8Unorm,
|
||||
SampleCount: 1, Usage: usageStaging, CPUAccessFlags: cpuAccessRead}
|
||||
if hr := call(r.device, devCreateTexture2D, uintptr(unsafe.Pointer(&desc)), 0, uintptr(unsafe.Pointer(&staging))); failed(hr) {
|
||||
return nil, 0, fmt.Errorf("d3d11: no staging texture: %#x", uint32(hr))
|
||||
}
|
||||
defer free(&staging)
|
||||
call(r.ctx, ctxCopyResource, staging, back)
|
||||
var m mapped
|
||||
if hr := call(r.ctx, ctxMap, staging, 0, mapRead, 0, uintptr(unsafe.Pointer(&m))); failed(hr) {
|
||||
return nil, 0, fmt.Errorf("d3d11: cannot map: %#x", uint32(hr))
|
||||
}
|
||||
defer call(r.ctx, ctxUnmap, staging, 0)
|
||||
pix := make([]byte, w*h*4)
|
||||
for y := range h {
|
||||
copy(pix[y*w*4:], unsafe.Slice((*byte)(ptr(m.Data+uintptr(y)*uintptr(m.RowPitch))), w*4))
|
||||
}
|
||||
return pix, w * 4, nil
|
||||
}
|
||||
|
||||
// Offscreen draws scenes into a window that never shows, timing each on
|
||||
// the GPU, for measurements (BenchmarkStressFrameGPU).
|
||||
type Offscreen struct {
|
||||
r *Renderer
|
||||
hwnd uintptr
|
||||
disjoint, t0, t1 uintptr
|
||||
}
|
||||
|
||||
// NewOffscreen returns an Offscreen drawing frames of w×h pixels.
|
||||
func NewOffscreen(w, h int) (*Offscreen, error) {
|
||||
hwnd, err := newHiddenWindow(w, h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
destroyWindow(hwnd)
|
||||
return nil, err
|
||||
}
|
||||
o := &Offscreen{r: r, hwnd: hwnd}
|
||||
const queryTimestamp, queryTimestampDisjoint = 2, 3
|
||||
for _, q := range []struct {
|
||||
kind uint32
|
||||
out *uintptr
|
||||
}{{queryTimestampDisjoint, &o.disjoint}, {queryTimestamp, &o.t0}, {queryTimestamp, &o.t1}} {
|
||||
desc := [2]uint32{q.kind, 0}
|
||||
if hr := call(r.device, devCreateQuery, uintptr(unsafe.Pointer(&desc)), uintptr(unsafe.Pointer(q.out))); failed(hr) {
|
||||
o.Release()
|
||||
return nil, fmt.Errorf("d3d11: cannot create a query: %#x", uint32(hr))
|
||||
}
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
// Render draws s whole and returns the time the GPU spent drawing it, once
|
||||
// it is done.
|
||||
func (o *Offscreen) Render(s *scene.Scene) (time.Duration, error) {
|
||||
ctx := o.r.ctx
|
||||
call(ctx, ctxBegin, o.disjoint)
|
||||
call(ctx, ctxEnd, o.t0)
|
||||
if err := o.r.draw(s); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
call(ctx, ctxEnd, o.t1)
|
||||
call(ctx, ctxEnd, o.disjoint)
|
||||
call(ctx, ctxFlush)
|
||||
var clock struct {
|
||||
Frequency uint64
|
||||
Disjoint int32
|
||||
_ int32
|
||||
}
|
||||
var start, end uint64
|
||||
get := func(q uintptr, out unsafe.Pointer, size uintptr) {
|
||||
// S_FALSE, 1, until the GPU gets there.
|
||||
for call(ctx, ctxGetData, q, uintptr(out), size, 0) == 1 {
|
||||
runtime.Gosched()
|
||||
}
|
||||
}
|
||||
get(o.disjoint, unsafe.Pointer(&clock), unsafe.Sizeof(clock))
|
||||
get(o.t0, unsafe.Pointer(&start), 8)
|
||||
get(o.t1, unsafe.Pointer(&end), 8)
|
||||
if clock.Disjoint != 0 || clock.Frequency == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
return time.Duration(float64(end-start) / float64(clock.Frequency) * float64(time.Second)), nil
|
||||
}
|
||||
|
||||
// Release frees what the Offscreen holds.
|
||||
func (o *Offscreen) Release() {
|
||||
free(&o.t1)
|
||||
free(&o.t0)
|
||||
free(&o.disjoint)
|
||||
o.r.Release()
|
||||
destroyWindow(o.hwnd)
|
||||
}
|
||||
|
||||
// Frames draws frames one after another into a window that never shows,
|
||||
// for videos (plugins/render): Draw draws one and copies it into a
|
||||
// staging texture kept from frame to frame, without waiting for the GPU;
|
||||
// Read waits for it and copies its pixels.
|
||||
type Frames struct {
|
||||
r *Renderer
|
||||
hwnd uintptr
|
||||
staging uintptr
|
||||
w, h int
|
||||
}
|
||||
|
||||
// NewFrames returns a Frames drawing frames of w×h pixels.
|
||||
func NewFrames(w, h int) (*Frames, error) {
|
||||
hwnd, err := newHiddenWindow(w, h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r, err := New(hwnd)
|
||||
if err != nil {
|
||||
destroyWindow(hwnd)
|
||||
return nil, err
|
||||
}
|
||||
return &Frames{r: r, hwnd: hwnd}, nil
|
||||
}
|
||||
|
||||
// Software reports whether the frames draw with WARP, Windows' software
|
||||
// rasterizer, for a system without a GPU.
|
||||
func (f *Frames) Software() bool { return f.r.warp }
|
||||
|
||||
// Name returns the description of the adapter, as "NVIDIA GeForce RTX 4070".
|
||||
func (f *Frames) Name() string {
|
||||
var dxgiDev, adapter uintptr
|
||||
if failed(call(f.r.device, 0, uintptr(unsafe.Pointer(&iidIDXGIDevice)), uintptr(unsafe.Pointer(&dxgiDev)))) {
|
||||
return ""
|
||||
}
|
||||
defer free(&dxgiDev)
|
||||
if failed(call(dxgiDev, dxgiDevGetAdapter, uintptr(unsafe.Pointer(&adapter)))) {
|
||||
return ""
|
||||
}
|
||||
defer free(&adapter)
|
||||
// DXGI_ADAPTER_DESC begins with its description, in 128 WCHARs.
|
||||
var desc [512]byte
|
||||
const adapterGetDesc = 8
|
||||
if failed(call(adapter, adapterGetDesc, uintptr(unsafe.Pointer(&desc[0])))) {
|
||||
return ""
|
||||
}
|
||||
return syscall.UTF16ToString(unsafe.Slice((*uint16)(unsafe.Pointer(&desc[0])), 128))
|
||||
}
|
||||
|
||||
// Draw draws s whole, and copies it for Read.
|
||||
func (f *Frames) Draw(s *scene.Scene) error {
|
||||
r := f.r
|
||||
if err := r.draw(s); err != nil {
|
||||
return err
|
||||
}
|
||||
if f.staging == 0 || f.w != r.bw || f.h != r.bh {
|
||||
free(&f.staging)
|
||||
const usageStaging, cpuAccessRead = 3, 0x20000
|
||||
desc := texture2DDesc{Width: uint32(r.bw), Height: uint32(r.bh), MipLevels: 1, ArraySize: 1, Format: formatB8G8R8A8Unorm,
|
||||
SampleCount: 1, Usage: usageStaging, CPUAccessFlags: cpuAccessRead}
|
||||
if hr := call(r.device, devCreateTexture2D, uintptr(unsafe.Pointer(&desc)), 0, uintptr(unsafe.Pointer(&f.staging))); failed(hr) {
|
||||
return fmt.Errorf("d3d11: no staging texture: %#x", uint32(hr))
|
||||
}
|
||||
f.w, f.h = r.bw, r.bh
|
||||
}
|
||||
var back uintptr
|
||||
if hr := call(r.swapChain, scGetBuffer, 0, uintptr(unsafe.Pointer(&iidID3D11Texture2D)), uintptr(unsafe.Pointer(&back))); failed(hr) {
|
||||
return fmt.Errorf("d3d11: no back buffer: %#x", uint32(hr))
|
||||
}
|
||||
defer free(&back)
|
||||
const ctxCopyResource = 47
|
||||
call(r.ctx, ctxCopyResource, f.staging, back)
|
||||
call(r.ctx, ctxFlush)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Read copies the pixels of the frame Draw drew last, w×h, into dst:
|
||||
// premultiplied BGRA rows from the top, 4×w bytes each. It waits for the
|
||||
// GPU to finish the frame.
|
||||
func (f *Frames) Read(dst []byte, w, h int) error {
|
||||
if f.staging == 0 || w > f.w || h > f.h || len(dst) < 4*w*h {
|
||||
return errors.New("d3d11: no frame to read, or too small a buffer")
|
||||
}
|
||||
const mapRead = 1
|
||||
var m mapped
|
||||
if hr := call(f.r.ctx, ctxMap, f.staging, 0, mapRead, 0, uintptr(unsafe.Pointer(&m))); failed(hr) {
|
||||
return fmt.Errorf("d3d11: cannot map: %#x", uint32(hr))
|
||||
}
|
||||
defer call(f.r.ctx, ctxUnmap, f.staging, 0)
|
||||
for y := range h {
|
||||
copy(dst[y*w*4:(y+1)*w*4], unsafe.Slice((*byte)(ptr(m.Data+uintptr(y)*uintptr(m.RowPitch))), w*4))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Release frees what the Frames hold.
|
||||
func (f *Frames) Release() {
|
||||
free(&f.staging)
|
||||
f.r.Release()
|
||||
destroyWindow(f.hwnd)
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11/device"
|
||||
)
|
||||
|
||||
//go:embed shader.hlsl
|
||||
var shaderSource string
|
||||
|
||||
// effectSource is the head and the tail of an effect's pixel shader,
|
||||
// around the line "// effect" (see EffectSource).
|
||||
//
|
||||
//go:embed effect.hlsl
|
||||
var effectSource string
|
||||
|
||||
//go:embed classes.hlsl
|
||||
var classSource string
|
||||
|
||||
// sourceSum is the SHA-256 of the source of the shaders of shaders.go.
|
||||
func sourceSum() string { return gpu.SourceSum(shaderSource + classSource) }
|
||||
|
||||
// classShader is what batches of some classes draw with, compiled ahead of
|
||||
// time: the vertex and pixel shaders of classes.hlsl with CLASSES defined.
|
||||
type classShader struct {
|
||||
classes uint32
|
||||
vs, ps []byte
|
||||
}
|
||||
|
||||
// classDefines returns what classes.hlsl needs defined for the classes cl (a
|
||||
// bit, 1 << gpu.Class, for each), as gen.go compiles it.
|
||||
func classDefines(cl uint32) string {
|
||||
s := fmt.Sprintf("#define CLASSES %d\n", cl)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
class gpu.Class
|
||||
}{{"PLAIN", gpu.ClassPlain}, {"FILL", gpu.ClassFill}, {"SHADOW", gpu.ClassShadow}, {"GLYPH", gpu.ClassGlyph}, {"SUBPIXEL", gpu.ClassSubpixel}, {"IMAGE", gpu.ClassImage}} {
|
||||
s += fmt.Sprintf("#define %s %d\n", c.name, cl>>c.class&1)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// compileClass compiles the shaders of the classes cl from their sources, for
|
||||
// shaders.go older than them.
|
||||
func compileClass(cl uint32) (vs, ps []byte, err error) {
|
||||
src := classDefines(cl) + shaderSource + "\n" + classSource
|
||||
if vs, err = compile(src, "classvs", "vs_4_0"); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if ps, err = compile(src, "classps", "ps_4_0"); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return vs, ps, nil
|
||||
}
|
||||
|
||||
// EffectSource returns the source of an effect's pixel shader: shader.hlsl
|
||||
// with EFFECT defined, the head of effect.hlsl, the effect's shader (see
|
||||
// scene.Effect), and the tail, which draws its instances with it
|
||||
// (effectps). Effects compile it ahead of time with CompileEffect.
|
||||
func EffectSource(src string) string {
|
||||
head, tail, _ := strings.Cut(effectSource, "\n// effect\n")
|
||||
return "#define EFFECT\n" + shaderSource + "\n" + head + "\n" + src + "\n" + tail
|
||||
}
|
||||
|
||||
// CompileEffect compiles the pixel shader of an effect whose shader is
|
||||
// src, with the compiler Windows has, as go generate does for code
|
||||
// compiled ahead of time.
|
||||
func CompileEffect(src string) ([]byte, error) {
|
||||
return compile(EffectSource(src), "effectps", "ps_4_0")
|
||||
}
|
||||
|
||||
// compileShaders makes shaderCode compile shader.hlsl even when the
|
||||
// bytecode of shaders.go comes from it, for tests.
|
||||
var compileShaders bool
|
||||
|
||||
// shaders is the bytecode of the shader's functions: the instances' vertex
|
||||
// and pixel shaders, and the passes computing backdrops (see package gpu).
|
||||
type shaders struct {
|
||||
vs, ps, passVS, down, blur []byte
|
||||
}
|
||||
|
||||
// shaderCode returns the bytecode of the shaders: that compiled ahead of
|
||||
// time into shaders.go, or, when shader.hlsl or classes.hlsl changed since (go generate
|
||||
// ./internal/gpu/d3d11 was not run), that compiled now from shader.hlsl,
|
||||
// with the compiler Windows has.
|
||||
func shaderCode() (code shaders, err error) {
|
||||
if sourceSum() == shaderSum && !compileShaders {
|
||||
return shaders{vertexShader, pixelShader, passVertexShader, downShader, blurShader}, nil
|
||||
}
|
||||
for _, f := range []struct {
|
||||
code *[]byte
|
||||
entry, target string
|
||||
}{{&code.vs, "vs", "vs_4_0"}, {&code.ps, "ps", "ps_4_0"}, {&code.passVS, "passvs", "vs_4_0"}, {&code.down, "downps", "ps_4_0"}, {&code.blur, "blurps", "ps_4_0"}} {
|
||||
if *f.code, err = compileShader(f.entry, f.target); err != nil {
|
||||
return shaders{}, err
|
||||
}
|
||||
}
|
||||
return code, nil
|
||||
}
|
||||
|
||||
// procD3DCompile is the shader compiler of Windows 10 and later, which gen.go
|
||||
// compiles shaders.go with too.
|
||||
var procD3DCompile = syscall.NewLazyDLL(device.SystemDir() + `\d3dcompiler_47.dll`).NewProc("D3DCompile")
|
||||
|
||||
// compileShader compiles the function entry of shader.hlsl for target, as
|
||||
// gen.go does.
|
||||
func compileShader(entry, target string) ([]byte, error) {
|
||||
return compile(shaderSource, entry, target)
|
||||
}
|
||||
|
||||
// compile compiles the function entry of source for target.
|
||||
func compile(source, entry, target string) ([]byte, error) {
|
||||
if err := procD3DCompile.Find(); err != nil {
|
||||
return nil, fmt.Errorf("d3d11: no shader compiler: %w", err)
|
||||
}
|
||||
src := []byte(source)
|
||||
name, _ := syscall.BytePtrFromString("shader.hlsl")
|
||||
e, _ := syscall.BytePtrFromString(entry)
|
||||
t, _ := syscall.BytePtrFromString(target)
|
||||
// IEEE strictness avoids the native optimizer's stack overflow on
|
||||
// transformed coverage sampling while retaining level 3 optimization.
|
||||
const optimize3IEEE = 1<<15 | 1<<13
|
||||
var blob, errs uintptr
|
||||
hr, _, _ := procD3DCompile.Call(uintptr(unsafe.Pointer(&src[0])), uintptr(len(src)), uintptr(unsafe.Pointer(name)),
|
||||
0, 0, uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(t)), optimize3IEEE, 0,
|
||||
uintptr(unsafe.Pointer(&blob)), uintptr(unsafe.Pointer(&errs)))
|
||||
if errs != 0 {
|
||||
defer free(&errs)
|
||||
}
|
||||
if failed(hr) || blob == 0 {
|
||||
msg := "unknown error"
|
||||
if errs != 0 {
|
||||
msg = string(blobBytes(errs))
|
||||
}
|
||||
return nil, fmt.Errorf("d3d11: cannot compile the %s shader: %s", entry, msg)
|
||||
}
|
||||
defer free(&blob)
|
||||
return append([]byte(nil), blobBytes(blob)...), nil
|
||||
}
|
||||
|
||||
// blobBytes returns the contents of an ID3DBlob, until it is released.
|
||||
func blobBytes(blob uintptr) []byte {
|
||||
const blobGetBufferPointer, blobGetBufferSize = 3, 4
|
||||
p, n := call(blob, blobGetBufferPointer), call(blob, blobGetBufferSize)
|
||||
return unsafe.Slice((*byte)(ptr(p)), n)
|
||||
}
|
||||
+654
@@ -0,0 +1,654 @@
|
||||
// The one shader of the Direct3D 11 renderer: every scene op is an
|
||||
// instanced quad, and the pixel shader computes the coverage of rounded
|
||||
// rectangles, borders, gradients, stripes and shadows from signed
|
||||
// distances, as the software renderer (internal/raster) does, with the
|
||||
// passes computing the backdrops of effects (passvs, downps and blurps).
|
||||
// The pixel shaders of effects (scene.Effect) take its start, with EFFECT
|
||||
// defined, before effect.hlsl. Colors are straight (not
|
||||
// premultiplied) and blending happens in sRGB space, as in browsers, with a
|
||||
// second color for the source's alpha of each channel, which subpixel
|
||||
// glyphs need.
|
||||
//
|
||||
// `go generate` compiles it to DXBC (shaders.go) on Windows.
|
||||
|
||||
cbuffer Globals : register(b0) {
|
||||
float2 viewport;
|
||||
float2 pad;
|
||||
};
|
||||
|
||||
struct Inst {
|
||||
float4 rect : RECT; // x, y, width, height in pixels
|
||||
float4 radii : RADII; // top-left, top-right, bottom-right, bottom-left
|
||||
float4 inner : INNER; // radii of the border's inner edge, of the box casting a shadow, or of an inner shadow's hole
|
||||
float4 color : COLOR0;
|
||||
float4 color2 : COLOR1; // gradient end
|
||||
float4 border : COLOR2; // border color
|
||||
float4 grad : GRAD; // gradient start and end points, or stripes
|
||||
float4 uv : UV; // texture rectangle, normalized, border widths, the box casting a shadow, or an inner shadow's hole
|
||||
float4 clip : CLIP; // the innermost clip rectangle
|
||||
float4 clipRadii : CLIPR;
|
||||
float4 transform0 : TRANSFORM0;
|
||||
float4 transform1 : TRANSFORM1;
|
||||
float4 transform2 : TRANSFORM2; // the projective row's g and h, and 1 where its constant is -1
|
||||
float4 params : PARAMS; // kind, dashed or grayscale, sigma or paint, opacity
|
||||
};
|
||||
|
||||
struct VSOut {
|
||||
float4 pos : SV_Position;
|
||||
float4 pt : PIXEL; // the position in pixels, and the texture coordinates
|
||||
nointerpolation float4 rect : RECT;
|
||||
nointerpolation float4 radii : RADII;
|
||||
nointerpolation float4 inner : INNER;
|
||||
nointerpolation float4 color : COLOR0;
|
||||
nointerpolation float4 color2 : COLOR1;
|
||||
nointerpolation float4 border : COLOR2;
|
||||
nointerpolation float4 grad : GRAD;
|
||||
nointerpolation float4 widths : WIDTHS;
|
||||
nointerpolation float4 clip : CLIP;
|
||||
nointerpolation float4 clipRadii : CLIPR;
|
||||
nointerpolation float4 params : PARAMS;
|
||||
nointerpolation float4 transform0 : TRANSFORM0;
|
||||
nointerpolation float4 transform1 : TRANSFORM1;
|
||||
nointerpolation float4 transform2 : TRANSFORM2;
|
||||
};
|
||||
|
||||
// frameH returns the frame point of local p, in homogeneous coordinates.
|
||||
float3 frameH(Inst i, float2 p) {
|
||||
return float3(dot(i.transform0.xyz, float3(p, 1)), dot(i.transform1.xyz, float3(p, 1)),
|
||||
dot(float3(i.transform2.xy, 1 - 2 * i.transform2.z), float3(p, 1)));
|
||||
}
|
||||
|
||||
VSOut vs(uint vid : SV_VertexID, Inst i) {
|
||||
float2 corner = float2(vid & 1, vid >> 1);
|
||||
float4 r = i.rect;
|
||||
float kind = i.params.x;
|
||||
if (kind < 0.5 || kind > 5.5) { // fills and effects
|
||||
r = float4(r.xy - 1, r.zw + 2);
|
||||
} else if (kind < 1.5) {
|
||||
float e = 3 * i.params.z + 1;
|
||||
r = float4(r.xy - e, r.zw + 2 * e);
|
||||
}
|
||||
float3 h = frameH(i, r.xy + corner * r.zw);
|
||||
if (i.transform0.w > 0.5 && h.z > 0) {
|
||||
// A pixel's reach at this corner, by the map's Jacobian there.
|
||||
float2 s = h.xy / h.z;
|
||||
float a = (i.transform0.x - s.x * i.transform2.x) / h.z, c = (i.transform0.y - s.x * i.transform2.y) / h.z;
|
||||
float b = (i.transform1.x - s.y * i.transform2.x) / h.z, d = (i.transform1.y - s.y * i.transform2.y) / h.z;
|
||||
float2 e = float2(abs(d) + abs(c), abs(b) + abs(a)) / abs(a * d - b * c);
|
||||
r = float4(r.xy - e, r.zw + 2 * e);
|
||||
}
|
||||
float2 p = r.xy + corner * r.zw;
|
||||
h = frameH(i, p);
|
||||
VSOut o;
|
||||
o.pos = float4(h.xy / viewport * float2(2, -2) + h.z * float2(-1, 1), 0, h.z);
|
||||
o.pt.xy = p;
|
||||
o.pt.zw = i.uv.xy + (p - i.rect.xy) / i.rect.zw * (i.uv.zw - i.uv.xy);
|
||||
o.rect = i.rect;
|
||||
o.radii = i.radii;
|
||||
o.inner = i.inner;
|
||||
o.color = i.color;
|
||||
o.color2 = i.color2;
|
||||
o.border = i.border;
|
||||
o.grad = i.grad;
|
||||
o.widths = i.uv;
|
||||
o.clip = i.clip;
|
||||
o.clipRadii = i.clipRadii;
|
||||
o.params = i.params;
|
||||
o.transform0 = i.transform0;
|
||||
o.transform1 = i.transform1;
|
||||
o.transform2 = i.transform2;
|
||||
return o;
|
||||
}
|
||||
|
||||
// The color and, for dual-source blending, the source's alpha of each
|
||||
// channel.
|
||||
struct PSOut {
|
||||
float4 color : SV_Target0;
|
||||
float4 alpha : SV_Target1;
|
||||
};
|
||||
|
||||
Texture2D maskTex : register(t0);
|
||||
Texture2D colorTex : register(t1);
|
||||
Texture2D imageTex : register(t2);
|
||||
Texture2D clipTex : register(t5);
|
||||
SamplerState samp : register(s0);
|
||||
|
||||
float sdRoundRect(float2 p, float4 rect, float4 radii) {
|
||||
float2 h = rect.zw * 0.5;
|
||||
float2 q = p - rect.xy - h;
|
||||
float r = q.x < 0 ? (q.y < 0 ? radii.x : radii.w) : (q.y < 0 ? radii.y : radii.z);
|
||||
float2 a = abs(q) - h + r;
|
||||
return length(max(a, 0)) + min(max(a.x, a.y), 0) - r;
|
||||
}
|
||||
|
||||
float coverage(float d) { return saturate(0.5 - d); }
|
||||
|
||||
// rectCoverage returns how much of the pixel at p a rounded rectangle
|
||||
// covers: by the distance to its edge near rounded corners, and exactly,
|
||||
// the area of the pixel inside it, near square ones.
|
||||
float rectCoverage(float2 p, float4 rect, float4 radii) {
|
||||
float2 q = p - rect.xy - rect.zw * 0.5;
|
||||
float r = q.x < 0 ? (q.y < 0 ? radii.x : radii.w) : (q.y < 0 ? radii.y : radii.z);
|
||||
if (r > 0) {
|
||||
return coverage(sdRoundRect(p, rect, radii));
|
||||
}
|
||||
float2 c = saturate(min(rect.xy + rect.zw, p + 0.5) - max(rect.xy, p - 0.5));
|
||||
return c.x * c.y;
|
||||
}
|
||||
|
||||
// Frame is where a fragment is in the frame, s, and, when its instance's
|
||||
// map is projective (persp), the columns of the map back, up to a factor.
|
||||
struct Frame {
|
||||
float2 s;
|
||||
float3 c0, c1, c2;
|
||||
bool persp;
|
||||
};
|
||||
Frame frameOf(VSOut v) {
|
||||
Frame f;
|
||||
f.persp = any(v.transform2.xy != 0);
|
||||
// In perspective, the pixel's center; else the frame point of the
|
||||
// local one, which the affine map moves linearly: Direct3D 10's shaders
|
||||
// pass on 16 values at most.
|
||||
f.s = f.persp ? v.pos.xy : float2(dot(v.transform0.xyz, float3(v.pt.xy, 1)), dot(v.transform1.xyz, float3(v.pt.xy, 1)));
|
||||
float3 r0 = v.transform0.xyz, r1 = v.transform1.xyz, r2 = float3(v.transform2.xy, 1 - 2 * v.transform2.z);
|
||||
f.c0 = cross(r1, r2);
|
||||
f.c1 = cross(r2, r0);
|
||||
f.c2 = cross(r0, r1);
|
||||
return f;
|
||||
}
|
||||
// localOf returns the point of the instance that shows at the frame's s.
|
||||
float2 localOf(Frame f, float2 s) {
|
||||
float3 q = f.c0 * s.x + f.c1 * s.y + f.c2;
|
||||
return q.xy / q.z;
|
||||
}
|
||||
// perspectiveCoverage is localCoverage in perspective: each sample where
|
||||
// the CPU renderer takes it.
|
||||
float perspectiveCoverage(float4 rect, float4 radii, Frame fr) {
|
||||
float2 p = localOf(fr, fr.s);
|
||||
float2 a = localOf(fr, fr.s + float2(0.5, 0.5)) - p, b = localOf(fr, fr.s + float2(0.5, -0.5)) - p;
|
||||
float reach = max(abs(a.x) + abs(a.y), abs(b.x) + abs(b.y)) * 2;
|
||||
float d = sdRoundRect(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1;
|
||||
if (d > reach)
|
||||
return 0;
|
||||
float n = 0;
|
||||
[loop] for (int y = 0; y < 4; y++)[loop] for (int x = 0; x < 4; x++) {
|
||||
float2 q = localOf(fr, fr.s + float2((float(x) + 0.5) / 4 - 0.5, (float(y) + 0.5) / 4 - 0.5));
|
||||
n += sdRoundRect(q, rect, radii) <= 0 ? 1 : 0;
|
||||
}
|
||||
return n / 16;
|
||||
}
|
||||
float localCoverage(float2 p, float4 rect, float4 radii, float affine, Frame fr) {
|
||||
if (affine < 0.5)
|
||||
return rectCoverage(p, rect, radii);
|
||||
float2 dx = ddx(p), dy = ddy(p), a = (dx + dy) * 0.5, b = (dx - dy) * 0.5;
|
||||
if (fr.persp)
|
||||
return perspectiveCoverage(rect, radii, fr);
|
||||
float reach = max(abs(a.x) + abs(a.y), abs(b.x) + abs(b.y)) * 2;
|
||||
float d = sdRoundRect(p, rect, radii);
|
||||
if (d < -reach)
|
||||
return 1;
|
||||
if (d > reach)
|
||||
return 0;
|
||||
float n = 0;
|
||||
[loop] for (int y = 0; y < 4; y++)[loop] for (int x = 0; x < 4; x++) {
|
||||
float2 q = p + dx * ((float(x) + 0.5) / 4 - 0.5) + dy * ((float(y) + 0.5) / 4 - 0.5);
|
||||
n += sdRoundRect(q, rect, radii) <= 0 ? 1 : 0;
|
||||
}
|
||||
return n / 16;
|
||||
}
|
||||
float clipCoverage(VSOut i) {
|
||||
Frame fr = frameOf(i);
|
||||
float2 world = fr.s;
|
||||
if (i.transform1.w < 0.5)
|
||||
return rectCoverage(world, i.clip, i.clipRadii);
|
||||
if (i.transform1.w > 1.5)
|
||||
return localCoverage(i.pt.xy, i.clip, float4(0, 0, 0, 0), i.transform0.w, fr) *
|
||||
clipTex.Sample(samp, (world - i.clipRadii.xy) / i.clipRadii.zw).a;
|
||||
return clipTex.Sample(samp, (world - i.clip.xy) / i.clip.zw).a;
|
||||
}
|
||||
float4 sampleLocal(Texture2D t, float2 uv, float4 src, float affine) {
|
||||
if (affine > 0.5) {
|
||||
uint w, h;
|
||||
t.GetDimensions(w, h);
|
||||
float2 halfPixel = 0.5 / float2(w, h);
|
||||
uv = clamp(uv, src.xy + halfPixel, src.zw - halfPixel);
|
||||
}
|
||||
return t.Sample(samp, uv);
|
||||
}
|
||||
|
||||
// sampleImage samples an image held inside src, which is reversed along
|
||||
// an axis it flips, so that a part of a sheet shows none of its
|
||||
// neighbors; where pixelated is set, as pixel art draws, each texel a
|
||||
// square of its color whose edges blend with the next only across the
|
||||
// pixel they cross (Ebitengine's FilterPixelated): nearest where it shows
|
||||
// at whole multiples of its size, and texels of even widths with smooth
|
||||
// edges at any other. dtex is the fwidth of uv, taken where every
|
||||
// fragment of the quad takes it.
|
||||
float4 sampleImage(Texture2D t, float2 uv, float4 src, float pixelated, float2 dtex) {
|
||||
uint w, h;
|
||||
t.GetDimensions(w, h);
|
||||
float2 size = float2(w, h);
|
||||
float2 lo = min(src.xy, src.zw), hi = max(src.xy, src.zw);
|
||||
if (pixelated > 0.5) {
|
||||
float2 tc = uv * size - 0.5;
|
||||
float2 i = floor(tc);
|
||||
float2 f = saturate((tc - i - 0.5) / clamp(dtex * size, 1e-5, 1.0) + 0.5);
|
||||
uv = (i + f + 0.5) / size;
|
||||
}
|
||||
return t.Sample(samp, clamp(uv, lo + 0.5 / size, hi - 0.5 / size));
|
||||
}
|
||||
|
||||
// tint multiplies premultiplied c by straight color t.
|
||||
float4 tint(float4 c, float4 t) { return c * float4(t.rgb * t.a, t.a); }
|
||||
|
||||
float4 premul(float4 c) { return float4(c.rgb * c.a, c.a); }
|
||||
|
||||
float3 unpremul(float4 c) { return c.a > 0 ? c.rgb / c.a : float3(0, 0, 0); }
|
||||
|
||||
// textCoverage corrects the coverage a of a glyph of straight color c as
|
||||
// Direct2D blends text (scene.TextCoverage): it enhances the contrast,
|
||||
// the more the darker c is, and corrects for gamma with the ratios g.
|
||||
float textCoverage(float a, float3 c, float contrast, float boost, float4 g) {
|
||||
float k = contrast * saturate(3 - 4 * dot(c, float3(0.30, 0.59, 0.11))) + boost;
|
||||
a = a * (k + 1) / (a * k + 1);
|
||||
float f = dot(c, float3(0.25, 0.5, 0.25));
|
||||
return saturate(a + a * (1 - a) * ((g.x * f + g.y) * a + (g.z * f + g.w)));
|
||||
}
|
||||
|
||||
// What follows is the renderer's own; effects (effect.hlsl) take what is
|
||||
// above.
|
||||
#ifndef EFFECT
|
||||
|
||||
// The chroma of an image that is a frame of video in NV12, whose luma
|
||||
// imageTex holds (gpu.ImageYUV).
|
||||
Texture2D chromaTex : register(t11);
|
||||
|
||||
// chromaScale is what scales coordinates of the luma to those of the
|
||||
// chroma, which covers twice its size in luma: a column or row more than
|
||||
// an odd size has.
|
||||
float2 chromaScale() {
|
||||
uint lw, lh, cw, ch;
|
||||
imageTex.GetDimensions(lw, lh);
|
||||
chromaTex.GetDimensions(cw, ch);
|
||||
return float2(lw, lh) / (2 * float2(cw, ch));
|
||||
}
|
||||
|
||||
// yuvToRGB converts the samples of a frame of video in YCbCr to RGB, as
|
||||
// scene.YUVMatrix.YUVToRGB does: m is the matrix, 0 to 2 for BT.601, 709
|
||||
// and 2020 in the limited range, plus 3 for the full range.
|
||||
float3 yuvToRGB(float y, float2 c, float m) {
|
||||
float full = m > 2.5 ? 1 : 0;
|
||||
float std = m - 3 * full;
|
||||
float2 k = std < 0.5 ? float2(0.299, 0.114) : std < 1.5 ? float2(0.2126, 0.0722) : float2(0.2627, 0.0593);
|
||||
c -= 128.0 / 255.0;
|
||||
if (full < 0.5) {
|
||||
y = (y - 16.0 / 255.0) * (255.0 / 219.0);
|
||||
c *= 255.0 / 224.0;
|
||||
}
|
||||
float r = y + 2 * (1 - k.x) * c.y;
|
||||
float b = y + 2 * (1 - k.y) * c.x;
|
||||
float g = (y - k.x * r - k.y * b) / (1 - k.x - k.y);
|
||||
return saturate(float3(r, g, b));
|
||||
}
|
||||
|
||||
// subpixelCoverage does the same for each subpixel of a subpixel glyph.
|
||||
float3 subpixelCoverage(float3 a, float3 c, float contrast, float boost, float4 g) {
|
||||
float k = contrast * saturate(3 - 4 * dot(c, float3(0.30, 0.59, 0.11))) + boost;
|
||||
a = a * (k + 1) / (a * k + 1);
|
||||
return saturate(a + a * (1 - a) * ((g.x * c + g.y) * a + (g.z * c + g.w)));
|
||||
}
|
||||
|
||||
float2 erf2(float2 x) {
|
||||
float2 s = sign(x), a = abs(x);
|
||||
x = 1 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
|
||||
x *= x;
|
||||
return s - s / (x * x);
|
||||
}
|
||||
|
||||
float gaussian(float x, float sigma) { return exp(-(x * x) / (2 * sigma * sigma)) / (2.50662827463 * sigma); }
|
||||
|
||||
// The blurred rounded box of Evan Wallace: exact along x, four samples
|
||||
// along y.
|
||||
float shadowX(float x, float y, float sigma, float corner, float2 h) {
|
||||
float delta = min(h.y - corner - abs(y), 0);
|
||||
float curved = h.x - corner + sqrt(max(0, corner * corner - delta * delta));
|
||||
float2 integral = 0.5 + 0.5 * erf2((x + float2(-curved, curved)) * (sqrt(0.5) / sigma));
|
||||
return integral.y - integral.x;
|
||||
}
|
||||
|
||||
float boxShadow(float2 p, float4 rect, float sigma, float corner) {
|
||||
float2 h = rect.zw * 0.5;
|
||||
p -= rect.xy + h;
|
||||
float low = p.y - h.y, high = p.y + h.y;
|
||||
float start = clamp(-3 * sigma, low, high);
|
||||
float end = clamp(3 * sigma, low, high);
|
||||
float step = (end - start) / 4;
|
||||
float y = start + step * 0.5;
|
||||
float v = 0;
|
||||
for (int k = 0; k < 4; k++) {
|
||||
v += shadowX(p.x, p.y - y, sigma, corner, h) * gaussian(y, sigma) * step;
|
||||
y += step;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
float3 toLinear(float3 c) { return c <= 0.04045 ? c / 12.92 : pow((c + 0.055) / 1.055, 2.4); }
|
||||
|
||||
float3 toSRGB(float3 c) { return c <= 0.0031308 ? c * 12.92 : 1.055 * pow(max(c, 0), 1.0 / 2.4) - 0.055; }
|
||||
|
||||
float3 cbrt3(float3 v) { return sign(v) * pow(abs(v), 1.0 / 3.0); }
|
||||
|
||||
float3 oklab(float3 srgb) {
|
||||
float3 c = toLinear(srgb);
|
||||
float3 lms = cbrt3(float3(0.4122214708 * c.r + 0.5363325363 * c.g + 0.0514459929 * c.b,
|
||||
0.2119034982 * c.r + 0.6806995451 * c.g + 0.1073969566 * c.b,
|
||||
0.0883024619 * c.r + 0.2817188376 * c.g + 0.6299787005 * c.b));
|
||||
return float3(0.2104542553 * lms.x + 0.7936177850 * lms.y - 0.0040720468 * lms.z,
|
||||
1.9779984951 * lms.x - 2.4285922050 * lms.y + 0.4505937099 * lms.z,
|
||||
0.0259040371 * lms.x + 0.7827717662 * lms.y - 0.8086757660 * lms.z);
|
||||
}
|
||||
|
||||
float3 fromOklab(float3 lab) {
|
||||
float3 lms = float3(lab.x + 0.3963377774 * lab.y + 0.2158037573 * lab.z,
|
||||
lab.x - 0.1055613458 * lab.y - 0.0638541728 * lab.z,
|
||||
lab.x - 0.0894841775 * lab.y - 1.2914855480 * lab.z);
|
||||
lms = lms * lms * lms;
|
||||
return toSRGB(float3(4.0767416621 * lms.x - 3.3077115913 * lms.y + 0.2309699292 * lms.z,
|
||||
-1.2684380046 * lms.x + 2.6097574011 * lms.y - 0.3413193965 * lms.z,
|
||||
-0.0041960863 * lms.x - 0.7034186147 * lms.y + 1.7076147010 * lms.z));
|
||||
}
|
||||
|
||||
// The stops of the frame's gradients (gpu.Builder.Stops): two texels each,
|
||||
// the color, straight sRGB, then its place and its color in Oklab.
|
||||
Texture2D stopsTex : register(t10);
|
||||
|
||||
// stop returns texel k of the stops.
|
||||
float4 stop(int k) {
|
||||
return stopsTex.Load(int3(k % 1024, k / 1024, 0));
|
||||
}
|
||||
|
||||
// stopsAt returns the color at t of the gradient whose stops stopsTex
|
||||
// holds from first, n of them (gpu.Builder.Stops): the first stop's
|
||||
// before it, the last's after it, and between two the colors of both
|
||||
// mixed, premultiplied, in sRGB, or in Oklab, as internal/raster's stopsAt.
|
||||
float4 stopsAt(float4 c2, float t, bool lab) {
|
||||
int first = int(c2.x);
|
||||
int n = int(c2.y);
|
||||
if (n <= 0) {
|
||||
return float4(0, 0, 0, 0);
|
||||
}
|
||||
float4 a = stop(2 * first);
|
||||
float4 ap = stop(2 * first + 1);
|
||||
if (t <= ap.x) {
|
||||
return premul(a);
|
||||
}
|
||||
float4 last = stop(2 * (first + n - 1));
|
||||
float4 lastp = stop(2 * (first + n - 1) + 1);
|
||||
if (t >= lastp.x) {
|
||||
return premul(last);
|
||||
}
|
||||
float4 b = last;
|
||||
float4 bp = lastp;
|
||||
for (int i = 1; i < n - 1; i++) {
|
||||
float4 c = stop(2 * (first + i));
|
||||
float4 cp = stop(2 * (first + i) + 1);
|
||||
if (t < cp.x) {
|
||||
b = c;
|
||||
bp = cp;
|
||||
break;
|
||||
}
|
||||
a = c;
|
||||
ap = cp;
|
||||
}
|
||||
float f = saturate((t - ap.x) / max(bp.x - ap.x, 1e-6));
|
||||
float alpha = lerp(a.a, b.a, f);
|
||||
if (!lab) {
|
||||
return float4(lerp(a.rgb * a.a, b.rgb * b.a, f), alpha);
|
||||
}
|
||||
if (alpha <= 0) {
|
||||
return float4(0, 0, 0, 0);
|
||||
}
|
||||
return float4(saturate(fromOklab(lerp(ap.yzw * a.a, bp.yzw * b.a, f) / alpha)) * alpha, alpha);
|
||||
}
|
||||
|
||||
// paint returns the premultiplied color at p of plain color, a gradient
|
||||
// mixed in sRGB (1) or Oklab (2), stripes (3), or a gradient of stops,
|
||||
// linear (4, 5), conic (6, 7) or radial (8, 9), mixed in sRGB or in
|
||||
// Oklab, as scene.Paint says.
|
||||
float4 paint(float2 p, float mode, float4 rect, float4 c1, float4 c2, float4 g) {
|
||||
if (mode < 0.5) {
|
||||
return premul(c1);
|
||||
}
|
||||
if (mode > 3.5) {
|
||||
float t;
|
||||
if (mode < 5.5) {
|
||||
float2 d = g.zw - g.xy;
|
||||
t = dot(p - g.xy, d) / max(dot(d, d), 0.0001);
|
||||
} else if (mode < 7.5) {
|
||||
float2 d = p - g.xy;
|
||||
t = (atan2(d.x, -d.y) - g.z) * 0.15915494309189535;
|
||||
t -= floor(t);
|
||||
} else {
|
||||
t = length(p - g.xy) / max(g.z, 0.0001);
|
||||
}
|
||||
return stopsAt(c2, t, mode > 4.5 && mode < 5.5 || mode > 6.5 && mode < 7.5 || mode > 8.5);
|
||||
}
|
||||
if (mode < 2.5) {
|
||||
float2 d = g.zw - g.xy;
|
||||
float t = saturate(dot(p - g.xy, d) / max(dot(d, d), 0.0001));
|
||||
float a = lerp(c1.a, c2.a, t);
|
||||
if (mode < 1.5) {
|
||||
return float4(lerp(c1.rgb * c1.a, c2.rgb * c2.a, t), a);
|
||||
}
|
||||
float3 lab = lerp(oklab(c1.rgb) * c1.a, oklab(c2.rgb) * c2.a, t);
|
||||
return a > 0 ? float4(saturate(fromOklab(lab / a)) * a, a) : float4(0, 0, 0, 0);
|
||||
}
|
||||
float s = dot(p - rect.xy, g.xy);
|
||||
float phase = s - g.w * floor(s / g.w);
|
||||
float cov = coverage(min(max(-phase, phase - g.z), g.w - phase));
|
||||
return premul(c1) * cov + premul(c2) * (1 - cov);
|
||||
}
|
||||
|
||||
// dash returns how much of a dashed border shows at p: each side, which
|
||||
// the pixel belongs to when it is nearest that side's edge in widths of
|
||||
// its border, has an odd number of dashes and gaps of equal length, about
|
||||
// three widths, starting and ending with a dash.
|
||||
float dash(float2 p, float4 rect, float4 w) {
|
||||
float2 q = p - rect.xy;
|
||||
float dt = w.x > 0 ? q.y / w.x : 1e9;
|
||||
float dr = w.y > 0 ? (rect.z - q.x) / w.y : 1e9;
|
||||
float db = w.z > 0 ? (rect.w - q.y) / w.z : 1e9;
|
||||
float dl = w.w > 0 ? q.x / w.w : 1e9;
|
||||
float s, len, bw;
|
||||
if (dt <= dr && dt <= db && dt <= dl) {
|
||||
s = q.x;
|
||||
len = rect.z;
|
||||
bw = w.x;
|
||||
} else if (dr <= db && dr <= dl) {
|
||||
s = q.y;
|
||||
len = rect.w;
|
||||
bw = w.y;
|
||||
} else if (db <= dl) {
|
||||
s = rect.z - q.x;
|
||||
len = rect.z;
|
||||
bw = w.z;
|
||||
} else {
|
||||
s = rect.w - q.y;
|
||||
len = rect.w;
|
||||
bw = w.w;
|
||||
}
|
||||
// n - 1 is how many periods of a dash and a gap, six widths, fit in
|
||||
// len: GPUs divide less exactly than CPUs, and may count one too few
|
||||
// or too many where len is a whole number of periods, as sides often
|
||||
// are, so the count is checked by multiplying back.
|
||||
float n = max(1, floor((len / (3 * bw) + 1) * 0.5 + 0.5));
|
||||
float period = 6 * bw;
|
||||
n += n * period <= len ? 1 : 0;
|
||||
n -= (n - 1) * period > len ? 1 : 0;
|
||||
float seg = len / (2 * n - 1);
|
||||
float k = floor(s / seg);
|
||||
float f = s - k * seg;
|
||||
float edge = min(f, seg - f);
|
||||
return coverage(k - 2 * floor(k * 0.5) < 0.5 ? -edge : edge);
|
||||
}
|
||||
|
||||
PSOut ps(VSOut i) {
|
||||
Frame fr = frameOf(i);
|
||||
float2 dtex = fwidth(i.pt.zw);
|
||||
float kind = i.params.x;
|
||||
float4 res;
|
||||
float glyphCov = i.transform0.w > 0.5 ? localCoverage(i.pt.xy, i.rect, float4(0, 0, 0, 0), 1, fr) : 1;
|
||||
if (kind < 0.5) {
|
||||
float outer = localCoverage(i.pt.xy, i.rect, i.radii, i.transform0.w, fr);
|
||||
// params.y: 1 dashes the border, 2 paints it with the gradient (the
|
||||
// inside with plain color), 3 both.
|
||||
bool borderPaint = i.params.y > 1.5;
|
||||
float4 pc = paint(i.pt.xy, i.params.z, i.rect, i.color, i.color2, i.grad);
|
||||
res = (borderPaint ? premul(i.color) : pc) * outer;
|
||||
float4 bw = i.widths; // top, right, bottom, left
|
||||
if (any(bw > 0)) {
|
||||
float4 ir = float4(i.rect.xy + bw.wx, i.rect.zw - bw.yz - bw.wx);
|
||||
float innerCov = (ir.z > 0 && ir.w > 0) ? localCoverage(i.pt.xy, ir, i.inner, i.transform0.w, fr) : 0;
|
||||
float bc = saturate(outer - innerCov);
|
||||
float dashed = i.params.y - (borderPaint ? 2 : 0);
|
||||
if (dashed > 0.5) {
|
||||
bc *= dash(i.pt.xy, i.rect, bw);
|
||||
}
|
||||
float4 b = (borderPaint ? pc * float4(i.border.rgb * i.border.a, i.border.a) : premul(i.border)) * bc;
|
||||
res = b + res * (1 - b.a);
|
||||
}
|
||||
} else if (kind < 1.5 && i.params.y > 0.5) {
|
||||
// An inner shadow: inside the box, what the hole, blurred, leaves.
|
||||
float sigma = i.params.z;
|
||||
float hole = 0;
|
||||
if (i.widths.z > 0 && i.widths.w > 0) {
|
||||
float corner = max(max(i.inner.x, i.inner.y), max(i.inner.z, i.inner.w));
|
||||
hole = sigma > 0 ? boxShadow(i.pt.xy, i.widths, sigma, corner)
|
||||
: localCoverage(i.pt.xy, i.widths, i.inner, i.transform0.w, fr);
|
||||
}
|
||||
res = premul(i.color) * (localCoverage(i.pt.xy, i.rect, i.radii, i.transform0.w, fr) * (1 - hole));
|
||||
} else if (kind < 1.5) {
|
||||
float sigma = i.params.z;
|
||||
float corner = max(max(i.radii.x, i.radii.y), max(i.radii.z, i.radii.w));
|
||||
float s = sigma > 0 ? boxShadow(i.pt.xy, i.rect, sigma, corner)
|
||||
: localCoverage(i.pt.xy, i.rect, i.radii, i.transform0.w, fr);
|
||||
if (i.widths.z > 0 && i.widths.w > 0) {
|
||||
s *= 1 - localCoverage(i.pt.xy, i.widths, i.inner, i.transform0.w, fr); // outside the box casting it
|
||||
}
|
||||
res = premul(i.color) * s;
|
||||
} else if (kind < 2.5) {
|
||||
float4 c = paint(i.pt.xy, i.params.z, i.rect, i.color, i.color2, i.grad);
|
||||
res = c *
|
||||
textCoverage(sampleLocal(maskTex, i.pt.zw, i.widths, i.transform0.w).r, unpremul(c), i.inner.x,
|
||||
i.inner.y, i.radii) *
|
||||
glyphCov;
|
||||
} else if (kind < 3.5) {
|
||||
res = sampleLocal(colorTex, i.pt.zw, i.widths, i.transform0.w) * i.color.a * glyphCov;
|
||||
} else if (kind < 4.5) {
|
||||
if (i.params.y > 1.5) {
|
||||
// A frame of video: its luma and its chroma, converted.
|
||||
float code = i.params.y - 2;
|
||||
float gray = code > 7.5 ? 1 : 0;
|
||||
float2 cs = chromaScale();
|
||||
res = float4(yuvToRGB(sampleImage(imageTex, i.pt.zw, i.widths, i.params.z, dtex).r,
|
||||
sampleImage(chromaTex, i.pt.zw * cs, i.widths * cs.xyxy, i.params.z, dtex * cs).rg,
|
||||
code - 8 * gray),
|
||||
1);
|
||||
if (gray > 0.5) {
|
||||
res.rgb = dot(res.rgb, float3(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
} else {
|
||||
res = sampleImage(imageTex, i.pt.zw, i.widths, i.params.z, dtex);
|
||||
if (i.params.y > 0.5) {
|
||||
res.rgb = dot(res.rgb, float3(0.2126, 0.7152, 0.0722));
|
||||
}
|
||||
}
|
||||
res = tint(res, i.color) * localCoverage(i.pt.xy, i.rect, i.radii, i.transform0.w, fr);
|
||||
} else {
|
||||
float4 c = paint(i.pt.xy, i.params.z, i.rect, i.color, i.color2, i.grad);
|
||||
float3 straight = unpremul(c);
|
||||
if (i.transform0.w > 0.5) {
|
||||
float3 rgb = sampleLocal(colorTex, i.pt.zw, i.widths, 1).rgb;
|
||||
res = c * textCoverage((rgb.r + rgb.g + rgb.b) / 3, straight, i.inner.x, i.inner.y, i.radii) *
|
||||
glyphCov;
|
||||
PSOut gray;
|
||||
gray.color = res * clipCoverage(i) * i.params.w;
|
||||
gray.alpha = gray.color.aaaa;
|
||||
return gray;
|
||||
}
|
||||
float3 a = subpixelCoverage(sampleLocal(colorTex, i.pt.zw, i.widths, i.transform0.w).rgb, straight,
|
||||
i.inner.x, i.inner.y, i.radii);
|
||||
float3 w = a * c.a * clipCoverage(i) * i.params.w;
|
||||
float wa = (w.r + w.g + w.b) / 3;
|
||||
PSOut so;
|
||||
so.color = float4(straight * w, wa);
|
||||
so.alpha = float4(w, wa);
|
||||
return so;
|
||||
}
|
||||
float clip = clipCoverage(i);
|
||||
PSOut o;
|
||||
o.color = res * (clip * i.params.w);
|
||||
o.alpha = o.color.aaaa;
|
||||
return o;
|
||||
}
|
||||
|
||||
// The passes computing the backdrop of an effect draw a quad over their
|
||||
// target, scissored to the texels they compute.
|
||||
cbuffer PassConstants : register(b1) {
|
||||
int2 passOrigin; // down: the first pixel of the area read, in the frame
|
||||
int2 passLimit; // the last texel that may be read: in the frame for down
|
||||
int2 passShift; // down: subtracted from frame pixels to read the source
|
||||
int2 passDir; // blur: along rows (1, 0) or columns (0, 1)
|
||||
int passDown; // down: the size of the squares averaged
|
||||
int passRadius; // blur: how far it reaches each way
|
||||
float passSigma; // blur: its standard deviation, 0 for none
|
||||
int passMode; // 1: transparent beyond the area or the texels (gpu.PassClear)
|
||||
};
|
||||
|
||||
Texture2D passSrc : register(t4);
|
||||
|
||||
float4 passvs(uint vid : SV_VertexID) : SV_Position {
|
||||
float2 corner = float2(vid & 1, vid >> 1);
|
||||
return float4(corner * 2 - 1, 0, 1);
|
||||
}
|
||||
|
||||
// down averages the square of the area that texel stands for, repeating
|
||||
// the area's last pixels past its far edges, or, for an image blurred
|
||||
// (mode 1), reading them as transparent.
|
||||
float4 downps(float4 pos : SV_Position) : SV_Target {
|
||||
int2 o = passOrigin + int2(pos.xy) * passDown;
|
||||
float4 c = float4(0, 0, 0, 0);
|
||||
for (int y = 0; y < passDown; y++) {
|
||||
for (int x = 0; x < passDown; x++) {
|
||||
int2 at = o + int2(x, y);
|
||||
if ((passMode & 1) != 0 && (at.x > passLimit.x || at.y > passLimit.y)) {
|
||||
continue;
|
||||
}
|
||||
c += passSrc.Load(int3(min(at, passLimit) - passShift, 0));
|
||||
}
|
||||
}
|
||||
return c * (1.0 / float(passDown * passDown));
|
||||
}
|
||||
|
||||
// blur blurs along a row or a column, clamping at its ends, or, for an
|
||||
// image blurred (mode 1), transparent beyond them.
|
||||
float4 blurps(float4 pos : SV_Position) : SV_Target {
|
||||
int2 at = int2(pos.xy);
|
||||
float4 c = float4(0, 0, 0, 0);
|
||||
float sum = 0;
|
||||
for (int o = -passRadius; o <= passRadius; o++) {
|
||||
float x = float(o);
|
||||
float w = passSigma > 0 ? exp(-(x * x) / (2 * passSigma * passSigma)) : 1;
|
||||
int2 q = at + passDir * o;
|
||||
sum += w;
|
||||
if ((passMode & 1) != 0 && (any(q < int2(0, 0)) || any(q > passLimit))) {
|
||||
continue;
|
||||
}
|
||||
c += passSrc.Load(int3(clamp(q, int2(0, 0), passLimit), 0)) * w;
|
||||
}
|
||||
return c / sum;
|
||||
}
|
||||
|
||||
#endif
|
||||
+18851
File diff suppressed because it is too large.
Load diff
+281
@@ -0,0 +1,281 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu"
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11/device"
|
||||
)
|
||||
|
||||
// The renderers of a process share one Direct3D 11 device and its
|
||||
// immediate context (#1517): a device costs the driver tens of megabytes,
|
||||
// which a device for each window would cost each window. So do what never
|
||||
// changes once made, the shaders, the input layout and the states, while
|
||||
// each renderer keeps its swap chain and what its frames change: its
|
||||
// buffers, textures and queries. The device goes with the last renderer
|
||||
// holding it.
|
||||
//
|
||||
// Renderers draw on the main thread, one frame at a time, so the context
|
||||
// they share needs no lock of theirs, and each frame binds all the state it
|
||||
// draws with. The device is multithread protected all the same
|
||||
// (ID3D10Multithread): Direct3D then serializes each call to the context
|
||||
// with DXGI's calls on the device's swap chains, so that a swap chain may
|
||||
// present or resize its buffers on another thread while other windows draw.
|
||||
//
|
||||
// When the GPU device is removed (a driver update, a GPU reset), a
|
||||
// renderer's next present fails and the window makes another renderer
|
||||
// (ui's windowHost.render): the first one made finds the device removed
|
||||
// and makes a new one, which the renderers made after it share. The others
|
||||
// find the device they hold replaced as they next draw (Render), and fail
|
||||
// so that their windows make them again on the new one, as they would on
|
||||
// a device of their own that failed. A device made with WARP, for want of
|
||||
// a GPU, is replaced the same way as a renderer is made once the GPU can
|
||||
// make one again, as ui does from time to time while drawing in software.
|
||||
|
||||
// sharedDevice is the device renderers share, with what they draw with
|
||||
// that never changes.
|
||||
type sharedDevice struct {
|
||||
device, ctx, ctx1, factory uintptr
|
||||
warp bool
|
||||
// refs counts the renderers holding the device.
|
||||
refs int
|
||||
|
||||
vs, ps, layout uintptr
|
||||
blend, holeBlend, overBlend, overHoleBlend uintptr
|
||||
raster, samp uintptr
|
||||
passVS, downPS, blurPS uintptr
|
||||
classes [1 << gpu.NumClasses]*classPipe
|
||||
compileClasses bool
|
||||
}
|
||||
|
||||
// devices holds the device new renderers share, nil before the first or
|
||||
// after the last renderer released it, or when it was found removed.
|
||||
var devices struct {
|
||||
sync.Mutex
|
||||
current *sharedDevice
|
||||
}
|
||||
|
||||
// errDeviceReplaced is Render's error for a renderer whose device another
|
||||
// one replaced, removed or drawing with WARP.
|
||||
var errDeviceReplaced = errors.New("d3d11: the device shared by the windows was made again")
|
||||
|
||||
// deviceRemoved reports whether the GPU device of d was removed; tests
|
||||
// replace it.
|
||||
var deviceRemoved = func(d *sharedDevice) bool {
|
||||
const devGetDeviceRemovedReason = 39
|
||||
return call(d.device, devGetDeviceRemovedReason) != 0
|
||||
}
|
||||
|
||||
// newDeviceOnGPU makes a device on the GPU only, for one drawing with WARP
|
||||
// to be replaced; tests replace it.
|
||||
var newDeviceOnGPU = device.NewOnGPU
|
||||
|
||||
// acquireDevice returns the device new renderers share, which the caller
|
||||
// releases with releaseDevice: the current one, or a new one where there
|
||||
// is none, it was removed, or it draws with WARP and the GPU can make one
|
||||
// now.
|
||||
func acquireDevice() (*sharedDevice, error) {
|
||||
devices.Lock()
|
||||
defer devices.Unlock()
|
||||
d := devices.current
|
||||
if d != nil && deviceRemoved(d) {
|
||||
devices.current, d = nil, nil
|
||||
}
|
||||
if d != nil && d.warp {
|
||||
if dev, ctx, err := newDeviceOnGPU(); err == nil {
|
||||
if n, err := newSharedDevice(dev, ctx, false); err == nil {
|
||||
devices.current, d = n, n
|
||||
}
|
||||
}
|
||||
}
|
||||
if d == nil {
|
||||
dev, ctx, warp, err := device.New()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d, err = newSharedDevice(dev, ctx, warp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
devices.current = d
|
||||
}
|
||||
d.refs++
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// releaseDevice lets go of d, freeing it with the last renderer holding it.
|
||||
func releaseDevice(d *sharedDevice) {
|
||||
devices.Lock()
|
||||
defer devices.Unlock()
|
||||
if d.refs--; d.refs > 0 {
|
||||
return
|
||||
}
|
||||
if devices.current == d {
|
||||
devices.current = nil
|
||||
}
|
||||
d.free()
|
||||
}
|
||||
|
||||
// replaced reports whether renderers made now share another device than d.
|
||||
func (d *sharedDevice) replaced() bool {
|
||||
devices.Lock()
|
||||
defer devices.Unlock()
|
||||
return devices.current != d
|
||||
}
|
||||
|
||||
// newSharedDevice makes what renderers draw with on the device dev, whose
|
||||
// immediate context is ctx; it releases both when it fails.
|
||||
func newSharedDevice(dev, ctx uintptr, warp bool) (*sharedDevice, error) {
|
||||
d := &sharedDevice{device: dev, ctx: ctx, warp: warp}
|
||||
if err := d.init(); err != nil {
|
||||
d.free()
|
||||
return nil, err
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
var iidID3D10Multithread = guid{0x9b7e4e00, 0x342c, 0x4106, [8]byte{0xa1, 0x9f, 0x4f, 0x27, 0x04, 0xf6, 0x89, 0xf0}}
|
||||
|
||||
func (d *sharedDevice) init() error {
|
||||
const setMultithreadProtected = 5 // ID3D10Multithread
|
||||
var mt uintptr
|
||||
if !failed(call(d.device, 0, uintptr(unsafe.Pointer(&iidID3D10Multithread)), uintptr(unsafe.Pointer(&mt)))) {
|
||||
call(mt, setMultithreadProtected, 1)
|
||||
free(&mt)
|
||||
}
|
||||
// The factory that made the device's adapter makes the swap chains.
|
||||
var dxgiDev, adapter uintptr
|
||||
if failed(call(d.device, 0, uintptr(unsafe.Pointer(&iidIDXGIDevice)), uintptr(unsafe.Pointer(&dxgiDev)))) {
|
||||
return errors.New("d3d11: no DXGI device")
|
||||
}
|
||||
defer free(&dxgiDev)
|
||||
// One frame queued ahead of the screen, not three: a frame shows the
|
||||
// input of when it was drawn while frames follow each other, as when
|
||||
// scrolling or animating.
|
||||
var dxgiDev1 uintptr
|
||||
if !failed(call(d.device, 0, uintptr(unsafe.Pointer(&iidIDXGIDevice1)), uintptr(unsafe.Pointer(&dxgiDev1)))) {
|
||||
call(dxgiDev1, dxgiDevSetMaxLatency, 1)
|
||||
free(&dxgiDev1)
|
||||
}
|
||||
if noPartial || failed(call(d.ctx, 0, uintptr(unsafe.Pointer(&iidID3D11DeviceContext1)), uintptr(unsafe.Pointer(&d.ctx1)))) {
|
||||
d.ctx1 = 0
|
||||
}
|
||||
if failed(call(dxgiDev, dxgiDevGetAdapter, uintptr(unsafe.Pointer(&adapter)))) {
|
||||
return errors.New("d3d11: no adapter")
|
||||
}
|
||||
defer free(&adapter)
|
||||
if failed(call(adapter, dxgiGetParent, uintptr(unsafe.Pointer(&iidIDXGIFactory2)), uintptr(unsafe.Pointer(&d.factory)))) {
|
||||
return errors.New("d3d11: DXGI 1.2 is required")
|
||||
}
|
||||
|
||||
// The shaders compiled ahead of time, or from shader.hlsl when they are
|
||||
// older or a test asks (compileShaders), as the device is made.
|
||||
code, err := shaderCode()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.compileClasses = sourceSum() != shaderSum || compileShaders
|
||||
vsCode := code.vs
|
||||
for _, s := range []struct {
|
||||
code []byte
|
||||
out *uintptr
|
||||
vtbl int
|
||||
name string
|
||||
}{{code.vs, &d.vs, devCreateVertexShader, "vertex"}, {code.ps, &d.ps, devCreatePixelShader, "pixel"},
|
||||
{code.passVS, &d.passVS, devCreateVertexShader, "pass vertex"}, {code.down, &d.downPS, devCreatePixelShader, "down"},
|
||||
{code.blur, &d.blurPS, devCreatePixelShader, "blur"}} {
|
||||
if len(s.code) == 0 || failed(call(d.device, s.vtbl, uintptr(unsafe.Pointer(&s.code[0])), uintptr(len(s.code)), 0, uintptr(unsafe.Pointer(s.out)))) {
|
||||
return fmt.Errorf("d3d11: cannot create the %s shader", s.name)
|
||||
}
|
||||
}
|
||||
names := []string{"RECT", "RADII", "INNER", "COLOR", "COLOR", "COLOR", "GRAD", "UV", "CLIP", "CLIPR", "PARAMS", "TRANSFORM", "TRANSFORM", "TRANSFORM"}
|
||||
indices := []uint32{0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 1, 2}
|
||||
elems := make([]inputElement, len(names))
|
||||
cstr := make([][]byte, len(names))
|
||||
for i, n := range names {
|
||||
cstr[i] = append([]byte(n), 0)
|
||||
elems[i] = inputElement{SemanticName: &cstr[i][0], SemanticIndex: indices[i], Format: formatR32G32B32A32Float,
|
||||
AlignedByteOffset: uint32(16 * i), InputSlotClass: 1, InstanceDataStepRate: 1}
|
||||
}
|
||||
if failed(call(d.device, devCreateInputLayout, uintptr(unsafe.Pointer(&elems[0])), uintptr(len(elems)),
|
||||
uintptr(unsafe.Pointer(&vsCode[0])), uintptr(len(vsCode)), uintptr(unsafe.Pointer(&d.layout)))) {
|
||||
return errors.New("d3d11: cannot create the input layout")
|
||||
}
|
||||
|
||||
// Dual-source blending: the destination times one minus the shader's
|
||||
// second color, the source's alpha of each channel (D3D11_BLEND_ONE,
|
||||
// D3D11_BLEND_INV_SRC1_COLOR and D3D11_BLEND_INV_SRC1_ALPHA).
|
||||
bd := blendDesc{}
|
||||
bd.RenderTarget[0] = rtBlend{BlendEnable: 1, SrcBlend: 2, DestBlend: 17, BlendOp: 1, SrcBlendAlpha: 2, DestBlendAlpha: 19, BlendOpAlpha: 1, WriteMask: 0xf}
|
||||
if failed(call(d.device, devCreateBlendState, uintptr(unsafe.Pointer(&bd)), uintptr(unsafe.Pointer(&d.blend)))) {
|
||||
return errors.New("d3d11: cannot create the blend state")
|
||||
}
|
||||
// Holes take none of the source (D3D11_BLEND_ZERO).
|
||||
bd.RenderTarget[0].SrcBlend, bd.RenderTarget[0].SrcBlendAlpha = 1, 1
|
||||
if failed(call(d.device, devCreateBlendState, uintptr(unsafe.Pointer(&bd)), uintptr(unsafe.Pointer(&d.holeBlend)))) {
|
||||
return errors.New("d3d11: cannot create the blend state of holes")
|
||||
}
|
||||
// One color: its alpha is the source's (D3D11_BLEND_INV_SRC_ALPHA).
|
||||
bd.RenderTarget[0].SrcBlend, bd.RenderTarget[0].DestBlend, bd.RenderTarget[0].SrcBlendAlpha, bd.RenderTarget[0].DestBlendAlpha = 2, 6, 2, 6
|
||||
if failed(call(d.device, devCreateBlendState, uintptr(unsafe.Pointer(&bd)), uintptr(unsafe.Pointer(&d.overBlend)))) {
|
||||
return errors.New("d3d11: cannot create the blend state of one color")
|
||||
}
|
||||
bd.RenderTarget[0].SrcBlend, bd.RenderTarget[0].SrcBlendAlpha = 1, 1
|
||||
if failed(call(d.device, devCreateBlendState, uintptr(unsafe.Pointer(&bd)), uintptr(unsafe.Pointer(&d.overHoleBlend)))) {
|
||||
return errors.New("d3d11: cannot create the blend state of holes of one color")
|
||||
}
|
||||
rd := rasterizerDesc{FillMode: 3, CullMode: 1, DepthClip: 1, Scissor: 1}
|
||||
if failed(call(d.device, devCreateRasterizerState, uintptr(unsafe.Pointer(&rd)), uintptr(unsafe.Pointer(&d.raster)))) {
|
||||
return errors.New("d3d11: cannot create the rasterizer state")
|
||||
}
|
||||
sd := samplerDesc{Filter: 0x15, AddressU: 3, AddressV: 3, AddressW: 3, ComparisonFunc: 1, MaxLOD: math.MaxFloat32}
|
||||
if failed(call(d.device, devCreateSamplerState, uintptr(unsafe.Pointer(&sd)), uintptr(unsafe.Pointer(&d.samp)))) {
|
||||
return errors.New("d3d11: cannot create the sampler")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *sharedDevice) free() {
|
||||
if d.ctx != 0 {
|
||||
call(d.ctx, ctxClearState)
|
||||
call(d.ctx, ctxFlush)
|
||||
}
|
||||
for _, s := range classShaders {
|
||||
if p := d.classes[s.classes]; p != nil {
|
||||
free(&p.vs)
|
||||
free(&p.ps)
|
||||
}
|
||||
}
|
||||
d.classes = [len(d.classes)]*classPipe{}
|
||||
for _, p := range []*uintptr{&d.samp, &d.raster, &d.overHoleBlend, &d.overBlend, &d.holeBlend, &d.blend, &d.layout,
|
||||
&d.blurPS, &d.downPS, &d.passVS, &d.ps, &d.vs, &d.factory, &d.ctx1, &d.ctx, &d.device} {
|
||||
free(p)
|
||||
}
|
||||
}
|
||||
|
||||
// useDevice has r draw on d, with what d holds.
|
||||
func (r *Renderer) useDevice(d *sharedDevice) {
|
||||
r.dev = d
|
||||
r.device, r.ctx, r.ctx1, r.factory, r.warp = d.device, d.ctx, d.ctx1, d.factory, d.warp
|
||||
r.vs, r.ps, r.layout = d.vs, d.ps, d.layout
|
||||
r.blend, r.holeBlend, r.overBlend, r.overHoleBlend = d.blend, d.holeBlend, d.overBlend, d.overHoleBlend
|
||||
r.raster, r.samp = d.raster, d.samp
|
||||
r.passVS, r.downPS, r.blurPS = d.passVS, d.downPS, d.blurPS
|
||||
r.classes, r.compileClasses = &d.classes, d.compileClasses
|
||||
}
|
||||
|
||||
// dropDevice has r let go of its device, which it no longer draws on.
|
||||
func (r *Renderer) dropDevice() {
|
||||
if r.dev == nil {
|
||||
return
|
||||
}
|
||||
d := r.dev
|
||||
r.useDevice(&sharedDevice{})
|
||||
r.dev, r.classes = nil, nil
|
||||
releaseDevice(d)
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11/device"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// newRendererFor makes a renderer drawing s into a window of its own.
|
||||
func newRendererFor(t *testing.T, s *scene.Scene) *Renderer {
|
||||
t.Helper()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// drawAndCompare draws s whole with r, requires the CPU renderer's pixels,
|
||||
// and presents it.
|
||||
func drawAndCompare(t *testing.T, name string, r *Renderer, s *scene.Scene) {
|
||||
t.Helper()
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, name, pix, stride, s)
|
||||
if err := r.present(1); err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRenderersShareTheDevice checks that the renderers of two windows draw
|
||||
// on one device and its context, with the same shaders and states, each
|
||||
// into its own swap chain, their frames taking turns; that one released
|
||||
// leaves the other drawing; and that the device goes with the last.
|
||||
func TestRenderersShareTheDevice(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s1, s2 := gputest.Scene(), gputest.CornerClipScene()
|
||||
r1 := newRendererFor(t, s1)
|
||||
r2 := newRendererFor(t, s2)
|
||||
defer r2.Release()
|
||||
if r1.dev != r2.dev || r1.device != r2.device || r1.ctx != r2.ctx {
|
||||
r1.Release()
|
||||
t.Fatal("the renderers of two windows draw on devices of their own")
|
||||
}
|
||||
d := r1.dev
|
||||
if d.refs != 2 {
|
||||
t.Errorf("the device counts %d renderers, want 2", d.refs)
|
||||
}
|
||||
if r1.vs != r2.vs || r1.ps != r2.ps || r1.layout != r2.layout || r1.blend != r2.blend || r1.samp != r2.samp || r1.classes != r2.classes {
|
||||
t.Error("the renderers do not share the shaders and states of their device")
|
||||
}
|
||||
if r1.cbuf == r2.cbuf || r1.passCB == r2.passCB {
|
||||
t.Error("the renderers share the buffers their frames change")
|
||||
}
|
||||
for frame := range 2 {
|
||||
drawAndCompare(t, "d3d11 shared, first window", r1, s1)
|
||||
drawAndCompare(t, "d3d11 shared, second window", r2, s2)
|
||||
if frame == 0 {
|
||||
// The swap chains are made with the first frame.
|
||||
if r1.swapChain == 0 || r2.swapChain == 0 {
|
||||
t.Fatal("no swap chain")
|
||||
}
|
||||
if r1.swapChain == r2.swapChain {
|
||||
t.Error("the renderers share a swap chain")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
r1.Release()
|
||||
if d.refs != 1 || d.device == 0 || r2.device != d.device {
|
||||
t.Fatalf("releasing a renderer freed the device the other draws on (%d renderers)", d.refs)
|
||||
}
|
||||
for range 2 {
|
||||
drawAndCompare(t, "d3d11 shared, after the other window closed", r2, s2)
|
||||
}
|
||||
if r2.dev.replaced() {
|
||||
t.Error("the device of the remaining renderer counts as replaced")
|
||||
}
|
||||
|
||||
r2.Release()
|
||||
if d.refs != 0 || d.device != 0 {
|
||||
t.Errorf("the device outlives its last renderer (%d renderers)", d.refs)
|
||||
}
|
||||
devices.Lock()
|
||||
current := devices.current
|
||||
devices.Unlock()
|
||||
if current != nil {
|
||||
t.Error("new renderers would share a device no renderer holds")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemovedDeviceIsMadeAgain checks that a renderer made after the device
|
||||
// was removed, as one a window makes after a failed frame, makes a new
|
||||
// device, which the renderers made after it share; that the renderers
|
||||
// holding the old one fail their next frame, so that their windows make
|
||||
// them again, on the new one; and that the old device goes with the last of
|
||||
// them.
|
||||
func TestRemovedDeviceIsMadeAgain(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s1, s2 := gputest.Scene(), gputest.CornerClipScene()
|
||||
r1 := newRendererFor(t, s1)
|
||||
r2 := newRendererFor(t, s2)
|
||||
old := r1.dev
|
||||
defer func(f func(*sharedDevice) bool) { deviceRemoved = f }(deviceRemoved)
|
||||
deviceRemoved = func(d *sharedDevice) bool { return d == old }
|
||||
|
||||
// The first window to fail makes its renderer again.
|
||||
if err := r1.Render(s1); err != nil {
|
||||
t.Fatalf("a frame failed before the device was replaced: %v", err)
|
||||
}
|
||||
r1.Release()
|
||||
r1 = newRendererFor(t, s1)
|
||||
defer r1.Release()
|
||||
if r1.dev == old {
|
||||
t.Fatal("a renderer made after the device was removed draws on it")
|
||||
}
|
||||
if old.refs != 1 || old.device == 0 {
|
||||
t.Fatalf("the removed device has %d renderers", old.refs)
|
||||
}
|
||||
drawAndCompare(t, "d3d11 on the device made again", r1, s1)
|
||||
|
||||
// The other window's next frame fails, and its renderer made again
|
||||
// shares the new device.
|
||||
if err := r2.Render(s2); !errors.Is(err, errDeviceReplaced) {
|
||||
t.Fatalf("a frame on the removed device: %v, want %v", err, errDeviceReplaced)
|
||||
}
|
||||
r2.Release()
|
||||
if old.refs != 0 || old.device != 0 {
|
||||
t.Errorf("the removed device outlives its last renderer (%d renderers)", old.refs)
|
||||
}
|
||||
r2 = newRendererFor(t, s2)
|
||||
defer r2.Release()
|
||||
if r2.dev != r1.dev {
|
||||
t.Fatal("the renderers made again draw on devices of their own")
|
||||
}
|
||||
drawAndCompare(t, "d3d11 made again, first window", r1, s1)
|
||||
drawAndCompare(t, "d3d11 made again, second window", r2, s2)
|
||||
if r1.dev.refs != 2 {
|
||||
t.Errorf("the new device counts %d renderers, want 2", r1.dev.refs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeviceOnWARPGivesWayToTheGPU checks that renderers share a device
|
||||
// made with WARP while the GPU can make none, and that a renderer made once
|
||||
// it can makes a device on it, which the renderers on WARP then give way
|
||||
// to, as a window drawing in software tries for the GPU from time to time.
|
||||
func TestDeviceOnWARPGivesWayToTheGPU(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
defer func(f func() (uintptr, uintptr, error)) { newDeviceOnGPU = f }(newDeviceOnGPU)
|
||||
s := gputest.Scene()
|
||||
r1 := newRendererFor(t, s)
|
||||
defer func() { r1.Release() }()
|
||||
if r1.dev.warp {
|
||||
t.Skip("no GPU: the device is WARP's")
|
||||
}
|
||||
// It stands for a device made with WARP.
|
||||
r1.dev.warp = true
|
||||
|
||||
newDeviceOnGPU = func() (uintptr, uintptr, error) { return 0, 0, errors.New("no GPU") }
|
||||
r2 := newRendererFor(t, s)
|
||||
if r2.dev != r1.dev {
|
||||
r2.Release()
|
||||
t.Fatal("a renderer made while the GPU can make no device does not share the one on WARP")
|
||||
}
|
||||
r2.Release()
|
||||
|
||||
newDeviceOnGPU = device.NewOnGPU
|
||||
r2 = newRendererFor(t, s)
|
||||
defer r2.Release()
|
||||
if r2.dev == r1.dev || r2.dev.warp {
|
||||
t.Fatal("a renderer made once the GPU can make a device draws with WARP")
|
||||
}
|
||||
drawAndCompare(t, "d3d11 back on the GPU", r2, s)
|
||||
if err := r1.Render(s); !errors.Is(err, errDeviceReplaced) {
|
||||
t.Fatalf("a frame on WARP once the GPU is back: %v, want %v", err, errDeviceReplaced)
|
||||
}
|
||||
r1.Release()
|
||||
r1 = newRendererFor(t, s)
|
||||
if r1.dev != r2.dev {
|
||||
t.Fatal("a renderer made again after drawing with WARP does not share the device on the GPU")
|
||||
}
|
||||
}
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Uncapped (MYGO_UNCAPPED, package pacing), a frame presents as soon as it
|
||||
// is drawn, and the next draws at once: the swap chain is made without the
|
||||
// frame latency object, so that no frame waits for the screen to have room
|
||||
// (latency.go), and every frame presents with sync interval 0, none waiting
|
||||
// for DWM to compose the last (waitComposed) nor, when it changed nothing,
|
||||
// for the next refresh (waitRefresh). Where the system shows frames torn
|
||||
// (DXGI_FEATURE_PRESENT_ALLOW_TEARING, Windows 10 1703 on with a driver
|
||||
// that can), the window's swap chain allows tearing and its frames present
|
||||
// with it, flipping to the screen mid-refresh once DWM gives the window the
|
||||
// display (independent flip, as a borderless window covering the screen
|
||||
// has); a window DWM composes still shows the newest frame at each refresh.
|
||||
// A swap chain for composition (NewComposed) has no tearing: its frames
|
||||
// present with sync interval 0 all the same.
|
||||
//
|
||||
// While the window changes size, from its first change until the swap
|
||||
// chain settles (resize, settleDelay), frames present paced
|
||||
// (presentsUncapped), as without MYGO_UNCAPPED: none with tearing, a frame
|
||||
// of a new size waiting for DWM to show it (Render, waitShown), the others
|
||||
// each waiting for the composition that shows it (waitComposed), and one
|
||||
// that changed nothing for the next refresh (waitRefresh). Uncapped, a live
|
||||
// resize had one present take 2 s, on a Radeon 780M and a 59 Hz display,
|
||||
// with the window resized every 50 ms while it animated, and frames then
|
||||
// came at 92 to 95 a second, about two a composition besides the resize's,
|
||||
// where paced frames took no more than a refresh. The resize's buffers are
|
||||
// larger than the window and shown clipped, so DWM composes the window and
|
||||
// flips none of its frames to the screen torn: frames presented faster than
|
||||
// DWM composes only queue for it, filling the buffers, while DWM resizes the
|
||||
// window, and the frame of the next size, which waits for DWM to show it,
|
||||
// waits behind them. Paced, at most one frame a composition reaches DWM.
|
||||
// Before ResizeBuffers, no view of the buffers stays bound (unbindBuffers),
|
||||
// as DXGI asks.
|
||||
//
|
||||
// Unlike a paced frame of a new size, which calls DwmFlush on the main
|
||||
// thread and returns once DWM composed, an uncapped one waits for DWM at
|
||||
// most two refreshes, DwmFlush called on another thread (awaitRefresh,
|
||||
// shared with waitComposed's): every wait of an uncapped frame on DWM is
|
||||
// bounded. With that wait unbounded, a resize the app made with
|
||||
// SetWindowPos every 50 ms still had one present take 2.0 s, at its first
|
||||
// frame or after its last change, on the Radeon 780M, though its other
|
||||
// frames presented paced, while the same resize without MYGO_UNCAPPED,
|
||||
// and a drag of the window's edge uncapped, had none. The frame of a new size draws
|
||||
// within SetWindowPos (WM_SIZE), and its DwmFlush was the only wait of an
|
||||
// uncapped frame with no bound: it returns at DWM's next composition,
|
||||
// which frames flipped to the screen torn, as the uncapped ones before the
|
||||
// resize, do not bring about, and DWM may itself wait on the window's
|
||||
// thread while the window changes size; 2 s exactly looks like the end of
|
||||
// such a wait. A frame that waits for DWM no longer than two refreshes,
|
||||
// and then returns to the window's messages, leaves DWM nothing to wait
|
||||
// on, and a composition missed costs it two refreshes.
|
||||
//
|
||||
// Nor does Present itself wait long on the main thread while the window
|
||||
// changes size. With the frame of a new size's wait bounded, the
|
||||
// SetWindowPos resize still had one present take 2.0 s in 2 runs of 12 on
|
||||
// the Radeon 780M, once a second into the resize and once after its last
|
||||
// change, both of a frame not of a new size that redrew part of the last
|
||||
// (Present1 with dirty rectangles, sync interval 0, no flags). Such a
|
||||
// frame's wait for its composition is bounded and off the main thread; on
|
||||
// the main thread it calls nothing that may wait long but Present and,
|
||||
// every sweepEvery frames, DwmGetCompositionTimingInfo (readPeriod). Paced,
|
||||
// a frame presents only once the frame latency object said the swap chain
|
||||
// has room for it (latency.go), so its Present has nothing to wait for;
|
||||
// uncapped, there is no such object, and Present waits for room itself:
|
||||
// for the GPU to finish the frame before (one frame queued at most), which
|
||||
// waits for DWM to give its buffer back. DWM held up by the resize keeps
|
||||
// the buffers it holds, a frame drawn once the wait for its composition
|
||||
// timed out queues behind them, and Present then waits on DWM, which may
|
||||
// itself wait on the window's thread; that is the likeliest 2 s, though
|
||||
// nothing measured it. So while the window changes size, uncapped frames
|
||||
// present with DXGI_PRESENT_DO_NOT_WAIT (presentFlags), with which Present
|
||||
// returns DXGI_ERROR_WAS_STILL_DRAWING where it would wait. Present is tried
|
||||
// again for a refresh at most (showSoon), as long as the GPU or DWM take to
|
||||
// make room unless held up; after that the frame waits, unpresented
|
||||
// (holdFrame): the main thread goes back to the window's messages, the
|
||||
// frame after waits for it (Ready), and it presents after the next
|
||||
// composition, or two refreshes, tried as before (presentHeld). A frame
|
||||
// drawn meanwhile, as one of a new size within SetWindowPos, takes its
|
||||
// place, drawn whole as none showed it. A frame of a new size that Present
|
||||
// refuses for a refresh waits so too, its wait for DWM to show it
|
||||
// (waitShown) left out, rather than wait in Present within SetWindowPos,
|
||||
// where DWM may wait on the window's thread: the window shows the last
|
||||
// frame at its new size until it presents, a composition or two later,
|
||||
// which WARP on a busy CI runner does too. A frame waits so maxHeld at
|
||||
// most: without that bound, on the Radeon 780M, 2 runs of 30 SetWindowPos
|
||||
// resizes held their last frame, and nothing drew for the 2 to 3.5 s the
|
||||
// app ran on: the frame after waited for it, which DXGI never took with
|
||||
// the flag, tried after each composition.
|
||||
//
|
||||
// A frame held maxHeld presents as it would without the flag, waiting in
|
||||
// Present as long as DXGI has it, but on another goroutine (presentAside,
|
||||
// goAside), and after it, until DXGI takes a frame at once with the swap
|
||||
// chain settled (gaveUp), frames present paced, with the flag, and the
|
||||
// buffers resize, to settle the swap chain or for a size they do not hold,
|
||||
// on another goroutine too (resizeAside). While such a call is under way,
|
||||
// the main thread makes none to the device's context nor the swap chain,
|
||||
// which it may not while another thread does: it goes back to the
|
||||
// window's messages, a frame drawn meanwhile, as one of a new size within
|
||||
// SetWindowPos, is put off, the window showing the last frame, the frame
|
||||
// after waits for the call (Ready), and Release waits for it to return,
|
||||
// releaseWait at most, past which it leaves the GPU objects to the
|
||||
// process's end: DXGI may send the window a message meanwhile.
|
||||
// Once it returned, the frame after draws, at once if one waits, or once
|
||||
// the window asks for one (askFrame), as the settle timer's may have been
|
||||
// put off. DXGI refusing frames was not ended by anything the app did
|
||||
// without waiting. Giving the held frame up, never presented, and drawing
|
||||
// the frames after (bac8b96): in the one run of 40 where frames were given
|
||||
// up on, three in a row after the last change, the frame that then
|
||||
// settled the swap chain took 994 ms in Render on the main thread, in
|
||||
// ResizeBuffers or the Present without the flag after it, and frames came
|
||||
// again after it. Waiting on neither (0338404), as the frame that would
|
||||
// resize the buffers was put off until DXGI took a frame with the flag,
|
||||
// probed by presenting the frame last drawn with it, and an event query
|
||||
// said the GPU drew the frames before: in 4 runs of 70, every frame after
|
||||
// the give-ups, 167 of them over the 4 s watched, was put off, nothing
|
||||
// presenting and nothing resizing, the window showing a stale frame. The
|
||||
// stats could not tell which of the two waits held, as a frame put off
|
||||
// said the same for both; the code holds no fault in either (the probe
|
||||
// presents with the flag, and a success clears the wait; the query ended
|
||||
// after the frames drawn, GetData's S_OK told from S_FALSE), and neither
|
||||
// had a bound, so what ended them was DXGI or the GPU moving on by
|
||||
// itself, which they did not. That the probe was refused throughout is
|
||||
// the likelier, as DXGI refused the held frames for seconds before
|
||||
// maxHeld; nothing measured it. A call that waits for DXGI, made off the
|
||||
// main thread, ends that state as the 994 ms frame did, while the window
|
||||
// keeps taking its messages, which DWM may wait on as the window changes
|
||||
// size. Nothing can end such a call sooner, and it has no bound of the
|
||||
// app's; the waits seen, 994 ms and the 2 s presents above, all ended by
|
||||
// themselves, and the window takes its messages meanwhile. Frame stats
|
||||
// tell how many times Present said it was still drawing, a frame left to
|
||||
// present later, a frame put off while a call waits on another thread
|
||||
// ("put off while Present waits on another thread", or ResizeBuffers),
|
||||
// the frame after it ("after Present waited on another thread"), and one
|
||||
// paced until DXGI takes a frame at once. Nor does the main thread read
|
||||
// the refresh period from DWM uncapped, which may wait for it: another
|
||||
// goroutine does (readPeriodAside), and none while the window changes
|
||||
// size, as the period does not change with it. A swap chain that takes no
|
||||
// DXGI_PRESENT_DO_NOT_WAIT (DXGI_ERROR_INVALID_CALL) presents without it,
|
||||
// waiting as before (noWaitRefused).
|
||||
//
|
||||
// With two buffers, a frame presented with sync interval 0 that DWM has not
|
||||
// shown yet holds one and the screen the other, and the next frame waits
|
||||
// for the screen to give its buffer back, at the next refresh: the swap
|
||||
// chain has three (uncappedBuffers), so that a frame replaces the one
|
||||
// queued, which DWM drops. The device's frame latency, one frame queued at
|
||||
// most (init), still keeps the main thread from running ahead of the GPU:
|
||||
// Present blocks for it, and the GPU's pace is the frames'.
|
||||
const (
|
||||
// swapChainTearing is DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING, and
|
||||
// presentTearing DXGI_PRESENT_ALLOW_TEARING.
|
||||
swapChainTearing = 0x800
|
||||
presentTearing = 0x200
|
||||
// factory5CheckFeatureSupport is IDXGIFactory5::CheckFeatureSupport,
|
||||
// and featureTearing DXGI_FEATURE_PRESENT_ALLOW_TEARING.
|
||||
factory5CheckFeatureSupport = 28
|
||||
featureTearing = 0
|
||||
// uncappedBuffers is how many buffers an uncapped swap chain has at
|
||||
// least.
|
||||
uncappedBuffers = 3
|
||||
// presentDoNotWait is DXGI_PRESENT_DO_NOT_WAIT, with which Present
|
||||
// returns DXGI_ERROR_WAS_STILL_DRAWING rather than wait, and
|
||||
// dxgiErrorInvalidCall DXGI_ERROR_INVALID_CALL, which it returns where
|
||||
// the flag is not taken.
|
||||
presentDoNotWait = 0x8
|
||||
dxgiErrorWasStillDrawing = 0x887a000a
|
||||
dxgiErrorInvalidCall = 0x887a0001
|
||||
)
|
||||
|
||||
// errStillDrawing is what show returns when Present, with
|
||||
// DXGI_PRESENT_DO_NOT_WAIT, would have waited: the frame is not presented.
|
||||
var errStillDrawing = errors.New("d3d11: the swap chain has no room for the frame yet")
|
||||
|
||||
var iidIDXGIFactory5 = guid{0x7632e1f5, 0xee65, 0x4dca, [8]byte{0x87, 0xfd, 0x84, 0xcd, 0x75, 0xf8, 0x83, 0x8d}}
|
||||
|
||||
// tearingSupported reports whether the system shows frames presented with
|
||||
// tearing, as the factory's IDXGIFactory5 (DXGI 1.5) tells.
|
||||
func tearingSupported(factory uintptr) bool {
|
||||
var f5 uintptr
|
||||
if failed(call(factory, 0, uintptr(unsafe.Pointer(&iidIDXGIFactory5)), uintptr(unsafe.Pointer(&f5)))) {
|
||||
return false
|
||||
}
|
||||
defer free(&f5)
|
||||
var allow int32 // BOOL
|
||||
if failed(call(f5, factory5CheckFeatureSupport, featureTearing, uintptr(unsafe.Pointer(&allow)), unsafe.Sizeof(allow))) {
|
||||
return false
|
||||
}
|
||||
return allow != 0
|
||||
}
|
||||
|
||||
// swapChainFlags returns the flags the swap chain is made and resized
|
||||
// with: the frame latency object's, or uncapped, tearing's where it
|
||||
// presents with tearing.
|
||||
func (r *Renderer) swapChainFlags() uint32 {
|
||||
switch {
|
||||
case !r.uncapped:
|
||||
return swapChainWaitable
|
||||
case r.tearing:
|
||||
return swapChainTearing
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// presentFlags returns the flags of a present after sync vertical blanks:
|
||||
// tearing's for one at once (sync 0), where the swap chain allows it and
|
||||
// frames present uncapped; uncapped, when frames present paced, as while
|
||||
// the window changes size, DXGI_PRESENT_DO_NOT_WAIT, where the frame can
|
||||
// present later (post) and the swap chain takes it.
|
||||
func (r *Renderer) presentFlags(sync uintptr) uintptr {
|
||||
switch {
|
||||
case sync == 0 && r.tearing && r.presentsUncapped():
|
||||
return presentTearing
|
||||
case r.uncapped && !r.presentsUncapped() && r.post != nil && !r.noWaitRefused:
|
||||
return presentDoNotWait
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// showSoon presents the back buffer with DXGI_PRESENT_DO_NOT_WAIT, trying
|
||||
// again for at most a refresh while Present would wait, as for the GPU to
|
||||
// finish the last frame or DWM to give a buffer back, which takes that
|
||||
// long at most when DWM is not held up; then it returns errStillDrawing,
|
||||
// and the frame waits (holdFrame).
|
||||
func (r *Renderer) showSoon(sync uintptr) error {
|
||||
deadline := time.Now().Add(r.cost.refreshPeriod())
|
||||
for {
|
||||
err := r.show(sync)
|
||||
if err != errStillDrawing {
|
||||
return err
|
||||
}
|
||||
r.refused++
|
||||
if !time.Now().Before(deadline) {
|
||||
return err
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// holdFrame returns err, a present's, but for errStillDrawing: the frame
|
||||
// drawn, which Present refused, then presents after the next composition,
|
||||
// or a refresh or two, from refreshed (presentHeld), while the main thread
|
||||
// goes back to the window's messages, and the frame after waits for that
|
||||
// (Ready). A frame drawn before, as one of a new size within SetWindowPos,
|
||||
// takes its place (Render), and one that waited too long presents on
|
||||
// another goroutine (presentHeld).
|
||||
func (r *Renderer) holdFrame(err error) error {
|
||||
if err != errStillDrawing {
|
||||
return err
|
||||
}
|
||||
// The GPU draws the frame meanwhile.
|
||||
call(r.ctx, ctxFlush)
|
||||
r.unpresented = true
|
||||
if r.heldAt.IsZero() {
|
||||
r.heldAt = time.Now()
|
||||
}
|
||||
r.waitComposed()
|
||||
return nil
|
||||
}
|
||||
|
||||
// maxHeld is how long a frame waits to present at most (presentHeld);
|
||||
// tests change it.
|
||||
var maxHeld = 100 * time.Millisecond
|
||||
|
||||
// askFrame has the window ask for a frame, as the settle timer does
|
||||
// (armSettle); tests replace it.
|
||||
var askFrame = func(hwnd uintptr) { procInvalidateRect.Call(hwnd, 0, 0) }
|
||||
|
||||
// presentHeld presents the frame Present refused (holdFrame), or has it
|
||||
// wait again, and reports whether the frame after can draw now. A frame
|
||||
// that waited maxHeld presents without DXGI_PRESENT_DO_NOT_WAIT, on
|
||||
// another goroutine (presentAside), and the frame after waits for it; until
|
||||
// DXGI takes a frame at once, frames present paced, and the buffers
|
||||
// resize on another goroutine too (gaveUp).
|
||||
func (r *Renderer) presentHeld() bool {
|
||||
r.unpresented = false
|
||||
if time.Since(r.heldAt) >= maxHeld {
|
||||
r.gaveUp = true
|
||||
r.presentAside()
|
||||
return false
|
||||
}
|
||||
err := r.present(0)
|
||||
if err == nil {
|
||||
// The frame after waits for the composition that shows it.
|
||||
r.waitComposed()
|
||||
return false
|
||||
}
|
||||
if err = r.holdFrame(err); err == nil {
|
||||
return false
|
||||
}
|
||||
if r.failed == nil {
|
||||
r.failed = err // the next frame finds it
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// presentsUncapped reports whether frames present without waiting for the
|
||||
// display: uncapped (MYGO_UNCAPPED), but while the window changes size, or
|
||||
// after a frame that waited maxHeld until DXGI takes one at once (gaveUp),
|
||||
// when they present paced.
|
||||
func (r *Renderer) presentsUncapped() bool {
|
||||
return r.uncapped && !r.resizing && !r.gaveUp
|
||||
}
|
||||
|
||||
// errAside is what buffers returns when another goroutine resizes the
|
||||
// buffers (resizeAside): the frame is put off.
|
||||
var errAside = errors.New("d3d11: the buffers resize on another thread")
|
||||
|
||||
// presentAside presents the frame drawn, which Present refused for
|
||||
// maxHeld, as it would without DXGI_PRESENT_DO_NOT_WAIT, waiting as long
|
||||
// as DXGI has it wait, on another goroutine (goAside).
|
||||
func (r *Renderer) presentAside() {
|
||||
sc, flags, params := r.swapChain, r.presentFlags(0)&^presentDoNotWait, r.presentParams()
|
||||
r.goAside("Present", func() uintptr { return presentCall(sc, 0, flags, params) }, func(hr uintptr) error {
|
||||
if failed(hr) {
|
||||
return fmt.Errorf("d3d11: present failed: %#x", uint32(hr))
|
||||
}
|
||||
r.held = r.ctx1 != 0 && uint32(hr) != dxgiStatusOccluded
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// resizeAside makes the swap chain's n buffers bw×bh pixels, showing w×h
|
||||
// of them, as buffers does, ResizeBuffers called on another goroutine
|
||||
// (goAside), the views of the buffers released before.
|
||||
func (r *Renderer) resizeAside(w, h, bw, bh, n int) {
|
||||
sc, flags := r.swapChain, uintptr(r.swapChainFlags())
|
||||
r.goAside("ResizeBuffers", func() uintptr { return resizeBuffersCall(sc, uintptr(n), uintptr(bw), uintptr(bh), flags) }, func(hr uintptr) error {
|
||||
if failed(hr) {
|
||||
return fmt.Errorf("d3d11: cannot resize the swap chain: %#x", uint32(hr))
|
||||
}
|
||||
return r.viewBuffers(w, h, bw, bh)
|
||||
})
|
||||
}
|
||||
|
||||
// goAside has another goroutine run fn, a call to the swap chain named
|
||||
// what, which may wait for DWM, and then runs done with what it returned
|
||||
// on the main thread (post). Meanwhile, the main thread makes no call to the
|
||||
// device's context nor the swap chain: a frame is put off (Render), the
|
||||
// frame after waits (Ready), and Release waits for fn (releaseWait). Once it
|
||||
// did, the frame after draws, at once if one waits, or once the window
|
||||
// asks for one (askFrame).
|
||||
func (r *Renderer) goAside(what string, fn func() uintptr, done func(hr uintptr) error) {
|
||||
ended, post := make(chan struct{}), r.post
|
||||
r.aside, r.asideEnded = what, ended
|
||||
go func() {
|
||||
hr := fn()
|
||||
close(ended)
|
||||
post(func() {
|
||||
if r.asideEnded != ended {
|
||||
return // released meanwhile
|
||||
}
|
||||
r.aside, r.asideEnded, r.asideDone = "", nil, what
|
||||
if err := done(hr); err != nil && r.failed == nil {
|
||||
r.failed = err // the next frame finds it
|
||||
}
|
||||
if r.wake != nil {
|
||||
r.woke()
|
||||
return
|
||||
}
|
||||
askFrame(r.hwnd)
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
// readPeriodAside reads the display's refresh period from DWM on another
|
||||
// goroutine, as DwmGetCompositionTimingInfo may wait for it, and sets it on
|
||||
// the main thread (post). Without post, it reads it at once.
|
||||
func (r *Renderer) readPeriodAside() {
|
||||
if r.post == nil {
|
||||
r.cost.readPeriod()
|
||||
return
|
||||
}
|
||||
if r.readingPeriod {
|
||||
return
|
||||
}
|
||||
r.readingPeriod = true
|
||||
post := r.post
|
||||
go func() {
|
||||
p := dwmPeriod()
|
||||
post(func() {
|
||||
r.readingPeriod = false
|
||||
if p != 0 {
|
||||
r.cost.period = p
|
||||
}
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
// unbindBuffers unbinds the render target views of the swap chain's
|
||||
// buffers from the device context and submits the commands drawing into
|
||||
// them, before ResizeBuffers, which needs no reference to the buffers
|
||||
// left: a view bound to the context is one. The context waits for the GPU
|
||||
// to be done with them by itself.
|
||||
func (r *Renderer) unbindBuffers() {
|
||||
call(r.ctx, ctxOMSetRenderTargets, 0, 0, 0)
|
||||
r.drawing = 0
|
||||
call(r.ctx, ctxFlush)
|
||||
}
|
||||
+1275
File diff suppressed because it is too large.
Load diff
+180
@@ -0,0 +1,180 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// Frames of video (scene.Surface) reach the GPU as the decoder left them:
|
||||
// a texture in BGRA that Media Foundation drew on a device of its own and
|
||||
// shares by an NT handle (Surface.Native), which the renderer opens on
|
||||
// its device once and reads under the texture's keyed mutex, or planes in
|
||||
// memory, which it uploads, NV12's luma and chroma into textures of their
|
||||
// own that the shader converts.
|
||||
|
||||
const (
|
||||
devOpenSharedResource1 = 48 // ID3D11Device1
|
||||
keyedAcquireSync = 8 // IDXGIKeyedMutex
|
||||
keyedReleaseSync = 9
|
||||
formatR8G8Unorm = 49
|
||||
// acquireTimeout is how long, in ms, a frame waits for the decoder to
|
||||
// finish writing a frame of video into a shared texture.
|
||||
acquireTimeout = 100
|
||||
waitTimeout = 0x102
|
||||
)
|
||||
|
||||
var (
|
||||
iidID3D11Device1 = guid{0xa04bfb29, 0x08ef, 0x43d6, [8]byte{0xa4, 0x9c, 0xa9, 0xbd, 0xbd, 0xcb, 0xe6, 0x86}}
|
||||
iidIDXGIKeyedMutex = guid{0x9d8e1289, 0xd7b3, 0x465f, [8]byte{0x81, 0x26, 0x25, 0x0e, 0x34, 0x9a, 0xf8, 0x5d}}
|
||||
)
|
||||
|
||||
// sharedTexture is a texture a decoder shares, opened on the renderer's
|
||||
// device.
|
||||
type sharedTexture struct {
|
||||
texture
|
||||
mutex uintptr // IDXGIKeyedMutex
|
||||
}
|
||||
|
||||
// videoState is what the renderer keeps of frames of video.
|
||||
type videoState struct {
|
||||
device1 uintptr // ID3D11Device1, for OpenSharedResource1
|
||||
shared map[uint64]*sharedTexture
|
||||
// acquired are the keyed mutexes the frame being drawn holds, released
|
||||
// once its draws are issued (releaseShared).
|
||||
acquired []uintptr
|
||||
}
|
||||
|
||||
// surfaceView returns the view of the texture of a frame of video: its
|
||||
// luma, for NV12 in memory, whose chroma chromaView returns.
|
||||
func (r *Renderer) surfaceView(img *scene.Image, s *scene.Surface) uintptr {
|
||||
if s.Native != 0 {
|
||||
return r.sharedView(s)
|
||||
}
|
||||
t := r.images[img.ID()]
|
||||
cw, ch := (img.W+1)/2, (img.H+1)/2
|
||||
if t != nil && (t.chroma == nil || t.w != img.W || t.h != img.H) {
|
||||
freeTexture(t)
|
||||
t = nil
|
||||
}
|
||||
if t == nil {
|
||||
t = &texture{chroma: &texture{}}
|
||||
if r.planeTexture(t, img.W, img.H, formatR8Unorm, s.Planes[0]) != nil ||
|
||||
r.planeTexture(t.chroma, cw, ch, formatR8G8Unorm, s.Planes[1]) != nil {
|
||||
freeTexture(t)
|
||||
delete(r.images, img.ID())
|
||||
return 0
|
||||
}
|
||||
t.ver = img.Version()
|
||||
r.images[img.ID()] = t
|
||||
} else if t.ver != img.Version() {
|
||||
call(r.ctx, ctxUpdateSubresource, t.tex, 0, 0, uintptr(unsafe.Pointer(&s.Planes[0].Pix[0])), uintptr(s.Planes[0].Stride), 0)
|
||||
call(r.ctx, ctxUpdateSubresource, t.chroma.tex, 0, 0, uintptr(unsafe.Pointer(&s.Planes[1].Pix[0])), uintptr(s.Planes[1].Stride), 0)
|
||||
t.ver = img.Version()
|
||||
}
|
||||
t.lastFrame = r.frame
|
||||
return t.srv
|
||||
}
|
||||
|
||||
// planeTexture makes t a texture of a plane of w×h texels in memory.
|
||||
func (r *Renderer) planeTexture(t *texture, w, h int, format uint32, p scene.Plane) error {
|
||||
if err := r.newTexture(t, w, h, format, nil, 1); err != nil {
|
||||
return err
|
||||
}
|
||||
call(r.ctx, ctxUpdateSubresource, t.tex, 0, 0, uintptr(unsafe.Pointer(&p.Pix[0])), uintptr(p.Stride), 0)
|
||||
return nil
|
||||
}
|
||||
|
||||
// chromaView returns the view of the chroma of a frame of video in NV12,
|
||||
// after imageView returned that of its luma, or 0.
|
||||
func (r *Renderer) chromaView(img *scene.Image) uintptr {
|
||||
if t := r.images[img.ID()]; t != nil && t.chroma != nil {
|
||||
return t.chroma.srv
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// sharedView opens the texture a decoder shares, once, and acquires its
|
||||
// keyed mutex for the frame, which releaseShared releases once its draws
|
||||
// are issued: the GPU then reads it after the decoder's writes, and the
|
||||
// decoder writes it again after the frame's reads.
|
||||
func (r *Renderer) sharedView(s *scene.Surface) uintptr {
|
||||
v := &r.video
|
||||
t := v.shared[s.NativeID]
|
||||
if t == nil {
|
||||
if v.device1 == 0 && failed(call(r.device, 0, uintptr(unsafe.Pointer(&iidID3D11Device1)), uintptr(unsafe.Pointer(&v.device1)))) {
|
||||
v.device1 = 0
|
||||
return 0
|
||||
}
|
||||
t = &sharedTexture{}
|
||||
if failed(call(v.device1, devOpenSharedResource1, s.Native, uintptr(unsafe.Pointer(&iidID3D11Texture2D)), uintptr(unsafe.Pointer(&t.tex)))) {
|
||||
return 0
|
||||
}
|
||||
if failed(call(t.tex, 0, uintptr(unsafe.Pointer(&iidIDXGIKeyedMutex)), uintptr(unsafe.Pointer(&t.mutex)))) ||
|
||||
failed(call(r.device, devCreateShaderResourceView, t.tex, 0, uintptr(unsafe.Pointer(&t.srv)))) {
|
||||
free(&t.mutex)
|
||||
free(&t.srv)
|
||||
free(&t.tex)
|
||||
return 0
|
||||
}
|
||||
if v.shared == nil {
|
||||
v.shared = map[uint64]*sharedTexture{}
|
||||
}
|
||||
v.shared[s.NativeID] = t
|
||||
}
|
||||
if t.lastFrame != r.frame || !v.holds(t.mutex) {
|
||||
hr := call(t.mutex, keyedAcquireSync, 0, acquireTimeout)
|
||||
if failed(hr) || hr == waitTimeout {
|
||||
return 0
|
||||
}
|
||||
v.acquired = append(v.acquired, t.mutex)
|
||||
}
|
||||
t.lastFrame = r.frame
|
||||
return t.srv
|
||||
}
|
||||
|
||||
func (v *videoState) holds(mutex uintptr) bool {
|
||||
for _, m := range v.acquired {
|
||||
if m == mutex {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// releaseShared releases the keyed mutexes of the shared textures the
|
||||
// frame read, its draws issued.
|
||||
func (r *Renderer) releaseShared() {
|
||||
for _, m := range r.video.acquired {
|
||||
call(m, keyedReleaseSync, 0)
|
||||
}
|
||||
r.video.acquired = r.video.acquired[:0]
|
||||
}
|
||||
|
||||
// sweepShared closes the shared textures no frame read for a while.
|
||||
func (r *Renderer) sweepShared(all bool) {
|
||||
for key, t := range r.video.shared {
|
||||
if all || r.frame-t.lastFrame > 240 {
|
||||
free(&t.mutex)
|
||||
free(&t.srv)
|
||||
free(&t.tex)
|
||||
delete(r.video.shared, key)
|
||||
}
|
||||
}
|
||||
if all {
|
||||
free(&r.video.device1)
|
||||
}
|
||||
}
|
||||
|
||||
// freeTexture frees an image's texture, and its chroma's.
|
||||
func freeTexture(t *texture) {
|
||||
free(&t.srv)
|
||||
free(&t.tex)
|
||||
if t.chroma != nil {
|
||||
free(&t.chroma.srv)
|
||||
free(&t.chroma.tex)
|
||||
t.chroma = nil
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
//go:build windows
|
||||
|
||||
package d3d11
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"syscall"
|
||||
"testing"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11/device"
|
||||
"github.com/egoist/mygo/internal/gpu/gputest"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// TestDrawsVideoAsTheCPURenderer draws frames of video in NV12 from their
|
||||
// planes in memory, which the shader converts as the CPU renderer does,
|
||||
// then frames in BGRA that another device drew into textures it shares,
|
||||
// as Media Foundation does, which the renderer reads where they are.
|
||||
func TestDrawsVideoAsTheCPURenderer(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
s := gputest.VideoScene()
|
||||
r, err := New(hiddenWindow(t, s.Width, s.Height))
|
||||
if err != nil {
|
||||
t.Skip("no Direct3D 11:", err)
|
||||
}
|
||||
defer r.Release()
|
||||
for range 2 {
|
||||
for _, op := range s.Ops {
|
||||
op.Image.Changed()
|
||||
}
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-video", pix, stride, s)
|
||||
}
|
||||
for _, op := range s.Ops {
|
||||
if tex := r.images[op.Image.ID()]; tex == nil || tex.chroma == nil {
|
||||
t.Fatal("a frame of video drew from RGBA, not its planes")
|
||||
}
|
||||
}
|
||||
|
||||
// The frames converted to BGRA, in textures of another device.
|
||||
dev, ctx, _, err := device.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer free(&dev)
|
||||
defer free(&ctx)
|
||||
var shared []uintptr
|
||||
defer func() {
|
||||
for _, h := range shared {
|
||||
syscall.CloseHandle(syscall.Handle(h))
|
||||
}
|
||||
}()
|
||||
done := map[*scene.Image]bool{}
|
||||
for i, op := range s.Ops {
|
||||
img := op.Image
|
||||
if done[img] {
|
||||
continue
|
||||
}
|
||||
done[img] = true
|
||||
rgba := img.Surface.RGBA(nil, img.W, img.H)
|
||||
bgra := make([]byte, len(rgba))
|
||||
for k := 0; k < len(rgba); k += 4 {
|
||||
bgra[k], bgra[k+1], bgra[k+2], bgra[k+3] = rgba[k+2], rgba[k+1], rgba[k], rgba[k+3]
|
||||
}
|
||||
h := newSharedTexture(t, dev, ctx, img.W, img.H, bgra)
|
||||
shared = append(shared, h)
|
||||
img.Surface = &scene.Surface{Format: scene.SurfaceBGRA, Native: h, NativeID: uint64(i + 1)}
|
||||
img.Restore = func() []byte { return rgba }
|
||||
img.Pix = nil
|
||||
img.Changed()
|
||||
}
|
||||
for range 3 {
|
||||
if err := r.draw(s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pix, stride := r.readBack(t)
|
||||
gputest.Compare(t, "d3d11-video-shared", pix, stride, s)
|
||||
}
|
||||
if len(r.video.shared) != len(shared) {
|
||||
t.Fatalf("the renderer opened %d shared textures, not %d", len(r.video.shared), len(shared))
|
||||
}
|
||||
if len(r.video.acquired) != 0 {
|
||||
t.Fatal("the frame kept the keyed mutexes of the textures it read")
|
||||
}
|
||||
}
|
||||
|
||||
// newSharedTexture returns the NT handle of a w×h texture in BGRA of dev with
|
||||
// a keyed mutex, holding pix, which dev wrote under the mutex.
|
||||
func newSharedTexture(t *testing.T, dev, ctx uintptr, w, h int, pix []byte) uintptr {
|
||||
const (
|
||||
miscSharedKeyedMutex = 0x100
|
||||
miscSharedNTHandle = 0x800
|
||||
sharedRead = 0x80000000
|
||||
sharedWrite = 1
|
||||
createSharedHandle = 13 // IDXGIResource1
|
||||
)
|
||||
iidIDXGIResource1 := guid{0x30961379, 0x4609, 0x4a41, [8]byte{0x99, 0x8e, 0x54, 0xfe, 0x56, 0x7e, 0xe0, 0xc1}}
|
||||
desc := texture2DDesc{Width: uint32(w), Height: uint32(h), MipLevels: 1, ArraySize: 1, Format: formatB8G8R8A8Unorm, SampleCount: 1,
|
||||
Usage: usageDefault, BindFlags: bindShaderResource, MiscFlags: miscSharedKeyedMutex | miscSharedNTHandle}
|
||||
var tex, mutex, res uintptr
|
||||
if hr := call(dev, devCreateTexture2D, uintptr(unsafe.Pointer(&desc)), 0, uintptr(unsafe.Pointer(&tex))); failed(hr) {
|
||||
t.Fatalf("cannot create a shared texture: %#x", uint32(hr))
|
||||
}
|
||||
defer free(&tex)
|
||||
if failed(call(tex, 0, uintptr(unsafe.Pointer(&iidIDXGIKeyedMutex)), uintptr(unsafe.Pointer(&mutex)))) {
|
||||
t.Fatal("no keyed mutex")
|
||||
}
|
||||
defer free(&mutex)
|
||||
call(mutex, keyedAcquireSync, 0, 1000)
|
||||
call(ctx, ctxUpdateSubresource, tex, 0, 0, uintptr(unsafe.Pointer(&pix[0])), uintptr(4*w), 0)
|
||||
call(mutex, keyedReleaseSync, 0)
|
||||
call(ctx, ctxFlush)
|
||||
if failed(call(tex, 0, uintptr(unsafe.Pointer(&iidIDXGIResource1)), uintptr(unsafe.Pointer(&res)))) {
|
||||
t.Fatal("no IDXGIResource1")
|
||||
}
|
||||
defer free(&res)
|
||||
var handle uintptr
|
||||
if hr := call(res, createSharedHandle, 0, sharedRead|sharedWrite, 0, uintptr(unsafe.Pointer(&handle))); failed(hr) {
|
||||
t.Fatalf("cannot share the texture: %#x", uint32(hr))
|
||||
}
|
||||
return handle
|
||||
}
|
||||
Reference in new issue
Block a user