Merge branch 'develop' into feature-text

This commit is contained in:
2020-07-02 20:13:46 -07:00
41 changed files with 1661 additions and 1312 deletions

View File

@ -60,23 +60,25 @@
<Compile Include="DecalConfig.cs" />
<Compile Include="DecalIconFixer.cs" />
<Compile Include="DecalPropertyIDs.cs" />
<Compile Include="MaterialModifiers\MaterialColorProperty.cs" />
<Compile Include="MaterialModifiers\MaterialFloatProperty.cs" />
<Compile Include="MaterialModifiers\MaterialProperty.cs" />
<Compile Include="MaterialModifiers\MaterialPropertyCollection.cs" />
<Compile Include="MaterialModifiers\MaterialTextureProperty.cs" />
<Compile Include="MaterialProperties\MaterialColorProperty.cs" />
<Compile Include="MaterialProperties\MaterialFloatProperty.cs" />
<Compile Include="MaterialProperties\MaterialKeywordProperty.cs" />
<Compile Include="MaterialProperties\MaterialProperty.cs" />
<Compile Include="MaterialProperties\MaterialPropertyCollection.cs" />
<Compile Include="MaterialProperties\MaterialTextureProperty.cs" />
<Compile Include="ModuleConformalFlag.cs" />
<Compile Include="ModuleConformalText.cs" />
<Compile Include="ProjectionTarget.cs" />
<Compile Include="ModuleConformalDecal.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Text\DecalFont.cs" />
<Compile Include="Text\FontLoader.cs" />
<Compile Include="Text\TextRenderer.cs" />
<Compile Include="Text\TextSettings.cs" />
<Compile Include="Test\TestLayers.cs" />
<Compile Include="Util\Logging.cs" />
<Compile Include="Util\OrientedBounds.cs" />
<Compile Include="Util\TextureUtils.cs" />
<Compile Include="Util\ParseUtil.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>

View File

@ -1,14 +1,48 @@
using System.Collections.Generic;
using ConformalDecals.Util;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
namespace ConformalDecals {
public static class DecalConfig {
private static Texture2D _blankNormal;
private static Texture2D _blankNormal;
private static List<string> _shaderBlacklist;
private static int _decalLayer = 31;
private static bool _selectableInFlight;
private struct LegacyShaderEntry {
public string name;
public string[] keywords;
}
private static readonly Dictionary<string, LegacyShaderEntry> LegacyShaderPairs = new Dictionary<string, LegacyShaderEntry>() {
["ConformalDecals/Feature/Bumped"] = new LegacyShaderEntry() {
name = "ConformalDecals/Decal/Standard",
keywords = new[] {"DECAL_BUMPMAP"}
},
["ConformalDecals/Paint/Diffuse"] = new LegacyShaderEntry() {
name = "ConformalDecals/Decal/Standard",
keywords = new string[] { }
},
["ConformalDecals/Paint/Specular"] = new LegacyShaderEntry() {
name = "ConformalDecals/Decal/Standard",
keywords = new[] {"DECAL_SPECMAP"}
},
["ConformalDecals/Paint/DiffuseSDF"] = new LegacyShaderEntry() {
name = "ConformalDecals/Decal/Standard",
keywords = new[] {"DECAL_SDF_ALPHA"}
},
["ConformalDecals/Paint/SpecularSDF"] = new LegacyShaderEntry() {
name = "ConformalDecals/Decal/Standard",
keywords = new[] {"DECAL_SDF_ALPHA", "DECAL_SPECMAP"}
},
};
public static Texture2D BlankNormal => _blankNormal;
public static int DecalLayer => _decalLayer;
public static bool SelectableInFlight => _selectableInFlight;
public static bool IsBlacklisted(Shader shader) {
return IsBlacklisted(shader.name);
}
@ -17,11 +51,26 @@ namespace ConformalDecals {
return _shaderBlacklist.Contains(shaderName);
}
public static bool IsLegacy(string shaderName, out string newShader, out string[] keywords) {
if (LegacyShaderPairs.TryGetValue(shaderName, out var entry)) {
newShader = entry.name;
keywords = entry.keywords;
return true;
}
newShader = null;
keywords = null;
return false;
}
private static void ParseConfig(ConfigNode node) {
foreach (var blacklist in node.GetNodes("SHADERBLACKLIST")) {
foreach (var shaderName in blacklist.GetValuesList("shader")) {
_shaderBlacklist.Add(shaderName);
}
ParseUtil.ParseIntIndirect(ref _decalLayer, node, "decalLayer");
ParseUtil.ParseBoolIndirect(ref _selectableInFlight, node, "selectableInFlight");
}
}
@ -30,7 +79,7 @@ namespace ConformalDecals {
var width = 2;
var height = 2;
var color = new Color32(255, 128, 128, 128);
var colors = new Color32[] { color, color, color, color };
var colors = new[] {color, color, color, color};
var tex = new Texture2D(width, height, TextureFormat.RGBA32, false);
for (var x = 0; x <= width; x++) {
@ -38,11 +87,13 @@ namespace ConformalDecals {
tex.SetPixels32(colors);
}
}
tex.Apply();
return tex;
}
// ReSharper disable once UnusedMember.Global
public static void ModuleManagerPostLoad() {
_shaderBlacklist = new List<string>();
@ -55,6 +106,14 @@ namespace ConformalDecals {
}
}
// setup physics for decals, ignore collision with everything
Physics.IgnoreLayerCollision(_decalLayer, 1, true); // default
Physics.IgnoreLayerCollision(_decalLayer, 17, true); // EVA
Physics.IgnoreLayerCollision(_decalLayer, 19, true); // PhysicalObjects
Physics.IgnoreLayerCollision(_decalLayer, 23, true); // AeroFXIgnore
Physics.IgnoreLayerCollision(_decalLayer, 26, true); // wheelCollidersIgnore
Physics.IgnoreLayerCollision(_decalLayer, 27, true); // wheelColliders
_blankNormal = MakeBlankNormal();
}
}

View File

@ -1,4 +1,5 @@
using UnityEngine;
// ReSharper disable InconsistentNaming
namespace ConformalDecals {
@ -12,5 +13,6 @@ namespace ConformalDecals {
public static readonly int _DecalTangent = Shader.PropertyToID("_DecalTangent");
public static readonly int _EdgeWearStrength = Shader.PropertyToID("_EdgeWearStrength");
public static readonly int _ProjectionMatrix = Shader.PropertyToID("_ProjectionMatrix");
public static readonly int _ZWrite = Shader.PropertyToID("_ZWrite");
}
}

View File

@ -1,79 +0,0 @@
using System;
using UnityEngine;
namespace ConformalDecals.MaterialModifiers {
public abstract class MaterialProperty : ScriptableObject {
public string PropertyName {
get => _propertyName;
set {
_propertyName = value;
_propertyID = Shader.PropertyToID(_propertyName);
}
}
[SerializeField] protected int _propertyID;
[SerializeField] protected string _propertyName;
public virtual void ParseNode(ConfigNode node) {
if (node == null) throw new ArgumentNullException(nameof(node));
PropertyName = node.GetValue("name");
Debug.Log($"Parsing material property {_propertyName}");
}
public abstract void Modify(Material material);
private delegate bool TryParseDelegate<T>(string valueString, out T value);
protected bool ParsePropertyBool(ConfigNode node, string valueName, bool isOptional = false, bool defaultValue = false) {
return ParsePropertyValue(node, valueName, bool.TryParse, isOptional, defaultValue);
}
protected float ParsePropertyFloat(ConfigNode node, string valueName, bool isOptional = false, float defaultValue = 0.0f) {
return ParsePropertyValue(node, valueName, float.TryParse, isOptional, defaultValue);
}
protected int ParsePropertyInt(ConfigNode node, string valueName, bool isOptional = false, int defaultValue = 0) {
return ParsePropertyValue(node, valueName, int.TryParse, isOptional, defaultValue);
}
protected Color ParsePropertyColor(ConfigNode node, string valueName, bool isOptional = false, Color defaultValue = default) {
return ParsePropertyValue(node, valueName, ParseExtensions.TryParseColor, isOptional, defaultValue);
}
protected Rect ParsePropertyRect(ConfigNode node, string valueName, bool isOptional = false, Rect defaultValue = default) {
return ParsePropertyValue(node, valueName, ParseExtensions.TryParseRect, isOptional, defaultValue);
}
protected Vector2 ParsePropertyVector2(ConfigNode node, string valueName, bool isOptional = false, Vector2 defaultValue = default) {
return ParsePropertyValue(node, valueName, ParseExtensions.TryParseVector2, isOptional, defaultValue);
}
private T ParsePropertyValue<T>(ConfigNode node, string valueName, TryParseDelegate<T> tryParse, bool isOptional = false, T defaultValue = default) {
string valueString = node.GetValue(valueName);
if (isOptional) {
if (string.IsNullOrEmpty(valueString)) return defaultValue;
}
else {
if (valueString == null)
throw new FormatException($"Missing {typeof(T)} value for {valueName} in property '{PropertyName}'");
if (valueString == string.Empty)
throw new FormatException($"Empty {typeof(T)} value for {valueName} in property '{PropertyName}'");
}
if (tryParse(valueString, out var value)) {
return value;
}
if (isOptional) {
return defaultValue;
}
else {
throw new FormatException($"Improperly formatted {typeof(T)} value for {valueName} in property '{PropertyName}' : '{valueString}");
}
}
}
}

View File

@ -1,18 +1,19 @@
using System;
using ConformalDecals.Util;
using UnityEngine;
namespace ConformalDecals.MaterialModifiers {
namespace ConformalDecals.MaterialProperties {
public class MaterialColorProperty : MaterialProperty {
[SerializeField] public Color color;
[SerializeField] public Color32 color = new Color32(0, 0, 0, byte.MaxValue);
public override void ParseNode(ConfigNode node) {
base.ParseNode(node);
color = ParsePropertyColor(node, "color", true, color);
ParseUtil.ParseColor32Indirect(ref color, node, "color");
}
public override void Modify(Material material) {
if (material == null) throw new ArgumentNullException("material cannot be null");
if (material == null) throw new ArgumentNullException(nameof(material));
material.SetColor(_propertyID, color);
}

View File

@ -1,18 +1,19 @@
using System;
using ConformalDecals.Util;
using UnityEngine;
namespace ConformalDecals.MaterialModifiers {
namespace ConformalDecals.MaterialProperties {
public class MaterialFloatProperty : MaterialProperty {
[SerializeField] public float value;
public override void ParseNode(ConfigNode node) {
base.ParseNode(node);
value = ParsePropertyFloat(node, "value", true, value);
ParseUtil.ParseFloatIndirect(ref value, node, "value");
}
public override void Modify(Material material) {
if (material == null) throw new ArgumentNullException("material cannot be null");
if (material == null) throw new ArgumentNullException(nameof(material));
material.SetFloat(_propertyID, value);
}

View File

@ -0,0 +1,19 @@
using ConformalDecals.Util;
using UnityEngine;
namespace ConformalDecals.MaterialProperties {
public class MaterialKeywordProperty : MaterialProperty {
[SerializeField] public bool value = true;
public override void ParseNode(ConfigNode node) {
base.ParseNode(node);
ParseUtil.ParseBoolIndirect(ref value, node, "value");
}
public override void Modify(Material material) {
if (value) material.EnableKeyword(_propertyName);
else material.DisableKeyword(_propertyName);
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using UnityEngine;
namespace ConformalDecals.MaterialProperties {
public abstract class MaterialProperty : ScriptableObject {
public string PropertyName {
get => _propertyName;
set {
_propertyName = value;
_propertyID = Shader.PropertyToID(_propertyName);
}
}
[SerializeField] protected int _propertyID;
[SerializeField] protected string _propertyName;
public abstract void Modify(Material material);
public virtual void ParseNode(ConfigNode node) {
if (node == null) throw new ArgumentNullException(nameof(node));
PropertyName = node.GetValue("name");
}
public virtual void Remove(Material material) { }
}
}

View File

@ -1,11 +1,12 @@
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using ConformalDecals.Util;
using UniLinq;
using UnityEngine;
using UnityEngine.Rendering;
namespace ConformalDecals.MaterialModifiers {
namespace ConformalDecals.MaterialProperties {
public class MaterialPropertyCollection : ScriptableObject, ISerializationCallbackReceiver {
public int RenderQueue {
get => _renderQueue;
@ -29,12 +30,20 @@ namespace ConformalDecals.MaterialModifiers {
public Shader DecalShader => _shader;
public IEnumerable<Material> Materials {
get {
yield return PreviewMaterial;
yield return DecalMaterial;
}
}
public Material DecalMaterial {
get {
if (_decalMaterial == null) {
_decalMaterial = new Material(_shader);
_decalMaterial.SetInt(DecalPropertyIDs._Cull, (int) CullMode.Off);
_decalMaterial.SetInt(DecalPropertyIDs._ZWrite, 0);
_decalMaterial.renderQueue = RenderQueue;
}
@ -49,6 +58,7 @@ namespace ConformalDecals.MaterialModifiers {
_previewMaterial.EnableKeyword("DECAL_PREVIEW");
_previewMaterial.SetInt(DecalPropertyIDs._Cull, (int) CullMode.Back);
_previewMaterial.SetInt(DecalPropertyIDs._ZWrite, 1);
}
return _previewMaterial;
@ -68,7 +78,6 @@ namespace ConformalDecals.MaterialModifiers {
public float AspectRatio => MainTexture == null ? 1 : MainTexture.AspectRatio;
public void OnBeforeSerialize() {
Debug.Log($"Serializing MaterialPropertyCollection {this.GetInstanceID()}");
if (_materialProperties == null) throw new SerializationException("Tried to serialize an uninitialized MaterialPropertyCollection");
_serializedNames = _materialProperties.Keys.ToArray();
@ -76,7 +85,6 @@ namespace ConformalDecals.MaterialModifiers {
}
public void OnAfterDeserialize() {
Debug.Log($"Deserializing MaterialPropertyCollection {this.GetInstanceID()}");
if (_serializedNames == null) throw new SerializationException("ID array is null");
if (_serializedProperties == null) throw new SerializationException("Property array is null");
if (_serializedProperties.Length != _serializedNames.Length) throw new SerializationException("Material property arrays are different lengths.");
@ -94,7 +102,6 @@ namespace ConformalDecals.MaterialModifiers {
}
public void Awake() {
Debug.Log($"MaterialPropertyCollection {this.GetInstanceID()} onAwake");
_materialProperties ??= new Dictionary<string, MaterialProperty>();
}
@ -144,6 +151,20 @@ namespace ConformalDecals.MaterialModifiers {
}
}
public bool RemoveProperty(string propertyName) {
if (_materialProperties.TryGetValue(propertyName, out var property)) {
foreach (var material in Materials) {
property.Remove(material);
}
_materialProperties.Remove(propertyName);
Destroy(property);
return true;
}
return false;
}
public MaterialTextureProperty AddTextureProperty(string propertyName, bool isMain = false) {
var newProperty = AddProperty<MaterialTextureProperty>(propertyName);
if (isMain) _mainTexture = newProperty;
@ -163,8 +184,10 @@ namespace ConformalDecals.MaterialModifiers {
}
public T ParseProperty<T>(ConfigNode node) where T : MaterialProperty {
var propertyName = node.GetValue("name");
if (string.IsNullOrEmpty(propertyName)) throw new ArgumentException("node has no name");
string propertyName = "";
if (!ParseUtil.ParseStringIndirect(ref propertyName, node, "name")) throw new ArgumentException("node has no name");
if (ParseUtil.ParseBool(node, "remove", true)) RemoveProperty(propertyName);
var newProperty = AddOrGetProperty<T>(propertyName);
newProperty.ParseNode(node);
@ -180,13 +203,22 @@ namespace ConformalDecals.MaterialModifiers {
if (string.IsNullOrEmpty(shaderName)) {
if (_shader == null) {
Debug.Log("Using default decal shader");
shaderName = "ConformalDecals/Paint/Diffuse";
shaderName = "ConformalDecals/Decal/Standard";
}
else {
return;
}
}
if (DecalConfig.IsLegacy(shaderName, out var newShader, out var keywords)) {
Debug.LogWarning($"[ConformalDecals] Part is using shader {shaderName}, which has been replaced by {newShader}.");
shaderName = newShader;
foreach (var keyword in keywords) {
var newProperty = AddOrGetProperty<MaterialKeywordProperty>(keyword);
newProperty.value = true;
}
}
var shader = Shabby.Shabby.FindShader(shaderName);
if (shader == null) throw new FormatException($"Unable to find specified shader '{shaderName}'");
@ -208,8 +240,6 @@ namespace ConformalDecals.MaterialModifiers {
if (_mainTexture == null) throw new InvalidOperationException("UpdateTile called but no main texture is specified!");
var mainTexSize = _mainTexture.Dimensions;
Debug.Log($"Main texture is {_mainTexture.PropertyName} and its size is {mainTexSize}");
foreach (var entry in _materialProperties) {
if (entry.Value is MaterialTextureProperty textureProperty && textureProperty.autoTile) {
textureProperty.SetTile(tile, mainTexSize);
@ -243,8 +273,9 @@ namespace ConformalDecals.MaterialModifiers {
}
public void UpdateMaterials() {
UpdateMaterial(DecalMaterial);
UpdateMaterial(PreviewMaterial);
foreach (var material in Materials) {
UpdateMaterial(material);
}
}
public void UpdateMaterial(Material material) {

View File

@ -1,7 +1,8 @@
using System;
using ConformalDecals.Util;
using UnityEngine;
namespace ConformalDecals.MaterialModifiers {
namespace ConformalDecals.MaterialProperties {
public class MaterialTextureProperty : MaterialProperty {
[SerializeField] public bool isNormal;
[SerializeField] public bool isMain;
@ -9,7 +10,7 @@ namespace ConformalDecals.MaterialModifiers {
[SerializeField] public bool autoTile;
[SerializeField] private string _textureUrl;
[SerializeField] private Texture2D _texture;
[SerializeField] private Texture2D _texture = Texture2D.whiteTexture;
[SerializeField] private bool _hasTile;
[SerializeField] private Rect _tileRect;
@ -45,24 +46,17 @@ namespace ConformalDecals.MaterialModifiers {
public override void ParseNode(ConfigNode node) {
base.ParseNode(node);
isNormal = ParsePropertyBool(node, "isNormalMap", true, (PropertyName == "_BumpMap") || (PropertyName == "_DecalBumpMap") || isNormal);
isMain = ParsePropertyBool(node, "isMain", true, isMain);
autoScale = ParsePropertyBool(node, "autoScale", true, autoScale);
autoTile = ParsePropertyBool(node, "autoTile", true, autoTile);
ParseUtil.ParseBoolIndirect(ref isMain, node, "isMain");
ParseUtil.ParseBoolIndirect(ref isNormal, node, "isNormalMap");
ParseUtil.ParseBoolIndirect(ref autoScale, node, "autoScale");
ParseUtil.ParseBoolIndirect(ref autoTile, node, "autoTile");
var textureUrl = node.GetValue("textureUrl");
if (string.IsNullOrEmpty(textureUrl)) {
if (string.IsNullOrEmpty(_textureUrl)) {
TextureUrl = "";
}
}
else {
TextureUrl = node.GetValue("textureUrl");
if (!autoTile) {
ParseUtil.ParseRectIndirect(ref _tileRect, node, "tile");
}
if (node.HasValue("tile") && !autoTile) {
SetTile(ParsePropertyRect(node, "tile", true, _tileRect));
if (ParseUtil.ParseStringIndirect(ref _textureUrl, node, "textureUrl")) {
_texture = LoadTexture(_textureUrl, isNormal);
}
}
@ -76,6 +70,14 @@ namespace ConformalDecals.MaterialModifiers {
material.SetTexture(_propertyID, _texture);
material.SetTextureOffset(_propertyID, _textureOffset);
material.SetTextureScale(_propertyID, _textureScale * _scale);
if (_propertyName != "_Decal") material.EnableKeyword("DECAL" + _propertyName.ToUpper());
}
public override void Remove(Material material) {
if (material == null) throw new ArgumentNullException(nameof(material));
base.Remove(material);
if (_propertyName != "_Decal") material.DisableKeyword("DECAL" + _propertyName.ToUpper());
}
public void SetScale(Vector2 scale) {

View File

@ -1,11 +1,13 @@
using System;
using System.Collections.Generic;
using ConformalDecals.MaterialModifiers;
using System.Diagnostics.CodeAnalysis;
using ConformalDecals.MaterialProperties;
using ConformalDecals.Util;
using UnityEngine;
namespace ConformalDecals {
public class ModuleConformalDecal : PartModule {
[SuppressMessage("ReSharper", "InconsistentNaming")]
public enum DecalScaleMode {
HEIGHT,
WIDTH,
@ -17,43 +19,21 @@ namespace ConformalDecals {
// CONFIGURABLE VALUES
/// <summary>
/// Shader name. Should be one that supports decal projection.
/// </summary>
[KSPField] public string shader = "ConformalDecals/Paint/Diffuse";
[KSPField] public string shader = "ConformalDecals/Decal/Standard";
/// <summary>
/// Decal front transform name. Required
/// </summary>
[KSPField] public string decalFront = "Decal-Front";
/// <summary>
/// Decal back transform name. Required if <see cref="updateBackScale"/> is true.
/// </summary>
[KSPField] public string decalBack = "Decal-Back";
/// <summary>
/// Decal model transform name. Is rescaled to preview the decal scale when unattached.
/// </summary>
/// <remarks>
/// If unspecified, the decal front transform is used instead.
/// </remarks>
[KSPField] public string decalModel = "Decal-Model";
/// <summary>
/// Decal projector transform name. The decal will project along the +Z axis of this transform.
/// </summary>
/// <remarks>
/// if unspecified, the part "model" transform will be used instead.
/// </remarks>
[KSPField] public string decalFront = "Decal-Front";
[KSPField] public string decalBack = "Decal-Back";
[KSPField] public string decalModel = "Decal-Model";
[KSPField] public string decalProjector = "Decal-Projector";
[KSPField] public string decalCollider = "Decal-Collider";
// Parameters
[KSPField] public bool scaleAdjustable = true;
[KSPField] public float defaultScale = 1;
[KSPField] public Vector2 scaleRange = new Vector2(0, 4);
[KSPField] public DecalScaleMode scaleMode = DecalScaleMode.HEIGHT;
[KSPField] public bool scaleAdjustable = true;
[KSPField] public float defaultScale = 1;
[KSPField] public Vector2 scaleRange = new Vector2(0, 4);
[KSPField] public DecalScaleMode scaleMode = DecalScaleMode.HEIGHT;
[KSPField] public bool depthAdjustable = true;
[KSPField] public float defaultDepth = 0.1f;
@ -75,56 +55,40 @@ namespace ConformalDecals {
[KSPField] public Vector2 tileSize;
[KSPField] public int tileIndex = -1;
/// <summary>
/// Should the back material scale be updated automatically?
/// </summary>
[KSPField] public bool updateBackScale = true;
[KSPField] public bool selectableInFlight;
// INTERNAL VALUES
/// <summary>
/// Decal scale factor, in meters.
/// </summary>
[KSPField(guiName = "#LOC_ConformalDecals_gui-scale", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"),
UI_FloatRange(stepIncrement = 0.05f)]
public float scale = 1.0f;
/// <summary>
/// Projection depth value for the decal projector, in meters.
/// </summary>
[KSPField(guiName = "#LOC_ConformalDecals_gui-depth", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"),
UI_FloatRange(stepIncrement = 0.02f)]
public float depth = 0.2f;
/// <summary>
/// Opacity value for the decal shader.
/// </summary>
[KSPField(guiName = "#LOC_ConformalDecals_gui-opacity", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "P0"),
UI_FloatRange(stepIncrement = 0.05f)]
public float opacity = 1.0f;
/// <summary>
/// Alpha cutoff value for the decal shader.
/// </summary>
[KSPField(guiName = "#LOC_ConformalDecals_gui-cutoff", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "P0"),
UI_FloatRange(stepIncrement = 0.05f)]
public float cutoff = 0.5f;
/// <summary>
/// Edge wear value for the decal shader. Only relevent when useBaseNormal is true and the shader is a paint shader
/// </summary>
[KSPField(guiName = "#LOC_ConformalDecals_gui-wear", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F0"),
UI_FloatRange()]
public float wear = 100;
[KSPField(isPersistant = true)] public bool projectMultiple; // reserved for future features. do not modify
[KSPField] public MaterialPropertyCollection materialProperties;
[KSPField] public Transform decalFrontTransform;
[KSPField] public Transform decalBackTransform;
[KSPField] public Transform decalModelTransform;
[KSPField] public Transform decalProjectorTransform;
[KSPField] public Transform decalColliderTransform;
[KSPField] public Material backMaterial;
[KSPField] public Vector2 backTextureBaseScale;
@ -137,10 +101,10 @@ namespace ConformalDecals {
private bool _isAttached;
private Matrix4x4 _orthoMatrix;
private Material _decalMaterial;
private Material _previewMaterial;
private BoxCollider _boundsCollider;
private Material _decalMaterial;
private Material _previewMaterial;
private MeshRenderer _boundsRenderer;
private int DecalQueue {
get {
_decalQueueCounter++;
@ -166,48 +130,25 @@ namespace ConformalDecals {
/// <inheritdoc />
public override void OnLoad(ConfigNode node) {
this.Log("Loading module");
try {
// SETUP TRANSFORMS
// find front transform
decalFrontTransform = part.FindModelTransform(decalFront);
if (decalFrontTransform == null) throw new FormatException($"Could not find decalFront transform: '{decalFront}'.");
// find back transform
if (string.IsNullOrEmpty(decalBack)) {
if (updateBackScale) {
this.LogWarning("updateBackScale is true but has no specified decalBack transform!");
this.LogWarning("Setting updateBackScale to false.");
updateBackScale = false;
}
}
else {
decalBackTransform = part.FindModelTransform(decalBack);
if (decalBackTransform == null) throw new FormatException($"Could not find decalBack transform: '{decalBack}'.");
}
decalBackTransform = part.FindModelTransform(decalBack);
if (decalBackTransform == null) throw new FormatException($"Could not find decalBack transform: '{decalBack}'.");
// find model transform
if (string.IsNullOrEmpty(decalModel)) {
decalModelTransform = decalFrontTransform;
}
else {
decalModelTransform = part.FindModelTransform(decalModel);
if (decalModelTransform == null) throw new FormatException($"Could not find decalModel transform: '{decalModel}'.");
}
decalModelTransform = part.FindModelTransform(decalModel);
if (decalModelTransform == null) throw new FormatException($"Could not find decalModel transform: '{decalModel}'.");
// find projector transform
if (string.IsNullOrEmpty(decalProjector)) {
decalProjectorTransform = part.transform;
}
else {
decalProjectorTransform = part.FindModelTransform(decalProjector);
if (decalProjectorTransform == null) throw new FormatException($"Could not find decalProjector transform: '{decalProjector}'.");
}
decalProjectorTransform = part.FindModelTransform(decalProjector);
if (decalProjectorTransform == null) throw new FormatException($"Could not find decalProjector transform: '{decalProjector}'.");
// get back material if necessary
decalColliderTransform = part.FindModelTransform(decalCollider);
if (decalColliderTransform == null) throw new FormatException($"Could not find decalCollider transform: '{decalCollider}'.");
// SETUP BACK MATERIAL
if (updateBackScale) {
this.Log("Getting material and base scale for back material");
var backRenderer = decalBackTransform.GetComponent<MeshRenderer>();
if (backRenderer == null) {
this.LogError($"Specified decalBack transform {decalBack} has no renderer attached! Setting updateBackScale to false.");
@ -229,6 +170,12 @@ namespace ConformalDecals {
// set shader
materialProperties.SetShader(shader);
materialProperties.AddOrGetProperty<MaterialKeywordProperty>("DECAL_BASE_NORMAL").value = useBaseNormal;
// add keyword nodes
foreach (var keywordNode in node.GetNodes("KEYWORD")) {
materialProperties.ParseProperty<MaterialKeywordProperty>(keywordNode);
}
// add texture nodes
foreach (var textureNode in node.GetNodes("TEXTURE")) {
@ -247,7 +194,6 @@ namespace ConformalDecals {
// handle texture tiling parameters
var tileString = node.GetValue("tile");
this.Log(tileString);
if (!string.IsNullOrEmpty(tileString)) {
var tileValid = ParseExtensions.TryParseRect(tileString, out tileRect);
if (!tileValid) throw new FormatException($"Invalid rect value for tile '{tileString}'");
@ -259,9 +205,6 @@ namespace ConformalDecals {
else if (tileIndex >= 0) {
materialProperties.UpdateTile(tileIndex, tileSize);
}
// QUEUE PART FOR ICON FIXING IN VAB
DecalIconFixer.QueuePart(part.name);
}
catch (Exception e) {
this.LogException("Exception parsing partmodule", e);
@ -269,6 +212,10 @@ namespace ConformalDecals {
UpdateMaterials();
foreach (var keyword in _decalMaterial.shaderKeywords) {
this.Log($"keyword: {keyword}");
}
if (HighLogic.LoadedSceneIsEditor) {
UpdateTweakables();
}
@ -282,6 +229,9 @@ namespace ConformalDecals {
opacity = defaultOpacity;
cutoff = defaultCutoff;
wear = defaultWear;
// QUEUE PART FOR ICON FIXING IN VAB
DecalIconFixer.QueuePart(part.name);
}
}
@ -292,7 +242,11 @@ namespace ConformalDecals {
/// <inheritdoc />
public override void OnStart(StartState state) {
this.Log("Starting module");
materialProperties.RenderQueue = DecalQueue;
_boundsRenderer = decalProjectorTransform.GetComponent<MeshRenderer>();
UpdateMaterials();
// handle tweakables
if (HighLogic.LoadedSceneIsEditor) {
@ -301,13 +255,10 @@ namespace ConformalDecals {
UpdateTweakables();
}
}
materialProperties.RenderQueue = DecalQueue;
_boundsCollider = decalProjectorTransform.GetComponent<BoxCollider>();
UpdateMaterials();
public override void OnStartFinished(StartState state) {
// handle game events
if (HighLogic.LoadedSceneIsGame) {
// set initial attachment state
if (part.parent == null) {
@ -317,12 +268,33 @@ namespace ConformalDecals {
OnAttach();
}
}
// handle flight events
if (HighLogic.LoadedSceneIsFlight) {
GameEvents.onPartWillDie.Add(OnPartWillDie);
if (part.parent == null) part.explode();
Part.layerMask |= 1 << DecalConfig.DecalLayer;
decalColliderTransform.gameObject.layer = DecalConfig.DecalLayer;
if (!selectableInFlight || !DecalConfig.SelectableInFlight) {
decalColliderTransform.GetComponent<Collider>().enabled = false;
_boundsRenderer.enabled = false;
}
}
}
public virtual void OnDestroy() {
// remove GameEvents
GameEvents.onEditorPartEvent.Remove(OnEditorEvent);
GameEvents.onVariantApplied.Remove(OnVariantApplied);
if (HighLogic.LoadedSceneIsEditor) {
GameEvents.onEditorPartEvent.Remove(OnEditorEvent);
GameEvents.onVariantApplied.Remove(OnVariantApplied);
}
if (HighLogic.LoadedSceneIsFlight) {
GameEvents.onPartWillDie.Remove(OnPartWillDie);
}
// remove from preCull delegate
Camera.onPreCull -= Render;
@ -381,6 +353,13 @@ namespace ConformalDecals {
}
}
protected void OnPartWillDie(Part willDie) {
if (willDie == part.parent) {
this.Log("Parent part about to be destroyed! Killing decal part.");
part.Die();
}
}
protected void OnAttach() {
if (part.parent == null) {
this.LogError("Attach function called but part has no parent!");
@ -390,8 +369,6 @@ namespace ConformalDecals {
_isAttached = true;
this.Log($"Decal attached to {part.parent.partName}");
// hide model
decalModelTransform.gameObject.SetActive(false);
@ -423,16 +400,18 @@ namespace ConformalDecals {
}
protected void UpdateScale() {
scale = Mathf.Max(0.01f, scale);
depth = Mathf.Max(0.01f, depth);
var aspectRatio = materialProperties.AspectRatio;
Vector2 size;
switch (scaleMode) {
default:
case DecalScaleMode.HEIGHT:
size = new Vector2(scale, scale * aspectRatio);
size = new Vector2(scale / aspectRatio, scale);
break;
case DecalScaleMode.WIDTH:
size = new Vector2(scale / aspectRatio, scale);
size = new Vector2(scale, scale * aspectRatio);
break;
case DecalScaleMode.AVERAGE:
var width1 = 2 * scale / (1 + aspectRatio);
@ -463,7 +442,7 @@ namespace ConformalDecals {
// update projection
foreach (var target in _targets) {
target.Project(_orthoMatrix, decalProjectorTransform, _boundsCollider.bounds, useBaseNormal);
target.Project(_orthoMatrix, decalProjectorTransform, _boundsRenderer.bounds, useBaseNormal);
}
}
else {
@ -597,7 +576,7 @@ namespace ConformalDecals {
public void Render(Camera camera) {
if (!_isAttached) return;
// render on each target object
foreach (var target in _targets) {
target.Render(_decalMaterial, part.mpb, camera);

View File

@ -32,7 +32,7 @@ namespace ConformalDecals {
}
}
materialProperties.AddOrGetTextureProperty("_Decal", true).Texture = TextRenderer.RenderToTexture(fonts[0], newText);
//materialProperties.AddOrGetTextureProperty("_Decal", true).Texture = TextRenderer.RenderToTexture(fonts[0], newText);
UpdateMaterials();
}

View File

@ -0,0 +1,34 @@
using System;
using UnityEngine;
namespace ConformalDecals.Test {
public class TestLayers : PartModule {
[KSPField(guiActive = true)]
public int layer = 2;
public override void OnStart(StartState state) {
base.OnStart(state);
Part.layerMask.value |= (1 << 3);
}
public void Update() {
foreach (var collider in GameObject.FindObjectsOfType<Collider>()) {
if (collider.gameObject.layer == 3) {
Debug.Log($"Has layer 3: {collider.gameObject.name}");
}
}
}
[KSPEvent(guiActive = true, guiActiveEditor = true, guiName = "switch layers")]
public void Switch() {
Debug.Log(Part.layerMask.value);
var cube = part.FindModelTransform("test");
layer = (layer + 1) % 32;
cube.gameObject.layer = layer;
}
}
}

View File

@ -64,49 +64,5 @@ namespace ConformalDecals.Text {
_blitMaterial = new Material(Shabby.Shabby.FindShader(BlitShader));
}
public Texture2D RenderToTexture(Texture2D texture2D, TMP_FontAsset font, string text, float fontSize, float pixelDensity) {
// generate text mesh
_tmp.SetText(text);
_tmp.font = font;
_tmp.fontSize = fontSize;
_tmp.ForceMeshUpdate();
// calculate camera and texture size
var mesh = _tmp.mesh;
var bounds = mesh.bounds;
var width = Mathf.NextPowerOfTwo((int) (bounds.size.x * pixelDensity));
var height = Mathf.NextPowerOfTwo((int) (bounds.size.y * pixelDensity));
_camera.orthographicSize = height / pixelDensity / 2;
_camera.aspect = (float) width / height;
_cameraObject.transform.localPosition = new Vector3(bounds.center.x, bounds.center.y, -1);
width = Mathf.Min(width, MaxTextureSize);
height = Mathf.Max(height, MaxTextureSize);
// setup render texture
var renderTex = RenderTexture.GetTemporary(width, height, 0, TextRenderTextureFormat, RenderTextureReadWrite.Linear, 1);
_camera.targetTexture = renderTex;
// setup material
_blitMaterial.SetTexture(PropertyIDs._MainTex, font.atlas);
_blitMaterial.SetPass(0);
// draw the mesh
Graphics.DrawMeshNow(mesh, _tmp.renderer.localToWorldMatrix);
var request = AsyncGPUReadback.Request(renderTex, 0, TextTextureFormat);
request.WaitForCompletion();
if (request.hasError) {
throw new Exception("[ConformalDecals] Error encountered trying to request render texture data from the GPU!");
}
}
}
}

View File

@ -0,0 +1,216 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
namespace ConformalDecals.Util {
public static class ParseUtil {
private static readonly Dictionary<string, Color> NamedColors = new Dictionary<string, Color>();
private static readonly char[] Separator = {',', ' ', '\t'};
public delegate bool TryParseDelegate<T>(string valueString, out T value);
static ParseUtil() {
// setup named colors
foreach (var propertyInfo in typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.Public)) {
if (!propertyInfo.CanRead) continue;
if (propertyInfo.PropertyType != typeof(Color)) continue;
NamedColors.Add(propertyInfo.Name, (Color) propertyInfo.GetValue(null, null));
}
foreach (var propertyInfo in typeof(XKCDColors).GetProperties(BindingFlags.Static | BindingFlags.Public)) {
if (!propertyInfo.CanRead) continue;
if (propertyInfo.PropertyType != typeof(Color)) continue;
if (NamedColors.ContainsKey(propertyInfo.Name)) throw new Exception("duplicate key " + propertyInfo.Name);
NamedColors.Add(propertyInfo.Name, (Color) propertyInfo.GetValue(null, null));
}
}
public static string ParseString(ConfigNode node, string valueName, bool isOptional = false, string defaultValue = "") {
if (!node.HasValue(valueName)) throw new FormatException($"Missing value for {valueName}");
return node.GetValue(valueName);
}
public static bool ParseStringIndirect(ref string value, ConfigNode node, string valueName) {
if (node.HasValue(valueName)) {
value = node.GetValue(valueName);
return true;
}
return false;
}
public static bool ParseBool(ConfigNode node, string valueName, bool isOptional = false, bool defaultValue = false) {
return ParseValue(node, valueName, bool.TryParse, isOptional, defaultValue);
}
public static bool ParseBoolIndirect(ref bool value, ConfigNode node, string valueName) {
return ParseValueIndirect(ref value, node, valueName, bool.TryParse);
}
public static float ParseFloat(ConfigNode node, string valueName, bool isOptional = false, float defaultValue = 0.0f) {
return ParseValue(node, valueName, float.TryParse, isOptional, defaultValue);
}
public static bool ParseFloatIndirect(ref float value, ConfigNode node, string valueName) {
return ParseValueIndirect(ref value, node, valueName, float.TryParse);
}
public static int ParseInt(ConfigNode node, string valueName, bool isOptional = false, int defaultValue = 0) {
return ParseValue(node, valueName, int.TryParse, isOptional, defaultValue);
}
public static bool ParseIntIndirect(ref int value, ConfigNode node, string valueName) {
return ParseValueIndirect(ref value, node, valueName, int.TryParse);
}
public static Color32 ParseColor32(ConfigNode node, string valueName, bool isOptional = false, Color32 defaultValue = default) {
return ParseValue(node, valueName, TryParseColor32, isOptional, defaultValue);
}
public static bool ParseColor32Indirect(ref Color32 value, ConfigNode node, string valueName) {
return ParseValueIndirect(ref value, node, valueName, TryParseColor32);
}
public static Rect ParseRect(ConfigNode node, string valueName, bool isOptional = false, Rect defaultValue = default) {
return ParseValue(node, valueName, ParseExtensions.TryParseRect, isOptional, defaultValue);
}
public static bool ParseRectIndirect(ref Rect value, ConfigNode node, string valueName) {
return ParseValueIndirect(ref value, node, valueName, ParseExtensions.TryParseRect);
}
public static Vector2 ParseVector2(ConfigNode node, string valueName, bool isOptional = false, Vector2 defaultValue = default) {
return ParseValue(node, valueName, ParseExtensions.TryParseVector2, isOptional, defaultValue);
}
public static bool ParseVector2Indirect(ref Vector2 value, ConfigNode node, string valueName) {
return ParseValueIndirect(ref value, node, valueName, ParseExtensions.TryParseVector2);
}
public static Vector3 ParseVector3(ConfigNode node, string valueName, bool isOptional = false, Vector3 defaultValue = default) {
return ParseValue(node, valueName, ParseExtensions.TryParseVector3, isOptional, defaultValue);
}
public static bool ParseVector3Indirect(ref Vector3 value, ConfigNode node, string valueName) {
return ParseValueIndirect(ref value, node, valueName, ParseExtensions.TryParseVector3);
}
public static T ParseValue<T>(ConfigNode node, string valueName, TryParseDelegate<T> tryParse, bool isOptional = false, T defaultValue = default) {
string valueString = node.GetValue(valueName);
if (isOptional) {
if (string.IsNullOrEmpty(valueString)) return defaultValue;
}
else {
if (valueString == null)
throw new FormatException($"Missing {typeof(T)} value for {valueName}");
if (valueString == string.Empty)
throw new FormatException($"Empty {typeof(T)} value for {valueName}");
}
if (tryParse(valueString, out var value)) {
return value;
}
if (isOptional) {
return defaultValue;
}
else {
throw new FormatException($"Improperly formatted {typeof(T)} value for {valueName} : '{valueString}");
}
}
public static bool ParseValueIndirect<T>(ref T value, ConfigNode node, string valueName, TryParseDelegate<T> tryParse) {
if (!node.HasValue(valueName)) return false;
var valueString = node.GetValue(valueName);
if (tryParse(valueString, out var newValue)) {
value = newValue;
return true;
}
throw new FormatException($"Improperly formatted {typeof(T)} value for {valueName} : '{valueString}");
}
public static bool TryParseColor32(string valueString, out Color32 value) {
value = new Color32(0, 0, 0, byte.MaxValue);
// HTML-style hex color
if (valueString[0] == '#') {
var hexColorString = valueString.Substring(1);
if (!int.TryParse(hexColorString, System.Globalization.NumberStyles.HexNumber, null, out var hexColor)) return false;
switch (hexColorString.Length) {
case 8: // RRGGBBAA
value.a = (byte) (hexColor & 0xFF);
hexColor >>= 8;
goto case 6;
case 6: // RRGGBB
value.b = (byte) (hexColor & 0xFF);
hexColor >>= 8;
value.g = (byte) (hexColor & 0xFF);
hexColor >>= 8;
value.r = (byte) (hexColor & 0xFF);
return true;
case 4: // RGBA
value.a = (byte) ((hexColor & 0xF) << 4);
hexColor >>= 4;
goto case 3;
case 3: // RGB
value.b = (byte) (hexColor & 0xF << 4);
hexColor >>= 4;
value.g = (byte) (hexColor & 0xF << 4);
hexColor >>= 4;
value.r = (byte) (hexColor & 0xF << 4);
return true;
default:
return false;
}
}
// named color
if (NamedColors.TryGetValue(valueString, out var namedColor)) {
value = namedColor;
return true;
}
// float color
var split = valueString.Split(Separator, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < split.Length; i++) {
split[i] = split[i].Trim();
}
switch (split.Length) {
case 4:
if (!float.TryParse(split[4], out var alpha)) return false;
value.a = (byte) (alpha * 0xFF);
goto case 3;
case 3:
if (!float.TryParse(split[0], out var red)) return false;
if (!float.TryParse(split[1], out var green)) return false;
if (!float.TryParse(split[2], out var blue)) return false;
value.r = (byte) (red * 0xFF);
value.g = (byte) (green * 0xFF);
value.b = (byte) (blue * 0xFF);
return true;
default:
return false;
}
}
}
}