PDA

View Full Version : How can i make far objects look fading or transparent?



esapir
03-14-2014, 08:29 AM
Say i have a 3D rectangle, rotated 45 degrees as in the attached screenshot. I would like the lines and the far edge (A) to look fading. Moreover, when i rotate the camera, i want the 'new' far lines and edges to look fading. So if B will be in the place if A, B and the lines to B will look fading. How can i do that?

If it makes any difference, i use OpenGL ES 2.0 on iOS.

Brokenmind
03-14-2014, 09:09 AM
I'm not familiar with openGL ES but I hope you can use shaders there, because then this will be an easy task:
You simply need to compute the distance between the geometry you draw and the camera, and set the opacity value in the fragment shader according to this distance.

Vertex shader:


#version 330

uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;

out vec3 vertexPosition;
out vec2 textureCoord;

layout(location = 0) in vec3 vVertex;
layout(location = 1) in vec2 vTex;

void main()
{
vertexPosition = vVertex;
textureCoord = vTex;
gl_Position = projectionMatrix * viewMatrix * vec4(vVertex,1);
}


Fragment shader:


#version 330

uniform sampler2D textureSampler;

uniform vec3 cameraPosition;

in vec3 vertexPosition;
in vec2 textureCoord;

out vec4 color;

void main()
{
float distance = length(cameraPosition, vertexPosition);

float opacity = clamp(distance / 1000, 0, 1);

color = texture(textureSampler, textureCoord) * vec4(1.0, 1.0, 1.0, 1.0 - opacity);
}


Untested, but this code should gradually increase transparency until the objects are 1000 (no unit) away. You can of course adapt this if you add non-linear fading or fading that starts only at a minimum distance of 500.

esapir
03-14-2014, 11:58 AM
Great answer!


I'm not familiar with openGL ES but I hope you can use shaders there, because then this will be an easy task:
You simply need to compute the distance between the geometry you draw and the camera, and set the opacity value in the fragment shader according to this distance.

Vertex shader:


#version 330

uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;

out vec3 vertexPosition;
out vec2 textureCoord;

layout(location = 0) in vec3 vVertex;
layout(location = 1) in vec2 vTex;

void main()
{
vertexPosition = vVertex;
textureCoord = vTex;
gl_Position = projectionMatrix * viewMatrix * vec4(vVertex,1);
}


Fragment shader:


#version 330

uniform sampler2D textureSampler;

uniform vec3 cameraPosition;

in vec3 vertexPosition;
in vec2 textureCoord;

out vec4 color;

void main()
{
float distance = length(cameraPosition, vertexPosition);

float opacity = clamp(distance / 1000, 0, 1);

color = texture(textureSampler, textureCoord) * vec4(1.0, 1.0, 1.0, 1.0 - opacity);
}


Untested, but this code should gradually increase transparency until the objects are 1000 (no unit) away. You can of course adapt this if you add non-linear fading or fading that starts only at a minimum distance of 500.