Skip to content

Commit 36262d7

Browse files
committed
text rendering improvements
1 parent 269025b commit 36262d7

3 files changed

Lines changed: 241 additions & 63 deletions

File tree

data/shaders/screen_text_shader.wgsl

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,29 @@ fn vs_main(v:VSIn) -> VSOut {
3030
return o;
3131
}
3232

33+
fn median(r: f32, g: f32, b: f32) -> f32 {
34+
return max(min(r, g), min(max(r, g), b));
35+
}
36+
37+
fn smooth_step(edge0: f32, edge1: f32, x: f32) -> f32 {
38+
let t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
39+
return t * t * (3.0 - 2.0 * t);
40+
}
41+
3342
@fragment
3443
fn fs_main(i:VSOut) -> @location(0) vec4<f32> {
35-
let a = textureSample(tex, samp, i.uv).r;
36-
return vec4<f32>(i.col.rgb, i.col.a * a);
44+
let msdf_sample = textureSample(tex, samp, i.uv);
45+
46+
let distance = median(msdf_sample.r, msdf_sample.g, msdf_sample.b);
47+
48+
let signed_distance = (distance - 0.5) * 12.0;
49+
50+
let unit_range = 6.0;
51+
let screen_px_range = unit_range * length(fwidth(i.uv)) * 64.0;
52+
let screen_px_distance = signed_distance / max(screen_px_range, 0.001);
53+
54+
let smoothness = 0.7;
55+
let alpha = smooth_step(-smoothness, smoothness, screen_px_distance);
56+
57+
return vec4<f32>(i.col.rgb, i.col.a * alpha);
3758
}

data/shaders/text_shader.wgsl

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,29 @@ fn vs_main(v: VSIn) -> VSOut {
2929
return o;
3030
}
3131

32+
fn median(r: f32, g: f32, b: f32) -> f32 {
33+
return max(min(r, g), min(max(r, g), b));
34+
}
35+
36+
fn smooth_step(edge0: f32, edge1: f32, x: f32) -> f32 {
37+
let t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
38+
return t * t * (3.0 - 2.0 * t);
39+
}
40+
3241
@fragment
3342
fn fs_main(inp: VSOut) -> @location(0) vec4<f32> {
34-
let a = textureSample(tex, samp, inp.uv).r;
35-
return vec4<f32>(inp.col.rgb, inp.col.a * a);
43+
let msdf_sample = textureSample(tex, samp, inp.uv);
44+
45+
let distance = median(msdf_sample.r, msdf_sample.g, msdf_sample.b);
46+
47+
let signed_distance = (distance - 0.5) * 12.0;
48+
49+
let unit_range = 6.0;
50+
let screen_px_range = unit_range * length(fwidth(inp.uv)) * 64.0;
51+
let screen_px_distance = signed_distance / max(screen_px_range, 0.001);
52+
53+
let smoothness = 0.7;
54+
let alpha = smooth_step(-smoothness, smoothness, screen_px_distance);
55+
56+
return vec4<f32>(inp.col.rgb, inp.col.a * alpha);
3657
}

0 commit comments

Comments
 (0)