Applying vertex color to custom mesh in standard material

I’m trying to create custom mesh using vertex position and colors, but I always see a black mesh as a result when I use standard material, vertex colors are not working.

Creating and initializing the data for mesh like this

var vertexFormat = new pc.VertexFormat(pc.app.graphicsDevice,
[{
       semantic: pc.SEMANTIC_POSITION,
       components: 3,
       type: pc.ELEMENTTYPE_FLOAT32,
},
{
       semantic: pc.SEMANTIC_COLOR,
       components: 4,
       type: pc.ELEMENTTYPE_FLOAT32,
},
{
       semantic: pc.SEMANTIC_TEXCOORD0,
       components: 2,
       type: pc.ELEMENTTYPE_FLOAT32,
}]);
var vertexData = getAllVerticesData();
var vertexBuffer = new pc.VertexBuffer(pc.app.graphicsDevice, vertexFormat, verticesCount, pc.BUFFER_STATIC);
var vertices = new Float32Array(vertexBuffer.lock());
var vertexArr = [];
for (var i = 0; i < vertexData.length; i = i + 9) {
    vertexArr.push(vertexData[i], vertexData[i + 1], vertexData[i + 2]);   // POSITION
    vertexArr.push(vertexData[i + 3], vertexData[i + 4], vertexData[i + 5], vertexData[i + 6]); // COLOR
    vertexArr.push(vertexData[i + 7], vertexData[i + 8]); // TEX COORDS
}
vertices.set(vertexArr);
vertexBuffer.unlock();

var indexData = getAllIndicesData();
var indexBuffer = new pc.IndexBuffer(pc.app.graphicsDevice, pc.INDEXFORMAT_UINT16, indicesCount);
var indices = new Uint16Array(indexBuffer.lock());
var indexArr = [];
for (j = 0; j < indexData.length; j++) indexArr.push(indexData[j]);
indices.set(indexArr);
indexBuffer.unlock();

Then I create the mesh and assign material like following

var mesh = new pc.Mesh();
mesh.vertexBuffer = vertexBuffer;
mesh.indexBuffer[0] = indexBuffer;
mesh.primitive[0].type = pc.PRIMITIVE_TRIANGLES;
mesh.primitive[0].base = 0;
mesh.primitive[0].count = indexBuffer.getNumIndices();
mesh.primitive[0].indexed = true;

var node = new pc.GraphNode();
var material = new pc.StandardMaterial();
material.diffuseVertexColor = true;
material.update();
var meshInstance = new pc.MeshInstance(node, mesh, material);
var model = new pc.Model();
model.graph = node;
model.meshInstances = [meshInstance];

I get perfect mesh but its always black, vertex colors are not being applied. Any idea what I’m doing wrong.

When I use basic material instead of standard material I can use vertex color by setting true vertexColors property, but when I go back to standard material I always get a black mesh even when I set diffuseVertexColor to true. Standard material is not even changing color on diffuse as well, its just always black.

I’m not entirely sure that is the problem, but standard material might need the mesh to contain normals to work properly.

If that’s the case @PC_Coder you can calculate the normals for your mesh like this:

var normals = pc.calculateNormals(positions, indices);

https://developer.playcanvas.com/en/api/pc.html#calculateNormals

Thanks a lot it worked :slight_smile:

2 Likes