KSP-Conformal-Decals/Source/ConformalDecals/ProjectionTarget.cs

63 lines
2.7 KiB
C#
Raw Normal View History

2020-05-30 04:02:58 +00:00
using UnityEngine;
using UnityEngine.Rendering;
namespace ConformalDecals {
public class ProjectionTarget {
// Target object data
2020-05-30 20:46:03 +00:00
public readonly Transform target;
2020-05-30 04:02:58 +00:00
private readonly Renderer _targetRenderer;
private readonly Mesh _targetMesh;
private bool _projectionEnabled;
2020-05-30 04:02:58 +00:00
// property block
private readonly MaterialPropertyBlock _decalMPB;
2020-06-06 04:36:14 +00:00
public ProjectionTarget(MeshRenderer targetRenderer, Mesh targetMesh) {
2020-05-30 20:46:03 +00:00
target = targetRenderer.transform;
2020-05-30 04:02:58 +00:00
_targetRenderer = targetRenderer;
_targetMesh = targetMesh;
_decalMPB = new MaterialPropertyBlock();
2020-05-30 04:02:58 +00:00
}
2020-06-08 20:14:25 +00:00
public void Project(Matrix4x4 orthoMatrix, Transform projector, bool useBaseNormal) {
_projectionEnabled = true;
var targetMaterial = _targetRenderer.sharedMaterial;
var projectorToTargetMatrix = target.worldToLocalMatrix * projector.localToWorldMatrix;
2020-05-31 05:44:44 +00:00
var projectionMatrix = orthoMatrix * projectorToTargetMatrix.inverse;
var decalNormal = projectorToTargetMatrix.MultiplyVector(Vector3.back).normalized;
var decalTangent = projectorToTargetMatrix.MultiplyVector(Vector3.right).normalized;
2020-05-31 05:44:44 +00:00
_decalMPB.SetMatrix(DecalPropertyIDs._ProjectionMatrix, projectionMatrix);
_decalMPB.SetVector(DecalPropertyIDs._DecalNormal, decalNormal);
_decalMPB.SetVector(DecalPropertyIDs._DecalTangent, decalTangent);
if (useBaseNormal && targetMaterial.HasProperty(DecalPropertyIDs._BumpMap)) {
_decalMPB.SetTexture(DecalPropertyIDs._BumpMap, targetMaterial.GetTexture(DecalPropertyIDs._BumpMap));
var normalScale = targetMaterial.GetTextureScale(DecalPropertyIDs._BumpMap);
var normalOffset = targetMaterial.GetTextureOffset(DecalPropertyIDs._BumpMap);
_decalMPB.SetVector(DecalPropertyIDs._BumpMap_ST, new Vector4(normalScale.x, normalScale.y, normalOffset.x, normalOffset.y));
}
else {
_decalMPB.SetTexture(DecalPropertyIDs._BumpMap, DecalConfig.BlankNormal);
2020-05-31 05:44:44 +00:00
}
2020-05-30 04:02:58 +00:00
}
public bool Render(Material decalMaterial, MaterialPropertyBlock partMPB, Camera camera) {
2020-05-31 05:44:44 +00:00
if (_projectionEnabled) {
_decalMPB.SetFloat(PropertyIDs._RimFalloff, partMPB.GetFloat(PropertyIDs._RimFalloff));
_decalMPB.SetColor(PropertyIDs._RimColor, partMPB.GetColor(PropertyIDs._RimColor));
Graphics.DrawMesh(_targetMesh, target.localToWorldMatrix, decalMaterial, 0, camera, 0, _decalMPB, ShadowCastingMode.Off, true);
2020-05-30 04:02:58 +00:00
return true;
2020-05-30 04:02:58 +00:00
}
return false;
}
}
}