Hey guys, for an optimisation I am baking vertex lighting into a model.
I started with this http://www.unifycommunity.com/wiki/index.php?title=PixelLightMapper but had to modify it a lot. I am very close with directionals and point lights now.
However, I’m having a hard time matching lighting on non uniform scaled objects.
for (int vertexIndex = 0; vertexIndex < sourceMesh.vertexCount; ++vertexIndex )
{
Vector3 worldPosition = sourceTransform.TransformPoint(sourceMesh.vertices[vertexIndex]);
Vector3 worldNormal = sourceTransform.TransformPoint(sourceMesh.normals[vertexIndex] + sourceMesh.vertices[vertexIndex]) - worldPosition;
worldNormal.Normalize();
Color calculatedColor = Color.black;
foreach (Light light in lights)
{
if (light.active)
{
Transform lightTransform = light.transform;
//POINT LIGHT
if (light.type == LightType.Point)
{
Vector3 toLight = lightTransform.position - worldPosition;
float distanceToLight = toLight.magnitude;
toLight *= 1.0f / distanceToLight;
if (light.range > distanceToLight)
{
float angleMod = Mathf.Max(Vector3.Dot(worldNormal, toLight), 0.0f);
float r = Mathf.Clamp01((distanceToLight / light.range));
float attenuationMod = 1.0f / (1.0f + 25.0f * r * r);
calculatedColor += light.color * light.intensity * angleMod * attenuationMod;
}
}
else if (light.type == LightType.Directional)
{
float angleMod = Mathf.Max(Vector3.Dot(worldNormal, -lightTransform.forward), 0.0f);
calculatedColor += light.color * light.intensity * angleMod;
}
}
} //END foreach light
calculatedColor *= tint;
calculatedColor += emissive;
m_colors[vertexIndex] = calculatedColor;
These are the offending lines
Vector3 worldNormal = sourceTransform.TransformPoint(sourceMesh.normals[vertexIndex] + sourceMesh.vertices[vertexIndex]) - worldPosition;
worldNormal.Normalize();
I have tried various combinations and so far failed. How does unity calculate the matrix applied to the normals?
Many thanks
Dan