Documentation
¶
Overview ¶
Package explicit is the renderer for the explicit GPU APIs, Vulkan and WebGPU (D19): the Device interface that both implement, the design limits they share (SPEC §9.3), and the WGSL shaders with the SPIR-V that glutter-gen makes from them (D20).
Flutter: Impeller's Vulkan and Metal backends (engine/src/flutter/impeller/renderer/backend).
Index ¶
- Constants
- Variables
- func IsDevicePending(err error) bool
- func IsSwapchainOutOfDate(err error) bool
- func RotateRects(rects []image.Rectangle, width, height int, rotation Rotation) []image.Rectangle
- type AddressMode
- type BindGroup
- type Binding
- type BindingKind
- type BlendFactor
- type BlendState
- type Buffer
- type BufferUsage
- type Device
- type Encoder
- type EntryPoint
- type FilterMode
- type FrameStats
- type Limits
- func (l Limits) AlignedRowPitch(width, bytesPerPixel int) int
- func (l Limits) CheckBindGroup(group int, entries []Binding)
- func (l Limits) CheckPipeline(desc PipelineDesc)
- func (l Limits) CheckSetBindGroup(group int, dynamicOffsets []uint32)
- func (l Limits) CheckSetVertexBuffer(slot int)
- func (l Limits) CheckTexture(desc TextureDesc)
- type LoadOp
- type Pass
- type Pipeline
- type PipelineDesc
- type Renderer
- func (r *Renderer) Close()
- func (r *Renderer) Describe() string
- func (r *Renderer) Draw(h gpu.SurfaceHandle, width, height int, scene *ui.Scene, capture bool) (*image.RGBA, error)
- func (r *Renderer) Invalidate(h gpu.SurfaceHandle)
- func (r *Renderer) LastFrame() FrameStats
- func (r *Renderer) RasterizeScene(scene *ui.Scene, width, height int) (*ui.Image, error)
- func (r *Renderer) Release(h gpu.SurfaceHandle)
- func (r *Renderer) Snapshot(scene *ui.Scene, size ui.Size) (*image.RGBA, error)
- type RendererOpts
- type Rotation
- type Sampler
- type SamplerDesc
- type Shader
- type ShaderBinding
- type ShaderStage
- type Swapchain
- type Texture
- type TextureDesc
- type TextureFormat
- type TextureUsage
- type VertexAttribute
- type VertexBufferLayout
- type VertexFormat
Constants ¶
const FramesInFlight = 2
FramesInFlight is how many frames the GPU works on at once (SPEC §9.3). A device's frame slots alternate with every Submit, so the renderer keeps one set of dynamic buffers for each, and the frame numbered n uses set n % FramesInFlight.
Flutter: no counterpart
const GPUDevicePending = "GPUDevicePending"
GPUDevicePending is the tag of the error that a Renderer's open function returns when the backend has no device at the moment and is getting one without blocking: WebGPU asks the browser for a new device after the old one was lost, and the UI goroutine never waits for a promise (SPEC §9.5, §23.3). The renderer draws nothing for that frame and returns no error; the backend tells its owner when the device is there, and the next frame opens it.
Flutter: no counterpart
const SwapchainOutOfDate = "SwapchainOutOfDate"
SwapchainOutOfDate is the tag of the error that Swapchain.Acquire returns when the swapchain no longer matches its surface (the window was resized, or the platform asks for a new one): the caller configures it again and retries once (SPEC §9.3).
Flutter: no counterpart
const TagAtlasFull = gpu.TagAtlasFull
TagAtlasFull is the tag of the error of a coverage atlas that has no slot left in the frame. It is produced by the atlas of internal/gpu (and the renderers' backends); this package only compares with it.
Flutter: no counterpart
const TagGPUDeviceLost = "GPUDeviceLost"
TagGPUDeviceLost is the tag of the error of a lost device of another backend, such as WebGPU's. The backends produce it; this package only compares with it (device loss, SPEC §9.5).
Flutter: no counterpart
const TagGPUImageTooLarge = "GPUImageTooLarge"
TagGPUImageTooLarge is the tag of the error of an image larger than the textures of the device (made by the resources of this package and compared in the shape code).
Flutter: no counterpart
const TagVulkanDeviceLost = "VulkanDeviceLost"
TagVulkanDeviceLost is the tag of the error of a lost Vulkan device. It is produced by the Vulkan backend; this package only compares with it (device loss, SPEC §9.3).
Flutter: no counterpart
Variables ¶
var ShaderBlit = &Shader{ Name: "blit", WGSL: `// Copies the frame texture into the swapchain image, whatever its format // (SPEC §9.3). Ported from the GLES blit shader (blit.vert.glsl, blit.frag.glsl). // // One triangle that covers the whole target, made from the vertex index, so it // needs no vertex buffer: draw 3 vertices. Clip space points up and texture space // points down, so the V coordinate is flipped and the picture stays upright. // // The instance index is the pre-rotation of the swapchain (explicit.Rotation, SPEC §24.4): the // image of the swapchain is the frame rotated clockwise by that many quarter turns, so that the // presentation engine need not rotate it. The renderer draws one instance, numbered with the // rotation (firstInstance), which is 0 on every window system but Android's. @group(0) @binding(0) var frameTexture: texture_2d<f32>; @group(0) @binding(1) var frameSampler: sampler; struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) uv: vec2<f32>, } @vertex fn vs_main(@builtin(vertex_index) index: u32, @builtin(instance_index) rotation: u32) -> VertexOutput { let p = vec2<f32>(f32((index << 1u) & 2u), f32(index & 2u)); // The position in the image, from its top left, as a fraction. let a = p.x; let b = 1.0 - p.y; // The point of the frame that lands there, when the frame is rotated clockwise by rotation // quarter turns: a point (u, v) of the frame goes to (1 - v, u) for one turn. var uv = vec2<f32>(a, b); if (rotation == 1u) { uv = vec2<f32>(b, 1.0 - a); } else if (rotation == 2u) { uv = vec2<f32>(1.0 - a, 1.0 - b); } else if (rotation == 3u) { uv = vec2<f32>(1.0 - b, a); } var out: VertexOutput; out.position = vec4<f32>(p * 2.0 - 1.0, 0.0, 1.0); out.uv = uv; return out; } @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> { return textureSample(frameTexture, frameSampler, in.uv); } `, SPIRV: spirvBlit, Entries: []EntryPoint{ {Name: "vs_main", Stage: ShaderStageVertex, Bindings: []ShaderBinding{}}, {Name: "fs_main", Stage: ShaderStageFragment, Bindings: []ShaderBinding{ {Name: "frameTexture", Group: 0, Binding: 0, Kind: BindingSampledTexture}, {Name: "frameSampler", Group: 0, Binding: 1, Kind: BindingSampler}, }}, }, }
ShaderBlit is shaders/blit.wgsl.
Flutter: no counterpart
var ShaderFilter = &Shader{ Name: "filter", WGSL: `// One pass of an image filter over a layer: a copy, one axis of a Gaussian blur, one axis of a // dilation or erosion, a transform of the pixels, a color filter, or the two resamplings that let // a large blur work on a smaller picture (gpu.FilterPass). Ported from // gles/shaders/filter.frag.glsl. All of them read the source with textureLoad and write // premultiplied pixels, rows counted from the top as in the surface. Draw 3 vertices: one triangle // covers the whole target. // The source color of a paint: a solid color, a gradient or an image shader, then the paint's // color filter and inverted colors, and the blend with what is already drawn. Ported from // gles/shaders/paint.glsl. Fragment shaders include this file, after blend.wgsl.inc. // // The 29 blend modes of Flutter's BlendMode, on premultiplied colors, as the software renderer // computes them (internal/gpu/soft/blend.go). mode is the index of the mode in BlendMode's // order: 0 clear, 1 src, 2 dst, 3 srcOver, 4 dstOver, 5 srcIn, 6 dstIn, 7 srcOut, 8 dstOut, // 9 srcATop, 10 dstATop, 11 xor, 12 plus, 13 modulate, 14 screen, 15 overlay, 16 darken, // 17 lighten, 18 colorDodge, 19 colorBurn, 20 hardLight, 21 softLight, 22 difference, // 23 exclusion, 24 multiply, 25 hue, 26 saturation, 27 color, 28 luminosity. Ported from // gles/shaders/blend.glsl. Shaders include this file with an include line. fn hardLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { if 2.0 * s <= sa { return s * (1.0 - da) + d * (1.0 - sa) + 2.0 * s * d; } return s * (1.0 - da) + d * (1.0 - sa) + sa * da - 2.0 * (da - d) * (sa - s); } fn softLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { var m = 0.0; if da > 0.0 { m = d / da; } let s2 = 2.0 * s; let m4 = 4.0 * m; let darkSrc = d * (sa + (s2 - sa) * (1.0 - m)); let darkDst = (m4 * m4 + m4) * (m - 1.0) + 7.0 * m; let liteDst = sqrt(m) - m; var tail = liteDst; if 4.0 * d <= da { tail = darkDst; } let liteSrc = d * sa + da * (s2 - sa) * tail; var body = liteSrc; if s2 <= sa { body = darkSrc; } return s * (1.0 - da) + d * (1.0 - sa) + body; } fn blendChannel(mode: i32, s: f32, d: f32, sa: f32, da: f32) -> f32 { switch mode { case 15: { return hardLightChannel(d, s, da, sa); // overlay } case 16: { return s + d - max(s * da, d * sa); // darken } case 17: { return s + d - min(s * da, d * sa); // lighten } case 18: { // colorDodge if d == 0.0 { return s * (1.0 - da); } if s == sa { return s + d * (1.0 - sa); } return sa * min(da, d * sa / (sa - s)) + s * (1.0 - da) + d * (1.0 - sa); } case 19: { // colorBurn if d == da { return d + s * (1.0 - da); } if s == 0.0 { return d * (1.0 - sa); } return sa * (da - min(da, (da - d) * sa / s)) + s * (1.0 - da) + d * (1.0 - sa); } case 20: { return hardLightChannel(s, d, sa, da); // hardLight } case 21: { return softLightChannel(s, d, sa, da); // softLight } case 22: { return s + d - 2.0 * min(s * da, d * sa); // difference } case 23: { return s + d - 2.0 * s * d; // exclusion } case 24: { return s * (1.0 - da) + d * (1.0 - sa) + s * d; // multiply } default: { return s + d * (1.0 - sa); } } } fn lum(c: vec3<f32>) -> f32 { return 0.30 * c.r + 0.59 * c.g + 0.11 * c.b; } fn sat(c: vec3<f32>) -> f32 { return max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b)); } fn setSat(c: vec3<f32>, s: f32) -> vec3<f32> { let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let range = mx - mn; if range == 0.0 { return vec3<f32>(0.0); } return (c - vec3<f32>(mn)) * s / range; } fn setLum(c: vec3<f32>, l: f32) -> vec3<f32> { return c + vec3<f32>(l - lum(c)); } fn clipColor(c0: vec3<f32>, a: f32) -> vec3<f32> { var c = c0; let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let l = lum(c); if mn < 0.0 { c = vec3<f32>(l) + (c - vec3<f32>(l)) * l / (l - mn); } if mx > a { c = vec3<f32>(l) + (c - vec3<f32>(l)) * (a - l) / (mx - l); } return max(c, vec3<f32>(0.0)); } fn blendNonSeparable(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; var c: vec3<f32>; if mode == 25 { // hue c = s.rgb * sa; c = setSat(c, sat(d.rgb) * sa); c = setLum(c, lum(d.rgb) * sa); } else if mode == 26 { // saturation c = d.rgb * sa; c = setSat(c, sat(s.rgb) * da); c = setLum(c, lum(d.rgb) * sa); } else if mode == 27 { // color c = s.rgb * da; c = setLum(c, lum(d.rgb) * sa); } else { // luminosity c = d.rgb * sa; c = setLum(c, lum(s.rgb) * da); } c = clipColor(c, sa * da); return vec4<f32>(s.rgb * (1.0 - da) + d.rgb * (1.0 - sa) + c, sa + da - sa * da); } // blendPair blends the source s over the destination d with the mode. fn blendPair(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; switch mode { case 0: { return vec4<f32>(0.0); } case 1: { return s; } case 2: { return d; } case 3: { return s + d * (1.0 - sa); } case 4: { return d + s * (1.0 - da); } case 5: { return s * da; } case 6: { return d * sa; } case 7: { return s * (1.0 - da); } case 8: { return d * (1.0 - sa); } case 9: { return s * da + d * (1.0 - sa); } case 10: { return d * sa + s * (1.0 - da); } case 11: { return s * (1.0 - da) + d * (1.0 - sa); } case 12: { return min(s + d, vec4<f32>(1.0)); } case 13: { return s * d; } case 14: { return s + d - s * d; } case 25, 26, 27, 28: { return blendNonSeparable(mode, s, d); } default: { // The separable modes defined per channel, whose alpha is that of source-over. return vec4<f32>( blendChannel(mode, s.r, d.r, sa, da), blendChannel(mode, s.g, d.g, sa, da), blendChannel(mode, s.b, d.b, sa, da), sa + da - sa * da); } } } const SHADER_NONE: i32 = 0; const SHADER_LINEAR: i32 = 1; const SHADER_RADIAL: i32 = 2; const SHADER_CONICAL: i32 = 3; const SHADER_SWEEP: i32 = 4; const SHADER_IMAGE: i32 = 5; const SHADER_CONST: i32 = 6; const MAX_STOPS: i32 = 32; const PI: f32 = 3.14159265358979; // What a draw call's paint sets, the layout of gpu.PaintSpec as float4s (see paintUniform). struct Paint { // The shader kind, the tile modes in x and y (0 clamp, 1 repeated, 2 mirror, 3 decal) and // the number of color stops. shader: vec4<f32>, // The matrix from pixels to the shader's space: a, b, c, d, then e, f. xf0: vec4<f32>, xf1: vec4<f32>, // linear: from x, y, dx, dy; radial: center x, y, radius; conical: focal x, y, focal radius; // sweep: center x, y, start, span. p0: vec4<f32>, // linear: 1 / (dx*dx + dy*dy); conical: end center x, y, end radius. p1: vec4<f32>, // The image shader's quality (0 none, 1 low, 2 medium, 3 high) and level. imageInfo: vec4<f32>, // A degenerate gradient: premultiplied color. constColor: vec4<f32>, // Dither (0 or 1), the color filter (0 none, 1 mode, 2 matrix, 3 linear to sRGB, 4 sRGB to // linear), the blend index of a mode filter, and inverted colors (0 or 1). flags: vec4<f32>, // The blend index of a blend that reads the destination (-1: the blend unit does it), and the // pixel of the surface that the copy of the destination starts at. blend: vec4<f32>, // A mode filter's premultiplied color. filterColor: vec4<f32>, // A matrix filter: the columns of the 4x5 matrix in 0 to 255 units. filterMatrix: array<vec4<f32>, 5>, // The gradient's colors (not premultiplied) and positions, four to a float4. rampColor: array<vec4<f32>, 32>, rampPos: array<vec4<f32>, 8>, } @group(0) @binding(2) var<uniform> paint: Paint; // The image of an image shader, and a copy of the pixels being drawn over. @group(3) @binding(0) var paintImage: texture_2d<f32>; @group(3) @binding(1) var dst: texture_2d<f32>; // ---- gradients // Applies the tile mode to a position along a gradient; the second component is 0 where the // shader draws nothing. fn tileT(t: f32, mode: i32) -> vec2<f32> { if mode == 1 { return vec2<f32>(t - floor(t), 1.0); } if mode == 2 { let u = t - 2.0 * floor(t / 2.0); if u > 1.0 { return vec2<f32>(2.0 - u, 1.0); } return vec2<f32>(u, 1.0); } if mode == 3 { if t >= 0.0 && t <= 1.0 { return vec2<f32>(t, 1.0); } return vec2<f32>(t, 0.0); } return vec2<f32>(clamp(t, 0.0, 1.0), 1.0); } fn rampPosAt(i: i32) -> f32 { return paint.rampPos[i >> 2u][i & 3]; } // The premultiplied color at t, interpolated without premultiplied alpha. fn rampAt(t: f32) -> vec4<f32> { let n = i32(paint.shader.w + 0.5); var i = 0; while i < n && rampPosAt(i) < t { i++; } var c: vec4<f32>; if i == 0 { c = paint.rampColor[0]; } else if i >= n { c = paint.rampColor[n - 1]; } else { let p0 = rampPosAt(i - 1); let p1 = rampPosAt(i); if p1 <= p0 { c = paint.rampColor[i]; } else { c = mix(paint.rampColor[i - 1], paint.rampColor[i], (t - p0) / (p1 - p0)); } } c = clamp(c, vec4<f32>(0.0), vec4<f32>(1.0)); return vec4<f32>(c.rgb * c.a, c.a); } fn gradientAt(t0: f32) -> vec4<f32> { if t0 != t0 { return vec4<f32>(0.0); } let tt = tileT(t0, i32(paint.shader.y + 0.5)); if tt.y == 0.0 { return vec4<f32>(0.0); } return rampAt(tt.x); } // The two-point conical gradient from the focal circle to the end circle: the color at a point // is that of the largest t whose circle, which moves and grows from one to the other, goes // through the point. fn conicalAt(q: vec2<f32>) -> vec4<f32> { let c0 = paint.p0.xy; let r0 = paint.p0.z; let cd = paint.p1.xy - c0; let dr = paint.p1.z - r0; let a = dot(cd, cd) - dr * dr; let p = q - c0; let b = dot(p, cd) + r0 * dr; let c = dot(p, p) - r0 * r0; var t: f32; if abs(a) < 1e-12 { if b == 0.0 { return vec4<f32>(0.0); } t = c / (2.0 * b); if r0 + t * dr < 0.0 { return vec4<f32>(0.0); } } else { let disc = b * b - a * c; if disc < 0.0 { return vec4<f32>(0.0); } let sq = sqrt(disc); var t1 = (b + sq) / a; var t2 = (b - sq) / a; if t1 < t2 { let tmp = t1; t1 = t2; t2 = tmp; } if r0 + t1 * dr >= 0.0 { t = t1; } else if r0 + t2 * dr >= 0.0 { t = t2; } else { return vec4<f32>(0.0); } } return gradientAt(t); } // ---- image shaders // A texel of the shader's image at a level, with the tile modes applied to the pixel's index; // transparent where decal draws nothing. fn shaderTexel(p: vec2<i32>, size: vec2<i32>, level: i32) -> vec4<f32> { var x = p.x; var y = p.y; let tileX = i32(paint.shader.y + 0.5); let tileY = i32(paint.shader.z + 0.5); if tileX == 1 { x = ((x % size.x) + size.x) % size.x; } else if tileX == 2 { let m = ((x % (2 * size.x)) + 2 * size.x) % (2 * size.x); if m >= size.x { x = 2 * size.x - 1 - m; } else { x = m; } } else if tileX == 3 { if x < 0 || x >= size.x { return vec4<f32>(0.0); } } else { x = clamp(x, 0, size.x - 1); } if tileY == 1 { y = ((y % size.y) + size.y) % size.y; } else if tileY == 2 { let m = ((y % (2 * size.y)) + 2 * size.y) % (2 * size.y); if m >= size.y { y = 2 * size.y - 1 - m; } else { y = m; } } else if tileY == 3 { if y < 0 || y >= size.y { return vec4<f32>(0.0); } } else { y = clamp(y, 0, size.y - 1); } return textureLoad(paintImage, vec2<i32>(x, y), level); } fn mitchellWeight(x0: f32) -> f32 { let b = 1.0 / 3.0; let c = 1.0 / 3.0; let x = abs(x0); if x < 1.0 { return ((12.0 - 9.0 * b - 6.0 * c) * x * x * x + (-18.0 + 12.0 * b + 6.0 * c) * x * x + (6.0 - 2.0 * b)) / 6.0; } if x < 2.0 { return ((-b - 6.0 * c) * x * x * x + (6.0 * b + 30.0 * c) * x * x + (-12.0 * b - 48.0 * c) * x + (8.0 * b + 24.0 * c)) / 6.0; } return 0.0; } // The shader's image at the point q of its pixels, with the filter quality. fn imageShaderAt(q: vec2<f32>) -> vec4<f32> { let base = vec2<i32>(textureDimensions(paintImage, 0)); let quality = i32(paint.imageInfo.x + 0.5); let level = i32(paint.imageInfo.y + 0.5); let size = vec2<i32>(textureDimensions(paintImage, level)); let uv = q * vec2<f32>(size) / vec2<f32>(base); if quality == 0 { return shaderTexel(vec2<i32>(floor(uv)), size, level); } let f = uv - vec2<f32>(0.5); let f0 = floor(f); let t = f - f0; let i0 = vec2<i32>(f0); if quality == 3 { var sum = vec4<f32>(0.0); for (var j = -1; j <= 2; j++) { let wy = mitchellWeight(f32(j) - t.y); for (var i = -1; i <= 2; i++) { sum += wy * mitchellWeight(f32(i) - t.x) * shaderTexel(i0 + vec2<i32>(i, j), size, level); } } let a = clamp(sum.a, 0.0, 1.0); return vec4<f32>(clamp(sum.rgb, vec3<f32>(0.0), vec3<f32>(a)), a); } let c00 = shaderTexel(i0, size, level); let c10 = shaderTexel(i0 + vec2<i32>(1, 0), size, level); let c01 = shaderTexel(i0 + vec2<i32>(0, 1), size, level); let c11 = shaderTexel(i0 + vec2<i32>(1, 1), size, level); return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); } // The premultiplied color of the shader at the pixel at p (or, for vertices, at the texture // coordinates p). fn shaderColor(p: vec2<f32>) -> vec4<f32> { let q = vec2<f32>( paint.xf0.x * p.x + paint.xf0.z * p.y + paint.xf1.x, paint.xf0.y * p.x + paint.xf0.w * p.y + paint.xf1.y); let kind = i32(paint.shader.x + 0.5); if kind == SHADER_LINEAR { return gradientAt(dot(q - paint.p0.xy, paint.p0.zw) * paint.p1.x); } if kind == SHADER_RADIAL { return gradientAt(length(q - paint.p0.xy) / paint.p0.z); } if kind == SHADER_CONICAL { return conicalAt(q); } if kind == SHADER_SWEEP { let d = q - paint.p0.xy; var a = atan2(d.y, d.x) - paint.p0.z; a = a - 2.0 * PI * floor(a / (2.0 * PI)); return gradientAt(a / paint.p0.w); } if kind == SHADER_IMAGE { return imageShaderAt(q); } return paint.constColor; } // ---- color filters fn unpremul(c: vec4<f32>) -> vec4<f32> { if c.a <= 0.0 { return vec4<f32>(0.0); } return vec4<f32>(clamp(c.rgb / c.a, vec3<f32>(0.0), vec3<f32>(1.0)), c.a); } fn premul(c: vec4<f32>) -> vec4<f32> { return vec4<f32>(c.rgb * c.a, c.a); } fn linearToSrgb(v: vec3<f32>) -> vec3<f32> { return select(1.055 * pow(v, vec3<f32>(1.0 / 2.4)) - vec3<f32>(0.055), 12.92 * v, v <= vec3<f32>(0.0031308)); } fn srgbToLinear(v: vec3<f32>) -> vec3<f32> { return select(pow((v + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4)), v / 12.92, v <= vec3<f32>(0.04045)); } // The paint's color filter, then its inverted colors. fn applyFilters(px0: vec4<f32>) -> vec4<f32> { var px = px0; let kind = i32(paint.flags.y + 0.5); if kind == 1 { px = blendPair(i32(paint.flags.z + 0.5), paint.filterColor, px); } else if kind == 2 { let c = unpremul(px) * 255.0; let o = paint.filterMatrix[0] * c.r + paint.filterMatrix[1] * c.g + paint.filterMatrix[2] * c.b + paint.filterMatrix[3] * c.a + paint.filterMatrix[4]; px = premul(clamp(o / 255.0, vec4<f32>(0.0), vec4<f32>(1.0))); } else if kind == 3 { let c = unpremul(px); px = premul(vec4<f32>(linearToSrgb(c.rgb), c.a)); } else if kind == 4 { let c = unpremul(px); px = premul(vec4<f32>(srgbToLinear(c.rgb), c.a)); } if paint.flags.w != 0.0 { let c = unpremul(px); px = premul(vec4<f32>(vec3<f32>(1.0) - c.rgb, c.a)); } return px; } // The source color of a paint at the pixel dev: base is the paint's color, premultiplied, or for // a shader its alpha in all four components; p is the point the shader is evaluated at. fn paintSource(base: vec4<f32>, p: vec2<f32>) -> vec4<f32> { var c = base; if i32(paint.shader.x + 0.5) != SHADER_NONE { c = shaderColor(p) * base; } return applyFilters(c); } // ---- output var<private> bayer: array<f32, 64> = array<f32, 64>( 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0); // The ordered dither of gradients: up to half a level of 8 bits either way. fn ditherAt(dev: vec2<f32>) -> f32 { let p = vec2<i32>(floor(dev)) & vec2<i32>(7); return ((bayer[p.y * 8 + p.x] + 0.5) / 64.0 - 0.5) / 255.0; } // The pixel of the copy of what is being drawn over at the pixel dev. fn destinationAt(dev: vec2<f32>) -> vec4<f32> { return textureLoad(dst, vec2<i32>(floor(dev)) - vec2<i32>(paint.blend.yz), 0); } // The color to write for the source src that covers the pixel by cov: with a fixed-function // blend, the source scaled by the coverage; with any other mode, the destination mixed toward // the blended color by the coverage. fn finish(src: vec4<f32>, cov: f32, dev: vec2<f32>) -> vec4<f32> { var o: vec4<f32>; if paint.blend.x < 0.0 { o = src * cov; } else { let d = destinationAt(dev); o = d + (blendPair(i32(paint.blend.x + 0.5), src, d) - d) * cov; } if paint.flags.x != 0.0 && src.a > 0.0 { o = o + vec4<f32>(ditherAt(dev)); } return o; } const PASS_COPY: i32 = 0; const PASS_BLUR: i32 = 1; const PASS_MORPH: i32 = 2; const PASS_MATRIX: i32 = 3; const PASS_COLOR: i32 = 4; const PASS_DOWN: i32 = 5; const PASS_UP: i32 = 6; // What a pass sets. struct Pass { // The pass kind, the axis (0 along x, 1 along y), the tile mode beyond the edges (0 clamp, // 1 repeated, 2 mirror, 3 decal), and 1 for a dilation or 0 for an erosion. kind: vec4<f32>, // The size of the source in pixels, and of the target. sizes: vec4<f32>, // The Gaussian's deviation, the taps on each side of the center, and 1 over the sum of the // weights. blur: vec4<f32>, // Resampling: the source pixels per output pixel in x and y; and the quality of a matrix pass // (0 bilinear, 1 nearest, 2 draws nothing). factor: vec4<f32>, // A matrix pass: from output to source pixels of the surface, a, b, c, d, then e, f and the // surface pixel of the layer's top left corner. mat0: vec4<f32>, mat1: vec4<f32>, } @group(0) @binding(1) var<uniform> params: Pass; @group(1) @binding(0) var src: texture_2d<f32>; struct VertexOutput { @builtin(position) position: vec4<f32>, } @vertex fn vs_main(@builtin(vertex_index) index: u32) -> VertexOutput { let p = vec2<f32>(f32((index << 1u) & 2u), f32(index & 2u)); var out: VertexOutput; out.position = vec4<f32>(p * 2.0 - 1.0, 0.0, 1.0); return out; } // i modulo m in 0..m-1, also for a negative i. fn floorMod(i: i32, m: i32) -> i32 { return i - m * i32(floor(f32(i) / f32(m))); } // The index in 0..n-1 that i stands for under the tile mode; the second component is 0 for // transparent. fn wrapIndex(i: i32, n: i32, mode: i32) -> vec2<i32> { if mode == 1 { return vec2<i32>(floorMod(i, n), 1); } if mode == 2 { let m = floorMod(i, 2 * n); return vec2<i32>(select(m, 2 * n - 1 - m, m >= n), 1); } if mode == 3 { return vec2<i32>(i, select(0, 1, i >= 0 && i < n)); } return vec2<i32>(clamp(i, 0, n - 1), 1); } // The pixel at column x and row y from the top of a texture of the given size. fn fetchTop(p: vec2<i32>, size: vec2<i32>, mode: i32) -> vec4<f32> { let x = wrapIndex(p.x, size.x, mode); let y = wrapIndex(p.y, size.y, mode); if x.y == 0 || y.y == 0 { return vec4<f32>(0.0); } return textureLoad(src, vec2<i32>(x.x, y.x), 0); } // The same without tiling: transparent outside. fn fetchOrClear(p: vec2<i32>, size: vec2<i32>) -> vec4<f32> { return fetchTop(p, size, 3); } @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> { let srcSize = vec2<i32>(params.sizes.xy + vec2<f32>(0.5)); let q = vec2<i32>(floor(in.position.xy)); let kind = i32(params.kind.x + 0.5); let axis = select(vec2<i32>(0, 1), vec2<i32>(1, 0), params.kind.y < 0.5); let tile = i32(params.kind.z + 0.5); let radius = i32(params.blur.y + 0.5); var o = vec4<f32>(0.0); if kind == PASS_COPY { o = fetchOrClear(q, srcSize); } else if kind == PASS_BLUR { let k = -0.5 / (params.blur.x * params.blur.x); for (var i = -radius; i <= radius; i++) { o += fetchTop(q + axis * i, srcSize, tile) * exp(f32(i * i) * k); } o *= params.blur.z; } else if kind == PASS_MORPH { let dilate = params.kind.w > 0.5; o = select(vec4<f32>(1.0), vec4<f32>(0.0), dilate); for (var i = -radius; i <= radius; i++) { let c = fetchOrClear(q + axis * i, srcSize); o = select(min(o, c), max(o, c), dilate); } } else if kind == PASS_MATRIX { if params.factor.z < 1.5 { let origin = params.mat1.zw; let dev = origin + vec2<f32>(q) + vec2<f32>(0.5); let s = vec2<f32>( params.mat0.x * dev.x + params.mat0.z * dev.y + params.mat1.x, params.mat0.y * dev.x + params.mat0.w * dev.y + params.mat1.y) - origin; if params.factor.z > 0.5 { o = fetchOrClear(vec2<i32>(floor(s)), srcSize); } else { let f = s - vec2<f32>(0.5); let i0 = vec2<i32>(floor(f)); let t = f - vec2<f32>(i0); let top = mix(fetchOrClear(i0, srcSize), fetchOrClear(i0 + vec2<i32>(1, 0), srcSize), t.x); let bot = mix(fetchOrClear(i0 + vec2<i32>(0, 1), srcSize), fetchOrClear(i0 + vec2<i32>(1, 1), srcSize), t.x); o = mix(top, bot, t.y); } } } else if kind == PASS_COLOR { o = clamp(applyFilters(fetchOrClear(q, srcSize)), vec4<f32>(0.0), vec4<f32>(1.0)); } else if kind == PASS_DOWN { let f = vec2<i32>(params.factor.xy + vec2<f32>(0.5)); for (var j = 0; j < f.y; j++) { for (var i = 0; i < f.x; i++) { o += fetchTop(q * f + vec2<i32>(i, j), srcSize, tile); } } o /= f32(f.x * f.y); } else { // Bilinear, from a picture with texels factor times as large. let f = (vec2<f32>(q) + vec2<f32>(0.5)) / params.factor.xy - vec2<f32>(0.5); let i0 = vec2<i32>(floor(f)); let t = f - vec2<f32>(i0); let top = mix(fetchTop(i0, srcSize, 0), fetchTop(i0 + vec2<i32>(1, 0), srcSize, 0), t.x); let bot = mix(fetchTop(i0 + vec2<i32>(0, 1), srcSize, 0), fetchTop(i0 + vec2<i32>(1, 1), srcSize, 0), t.x); o = mix(top, bot, t.y); } return o; } `, SPIRV: spirvFilter, Entries: []EntryPoint{ {Name: "vs_main", Stage: ShaderStageVertex, Bindings: []ShaderBinding{}}, {Name: "fs_main", Stage: ShaderStageFragment, Bindings: []ShaderBinding{ {Name: "params", Group: 0, Binding: 1, Kind: BindingUniformBuffer}, {Name: "paint", Group: 0, Binding: 2, Kind: BindingUniformBuffer}, {Name: "src", Group: 1, Binding: 0, Kind: BindingSampledTexture}, }}, }, }
ShaderFilter is shaders/filter.wgsl.
Flutter: no counterpart
var ShaderImage = &Shader{ Name: "image", WGSL: `// Images: one instance is one rectangle of an image, drawn through an affine transform. The // fragment shader maps each pixel back to the image's texels and samples them with the paint's // filter quality: nearest, bilinear, bilinear on one mip level, or bicubic. Ported from the // GLES image shaders (image.vert.glsl, image.frag.glsl). // Draw 6 vertices per instance. // The source color of a paint: a solid color, a gradient or an image shader, then the paint's // color filter and inverted colors, and the blend with what is already drawn. Ported from // gles/shaders/paint.glsl. Fragment shaders include this file, after blend.wgsl.inc. // // The 29 blend modes of Flutter's BlendMode, on premultiplied colors, as the software renderer // computes them (internal/gpu/soft/blend.go). mode is the index of the mode in BlendMode's // order: 0 clear, 1 src, 2 dst, 3 srcOver, 4 dstOver, 5 srcIn, 6 dstIn, 7 srcOut, 8 dstOut, // 9 srcATop, 10 dstATop, 11 xor, 12 plus, 13 modulate, 14 screen, 15 overlay, 16 darken, // 17 lighten, 18 colorDodge, 19 colorBurn, 20 hardLight, 21 softLight, 22 difference, // 23 exclusion, 24 multiply, 25 hue, 26 saturation, 27 color, 28 luminosity. Ported from // gles/shaders/blend.glsl. Shaders include this file with an include line. fn hardLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { if 2.0 * s <= sa { return s * (1.0 - da) + d * (1.0 - sa) + 2.0 * s * d; } return s * (1.0 - da) + d * (1.0 - sa) + sa * da - 2.0 * (da - d) * (sa - s); } fn softLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { var m = 0.0; if da > 0.0 { m = d / da; } let s2 = 2.0 * s; let m4 = 4.0 * m; let darkSrc = d * (sa + (s2 - sa) * (1.0 - m)); let darkDst = (m4 * m4 + m4) * (m - 1.0) + 7.0 * m; let liteDst = sqrt(m) - m; var tail = liteDst; if 4.0 * d <= da { tail = darkDst; } let liteSrc = d * sa + da * (s2 - sa) * tail; var body = liteSrc; if s2 <= sa { body = darkSrc; } return s * (1.0 - da) + d * (1.0 - sa) + body; } fn blendChannel(mode: i32, s: f32, d: f32, sa: f32, da: f32) -> f32 { switch mode { case 15: { return hardLightChannel(d, s, da, sa); // overlay } case 16: { return s + d - max(s * da, d * sa); // darken } case 17: { return s + d - min(s * da, d * sa); // lighten } case 18: { // colorDodge if d == 0.0 { return s * (1.0 - da); } if s == sa { return s + d * (1.0 - sa); } return sa * min(da, d * sa / (sa - s)) + s * (1.0 - da) + d * (1.0 - sa); } case 19: { // colorBurn if d == da { return d + s * (1.0 - da); } if s == 0.0 { return d * (1.0 - sa); } return sa * (da - min(da, (da - d) * sa / s)) + s * (1.0 - da) + d * (1.0 - sa); } case 20: { return hardLightChannel(s, d, sa, da); // hardLight } case 21: { return softLightChannel(s, d, sa, da); // softLight } case 22: { return s + d - 2.0 * min(s * da, d * sa); // difference } case 23: { return s + d - 2.0 * s * d; // exclusion } case 24: { return s * (1.0 - da) + d * (1.0 - sa) + s * d; // multiply } default: { return s + d * (1.0 - sa); } } } fn lum(c: vec3<f32>) -> f32 { return 0.30 * c.r + 0.59 * c.g + 0.11 * c.b; } fn sat(c: vec3<f32>) -> f32 { return max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b)); } fn setSat(c: vec3<f32>, s: f32) -> vec3<f32> { let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let range = mx - mn; if range == 0.0 { return vec3<f32>(0.0); } return (c - vec3<f32>(mn)) * s / range; } fn setLum(c: vec3<f32>, l: f32) -> vec3<f32> { return c + vec3<f32>(l - lum(c)); } fn clipColor(c0: vec3<f32>, a: f32) -> vec3<f32> { var c = c0; let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let l = lum(c); if mn < 0.0 { c = vec3<f32>(l) + (c - vec3<f32>(l)) * l / (l - mn); } if mx > a { c = vec3<f32>(l) + (c - vec3<f32>(l)) * (a - l) / (mx - l); } return max(c, vec3<f32>(0.0)); } fn blendNonSeparable(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; var c: vec3<f32>; if mode == 25 { // hue c = s.rgb * sa; c = setSat(c, sat(d.rgb) * sa); c = setLum(c, lum(d.rgb) * sa); } else if mode == 26 { // saturation c = d.rgb * sa; c = setSat(c, sat(s.rgb) * da); c = setLum(c, lum(d.rgb) * sa); } else if mode == 27 { // color c = s.rgb * da; c = setLum(c, lum(d.rgb) * sa); } else { // luminosity c = d.rgb * sa; c = setLum(c, lum(s.rgb) * da); } c = clipColor(c, sa * da); return vec4<f32>(s.rgb * (1.0 - da) + d.rgb * (1.0 - sa) + c, sa + da - sa * da); } // blendPair blends the source s over the destination d with the mode. fn blendPair(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; switch mode { case 0: { return vec4<f32>(0.0); } case 1: { return s; } case 2: { return d; } case 3: { return s + d * (1.0 - sa); } case 4: { return d + s * (1.0 - da); } case 5: { return s * da; } case 6: { return d * sa; } case 7: { return s * (1.0 - da); } case 8: { return d * (1.0 - sa); } case 9: { return s * da + d * (1.0 - sa); } case 10: { return d * sa + s * (1.0 - da); } case 11: { return s * (1.0 - da) + d * (1.0 - sa); } case 12: { return min(s + d, vec4<f32>(1.0)); } case 13: { return s * d; } case 14: { return s + d - s * d; } case 25, 26, 27, 28: { return blendNonSeparable(mode, s, d); } default: { // The separable modes defined per channel, whose alpha is that of source-over. return vec4<f32>( blendChannel(mode, s.r, d.r, sa, da), blendChannel(mode, s.g, d.g, sa, da), blendChannel(mode, s.b, d.b, sa, da), sa + da - sa * da); } } } const SHADER_NONE: i32 = 0; const SHADER_LINEAR: i32 = 1; const SHADER_RADIAL: i32 = 2; const SHADER_CONICAL: i32 = 3; const SHADER_SWEEP: i32 = 4; const SHADER_IMAGE: i32 = 5; const SHADER_CONST: i32 = 6; const MAX_STOPS: i32 = 32; const PI: f32 = 3.14159265358979; // What a draw call's paint sets, the layout of gpu.PaintSpec as float4s (see paintUniform). struct Paint { // The shader kind, the tile modes in x and y (0 clamp, 1 repeated, 2 mirror, 3 decal) and // the number of color stops. shader: vec4<f32>, // The matrix from pixels to the shader's space: a, b, c, d, then e, f. xf0: vec4<f32>, xf1: vec4<f32>, // linear: from x, y, dx, dy; radial: center x, y, radius; conical: focal x, y, focal radius; // sweep: center x, y, start, span. p0: vec4<f32>, // linear: 1 / (dx*dx + dy*dy); conical: end center x, y, end radius. p1: vec4<f32>, // The image shader's quality (0 none, 1 low, 2 medium, 3 high) and level. imageInfo: vec4<f32>, // A degenerate gradient: premultiplied color. constColor: vec4<f32>, // Dither (0 or 1), the color filter (0 none, 1 mode, 2 matrix, 3 linear to sRGB, 4 sRGB to // linear), the blend index of a mode filter, and inverted colors (0 or 1). flags: vec4<f32>, // The blend index of a blend that reads the destination (-1: the blend unit does it), and the // pixel of the surface that the copy of the destination starts at. blend: vec4<f32>, // A mode filter's premultiplied color. filterColor: vec4<f32>, // A matrix filter: the columns of the 4x5 matrix in 0 to 255 units. filterMatrix: array<vec4<f32>, 5>, // The gradient's colors (not premultiplied) and positions, four to a float4. rampColor: array<vec4<f32>, 32>, rampPos: array<vec4<f32>, 8>, } @group(0) @binding(2) var<uniform> paint: Paint; // The image of an image shader, and a copy of the pixels being drawn over. @group(3) @binding(0) var paintImage: texture_2d<f32>; @group(3) @binding(1) var dst: texture_2d<f32>; // ---- gradients // Applies the tile mode to a position along a gradient; the second component is 0 where the // shader draws nothing. fn tileT(t: f32, mode: i32) -> vec2<f32> { if mode == 1 { return vec2<f32>(t - floor(t), 1.0); } if mode == 2 { let u = t - 2.0 * floor(t / 2.0); if u > 1.0 { return vec2<f32>(2.0 - u, 1.0); } return vec2<f32>(u, 1.0); } if mode == 3 { if t >= 0.0 && t <= 1.0 { return vec2<f32>(t, 1.0); } return vec2<f32>(t, 0.0); } return vec2<f32>(clamp(t, 0.0, 1.0), 1.0); } fn rampPosAt(i: i32) -> f32 { return paint.rampPos[i >> 2u][i & 3]; } // The premultiplied color at t, interpolated without premultiplied alpha. fn rampAt(t: f32) -> vec4<f32> { let n = i32(paint.shader.w + 0.5); var i = 0; while i < n && rampPosAt(i) < t { i++; } var c: vec4<f32>; if i == 0 { c = paint.rampColor[0]; } else if i >= n { c = paint.rampColor[n - 1]; } else { let p0 = rampPosAt(i - 1); let p1 = rampPosAt(i); if p1 <= p0 { c = paint.rampColor[i]; } else { c = mix(paint.rampColor[i - 1], paint.rampColor[i], (t - p0) / (p1 - p0)); } } c = clamp(c, vec4<f32>(0.0), vec4<f32>(1.0)); return vec4<f32>(c.rgb * c.a, c.a); } fn gradientAt(t0: f32) -> vec4<f32> { if t0 != t0 { return vec4<f32>(0.0); } let tt = tileT(t0, i32(paint.shader.y + 0.5)); if tt.y == 0.0 { return vec4<f32>(0.0); } return rampAt(tt.x); } // The two-point conical gradient from the focal circle to the end circle: the color at a point // is that of the largest t whose circle, which moves and grows from one to the other, goes // through the point. fn conicalAt(q: vec2<f32>) -> vec4<f32> { let c0 = paint.p0.xy; let r0 = paint.p0.z; let cd = paint.p1.xy - c0; let dr = paint.p1.z - r0; let a = dot(cd, cd) - dr * dr; let p = q - c0; let b = dot(p, cd) + r0 * dr; let c = dot(p, p) - r0 * r0; var t: f32; if abs(a) < 1e-12 { if b == 0.0 { return vec4<f32>(0.0); } t = c / (2.0 * b); if r0 + t * dr < 0.0 { return vec4<f32>(0.0); } } else { let disc = b * b - a * c; if disc < 0.0 { return vec4<f32>(0.0); } let sq = sqrt(disc); var t1 = (b + sq) / a; var t2 = (b - sq) / a; if t1 < t2 { let tmp = t1; t1 = t2; t2 = tmp; } if r0 + t1 * dr >= 0.0 { t = t1; } else if r0 + t2 * dr >= 0.0 { t = t2; } else { return vec4<f32>(0.0); } } return gradientAt(t); } // ---- image shaders // A texel of the shader's image at a level, with the tile modes applied to the pixel's index; // transparent where decal draws nothing. fn shaderTexel(p: vec2<i32>, size: vec2<i32>, level: i32) -> vec4<f32> { var x = p.x; var y = p.y; let tileX = i32(paint.shader.y + 0.5); let tileY = i32(paint.shader.z + 0.5); if tileX == 1 { x = ((x % size.x) + size.x) % size.x; } else if tileX == 2 { let m = ((x % (2 * size.x)) + 2 * size.x) % (2 * size.x); if m >= size.x { x = 2 * size.x - 1 - m; } else { x = m; } } else if tileX == 3 { if x < 0 || x >= size.x { return vec4<f32>(0.0); } } else { x = clamp(x, 0, size.x - 1); } if tileY == 1 { y = ((y % size.y) + size.y) % size.y; } else if tileY == 2 { let m = ((y % (2 * size.y)) + 2 * size.y) % (2 * size.y); if m >= size.y { y = 2 * size.y - 1 - m; } else { y = m; } } else if tileY == 3 { if y < 0 || y >= size.y { return vec4<f32>(0.0); } } else { y = clamp(y, 0, size.y - 1); } return textureLoad(paintImage, vec2<i32>(x, y), level); } fn mitchellWeight(x0: f32) -> f32 { let b = 1.0 / 3.0; let c = 1.0 / 3.0; let x = abs(x0); if x < 1.0 { return ((12.0 - 9.0 * b - 6.0 * c) * x * x * x + (-18.0 + 12.0 * b + 6.0 * c) * x * x + (6.0 - 2.0 * b)) / 6.0; } if x < 2.0 { return ((-b - 6.0 * c) * x * x * x + (6.0 * b + 30.0 * c) * x * x + (-12.0 * b - 48.0 * c) * x + (8.0 * b + 24.0 * c)) / 6.0; } return 0.0; } // The shader's image at the point q of its pixels, with the filter quality. fn imageShaderAt(q: vec2<f32>) -> vec4<f32> { let base = vec2<i32>(textureDimensions(paintImage, 0)); let quality = i32(paint.imageInfo.x + 0.5); let level = i32(paint.imageInfo.y + 0.5); let size = vec2<i32>(textureDimensions(paintImage, level)); let uv = q * vec2<f32>(size) / vec2<f32>(base); if quality == 0 { return shaderTexel(vec2<i32>(floor(uv)), size, level); } let f = uv - vec2<f32>(0.5); let f0 = floor(f); let t = f - f0; let i0 = vec2<i32>(f0); if quality == 3 { var sum = vec4<f32>(0.0); for (var j = -1; j <= 2; j++) { let wy = mitchellWeight(f32(j) - t.y); for (var i = -1; i <= 2; i++) { sum += wy * mitchellWeight(f32(i) - t.x) * shaderTexel(i0 + vec2<i32>(i, j), size, level); } } let a = clamp(sum.a, 0.0, 1.0); return vec4<f32>(clamp(sum.rgb, vec3<f32>(0.0), vec3<f32>(a)), a); } let c00 = shaderTexel(i0, size, level); let c10 = shaderTexel(i0 + vec2<i32>(1, 0), size, level); let c01 = shaderTexel(i0 + vec2<i32>(0, 1), size, level); let c11 = shaderTexel(i0 + vec2<i32>(1, 1), size, level); return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); } // The premultiplied color of the shader at the pixel at p (or, for vertices, at the texture // coordinates p). fn shaderColor(p: vec2<f32>) -> vec4<f32> { let q = vec2<f32>( paint.xf0.x * p.x + paint.xf0.z * p.y + paint.xf1.x, paint.xf0.y * p.x + paint.xf0.w * p.y + paint.xf1.y); let kind = i32(paint.shader.x + 0.5); if kind == SHADER_LINEAR { return gradientAt(dot(q - paint.p0.xy, paint.p0.zw) * paint.p1.x); } if kind == SHADER_RADIAL { return gradientAt(length(q - paint.p0.xy) / paint.p0.z); } if kind == SHADER_CONICAL { return conicalAt(q); } if kind == SHADER_SWEEP { let d = q - paint.p0.xy; var a = atan2(d.y, d.x) - paint.p0.z; a = a - 2.0 * PI * floor(a / (2.0 * PI)); return gradientAt(a / paint.p0.w); } if kind == SHADER_IMAGE { return imageShaderAt(q); } return paint.constColor; } // ---- color filters fn unpremul(c: vec4<f32>) -> vec4<f32> { if c.a <= 0.0 { return vec4<f32>(0.0); } return vec4<f32>(clamp(c.rgb / c.a, vec3<f32>(0.0), vec3<f32>(1.0)), c.a); } fn premul(c: vec4<f32>) -> vec4<f32> { return vec4<f32>(c.rgb * c.a, c.a); } fn linearToSrgb(v: vec3<f32>) -> vec3<f32> { return select(1.055 * pow(v, vec3<f32>(1.0 / 2.4)) - vec3<f32>(0.055), 12.92 * v, v <= vec3<f32>(0.0031308)); } fn srgbToLinear(v: vec3<f32>) -> vec3<f32> { return select(pow((v + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4)), v / 12.92, v <= vec3<f32>(0.04045)); } // The paint's color filter, then its inverted colors. fn applyFilters(px0: vec4<f32>) -> vec4<f32> { var px = px0; let kind = i32(paint.flags.y + 0.5); if kind == 1 { px = blendPair(i32(paint.flags.z + 0.5), paint.filterColor, px); } else if kind == 2 { let c = unpremul(px) * 255.0; let o = paint.filterMatrix[0] * c.r + paint.filterMatrix[1] * c.g + paint.filterMatrix[2] * c.b + paint.filterMatrix[3] * c.a + paint.filterMatrix[4]; px = premul(clamp(o / 255.0, vec4<f32>(0.0), vec4<f32>(1.0))); } else if kind == 3 { let c = unpremul(px); px = premul(vec4<f32>(linearToSrgb(c.rgb), c.a)); } else if kind == 4 { let c = unpremul(px); px = premul(vec4<f32>(srgbToLinear(c.rgb), c.a)); } if paint.flags.w != 0.0 { let c = unpremul(px); px = premul(vec4<f32>(vec3<f32>(1.0) - c.rgb, c.a)); } return px; } // The source color of a paint at the pixel dev: base is the paint's color, premultiplied, or for // a shader its alpha in all four components; p is the point the shader is evaluated at. fn paintSource(base: vec4<f32>, p: vec2<f32>) -> vec4<f32> { var c = base; if i32(paint.shader.x + 0.5) != SHADER_NONE { c = shaderColor(p) * base; } return applyFilters(c); } // ---- output var<private> bayer: array<f32, 64> = array<f32, 64>( 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0); // The ordered dither of gradients: up to half a level of 8 bits either way. fn ditherAt(dev: vec2<f32>) -> f32 { let p = vec2<i32>(floor(dev)) & vec2<i32>(7); return ((bayer[p.y * 8 + p.x] + 0.5) / 64.0 - 0.5) / 255.0; } // The pixel of the copy of what is being drawn over at the pixel dev. fn destinationAt(dev: vec2<f32>) -> vec4<f32> { return textureLoad(dst, vec2<i32>(floor(dev)) - vec2<i32>(paint.blend.yz), 0); } // The color to write for the source src that covers the pixel by cov: with a fixed-function // blend, the source scaled by the coverage; with any other mode, the destination mixed toward // the blended color by the coverage. fn finish(src: vec4<f32>, cov: f32, dev: vec2<f32>) -> vec4<f32> { var o: vec4<f32>; if paint.blend.x < 0.0 { o = src * cov; } else { let d = destinationAt(dev); o = d + (blendPair(i32(paint.blend.x + 0.5), src, d) - d) * cov; } if paint.flags.x != 0.0 && src.a > 0.0 { o = o + vec4<f32>(ditherAt(dev)); } return o; } struct Frame { // The size of the texture being drawn into, in pixels. surface: vec2<f32>, // The pixel of the surface that the texture's top left corner is. origin: vec2<f32>, } // The clip mask's rectangle in the surface (x, y, width, height; a width of 0 means none). struct Draw { clipMask: vec4<f32>, } @group(0) @binding(0) var<uniform> frame: Frame; @group(0) @binding(1) var<uniform> draw: Draw; @group(1) @binding(0) var clipMask: texture_2d<f32>; // The image: premultiplied RGBA with mipmaps, and a linear sampler that picks a level. @group(2) @binding(0) var image: texture_2d<f32>; @group(2) @binding(1) var imageSampler: sampler; struct Instance { @location(0) quad: vec4<f32>, // left, top, right, bottom in pixels @location(1) inv0: vec4<f32>, // pixels to texels: a, b, c, d @location(2) inv1: vec4<f32>, // e, f, flags, unused @location(3) color: vec4<f32>, // premultiplied multiplier: the paint's alpha @location(4) clip: vec4<f32>, // left, top, right, bottom in pixels @location(5) box: vec4<f32>, // the rectangle drawn: texels, or pixels with the box flag @location(6) img: vec4<f32>, // level of detail, quality, blend index (-1 none), unused @location(7) tint: vec4<f32>, // premultiplied color blended with the image } struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) dev: vec2<f32>, @location(1) @interpolate(flat) inv0: vec4<f32>, @location(2) @interpolate(flat) inv1: vec4<f32>, @location(3) @interpolate(flat) color: vec4<f32>, @location(4) @interpolate(flat) clip: vec4<f32>, @location(5) @interpolate(flat) box: vec4<f32>, @location(6) @interpolate(flat) img: vec4<f32>, @location(7) @interpolate(flat) tint: vec4<f32>, } const FLAG_BOX: i32 = 1; // box is in pixels: exact coverage of an axis-aligned rectangle const FLAG_ANTIALIAS: i32 = 2; const QUALITY_NONE: i32 = 0; const QUALITY_HIGH: i32 = 3; fn toClip(dev: vec2<f32>) -> vec4<f32> { let p = dev - frame.origin; return vec4<f32>(p.x / frame.surface.x * 2.0 - 1.0, 1.0 - p.y / frame.surface.y * 2.0, 0.0, 1.0); } @vertex fn vs_main(@builtin(vertex_index) index: u32, instance: Instance) -> VertexOutput { var corners = array<vec2<f32>, 6>( vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0), vec2<f32>(0.0, 1.0), ); let dev = mix(instance.quad.xy, instance.quad.zw, corners[index]); var out: VertexOutput; out.position = toClip(dev); out.dev = dev; out.inv0 = instance.inv0; out.inv1 = instance.inv1; out.color = instance.color; out.clip = instance.clip; out.box = instance.box; out.img = instance.img; out.tint = instance.tint; return out; } // The part of the pixel centered at c that the interval [lo, hi] covers. fn span(c: f32, lo: f32, hi: f32) -> f32 { return clamp(min(c + 0.5, hi) - max(c - 0.5, lo), 0.0, 1.0); } // The part of the pixel centered at dev that the rectangle r covers; without antialiasing, 1 // when the center is inside. fn boxCoverage(dev: vec2<f32>, r: vec4<f32>, antialias: bool) -> f32 { if antialias { return span(dev.x, r.x, r.z) * span(dev.y, r.y, r.w); } if dev.x >= r.x && dev.x < r.z && dev.y >= r.y && dev.y < r.w { return 1.0; } return 0.0; } fn clipMaskCoverage(dev: vec2<f32>) -> f32 { if draw.clipMask.z <= 0.0 { return 1.0; } let p = vec2<i32>(floor(dev)) - vec2<i32>(draw.clipMask.xy); if p.x < 0 || p.y < 0 || p.x >= i32(draw.clipMask.z) || p.y >= i32(draw.clipMask.w) { return 0.0; } return textureLoad(clipMask, p, 0).r; } // The Mitchell-Netravali cubic with B = C = 1/3. fn mitchell(x0: f32) -> f32 { let b = 1.0 / 3.0; let c = 1.0 / 3.0; let x = abs(x0); if x < 1.0 { return ((12.0 - 9.0 * b - 6.0 * c) * x * x * x + (-18.0 + 12.0 * b + 6.0 * c) * x * x + (6.0 - 2.0 * b)) / 6.0; } if x < 2.0 { return ((-b - 6.0 * c) * x * x * x + (6.0 * b + 30.0 * c) * x * x + (-12.0 * b - 48.0 * c) * x + (8.0 * b + 24.0 * c)) / 6.0; } return 0.0; } // A texel of a level, with the edge repeated outside. fn texel(p: vec2<i32>, size: vec2<i32>, level: i32) -> vec4<f32> { return textureLoad(image, clamp(p, vec2<i32>(0), size - vec2<i32>(1)), level); } fn bicubic(uv: vec2<f32>, base: vec2<i32>, level: i32) -> vec4<f32> { let size = vec2<i32>(textureDimensions(image, level)); let f = uv * vec2<f32>(size) / vec2<f32>(base) - vec2<f32>(0.5); let f0 = floor(f); let t = f - f0; var sum = vec4<f32>(0.0); for (var j = -1; j <= 2; j++) { let wy = mitchell(f32(j) - t.y); for (var i = -1; i <= 2; i++) { let w = wy * mitchell(f32(i) - t.x); sum += w * texel(vec2<i32>(f0) + vec2<i32>(i, j), size, level); } } // The cubic can overshoot: keep a valid premultiplied color. let a = clamp(sum.a, 0.0, 1.0); return vec4<f32>(clamp(sum.rgb, vec3<f32>(0.0), vec3<f32>(a)), a); } @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> { let dev = floor(in.dev) + vec2<f32>(0.5); let flags = i32(in.inv1.z + 0.5); let aa = (flags & FLAG_ANTIALIAS) != 0; let uv = vec2<f32>( in.inv0.x * dev.x + in.inv0.z * dev.y + in.inv1.x, in.inv0.y * dev.x + in.inv0.w * dev.y + in.inv1.y); // The rectangle in texels: the distance outside it, in pixels by the screen derivatives. // The derivatives come before anything that returns or discards. let c = (in.box.xy + in.box.zw) * 0.5; let q = abs(uv - c) - (in.box.zw - in.box.xy) * 0.5; let d = max(q.x, q.y); let g = length(vec2<f32>(dpdx(d), dpdy(d))); var coverage: f32; if (flags & FLAG_BOX) != 0 { coverage = boxCoverage(dev, in.box, aa); } else if aa { var pixels = select(1.0, -1.0, d <= 0.0); if g > 1e-9 { pixels = d / g; } coverage = clamp(0.5 - pixels, 0.0, 1.0); } else { coverage = select(0.0, 1.0, d <= 0.0); } coverage = coverage * span(dev.x, in.clip.x, in.clip.z) * span(dev.y, in.clip.y, in.clip.w) * clipMaskCoverage(dev); let base = vec2<i32>(textureDimensions(image, 0)); let quality = i32(in.img.y + 0.5); var color: vec4<f32>; if quality == QUALITY_NONE { color = texel(vec2<i32>(floor(uv)), base, 0); } else if quality == QUALITY_HIGH { color = bicubic(uv, base, i32(in.img.x + 0.5)); } else { color = textureSampleLevel(image, imageSampler, uv / vec2<f32>(base), in.img.x); } color = color * in.color; if in.img.z >= 0.0 { color = blendPair(i32(in.img.z + 0.5), color, in.tint); } color = applyFilters(color); if coverage <= 0.0 { discard; } return finish(color, coverage, dev); } `, SPIRV: spirvImage, Entries: []EntryPoint{ {Name: "vs_main", Stage: ShaderStageVertex, Bindings: []ShaderBinding{ {Name: "frame", Group: 0, Binding: 0, Kind: BindingUniformBuffer}, }}, {Name: "fs_main", Stage: ShaderStageFragment, Bindings: []ShaderBinding{ {Name: "draw", Group: 0, Binding: 1, Kind: BindingUniformBuffer}, {Name: "paint", Group: 0, Binding: 2, Kind: BindingUniformBuffer}, {Name: "clipMask", Group: 1, Binding: 0, Kind: BindingSampledTexture}, {Name: "image", Group: 2, Binding: 0, Kind: BindingSampledTexture}, {Name: "imageSampler", Group: 2, Binding: 1, Kind: BindingSampler}, {Name: "dst", Group: 3, Binding: 1, Kind: BindingSampledTexture}, }}, }, }
ShaderImage is shaders/image.wgsl.
Flutter: no counterpart
var ShaderLayer = &Shader{ Name: "layer", WGSL: `// A layer composited into its parent: one instance is the rectangle of the layer's pixels that // the clip leaves. Ported from the GLES layer shaders (layer.vert.glsl, layer.frag.glsl). Draw 6 // vertices per instance. // The source color of a paint: a solid color, a gradient or an image shader, then the paint's // color filter and inverted colors, and the blend with what is already drawn. Ported from // gles/shaders/paint.glsl. Fragment shaders include this file, after blend.wgsl.inc. // // The 29 blend modes of Flutter's BlendMode, on premultiplied colors, as the software renderer // computes them (internal/gpu/soft/blend.go). mode is the index of the mode in BlendMode's // order: 0 clear, 1 src, 2 dst, 3 srcOver, 4 dstOver, 5 srcIn, 6 dstIn, 7 srcOut, 8 dstOut, // 9 srcATop, 10 dstATop, 11 xor, 12 plus, 13 modulate, 14 screen, 15 overlay, 16 darken, // 17 lighten, 18 colorDodge, 19 colorBurn, 20 hardLight, 21 softLight, 22 difference, // 23 exclusion, 24 multiply, 25 hue, 26 saturation, 27 color, 28 luminosity. Ported from // gles/shaders/blend.glsl. Shaders include this file with an include line. fn hardLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { if 2.0 * s <= sa { return s * (1.0 - da) + d * (1.0 - sa) + 2.0 * s * d; } return s * (1.0 - da) + d * (1.0 - sa) + sa * da - 2.0 * (da - d) * (sa - s); } fn softLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { var m = 0.0; if da > 0.0 { m = d / da; } let s2 = 2.0 * s; let m4 = 4.0 * m; let darkSrc = d * (sa + (s2 - sa) * (1.0 - m)); let darkDst = (m4 * m4 + m4) * (m - 1.0) + 7.0 * m; let liteDst = sqrt(m) - m; var tail = liteDst; if 4.0 * d <= da { tail = darkDst; } let liteSrc = d * sa + da * (s2 - sa) * tail; var body = liteSrc; if s2 <= sa { body = darkSrc; } return s * (1.0 - da) + d * (1.0 - sa) + body; } fn blendChannel(mode: i32, s: f32, d: f32, sa: f32, da: f32) -> f32 { switch mode { case 15: { return hardLightChannel(d, s, da, sa); // overlay } case 16: { return s + d - max(s * da, d * sa); // darken } case 17: { return s + d - min(s * da, d * sa); // lighten } case 18: { // colorDodge if d == 0.0 { return s * (1.0 - da); } if s == sa { return s + d * (1.0 - sa); } return sa * min(da, d * sa / (sa - s)) + s * (1.0 - da) + d * (1.0 - sa); } case 19: { // colorBurn if d == da { return d + s * (1.0 - da); } if s == 0.0 { return d * (1.0 - sa); } return sa * (da - min(da, (da - d) * sa / s)) + s * (1.0 - da) + d * (1.0 - sa); } case 20: { return hardLightChannel(s, d, sa, da); // hardLight } case 21: { return softLightChannel(s, d, sa, da); // softLight } case 22: { return s + d - 2.0 * min(s * da, d * sa); // difference } case 23: { return s + d - 2.0 * s * d; // exclusion } case 24: { return s * (1.0 - da) + d * (1.0 - sa) + s * d; // multiply } default: { return s + d * (1.0 - sa); } } } fn lum(c: vec3<f32>) -> f32 { return 0.30 * c.r + 0.59 * c.g + 0.11 * c.b; } fn sat(c: vec3<f32>) -> f32 { return max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b)); } fn setSat(c: vec3<f32>, s: f32) -> vec3<f32> { let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let range = mx - mn; if range == 0.0 { return vec3<f32>(0.0); } return (c - vec3<f32>(mn)) * s / range; } fn setLum(c: vec3<f32>, l: f32) -> vec3<f32> { return c + vec3<f32>(l - lum(c)); } fn clipColor(c0: vec3<f32>, a: f32) -> vec3<f32> { var c = c0; let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let l = lum(c); if mn < 0.0 { c = vec3<f32>(l) + (c - vec3<f32>(l)) * l / (l - mn); } if mx > a { c = vec3<f32>(l) + (c - vec3<f32>(l)) * (a - l) / (mx - l); } return max(c, vec3<f32>(0.0)); } fn blendNonSeparable(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; var c: vec3<f32>; if mode == 25 { // hue c = s.rgb * sa; c = setSat(c, sat(d.rgb) * sa); c = setLum(c, lum(d.rgb) * sa); } else if mode == 26 { // saturation c = d.rgb * sa; c = setSat(c, sat(s.rgb) * da); c = setLum(c, lum(d.rgb) * sa); } else if mode == 27 { // color c = s.rgb * da; c = setLum(c, lum(d.rgb) * sa); } else { // luminosity c = d.rgb * sa; c = setLum(c, lum(s.rgb) * da); } c = clipColor(c, sa * da); return vec4<f32>(s.rgb * (1.0 - da) + d.rgb * (1.0 - sa) + c, sa + da - sa * da); } // blendPair blends the source s over the destination d with the mode. fn blendPair(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; switch mode { case 0: { return vec4<f32>(0.0); } case 1: { return s; } case 2: { return d; } case 3: { return s + d * (1.0 - sa); } case 4: { return d + s * (1.0 - da); } case 5: { return s * da; } case 6: { return d * sa; } case 7: { return s * (1.0 - da); } case 8: { return d * (1.0 - sa); } case 9: { return s * da + d * (1.0 - sa); } case 10: { return d * sa + s * (1.0 - da); } case 11: { return s * (1.0 - da) + d * (1.0 - sa); } case 12: { return min(s + d, vec4<f32>(1.0)); } case 13: { return s * d; } case 14: { return s + d - s * d; } case 25, 26, 27, 28: { return blendNonSeparable(mode, s, d); } default: { // The separable modes defined per channel, whose alpha is that of source-over. return vec4<f32>( blendChannel(mode, s.r, d.r, sa, da), blendChannel(mode, s.g, d.g, sa, da), blendChannel(mode, s.b, d.b, sa, da), sa + da - sa * da); } } } const SHADER_NONE: i32 = 0; const SHADER_LINEAR: i32 = 1; const SHADER_RADIAL: i32 = 2; const SHADER_CONICAL: i32 = 3; const SHADER_SWEEP: i32 = 4; const SHADER_IMAGE: i32 = 5; const SHADER_CONST: i32 = 6; const MAX_STOPS: i32 = 32; const PI: f32 = 3.14159265358979; // What a draw call's paint sets, the layout of gpu.PaintSpec as float4s (see paintUniform). struct Paint { // The shader kind, the tile modes in x and y (0 clamp, 1 repeated, 2 mirror, 3 decal) and // the number of color stops. shader: vec4<f32>, // The matrix from pixels to the shader's space: a, b, c, d, then e, f. xf0: vec4<f32>, xf1: vec4<f32>, // linear: from x, y, dx, dy; radial: center x, y, radius; conical: focal x, y, focal radius; // sweep: center x, y, start, span. p0: vec4<f32>, // linear: 1 / (dx*dx + dy*dy); conical: end center x, y, end radius. p1: vec4<f32>, // The image shader's quality (0 none, 1 low, 2 medium, 3 high) and level. imageInfo: vec4<f32>, // A degenerate gradient: premultiplied color. constColor: vec4<f32>, // Dither (0 or 1), the color filter (0 none, 1 mode, 2 matrix, 3 linear to sRGB, 4 sRGB to // linear), the blend index of a mode filter, and inverted colors (0 or 1). flags: vec4<f32>, // The blend index of a blend that reads the destination (-1: the blend unit does it), and the // pixel of the surface that the copy of the destination starts at. blend: vec4<f32>, // A mode filter's premultiplied color. filterColor: vec4<f32>, // A matrix filter: the columns of the 4x5 matrix in 0 to 255 units. filterMatrix: array<vec4<f32>, 5>, // The gradient's colors (not premultiplied) and positions, four to a float4. rampColor: array<vec4<f32>, 32>, rampPos: array<vec4<f32>, 8>, } @group(0) @binding(2) var<uniform> paint: Paint; // The image of an image shader, and a copy of the pixels being drawn over. @group(3) @binding(0) var paintImage: texture_2d<f32>; @group(3) @binding(1) var dst: texture_2d<f32>; // ---- gradients // Applies the tile mode to a position along a gradient; the second component is 0 where the // shader draws nothing. fn tileT(t: f32, mode: i32) -> vec2<f32> { if mode == 1 { return vec2<f32>(t - floor(t), 1.0); } if mode == 2 { let u = t - 2.0 * floor(t / 2.0); if u > 1.0 { return vec2<f32>(2.0 - u, 1.0); } return vec2<f32>(u, 1.0); } if mode == 3 { if t >= 0.0 && t <= 1.0 { return vec2<f32>(t, 1.0); } return vec2<f32>(t, 0.0); } return vec2<f32>(clamp(t, 0.0, 1.0), 1.0); } fn rampPosAt(i: i32) -> f32 { return paint.rampPos[i >> 2u][i & 3]; } // The premultiplied color at t, interpolated without premultiplied alpha. fn rampAt(t: f32) -> vec4<f32> { let n = i32(paint.shader.w + 0.5); var i = 0; while i < n && rampPosAt(i) < t { i++; } var c: vec4<f32>; if i == 0 { c = paint.rampColor[0]; } else if i >= n { c = paint.rampColor[n - 1]; } else { let p0 = rampPosAt(i - 1); let p1 = rampPosAt(i); if p1 <= p0 { c = paint.rampColor[i]; } else { c = mix(paint.rampColor[i - 1], paint.rampColor[i], (t - p0) / (p1 - p0)); } } c = clamp(c, vec4<f32>(0.0), vec4<f32>(1.0)); return vec4<f32>(c.rgb * c.a, c.a); } fn gradientAt(t0: f32) -> vec4<f32> { if t0 != t0 { return vec4<f32>(0.0); } let tt = tileT(t0, i32(paint.shader.y + 0.5)); if tt.y == 0.0 { return vec4<f32>(0.0); } return rampAt(tt.x); } // The two-point conical gradient from the focal circle to the end circle: the color at a point // is that of the largest t whose circle, which moves and grows from one to the other, goes // through the point. fn conicalAt(q: vec2<f32>) -> vec4<f32> { let c0 = paint.p0.xy; let r0 = paint.p0.z; let cd = paint.p1.xy - c0; let dr = paint.p1.z - r0; let a = dot(cd, cd) - dr * dr; let p = q - c0; let b = dot(p, cd) + r0 * dr; let c = dot(p, p) - r0 * r0; var t: f32; if abs(a) < 1e-12 { if b == 0.0 { return vec4<f32>(0.0); } t = c / (2.0 * b); if r0 + t * dr < 0.0 { return vec4<f32>(0.0); } } else { let disc = b * b - a * c; if disc < 0.0 { return vec4<f32>(0.0); } let sq = sqrt(disc); var t1 = (b + sq) / a; var t2 = (b - sq) / a; if t1 < t2 { let tmp = t1; t1 = t2; t2 = tmp; } if r0 + t1 * dr >= 0.0 { t = t1; } else if r0 + t2 * dr >= 0.0 { t = t2; } else { return vec4<f32>(0.0); } } return gradientAt(t); } // ---- image shaders // A texel of the shader's image at a level, with the tile modes applied to the pixel's index; // transparent where decal draws nothing. fn shaderTexel(p: vec2<i32>, size: vec2<i32>, level: i32) -> vec4<f32> { var x = p.x; var y = p.y; let tileX = i32(paint.shader.y + 0.5); let tileY = i32(paint.shader.z + 0.5); if tileX == 1 { x = ((x % size.x) + size.x) % size.x; } else if tileX == 2 { let m = ((x % (2 * size.x)) + 2 * size.x) % (2 * size.x); if m >= size.x { x = 2 * size.x - 1 - m; } else { x = m; } } else if tileX == 3 { if x < 0 || x >= size.x { return vec4<f32>(0.0); } } else { x = clamp(x, 0, size.x - 1); } if tileY == 1 { y = ((y % size.y) + size.y) % size.y; } else if tileY == 2 { let m = ((y % (2 * size.y)) + 2 * size.y) % (2 * size.y); if m >= size.y { y = 2 * size.y - 1 - m; } else { y = m; } } else if tileY == 3 { if y < 0 || y >= size.y { return vec4<f32>(0.0); } } else { y = clamp(y, 0, size.y - 1); } return textureLoad(paintImage, vec2<i32>(x, y), level); } fn mitchellWeight(x0: f32) -> f32 { let b = 1.0 / 3.0; let c = 1.0 / 3.0; let x = abs(x0); if x < 1.0 { return ((12.0 - 9.0 * b - 6.0 * c) * x * x * x + (-18.0 + 12.0 * b + 6.0 * c) * x * x + (6.0 - 2.0 * b)) / 6.0; } if x < 2.0 { return ((-b - 6.0 * c) * x * x * x + (6.0 * b + 30.0 * c) * x * x + (-12.0 * b - 48.0 * c) * x + (8.0 * b + 24.0 * c)) / 6.0; } return 0.0; } // The shader's image at the point q of its pixels, with the filter quality. fn imageShaderAt(q: vec2<f32>) -> vec4<f32> { let base = vec2<i32>(textureDimensions(paintImage, 0)); let quality = i32(paint.imageInfo.x + 0.5); let level = i32(paint.imageInfo.y + 0.5); let size = vec2<i32>(textureDimensions(paintImage, level)); let uv = q * vec2<f32>(size) / vec2<f32>(base); if quality == 0 { return shaderTexel(vec2<i32>(floor(uv)), size, level); } let f = uv - vec2<f32>(0.5); let f0 = floor(f); let t = f - f0; let i0 = vec2<i32>(f0); if quality == 3 { var sum = vec4<f32>(0.0); for (var j = -1; j <= 2; j++) { let wy = mitchellWeight(f32(j) - t.y); for (var i = -1; i <= 2; i++) { sum += wy * mitchellWeight(f32(i) - t.x) * shaderTexel(i0 + vec2<i32>(i, j), size, level); } } let a = clamp(sum.a, 0.0, 1.0); return vec4<f32>(clamp(sum.rgb, vec3<f32>(0.0), vec3<f32>(a)), a); } let c00 = shaderTexel(i0, size, level); let c10 = shaderTexel(i0 + vec2<i32>(1, 0), size, level); let c01 = shaderTexel(i0 + vec2<i32>(0, 1), size, level); let c11 = shaderTexel(i0 + vec2<i32>(1, 1), size, level); return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); } // The premultiplied color of the shader at the pixel at p (or, for vertices, at the texture // coordinates p). fn shaderColor(p: vec2<f32>) -> vec4<f32> { let q = vec2<f32>( paint.xf0.x * p.x + paint.xf0.z * p.y + paint.xf1.x, paint.xf0.y * p.x + paint.xf0.w * p.y + paint.xf1.y); let kind = i32(paint.shader.x + 0.5); if kind == SHADER_LINEAR { return gradientAt(dot(q - paint.p0.xy, paint.p0.zw) * paint.p1.x); } if kind == SHADER_RADIAL { return gradientAt(length(q - paint.p0.xy) / paint.p0.z); } if kind == SHADER_CONICAL { return conicalAt(q); } if kind == SHADER_SWEEP { let d = q - paint.p0.xy; var a = atan2(d.y, d.x) - paint.p0.z; a = a - 2.0 * PI * floor(a / (2.0 * PI)); return gradientAt(a / paint.p0.w); } if kind == SHADER_IMAGE { return imageShaderAt(q); } return paint.constColor; } // ---- color filters fn unpremul(c: vec4<f32>) -> vec4<f32> { if c.a <= 0.0 { return vec4<f32>(0.0); } return vec4<f32>(clamp(c.rgb / c.a, vec3<f32>(0.0), vec3<f32>(1.0)), c.a); } fn premul(c: vec4<f32>) -> vec4<f32> { return vec4<f32>(c.rgb * c.a, c.a); } fn linearToSrgb(v: vec3<f32>) -> vec3<f32> { return select(1.055 * pow(v, vec3<f32>(1.0 / 2.4)) - vec3<f32>(0.055), 12.92 * v, v <= vec3<f32>(0.0031308)); } fn srgbToLinear(v: vec3<f32>) -> vec3<f32> { return select(pow((v + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4)), v / 12.92, v <= vec3<f32>(0.04045)); } // The paint's color filter, then its inverted colors. fn applyFilters(px0: vec4<f32>) -> vec4<f32> { var px = px0; let kind = i32(paint.flags.y + 0.5); if kind == 1 { px = blendPair(i32(paint.flags.z + 0.5), paint.filterColor, px); } else if kind == 2 { let c = unpremul(px) * 255.0; let o = paint.filterMatrix[0] * c.r + paint.filterMatrix[1] * c.g + paint.filterMatrix[2] * c.b + paint.filterMatrix[3] * c.a + paint.filterMatrix[4]; px = premul(clamp(o / 255.0, vec4<f32>(0.0), vec4<f32>(1.0))); } else if kind == 3 { let c = unpremul(px); px = premul(vec4<f32>(linearToSrgb(c.rgb), c.a)); } else if kind == 4 { let c = unpremul(px); px = premul(vec4<f32>(srgbToLinear(c.rgb), c.a)); } if paint.flags.w != 0.0 { let c = unpremul(px); px = premul(vec4<f32>(vec3<f32>(1.0) - c.rgb, c.a)); } return px; } // The source color of a paint at the pixel dev: base is the paint's color, premultiplied, or for // a shader its alpha in all four components; p is the point the shader is evaluated at. fn paintSource(base: vec4<f32>, p: vec2<f32>) -> vec4<f32> { var c = base; if i32(paint.shader.x + 0.5) != SHADER_NONE { c = shaderColor(p) * base; } return applyFilters(c); } // ---- output var<private> bayer: array<f32, 64> = array<f32, 64>( 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0); // The ordered dither of gradients: up to half a level of 8 bits either way. fn ditherAt(dev: vec2<f32>) -> f32 { let p = vec2<i32>(floor(dev)) & vec2<i32>(7); return ((bayer[p.y * 8 + p.x] + 0.5) / 64.0 - 0.5) / 255.0; } // The pixel of the copy of what is being drawn over at the pixel dev. fn destinationAt(dev: vec2<f32>) -> vec4<f32> { return textureLoad(dst, vec2<i32>(floor(dev)) - vec2<i32>(paint.blend.yz), 0); } // The color to write for the source src that covers the pixel by cov: with a fixed-function // blend, the source scaled by the coverage; with any other mode, the destination mixed toward // the blended color by the coverage. fn finish(src: vec4<f32>, cov: f32, dev: vec2<f32>) -> vec4<f32> { var o: vec4<f32>; if paint.blend.x < 0.0 { o = src * cov; } else { let d = destinationAt(dev); o = d + (blendPair(i32(paint.blend.x + 0.5), src, d) - d) * cov; } if paint.flags.x != 0.0 && src.a > 0.0 { o = o + vec4<f32>(ditherAt(dev)); } return o; } // The coverage of a rounded rectangle blurred by a Gaussian, in closed form (SPEC §9.1). Ported // from gles/shaders/shadow.glsl. Shaders include this file with an include line. // // Across a row of the rectangle, the blur of an interval of columns is a difference of two // normal distribution functions. Down the rows the Gaussian is integrated: exactly where the // rows do not change (the straight part of the sides), and by a sum of samples over the rows of // the rounded corners. // The error function (Abramowitz and Stegun 7.1.26, error below 1.5e-7). fn erfApprox(x0: f32) -> f32 { let s = select(1.0, -1.0, x0 < 0.0); let x = abs(x0); let t = 1.0 / (1.0 + 0.3275911 * x); let y = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * exp(-x * x); return s * y; } // The normal distribution function. fn normalCdf(x: f32) -> f32 { return 0.5 + 0.5 * erfApprox(x * 0.7071067811865476); } // How far a corner of radii rad pulls the side in at the row y, with y measured from the center // of the rectangle: top is true for the corners at the top. fn cornerInset(rad: vec2<f32>, y: f32, hy: f32, top: bool) -> f32 { if rad.y <= 0.0 || rad.x <= 0.0 { return 0.0; } let cy = select(hy - rad.y, -hy + rad.y, top); let t = select((y - cy) / rad.y, (cy - y) / rad.y, top); if t <= 0.0 { return 0.0; } return rad.x * (1.0 - sqrt(max(1.0 - t * t, 0.0))); } // The weight of the rows of a corner zone, [y0, y1] from the center, as seen from the pixel at p: // the sum over the rows of the Gaussian times the columns' share. fn zoneMass(y0: f32, y1: f32, p: vec2<f32>, h: vec2<f32>, r1: vec4<f32>, r2: vec4<f32>, sigma: f32, top: bool) -> f32 { let a = max(y0, p.y - 4.0 * sigma); let b = min(y1, p.y + 4.0 * sigma); if b <= a { return 0.0; } let dv = (b - a) / 16.0; var sum = 0.0; for (var i = 0; i < 16; i++) { let y = a + (f32(i) + 0.5) * dv; let l = -h.x + cornerInset(select(r2.zw, r1.xy, top), y, h.y, top); let r = h.x - cornerInset(select(r2.xy, r1.zw, top), y, h.y, top); let w = exp(-0.5 * (y - p.y) * (y - p.y) / (sigma * sigma)); sum += w * max(normalCdf((r - p.x) / sigma) - normalCdf((l - p.x) / sigma), 0.0); } return sum * dv / (sigma * 2.5066282746310002); } // The blurred coverage at the pixel whose position from the rectangle's center is p. fn blurredRRect(p: vec2<f32>, h: vec2<f32>, r1: vec4<f32>, r2: vec4<f32>, sigma: f32) -> f32 { let topH = max(r1.y, r1.w); let botH = max(r2.y, r2.w); var mass = zoneMass(-h.y, -h.y + topH, p, h, r1, r2, sigma, true); mass += zoneMass(h.y - botH, h.y, p, h, r1, r2, sigma, false); let m0 = -h.y + topH; let m1 = h.y - botH; if m1 > m0 { let rows = normalCdf((m1 - p.y) / sigma) - normalCdf((m0 - p.y) / sigma); let cols = normalCdf((h.x - p.x) / sigma) - normalCdf((-h.x - p.x) / sigma); mass += rows * cols; } return clamp(mass, 0.0, 1.0); } // The coverage of a blur style, from the blurred coverage b and the shape's own o. fn blurStyle(style: i32, b: f32, o: f32) -> f32 { if style == 1 { return o + b * (1.0 - o); // solid } if style == 2 { return b * (1.0 - o); // outer } if style == 3 { return b * o; // inner } return b; // normal } struct Frame { // The size of the texture being drawn into, in pixels. surface: vec2<f32>, // The pixel of the surface that the texture's top left corner is. origin: vec2<f32>, } // What a draw call sets: the clip mask's rectangle in the surface (x, y, width, height; a width // of 0 means none), the layer's pixels in the surface (x, y, width, height), and how the pixels // are read: the mask style (-1: the layer's pixels are composited; else the layer's alpha is the // coverage of a blurred shape, a blur style, that the paint's color fills) and drawnOnly (1: // pixels with no alpha are left as they are). struct Draw { clipMask: vec4<f32>, layerRect: vec4<f32>, read: vec4<f32>, } @group(0) @binding(0) var<uniform> frame: Frame; @group(0) @binding(1) var<uniform> draw: Draw; @group(1) @binding(0) var clipMask: texture_2d<f32>; // The layer's pixels, premultiplied. @group(2) @binding(0) var layer: texture_2d<f32>; // The layer before it was blurred, for a mask style other than normal. @group(2) @binding(1) var layerOwn: texture_2d<f32>; struct Instance { @location(0) quad: vec4<f32>, // left, top, right, bottom in pixels @location(1) color: vec4<f32>, // the layer's alpha in all four components @location(2) clip: vec4<f32>, // left, top, right, bottom in pixels } struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) dev: vec2<f32>, @location(1) @interpolate(flat) color: vec4<f32>, @location(2) @interpolate(flat) clip: vec4<f32>, } fn toClip(dev: vec2<f32>) -> vec4<f32> { let p = dev - frame.origin; return vec4<f32>(p.x / frame.surface.x * 2.0 - 1.0, 1.0 - p.y / frame.surface.y * 2.0, 0.0, 1.0); } @vertex fn vs_main(@builtin(vertex_index) index: u32, instance: Instance) -> VertexOutput { var corners = array<vec2<f32>, 6>( vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0), vec2<f32>(0.0, 1.0), ); let dev = mix(instance.quad.xy, instance.quad.zw, corners[index]); var out: VertexOutput; out.position = toClip(dev); out.dev = dev; out.color = instance.color; out.clip = instance.clip; return out; } // The part of the pixel centered at c that the interval [lo, hi] covers. fn span(c: f32, lo: f32, hi: f32) -> f32 { return clamp(min(c + 0.5, hi) - max(c - 0.5, lo), 0.0, 1.0); } fn clipMaskCoverage(dev: vec2<f32>) -> f32 { if draw.clipMask.z <= 0.0 { return 1.0; } let p = vec2<i32>(floor(dev)) - vec2<i32>(draw.clipMask.xy); if p.x < 0 || p.y < 0 || p.x >= i32(draw.clipMask.z) || p.y >= i32(draw.clipMask.w) { return 0.0; } return textureLoad(clipMask, p, 0).r; } @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> { let dev = floor(in.dev) + vec2<f32>(0.5); let coverage = span(dev.x, in.clip.x, in.clip.z) * span(dev.y, in.clip.y, in.clip.w) * clipMaskCoverage(dev); if coverage <= 0.0 { discard; } let p = vec2<i32>(floor(dev - draw.layerRect.xy)); let texel = textureLoad(layer, p, 0); if draw.read.y != 0.0 && texel.a <= 0.0 { discard; } let style = i32(draw.read.x); if style >= 0 { var own = 0.0; if style != 0 { own = textureLoad(layerOwn, p, 0).a; } let cov = blurStyle(style, texel.a, own) * coverage; if cov < 1.0 / 1024.0 { discard; } return finish(paintSource(in.color, dev), cov, dev); } let color = applyFilters(texel * in.color); return finish(color, coverage, dev); } `, SPIRV: spirvLayer, Entries: []EntryPoint{ {Name: "vs_main", Stage: ShaderStageVertex, Bindings: []ShaderBinding{ {Name: "frame", Group: 0, Binding: 0, Kind: BindingUniformBuffer}, }}, {Name: "fs_main", Stage: ShaderStageFragment, Bindings: []ShaderBinding{ {Name: "draw", Group: 0, Binding: 1, Kind: BindingUniformBuffer}, {Name: "paint", Group: 0, Binding: 2, Kind: BindingUniformBuffer}, {Name: "clipMask", Group: 1, Binding: 0, Kind: BindingSampledTexture}, {Name: "layer", Group: 2, Binding: 0, Kind: BindingSampledTexture}, {Name: "layerOwn", Group: 2, Binding: 1, Kind: BindingSampledTexture}, {Name: "paintImage", Group: 3, Binding: 0, Kind: BindingSampledTexture}, {Name: "dst", Group: 3, Binding: 1, Kind: BindingSampledTexture}, }}, }, }
ShaderLayer is shaders/layer.wgsl.
Flutter: no counterpart
var ShaderMask = &Shader{ Name: "mask", WGSL: `// Coverage masks (SPEC §9.1 "General paths"): one instance is one tile of the coverage atlas, // drawn over the pixels it covers. Ported from the GLES mask shaders (mask.vert.glsl, // mask.frag.glsl). Draw 6 vertices per instance. // The source color of a paint: a solid color, a gradient or an image shader, then the paint's // color filter and inverted colors, and the blend with what is already drawn. Ported from // gles/shaders/paint.glsl. Fragment shaders include this file, after blend.wgsl.inc. // // The 29 blend modes of Flutter's BlendMode, on premultiplied colors, as the software renderer // computes them (internal/gpu/soft/blend.go). mode is the index of the mode in BlendMode's // order: 0 clear, 1 src, 2 dst, 3 srcOver, 4 dstOver, 5 srcIn, 6 dstIn, 7 srcOut, 8 dstOut, // 9 srcATop, 10 dstATop, 11 xor, 12 plus, 13 modulate, 14 screen, 15 overlay, 16 darken, // 17 lighten, 18 colorDodge, 19 colorBurn, 20 hardLight, 21 softLight, 22 difference, // 23 exclusion, 24 multiply, 25 hue, 26 saturation, 27 color, 28 luminosity. Ported from // gles/shaders/blend.glsl. Shaders include this file with an include line. fn hardLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { if 2.0 * s <= sa { return s * (1.0 - da) + d * (1.0 - sa) + 2.0 * s * d; } return s * (1.0 - da) + d * (1.0 - sa) + sa * da - 2.0 * (da - d) * (sa - s); } fn softLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { var m = 0.0; if da > 0.0 { m = d / da; } let s2 = 2.0 * s; let m4 = 4.0 * m; let darkSrc = d * (sa + (s2 - sa) * (1.0 - m)); let darkDst = (m4 * m4 + m4) * (m - 1.0) + 7.0 * m; let liteDst = sqrt(m) - m; var tail = liteDst; if 4.0 * d <= da { tail = darkDst; } let liteSrc = d * sa + da * (s2 - sa) * tail; var body = liteSrc; if s2 <= sa { body = darkSrc; } return s * (1.0 - da) + d * (1.0 - sa) + body; } fn blendChannel(mode: i32, s: f32, d: f32, sa: f32, da: f32) -> f32 { switch mode { case 15: { return hardLightChannel(d, s, da, sa); // overlay } case 16: { return s + d - max(s * da, d * sa); // darken } case 17: { return s + d - min(s * da, d * sa); // lighten } case 18: { // colorDodge if d == 0.0 { return s * (1.0 - da); } if s == sa { return s + d * (1.0 - sa); } return sa * min(da, d * sa / (sa - s)) + s * (1.0 - da) + d * (1.0 - sa); } case 19: { // colorBurn if d == da { return d + s * (1.0 - da); } if s == 0.0 { return d * (1.0 - sa); } return sa * (da - min(da, (da - d) * sa / s)) + s * (1.0 - da) + d * (1.0 - sa); } case 20: { return hardLightChannel(s, d, sa, da); // hardLight } case 21: { return softLightChannel(s, d, sa, da); // softLight } case 22: { return s + d - 2.0 * min(s * da, d * sa); // difference } case 23: { return s + d - 2.0 * s * d; // exclusion } case 24: { return s * (1.0 - da) + d * (1.0 - sa) + s * d; // multiply } default: { return s + d * (1.0 - sa); } } } fn lum(c: vec3<f32>) -> f32 { return 0.30 * c.r + 0.59 * c.g + 0.11 * c.b; } fn sat(c: vec3<f32>) -> f32 { return max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b)); } fn setSat(c: vec3<f32>, s: f32) -> vec3<f32> { let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let range = mx - mn; if range == 0.0 { return vec3<f32>(0.0); } return (c - vec3<f32>(mn)) * s / range; } fn setLum(c: vec3<f32>, l: f32) -> vec3<f32> { return c + vec3<f32>(l - lum(c)); } fn clipColor(c0: vec3<f32>, a: f32) -> vec3<f32> { var c = c0; let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let l = lum(c); if mn < 0.0 { c = vec3<f32>(l) + (c - vec3<f32>(l)) * l / (l - mn); } if mx > a { c = vec3<f32>(l) + (c - vec3<f32>(l)) * (a - l) / (mx - l); } return max(c, vec3<f32>(0.0)); } fn blendNonSeparable(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; var c: vec3<f32>; if mode == 25 { // hue c = s.rgb * sa; c = setSat(c, sat(d.rgb) * sa); c = setLum(c, lum(d.rgb) * sa); } else if mode == 26 { // saturation c = d.rgb * sa; c = setSat(c, sat(s.rgb) * da); c = setLum(c, lum(d.rgb) * sa); } else if mode == 27 { // color c = s.rgb * da; c = setLum(c, lum(d.rgb) * sa); } else { // luminosity c = d.rgb * sa; c = setLum(c, lum(s.rgb) * da); } c = clipColor(c, sa * da); return vec4<f32>(s.rgb * (1.0 - da) + d.rgb * (1.0 - sa) + c, sa + da - sa * da); } // blendPair blends the source s over the destination d with the mode. fn blendPair(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; switch mode { case 0: { return vec4<f32>(0.0); } case 1: { return s; } case 2: { return d; } case 3: { return s + d * (1.0 - sa); } case 4: { return d + s * (1.0 - da); } case 5: { return s * da; } case 6: { return d * sa; } case 7: { return s * (1.0 - da); } case 8: { return d * (1.0 - sa); } case 9: { return s * da + d * (1.0 - sa); } case 10: { return d * sa + s * (1.0 - da); } case 11: { return s * (1.0 - da) + d * (1.0 - sa); } case 12: { return min(s + d, vec4<f32>(1.0)); } case 13: { return s * d; } case 14: { return s + d - s * d; } case 25, 26, 27, 28: { return blendNonSeparable(mode, s, d); } default: { // The separable modes defined per channel, whose alpha is that of source-over. return vec4<f32>( blendChannel(mode, s.r, d.r, sa, da), blendChannel(mode, s.g, d.g, sa, da), blendChannel(mode, s.b, d.b, sa, da), sa + da - sa * da); } } } const SHADER_NONE: i32 = 0; const SHADER_LINEAR: i32 = 1; const SHADER_RADIAL: i32 = 2; const SHADER_CONICAL: i32 = 3; const SHADER_SWEEP: i32 = 4; const SHADER_IMAGE: i32 = 5; const SHADER_CONST: i32 = 6; const MAX_STOPS: i32 = 32; const PI: f32 = 3.14159265358979; // What a draw call's paint sets, the layout of gpu.PaintSpec as float4s (see paintUniform). struct Paint { // The shader kind, the tile modes in x and y (0 clamp, 1 repeated, 2 mirror, 3 decal) and // the number of color stops. shader: vec4<f32>, // The matrix from pixels to the shader's space: a, b, c, d, then e, f. xf0: vec4<f32>, xf1: vec4<f32>, // linear: from x, y, dx, dy; radial: center x, y, radius; conical: focal x, y, focal radius; // sweep: center x, y, start, span. p0: vec4<f32>, // linear: 1 / (dx*dx + dy*dy); conical: end center x, y, end radius. p1: vec4<f32>, // The image shader's quality (0 none, 1 low, 2 medium, 3 high) and level. imageInfo: vec4<f32>, // A degenerate gradient: premultiplied color. constColor: vec4<f32>, // Dither (0 or 1), the color filter (0 none, 1 mode, 2 matrix, 3 linear to sRGB, 4 sRGB to // linear), the blend index of a mode filter, and inverted colors (0 or 1). flags: vec4<f32>, // The blend index of a blend that reads the destination (-1: the blend unit does it), and the // pixel of the surface that the copy of the destination starts at. blend: vec4<f32>, // A mode filter's premultiplied color. filterColor: vec4<f32>, // A matrix filter: the columns of the 4x5 matrix in 0 to 255 units. filterMatrix: array<vec4<f32>, 5>, // The gradient's colors (not premultiplied) and positions, four to a float4. rampColor: array<vec4<f32>, 32>, rampPos: array<vec4<f32>, 8>, } @group(0) @binding(2) var<uniform> paint: Paint; // The image of an image shader, and a copy of the pixels being drawn over. @group(3) @binding(0) var paintImage: texture_2d<f32>; @group(3) @binding(1) var dst: texture_2d<f32>; // ---- gradients // Applies the tile mode to a position along a gradient; the second component is 0 where the // shader draws nothing. fn tileT(t: f32, mode: i32) -> vec2<f32> { if mode == 1 { return vec2<f32>(t - floor(t), 1.0); } if mode == 2 { let u = t - 2.0 * floor(t / 2.0); if u > 1.0 { return vec2<f32>(2.0 - u, 1.0); } return vec2<f32>(u, 1.0); } if mode == 3 { if t >= 0.0 && t <= 1.0 { return vec2<f32>(t, 1.0); } return vec2<f32>(t, 0.0); } return vec2<f32>(clamp(t, 0.0, 1.0), 1.0); } fn rampPosAt(i: i32) -> f32 { return paint.rampPos[i >> 2u][i & 3]; } // The premultiplied color at t, interpolated without premultiplied alpha. fn rampAt(t: f32) -> vec4<f32> { let n = i32(paint.shader.w + 0.5); var i = 0; while i < n && rampPosAt(i) < t { i++; } var c: vec4<f32>; if i == 0 { c = paint.rampColor[0]; } else if i >= n { c = paint.rampColor[n - 1]; } else { let p0 = rampPosAt(i - 1); let p1 = rampPosAt(i); if p1 <= p0 { c = paint.rampColor[i]; } else { c = mix(paint.rampColor[i - 1], paint.rampColor[i], (t - p0) / (p1 - p0)); } } c = clamp(c, vec4<f32>(0.0), vec4<f32>(1.0)); return vec4<f32>(c.rgb * c.a, c.a); } fn gradientAt(t0: f32) -> vec4<f32> { if t0 != t0 { return vec4<f32>(0.0); } let tt = tileT(t0, i32(paint.shader.y + 0.5)); if tt.y == 0.0 { return vec4<f32>(0.0); } return rampAt(tt.x); } // The two-point conical gradient from the focal circle to the end circle: the color at a point // is that of the largest t whose circle, which moves and grows from one to the other, goes // through the point. fn conicalAt(q: vec2<f32>) -> vec4<f32> { let c0 = paint.p0.xy; let r0 = paint.p0.z; let cd = paint.p1.xy - c0; let dr = paint.p1.z - r0; let a = dot(cd, cd) - dr * dr; let p = q - c0; let b = dot(p, cd) + r0 * dr; let c = dot(p, p) - r0 * r0; var t: f32; if abs(a) < 1e-12 { if b == 0.0 { return vec4<f32>(0.0); } t = c / (2.0 * b); if r0 + t * dr < 0.0 { return vec4<f32>(0.0); } } else { let disc = b * b - a * c; if disc < 0.0 { return vec4<f32>(0.0); } let sq = sqrt(disc); var t1 = (b + sq) / a; var t2 = (b - sq) / a; if t1 < t2 { let tmp = t1; t1 = t2; t2 = tmp; } if r0 + t1 * dr >= 0.0 { t = t1; } else if r0 + t2 * dr >= 0.0 { t = t2; } else { return vec4<f32>(0.0); } } return gradientAt(t); } // ---- image shaders // A texel of the shader's image at a level, with the tile modes applied to the pixel's index; // transparent where decal draws nothing. fn shaderTexel(p: vec2<i32>, size: vec2<i32>, level: i32) -> vec4<f32> { var x = p.x; var y = p.y; let tileX = i32(paint.shader.y + 0.5); let tileY = i32(paint.shader.z + 0.5); if tileX == 1 { x = ((x % size.x) + size.x) % size.x; } else if tileX == 2 { let m = ((x % (2 * size.x)) + 2 * size.x) % (2 * size.x); if m >= size.x { x = 2 * size.x - 1 - m; } else { x = m; } } else if tileX == 3 { if x < 0 || x >= size.x { return vec4<f32>(0.0); } } else { x = clamp(x, 0, size.x - 1); } if tileY == 1 { y = ((y % size.y) + size.y) % size.y; } else if tileY == 2 { let m = ((y % (2 * size.y)) + 2 * size.y) % (2 * size.y); if m >= size.y { y = 2 * size.y - 1 - m; } else { y = m; } } else if tileY == 3 { if y < 0 || y >= size.y { return vec4<f32>(0.0); } } else { y = clamp(y, 0, size.y - 1); } return textureLoad(paintImage, vec2<i32>(x, y), level); } fn mitchellWeight(x0: f32) -> f32 { let b = 1.0 / 3.0; let c = 1.0 / 3.0; let x = abs(x0); if x < 1.0 { return ((12.0 - 9.0 * b - 6.0 * c) * x * x * x + (-18.0 + 12.0 * b + 6.0 * c) * x * x + (6.0 - 2.0 * b)) / 6.0; } if x < 2.0 { return ((-b - 6.0 * c) * x * x * x + (6.0 * b + 30.0 * c) * x * x + (-12.0 * b - 48.0 * c) * x + (8.0 * b + 24.0 * c)) / 6.0; } return 0.0; } // The shader's image at the point q of its pixels, with the filter quality. fn imageShaderAt(q: vec2<f32>) -> vec4<f32> { let base = vec2<i32>(textureDimensions(paintImage, 0)); let quality = i32(paint.imageInfo.x + 0.5); let level = i32(paint.imageInfo.y + 0.5); let size = vec2<i32>(textureDimensions(paintImage, level)); let uv = q * vec2<f32>(size) / vec2<f32>(base); if quality == 0 { return shaderTexel(vec2<i32>(floor(uv)), size, level); } let f = uv - vec2<f32>(0.5); let f0 = floor(f); let t = f - f0; let i0 = vec2<i32>(f0); if quality == 3 { var sum = vec4<f32>(0.0); for (var j = -1; j <= 2; j++) { let wy = mitchellWeight(f32(j) - t.y); for (var i = -1; i <= 2; i++) { sum += wy * mitchellWeight(f32(i) - t.x) * shaderTexel(i0 + vec2<i32>(i, j), size, level); } } let a = clamp(sum.a, 0.0, 1.0); return vec4<f32>(clamp(sum.rgb, vec3<f32>(0.0), vec3<f32>(a)), a); } let c00 = shaderTexel(i0, size, level); let c10 = shaderTexel(i0 + vec2<i32>(1, 0), size, level); let c01 = shaderTexel(i0 + vec2<i32>(0, 1), size, level); let c11 = shaderTexel(i0 + vec2<i32>(1, 1), size, level); return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); } // The premultiplied color of the shader at the pixel at p (or, for vertices, at the texture // coordinates p). fn shaderColor(p: vec2<f32>) -> vec4<f32> { let q = vec2<f32>( paint.xf0.x * p.x + paint.xf0.z * p.y + paint.xf1.x, paint.xf0.y * p.x + paint.xf0.w * p.y + paint.xf1.y); let kind = i32(paint.shader.x + 0.5); if kind == SHADER_LINEAR { return gradientAt(dot(q - paint.p0.xy, paint.p0.zw) * paint.p1.x); } if kind == SHADER_RADIAL { return gradientAt(length(q - paint.p0.xy) / paint.p0.z); } if kind == SHADER_CONICAL { return conicalAt(q); } if kind == SHADER_SWEEP { let d = q - paint.p0.xy; var a = atan2(d.y, d.x) - paint.p0.z; a = a - 2.0 * PI * floor(a / (2.0 * PI)); return gradientAt(a / paint.p0.w); } if kind == SHADER_IMAGE { return imageShaderAt(q); } return paint.constColor; } // ---- color filters fn unpremul(c: vec4<f32>) -> vec4<f32> { if c.a <= 0.0 { return vec4<f32>(0.0); } return vec4<f32>(clamp(c.rgb / c.a, vec3<f32>(0.0), vec3<f32>(1.0)), c.a); } fn premul(c: vec4<f32>) -> vec4<f32> { return vec4<f32>(c.rgb * c.a, c.a); } fn linearToSrgb(v: vec3<f32>) -> vec3<f32> { return select(1.055 * pow(v, vec3<f32>(1.0 / 2.4)) - vec3<f32>(0.055), 12.92 * v, v <= vec3<f32>(0.0031308)); } fn srgbToLinear(v: vec3<f32>) -> vec3<f32> { return select(pow((v + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4)), v / 12.92, v <= vec3<f32>(0.04045)); } // The paint's color filter, then its inverted colors. fn applyFilters(px0: vec4<f32>) -> vec4<f32> { var px = px0; let kind = i32(paint.flags.y + 0.5); if kind == 1 { px = blendPair(i32(paint.flags.z + 0.5), paint.filterColor, px); } else if kind == 2 { let c = unpremul(px) * 255.0; let o = paint.filterMatrix[0] * c.r + paint.filterMatrix[1] * c.g + paint.filterMatrix[2] * c.b + paint.filterMatrix[3] * c.a + paint.filterMatrix[4]; px = premul(clamp(o / 255.0, vec4<f32>(0.0), vec4<f32>(1.0))); } else if kind == 3 { let c = unpremul(px); px = premul(vec4<f32>(linearToSrgb(c.rgb), c.a)); } else if kind == 4 { let c = unpremul(px); px = premul(vec4<f32>(srgbToLinear(c.rgb), c.a)); } if paint.flags.w != 0.0 { let c = unpremul(px); px = premul(vec4<f32>(vec3<f32>(1.0) - c.rgb, c.a)); } return px; } // The source color of a paint at the pixel dev: base is the paint's color, premultiplied, or for // a shader its alpha in all four components; p is the point the shader is evaluated at. fn paintSource(base: vec4<f32>, p: vec2<f32>) -> vec4<f32> { var c = base; if i32(paint.shader.x + 0.5) != SHADER_NONE { c = shaderColor(p) * base; } return applyFilters(c); } // ---- output var<private> bayer: array<f32, 64> = array<f32, 64>( 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0); // The ordered dither of gradients: up to half a level of 8 bits either way. fn ditherAt(dev: vec2<f32>) -> f32 { let p = vec2<i32>(floor(dev)) & vec2<i32>(7); return ((bayer[p.y * 8 + p.x] + 0.5) / 64.0 - 0.5) / 255.0; } // The pixel of the copy of what is being drawn over at the pixel dev. fn destinationAt(dev: vec2<f32>) -> vec4<f32> { return textureLoad(dst, vec2<i32>(floor(dev)) - vec2<i32>(paint.blend.yz), 0); } // The color to write for the source src that covers the pixel by cov: with a fixed-function // blend, the source scaled by the coverage; with any other mode, the destination mixed toward // the blended color by the coverage. fn finish(src: vec4<f32>, cov: f32, dev: vec2<f32>) -> vec4<f32> { var o: vec4<f32>; if paint.blend.x < 0.0 { o = src * cov; } else { let d = destinationAt(dev); o = d + (blendPair(i32(paint.blend.x + 0.5), src, d) - d) * cov; } if paint.flags.x != 0.0 && src.a > 0.0 { o = o + vec4<f32>(ditherAt(dev)); } return o; } struct Frame { // The size of the texture being drawn into, in pixels. surface: vec2<f32>, // The pixel of the surface that the texture's top left corner is. origin: vec2<f32>, } // The clip mask's rectangle in the surface (x, y, width, height; a width of 0 means none). struct Draw { clipMask: vec4<f32>, } @group(0) @binding(0) var<uniform> frame: Frame; @group(0) @binding(1) var<uniform> draw: Draw; @group(1) @binding(0) var clipMask: texture_2d<f32>; // An atlas page: 8-bit coverage. @group(2) @binding(0) var atlas: texture_2d<f32>; struct Instance { @location(0) quad: vec4<f32>, // left, top, right, bottom in pixels @location(1) tile: vec4<f32>, // the tile's top left texel in the atlas page @location(2) color: vec4<f32>, // premultiplied @location(3) clip: vec4<f32>, // left, top, right, bottom in pixels } struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) dev: vec2<f32>, @location(1) @interpolate(flat) quad: vec4<f32>, @location(2) @interpolate(flat) tile: vec4<f32>, @location(3) @interpolate(flat) color: vec4<f32>, @location(4) @interpolate(flat) clip: vec4<f32>, } fn toClip(dev: vec2<f32>) -> vec4<f32> { let p = dev - frame.origin; return vec4<f32>(p.x / frame.surface.x * 2.0 - 1.0, 1.0 - p.y / frame.surface.y * 2.0, 0.0, 1.0); } @vertex fn vs_main(@builtin(vertex_index) index: u32, instance: Instance) -> VertexOutput { var corners = array<vec2<f32>, 6>( vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0), vec2<f32>(0.0, 1.0), ); let dev = mix(instance.quad.xy, instance.quad.zw, corners[index]); var out: VertexOutput; out.position = toClip(dev); out.dev = dev; out.quad = instance.quad; out.tile = instance.tile; out.color = instance.color; out.clip = instance.clip; return out; } // The part of the pixel centered at c that the interval [lo, hi] covers. fn span(c: f32, lo: f32, hi: f32) -> f32 { return clamp(min(c + 0.5, hi) - max(c - 0.5, lo), 0.0, 1.0); } fn clipMaskCoverage(dev: vec2<f32>) -> f32 { if draw.clipMask.z <= 0.0 { return 1.0; } let p = vec2<i32>(floor(dev)) - vec2<i32>(draw.clipMask.xy); if p.x < 0 || p.y < 0 || p.x >= i32(draw.clipMask.z) || p.y >= i32(draw.clipMask.w) { return 0.0; } return textureLoad(clipMask, p, 0).r; } @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> { let dev = floor(in.dev) + vec2<f32>(0.5); // The quad covers whole pixels, one texel each: the texel of this pixel is the tile's // corner plus its distance from the quad's corner. let texel = vec2<i32>(in.tile.xy) + vec2<i32>(floor(dev)) - vec2<i32>(in.quad.xy); var coverage = textureLoad(atlas, texel, 0).r; coverage = coverage * span(dev.x, in.clip.x, in.clip.z) * span(dev.y, in.clip.y, in.clip.w) * clipMaskCoverage(dev); if coverage <= 0.0 { discard; } return finish(paintSource(in.color, dev), coverage, dev); } `, SPIRV: spirvMask, Entries: []EntryPoint{ {Name: "vs_main", Stage: ShaderStageVertex, Bindings: []ShaderBinding{ {Name: "frame", Group: 0, Binding: 0, Kind: BindingUniformBuffer}, }}, {Name: "fs_main", Stage: ShaderStageFragment, Bindings: []ShaderBinding{ {Name: "draw", Group: 0, Binding: 1, Kind: BindingUniformBuffer}, {Name: "paint", Group: 0, Binding: 2, Kind: BindingUniformBuffer}, {Name: "clipMask", Group: 1, Binding: 0, Kind: BindingSampledTexture}, {Name: "atlas", Group: 2, Binding: 0, Kind: BindingSampledTexture}, {Name: "paintImage", Group: 3, Binding: 0, Kind: BindingSampledTexture}, {Name: "dst", Group: 3, Binding: 1, Kind: BindingSampledTexture}, }}, }, }
ShaderMask is shaders/mask.wgsl.
Flutter: no counterpart
var ShaderShape = &Shader{ Name: "shape", WGSL: `// Analytic shapes (SPEC §9.1, §9.3): one instance is one shape. The vertex shader only // places a quad that covers the shape's bounds in pixels; the fragment shader works out // the coverage of each pixel from a signed distance field. Ported from the GLES shape // shaders (shape.vert.glsl, shape.frag.glsl) with sdf.glsl and common.glsl's toClip. // // Draw 6 vertices per instance: two triangles made from the vertex index. The instance // is twelve vec4 attributes (gpu.ShapeInstance), the same for the corners, so each is // passed on as a flat varying. // // The color is the paint's: a solid color, a gradient or an image shader, with its color filter // (paint.wgsl.inc); the blend unit scales it by the coverage, or the shader blends it with a // copy of the destination. The clip masks of shape clips multiply the coverage (clipmask.glsl). // The source color of a paint: a solid color, a gradient or an image shader, then the paint's // color filter and inverted colors, and the blend with what is already drawn. Ported from // gles/shaders/paint.glsl. Fragment shaders include this file, after blend.wgsl.inc. // // The 29 blend modes of Flutter's BlendMode, on premultiplied colors, as the software renderer // computes them (internal/gpu/soft/blend.go). mode is the index of the mode in BlendMode's // order: 0 clear, 1 src, 2 dst, 3 srcOver, 4 dstOver, 5 srcIn, 6 dstIn, 7 srcOut, 8 dstOut, // 9 srcATop, 10 dstATop, 11 xor, 12 plus, 13 modulate, 14 screen, 15 overlay, 16 darken, // 17 lighten, 18 colorDodge, 19 colorBurn, 20 hardLight, 21 softLight, 22 difference, // 23 exclusion, 24 multiply, 25 hue, 26 saturation, 27 color, 28 luminosity. Ported from // gles/shaders/blend.glsl. Shaders include this file with an include line. fn hardLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { if 2.0 * s <= sa { return s * (1.0 - da) + d * (1.0 - sa) + 2.0 * s * d; } return s * (1.0 - da) + d * (1.0 - sa) + sa * da - 2.0 * (da - d) * (sa - s); } fn softLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { var m = 0.0; if da > 0.0 { m = d / da; } let s2 = 2.0 * s; let m4 = 4.0 * m; let darkSrc = d * (sa + (s2 - sa) * (1.0 - m)); let darkDst = (m4 * m4 + m4) * (m - 1.0) + 7.0 * m; let liteDst = sqrt(m) - m; var tail = liteDst; if 4.0 * d <= da { tail = darkDst; } let liteSrc = d * sa + da * (s2 - sa) * tail; var body = liteSrc; if s2 <= sa { body = darkSrc; } return s * (1.0 - da) + d * (1.0 - sa) + body; } fn blendChannel(mode: i32, s: f32, d: f32, sa: f32, da: f32) -> f32 { switch mode { case 15: { return hardLightChannel(d, s, da, sa); // overlay } case 16: { return s + d - max(s * da, d * sa); // darken } case 17: { return s + d - min(s * da, d * sa); // lighten } case 18: { // colorDodge if d == 0.0 { return s * (1.0 - da); } if s == sa { return s + d * (1.0 - sa); } return sa * min(da, d * sa / (sa - s)) + s * (1.0 - da) + d * (1.0 - sa); } case 19: { // colorBurn if d == da { return d + s * (1.0 - da); } if s == 0.0 { return d * (1.0 - sa); } return sa * (da - min(da, (da - d) * sa / s)) + s * (1.0 - da) + d * (1.0 - sa); } case 20: { return hardLightChannel(s, d, sa, da); // hardLight } case 21: { return softLightChannel(s, d, sa, da); // softLight } case 22: { return s + d - 2.0 * min(s * da, d * sa); // difference } case 23: { return s + d - 2.0 * s * d; // exclusion } case 24: { return s * (1.0 - da) + d * (1.0 - sa) + s * d; // multiply } default: { return s + d * (1.0 - sa); } } } fn lum(c: vec3<f32>) -> f32 { return 0.30 * c.r + 0.59 * c.g + 0.11 * c.b; } fn sat(c: vec3<f32>) -> f32 { return max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b)); } fn setSat(c: vec3<f32>, s: f32) -> vec3<f32> { let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let range = mx - mn; if range == 0.0 { return vec3<f32>(0.0); } return (c - vec3<f32>(mn)) * s / range; } fn setLum(c: vec3<f32>, l: f32) -> vec3<f32> { return c + vec3<f32>(l - lum(c)); } fn clipColor(c0: vec3<f32>, a: f32) -> vec3<f32> { var c = c0; let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let l = lum(c); if mn < 0.0 { c = vec3<f32>(l) + (c - vec3<f32>(l)) * l / (l - mn); } if mx > a { c = vec3<f32>(l) + (c - vec3<f32>(l)) * (a - l) / (mx - l); } return max(c, vec3<f32>(0.0)); } fn blendNonSeparable(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; var c: vec3<f32>; if mode == 25 { // hue c = s.rgb * sa; c = setSat(c, sat(d.rgb) * sa); c = setLum(c, lum(d.rgb) * sa); } else if mode == 26 { // saturation c = d.rgb * sa; c = setSat(c, sat(s.rgb) * da); c = setLum(c, lum(d.rgb) * sa); } else if mode == 27 { // color c = s.rgb * da; c = setLum(c, lum(d.rgb) * sa); } else { // luminosity c = d.rgb * sa; c = setLum(c, lum(s.rgb) * da); } c = clipColor(c, sa * da); return vec4<f32>(s.rgb * (1.0 - da) + d.rgb * (1.0 - sa) + c, sa + da - sa * da); } // blendPair blends the source s over the destination d with the mode. fn blendPair(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; switch mode { case 0: { return vec4<f32>(0.0); } case 1: { return s; } case 2: { return d; } case 3: { return s + d * (1.0 - sa); } case 4: { return d + s * (1.0 - da); } case 5: { return s * da; } case 6: { return d * sa; } case 7: { return s * (1.0 - da); } case 8: { return d * (1.0 - sa); } case 9: { return s * da + d * (1.0 - sa); } case 10: { return d * sa + s * (1.0 - da); } case 11: { return s * (1.0 - da) + d * (1.0 - sa); } case 12: { return min(s + d, vec4<f32>(1.0)); } case 13: { return s * d; } case 14: { return s + d - s * d; } case 25, 26, 27, 28: { return blendNonSeparable(mode, s, d); } default: { // The separable modes defined per channel, whose alpha is that of source-over. return vec4<f32>( blendChannel(mode, s.r, d.r, sa, da), blendChannel(mode, s.g, d.g, sa, da), blendChannel(mode, s.b, d.b, sa, da), sa + da - sa * da); } } } const SHADER_NONE: i32 = 0; const SHADER_LINEAR: i32 = 1; const SHADER_RADIAL: i32 = 2; const SHADER_CONICAL: i32 = 3; const SHADER_SWEEP: i32 = 4; const SHADER_IMAGE: i32 = 5; const SHADER_CONST: i32 = 6; const MAX_STOPS: i32 = 32; const PI: f32 = 3.14159265358979; // What a draw call's paint sets, the layout of gpu.PaintSpec as float4s (see paintUniform). struct Paint { // The shader kind, the tile modes in x and y (0 clamp, 1 repeated, 2 mirror, 3 decal) and // the number of color stops. shader: vec4<f32>, // The matrix from pixels to the shader's space: a, b, c, d, then e, f. xf0: vec4<f32>, xf1: vec4<f32>, // linear: from x, y, dx, dy; radial: center x, y, radius; conical: focal x, y, focal radius; // sweep: center x, y, start, span. p0: vec4<f32>, // linear: 1 / (dx*dx + dy*dy); conical: end center x, y, end radius. p1: vec4<f32>, // The image shader's quality (0 none, 1 low, 2 medium, 3 high) and level. imageInfo: vec4<f32>, // A degenerate gradient: premultiplied color. constColor: vec4<f32>, // Dither (0 or 1), the color filter (0 none, 1 mode, 2 matrix, 3 linear to sRGB, 4 sRGB to // linear), the blend index of a mode filter, and inverted colors (0 or 1). flags: vec4<f32>, // The blend index of a blend that reads the destination (-1: the blend unit does it), and the // pixel of the surface that the copy of the destination starts at. blend: vec4<f32>, // A mode filter's premultiplied color. filterColor: vec4<f32>, // A matrix filter: the columns of the 4x5 matrix in 0 to 255 units. filterMatrix: array<vec4<f32>, 5>, // The gradient's colors (not premultiplied) and positions, four to a float4. rampColor: array<vec4<f32>, 32>, rampPos: array<vec4<f32>, 8>, } @group(0) @binding(2) var<uniform> paint: Paint; // The image of an image shader, and a copy of the pixels being drawn over. @group(3) @binding(0) var paintImage: texture_2d<f32>; @group(3) @binding(1) var dst: texture_2d<f32>; // ---- gradients // Applies the tile mode to a position along a gradient; the second component is 0 where the // shader draws nothing. fn tileT(t: f32, mode: i32) -> vec2<f32> { if mode == 1 { return vec2<f32>(t - floor(t), 1.0); } if mode == 2 { let u = t - 2.0 * floor(t / 2.0); if u > 1.0 { return vec2<f32>(2.0 - u, 1.0); } return vec2<f32>(u, 1.0); } if mode == 3 { if t >= 0.0 && t <= 1.0 { return vec2<f32>(t, 1.0); } return vec2<f32>(t, 0.0); } return vec2<f32>(clamp(t, 0.0, 1.0), 1.0); } fn rampPosAt(i: i32) -> f32 { return paint.rampPos[i >> 2u][i & 3]; } // The premultiplied color at t, interpolated without premultiplied alpha. fn rampAt(t: f32) -> vec4<f32> { let n = i32(paint.shader.w + 0.5); var i = 0; while i < n && rampPosAt(i) < t { i++; } var c: vec4<f32>; if i == 0 { c = paint.rampColor[0]; } else if i >= n { c = paint.rampColor[n - 1]; } else { let p0 = rampPosAt(i - 1); let p1 = rampPosAt(i); if p1 <= p0 { c = paint.rampColor[i]; } else { c = mix(paint.rampColor[i - 1], paint.rampColor[i], (t - p0) / (p1 - p0)); } } c = clamp(c, vec4<f32>(0.0), vec4<f32>(1.0)); return vec4<f32>(c.rgb * c.a, c.a); } fn gradientAt(t0: f32) -> vec4<f32> { if t0 != t0 { return vec4<f32>(0.0); } let tt = tileT(t0, i32(paint.shader.y + 0.5)); if tt.y == 0.0 { return vec4<f32>(0.0); } return rampAt(tt.x); } // The two-point conical gradient from the focal circle to the end circle: the color at a point // is that of the largest t whose circle, which moves and grows from one to the other, goes // through the point. fn conicalAt(q: vec2<f32>) -> vec4<f32> { let c0 = paint.p0.xy; let r0 = paint.p0.z; let cd = paint.p1.xy - c0; let dr = paint.p1.z - r0; let a = dot(cd, cd) - dr * dr; let p = q - c0; let b = dot(p, cd) + r0 * dr; let c = dot(p, p) - r0 * r0; var t: f32; if abs(a) < 1e-12 { if b == 0.0 { return vec4<f32>(0.0); } t = c / (2.0 * b); if r0 + t * dr < 0.0 { return vec4<f32>(0.0); } } else { let disc = b * b - a * c; if disc < 0.0 { return vec4<f32>(0.0); } let sq = sqrt(disc); var t1 = (b + sq) / a; var t2 = (b - sq) / a; if t1 < t2 { let tmp = t1; t1 = t2; t2 = tmp; } if r0 + t1 * dr >= 0.0 { t = t1; } else if r0 + t2 * dr >= 0.0 { t = t2; } else { return vec4<f32>(0.0); } } return gradientAt(t); } // ---- image shaders // A texel of the shader's image at a level, with the tile modes applied to the pixel's index; // transparent where decal draws nothing. fn shaderTexel(p: vec2<i32>, size: vec2<i32>, level: i32) -> vec4<f32> { var x = p.x; var y = p.y; let tileX = i32(paint.shader.y + 0.5); let tileY = i32(paint.shader.z + 0.5); if tileX == 1 { x = ((x % size.x) + size.x) % size.x; } else if tileX == 2 { let m = ((x % (2 * size.x)) + 2 * size.x) % (2 * size.x); if m >= size.x { x = 2 * size.x - 1 - m; } else { x = m; } } else if tileX == 3 { if x < 0 || x >= size.x { return vec4<f32>(0.0); } } else { x = clamp(x, 0, size.x - 1); } if tileY == 1 { y = ((y % size.y) + size.y) % size.y; } else if tileY == 2 { let m = ((y % (2 * size.y)) + 2 * size.y) % (2 * size.y); if m >= size.y { y = 2 * size.y - 1 - m; } else { y = m; } } else if tileY == 3 { if y < 0 || y >= size.y { return vec4<f32>(0.0); } } else { y = clamp(y, 0, size.y - 1); } return textureLoad(paintImage, vec2<i32>(x, y), level); } fn mitchellWeight(x0: f32) -> f32 { let b = 1.0 / 3.0; let c = 1.0 / 3.0; let x = abs(x0); if x < 1.0 { return ((12.0 - 9.0 * b - 6.0 * c) * x * x * x + (-18.0 + 12.0 * b + 6.0 * c) * x * x + (6.0 - 2.0 * b)) / 6.0; } if x < 2.0 { return ((-b - 6.0 * c) * x * x * x + (6.0 * b + 30.0 * c) * x * x + (-12.0 * b - 48.0 * c) * x + (8.0 * b + 24.0 * c)) / 6.0; } return 0.0; } // The shader's image at the point q of its pixels, with the filter quality. fn imageShaderAt(q: vec2<f32>) -> vec4<f32> { let base = vec2<i32>(textureDimensions(paintImage, 0)); let quality = i32(paint.imageInfo.x + 0.5); let level = i32(paint.imageInfo.y + 0.5); let size = vec2<i32>(textureDimensions(paintImage, level)); let uv = q * vec2<f32>(size) / vec2<f32>(base); if quality == 0 { return shaderTexel(vec2<i32>(floor(uv)), size, level); } let f = uv - vec2<f32>(0.5); let f0 = floor(f); let t = f - f0; let i0 = vec2<i32>(f0); if quality == 3 { var sum = vec4<f32>(0.0); for (var j = -1; j <= 2; j++) { let wy = mitchellWeight(f32(j) - t.y); for (var i = -1; i <= 2; i++) { sum += wy * mitchellWeight(f32(i) - t.x) * shaderTexel(i0 + vec2<i32>(i, j), size, level); } } let a = clamp(sum.a, 0.0, 1.0); return vec4<f32>(clamp(sum.rgb, vec3<f32>(0.0), vec3<f32>(a)), a); } let c00 = shaderTexel(i0, size, level); let c10 = shaderTexel(i0 + vec2<i32>(1, 0), size, level); let c01 = shaderTexel(i0 + vec2<i32>(0, 1), size, level); let c11 = shaderTexel(i0 + vec2<i32>(1, 1), size, level); return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); } // The premultiplied color of the shader at the pixel at p (or, for vertices, at the texture // coordinates p). fn shaderColor(p: vec2<f32>) -> vec4<f32> { let q = vec2<f32>( paint.xf0.x * p.x + paint.xf0.z * p.y + paint.xf1.x, paint.xf0.y * p.x + paint.xf0.w * p.y + paint.xf1.y); let kind = i32(paint.shader.x + 0.5); if kind == SHADER_LINEAR { return gradientAt(dot(q - paint.p0.xy, paint.p0.zw) * paint.p1.x); } if kind == SHADER_RADIAL { return gradientAt(length(q - paint.p0.xy) / paint.p0.z); } if kind == SHADER_CONICAL { return conicalAt(q); } if kind == SHADER_SWEEP { let d = q - paint.p0.xy; var a = atan2(d.y, d.x) - paint.p0.z; a = a - 2.0 * PI * floor(a / (2.0 * PI)); return gradientAt(a / paint.p0.w); } if kind == SHADER_IMAGE { return imageShaderAt(q); } return paint.constColor; } // ---- color filters fn unpremul(c: vec4<f32>) -> vec4<f32> { if c.a <= 0.0 { return vec4<f32>(0.0); } return vec4<f32>(clamp(c.rgb / c.a, vec3<f32>(0.0), vec3<f32>(1.0)), c.a); } fn premul(c: vec4<f32>) -> vec4<f32> { return vec4<f32>(c.rgb * c.a, c.a); } fn linearToSrgb(v: vec3<f32>) -> vec3<f32> { return select(1.055 * pow(v, vec3<f32>(1.0 / 2.4)) - vec3<f32>(0.055), 12.92 * v, v <= vec3<f32>(0.0031308)); } fn srgbToLinear(v: vec3<f32>) -> vec3<f32> { return select(pow((v + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4)), v / 12.92, v <= vec3<f32>(0.04045)); } // The paint's color filter, then its inverted colors. fn applyFilters(px0: vec4<f32>) -> vec4<f32> { var px = px0; let kind = i32(paint.flags.y + 0.5); if kind == 1 { px = blendPair(i32(paint.flags.z + 0.5), paint.filterColor, px); } else if kind == 2 { let c = unpremul(px) * 255.0; let o = paint.filterMatrix[0] * c.r + paint.filterMatrix[1] * c.g + paint.filterMatrix[2] * c.b + paint.filterMatrix[3] * c.a + paint.filterMatrix[4]; px = premul(clamp(o / 255.0, vec4<f32>(0.0), vec4<f32>(1.0))); } else if kind == 3 { let c = unpremul(px); px = premul(vec4<f32>(linearToSrgb(c.rgb), c.a)); } else if kind == 4 { let c = unpremul(px); px = premul(vec4<f32>(srgbToLinear(c.rgb), c.a)); } if paint.flags.w != 0.0 { let c = unpremul(px); px = premul(vec4<f32>(vec3<f32>(1.0) - c.rgb, c.a)); } return px; } // The source color of a paint at the pixel dev: base is the paint's color, premultiplied, or for // a shader its alpha in all four components; p is the point the shader is evaluated at. fn paintSource(base: vec4<f32>, p: vec2<f32>) -> vec4<f32> { var c = base; if i32(paint.shader.x + 0.5) != SHADER_NONE { c = shaderColor(p) * base; } return applyFilters(c); } // ---- output var<private> bayer: array<f32, 64> = array<f32, 64>( 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0); // The ordered dither of gradients: up to half a level of 8 bits either way. fn ditherAt(dev: vec2<f32>) -> f32 { let p = vec2<i32>(floor(dev)) & vec2<i32>(7); return ((bayer[p.y * 8 + p.x] + 0.5) / 64.0 - 0.5) / 255.0; } // The pixel of the copy of what is being drawn over at the pixel dev. fn destinationAt(dev: vec2<f32>) -> vec4<f32> { return textureLoad(dst, vec2<i32>(floor(dev)) - vec2<i32>(paint.blend.yz), 0); } // The color to write for the source src that covers the pixel by cov: with a fixed-function // blend, the source scaled by the coverage; with any other mode, the destination mixed toward // the blended color by the coverage. fn finish(src: vec4<f32>, cov: f32, dev: vec2<f32>) -> vec4<f32> { var o: vec4<f32>; if paint.blend.x < 0.0 { o = src * cov; } else { let d = destinationAt(dev); o = d + (blendPair(i32(paint.blend.x + 0.5), src, d) - d) * cov; } if paint.flags.x != 0.0 && src.a > 0.0 { o = o + vec4<f32>(ditherAt(dev)); } return o; } // The coverage of a rounded rectangle blurred by a Gaussian, in closed form (SPEC §9.1). Ported // from gles/shaders/shadow.glsl. Shaders include this file with an include line. // // Across a row of the rectangle, the blur of an interval of columns is a difference of two // normal distribution functions. Down the rows the Gaussian is integrated: exactly where the // rows do not change (the straight part of the sides), and by a sum of samples over the rows of // the rounded corners. // The error function (Abramowitz and Stegun 7.1.26, error below 1.5e-7). fn erfApprox(x0: f32) -> f32 { let s = select(1.0, -1.0, x0 < 0.0); let x = abs(x0); let t = 1.0 / (1.0 + 0.3275911 * x); let y = 1.0 - (((((1.061405429 * t - 1.453152027) * t) + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t * exp(-x * x); return s * y; } // The normal distribution function. fn normalCdf(x: f32) -> f32 { return 0.5 + 0.5 * erfApprox(x * 0.7071067811865476); } // How far a corner of radii rad pulls the side in at the row y, with y measured from the center // of the rectangle: top is true for the corners at the top. fn cornerInset(rad: vec2<f32>, y: f32, hy: f32, top: bool) -> f32 { if rad.y <= 0.0 || rad.x <= 0.0 { return 0.0; } let cy = select(hy - rad.y, -hy + rad.y, top); let t = select((y - cy) / rad.y, (cy - y) / rad.y, top); if t <= 0.0 { return 0.0; } return rad.x * (1.0 - sqrt(max(1.0 - t * t, 0.0))); } // The weight of the rows of a corner zone, [y0, y1] from the center, as seen from the pixel at p: // the sum over the rows of the Gaussian times the columns' share. fn zoneMass(y0: f32, y1: f32, p: vec2<f32>, h: vec2<f32>, r1: vec4<f32>, r2: vec4<f32>, sigma: f32, top: bool) -> f32 { let a = max(y0, p.y - 4.0 * sigma); let b = min(y1, p.y + 4.0 * sigma); if b <= a { return 0.0; } let dv = (b - a) / 16.0; var sum = 0.0; for (var i = 0; i < 16; i++) { let y = a + (f32(i) + 0.5) * dv; let l = -h.x + cornerInset(select(r2.zw, r1.xy, top), y, h.y, top); let r = h.x - cornerInset(select(r2.xy, r1.zw, top), y, h.y, top); let w = exp(-0.5 * (y - p.y) * (y - p.y) / (sigma * sigma)); sum += w * max(normalCdf((r - p.x) / sigma) - normalCdf((l - p.x) / sigma), 0.0); } return sum * dv / (sigma * 2.5066282746310002); } // The blurred coverage at the pixel whose position from the rectangle's center is p. fn blurredRRect(p: vec2<f32>, h: vec2<f32>, r1: vec4<f32>, r2: vec4<f32>, sigma: f32) -> f32 { let topH = max(r1.y, r1.w); let botH = max(r2.y, r2.w); var mass = zoneMass(-h.y, -h.y + topH, p, h, r1, r2, sigma, true); mass += zoneMass(h.y - botH, h.y, p, h, r1, r2, sigma, false); let m0 = -h.y + topH; let m1 = h.y - botH; if m1 > m0 { let rows = normalCdf((m1 - p.y) / sigma) - normalCdf((m0 - p.y) / sigma); let cols = normalCdf((h.x - p.x) / sigma) - normalCdf((-h.x - p.x) / sigma); mass += rows * cols; } return clamp(mass, 0.0, 1.0); } // The coverage of a blur style, from the blurred coverage b and the shape's own o. fn blurStyle(style: i32, b: f32, o: f32) -> f32 { if style == 1 { return o + b * (1.0 - o); // solid } if style == 2 { return b * (1.0 - o); // outer } if style == 3 { return b * o; // inner } return b; // normal } struct Frame { // The size of the texture being drawn into, in pixels. surface: vec2<f32>, // The pixel of the surface that the texture's top left corner is: a layer draws // into a texture that covers a rectangle of the surface. origin: vec2<f32>, } // What a draw call sets: the clip mask's rectangle in the surface (x, y, width, height; a // width of 0 means no mask). struct Draw { clipMask: vec4<f32>, } // The uniform buffers are bound with dynamic offsets. @group(0) @binding(0) var<uniform> frame: Frame; @group(0) @binding(1) var<uniform> draw: Draw; // The coverage of the clip shapes that are not rectangles: one 8-bit coverage per pixel of a // rectangle of the surface; a 1x1 texture when there is no mask. @group(1) @binding(0) var clipMask: texture_2d<f32>; struct Instance { @location(0) quad: vec4<f32>, // left, top, right, bottom in pixels @location(1) inv0: vec4<f32>, // the inverse transform: a, b, c, d @location(2) inv1: vec4<f32>, // e, f, kind, flags @location(3) color: vec4<f32>, // premultiplied @location(4) clip: vec4<f32>, // left, top, right, bottom in pixels @location(5) a: vec4<f32>, // shape A: center x, y, half width, half height @location(6) arad1: vec4<f32>, // top left x, y; top right x, y @location(7) arad2: vec4<f32>, // bottom right x, y; bottom left x, y @location(8) b: vec4<f32>, // shape B, which is cut out of A @location(9) brad1: vec4<f32>, @location(10) brad2: vec4<f32>, @location(11) param: vec4<f32>, // half stroke width, cap, exponent, pixels per local unit } struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) dev: vec2<f32>, @location(1) @interpolate(flat) inv0: vec4<f32>, @location(2) @interpolate(flat) inv1: vec4<f32>, @location(3) @interpolate(flat) color: vec4<f32>, @location(4) @interpolate(flat) clip: vec4<f32>, @location(5) @interpolate(flat) a: vec4<f32>, @location(6) @interpolate(flat) arad1: vec4<f32>, @location(7) @interpolate(flat) arad2: vec4<f32>, @location(8) @interpolate(flat) b: vec4<f32>, @location(9) @interpolate(flat) brad1: vec4<f32>, @location(10) @interpolate(flat) brad2: vec4<f32>, @location(11) @interpolate(flat) param: vec4<f32>, } // The kinds of shape (gpu.ShapeKind*). const KIND_RRECT: i32 = 0; // a rounded rectangle, minus shape B when the flags say so const KIND_SUPER: i32 = 1; // a rounded superellipse const KIND_SEGMENT: i32 = 2; // a line segment with caps, or a dot const KIND_FILL: i32 = 3; // every pixel const KIND_BOX: i32 = 4; // an axis-aligned rectangle in pixels, minus shape B, by exact area const KIND_OUTLINE: i32 = 5; // every point within a half width of a rounded rectangle's outline const KIND_SHADOW: i32 = 6; // a rounded rectangle in pixels blurred by a Gaussian, see shadow.wgsl.inc // The flags (gpu.ShapeFlag*). const FLAG_HAS_B: i32 = 1; const FLAG_ANTIALIAS: i32 = 2; const FLAG_SIMILARITY: i32 = 4; // The clip space position of the point dev, in pixels from the top left of the surface. fn toClip(dev: vec2<f32>) -> vec4<f32> { let p = dev - frame.origin; return vec4<f32>(p.x / frame.surface.x * 2.0 - 1.0, 1.0 - p.y / frame.surface.y * 2.0, 0.0, 1.0); } @vertex fn vs_main(@builtin(vertex_index) index: u32, instance: Instance) -> VertexOutput { // The corners of the two triangles: (0,0) (1,0) (0,1) and (1,0) (1,1) (0,1). var corners = array<vec2<f32>, 6>( vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0), vec2<f32>(0.0, 1.0), ); let dev = mix(instance.quad.xy, instance.quad.zw, corners[index]); var out: VertexOutput; out.position = toClip(dev); out.dev = dev; out.inv0 = instance.inv0; out.inv1 = instance.inv1; out.color = instance.color; out.clip = instance.clip; out.a = instance.a; out.arad1 = instance.arad1; out.arad2 = instance.arad2; out.b = instance.b; out.brad1 = instance.brad1; out.brad2 = instance.brad2; out.param = instance.param; return out; } // The coverage of the pixel whose center is dev (in pixels from the top left). fn clipMaskCoverage(dev: vec2<f32>) -> f32 { if draw.clipMask.z <= 0.0 { return 1.0; } let p = vec2<i32>(floor(dev)) - vec2<i32>(draw.clipMask.xy); if p.x < 0 || p.y < 0 || p.x >= i32(draw.clipMask.z) || p.y >= i32(draw.clipMask.w) { return 0.0; } return textureLoad(clipMask, p, 0).r; } // ---- signed distance fields (sdf.glsl) // Distance from the corner q of an ellipse with radii r, with q measured from the // ellipse's center: a first-order estimate that is exact for a circle. fn ellipseDistance(q: vec2<f32>, r: vec2<f32>) -> f32 { let k0 = length(q / r); let k1 = length(q / (r * r)); if k1 > 0.0 { return k0 * (k0 - 1.0) / k1; } return -min(r.x, r.y); } // The corner radii of the quadrant that p is in (y points down). fn cornerRadii(p: vec2<f32>, r1: vec4<f32>, r2: vec4<f32>) -> vec2<f32> { if p.x < 0.0 { if p.y < 0.0 { return r1.xy; } return r2.zw; } if p.y < 0.0 { return r1.zw; } return r2.xy; } // A rounded rectangle centered on the origin with half extents h. fn rrectDistance(p: vec2<f32>, h: vec2<f32>, r1: vec4<f32>, r2: vec4<f32>) -> f32 { let r = cornerRadii(p, r1, r2); let q = abs(p) - (h - r); if q.x > 0.0 && q.y > 0.0 { if r.x > 0.0 && r.y > 0.0 { return ellipseDistance(q, r); } return length(q); } return max(q.x - r.x, q.y - r.y); } // The part of the pixel centered at c that the interval [lo, hi] covers. fn span(c: f32, lo: f32, hi: f32) -> f32 { return clamp(min(c + 0.5, hi) - max(c - 0.5, lo), 0.0, 1.0); } // The part of the pixel centered at dev that the rectangle r (left, top, right, bottom) // covers; without antialiasing, 1 when the center is inside. fn boxCoverage(dev: vec2<f32>, r: vec4<f32>, antialias: bool) -> f32 { if antialias { return span(dev.x, r.x, r.z) * span(dev.y, r.y, r.w); } if dev.x >= r.x && dev.x < r.z && dev.y >= r.y && dev.y < r.w { return 1.0; } return 0.0; } // A rounded superellipse: the corner boxes in r1 and r2 are filled by the curve // |x|^n + |y|^n = 1. fn superDistance(p: vec2<f32>, h: vec2<f32>, r1: vec4<f32>, r2: vec4<f32>, n: f32) -> f32 { let r = cornerRadii(p, r1, r2); let q = abs(p) - (h - r); if q.x > 0.0 && q.y > 0.0 { if r.x <= 0.0 || r.y <= 0.0 { return length(q); } let u = q / r; let f = pow(u.x, n) + pow(u.y, n) - 1.0; let g = n * length(pow(u, vec2<f32>(n - 1.0)) / r); if g > 0.0 { return f / g; } return 0.0; } return max(q.x - r.x, q.y - r.y); } // A segment from a to b of half width hw. cap is 0 for butt, 1 for round, 2 for square. // A segment of no length is a dot: round or square, nothing for butt. fn segmentDistance(p: vec2<f32>, a: vec2<f32>, b: vec2<f32>, hw: f32, cap: f32) -> f32 { let ba = b - a; let len = length(ba); if len < 1e-5 { let pa = p - a; if cap == 1.0 { return length(pa) - hw; } if cap == 2.0 { return max(abs(pa.x), abs(pa.y)) - hw; } return 1e9; } let dir = ba / len; let pa = p - (a + b) * 0.5; let along = abs(dot(pa, dir)); let across = abs(dot(pa, vec2<f32>(-dir.y, dir.x))); if cap == 1.0 { return length(vec2<f32>(max(along - len * 0.5, 0.0), across)) - hw; } if cap == 2.0 { return max(along - len * 0.5 - hw, across - hw); } return max(along - len * 0.5, across - hw); } @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> { // The interpolation is off by a rounding error, which would decide a pixel whose // center is on an edge; the center is where the position is the nearest half pixel. let dev = floor(in.dev) + vec2<f32>(0.5); // The clip rectangle: exact coverage, so anti-aliased clip edges are smooth. let clipCoverage = span(dev.x, in.clip.x, in.clip.z) * span(dev.y, in.clip.y, in.clip.w) * clipMaskCoverage(dev); let kind = i32(in.inv1.z + 0.5); let flags = i32(in.inv1.w + 0.5); let antialias = (flags & FLAG_ANTIALIAS) != 0; let hasB = (flags & FLAG_HAS_B) != 0; let p = vec2<f32>( in.inv0.x * dev.x + in.inv0.z * dev.y + in.inv1.x, in.inv0.y * dev.x + in.inv0.w * dev.y + in.inv1.y); // The distance d of the pixel from the shape, negative inside, in the shape's units. // A box has its coverage from the exact area instead. var d = -1.0; var boxCov = 0.0; if kind == KIND_BOX { boxCov = boxCoverage(dev, in.a, antialias); if hasB { boxCov -= boxCoverage(dev, in.b, antialias); } } else if kind == KIND_SHADOW { // Shape A is in pixels: center, half extents and radii. param holds the deviation of // the blur in pixels and the blur style. let c = dev - in.a.xy; let blurred = blurredRRect(c, in.a.zw, in.arad1, in.arad2, in.param.x); let style = i32(in.param.y + 0.5); var own = 0.0; if style != 0 { own = clamp(0.5 - rrectDistance(c, in.a.zw, in.arad1, in.arad2), 0.0, 1.0); } boxCov = blurStyle(style, blurred, own); } else if kind == KIND_RRECT { d = rrectDistance(p - in.a.xy, in.a.zw, in.arad1, in.arad2); if hasB { d = max(d, -rrectDistance(p - in.b.xy, in.b.zw, in.brad1, in.brad2)); } } else if kind == KIND_OUTLINE { d = abs(rrectDistance(p - in.a.xy, in.a.zw, in.arad1, in.arad2)) - in.param.x; } else if kind == KIND_SUPER { d = superDistance(p - in.a.xy, in.a.zw, in.arad1, in.arad2, in.param.z); } else if kind == KIND_SEGMENT { d = segmentDistance(p, in.a.xy, in.a.zw, in.param.x, in.param.y); } // The screen derivatives need every pixel of the quad: they come before anything // that returns or discards. let g = length(vec2<f32>(dpdx(d), dpdy(d))); var coverage: f32; if kind == KIND_BOX || kind == KIND_SHADOW { coverage = boxCov; } else if !antialias { coverage = select(0.0, 1.0, d <= 0.0); } else if kind == KIND_FILL { coverage = 1.0; } else { // The distance in pixels: the same everywhere for a transform that only rotates // and scales evenly, found from the screen derivatives otherwise. var pixels: f32; if (flags & FLAG_SIMILARITY) != 0 { pixels = d * in.param.w; } else if g > 1e-9 { pixels = d / g; } else { pixels = select(1.0, -1.0, d <= 0.0); } coverage = clamp(0.5 - pixels, 0.0, 1.0); } let total = coverage * clipCoverage; if total <= 0.0 || (kind == KIND_SHADOW && total < 1.0 / 1024.0) { discard; } return finish(paintSource(in.color, dev), total, dev); } `, SPIRV: spirvShape, Entries: []EntryPoint{ {Name: "vs_main", Stage: ShaderStageVertex, Bindings: []ShaderBinding{ {Name: "frame", Group: 0, Binding: 0, Kind: BindingUniformBuffer}, }}, {Name: "fs_main", Stage: ShaderStageFragment, Bindings: []ShaderBinding{ {Name: "draw", Group: 0, Binding: 1, Kind: BindingUniformBuffer}, {Name: "paint", Group: 0, Binding: 2, Kind: BindingUniformBuffer}, {Name: "clipMask", Group: 1, Binding: 0, Kind: BindingSampledTexture}, {Name: "paintImage", Group: 3, Binding: 0, Kind: BindingSampledTexture}, {Name: "dst", Group: 3, Binding: 1, Kind: BindingSampledTexture}, }}, }, }
ShaderShape is shaders/shape.wgsl.
Flutter: no counterpart
var ShaderSolid = &Shader{ Name: "solid", WGSL: `// Solid rectangles, one instance each (SPEC §9.3). Ported from the GLES solid // shader (solid.vert.glsl, solid.frag.glsl) and common.glsl's toClip, with the // rectangle and the color per instance, as the GLES renderer's instanced quads. // // Draw 6 vertices per instance: two triangles made from the vertex index. struct Frame { // The size of the texture being drawn into, in pixels. surface: vec2<f32>, // The pixel of the surface that the texture's top left corner is: a layer draws // into a texture that covers a rectangle of the surface. origin: vec2<f32>, } // The uniform buffer is bound with a dynamic offset. @group(0) @binding(0) var<uniform> frame: Frame; struct Instance { // x, y, width and height in pixels from the top left of the surface. @location(0) rect: vec4<f32>, // The color to fill with, premultiplied. @location(1) color: vec4<f32>, } struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) color: vec4<f32>, } // The clip space position of the point dev, in pixels from the top left of the surface. fn toClip(dev: vec2<f32>) -> vec4<f32> { let p = dev - frame.origin; return vec4<f32>(p.x / frame.surface.x * 2.0 - 1.0, 1.0 - p.y / frame.surface.y * 2.0, 0.0, 1.0); } @vertex fn vs_main(@builtin(vertex_index) index: u32, instance: Instance) -> VertexOutput { // The corners of the two triangles: (0,0) (1,0) (0,1) and (1,0) (1,1) (0,1). var corners = array<vec2<f32>, 6>( vec2<f32>(0.0, 0.0), vec2<f32>(1.0, 0.0), vec2<f32>(0.0, 1.0), vec2<f32>(1.0, 0.0), vec2<f32>(1.0, 1.0), vec2<f32>(0.0, 1.0), ); let corner = corners[index]; var out: VertexOutput; out.position = toClip(instance.rect.xy + corner * instance.rect.zw); out.color = instance.color; return out; } @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> { return in.color; } `, SPIRV: spirvSolid, Entries: []EntryPoint{ {Name: "vs_main", Stage: ShaderStageVertex, Bindings: []ShaderBinding{ {Name: "frame", Group: 0, Binding: 0, Kind: BindingUniformBuffer}, }}, {Name: "fs_main", Stage: ShaderStageFragment, Bindings: []ShaderBinding{}}, }, }
ShaderSolid is shaders/solid.wgsl.
Flutter: no counterpart
var ShaderVertices = &Shader{ Name: "vertices", WGSL: `// Triangles from vertices (Canvas.drawVertices): positions are already in pixels. Ported from // the GLES vertices shaders (vertices.vert.glsl, vertices.frag.glsl). Draw the vertices as they // are: three for each triangle. // The source color of a paint: a solid color, a gradient or an image shader, then the paint's // color filter and inverted colors, and the blend with what is already drawn. Ported from // gles/shaders/paint.glsl. Fragment shaders include this file, after blend.wgsl.inc. // // The 29 blend modes of Flutter's BlendMode, on premultiplied colors, as the software renderer // computes them (internal/gpu/soft/blend.go). mode is the index of the mode in BlendMode's // order: 0 clear, 1 src, 2 dst, 3 srcOver, 4 dstOver, 5 srcIn, 6 dstIn, 7 srcOut, 8 dstOut, // 9 srcATop, 10 dstATop, 11 xor, 12 plus, 13 modulate, 14 screen, 15 overlay, 16 darken, // 17 lighten, 18 colorDodge, 19 colorBurn, 20 hardLight, 21 softLight, 22 difference, // 23 exclusion, 24 multiply, 25 hue, 26 saturation, 27 color, 28 luminosity. Ported from // gles/shaders/blend.glsl. Shaders include this file with an include line. fn hardLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { if 2.0 * s <= sa { return s * (1.0 - da) + d * (1.0 - sa) + 2.0 * s * d; } return s * (1.0 - da) + d * (1.0 - sa) + sa * da - 2.0 * (da - d) * (sa - s); } fn softLightChannel(s: f32, d: f32, sa: f32, da: f32) -> f32 { var m = 0.0; if da > 0.0 { m = d / da; } let s2 = 2.0 * s; let m4 = 4.0 * m; let darkSrc = d * (sa + (s2 - sa) * (1.0 - m)); let darkDst = (m4 * m4 + m4) * (m - 1.0) + 7.0 * m; let liteDst = sqrt(m) - m; var tail = liteDst; if 4.0 * d <= da { tail = darkDst; } let liteSrc = d * sa + da * (s2 - sa) * tail; var body = liteSrc; if s2 <= sa { body = darkSrc; } return s * (1.0 - da) + d * (1.0 - sa) + body; } fn blendChannel(mode: i32, s: f32, d: f32, sa: f32, da: f32) -> f32 { switch mode { case 15: { return hardLightChannel(d, s, da, sa); // overlay } case 16: { return s + d - max(s * da, d * sa); // darken } case 17: { return s + d - min(s * da, d * sa); // lighten } case 18: { // colorDodge if d == 0.0 { return s * (1.0 - da); } if s == sa { return s + d * (1.0 - sa); } return sa * min(da, d * sa / (sa - s)) + s * (1.0 - da) + d * (1.0 - sa); } case 19: { // colorBurn if d == da { return d + s * (1.0 - da); } if s == 0.0 { return d * (1.0 - sa); } return sa * (da - min(da, (da - d) * sa / s)) + s * (1.0 - da) + d * (1.0 - sa); } case 20: { return hardLightChannel(s, d, sa, da); // hardLight } case 21: { return softLightChannel(s, d, sa, da); // softLight } case 22: { return s + d - 2.0 * min(s * da, d * sa); // difference } case 23: { return s + d - 2.0 * s * d; // exclusion } case 24: { return s * (1.0 - da) + d * (1.0 - sa) + s * d; // multiply } default: { return s + d * (1.0 - sa); } } } fn lum(c: vec3<f32>) -> f32 { return 0.30 * c.r + 0.59 * c.g + 0.11 * c.b; } fn sat(c: vec3<f32>) -> f32 { return max(c.r, max(c.g, c.b)) - min(c.r, min(c.g, c.b)); } fn setSat(c: vec3<f32>, s: f32) -> vec3<f32> { let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let range = mx - mn; if range == 0.0 { return vec3<f32>(0.0); } return (c - vec3<f32>(mn)) * s / range; } fn setLum(c: vec3<f32>, l: f32) -> vec3<f32> { return c + vec3<f32>(l - lum(c)); } fn clipColor(c0: vec3<f32>, a: f32) -> vec3<f32> { var c = c0; let mn = min(c.r, min(c.g, c.b)); let mx = max(c.r, max(c.g, c.b)); let l = lum(c); if mn < 0.0 { c = vec3<f32>(l) + (c - vec3<f32>(l)) * l / (l - mn); } if mx > a { c = vec3<f32>(l) + (c - vec3<f32>(l)) * (a - l) / (mx - l); } return max(c, vec3<f32>(0.0)); } fn blendNonSeparable(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; var c: vec3<f32>; if mode == 25 { // hue c = s.rgb * sa; c = setSat(c, sat(d.rgb) * sa); c = setLum(c, lum(d.rgb) * sa); } else if mode == 26 { // saturation c = d.rgb * sa; c = setSat(c, sat(s.rgb) * da); c = setLum(c, lum(d.rgb) * sa); } else if mode == 27 { // color c = s.rgb * da; c = setLum(c, lum(d.rgb) * sa); } else { // luminosity c = d.rgb * sa; c = setLum(c, lum(s.rgb) * da); } c = clipColor(c, sa * da); return vec4<f32>(s.rgb * (1.0 - da) + d.rgb * (1.0 - sa) + c, sa + da - sa * da); } // blendPair blends the source s over the destination d with the mode. fn blendPair(mode: i32, s: vec4<f32>, d: vec4<f32>) -> vec4<f32> { let sa = s.a; let da = d.a; switch mode { case 0: { return vec4<f32>(0.0); } case 1: { return s; } case 2: { return d; } case 3: { return s + d * (1.0 - sa); } case 4: { return d + s * (1.0 - da); } case 5: { return s * da; } case 6: { return d * sa; } case 7: { return s * (1.0 - da); } case 8: { return d * (1.0 - sa); } case 9: { return s * da + d * (1.0 - sa); } case 10: { return d * sa + s * (1.0 - da); } case 11: { return s * (1.0 - da) + d * (1.0 - sa); } case 12: { return min(s + d, vec4<f32>(1.0)); } case 13: { return s * d; } case 14: { return s + d - s * d; } case 25, 26, 27, 28: { return blendNonSeparable(mode, s, d); } default: { // The separable modes defined per channel, whose alpha is that of source-over. return vec4<f32>( blendChannel(mode, s.r, d.r, sa, da), blendChannel(mode, s.g, d.g, sa, da), blendChannel(mode, s.b, d.b, sa, da), sa + da - sa * da); } } } const SHADER_NONE: i32 = 0; const SHADER_LINEAR: i32 = 1; const SHADER_RADIAL: i32 = 2; const SHADER_CONICAL: i32 = 3; const SHADER_SWEEP: i32 = 4; const SHADER_IMAGE: i32 = 5; const SHADER_CONST: i32 = 6; const MAX_STOPS: i32 = 32; const PI: f32 = 3.14159265358979; // What a draw call's paint sets, the layout of gpu.PaintSpec as float4s (see paintUniform). struct Paint { // The shader kind, the tile modes in x and y (0 clamp, 1 repeated, 2 mirror, 3 decal) and // the number of color stops. shader: vec4<f32>, // The matrix from pixels to the shader's space: a, b, c, d, then e, f. xf0: vec4<f32>, xf1: vec4<f32>, // linear: from x, y, dx, dy; radial: center x, y, radius; conical: focal x, y, focal radius; // sweep: center x, y, start, span. p0: vec4<f32>, // linear: 1 / (dx*dx + dy*dy); conical: end center x, y, end radius. p1: vec4<f32>, // The image shader's quality (0 none, 1 low, 2 medium, 3 high) and level. imageInfo: vec4<f32>, // A degenerate gradient: premultiplied color. constColor: vec4<f32>, // Dither (0 or 1), the color filter (0 none, 1 mode, 2 matrix, 3 linear to sRGB, 4 sRGB to // linear), the blend index of a mode filter, and inverted colors (0 or 1). flags: vec4<f32>, // The blend index of a blend that reads the destination (-1: the blend unit does it), and the // pixel of the surface that the copy of the destination starts at. blend: vec4<f32>, // A mode filter's premultiplied color. filterColor: vec4<f32>, // A matrix filter: the columns of the 4x5 matrix in 0 to 255 units. filterMatrix: array<vec4<f32>, 5>, // The gradient's colors (not premultiplied) and positions, four to a float4. rampColor: array<vec4<f32>, 32>, rampPos: array<vec4<f32>, 8>, } @group(0) @binding(2) var<uniform> paint: Paint; // The image of an image shader, and a copy of the pixels being drawn over. @group(3) @binding(0) var paintImage: texture_2d<f32>; @group(3) @binding(1) var dst: texture_2d<f32>; // ---- gradients // Applies the tile mode to a position along a gradient; the second component is 0 where the // shader draws nothing. fn tileT(t: f32, mode: i32) -> vec2<f32> { if mode == 1 { return vec2<f32>(t - floor(t), 1.0); } if mode == 2 { let u = t - 2.0 * floor(t / 2.0); if u > 1.0 { return vec2<f32>(2.0 - u, 1.0); } return vec2<f32>(u, 1.0); } if mode == 3 { if t >= 0.0 && t <= 1.0 { return vec2<f32>(t, 1.0); } return vec2<f32>(t, 0.0); } return vec2<f32>(clamp(t, 0.0, 1.0), 1.0); } fn rampPosAt(i: i32) -> f32 { return paint.rampPos[i >> 2u][i & 3]; } // The premultiplied color at t, interpolated without premultiplied alpha. fn rampAt(t: f32) -> vec4<f32> { let n = i32(paint.shader.w + 0.5); var i = 0; while i < n && rampPosAt(i) < t { i++; } var c: vec4<f32>; if i == 0 { c = paint.rampColor[0]; } else if i >= n { c = paint.rampColor[n - 1]; } else { let p0 = rampPosAt(i - 1); let p1 = rampPosAt(i); if p1 <= p0 { c = paint.rampColor[i]; } else { c = mix(paint.rampColor[i - 1], paint.rampColor[i], (t - p0) / (p1 - p0)); } } c = clamp(c, vec4<f32>(0.0), vec4<f32>(1.0)); return vec4<f32>(c.rgb * c.a, c.a); } fn gradientAt(t0: f32) -> vec4<f32> { if t0 != t0 { return vec4<f32>(0.0); } let tt = tileT(t0, i32(paint.shader.y + 0.5)); if tt.y == 0.0 { return vec4<f32>(0.0); } return rampAt(tt.x); } // The two-point conical gradient from the focal circle to the end circle: the color at a point // is that of the largest t whose circle, which moves and grows from one to the other, goes // through the point. fn conicalAt(q: vec2<f32>) -> vec4<f32> { let c0 = paint.p0.xy; let r0 = paint.p0.z; let cd = paint.p1.xy - c0; let dr = paint.p1.z - r0; let a = dot(cd, cd) - dr * dr; let p = q - c0; let b = dot(p, cd) + r0 * dr; let c = dot(p, p) - r0 * r0; var t: f32; if abs(a) < 1e-12 { if b == 0.0 { return vec4<f32>(0.0); } t = c / (2.0 * b); if r0 + t * dr < 0.0 { return vec4<f32>(0.0); } } else { let disc = b * b - a * c; if disc < 0.0 { return vec4<f32>(0.0); } let sq = sqrt(disc); var t1 = (b + sq) / a; var t2 = (b - sq) / a; if t1 < t2 { let tmp = t1; t1 = t2; t2 = tmp; } if r0 + t1 * dr >= 0.0 { t = t1; } else if r0 + t2 * dr >= 0.0 { t = t2; } else { return vec4<f32>(0.0); } } return gradientAt(t); } // ---- image shaders // A texel of the shader's image at a level, with the tile modes applied to the pixel's index; // transparent where decal draws nothing. fn shaderTexel(p: vec2<i32>, size: vec2<i32>, level: i32) -> vec4<f32> { var x = p.x; var y = p.y; let tileX = i32(paint.shader.y + 0.5); let tileY = i32(paint.shader.z + 0.5); if tileX == 1 { x = ((x % size.x) + size.x) % size.x; } else if tileX == 2 { let m = ((x % (2 * size.x)) + 2 * size.x) % (2 * size.x); if m >= size.x { x = 2 * size.x - 1 - m; } else { x = m; } } else if tileX == 3 { if x < 0 || x >= size.x { return vec4<f32>(0.0); } } else { x = clamp(x, 0, size.x - 1); } if tileY == 1 { y = ((y % size.y) + size.y) % size.y; } else if tileY == 2 { let m = ((y % (2 * size.y)) + 2 * size.y) % (2 * size.y); if m >= size.y { y = 2 * size.y - 1 - m; } else { y = m; } } else if tileY == 3 { if y < 0 || y >= size.y { return vec4<f32>(0.0); } } else { y = clamp(y, 0, size.y - 1); } return textureLoad(paintImage, vec2<i32>(x, y), level); } fn mitchellWeight(x0: f32) -> f32 { let b = 1.0 / 3.0; let c = 1.0 / 3.0; let x = abs(x0); if x < 1.0 { return ((12.0 - 9.0 * b - 6.0 * c) * x * x * x + (-18.0 + 12.0 * b + 6.0 * c) * x * x + (6.0 - 2.0 * b)) / 6.0; } if x < 2.0 { return ((-b - 6.0 * c) * x * x * x + (6.0 * b + 30.0 * c) * x * x + (-12.0 * b - 48.0 * c) * x + (8.0 * b + 24.0 * c)) / 6.0; } return 0.0; } // The shader's image at the point q of its pixels, with the filter quality. fn imageShaderAt(q: vec2<f32>) -> vec4<f32> { let base = vec2<i32>(textureDimensions(paintImage, 0)); let quality = i32(paint.imageInfo.x + 0.5); let level = i32(paint.imageInfo.y + 0.5); let size = vec2<i32>(textureDimensions(paintImage, level)); let uv = q * vec2<f32>(size) / vec2<f32>(base); if quality == 0 { return shaderTexel(vec2<i32>(floor(uv)), size, level); } let f = uv - vec2<f32>(0.5); let f0 = floor(f); let t = f - f0; let i0 = vec2<i32>(f0); if quality == 3 { var sum = vec4<f32>(0.0); for (var j = -1; j <= 2; j++) { let wy = mitchellWeight(f32(j) - t.y); for (var i = -1; i <= 2; i++) { sum += wy * mitchellWeight(f32(i) - t.x) * shaderTexel(i0 + vec2<i32>(i, j), size, level); } } let a = clamp(sum.a, 0.0, 1.0); return vec4<f32>(clamp(sum.rgb, vec3<f32>(0.0), vec3<f32>(a)), a); } let c00 = shaderTexel(i0, size, level); let c10 = shaderTexel(i0 + vec2<i32>(1, 0), size, level); let c01 = shaderTexel(i0 + vec2<i32>(0, 1), size, level); let c11 = shaderTexel(i0 + vec2<i32>(1, 1), size, level); return mix(mix(c00, c10, t.x), mix(c01, c11, t.x), t.y); } // The premultiplied color of the shader at the pixel at p (or, for vertices, at the texture // coordinates p). fn shaderColor(p: vec2<f32>) -> vec4<f32> { let q = vec2<f32>( paint.xf0.x * p.x + paint.xf0.z * p.y + paint.xf1.x, paint.xf0.y * p.x + paint.xf0.w * p.y + paint.xf1.y); let kind = i32(paint.shader.x + 0.5); if kind == SHADER_LINEAR { return gradientAt(dot(q - paint.p0.xy, paint.p0.zw) * paint.p1.x); } if kind == SHADER_RADIAL { return gradientAt(length(q - paint.p0.xy) / paint.p0.z); } if kind == SHADER_CONICAL { return conicalAt(q); } if kind == SHADER_SWEEP { let d = q - paint.p0.xy; var a = atan2(d.y, d.x) - paint.p0.z; a = a - 2.0 * PI * floor(a / (2.0 * PI)); return gradientAt(a / paint.p0.w); } if kind == SHADER_IMAGE { return imageShaderAt(q); } return paint.constColor; } // ---- color filters fn unpremul(c: vec4<f32>) -> vec4<f32> { if c.a <= 0.0 { return vec4<f32>(0.0); } return vec4<f32>(clamp(c.rgb / c.a, vec3<f32>(0.0), vec3<f32>(1.0)), c.a); } fn premul(c: vec4<f32>) -> vec4<f32> { return vec4<f32>(c.rgb * c.a, c.a); } fn linearToSrgb(v: vec3<f32>) -> vec3<f32> { return select(1.055 * pow(v, vec3<f32>(1.0 / 2.4)) - vec3<f32>(0.055), 12.92 * v, v <= vec3<f32>(0.0031308)); } fn srgbToLinear(v: vec3<f32>) -> vec3<f32> { return select(pow((v + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4)), v / 12.92, v <= vec3<f32>(0.04045)); } // The paint's color filter, then its inverted colors. fn applyFilters(px0: vec4<f32>) -> vec4<f32> { var px = px0; let kind = i32(paint.flags.y + 0.5); if kind == 1 { px = blendPair(i32(paint.flags.z + 0.5), paint.filterColor, px); } else if kind == 2 { let c = unpremul(px) * 255.0; let o = paint.filterMatrix[0] * c.r + paint.filterMatrix[1] * c.g + paint.filterMatrix[2] * c.b + paint.filterMatrix[3] * c.a + paint.filterMatrix[4]; px = premul(clamp(o / 255.0, vec4<f32>(0.0), vec4<f32>(1.0))); } else if kind == 3 { let c = unpremul(px); px = premul(vec4<f32>(linearToSrgb(c.rgb), c.a)); } else if kind == 4 { let c = unpremul(px); px = premul(vec4<f32>(srgbToLinear(c.rgb), c.a)); } if paint.flags.w != 0.0 { let c = unpremul(px); px = premul(vec4<f32>(vec3<f32>(1.0) - c.rgb, c.a)); } return px; } // The source color of a paint at the pixel dev: base is the paint's color, premultiplied, or for // a shader its alpha in all four components; p is the point the shader is evaluated at. fn paintSource(base: vec4<f32>, p: vec2<f32>) -> vec4<f32> { var c = base; if i32(paint.shader.x + 0.5) != SHADER_NONE { c = shaderColor(p) * base; } return applyFilters(c); } // ---- output var<private> bayer: array<f32, 64> = array<f32, 64>( 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0); // The ordered dither of gradients: up to half a level of 8 bits either way. fn ditherAt(dev: vec2<f32>) -> f32 { let p = vec2<i32>(floor(dev)) & vec2<i32>(7); return ((bayer[p.y * 8 + p.x] + 0.5) / 64.0 - 0.5) / 255.0; } // The pixel of the copy of what is being drawn over at the pixel dev. fn destinationAt(dev: vec2<f32>) -> vec4<f32> { return textureLoad(dst, vec2<i32>(floor(dev)) - vec2<i32>(paint.blend.yz), 0); } // The color to write for the source src that covers the pixel by cov: with a fixed-function // blend, the source scaled by the coverage; with any other mode, the destination mixed toward // the blended color by the coverage. fn finish(src: vec4<f32>, cov: f32, dev: vec2<f32>) -> vec4<f32> { var o: vec4<f32>; if paint.blend.x < 0.0 { o = src * cov; } else { let d = destinationAt(dev); o = d + (blendPair(i32(paint.blend.x + 0.5), src, d) - d) * cov; } if paint.flags.x != 0.0 && src.a > 0.0 { o = o + vec4<f32>(ditherAt(dev)); } return o; } struct Frame { // The size of the texture being drawn into, in pixels. surface: vec2<f32>, // The pixel of the surface that the texture's top left corner is. origin: vec2<f32>, } // What a draw call sets. struct Draw { // The clip mask's rectangle in the surface (x, y, width, height; a width of 0 means none). clipMask: vec4<f32>, // The paint's color, premultiplied. paint: vec4<f32>, // The clip rectangle: left, top, right, bottom in pixels. clip: vec4<f32>, // The blend index of the paint (source) with the vertex colors (destination), whether the // vertices have colors (0 or 1), whether the shader is evaluated at the texture coordinates // (0 or 1), and one unused. mode: vec4<f32>, } @group(0) @binding(0) var<uniform> frame: Frame; @group(0) @binding(1) var<uniform> draw: Draw; @group(1) @binding(0) var clipMask: texture_2d<f32>; struct VertexInput { @location(0) pos: vec2<f32>, @location(1) color: vec4<f32>, // not premultiplied @location(2) tex: vec2<f32>, // texture coordinates, for a shader } struct VertexOutput { @builtin(position) position: vec4<f32>, @location(0) dev: vec2<f32>, @location(1) color: vec4<f32>, @location(2) tex: vec2<f32>, } fn toClip(dev: vec2<f32>) -> vec4<f32> { let p = dev - frame.origin; return vec4<f32>(p.x / frame.surface.x * 2.0 - 1.0, 1.0 - p.y / frame.surface.y * 2.0, 0.0, 1.0); } @vertex fn vs_main(v: VertexInput) -> VertexOutput { var out: VertexOutput; out.position = toClip(v.pos); out.dev = v.pos; out.color = v.color; out.tex = v.tex; return out; } // The part of the pixel centered at c that the interval [lo, hi] covers. fn span(c: f32, lo: f32, hi: f32) -> f32 { return clamp(min(c + 0.5, hi) - max(c - 0.5, lo), 0.0, 1.0); } fn clipMaskCoverage(dev: vec2<f32>) -> f32 { if draw.clipMask.z <= 0.0 { return 1.0; } let p = vec2<i32>(floor(dev)) - vec2<i32>(draw.clipMask.xy); if p.x < 0 || p.y < 0 || p.x >= i32(draw.clipMask.z) || p.y >= i32(draw.clipMask.w) { return 0.0; } return textureLoad(clipMask, p, 0).r; } @fragment fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> { let dev = floor(in.dev) + vec2<f32>(0.5); var color = draw.paint; if i32(paint.shader.x + 0.5) != SHADER_NONE { var at = dev; if draw.mode.z != 0.0 { at = in.tex; } color = shaderColor(at) * draw.paint; } if draw.mode.y != 0.0 { color = blendPair(i32(draw.mode.x + 0.5), color, vec4<f32>(in.color.rgb * in.color.a, in.color.a)); } color = applyFilters(color); let coverage = span(dev.x, draw.clip.x, draw.clip.z) * span(dev.y, draw.clip.y, draw.clip.w) * clipMaskCoverage(dev); return finish(color, coverage, dev); } `, SPIRV: spirvVertices, Entries: []EntryPoint{ {Name: "vs_main", Stage: ShaderStageVertex, Bindings: []ShaderBinding{ {Name: "frame", Group: 0, Binding: 0, Kind: BindingUniformBuffer}, }}, {Name: "fs_main", Stage: ShaderStageFragment, Bindings: []ShaderBinding{ {Name: "draw", Group: 0, Binding: 1, Kind: BindingUniformBuffer}, {Name: "paint", Group: 0, Binding: 2, Kind: BindingUniformBuffer}, {Name: "clipMask", Group: 1, Binding: 0, Kind: BindingSampledTexture}, {Name: "paintImage", Group: 3, Binding: 0, Kind: BindingSampledTexture}, {Name: "dst", Group: 3, Binding: 1, Kind: BindingSampledTexture}, }}, }, }
ShaderVertices is shaders/vertices.wgsl.
Flutter: no counterpart
Functions ¶
func IsDevicePending ¶
IsDevicePending reports whether err is the error of a device that is on its way.
Flutter: no counterpart
func IsSwapchainOutOfDate ¶
IsSwapchainOutOfDate reports whether err is the error of an out-of-date swapchain.
Flutter: no counterpart
func RotateRects ¶
RotateRects turns rectangles of a width x height window, from its top left, into the rectangles of the image that is drawn with the pre-rotation: the image has the frame rotated clockwise by it (SPEC §24.4). nil stays nil (the whole window).
Flutter: no counterpart
Types ¶
type AddressMode ¶
type AddressMode int
AddressMode is what a sampler does outside the texture. The zero value is AddressUnspecified, which means AddressClamp.
Flutter: no counterpart
const ( // AddressUnspecified is the zero value and means AddressClamp. // // Flutter: no counterpart AddressUnspecified AddressMode = iota // AddressClamp repeats the edge texel. // // Flutter: no counterpart AddressClamp // AddressRepeat tiles the texture. // // Flutter: no counterpart AddressRepeat // AddressMirror tiles the texture, flipping every other tile. // // Flutter: no counterpart AddressMirror )
The address modes.
type BindGroup ¶
type BindGroup interface {
// Destroy releases the bind group.
Destroy()
}
BindGroup is a set of resources for one bind group of a pipeline.
Flutter: no counterpart
type Binding ¶
type Binding struct {
// Binding is the number of the shader's @binding.
Binding int
// Buffer, with Offset and Size, is a uniform buffer; Size 0 means up to the end.
Buffer Buffer
// Offset is where the binding starts in Buffer, in bytes.
Offset int
// Size is the size of the binding in bytes.
Size int
// Texture is a sampled texture.
Texture Texture
// Sampler is a sampler.
Sampler Sampler
}
Binding is one resource of a bind group: the entry for @binding(Binding).
Flutter: no counterpart
type BindingKind ¶
type BindingKind int
BindingKind is what a shader binding is.
Flutter: no counterpart
const ( // BindingUnspecified is the zero value: no binding. // // Flutter: no counterpart BindingUnspecified BindingKind = iota // BindingUniformBuffer is a `var<uniform>`. It is always bound with a dynamic // offset: the uniforms of a frame go into a ring buffer (SPEC §9.3). // // Flutter: no counterpart BindingUniformBuffer // BindingSampledTexture is a `texture_2d<f32>`. // // Flutter: no counterpart BindingSampledTexture // BindingSampler is a `sampler`. // // Flutter: no counterpart BindingSampler )
The kinds of binding the design limits allow (SPEC §9.3).
func (BindingKind) String ¶
func (k BindingKind) String() string
String returns "uniform", "texture" or "sampler".
type BlendFactor ¶
type BlendFactor int
BlendFactor is a factor of the blend equation. The zero value is BlendFactorUnspecified, which means BlendOne.
Flutter: no counterpart
const ( // BlendFactorUnspecified is the zero value and means BlendOne. // // Flutter: no counterpart BlendFactorUnspecified BlendFactor = iota // BlendZero is 0. // // Flutter: no counterpart BlendZero // BlendOne is 1. // // Flutter: no counterpart BlendOne // BlendSrcAlpha is the alpha of the source. // // Flutter: no counterpart BlendSrcAlpha // BlendOneMinusSrcAlpha is 1 minus the alpha of the source. // // Flutter: no counterpart BlendOneMinusSrcAlpha // BlendDstAlpha is the alpha of the destination. // // Flutter: no counterpart BlendDstAlpha // BlendOneMinusDstAlpha is 1 minus the alpha of the destination. // // Flutter: no counterpart BlendOneMinusDstAlpha )
The blend factors.
type BlendState ¶
type BlendState struct {
// Enabled turns blending on; off, the source replaces the destination.
Enabled bool
// SrcFactor and DstFactor are the factors for the color and the alpha.
SrcFactor, DstFactor BlendFactor
}
BlendState is the blend equation of a pipeline: source * SrcFactor + destination * DstFactor, for color and alpha. The zero value is no blending: the source replaces the destination.
Flutter: no counterpart
type Buffer ¶
type Buffer interface {
// Size is the size in bytes.
Size() int
// Destroy releases the buffer. The GPU finishes the frames that use it first.
Destroy()
}
Buffer is a GPU buffer.
Flutter: no counterpart
type BufferUsage ¶
type BufferUsage int
BufferUsage says what a buffer is used for; values are combined with |.
Flutter: no counterpart
const ( // BufferVertex is a buffer of vertex or instance data. // // Flutter: no counterpart BufferVertex BufferUsage = 1 << iota // BufferIndex is a buffer of 16 bit indices. // // Flutter: no counterpart BufferIndex // BufferUniform is a buffer that uniform bindings read, with dynamic offsets. // // Flutter: no counterpart BufferUniform )
The uses of a buffer. Every buffer can be written with Device.WriteBuffer.
type Device ¶
type Device interface {
// Limits are the design limits.
Limits() Limits
// NewBuffer makes a buffer of size bytes.
NewBuffer(size int, usage BufferUsage) (Buffer, error)
// NewTexture makes a 2D texture.
NewTexture(desc TextureDesc) (Texture, error)
// NewSampler makes a sampler.
NewSampler(desc SamplerDesc) (Sampler, error)
// NewPipeline makes a pipeline from a generated shader.
NewPipeline(desc PipelineDesc) (Pipeline, error)
// NewBindGroup makes the resources of the bind group number group of the
// pipeline.
NewBindGroup(p Pipeline, group int, entries []Binding) (BindGroup, error)
// WriteBuffer copies data into the buffer at offset. The data is copied before
// the call returns.
WriteBuffer(b Buffer, offset int, data []byte)
// WriteTexture copies the rows of data, stride bytes apart, into the rectangle r
// of the level of the texture.
WriteTexture(t Texture, level int, r image.Rectangle, data []byte, stride int)
// NewSwapchain makes the swapchain of a window.
NewSwapchain(h gpu.SurfaceHandle) (Swapchain, error)
// Begin starts the commands of a frame; there is one encoder per frame.
Begin() (Encoder, error)
// Close releases the device and everything made with it.
Close() error
}
Device is a GPU, as the explicit renderer sees it. Vulkan and WebGPU implement it within the design limits (SPEC §9.3). Every method runs on the UI thread. The methods that make resources fail with GPUOutOfMemory or GPUDeviceLost; a call that breaks a design limit panics with GPULimitExceeded in debug builds.
Flutter: no counterpart
type Encoder ¶
type Encoder interface {
// BeginPass starts a pass that draws into the target, which must have
// TextureRenderTarget. The previous pass must have ended.
BeginPass(target Texture, load LoadOp, clear ui.Color) Pass
// CopyTexture copies the rectangle r of src to dst at the point at.
CopyTexture(src Texture, r image.Rectangle, dst Texture, at image.Point)
// ReadTexture reads the rectangle r of src. done runs once the GPU has finished,
// never inside the frame that asked.
ReadTexture(src Texture, r image.Rectangle, done func(*image.RGBA, error))
// Submit sends the frame to the GPU.
Submit() error
}
Encoder records the commands of one frame.
Flutter: no counterpart
type EntryPoint ¶
type EntryPoint struct {
// Name is the name of the function.
Name string
// Stage is the stage the function runs in.
Stage ShaderStage
// Bindings are the resources the function reads, directly or through the
// functions it calls, sorted by group and binding.
Bindings []ShaderBinding
}
EntryPoint is a function of a shader that a pipeline stage runs.
Flutter: no counterpart
type FilterMode ¶
type FilterMode int
FilterMode is how a sampler reads between texels. The zero value is FilterUnspecified, which means FilterNearest.
Flutter: no counterpart
const ( // FilterUnspecified is the zero value and means FilterNearest. // // Flutter: no counterpart FilterUnspecified FilterMode = iota // FilterNearest takes the nearest texel. // // Flutter: no counterpart FilterNearest // FilterLinear blends the two nearest texels in each direction. // // Flutter: no counterpart FilterLinear )
The filter modes.
type FrameStats ¶
type FrameStats struct {
// Commands is the number of drawing commands in the scene.
Commands int
// Drawn is the number of commands drawn.
Drawn int
// Skipped is the number of commands left out because the renderer cannot draw them
// yet; only a renderer with SkipUnsupported skips.
Skipped int
// Instances is the number of instanced primitives sent to the GPU (shapes, coverage
// tiles and image rectangles), Vertices the number of vertices, and Batches the number
// of draw calls that drew them.
Instances, Vertices, Batches int
// TilesRasterized, ClipMasksBuilt and ImagesUploaded count the work the frame did that an
// earlier frame's cache could have saved: coverage tiles rasterized, clip masks made and
// images uploaded.
TilesRasterized, ClipMasksBuilt, ImagesUploaded int
// CachedLayersMade is the number of layers drawn into a texture that the raster cache keeps,
// and CachedLayersDrawn the number drawn from such a texture instead of from their contents
// (SPEC §9.1 "Raster cache").
CachedLayersMade, CachedLayersDrawn int
// DamagedPixels is the number of pixels the frame told the compositor to update, and
// DamageRects the number of rectangles they were in: the whole window and 0 when the frame
// was presented whole (SPEC §9.1 "Damage").
DamagedPixels, DamageRects int
// Unsupported lists the features that caused skipped commands, once each.
Unsupported []string
}
FrameStats says what the last frame did.
Flutter: no counterpart
type Limits ¶
type Limits struct {
// MaxBindGroups is the number of bind groups a pipeline can use.
MaxBindGroups int
// MaxSampledTexturesPerStage, MaxSamplersPerStage and MaxUniformBuffersPerStage
// are how many resources of each kind one shader stage can read.
MaxSampledTexturesPerStage, MaxSamplersPerStage, MaxUniformBuffersPerStage int
// UniformOffsetAlignment is what dynamic uniform offsets are a multiple of.
UniformOffsetAlignment int
// MaxUniformBindingSize is the largest uniform binding, in bytes.
MaxUniformBindingSize int
// MaxTextureSize is the largest width or height of a texture, in pixels.
MaxTextureSize int
// MaxVertexBuffers and MaxVertexAttributes are what a pipeline's vertex layout
// can have.
MaxVertexBuffers, MaxVertexAttributes int
// CopyRowPitchAlignment is what the row pitch of a copy between a buffer and a
// texture is a multiple of, in bytes.
CopyRowPitchAlignment int
}
Limits are what a Device guarantees and what the renderer may use. They are WebGPU's default limits, so neither Vulkan nor WebGPU requests more (SPEC §9.3).
Flutter: no counterpart
func DefaultLimits ¶
func DefaultLimits() Limits
DefaultLimits returns the design limits of SPEC §9.3.
Flutter: no counterpart
func (Limits) AlignedRowPitch ¶
AlignedRowPitch returns the row pitch, in bytes, of a copy between a buffer and a texture of the width and the bytes per pixel: the row rounded up to a multiple of CopyRowPitchAlignment.
Flutter: no counterpart
func (Limits) CheckBindGroup ¶
CheckBindGroup panics with GPULimitExceeded in debug builds when the group index is not below MaxBindGroups, or a uniform binding is larger than MaxUniformBindingSize. Backends and the fake device call it from NewBindGroup.
Flutter: no counterpart
func (Limits) CheckPipeline ¶
func (l Limits) CheckPipeline(desc PipelineDesc)
CheckPipeline panics with GPULimitExceeded in debug builds when the pipeline has more vertex buffers or attributes, or its entry points read more resources of a kind or from more bind groups, than the limits allow. Backends and the fake device call it from NewPipeline.
Flutter: no counterpart
func (Limits) CheckSetBindGroup ¶
CheckSetBindGroup panics with GPULimitExceeded in debug builds when the group index is not below MaxBindGroups or a dynamic offset is not a multiple of UniformOffsetAlignment. Backends and the fake device call it from SetBindGroup.
Flutter: no counterpart
func (Limits) CheckSetVertexBuffer ¶
CheckSetVertexBuffer panics with GPULimitExceeded in debug builds when the slot is not below MaxVertexBuffers. Backends and the fake device call it from SetVertexBuffer.
Flutter: no counterpart
func (Limits) CheckTexture ¶
func (l Limits) CheckTexture(desc TextureDesc)
CheckTexture panics with GPULimitExceeded in debug builds when the texture is larger than MaxTextureSize. Backends and the fake device call it from NewTexture.
Flutter: no counterpart
type LoadOp ¶
type LoadOp int
LoadOp is what a pass does with the target's contents before it draws. The zero value is LoadClear.
Flutter: no counterpart
const ( // LoadClear fills the target with the clear color. // // Flutter: no counterpart LoadClear LoadOp = iota // LoadLoad keeps the target's contents. // // Flutter: no counterpart LoadLoad // LoadDontCare leaves the target's contents undefined, for a pass that draws every pixel of // it: a tile-based GPU (Adreno, Mali, PowerVR) then neither clears the tile nor reads it // from memory (SPEC §24.4). A backend without the operation clears. // // Flutter: no counterpart LoadDontCare )
The load operations.
type Pass ¶
type Pass interface {
// SetPipeline chooses the pipeline of the next draws.
SetPipeline(Pipeline)
// SetBindGroup binds the group number group, with one dynamic offset for each
// uniform buffer in it, in binding order, each a multiple of
// Limits.UniformOffsetAlignment.
SetBindGroup(group int, g BindGroup, dynamicOffsets ...uint32)
// SetVertexBuffer binds a vertex buffer to a slot, starting at offset bytes.
SetVertexBuffer(slot int, b Buffer, offset int)
// SetIndexBuffer binds the index buffer, starting at offset bytes.
SetIndexBuffer(b Buffer, offset int)
// SetScissor limits the draws to the rectangle, in pixels of the target.
SetScissor(r image.Rectangle)
// Draw draws vertices, instances times.
Draw(vertices, instances, firstVertex, firstInstance int)
// DrawIndexed draws indices, instances times.
DrawIndexed(indices, instances, firstIndex, baseVertex, firstInstance int)
// End finishes the pass.
End()
}
Pass records the draws of one render pass.
Flutter: no counterpart
type Pipeline ¶
type Pipeline interface {
// Desc is what the pipeline was made with.
Desc() PipelineDesc
// Destroy releases the pipeline.
Destroy()
}
Pipeline is a GPU render pipeline.
Flutter: no counterpart
type PipelineDesc ¶
type PipelineDesc struct {
// Shader is a generated shader.
Shader *Shader
// VertexEntry and FragmentEntry are the names of its entry points.
VertexEntry, FragmentEntry string
// VertexBuffers are the layouts of the vertex buffers, by slot.
VertexBuffers []VertexBufferLayout
// Blend is the blend state.
Blend BlendState
// Target is the format of the texture the pipeline draws into.
Target TextureFormat
}
PipelineDesc describes a render pipeline: a generated shader, its entry points, the vertex layout, the blend state and the format of the target. Triangles are the only topology the renderer uses.
Flutter: no counterpart
type Renderer ¶
type Renderer struct {
// contains filtered or unexported fields
}
Renderer is the renderer for the explicit APIs (SPEC §9.3): the engine's renderer on Vulkan and WebGPU. Each window has a swapchain and an offscreen frame texture; a frame is drawn into the frame texture, then blitted into the swapchain image and presented. It draws everything the GLES renderer draws (SPEC §9.1): shapes, paths, clips, images, text, gradients, color filters, blend modes, layers, blurs, shadows and image filters, with the raster cache and damage tracking, and snapshots without a window (step 20.6).
The device is opened at the first frame, with the handle of the first window, because the choice of a Vulkan device depends on the window.
Flutter: no counterpart (flutter::Rasterizer)
func NewRenderer ¶
func NewRenderer(open func(gpu.SurfaceHandle) (Device, error), opts ...RendererOpts) *Renderer
NewRenderer returns a renderer that has no device yet: open makes it at the first frame, from the handle of the first window.
Flutter: no counterpart
func (*Renderer) Close ¶
func (r *Renderer) Close()
Close destroys the windows' state and the device. It can be called twice.
Flutter: no counterpart
func (*Renderer) Describe ¶
Describe names the renderer and its device, as the device does, or "" before the first frame.
Flutter: no counterpart
func (*Renderer) Draw ¶
func (r *Renderer) Draw(h gpu.SurfaceHandle, width, height int, scene *ui.Scene, capture bool) (*image.RGBA, error)
Draw draws one frame into the window of the handle, whose size is width x height pixels, and presents it; with capture it also reads the frame back, top row first. The first call opens the device and the swapchain (their errors are returned unchanged, such as VulkanLoadFailed or VulkanNoDevice). A swapchain that is out of date is configured again and the frame retried once.
Flutter: no counterpart
func (*Renderer) Invalidate ¶
func (r *Renderer) Invalidate(h gpu.SurfaceHandle)
Invalidate says that the window lost its content, so that its next frame is presented whole; a handle that was never drawn into is ignored.
Flutter: no counterpart
func (*Renderer) LastFrame ¶
func (r *Renderer) LastFrame() FrameStats
LastFrame says what the last call of Draw drew and left out.
Flutter: no counterpart
func (*Renderer) RasterizeScene ¶
RasterizeScene draws the scene into a new image of width x height pixels, as Snapshot does: the ui.Rasterizer of the GPU renderer, for Picture.ToImage and Scene.ToImage.
Flutter: no counterpart
func (*Renderer) Release ¶
func (r *Renderer) Release(h gpu.SurfaceHandle)
Release destroys what the renderer keeps for the window of the handle, which must still exist; a handle that was never drawn into is ignored.
Flutter: no counterpart
func (*Renderer) Snapshot ¶
Snapshot draws the scene into a new image of the size, without a window: the work of Picture.ToImage and Scene.ToImage. The scene is drawn over transparent pixels into a pooled texture, which is read back; the pixels are premultiplied, top row first. The device must exist, so a window has to have been drawn into at some point; the raster cache is neither used nor fed. It fails with RendererClosed, RendererNotAttached, RendererSizeInvalid, GPUNotImplemented as Draw does, and the errors of the device.
Flutter: no counterpart
type RendererOpts ¶
type RendererOpts struct {
// Background is the color each frame is cleared to when HasBackground is set;
// otherwise opaque white.
Background ui.Color
// HasBackground says that Background is set.
HasBackground bool
// Damage tells the compositor which part of a window changed in each frame, when
// the device can (SPEC §9.1 "Damage", §9.4).
Damage bool
// RasterCacheAfter turns on the raster cache: a layer that a scene retains (it is in this
// many consecutive scenes) is drawn into a texture that later frames draw instead of its
// contents (SPEC §9.1 "Raster cache"). Zero, the default, keeps nothing. The engine sets 3:
// the layer of a RepaintBoundary that the framework did not repaint for three frames.
RasterCacheAfter int
// Now is the clock of the device-loss rule (a second loss within 10 seconds of the first
// ends the app); time.Now when nil. Tests set it.
Now func() time.Time
// Log is where a lost device is reported, at Info level; nothing is logged when nil.
Log *slog.Logger
// OnCapture receives a capture whose read-back finishes after Draw returned, on a device
// whose reads are asynchronous (WebGPU, SPEC §9.5): Draw then returns a nil image and a nil
// error for the frame that asked, and OnCapture is called later, on the thread that
// calls Draw, with the image or the error of the read. A device that finishes reads inside
// Submit (Vulkan) returns the image from Draw as before. Without OnCapture a capture that is
// late fails with RendererCaptureFailed.
OnCapture func(img *image.RGBA, err error)
// SkipUnsupported makes Draw leave out what the renderer cannot draw yet, and count
// it in LastFrame, instead of failing with GPUNotImplemented. The development
// examples use it to show what works.
SkipUnsupported bool
}
RendererOpts are the optional parameters of NewRenderer.
Flutter: no counterpart
type Rotation ¶
type Rotation int
Rotation is a rotation by quarter turns, clockwise: a surface's pre-transform (SPEC §24.4).
Flutter: no counterpart
type Sampler ¶
type Sampler interface {
// Destroy releases the sampler.
Destroy()
}
Sampler is a GPU sampler.
Flutter: no counterpart
type SamplerDesc ¶
type SamplerDesc struct {
// MinFilter and MagFilter are used when the texture is minified and magnified.
MinFilter, MagFilter FilterMode
// MipmapFilter chooses between mip levels; FilterUnspecified uses level 0 only.
MipmapFilter FilterMode
// AddressU and AddressV are the modes of the two directions.
AddressU, AddressV AddressMode
}
SamplerDesc describes a sampler.
Flutter: no counterpart
type Shader ¶
type Shader struct {
// Name is the name of the .wgsl file without its extension.
Name string
// WGSL is the source text.
WGSL string
// SPIRV is what naga made from WGSL: one module with every entry point.
SPIRV []byte
// Entries are the entry points of the module.
Entries []EntryPoint
}
Shader is one WGSL module with its SPIR-V. glutter-gen shaders makes the values of this type in shaders_gen.go (D20): WebGPU takes WGSL, Vulkan takes SPIR-V.
Flutter: no counterpart
type ShaderBinding ¶
type ShaderBinding struct {
// Name is the name of the variable in the WGSL.
Name string
// Group and Binding are the numbers of the declaration.
Group, Binding int
// Kind says what the resource is.
Kind BindingKind
}
ShaderBinding is one resource a shader reads, from its declaration in the WGSL: `@group(g) @binding(b) var ...`.
Flutter: no counterpart
type ShaderStage ¶
type ShaderStage int
ShaderStage is the stage of a shader entry point.
Flutter: no counterpart
const ( // ShaderStageUnspecified is the zero value: no stage. // // Flutter: no counterpart ShaderStageUnspecified ShaderStage = iota // ShaderStageVertex is an entry point marked @vertex. // // Flutter: no counterpart ShaderStageVertex // ShaderStageFragment is an entry point marked @fragment. // // Flutter: no counterpart ShaderStageFragment )
The stages of the shaders of the explicit renderer. There is no compute in 1.1.
func (ShaderStage) String ¶
func (s ShaderStage) String() string
String returns "vertex" or "fragment".
type Swapchain ¶
type Swapchain interface {
// Configure sets the size of the images, in device pixels of the window as it is seen: when
// the swapchain has a pre-transform of a quarter turn, its images have the size turned.
Configure(width, height int) error
// PreRotation is the rotation that the window system expects of the images (Android's
// currentTransform): the frame is drawn into the image rotated clockwise by it, and the
// presentation engine then does not rotate it again. It is valid after Configure, and
// Rotation0 on every window system but Android's.
PreRotation() Rotation
// Stale says that the window system turned the surface (Android's currentTransform changed,
// which it reports once the surface is on screen, or when the device is turned without a
// change of size): the image that was just presented was drawn for the old pre-transform, and the
// renderer draws it again, whole and without building the scene again, into a swapchain that
// Configure makes. It is cleared by Configure.
Stale() bool
// Acquire returns the image to draw into next. When it is out of date, Configure
// again and retry once.
Acquire() (Texture, error)
// Present shows the image, telling the compositor which rectangles changed (nil
// means all).
Present(damage []image.Rectangle) error
// Destroy releases the swapchain.
Destroy()
}
Swapchain is the images of a window.
Flutter: no counterpart
type Texture ¶
type Texture interface {
// Desc is what the texture was made with, with MipLevels at least 1.
Desc() TextureDesc
// Level returns a texture that is the mip level i of this one: it has the size of that
// level and one level, and a pass can draw into it and a bind group can sample it, which
// is how the downsampling pass makes the mipmaps (SPEC §9.3). The texture it returns
// belongs to this one and goes away with it. Level(0) of a texture with one level is the
// texture itself.
Level(i int) Texture
// Destroy releases the texture. The GPU finishes the frames that use it first.
Destroy()
}
Texture is a GPU 2D texture.
Flutter: no counterpart
type TextureDesc ¶
type TextureDesc struct {
// Width and Height are in pixels, at most Limits.MaxTextureSize.
Width, Height int
// Format is the pixel format.
Format TextureFormat
// MipLevels is the number of levels; 0 means 1.
MipLevels int
// Usage says how the texture is used.
Usage TextureUsage
}
TextureDesc describes a 2D texture.
Flutter: no counterpart
type TextureFormat ¶
type TextureFormat int
TextureFormat is the pixel format of a texture. There are no sRGB formats: blending is done in non-linear sRGB (SPEC §9.1, §9.3). The zero value is TextureFormatUnspecified.
Flutter: no counterpart
const ( // TextureFormatUnspecified is the zero value: no format. // // Flutter: no counterpart TextureFormatUnspecified TextureFormat = iota // TextureFormatRGBA8Unorm is 4 bytes per pixel, red first. // // Flutter: no counterpart TextureFormatRGBA8Unorm // TextureFormatBGRA8Unorm is 4 bytes per pixel, blue first: the usual swapchain // format. // // Flutter: no counterpart TextureFormatBGRA8Unorm // TextureFormatR8Unorm is 1 byte per pixel: coverage masks and glyph atlases. // // Flutter: no counterpart TextureFormatR8Unorm )
The formats of a texture.
func (TextureFormat) BytesPerPixel ¶
func (f TextureFormat) BytesPerPixel() int
BytesPerPixel returns the size of a pixel in bytes; 0 for an unspecified format.
Flutter: no counterpart
type TextureUsage ¶
type TextureUsage int
TextureUsage says what a texture is used for; values are combined with |. Every texture can be written with Device.WriteTexture.
Flutter: no counterpart
const ( // TextureSampled is a texture that shaders sample. // // Flutter: no counterpart TextureSampled TextureUsage = 1 << iota // TextureRenderTarget is a texture that a pass draws into. // // Flutter: no counterpart TextureRenderTarget // TextureCopySource is a texture that CopyTexture or ReadTexture reads. // // Flutter: no counterpart TextureCopySource )
The uses of a texture.
type VertexAttribute ¶
type VertexAttribute struct {
// Location is the @location of the shader's input.
Location int
// Format is the type of the data.
Format VertexFormat
// Offset is where the data starts in an element of the buffer, in bytes.
Offset int
}
VertexAttribute is one input of the vertex shader, in a buffer.
Flutter: no counterpart
type VertexBufferLayout ¶
type VertexBufferLayout struct {
// Stride is the size of an element in bytes.
Stride int
// PerInstance makes the buffer advance once for each instance instead of each
// vertex.
PerInstance bool
// Attributes are the inputs that come from this buffer.
Attributes []VertexAttribute
}
VertexBufferLayout is how a vertex buffer is read.
Flutter: no counterpart
type VertexFormat ¶
type VertexFormat int
VertexFormat is the type of a vertex attribute. The zero value is VertexFormatUnspecified.
Flutter: no counterpart
const ( // VertexFormatUnspecified is the zero value: no format. // // Flutter: no counterpart VertexFormatUnspecified VertexFormat = iota // VertexFloat32 is one float32. // // Flutter: no counterpart VertexFloat32 // VertexFloat32x2 is two float32. // // Flutter: no counterpart VertexFloat32x2 // VertexFloat32x3 is three float32. // // Flutter: no counterpart VertexFloat32x3 // VertexFloat32x4 is four float32. // // Flutter: no counterpart VertexFloat32x4 // VertexUnorm8x4 is four bytes read as numbers from 0 to 1. // // Flutter: no counterpart VertexUnorm8x4 )
The vertex formats.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package fakedevice is an explicit.Device that records every call, for the unit tests of the explicit renderer without a GPU.
|
Package fakedevice is an explicit.Device that records every call, for the unit tests of the explicit renderer without a GPU. |