Exact Polygonal Filtering: Using Green's Theorem and Clipping for Anti-Aliasing
jonathanolson.net
jonathanolson.net
We do have a plan for conflation free compositing[1] which should closely approximate the quality of the samples here. That in turn depends on sparse strips[2], though a degraded performance experiment could be done to validate the quality outcomes. Sparse strips in turn depend on high performance segmented sort[3].
The analytic approach to path overlaps is intriguing, but I think it will be very challenging to implement efficiently on GPU. I'm looking forward to seeing what results.
[1]: https://xi.zulipchat.com/#narrow/stream/197075-gpu/topic/Con...
[2]: https://docs.google.com/document/d/16dlcHvvLMumRa5MAyk2Du_Ms...
[3]: https://xi.zulipchat.com/#narrow/stream/197075-gpu/topic/A.2...
If I were going to take it on, I'd start with BVH construction - the H-PLOC paper at the latest HPG [1] looks promising - then traverse down the hierarchy until you get very small number of path segments so you can pairwise compare them. Obviously any time there is an intersection you need at least the two segments.
This seems hard to me, humbling even. I mean, overlap removal is hard enough on the CPU, especially because it's so sensitive to numerical robustness, and doubly so for curves. But I think you'll learn something for trying!
[﹡] https://news.ycombinator.com/item?id=41105102 but it didn't make the front page; I'm holding back promoting it further pending writing a companion blog post.
I've written similar operations[1] that include elliptical arcs AND Bézier curves, and robustness has been an issue. An assortment of polygon clipping approaches use ONLY line segments and fixed precision numbers to work around this.
If I discretize the line segments to 20bits (fixed), potentially in tiles (to reduce inaccuracies), then I can represent exact rational intersections (and parametric t values) with 64-bit numerators and 64-bit denominators[2].
This significantly concerns me about computation cost (and memory if I need to store them), but using this scheme to ensure absolute correctness (and ordering) of intersections does seem to work in CPU proof-of-concepts. Perhaps it is possible to only use this expensive method to disambiguate if it cannot be done from floating-point numbers.
My initial GPU concept imagined a sorting of intersected segments, however a radix sort over a 128-bit object seems like a non-starter, and if I try that, a merge sort may still be viable?
Thank you for the links and recommendations!
[1]: https://github.com/phetsims/kite
[2]: https://github.com/phetsims/alpenglow/blob/main/js/webgpu/wg...
One significant limitation here is that the polygon needs to have constant colour, unfortunately.
Pixar's Renderman used to use a (slightly) related technique. This was along time ago, and I have no idea if they still do things this way - but they would subdivide patches until each primitive was smaller than a pixel.
There's also this work on analytic antialiasing by Michael Mccool: https://www.researchgate.net/publication/2524514_Analytic_An...
The problem you run into with non-constant polygon colors is that you’d have to integrate the product of two different functions here - the polygon color and the filter function. For anything real-world, this is almost certainly going to result in an expression that is not analytically integrable.
Ideally you also want motion blur and probably some other effects, so IMO it just makes sense to use a 2D BVH and high efficiency Monte Carlo importance sampling methods.
A more interesting approach to antialiasing, in my opinion, is the use of neural nets to generate aesthetically pleasing outputs from limited sample data, as seen for example in NVidia's DLAA [0]. These methods go beyond trying to optimize over-simplistic signal processing reconstruction metrics.
[0] https://en.wikipedia.org/wiki/Deep_learning_anti-aliasing
Am I the only one who has trouble understanding what is meant by this? What is the exact operation that's referred to here?
I know box filters in the context of 2D image filtering and they're straightforward but the concept of applying them to shapes just doesn't make any sense to me.
Can someone clarify?
- You take a square a single pixel spacing wide by its center and attach it to a sampling point (“center of a pixel”). The value of that pixel is then your mathematically perfect image (of a polygon) integrated over that square (and normalized). This is perhaps the more intuitive definition.
- You take a box kernel (the indicator function of that square, centered, normalized), take the convolution[1] of it with the original perfect image, then sample the result at the final points (“pixel centers”). This is the standard definition, which yields exactly the same result as long as your kernel is symmetric (which the box kernel is).
The connection with the pixel-image filtering case is that you take the perfect image to be composed of delta functions at the original pixel centers and multiplied by the original pixel values. That is, in the first definition above, “integrate” means to sum the original pixel values multiplied by the filter’s value at the original pixel centers (for a box filter, zero if outside the box—i.e. throw away the addend—and a normalization constant if inside it). Alternatively, in the second definition above, “take the convolution” means to attach a copy of the filter (still sized according to the new pixel spacing) multiplied by the original pixel value to the original pixel center and sum up any overlaps. Try proving both of these give the answer you’re already accustomed to.
This is the most honest signal-processing answer, and it might be a bit challenging to work through but my hope is that it’ll be ultimately doable. I’m sure there’ll be neighboring answers in more elementary terms, but this is ultimately a (two-dimensional) signal processing task and there’s value in knowing exactly what those signal processing people are talking about.
[1] (f∗g)(x) = (g∗f)(x) = ∫f(y)g(x-y)dy is the definition you’re most likely to encounter. Equivalently, (f∗g)(x) is f(y)g(z) integrated over the line (plane, etc.) x=y+z, which sounds a bit more vague but exposes the underlying symmetry more directly. Convolving an image with a box filter gives you, at each point, the average of the original over the box centered around that point.
Dig a little further into the “bilinear filter” and “bicubic filter” that follow the box filter discussion. They are more interesting than the box filter because the contribution of a clipped polygon is not constant across the polygon fragment, unlike the box filter which is constant across each fragment. Integrating non-constant contribution is where Green’s Theorem comes in.
It’s also conceptually useful to understand the equivalence between box filtering with analytic computation and box filtering with multi-sample point sampling. It is the same mathematical convolution in both cases, but it expressed very very differently depending on how you sample & integrate.
If they called it a choice of basis or influence function, it would've been so much clearer.
I would think that conceptually that a basis function is different form a filter function because a basis function is usually about transforming a point in one space to some different space, and basis functions come in a set that’s the size of the dimensionality of the target space. Filters, even if you can think of the function as a sort of basis, aren’t meant for changing spaces or encoding & decoding against a different basis than the signal. Filters transform the signal but keep it in the same space it started from, and the filter is singular and might lose data.
May be better if I just link to what others say about filters than me trying to blabber on https://en.wikipedia.org/wiki/Filter_(signal_processing)
Essentially if you have a polygon function p(x,y) => { 1 if inside the polygon, otherwise 0 }, and a filter function f(x,y) centered at the origin, then you can evaluate the filter at any point x_0,y_0 with the double-integral / total sum of f(x-x_0,y-y_0)*p(x,y).
In this case, the filtering and the sampling of the scene are both wrapped into the operation of intersection of the square with polygons. The filtering and the sampling are happening during rasterization, not before or after.
Keep in mind a pixel is an image sample, which is different from taking one or many point-samples of the scene in order to compute the pixel color.
It can be surprising at first, but when you analytically compute the area of non-overlapping parts of a pixel (i.e., use Box Filtering) you can introduce high frequencies that cause visible aliasing artifacts that will never go away. This is also true if you are using sub-sampling of a pixel, taking point samples and averaging them, no matter how many samples you take.
You can see the aliasing I’m talking about in the example at the top of the article, the 3rd one is the Box Filter - equivalent to computing the area of the polygons within each pixel. Look closely near the center of the circle where all the lines converge, and you can see little artifacts above and below, and to the left and right of the center, artifacts that are not there in the “Bilinear Filter” example on the right.
The Mitchell-Netravali paper[1] correctly describes sampling as a tradeoff space. If you optimize for frequency response (brick wall rejection of aliasing) the impulse response is sinc and you get a lot of ringing. If you optimize for total rejection of aliasing while maintaining positive support, you get something that looks like a Gaussian impulse response, which is very smooth but blurry. And if you optimize for small spatial support and lack of ringing, you get a box filter, which lets some aliasing through.
Which is best, I think, depends on what you're filtering. For natural scenes, you can make an argument that the oblique projection approach of Rocha et al[2] is the optimal point in the tradeoff space. I tried it on text, though, and there were noticeable ringing artifacts; box filtering is definitely better quality to my eyes.
I like to think about antialiasing specific test images. The Siemens star is very sensitive in showing aliasing, but it also makes sense to look at a half-plane and a thin line, as they're more accurate models of real 2D scenes that people care about. It's hard to imagine doing better than a box filter for a half-plane; either you get ringing (which has the additional negative impact of clipping when the half-planes are at the gamut boundary of the display; not something you have to worry about with natural images) or blurriness. In particular, a tent filter is going to be softer but your eye won't pick up the reduction in aliasing, though it is certainly present in the frequency domain.
A thin line is a different story. With a box filter, you get basically a non antialiased line of single pixel thickness, just less alpha, and it's clearly possible to do better; a tent filter is going to look better.
But a thin line is just a linear combination of two half-planes. So if you accept that a box filter is better visual quality than a tent filter for a half-plane, and the other way around for a thin line, then the conclusion is that linear filtering is not the correct path to truly highest quality.
With the exception of thin lines, for most 2D scenes a box filter with antialiasing done in the correct color space is very close to the best quality - maybe the midwit meme applies, and it does make sense to model a pixel as a little square in that case. But I am interested in the question of how to truly achieve the best quality, and I don't think we really know the answer yet.
[1] https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/l...
[2] https://www.inf.ufrgs.br/~eslgastal/SBS3/Rocha_Oliveira_Gast...
You are claiming it’s the best possible. Box filter is simply not the best possible, and this fact is well understood and documented.
You can relax your claim to say it’s good enough for what you need, and I won’t disagree with you anymore. Personally, I’m sensitive to visible pixelation, and the Box Filter will always result in some visible pixelation with all 2D vector graphics, so if you really care about high quality rendering, I’m very skeptical that you really want Box filtering as the ideal target. Box filter is a compromise, it’s easier & faster to compute. But it’s not the highest quality. It would be good to understand why that’s the case.
* Edit to further clarify and respond to this:
> With the analytical coverage calculation you can have perfect font/text rendering, perfect thin lines/shapes and, by solving all the areas at once, no conflating artifacts.
You cannot get perfect font or text rendering with a Box filter, and you will get some conflating artifacts. They might be very slight, and not bothersome to most people, but they do exist with a Box filter, always. This is a mathematical property of Box filtering, not a subjective claim.
If you have two non-overlapping shapes of the same color covering the plane and use a box filter on the first shape to sample a pixel on the boundary, and then use the same box filter on the second shape, and then composit them with alpha blending, you get a conflation artifact along the boundary where the background bleeds through.
But if you use the fact that the shapes are non-overlapping and sum their contributions instead, the artifact disappears, while still using the same box filter.
You can see this with a single sharp edge, it doesn’t need to involve multiple polygons, nor even vector rendering, it happens when downsampling images too.
Can we make a magical adaptive filter which resembles box filter for half-planes, a tent filter for thin lines, Mitchell-Netravali or oblique projection for natural images, and Gaussian when filtering images for which high frequency detail is not important? Perhaps, but that feels like advanced research, and also computationally expensive. I don't think you can claim "perfect" without backing it up with human factors data really demonstrating that the filtered images are optimum with respect to perceived quality.
All of this "filtering" is variations on adding blur. In fact the article extends the technique to deliberately blur images on a larger scale. When we integrate a function (which could be a color gradient over a fully filled polygon) and then paint the little square with a solid "average" color that's also a form of blurring (more like distorting in this case) the detail.
It is notable that the examples given are moving, which means moire patterns and other artifacts will have frame-to-frame effects that may be annoying visually. Simply blurring the image takes care of that at the expense of eliminating what looks like detail but may not actually be meaningful. Some of the less blurry images seem to have radial lines that bend and go back out in another location for example, so I'd call that false detail. It may actually be better to blur such detail instead of leaving it look sharper with false contours.
Conceptually, what we’re doing is low-pass filtering, rather than blurring, so I wouldn’t necessarily call filtering just “adding blur”, but in some sense those two ideas are very close to each other, so I wouldn’t call it wrong either. :P The render filtering is a convolution integral, and is slightly different than adding blur to an image without taking the pixel shape into account. Here the filter’s quality depends on taking the pixel shape into account.
You’re right about making note of the animated examples - this is because it’s easier to demonstrate aliasing when animated. The ‘false detail’ is also aliasing, and does arise because the filtering didn’t adequately filter out high frequencies, so they’ve been sampled incorrectly and lead to incorrect image reconstruction. I totally agree that if you get such aliasing false detail, it’s preferable to err (slightly) on the side of blurry, rather than sharp and wrong.
All this comes down to the projected pixels not being nearly as square as one might think (maybe that’s on purpose), though do note that squares are not the ideal shape of a pixel in the first place, for the same reason box filtering isn’t the best filter. If your pixel has sharp edges, that causes artifacts.
Take a look at the pixel-close-up comparisons in the projection shoot-out: https://www.projectorcentral.com/Projector-Resolution-Shooto...
Notice how all of them are visibly blurrier than the source image, and even that all of them have visible aliasing.
Also just for fun, check out this interesting video showing what DMD mirrors look like under a microscope: https://youtu.be/KpatWNi0__o
It’s subjective, so box filter being ‘close’ is a somewhat accurate statement. I’m coming from the film world, and so I have a pretty hard time agreeing that it’s “very” close. Box filter breaks often and easily, especially under animation, but it’s certainly better than nearest neighbor sampling, if that’s our baseline. Box filter is pretty bad for nearly any scenario where there are frequencies higher than the pixel spacing, which includes textures, patterns, thin lines, and all kinds of things, and the real world is full of these box-filter-confounding features.
One interesting question to ask is whether you the viewer can reliably identify the size of a pixel anywhere in the image. If you can see any stepping of any kind, the pixel size is visible, and that means the filter is inadequate and cannot achieve “best possible output quality”. Most people are not sensitive to this at all, but I’ve sat through many filter evaluation sessions with film directors and lighting/vfx supervisors who are insanely sensitive to the differences between well tuned and closely matching Mitchell and Gaussian filters, for example. Personally, for various reasons based on past experience, I think it’s better to err slightly on the side of too blurry than too sharp. I’d rather use a Gaussian than bicubic, but the film people don’t necessarily agree and they think Gaussian is too blurry once you eliminate aliasing. Once you find the sharpest Gaussian you can that doesn’t alias, you will not be able to identify the size of a pixel - image features transition from sharp to blurry as you consider smaller scales, but pixel boundaries are not visible. I’ve never personally seen another filter that does this always, even under contrived scenarios.
That said, I still think it’s tautologically true that box filter is simply not the “best” quality, even if we’re talking about very minor differences. Bilinear and Bicubic are always as good or better, even when the lay person can’t see the differences (or when they don’t know what to look for).
My opinion is that there is no such thing as “best” output quality. We are in a tradeoff space, and the optimal result depends on goals that need to be stated explicitly and elaborated carefully. It depends heavily on the specific display, who/what is looking at the display, what the viewer cares about, what the surrounding environment is like, etc., etc..
* edit just to add that even though I don’t think “best” visual quality exists, I do think box filter can never get there, the contention for top spot is between the higher order filters, and box filter isn’t even in the running. I had meant to mention that even a single 2d plane that black on one side and white on the other, when rendered with box filter, yields an edge in which you can identify visible stepping. If you handle gamma & color properly, you can minimize it, but you can still see the pixels, even in this simplest of all cases. For me, that’s one reason box filter is disqualified from any discussion of high quality rendering.
Anti-aliasing is exactly as it sounds, a low-pass filter to prevent artefacts. Convolution with a square pulse is serviceable, but is not actually that good a low-pass filter, you get all kinds of moire effects. This is why a Bicubic kernel that kind of mimics a perfect low-pass filter (which would be a sinc kernel), can perform better.
It is tempting to use a square kernel though, because it's pretty much the sharpest possible method of acceptable quality.
In the given example (periodic checkerboard), that would be impossible because the pixels that touch the horizon intersect an infinite amount of polygons.
Not that TFA solves that problem either. As far as I know the exact rendering of a periodic pattern in perspective is an open problem.
EDIT: yes it is.
(Android 14, Android WebView/Chrome 127)
Viewing the page in either browser was fine for the rest of my machine. But I can imagine that it's a heavy load on some computers.
(However it seems wrong that Android doesn't set up things via eg cgroups or whatever to make sure that the browser can't hog all the resources. You'd want to reserve say 5% of memory and RAM for use by system tasks perhaps? (Reserve in the sense that these system tasks can pre-empt anyone else using these, not that no one else can use these.))
But this one is different. I don't know the underlying mechanisms for the browser and the OS, but it almost feels like a bug.
Analytic integration is always superior to multisampling, assuming the same choice of filter, and as long as the analytic integration is correct. Your comment is making an assumption that the analytic integration is incorrect in the presence of multiple polygons. This isn’t true though, the article is using multiple polygons, though the demo is limited in multiple ways for simplicity, it doesn’t appear to handle any arbitrary situation.
The limitations of the demo (whether it handles overlapping polygons, stitched meshes, textures, etc.) does not have any bearing on the conceptual point that computing the pixel analytically is better than taking multiple point samples. GPUs use multisampling because it’s easy and finite to compute, not because it’s higher quality. Multisampling is lower quality than analytic, but it’s far, far easier to productize, and it’s good enough for most things (especially games).