Polygons opacity based on distance to camera

Hi blokes,
Is there a way to make a mesh change its alpha (non-uniformly) based on distance to camera?
It’s very easy to achieve for the whole mesh, but I need to make parts further away from the camera more opaque and visa versa.

Cheers!

If you want to change non uniformly parts of a mesh, you could :

  • use a dedicated shader
    or
  • maybe, digest your mesh in a solid particle system, then access its parts as separate entities and set them the right alpha value according to the distance from the camera
2 Likes

Another (better ?) lead : use FacetData and depthSort
https://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort

Once the mesh indices are sorted according to the distance to the camera, then access from the indices array to the colors array and set varying alpha values, knowing that the indices array is now sorted from the furthest facets to the closest ones.

1 Like

Hi @jerome, thanks for the suggestions!
I’m inclined to go with the shader solution as the model is quite complex (hi poly-count) and I don’t think the cpu is up to the task.

I found something that I’ll need to marry with Babylon’s default shader (I don’t want to lose specularity, shading etc):

Vertex shader:

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:

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);
}

can’t wait to see a PG demo :wink:

1 Like

Anyway, I think that, if you’re dealing with a transparent mesh (especially if it’s concave), you might have to use the facetData depth sort to reorder the indices before the draw call in order to avoid some strange rendering when the first facets (polygons) to be drawn will be closer to the camera than the last ones.