Writ

UE4 Nearest-Neighbor

2021-05-02

This is not affiliated with Epic or Unreal in any way, this is just personal project shenanigans

I wanted to have UE4 filter a texture by nearest-neighbor on-demand. Or at least, to make it the default for a texture on import.

On Import

There doesn’t seem to be an easy way to do it. You could try to write a plugin that post-processes textures and have it set the filtering, but that’s too much work.

On Render

This is what I ended up doing; it’s far worse than actual low-level filtering, since it doesnt use a dedicated samplerstate to return values, but whatever here we are.

closest tex2d

The frac is important here, you might be tempted to use a modulus, but that overlaps for values of both 0 and 1. frac is exactly meant for this case.

The custom loading just uses the HLSL Load for a sampler, we’re still technically using linear sampling, we’re just always getting exactly the middle of whatever uv we’re closest to. It’s terrible and dumb but it works.

A note on compression

While compression is ideally a transparent thing, it doesn’t always end up that way. The default compression in UE 4.26 (among other versions) is DX1/5, which gives incorrect results sometimes. For instance, compare

DX1/5

against BC7

BC7

BC7 is what it’s supposed to look like, that’s what it looks like in blender.

The full list of compression types looks like this; most of them are for fairly specific things, some for backwards compatibility, some for optimizations, but the two defaults (and BC7) are the ones to watch for.

compression

All site content protected by CC-BY-4.0 license