MetalNanoVG icon indicating copy to clipboard operation
MetalNanoVG copied to clipboard

Use discard_fragment to fix antialiasing

Open bohdanovskyi opened this issue 5 years ago • 4 comments

In order to indicate to Metal that we don’t want to provide a color for a fragment, we cannot simply set the returned alpha value to 0. If we did, the fragment depth would still be written into the depth buffer, causing any geometry behind the “transparent” point to be obscured.

Instead, we need to call a special function that avoids specifying a color value for the fragment entirely: discard_fragment. Calling this function prevents Metal from writing the computed depth and color values of the fragment into the renderbuffer, which allows the scene behind the fragment to show through.

Link: http://metalbyexample.com/translucency-and-transparency/

bohdanovskyi avatar Jun 25 '19 08:06 bohdanovskyi

Do you have a real example demonstrating the difference? discard_fragment() was used in the earlier versions, but the performance is much worse than float4(0).

olliwang avatar Aug 17 '19 12:08 olliwang

Here's an example running the nanovg demo:

Using discard_fragment: example1 Current implementation: example2

You can see how thin lines in the demo (top left) become almost invisible and lines in general look very jagged.

You are right that discard_fragment is slower however but it's still cheaper than using multisampling as an alternative to achieve smooth lines. discard_fragment: profile1 Current implementation: profile2

bohdanovskyi avatar Aug 23 '19 09:08 bohdanovskyi

I just tested both methods on my iMac 5K (Late 2014). I think the difference is negligible. Can you tell which one uses discard_fragment() in the pic below?

Screen Shot 2019-08-23 at 9 36 17 PM

olliwang avatar Aug 23 '19 13:08 olliwang

@olliwang use discard_fragment(), my black apple 4k

分辨率:	3840 x 2160(2160p/4K UHD 1 - 超高清)
UI看起来类似:	1920 x 1080 @ 60.00Hz

my example code

The trial effect is obviously better than the original:

截屏2023-02-09 11 21 35

zeromake avatar Feb 09 '23 03:02 zeromake