Skip to content

Instantly share code, notes, and snippets.

@PARTYMANX
Last active April 21, 2020 03:19
Show Gist options
  • Save PARTYMANX/91768428c5e5902abc0088b89ee2eade to your computer and use it in GitHub Desktop.
Save PARTYMANX/91768428c5e5902abc0088b89ee2eade to your computer and use it in GitHub Desktop.
Biased Bilinear Sampling
// uv is input texture coord, srcRes is original texture resolution, returns filtered texture coords
vec2 filterCoord(vec2 uv, vec2 srcRes) {
vec2 invSrc = 1.0 / srcRes;
// calculate destination resolution
vec2 duv1 = vec2(dFdx(uv.x), dFdy(uv.y));
vec2 duv2 = vec2(dFdy(uv.x), dFdx(uv.y));
vec2 duv = max(abs(duv1), abs(duv2)); // pick the larger derivatives (accounting for sideways sampling)
vec2 dstRes = 1.0 / duv;
vec2 scale = dstRes * invSrc; // (dstRes / invSrc)
vec2 scaleFactor = floor(scale) + 1.0; // add one to integer scale factor so we scale down, not up
vec2 texelCoord = uv * srcRes; // coordinate in texel space
vec2 roundCoord = floor(texelCoord) + 0.5; // center of nearest texel of uv
vec2 fractCoord = fract(texelCoord) - 0.5; // offset from nearest texel
vec2 offset = abs(fractCoord * scaleFactor); // absolute offset multiplied by scale factor
offset -= 0.5 * (scaleFactor - 1.0); // subtract border of scaled texel
offset = max(offset, 0.0) * sign(fractCoord); // get rid of wrong direction offsets, restore sign
return (roundCoord + offset) * invSrc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment