|
| 1 | +// Copyright (c) Six Labors. |
| 2 | +// Licensed under the Six Labors Split License. |
| 3 | + |
| 4 | +using System.Text; |
| 5 | +using Silk.NET.WebGPU; |
| 6 | + |
| 7 | +namespace SixLabors.ImageSharp.Drawing.Processing.Backends; |
| 8 | + |
| 9 | +/// <summary> |
| 10 | +/// Final staged-scene fine pass for thresholded aliased rasterization. |
| 11 | +/// The WGSL stays shared with the analytic fine pass, but coverage is quantized |
| 12 | +/// immediately after path evaluation so brush evaluation and composition still |
| 13 | +/// reuse the same scene encoding and blend logic. |
| 14 | +/// </summary> |
| 15 | +internal static class FineAliasedThresholdComputeShader |
| 16 | +{ |
| 17 | + private const string OutputBindingMarker = "var output: texture_storage_2d<rgba8unorm, write>;"; |
| 18 | + private const string OutputStoreMarker = "textureStore(output, vec2<i32>(coords), rgba_sep);"; |
| 19 | + private const string PremulAlphaMarker = "fn premul_alpha(rgba: vec4<f32>) -> vec4<f32> {"; |
| 20 | + private const string WorkgroupSizeMarker = "// The X size should be 16 / PIXELS_PER_THREAD"; |
| 21 | + private const string AnalyticFillCallMarker = " fill_path(fill, local_xy, &area);"; |
| 22 | + private const string MsaaFillCallMarker = " fill_path_ms(fill, local_id.xy, &area);"; |
| 23 | + private const string ThresholdHelper = |
| 24 | + """ |
| 25 | + fn apply_aliased_threshold(result: ptr<function, array<f32, PIXELS_PER_THREAD>>) { |
| 26 | + let threshold = config.fine_coverage_threshold; |
| 27 | + for (var i = 0u; i < PIXELS_PER_THREAD; i += 1u) { |
| 28 | + (*result)[i] = select(0.0, 1.0, (*result)[i] >= threshold); |
| 29 | + } |
| 30 | + } |
| 31 | +
|
| 32 | + """; |
| 33 | + |
| 34 | + private static readonly object CacheSync = new(); |
| 35 | + private static readonly Dictionary<TextureFormat, byte[]> ShaderCache = []; |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// Gets the compute entry point exported by the aliased fine shader. |
| 39 | + /// </summary> |
| 40 | + public static ReadOnlySpan<byte> EntryPoint => "main\0"u8; |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Gets the texture-format-specialized WGSL for the aliased threshold fine pass. |
| 44 | + /// </summary> |
| 45 | + public static bool TryGetCode(TextureFormat textureFormat, out byte[] code, out string? error) |
| 46 | + { |
| 47 | + if (!TryGetTraits(textureFormat, out ShaderTraits traits)) |
| 48 | + { |
| 49 | + code = []; |
| 50 | + error = $"Scene aliased-threshold fine shader does not support texture format '{textureFormat}'."; |
| 51 | + return false; |
| 52 | + } |
| 53 | + |
| 54 | + lock (CacheSync) |
| 55 | + { |
| 56 | + if (ShaderCache.TryGetValue(textureFormat, out byte[]? cachedCode)) |
| 57 | + { |
| 58 | + code = cachedCode; |
| 59 | + error = null; |
| 60 | + return true; |
| 61 | + } |
| 62 | + |
| 63 | + string source = GeneratedWgslShaderSources.FineText; |
| 64 | + source = source.Replace(OutputBindingMarker, $"var output: texture_storage_2d<{traits.OutputFormat}, write>;", StringComparison.Ordinal); |
| 65 | + source = source.Replace(OutputStoreMarker, traits.StoreOutputStatement, StringComparison.Ordinal); |
| 66 | + source = source.Replace(PremulAlphaMarker, $"{traits.EncodeOutputFunction}\n\n{PremulAlphaMarker}", StringComparison.Ordinal); |
| 67 | + source = source.Replace(WorkgroupSizeMarker, $"{ThresholdHelper}{WorkgroupSizeMarker}", StringComparison.Ordinal); |
| 68 | + source = source.Replace(AnalyticFillCallMarker, $"{AnalyticFillCallMarker}\n apply_aliased_threshold(&area);", StringComparison.Ordinal); |
| 69 | + source = source.Replace(MsaaFillCallMarker, $"{MsaaFillCallMarker}\n apply_aliased_threshold(&area);", StringComparison.Ordinal); |
| 70 | + |
| 71 | + int byteCount = Encoding.UTF8.GetByteCount(source); |
| 72 | + code = new byte[byteCount + 1]; |
| 73 | + _ = Encoding.UTF8.GetBytes(source, code); |
| 74 | + code[^1] = 0; |
| 75 | + ShaderCache[textureFormat] = code; |
| 76 | + } |
| 77 | + |
| 78 | + error = null; |
| 79 | + return true; |
| 80 | + } |
| 81 | + |
| 82 | + /// <summary> |
| 83 | + /// Creates the bind-group layout consumed by the aliased threshold fine pass. |
| 84 | + /// </summary> |
| 85 | + public static unsafe bool TryCreateBindGroupLayout( |
| 86 | + WebGPU api, |
| 87 | + Device* device, |
| 88 | + TextureFormat outputTextureFormat, |
| 89 | + out BindGroupLayout* layout, |
| 90 | + out string? error) |
| 91 | + => FineAreaComputeShader.TryCreateBindGroupLayout(api, device, outputTextureFormat, out layout, out error); |
| 92 | + |
| 93 | + private static bool TryGetTraits(TextureFormat textureFormat, out ShaderTraits traits) |
| 94 | + { |
| 95 | + if (!WebGPUDrawingBackend.TryGetCompositeTextureShaderTraits(textureFormat, out WebGPUDrawingBackend.CompositeTextureShaderTraits compositeTraits)) |
| 96 | + { |
| 97 | + traits = default; |
| 98 | + return false; |
| 99 | + } |
| 100 | + |
| 101 | + traits = compositeTraits.EncodingKind switch |
| 102 | + { |
| 103 | + WebGPUDrawingBackend.CompositeTextureEncodingKind.Float => CreateFloatTraits(compositeTraits.OutputFormat), |
| 104 | + WebGPUDrawingBackend.CompositeTextureEncodingKind.Snorm => CreateSnormTraits(compositeTraits.OutputFormat), |
| 105 | + WebGPUDrawingBackend.CompositeTextureEncodingKind.Uint8 => CreateUintTraits(compositeTraits.OutputFormat, 255F), |
| 106 | + WebGPUDrawingBackend.CompositeTextureEncodingKind.Uint16 => CreateUintTraits(compositeTraits.OutputFormat, 65535F), |
| 107 | + WebGPUDrawingBackend.CompositeTextureEncodingKind.Sint16 => CreateSintTraits(compositeTraits.OutputFormat, -32768F, 32767F), |
| 108 | + _ => default |
| 109 | + }; |
| 110 | + |
| 111 | + return true; |
| 112 | + } |
| 113 | + |
| 114 | + private static ShaderTraits CreateFloatTraits(string outputFormat) |
| 115 | + { |
| 116 | + const string encodeOutput = |
| 117 | + """ |
| 118 | + fn encode_output(color: vec4<f32>) -> vec4<f32> { |
| 119 | + return color; |
| 120 | + } |
| 121 | + """; |
| 122 | + |
| 123 | + return new ShaderTraits( |
| 124 | + outputFormat, |
| 125 | + encodeOutput, |
| 126 | + "textureStore(output, vec2<i32>(coords), encode_output(rgba_sep));"); |
| 127 | + } |
| 128 | + |
| 129 | + private static ShaderTraits CreateSnormTraits(string outputFormat) |
| 130 | + { |
| 131 | + const string encodeOutput = |
| 132 | + """ |
| 133 | + fn encode_output(color: vec4<f32>) -> vec4<f32> { |
| 134 | + let clamped = clamp(color, vec4<f32>(0.0), vec4<f32>(1.0)); |
| 135 | + return (clamped * 2.0) - vec4<f32>(1.0); |
| 136 | + } |
| 137 | + """; |
| 138 | + |
| 139 | + return new ShaderTraits( |
| 140 | + outputFormat, |
| 141 | + encodeOutput, |
| 142 | + "textureStore(output, vec2<i32>(coords), encode_output(rgba_sep));"); |
| 143 | + } |
| 144 | + |
| 145 | + private static ShaderTraits CreateUintTraits(string outputFormat, float maxValue) |
| 146 | + { |
| 147 | + string maxVector = $"vec4<f32>({maxValue:F1}, {maxValue:F1}, {maxValue:F1}, {maxValue:F1})"; |
| 148 | + const string encodeOutput = |
| 149 | + """ |
| 150 | + const UINT_TEXEL_MAX: vec4<f32> = __UINT_TEXEL_MAX__; |
| 151 | + fn encode_output(color: vec4<f32>) -> vec4<u32> { |
| 152 | + let clamped = clamp(color, vec4<f32>(0.0), vec4<f32>(1.0)); |
| 153 | + return vec4<u32>(round(clamped * UINT_TEXEL_MAX)); |
| 154 | + } |
| 155 | + """; |
| 156 | + |
| 157 | + return new ShaderTraits( |
| 158 | + outputFormat, |
| 159 | + encodeOutput.Replace("__UINT_TEXEL_MAX__", maxVector, StringComparison.Ordinal), |
| 160 | + "textureStore(output, vec2<i32>(coords), encode_output(rgba_sep));"); |
| 161 | + } |
| 162 | + |
| 163 | + private static ShaderTraits CreateSintTraits(string outputFormat, float minValue, float maxValue) |
| 164 | + { |
| 165 | + string minVector = $"vec4<f32>({minValue:F1}, {minValue:F1}, {minValue:F1}, {minValue:F1})"; |
| 166 | + string maxVector = $"vec4<f32>({maxValue:F1}, {maxValue:F1}, {maxValue:F1}, {maxValue:F1})"; |
| 167 | + string encodeOutput = |
| 168 | + $$""" |
| 169 | + const SINT_TEXEL_MIN: vec4<f32> = {{minVector}}; |
| 170 | + const SINT_TEXEL_MAX: vec4<f32> = {{maxVector}}; |
| 171 | + const SINT_TEXEL_RANGE: vec4<f32> = SINT_TEXEL_MAX - SINT_TEXEL_MIN; |
| 172 | + fn encode_output(color: vec4<f32>) -> vec4<i32> { |
| 173 | + let clamped = clamp(color, vec4<f32>(0.0), vec4<f32>(1.0)); |
| 174 | + return vec4<i32>(round((clamped * SINT_TEXEL_RANGE) + SINT_TEXEL_MIN)); |
| 175 | + } |
| 176 | + """; |
| 177 | + |
| 178 | + return new ShaderTraits( |
| 179 | + outputFormat, |
| 180 | + encodeOutput, |
| 181 | + "textureStore(output, vec2<i32>(coords), encode_output(rgba_sep));"); |
| 182 | + } |
| 183 | + |
| 184 | + private readonly struct ShaderTraits( |
| 185 | + string outputFormat, |
| 186 | + string encodeOutputFunction, |
| 187 | + string storeOutputStatement) |
| 188 | + { |
| 189 | + public string OutputFormat { get; } = outputFormat; |
| 190 | + |
| 191 | + public string EncodeOutputFunction { get; } = encodeOutputFunction; |
| 192 | + |
| 193 | + public string StoreOutputStatement { get; } = storeOutputStatement; |
| 194 | + } |
| 195 | +} |
0 commit comments