2D Radial Distortion – Fisheye/Barrel

Screen space shader based on: https://gist.github.com/aggregate1166877/a889083801d67917c26c12a98e7f57a7 Works great for creating fisheye distortion, barrel distortion or spherical mappings of the screen space. To use this shader, it’s recommended that you add it to a ColorRect node or similar, this makes it easy to position or crop the effect.

Shader code
/////////////////////////////////
// 2D Radial Distortion Shader //
/////////////////////////////////

// Screen space shader for Godot, based on: https://gist.github.com/aggregate1166877/a889083801d67917c26c12a98e7f57a7

shader_type canvas_item;

uniform float aspect = 1.0;
uniform float distortion = 1.0;
uniform float radius = 1.0;
uniform float alpha = 1.0;
uniform float crop = 1.0;
uniform vec4 crop_color : hint_color = vec4(0,0,0,1);

vec2 distort(vec2 p)
{
	float d = length(p);
	float z = sqrt(distortion + d * d * -distortion);
	float r = atan(d, z) / 3.1415926535;
	float phi = atan(p.y, p.x);
	return vec2(r * cos(phi) * (1.0 / aspect) + 0.5, r * sin(phi) + 0.5);
}

void fragment()
{
	vec2 xy = (SCREEN_UV * 2.0 - 1.0); // move origin of UV coordinates to center of screen

	xy = vec2(xy.x * aspect, xy.y); // adjust aspect ratio

	float d = length(xy); // distance from center

	vec4 tex;

	if (d < radius)
	{
		xy = distort(xy);
		tex = texture(SCREEN_TEXTURE, xy);
		COLOR = tex;
		COLOR.a = alpha;
	}

	// radial crop
	if (d > crop)
	{
		COLOR = crop_color;
	}
}
Tags
barrel, distortion, fisheye, mapping, radial, spherical
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

Related shaders

Fisheye & Anti fisheye Camera Effect

Five Nights at Freddy’s Style ‘Fisheye’

Scratch fisheye effect

Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Rakun
Rakun
3 years ago
This code has an error on line 35
admin
Admin
3 years ago
Reply to  Rakun

There seems to be a problem when uploading code that can be interpreted as html, e.g. a “less than” followed by a “greater than”. The code in this post has temporarily been fixed so it should be correct now, and I’m working on a fix to not have this happen in other posts. So sorry for this!