Make an imported mesh double sided and apply two materials

I have an imported mesh and I would like to make it double sided and put one material on front face and one on the back face. So far I have this:

var backMaterial = new BABYLON.StandardMaterial('backMaterial', scene);
backMaterial.diffuseColor = new BABYLON.Color3(0, 1, 0);
	
var frontMaterial = new BABYLON.StandardMaterial('frontMaterial', scene);
frontMaterial.diffuseColor = new BABYLON.Color3(1, 0, 0);

BABYLON.VertexData._ComputeSides(
	BABYLON.Mesh.DOUBLESIDE,
	scene.meshes[2].getVerticesData(BABYLON.VertexBuffer.PositionKind),
	scene.meshes[2].getIndices(),
	scene.meshes[2].getVerticesData(BABYLON.VertexBuffer.NormalKind),
	scene.meshes[2].getVerticesData(BABYLON.VertexBuffer.UVKind),
	scene.meshes[2].getVerticesData(BABYLON.VertexBuffer.UV2Kind)
	);

var multiMaterial = new BABYLON.MultiMaterial("multiMaterial", scene);
multiMaterial.subMaterials.push(frontMaterial);
multiMaterial.subMaterials.push(backMaterial);

scene.meshes[2].material = multiMaterial;
scene.meshes[2].subMeshes = [];
var verticesCount = scene.meshes[2].getTotalVertices();
var indicesCount = scene.meshes[2].getTotalIndices();

new BABYLON.SubMesh(0, 0, verticesCount, 0, indicesCount / 2, scene.meshes[2]);
new BABYLON.SubMesh(1, 0, verticesCount, indicesCount / 2, 	indicesCount / 2, scene.meshes[2]);

The mesh shows only the front material, the back face is completely transparent & I also get this error:
[.WebGL-000040D806DD8D00] GL_INVALID_OPERATION: Insufficient buffer size.

I’m sure I’m doing something wrong, but can’t work out what. Any help would be great. Thank you.

Would be great if you could provide a repro in the playground ?

Hi @sebavan,

Here’s a PG: Babylon.js Playground

BABYLON.VertexData._ComputeSides(2, … doesnt work in the PG.

I am stuck!

Thank you,

Here is a solution: different material on back face | Babylon.js Playground (babylonjs.com)

2 Likes

Thank you very much! I would rather not admit how long I spent trying to do it myself.

2 Likes

@sebavan @Deltakosh @babbleon

Hey guys!

I have a follow up question here. In the solution PG, the cloned back mesh seems have wrong normals…the surfaces react to lights seems visually reversed. For example, the light source in the scene is from the top. According, the bottom of the inside (green color) should be illuminated right? But in the PG, the top end of the inside is been illuminated. Feels like after setting up the sideOrientation, the normal should be taken care of?

I know there is a way we can use flipFaces(true) on mesh to make the normal flipped. But just wondering is there a better way to make the render look right? For example, flip normals on shaders or other approaches?

This is what I mean:

Hope my question makes sense here.
Many thanks
Tawibox

see this one for a solution Simple solution to flip normals on materials? - #6 by Evgeni_Popov

1 Like