Getting submesh center in batch
Hello community.
I'm trying to optimize rendering and use batching for a lot of meshes. But there is a shader that uses center of mesh and I need to store it somewhere. I believe that I can just store them in constant buffer, but I'd like to try storing them inside vertices colors.
So I wrote a little script that will set colors for all vertices:
public void ResetVertexColors()
{
var vertices = meshFilter.sharedMesh.vertices;
var colors = meshFilter.sharedMesh.colors;
var squaredLength = 0f;
for (var i = 0; i < vertices.Length; i++)
{
squaredLength += Mathf.Pow(vertices[i].magnitude, 2f);
}
var length = Mathf.Sqrt(squaredLength);
for (var i = 0; i < vertices.Length; i++)
{
vertices[i] = vertices[i] / length * 0.5f + Vector3.one * 0.5f;
colors[i] = new Color(vertices[i].x, vertices[i].y, vertices[i].z, 1f);
}
meshFilter.sharedMesh.SetVertices(vertices.ToList());
meshFilter.sharedMesh.SetColors(colors.ToList());
}
I'm normalizing vertices here, so colors and positions will be in [0, 1] range.
After that I use this vertex shader to be sure that all submesh vertices will have the same center position:
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.color = (v.vertex - v.color) / 10;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
return i.color;
}
I expect to see submeshes filled with one same color, but this is what I actually see: http://take.ms/uVRvG
These two submeshes have different colors on their edges. That means that each vertex "is pointing" on different center point and I can't use my shader properly.
Anyone knows what I'm doing wrong?
Answer by ValakhP · Nov 20, 2017 at 07:37 PM
Alright, I found a problem.
Actually, there were two mistakes:
Transformation of the object on the scene. All scales and rotations should be reseted to default: Vector3.one and Vector3.zero;
Don't change vertices and wrire all positions into colors as they are.
As a result, I have this script for changing colors of vertices:
public void ResetVertexColors()
{
var vertices = meshFilter.sharedMesh.vertices;
var colors = meshFilter.sharedMesh.colors;
for (var i = 0; i < vertices.Length; i++)
{
colors[i] = new Color(vertices[i].x, vertices[i].y, vertices[i].z, 1f);
}
meshFilter.sharedMesh.SetColors(colors.ToList());
}
And everything work fine from this point.
Your answer
Follow this Question
Related Questions
Tiling a noise texture 1:1 over each triangle without creating extra vertices 1 Answer
Vertex Displacement stretched when used in a particle emitter, how can I fix it? 1 Answer
Can I create a mesh from a terrain and get a similar texture quality ? Or this is not possible ? 0 Answers
Get an array or list of points and normals of mesh surface (Not vertecis) 1 Answer
Help with a NURBS / B-Spline / Bezier patch shader. 0 Answers