Merge branch 'feature-multiProject' into develop

feature-better-tweakables
Andrew Cassidy 3 years ago
commit 3effae6ecd

3
.gitignore vendored

@ -49,4 +49,7 @@ Source/ConformalDecals/bin
.ds_store
*.sublime*
.idea
.vs
obj
*.swp
Source/.editorconfig

@ -3,15 +3,13 @@ python:
- 3.6
before_install:
- echo -e "machine github.com\n login $GITHUB_OAUTH_TOKEN" > ~/.netrc
- git lfs pull
- git lfs fetch --all
install:
- pip install awscli boto3 requests
branches:
only:
- release
script:
- git clone https://github.com/post-kerbin-mining-corporation/build-deploy.git
- git clone https://github.com/post-kerbin-mining-corporation/build-deploy.git
- cd build-deploy
- git checkout master
- cd ..
@ -24,4 +22,4 @@ deploy:
script: python build-deploy/src/deploy.py --f ".mod_data.yml" # Deploy package to spacedock, curse, github
skip_cleanup: true
on:
branch: release
branch: release

@ -15,7 +15,7 @@ Localization
#LOC_ConformalDecals_gui-opacity = Opacity
#LOC_ConformalDecals_gui-cutoff = Cutoff
#LOC_ConformalDecals_gui-wear = Edge Wear
#LOC_ConformalDecals_gui-aspectratio = Aspect Ratio
#LOC_ConformalDecals_gui-multiproject = Project onto Multiple
#LOC_ConformalDecals_gui-select-flag = Select Flag
#LOC_ConformalDecals_gui-reset-flag = Reset Flag
#LOC_ConformalDecals_gui-set-text = Set Text

@ -98,7 +98,7 @@ PART
MODULE {
IDENTIFIER { name = ModuleConformalDecal }
DATA {
shader = ConformalDecals/Paint/DiffuseSDF
KEYWORD { name = DECAL_SDF_ALPHA }
tile = 0, 2, 128, 112
}
}

@ -52,11 +52,17 @@ PART
name = ModuleConformalText
text = Text
fontName = Calibri SDF
fillColor = #000000FF
outlineColor = #FFFFFFFF
fillEnabled = true
outlineEnabled = false
shader = ConformalDecals/Decal/Text
useBaseNormal = true
scaleMode = MINIMUM
defaultScale = 0.2
defaultDepth = 0.2
defaultCutoff = 0.5
}

@ -0,0 +1,17 @@
// Decals are just paint, so they shouldnt affect a vessel's aerodynamics at all
@PART[*]:HAS[@MODULE[ModuleConformalDecal]]:After[FerramAerospaceResearch]
{
!MODULE[GeometryPartModule] {}
}
@PART[*]:HAS[@MODULE[ModuleConformalFlag]]:After[FerramAerospaceResearch]
{
!MODULE[GeometryPartModule] {}
}
@PART[*]:HAS[@MODULE[ModuleConformalText]]:After[FerramAerospaceResearch]
{
!MODULE[GeometryPartModule] {}
}

@ -6,14 +6,14 @@
{
"MAJOR":0,
"MINOR":2,
"PATCH":1,
"PATCH":7,
"BUILD":0
},
"KSP_VERSION":
{
"MAJOR":1,
"MINOR":10,
"PATCH":1
"MINOR":11,
"PATCH":0
},
"KSP_VERSION_MIN":{
"MAJOR":1,
@ -22,7 +22,7 @@
},
"KSP_VERSION_MAX":{
"MAJOR":1,
"MINOR":10,
"MINOR":11,
"PATCH":99
}
}

@ -1,5 +1,5 @@
# Conformal Decals v0.2.1
[![Build Status](https://travis-ci.org/drewcassidy/KSP-Conformal-Decals.svg?branch=release)](https://travis-ci.org/drewcassidy/KSP-Conformal-Decals) [![Art: CC BY-SA 4.0](https://img.shields.io/badge/Art%20License-CC%20BY--SA%204.0-orange.svg)](https://creativecommons.org/licenses/by-sa/4.0/) [![Code: GPL v3](https://img.shields.io/badge/Code%20License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
# Conformal Decals v0.2.7
[![Build Status](https://travis-ci.com/drewcassidy/KSP-Conformal-Decals.svg?branch=release)](https://travis-ci.com/drewcassidy/KSP-Conformal-Decals) [![Art: CC BY-SA 4.0](https://img.shields.io/badge/Art%20License-CC%20BY--SA%204.0-orange.svg)](https://creativecommons.org/licenses/by-sa/4.0/) [![Code: GPL v3](https://img.shields.io/badge/Code%20License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
![Screenshot](http://pileof.rocks/KSP/images/ConformalDecalsHeader.png)

@ -1,6 +1,12 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConformalDecals", "ConformalDecals/ConformalDecals.csproj", "{1ea983f9-42e5-494e-9683-fdac9c9121f4}"
# Visual Studio Version 16
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConformalDecals", "ConformalDecals\ConformalDecals.csproj", "{1EA983F9-42E5-494E-9683-FDAC9C9121F4}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C2564402-B081-479B-B723-D5C065BC884E}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -8,9 +14,33 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1ea983f9-42e5-494e-9683-fdac9c9121f4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1ea983f9-42e5-494e-9683-fdac9c9121f4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1ea983f9-42e5-494e-9683-fdac9c9121f4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1ea983f9-42e5-494e-9683-fdac9c9121f4}.Release|Any CPU.Build.0 = Release|Any CPU
{1EA983F9-42E5-494E-9683-FDAC9C9121F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1EA983F9-42E5-494E-9683-FDAC9C9121F4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1EA983F9-42E5-494E-9683-FDAC9C9121F4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1EA983F9-42E5-494E-9683-FDAC9C9121F4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
Policies = $0
$0.DotNetNamingPolicy = $1
$1.DirectoryNamespaceAssociation = PrefixedHierarchical
$0.TextStylePolicy = $2
$2.FileWidth = 80
$2.TabsToSpaces = True
$2.scope = text/x-csharp
$2.NoTabsAfterNonTabs = True
$2.EolMarker = Unix
$0.CSharpFormattingPolicy = $3
$3.NewLinesForBracesInTypes = False
$3.NewLinesForBracesInMethods = False
$3.NewLinesForBracesInProperties = False
$3.NewLinesForBracesInAccessors = False
$3.NewLinesForBracesInAnonymousMethods = False
$3.NewLinesForBracesInControlBlocks = False
$3.NewLinesForBracesInAnonymousTypes = False
$3.NewLinesForBracesInObjectCollectionArrayInitializers = False
$3.NewLinesForBracesInLambdaExpressionBody = False
$3.scope = text/x-csharp
$3.SpaceAfterCast = True
$0.StandardHeader = $4
EndGlobalSection
EndGlobal

@ -1,116 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)/$(MSBuildToolsVersion)/Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)/$(MSBuildToolsVersion)/Microsoft.Common.props')" />
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{1ea983f9-42e5-494e-9683-fdac9c9121f4}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFramework>net48</TargetFramework>
<LangVersion>8</LangVersion>
<RootNamespace>ConformalDecals</RootNamespace>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin/Debug/</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin/Release/</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>bin/Release/ConformalDecals.xml</DocumentationFile>
<NoWarn>CS1591,CS0649</NoWarn>
<IsPackable>false</IsPackable>
<PlatformTarget>x64</PlatformTarget>
<NoWarn>1701;1702;CS0649;CS1591</NoWarn>
<AssemblyVersion>0.2.7</AssemblyVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls/Assembly-CSharp.dll</HintPath>
</Reference>
<Reference Include="KSPAssets, Version=1.4.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls\KSPAssets.dll</HintPath>
<HintPath>dlls\Assembly-CSharp.dll</HintPath>
</Reference>
<Reference Include="Shabby, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls/Shabby.dll</HintPath>
<HintPath>dlls\Shabby.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls/UnityEngine.dll</HintPath>
<HintPath>dlls\UnityEngine.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.AssetBundleModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls/UnityEngine.AssetBundleModule.dll</HintPath>
<HintPath>dlls\UnityEngine.AssetBundleModule.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls/UnityEngine.CoreModule.dll</HintPath>
<HintPath>dlls\UnityEngine.CoreModule.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.PhysicsModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls/UnityEngine.PhysicsModule.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.TextCoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls/UnityEngine.TextCoreModule.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.TextRenderingModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls/UnityEngine.TextRenderingModule.dll</HintPath>
<HintPath>dlls\UnityEngine.PhysicsModule.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls/UnityEngine.UI.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.UIElementsModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls/UnityEngine.UIElementsModule.dll</HintPath>
<HintPath>dlls\UnityEngine.UI.dll</HintPath>
</Reference>
<Reference Include="UnityEngine.UIModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null">
<HintPath>dlls/UnityEngine.UIModule.dll</HintPath>
<HintPath>dlls\UnityEngine.UIModule.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="DecalConfig.cs" />
<Compile Include="DecalIconFixer.cs" />
<Compile Include="DecalPropertyIDs.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/DecalText.cs" />
<Compile Include="Text\DecalTextStyle.cs" />
<Compile Include="Text\TextRenderOutput.cs" />
<Compile Include="Text\TextRenderJob.cs" />
<Compile Include="UI/ColorPickerController.cs" />
<Compile Include="UI/FontMenuController.cs" />
<Compile Include="UI/FontMenuItem.cs" />
<Compile Include="UI/TextEntryController.cs" />
<Compile Include="UI/UILoader.cs" />
<Compile Include="UI/UITag.cs" />
<Compile Include="UI\ColorBoxSlider.cs" />
<Compile Include="UI\ColorChannelSlider.cs" />
<Compile Include="Util/Logging.cs" />
<Compile Include="Util/OrientedBounds.cs" />
<Compile Include="Util/ParseUtil.cs" />
<Compile Include="UI/BoxSlider.cs" />
<Compile Include="Util\ColorHSL.cs" />
<Compile Include="Util\ColorHSV.cs" />
<Compile Include="Util\ColorUtil.cs" />
<Compile Remove="dlls\**" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)/Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>sh -e -c "cp -v '$(TargetPath)' '$(SolutionDir)/../GameData/ConformalDecals/Plugins'"</PostBuildEvent>
</PropertyGroup>
<ItemGroup>
<EmbeddedResource Remove="dlls\**" />
</ItemGroup>
<ItemGroup>
<None Remove="dlls\**" />
</ItemGroup>
<ItemGroup>
<None Include="..\.editorconfig" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="/bin/cp -v '$(OutDir)ConformalDecals.dll' '$(SolutionDir)../GameData/ConformalDecals/Plugins'" />
</Target>
</Project>

@ -3,7 +3,6 @@ using System.Collections.Generic;
using ConformalDecals.Text;
using ConformalDecals.Util;
using TMPro;
using UniLinq;
using UnityEngine;
namespace ConformalDecals {
@ -50,8 +49,6 @@ namespace ConformalDecals {
public static bool SelectableInFlight => _selectableInFlight;
public static IEnumerable<DecalFont> Fonts => _fontList.Values;
public static DecalFont FallbackFont { get; private set; }
public static bool IsBlacklisted(Shader shader) {
return IsBlacklisted(shader.name);
@ -92,12 +89,12 @@ namespace ConformalDecals {
_shaderBlacklist.Add(shaderName);
}
}
var allFonts = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
foreach (var fontNode in node.GetNodes("FONT")) {
try {
var font = new DecalFont(fontNode, allFonts);
var font = DecalFont.Parse(fontNode, allFonts);
_fontList.Add(font.Name, font);
}
catch (Exception e) {
@ -114,12 +111,8 @@ namespace ConformalDecals {
var colors = new[] {color, color, color, color};
var tex = new Texture2D(width, height, TextureFormat.RGBA32, false);
for (var x = 0; x <= width; x++) {
for (var y = 0; y < height; y++) {
tex.SetPixels32(colors);
}
}
tex.SetPixels32(colors);
tex.Apply();
return tex;
@ -133,7 +126,7 @@ namespace ConformalDecals {
var configs = GameDatabase.Instance.GetConfigs("CONFORMALDECALS");
if (configs.Length > 0) {
Logging.Log("loading config");
Logging.Log("Loading config");
foreach (var config in configs) {
ParseConfig(config.config);
}

@ -0,0 +1,8 @@
using UnityEngine;
namespace ConformalDecals {
public interface IProjectionTarget {
bool Project(Matrix4x4 orthoMatrix, Transform projector, Bounds projectionBounds);
void Render(Material decalMaterial, MaterialPropertyBlock partMPB, Camera camera);
}
}

@ -8,7 +8,7 @@ namespace ConformalDecals.MaterialProperties {
public override void ParseNode(ConfigNode node) {
base.ParseNode(node);
ParseUtil.ParseBoolIndirect(ref value, node, "value");
value = ParseUtil.ParseBool(node, "value", true, true);
}
public override void Modify(Material material) {

@ -95,7 +95,7 @@ namespace ConformalDecals.MaterialProperties {
var property = MaterialProperty.Instantiate(_serializedProperties[i]);
_materialProperties.Add(_serializedNames[i], property);
if (property is MaterialTextureProperty textureProperty && textureProperty.isMain) {
if (property is MaterialTextureProperty {isMain: true} textureProperty) {
_mainTexture = textureProperty;
}
}
@ -105,6 +105,28 @@ namespace ConformalDecals.MaterialProperties {
_materialProperties ??= new Dictionary<string, MaterialProperty>();
}
public void Load(ConfigNode node) {
// add keyword nodes
foreach (var keywordNode in node.GetNodes("KEYWORD")) {
ParseProperty<MaterialKeywordProperty>(keywordNode);
}
// add texture nodes
foreach (var textureNode in node.GetNodes("TEXTURE")) {
ParseProperty<MaterialTextureProperty>(textureNode);
}
// add float nodes
foreach (var floatNode in node.GetNodes("FLOAT")) {
ParseProperty<MaterialTextureProperty>(floatNode);
}
// add color nodes
foreach (var colorNode in node.GetNodes("COLOR")) {
ParseProperty<MaterialColorProperty>(colorNode);
}
}
public void OnDestroy() {
if (_decalMaterial != null) Destroy(_decalMaterial);
if (_previewMaterial != null) Destroy(_previewMaterial);
@ -192,7 +214,7 @@ namespace ConformalDecals.MaterialProperties {
var newProperty = AddOrGetProperty<T>(propertyName);
newProperty.ParseNode(node);
if (newProperty is MaterialTextureProperty textureProperty && textureProperty.isMain) {
if (newProperty is MaterialTextureProperty {isMain: true} textureProperty) {
_mainTexture = textureProperty;
}
@ -230,7 +252,7 @@ namespace ConformalDecals.MaterialProperties {
public void UpdateScale(Vector2 scale) {
foreach (var entry in _materialProperties) {
if (entry.Value is MaterialTextureProperty textureProperty && textureProperty.autoScale) {
if (entry.Value is MaterialTextureProperty {autoScale: true} textureProperty) {
textureProperty.SetScale(scale);
}
}
@ -241,7 +263,7 @@ namespace ConformalDecals.MaterialProperties {
var mainTexSize = _mainTexture.Dimensions;
foreach (var entry in _materialProperties) {
if (entry.Value is MaterialTextureProperty textureProperty && textureProperty.autoTile) {
if (entry.Value is MaterialTextureProperty {autoTile: true} textureProperty) {
textureProperty.SetTile(tile, mainTexSize);
}
}

@ -41,7 +41,13 @@ namespace ConformalDecals.MaterialProperties {
public Vector2 Dimensions => new Vector2(_texture.width, _texture.height);
public Vector2 MaskedDimensions => _hasTile ? _tileRect.size : Dimensions;
public float AspectRatio => MaskedHeight / (float) MaskedWidth;
public float AspectRatio {
get {
if (_texture == null) return 1;
if (_textureUrl?.Contains("Squad/Flags") == true) return 0.625f; // squad flags are slightly stretched, so unstretch them
return MaskedHeight / (float) MaskedWidth;
}
}
public override void ParseNode(ConfigNode node) {
base.ParseNode(node);

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using ConformalDecals.MaterialProperties;
using ConformalDecals.Util;
using UniLinq;
using UnityEngine;
namespace ConformalDecals {
@ -31,7 +32,7 @@ namespace ConformalDecals {
[KSPField] public bool scaleAdjustable = true;
[KSPField] public float defaultScale = 1;
[KSPField] public Vector2 scaleRange = new Vector2(0, 4);
[KSPField] public Vector2 scaleRange = new Vector2(0, 5);
[KSPField] public DecalScaleMode scaleMode = DecalScaleMode.HEIGHT;
@ -60,26 +61,28 @@ namespace ConformalDecals {
// INTERNAL VALUES
[KSPField(guiName = "#LOC_ConformalDecals_gui-scale", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"),
UI_FloatRange(stepIncrement = 0.05f)]
UI_FloatRange()]
public float scale = 1.0f;
[KSPField(guiName = "#LOC_ConformalDecals_gui-depth", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"),
UI_FloatRange(stepIncrement = 0.02f)]
UI_FloatRange()]
public float depth = 0.2f;
[KSPField(guiName = "#LOC_ConformalDecals_gui-opacity", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "P0"),
UI_FloatRange(stepIncrement = 0.05f)]
UI_FloatRange()]
public float opacity = 1.0f;
[KSPField(guiName = "#LOC_ConformalDecals_gui-cutoff", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "P0"),
UI_FloatRange(stepIncrement = 0.05f)]
UI_FloatRange()]
public float cutoff = 0.5f;
[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(guiName = "#LOC_ConformalDecals_gui-multiproject", guiActive = false, guiActiveEditor = true, isPersistant = true),
UI_Toggle()]
public bool projectMultiple = true;
[KSPField] public MaterialPropertyCollection materialProperties;
@ -96,7 +99,7 @@ namespace ConformalDecals {
private const int DecalQueueMax = 2400;
private static int _decalQueueCounter = -1;
private List<ProjectionTarget> _targets;
private readonly Dictionary<Part, ProjectionPartTarget> _targets = new Dictionary<Part, ProjectionPartTarget>();
private bool _isAttached;
private Matrix4x4 _orthoMatrix;
@ -116,6 +119,8 @@ namespace ConformalDecals {
}
}
// EVENTS
/// <inheritdoc />
public override void OnAwake() {
base.OnAwake();
@ -130,114 +135,27 @@ namespace ConformalDecals {
/// <inheritdoc />
public override void OnLoad(ConfigNode node) {
// Load
try {
// SETUP TRANSFORMS
decalFrontTransform = part.FindModelTransform(decalFront);
if (decalFrontTransform == null) throw new FormatException($"Could not find decalFront transform: '{decalFront}'.");
decalBackTransform = part.FindModelTransform(decalBack);
if (decalBackTransform == null) throw new FormatException($"Could not find decalBack transform: '{decalBack}'.");
decalModelTransform = part.FindModelTransform(decalModel);
if (decalModelTransform == null) throw new FormatException($"Could not find decalModel transform: '{decalModel}'.");
decalProjectorTransform = part.FindModelTransform(decalProjector);
if (decalProjectorTransform == null) throw new FormatException($"Could not find decalProjector transform: '{decalProjector}'.");
decalColliderTransform = part.FindModelTransform(decalCollider);
if (decalColliderTransform == null) throw new FormatException($"Could not find decalCollider transform: '{decalCollider}'.");
// SETUP BACK MATERIAL
if (updateBackScale) {
var backRenderer = decalBackTransform.GetComponent<MeshRenderer>();
if (backRenderer == null) {
this.LogError($"Specified decalBack transform {decalBack} has no renderer attached! Setting updateBackScale to false.");
updateBackScale = false;
}
else {
backMaterial = backRenderer.material;
if (backMaterial == null) {
this.LogError($"Specified decalBack transform {decalBack} has a renderer but no material! Setting updateBackScale to false.");
updateBackScale = false;
}
else {
if (backTextureBaseScale == default) backTextureBaseScale = backMaterial.GetTextureScale(PropertyIDs._MainTex);
}
}
}
// PARSE MATERIAL PROPERTIES
// 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")) {
materialProperties.ParseProperty<MaterialTextureProperty>(textureNode);
}
// add float nodes
foreach (var floatNode in node.GetNodes("FLOAT")) {
materialProperties.ParseProperty<MaterialTextureProperty>(floatNode);
}
// add color nodes
foreach (var colorNode in node.GetNodes("COLOR")) {
materialProperties.ParseProperty<MaterialColorProperty>(colorNode);
}
// handle texture tiling parameters
var tileString = node.GetValue("tile");
if (!string.IsNullOrEmpty(tileString)) {
var tileValid = ParseExtensions.TryParseRect(tileString, out tileRect);
if (!tileValid) throw new FormatException($"Invalid rect value for tile '{tileString}'");
}
if (tileRect.x >= 0) {
materialProperties.UpdateTile(tileRect);
}
else if (tileIndex >= 0) {
materialProperties.UpdateTile(tileIndex, tileSize);
}
LoadDecal(node);
}
catch (Exception e) {
this.LogException("Exception parsing partmodule", e);
this.LogException("Error loading decal", e);
}
UpdateMaterials();
foreach (var keyword in _decalMaterial.shaderKeywords) {
this.Log($"keyword: {keyword}");
}
if (HighLogic.LoadedSceneIsEditor) {
UpdateTweakables();
}
if (HighLogic.LoadedSceneIsGame) {
UpdateScale();
// Setup
try {
SetupDecal();
}
else {
scale = defaultScale;
depth = defaultDepth;
opacity = defaultOpacity;
cutoff = defaultCutoff;
wear = defaultWear;
// QUEUE PART FOR ICON FIXING IN VAB
DecalIconFixer.QueuePart(part.name);
catch (Exception e) {
this.LogException("Error setting up decal", e);
}
}
/// <inheritdoc />
public override void OnIconCreate() {
UpdateScale();
UpdateTextures();
UpdateProjection();
}
/// <inheritdoc />
@ -255,6 +173,8 @@ namespace ConformalDecals {
}
}
/// Called after OnStart is finished for all parts
/// This is mostly used to make sure all B9 variants are already in place for the rest of the vessel
public override void OnStartFinished(StartState state) {
// handle game events
if (HighLogic.LoadedSceneIsGame) {
@ -283,6 +203,7 @@ namespace ConformalDecals {
}
}
/// Called when the decal is destroyed
public virtual void OnDestroy() {
// remove GameEvents
if (HighLogic.LoadedSceneIsEditor) {
@ -301,17 +222,21 @@ namespace ConformalDecals {
Destroy(materialProperties);
}
protected void OnSizeTweakEvent(BaseField field, object obj) {
/// Called when the decal's projection and scale is modified through a tweakable
protected void OnProjectionTweakEvent(BaseField field, object obj) {
// scale or depth values have been changed, so update scale
// and update projection matrices if attached
UpdateScale();
UpdateProjection();
UpdateTargets();
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalDecal>();
decal.UpdateScale();
decal.UpdateProjection();
decal.UpdateTargets();
}
}
/// Called when the decal's material is modified through a tweakable
protected void OnMaterialTweakEvent(BaseField field, object obj) {
materialProperties.SetOpacity(opacity);
materialProperties.SetCutoff(cutoff);
@ -329,35 +254,85 @@ namespace ConformalDecals {
}
}
/// Called when a new variant is applied in the editor
protected void OnVariantApplied(Part eventPart, PartVariant variant) {
if (_isAttached && eventPart == part.parent) {
if (_isAttached && eventPart != null && (!projectMultiple || eventPart == part.parent)) {
_targets.Remove(eventPart);
UpdateTargets();
}
}
/// Called when an editor event occurs
protected void OnEditorEvent(ConstructionEventType eventType, Part eventPart) {
if (this.part != eventPart && !part.symmetryCounterparts.Contains(eventPart)) return;
switch (eventType) {
case ConstructionEventType.PartAttached:
OnAttach();
OnPartAttached(eventPart);
break;
case ConstructionEventType.PartDetached:
OnDetach();
OnPartDetached(eventPart);
break;
case ConstructionEventType.PartOffsetting:
case ConstructionEventType.PartRotating:
UpdateScale();
OnPartTransformed(eventPart);
break;
}
}
/// Called when a part is transformed in the editor
protected void OnPartTransformed(Part eventPart) {
if (this.part == eventPart) {
UpdateProjection();
UpdateTargets();
}
else if (_isAttached && projectMultiple) {
UpdatePartTarget(eventPart, _boundsRenderer.bounds);
// recursively call for child parts
foreach (var child in eventPart.children) {
OnPartTransformed(child);
}
}
}
/// Called when a part is attached in the editor
protected void OnPartAttached(Part eventPart) {
if (this.part == eventPart) {
OnAttach();
}
else if (_isAttached && projectMultiple) {
UpdatePartTarget(eventPart, _boundsRenderer.bounds);
// recursively call for child parts
foreach (var child in eventPart.children) {
OnPartAttached(child);
}
}
}
/// Called when a part is detached in the editor
protected void OnPartDetached(Part eventPart) {
if (this.part == eventPart) {
OnDetach();
}
else if (_isAttached && projectMultiple) {
_targets.Remove(eventPart);
// recursively call for child parts
foreach (var child in eventPart.children) {
OnPartDetached(child);
}
}
}
/// Called when part `willDie` will be destroyed
protected void OnPartWillDie(Part willDie) {
if (willDie == part.parent) {
this.Log("Parent part about to be destroyed! Killing decal part.");
part.Die();
}
else if (_isAttached && projectMultiple) {
_targets.Remove(willDie);
}
}
/// Called when decal is attached to a new part
protected virtual void OnAttach() {
if (part.parent == null) {
this.LogError("Attach function called but part has no parent!");
@ -366,6 +341,7 @@ namespace ConformalDecals {
}
_isAttached = true;
_targets.Clear();
// hide model
decalModelTransform.gameObject.SetActive(false);
@ -377,10 +353,11 @@ namespace ConformalDecals {
Camera.onPreCull += Render;
UpdateMaterials();
UpdateProjection();
UpdateTargets();
UpdateScale();
}
/// Called when decal is detached from its parent part
protected virtual void OnDetach() {
_isAttached = false;
@ -394,110 +371,94 @@ namespace ConformalDecals {
Camera.onPreCull -= Render;
UpdateMaterials();
UpdateScale();
UpdateProjection();
}
protected void UpdateScale() {
scale = Mathf.Max(0.01f, scale);
depth = Mathf.Max(0.01f, depth);
var aspectRatio = materialProperties.AspectRatio;
Vector2 size;
// FUNCTIONS
switch (scaleMode) {
default:
case DecalScaleMode.HEIGHT:
size = new Vector2(scale / aspectRatio, scale);
break;
case DecalScaleMode.WIDTH:
size = new Vector2(scale, scale * aspectRatio);
break;
case DecalScaleMode.AVERAGE:
var width1 = 2 * scale / (1 + aspectRatio);
size = new Vector2(width1, width1 * aspectRatio);
break;
case DecalScaleMode.AREA:
var width2 = Mathf.Sqrt(scale / aspectRatio);
size = new Vector2(width2, width2 * aspectRatio);
break;
case DecalScaleMode.MINIMUM:
if (aspectRatio > 1) goto case DecalScaleMode.WIDTH;
else goto case DecalScaleMode.HEIGHT;
case DecalScaleMode.MAXIMUM:
if (aspectRatio > 1) goto case DecalScaleMode.HEIGHT;
else goto case DecalScaleMode.WIDTH;
}
/// Load any settings from the decal config
protected virtual void LoadDecal(ConfigNode node) {
// PARSE TRANSFORMS
decalFrontTransform = part.FindModelTransform(decalFront);
if (decalFrontTransform == null) throw new FormatException($"Could not find decalFront transform: '{decalFront}'.");
// update material scale
materialProperties.UpdateScale(size);
decalBackTransform = part.FindModelTransform(decalBack);
if (decalBackTransform == null) throw new FormatException($"Could not find decalBack transform: '{decalBack}'.");
if (_isAttached) {
// update orthogonal matrix
_orthoMatrix = Matrix4x4.identity;
_orthoMatrix[0, 3] = 0.5f;
_orthoMatrix[1, 3] = 0.5f;
decalModelTransform = part.FindModelTransform(decalModel);
if (decalModelTransform == null) throw new FormatException($"Could not find decalModel transform: '{decalModel}'.");
decalProjectorTransform.localScale = new Vector3(size.x, size.y, depth);
decalProjectorTransform = part.FindModelTransform(decalProjector);
if (decalProjectorTransform == null) throw new FormatException($"Could not find decalProjector transform: '{decalProjector}'.");
// update projection
foreach (var target in _targets) {
target.Project(_orthoMatrix, decalProjectorTransform, _boundsRenderer.bounds, useBaseNormal);
}
}
else {
// rescale preview model
decalModelTransform.localScale = new Vector3(size.x, size.y, (size.x + size.y) / 2);
decalColliderTransform = part.FindModelTransform(decalCollider);
if (decalColliderTransform == null) throw new FormatException($"Could not find decalCollider transform: '{decalCollider}'.");
// update back material scale
if (updateBackScale) {
backMaterial.SetTextureScale(PropertyIDs._MainTex, new Vector2(size.x * backTextureBaseScale.x, size.y * backTextureBaseScale.y));
// SETUP BACK MATERIAL
if (updateBackScale) {
var backRenderer = decalBackTransform.GetComponent<MeshRenderer>();
if (backRenderer == null) {
this.LogError($"Specified decalBack transform {decalBack} has no renderer attached! Setting updateBackScale to false.");
updateBackScale = false;
}
else {
backMaterial = backRenderer.material;
if (backMaterial == null) {
this.LogError($"Specified decalBack transform {decalBack} has a renderer but no material! Setting updateBackScale to false.");
updateBackScale = false;
}
else {
if (backTextureBaseScale == default) backTextureBaseScale = backMaterial.GetTextureScale(PropertyIDs._MainTex);
}
}
}
}
protected virtual void UpdateMaterials() {
materialProperties.UpdateMaterials();
materialProperties.SetOpacity(opacity);
materialProperties.SetCutoff(cutoff);
if (useBaseNormal) {
materialProperties.SetWear(wear);
}
_decalMaterial = materialProperties.DecalMaterial;
_previewMaterial = materialProperties.PreviewMaterial;
// PARSE MATERIAL PROPERTIES
// set shader
materialProperties.SetShader(shader);
materialProperties.AddOrGetProperty<MaterialKeywordProperty>("DECAL_BASE_NORMAL").value = useBaseNormal;
materialProperties.Load(node);
if (!_isAttached) decalFrontTransform.GetComponent<MeshRenderer>().material = _previewMaterial;
}
// handle texture tiling parameters
var tileString = node.GetValue("tile");
if (!string.IsNullOrEmpty(tileString)) {
var tileValid = ParseExtensions.TryParseRect(tileString, out tileRect);
if (!tileValid) throw new FormatException($"Invalid rect value for tile '{tileString}'");
}
protected void UpdateTargets() {
if (_targets == null) {
_targets = new List<ProjectionTarget>();
if (tileRect.x >= 0) {
materialProperties.UpdateTile(tileRect);
}
else {
_targets.Clear();
else if (tileIndex >= 0) {
materialProperties.UpdateTile(tileIndex, tileSize);
}
}
// find all valid renderers
var renderers = part.parent.FindModelComponents<MeshRenderer>();
foreach (var renderer in renderers) {
// skip disabled renderers
if (renderer.gameObject.activeInHierarchy == false) continue;
// skip blacklisted shaders
if (DecalConfig.IsBlacklisted(renderer.material.shader)) continue;
/// Setup decal by calling update functions relevent for the current situation
protected virtual void SetupDecal() {
if (HighLogic.LoadedSceneIsEditor) {
// Update tweakables in editor mode
UpdateTweakables();
}
var meshFilter = renderer.GetComponent<MeshFilter>();
if (meshFilter == null) continue; // object has a meshRenderer with no filter, invalid
var mesh = meshFilter.mesh;
if (mesh == null) continue; // object has a null mesh, invalid
if (HighLogic.LoadedSceneIsGame) {
UpdateAll();
}
else {
scale = defaultScale;
depth = defaultDepth;
opacity = defaultOpacity;
cutoff = defaultCutoff;
wear = defaultWear;
// create new ProjectionTarget to represent the renderer
var target = new ProjectionTarget(renderer, mesh);
UpdateAll();
// add the target to the list
_targets.Add(target);
// QUEUE PART FOR ICON FIXING IN VAB
DecalIconFixer.QueuePart(part.name);
}
}
/// Update decal editor tweakables
protected virtual void UpdateTweakables() {
// setup tweakable fields
var scaleField = Fields[nameof(scale)];
@ -505,6 +466,7 @@ namespace ConformalDecals {
var opacityField = Fields[nameof(opacity)];
var cutoffField = Fields[nameof(cutoff)];
var wearField = Fields[nameof(wear)];
var multiprojectField = Fields[nameof(projectMultiple)];
scaleField.guiActiveEditor = scaleAdjustable;
depthField.guiActiveEditor = depthAdjustable;
@ -512,7 +474,7 @@ namespace ConformalDecals {
cutoffField.guiActiveEditor = cutoffAdjustable;
wearField.guiActiveEditor = useBaseNormal;
var steps = 40;
var steps = 20;
if (scaleAdjustable) {
var minValue = Mathf.Max(Mathf.Epsilon, scaleRange.x);
@ -521,8 +483,8 @@ namespace ConformalDecals {
var scaleEditor = (UI_FloatRange) scaleField.uiControlEditor;
scaleEditor.minValue = minValue;
scaleEditor.maxValue = maxValue;
scaleEditor.stepIncrement = (maxValue - minValue) / steps;
scaleEditor.onFieldChanged = OnSizeTweakEvent;
scaleEditor.stepIncrement = 0.01f; //1cm
scaleEditor.onFieldChanged = OnProjectionTweakEvent;
}
if (depthAdjustable) {
@ -532,8 +494,8 @@ namespace ConformalDecals {
var depthEditor = (UI_FloatRange) depthField.uiControlEditor;
depthEditor.minValue = minValue;
depthEditor.maxValue = maxValue;
depthEditor.stepIncrement = (maxValue - minValue) / steps;
depthEditor.onFieldChanged = OnSizeTweakEvent;
depthEditor.stepIncrement = 0.01f; //1cm
depthEditor.onFieldChanged = OnProjectionTweakEvent;
}
if (opacityAdjustable) {
@ -570,13 +532,144 @@ namespace ConformalDecals {
wearEditor.stepIncrement = (maxValue - minValue) / steps;
wearEditor.onFieldChanged = OnMaterialTweakEvent;
}
var multiprojectEditor = (UI_Toggle) multiprojectField.uiControlEditor;
multiprojectEditor.onFieldChanged = OnProjectionTweakEvent;
}
/// Updates textures, materials, scale and targets
protected virtual void UpdateAll() {
UpdateTextures();
UpdateMaterials();
UpdateProjection();
UpdateTargets();
}
/// Update decal textures
protected virtual void UpdateTextures() { }
/// Update decal materials
protected virtual void UpdateMaterials() {
materialProperties.UpdateMaterials();
materialProperties.SetOpacity(opacity);
materialProperties.SetCutoff(cutoff);
if (useBaseNormal) {
materialProperties.SetWear(wear);
}
_decalMaterial = materialProperties.DecalMaterial;
_previewMaterial = materialProperties.PreviewMaterial;
if (!_isAttached) decalFrontTransform.GetComponent<MeshRenderer>().material = _previewMaterial;
}
/// Update decal scale and projection
protected void UpdateProjection() {
// Update scale and depth
scale = Mathf.Max(0.01f, scale);
depth = Mathf.Max(0.01f, depth);
var aspectRatio = Mathf.Max(0.01f, materialProperties.AspectRatio);
Vector2 size;
switch (scaleMode) {
default:
case DecalScaleMode.HEIGHT:
size = new Vector2(scale / aspectRatio, scale);
break;
case DecalScaleMode.WIDTH:
size = new Vector2(scale, scale * aspectRatio);
break;
case DecalScaleMode.AVERAGE:
var width1 = 2 * scale / (1 + aspectRatio);
size = new Vector2(width1, width1 * aspectRatio);
break;
case DecalScaleMode.AREA:
var width2 = Mathf.Sqrt(scale / aspectRatio);
size = new Vector2(width2, width2 * aspectRatio);
break;
case DecalScaleMode.MINIMUM:
if (aspectRatio > 1) goto case DecalScaleMode.WIDTH;
else goto case DecalScaleMode.HEIGHT;
case DecalScaleMode.MAXIMUM:
if (aspectRatio > 1) goto case DecalScaleMode.HEIGHT;
else goto case DecalScaleMode.WIDTH;
}
// update material scale
materialProperties.UpdateScale(size);
if (_isAttached) {
// update orthogonal matrix
_orthoMatrix = Matrix4x4.identity;
_orthoMatrix[0, 3] = 0.5f;
_orthoMatrix[1, 3] = 0.5f;
decalProjectorTransform.localScale = new Vector3(size.x, size.y, depth);
}
else {
// rescale preview model
decalModelTransform.localScale = new Vector3(size.x, size.y, (size.x + size.y) / 2);
// update back material scale
if (updateBackScale) {
backMaterial.SetTextureScale(PropertyIDs._MainTex, new Vector2(size.x * backTextureBaseScale.x, size.y * backTextureBaseScale.y));
}
}
}
/// Called when updating decal targets
protected void UpdateTargets() {
if (!_isAttached) return;
var projectionBounds = _boundsRenderer.bounds;
// disable all targets
foreach (var target in _targets.Values) {
target.enabled = false;
}
// collect list of potential targets
IEnumerable<Part> targetParts;
if (projectMultiple) {
targetParts = HighLogic.LoadedSceneIsFlight ? part.vessel.parts : EditorLogic.fetch.ship.parts;
}
else {
targetParts = new[] {part.parent};
}
foreach (var targetPart in targetParts) {
UpdatePartTarget(targetPart, projectionBounds);
}
}
protected void UpdatePartTarget(Part targetPart, Bounds projectionBounds) {
if (targetPart.GetComponent<ModuleConformalDecal>() != null) return; // skip other decals
this.Log($"Updating projection onto part {targetPart.name}");
if (!_targets.TryGetValue(targetPart, out var target)) {
var rendererList = targetPart.FindModelComponents<MeshRenderer>();
if (rendererList.Any(o => projectionBounds.Intersects(o.bounds))) {
target = new ProjectionPartTarget(targetPart, useBaseNormal);
_targets.Add(targetPart, target);
}
else {
return;
}
}
this.Log($"valid target: {targetPart.name}");
target.Project(_orthoMatrix, decalProjectorTransform, projectionBounds);
}
/// Render the decal
public void Render(Camera camera) {
if (!_isAttached) return;
// render on each target object
foreach (var target in _targets) {
foreach (var target in _targets.Values) {
target.Render(_decalMaterial, part.mpb, camera);
}
}

@ -1,4 +1,5 @@
using ConformalDecals.Util;
using ConformalDecals.MaterialProperties;
using UniLinq;
using UnityEngine;
namespace ConformalDecals {
@ -9,6 +10,8 @@ namespace ConformalDecals {
[KSPField(isPersistant = true)] public bool useCustomFlag;
private MaterialTextureProperty _flagTextureProperty;
public string MissionFlagUrl {
get {
if (HighLogic.LoadedSceneIsEditor) {
@ -23,17 +26,6 @@ namespace ConformalDecals {
}
}
public override void OnLoad(ConfigNode node) {
base.OnLoad(node);
if (useCustomFlag) {
SetFlag(flagUrl);
}
else {
SetFlag(MissionFlagUrl);
}
}
public override void OnStart(StartState state) {
base.OnStart(state);
@ -44,66 +36,60 @@ namespace ConformalDecals {
if (HighLogic.LoadedSceneIsEditor) {
Events[nameof(ResetFlag)].guiActiveEditor = useCustomFlag;
}
if (useCustomFlag) {
SetFlag(flagUrl);
}
else {
SetFlag(MissionFlagUrl);
}
}
public override void OnDestroy() {
GameEvents.onMissionFlagSelect.Remove(SetFlag);
GameEvents.onMissionFlagSelect.Remove(OnEditorFlagSelected);
base.OnDestroy();
}
[KSPEvent(guiActive = false, guiActiveEditor = true, guiName = "#LOC_ConformalDecals_gui-select-flag")]
public void SelectFlag() {
var flagBrowser = (Instantiate((Object) (new FlagBrowserGUIButton(null, null, null, null)).FlagBrowserPrefab) as GameObject).GetComponent<FlagBrowser>();
flagBrowser.OnFlagSelected = OnCustomFlagSelected;
var flagBrowser = (Instantiate((Object) (new FlagBrowserGUIButton(null, null, null, null)).FlagBrowserPrefab) as GameObject)?.GetComponent<FlagBrowser>();
if (flagBrowser is { }) flagBrowser.OnFlagSelected = OnCustomFlagSelected;
}
[KSPEvent(guiActive = false, guiActiveEditor = true, guiName = "#LOC_ConformalDecals_gui-reset-flag")]
public void ResetFlag() {
SetFlag(MissionFlagUrl);
SetFlagSymmetryCounterparts(MissionFlagUrl);
useCustomFlag = false;
Events[nameof(ResetFlag)].guiActiveEditor = false;
flagUrl = MissionFlagUrl;
useCustomFlag = false;
UpdateAll();
foreach (var decal in part.symmetryCounterparts.Select(o => o.GetComponent<ModuleConformalFlag>())) {
decal.Events[nameof(ResetFlag)].guiActiveEditor = false;
decal.flagUrl = flagUrl;
decal.useCustomFlag = false;
decal.UpdateAll();
}
}
private void OnCustomFlagSelected(FlagBrowser.FlagEntry newFlagEntry) {
SetFlag(newFlagEntry.textureInfo.name);
SetFlagSymmetryCounterparts(newFlagEntry.textureInfo.name);
useCustomFlag = true;
Events[nameof(ResetFlag)].guiActiveEditor = true;
}
flagUrl = newFlagEntry.textureInfo.name;
useCustomFlag = true;
UpdateAll();
private void OnEditorFlagSelected(string newFlagUrl) {
if (!useCustomFlag) {
SetFlag(newFlagUrl);
SetFlagSymmetryCounterparts(newFlagUrl);
foreach (var decal in part.symmetryCounterparts.Select(o => o.GetComponent<ModuleConformalFlag>())) {
decal.Events[nameof(ResetFlag)].guiActiveEditor = true;
decal.flagUrl = flagUrl;
decal.useCustomFlag = true;
decal.UpdateAll();
}
}
private void SetFlag(string newFlagUrl) {
this.Log($"Loading flag texture '{newFlagUrl}'.");
flagUrl = newFlagUrl;
materialProperties.AddOrGetTextureProperty("_Decal", true).TextureUrl = newFlagUrl;
UpdateMaterials();
UpdateScale();
private void OnEditorFlagSelected(string newFlagUrl) {
if (!useCustomFlag) UpdateAll();
}
private void SetFlagSymmetryCounterparts(string newFlagUrl) {
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalFlag>();
protected override void UpdateTextures() {
_flagTextureProperty ??= materialProperties.AddOrGetTextureProperty("_Decal", true);
decal.SetFlag(newFlagUrl);
decal.useCustomFlag = useCustomFlag;
base.UpdateTextures();
if (useCustomFlag) {
_flagTextureProperty.TextureUrl = flagUrl;
}
else {
_flagTextureProperty.TextureUrl = MissionFlagUrl;
}
}
}

@ -1,32 +1,34 @@
using System.Collections;
using System.Net;
using ConformalDecals.MaterialProperties;
using ConformalDecals.Text;
using ConformalDecals.UI;
using ConformalDecals.Util;
using TMPro;
using UniLinq;
using UnityEngine;
namespace ConformalDecals {
public class ModuleConformalText : ModuleConformalDecal, ISerializationCallbackReceiver {
[KSPField(isPersistant = true)] public string text = "Text";
public class ModuleConformalText : ModuleConformalDecal {
[KSPField] public Vector2 lineSpacingRange = new Vector2(-50, 50);
[KSPField] public Vector2 charSpacingRange = new Vector2(-50, 50);
// serialization-only fields. do not use except in serialization functions
[KSPField(isPersistant = true)] public string fontName = "Calibri SDF";
[KSPField(isPersistant = true)] public int style;
[KSPField(isPersistant = true)] public bool vertical;
[KSPField(isPersistant = true)] public float lineSpacing;
[KSPField(isPersistant = true)] public float charSpacing;
[KSPField(isPersistant = true)] public string fillColor = "000000FF";
[KSPField(isPersistant = true)] public string outlineColor = "FFFFFFFF";
[KSPField(isPersistant = true)] public bool vertical;
[KSPField(isPersistant = true)] public float lineSpacing;
[KSPField(isPersistant = true)] public float charSpacing;
[KSPField] public string text;
[KSPField] public DecalFont font;
[KSPField] public FontStyles style;
[KSPField] public Color32 fillColor = Color.black;
[KSPField] public Color32 outlineColor = Color.white;
// KSP TWEAKABLES
[KSPEvent(guiName = "#LOC_ConformalDecals_gui-set-text", guiActive = false, guiActiveEditor = true)]
public void SetText() {
if (_textEntryController == null) {
_textEntryController = TextEntryController.Create(text, _font, _style, lineSpacingRange, charSpacingRange, OnTextUpdate);
_textEntryController = TextEntryController.Create(text, font, style, vertical, lineSpacing, charSpacing, lineSpacingRange, charSpacingRange, OnTextUpdate);
}
else {
_textEntryController.Close();
@ -44,7 +46,7 @@ namespace ConformalDecals {
guiActive = false, guiActiveEditor = true)]
public void SetFillColor() {
if (_fillColorPickerController == null) {
_fillColorPickerController = ColorPickerController.Create(_fillColor, OnFillColorUpdate);
_fillColorPickerController = ColorPickerController.Create(fillColor, OnFillColorUpdate);
}
else {
_fillColorPickerController.Close();
@ -67,17 +69,13 @@ namespace ConformalDecals {
guiActive = false, guiActiveEditor = true)]
public void SetOutlineColor() {
if (_outlineColorPickerController == null) {
_outlineColorPickerController = ColorPickerController.Create(_outlineColor, OnOutlineColorUpdate);
_outlineColorPickerController = ColorPickerController.Create(outlineColor, OnOutlineColorUpdate);
}
else {
_outlineColorPickerController.Close();
}
}
private DecalTextStyle _style;
private DecalFont _font;
private Color32 _fillColor;
private Color32 _outlineColor;
private TextEntryController _textEntryController;
private ColorPickerController _fillColorPickerController;
@ -92,27 +90,20 @@ namespace ConformalDecals {
private MaterialColorProperty _outlineColorProperty;
private MaterialFloatProperty _outlineWidthProperty;
private TextRenderJob _currentJob;
private DecalText _currentText;
private DecalText _currentText;
public override void OnLoad(ConfigNode node) {
base.OnLoad(node);
OnAfterDeserialize();
UpdateTextRecursive();
}
// EVENTS
/// <inheritdoc />
public override void OnSave(ConfigNode node) {
OnBeforeSerialize();
node.AddValue("text", WebUtility.UrlEncode(text));
node.AddValue("fontName", font.Name);
node.AddValue("style", (int) style);
node.AddValue("fillColor", fillColor.ToHexString());
node.AddValue("outlineColor", outlineColor.ToHexString());
base.OnSave(node);
}
public override void OnStart(StartState state) {
base.OnStart(state);
UpdateTextRecursive();
}
public override void OnAwake() {
base.OnAwake();
@ -126,31 +117,44 @@ namespace ConformalDecals {
_outlineWidthProperty = materialProperties.AddOrGetProperty<MaterialFloatProperty>("_OutlineWidth");
}
public void OnTextUpdate(string newText, DecalFont newFont, DecalTextStyle newStyle) {
public void OnTextUpdate(string newText, DecalFont newFont, FontStyles newStyle, bool newVertical, float newLineSpacing, float newCharSpacing) {
text = newText;
_font = newFont;
_style = newStyle;
UpdateTextRecursive();
font = newFont;
style = newStyle;
vertical = newVertical;
lineSpacing = newLineSpacing;
charSpacing = newCharSpacing;
UpdateAll();
foreach (var decal in part.symmetryCounterparts.Select(o => o.GetComponent<ModuleConformalText>())) {
decal.text = newText;
decal.font = newFont;
decal.style = newStyle;
decal.vertical = newVertical;
decal.lineSpacing = newLineSpacing;
decal.charSpacing = newCharSpacing;
decal.UpdateAll();
}
}
public void OnFillColorUpdate(Color rgb, Util.ColorHSV hsv) {
_fillColor = rgb;
fillColor = rgb;
UpdateMaterials();
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalText>();
decal._fillColor = _fillColor;
decal.fillColor = fillColor;
decal.UpdateMaterials();
}
}
public void OnOutlineColorUpdate(Color rgb, Util.ColorHSV hsv) {
_outlineColor = rgb;
outlineColor = rgb;
UpdateMaterials();
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalText>();
decal._outlineColor = _outlineColor;
decal.outlineColor = outlineColor;
decal.UpdateMaterials();
}
}
@ -197,34 +201,14 @@ namespace ConformalDecals {
}
}
public void OnBeforeSerialize() {
fontName = _font.Name;
style = (int) _style.FontStyle;
vertical = _style.Vertical;
lineSpacing = _style.LineSpacing;
charSpacing = _style.CharSpacing;
fillColor = _fillColor.ToHexString();
outlineColor = _outlineColor.ToHexString();
}
public void OnAfterDeserialize() {
_font = DecalConfig.GetFont(fontName);
_style = new DecalTextStyle((FontStyles) style, vertical, lineSpacing, charSpacing);
if (!ParseUtil.TryParseColor32(fillColor, out _fillColor)) {
Logging.LogWarning($"Improperly formatted color value for fill: '{fillColor}'");
_fillColor = Color.magenta;
}
if (!ParseUtil.TryParseColor32(outlineColor, out _outlineColor)) {
Logging.LogWarning($"Improperly formatted color value for outline: '{outlineColor}'");
_outlineColor = Color.magenta;
}
}
public override void OnDestroy() {
if (HighLogic.LoadedSceneIsGame && _currentText != null) TextRenderer.UnregisterText(_currentText);
// close all UIs
if (_textEntryController != null) _textEntryController.Close();
if (_fillColorPickerController != null) _fillColorPickerController.Close();
if (_outlineColorPickerController != null) _outlineColorPickerController.Close();
base.OnDestroy();
}
@ -237,49 +221,78 @@ namespace ConformalDecals {
base.OnDetach();
}
private void UpdateTextRecursive() {
UpdateText();
// FUNCTIONS
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalText>();
decal.text = text;
decal._font = _font;
decal._style = _style;
protected override void LoadDecal(ConfigNode node) {
base.LoadDecal(node);
string textRaw = "";
if (ParseUtil.ParseStringIndirect(ref textRaw, node, "text")) {
text = WebUtility.UrlDecode(textRaw);
}
string fontName = "";
if (ParseUtil.ParseStringIndirect(ref fontName, node, "fontName")) {
font = DecalConfig.GetFont(fontName);
}
else if (font == null) font = DecalConfig.GetFont("Calibri SDF");
decal._currentJob = _currentJob;
decal._currentText = _currentText;
decal.UpdateText();
int styleInt = 0;
if (ParseUtil.ParseIntIndirect(ref styleInt, node, "style")) {
style = (FontStyles) styleInt;
}
ParseUtil.ParseColor32Indirect(ref fillColor, node, "fillColor");
ParseUtil.ParseColor32Indirect(ref outlineColor, node, "outlineColor");
}
private void UpdateText() {
// Render text
var newText = new DecalText(text, _font, _style);
var output = TextRenderer.UpdateTextNow(_currentText, newText);
_currentText = newText;
protected override void SetupDecal() {
if (HighLogic.LoadedSceneIsEditor) {
// Update tweakables in editor mode
UpdateTweakables();
}
UpdateTexture(output);
if (HighLogic.LoadedSceneIsGame) {
// For some reason text rendering fails on the first frame of a scene, so this is my workaround
StartCoroutine(UpdateTextLate());
}
else {
scale = defaultScale;
depth = defaultDepth;
opacity = defaultOpacity;
cutoff = defaultCutoff;
wear = defaultWear;
UpdateTextures();
UpdateMaterials();
UpdateProjection();
// QUEUE PART FOR ICON FIXING IN VAB
DecalIconFixer.QueuePart(part.name);
}
}
// TODO: ASYNC RENDERING
// var newText = new DecalText(text, _font, _style);
// _currentJob = TextRenderer.UpdateText(_currentText, newText, UpdateTexture);
// _currentText = newText;
private IEnumerator UpdateTextLate() {
yield return null;
UpdateAll();
}
public void UpdateTexture(TextRenderOutput output) {
protected override void UpdateTextures() {
// Render text
var newText = new DecalText(text, font, style, vertical, lineSpacing, charSpacing);
var output = TextRenderer.UpdateText(_currentText, newText);
_currentText = newText;
_decalTextureProperty.Texture = output.Texture;
_decalTextureProperty.SetTile(output.Window);
UpdateMaterials();
UpdateScale();
}
protected override void UpdateMaterials() {
_fillEnabledProperty.value = fillEnabled;
_fillColorProperty.color = _fillColor;
_fillColorProperty.color = fillColor;
_outlineEnabledProperty.value = outlineEnabled;
_outlineColorProperty.color = _outlineColor;
_outlineColorProperty.color = outlineColor;
_outlineWidthProperty.value = outlineWidth;
base.UpdateMaterials();

@ -0,0 +1,93 @@
using UnityEngine;
using UnityEngine.Rendering;
namespace ConformalDecals {
public class ProjectionMeshTarget : IProjectionTarget {
public const string NodeName = "MESH_TARGET";
// enabled flag
public bool enabled;
// Target object data
public readonly Transform target;
public readonly Transform root;
public readonly Mesh mesh;
public readonly MeshRenderer renderer;
// Projection data
private Matrix4x4 _decalMatrix;
private Vector3 _decalNormal;
private Vector3 _decalTangent;
// property block
private readonly MaterialPropertyBlock _decalMPB;
public ProjectionMeshTarget(Transform target, Transform root, MeshRenderer renderer, Mesh mesh, bool useBaseNormal) {
this.root = root;
this.target = target;
this.renderer = renderer;
this.mesh = mesh;
_decalMPB = new MaterialPropertyBlock();
SetNormalMap(renderer.sharedMaterial, useBaseNormal);
}
private void SetNormalMap(Material targetMaterial, bool useBaseNormal) {
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);
}
}
public bool Project(Matrix4x4 orthoMatrix, Transform projector, Bounds projectionBounds) {
if (projectionBounds.Intersects(renderer.bounds)) {
enabled = true;
var projectorToTargetMatrix = target.worldToLocalMatrix * projector.localToWorldMatrix;
_decalMatrix = orthoMatrix * projectorToTargetMatrix.inverse;
_decalNormal = projectorToTargetMatrix.MultiplyVector(Vector3.back).normalized;
_decalTangent = projectorToTargetMatrix.MultiplyVector(Vector3.right).normalized;
_decalMPB.SetMatrix(DecalPropertyIDs._ProjectionMatrix, _decalMatrix);
_decalMPB.SetVector(DecalPropertyIDs._DecalNormal, _decalNormal);
_decalMPB.SetVector(DecalPropertyIDs._DecalTangent, _decalTangent);
}
else {
enabled = false;
}
return enabled;
}
public void Render(Material decalMaterial, MaterialPropertyBlock partMPB, Camera camera) {
if (!enabled) return;
_decalMPB.SetFloat(PropertyIDs._RimFalloff, partMPB.GetFloat(PropertyIDs._RimFalloff));
_decalMPB.SetColor(PropertyIDs._RimColor, partMPB.GetColor(PropertyIDs._RimColor));
Graphics.DrawMesh(mesh, target.localToWorldMatrix, decalMaterial, 0, camera, 0, _decalMPB, ShadowCastingMode.Off, true);
}
public static bool ValidateTarget(Transform target, MeshRenderer renderer, MeshFilter filter) {
if (renderer == null) return false;
if (filter == null) return false;
if (!target.gameObject.activeInHierarchy) return false;
var material = renderer.material;
if (material == null) return false;
if (DecalConfig.IsBlacklisted(material.shader)) return false;
if (filter.sharedMesh == null) return false;
return true;
}
}
}

@ -0,0 +1,50 @@
using System.Collections.Generic;
using UnityEngine;
namespace ConformalDecals {
public class ProjectionPartTarget : IProjectionTarget {
public const string NodeName = "PART_TARGET";
// enabled flag
public bool enabled;
public readonly Part part;
public readonly List<ProjectionMeshTarget> meshTargets = new List<ProjectionMeshTarget>();
public ProjectionPartTarget(Part part, bool useBaseNormal) {
this.part = part;
foreach (var renderer in part.FindModelComponents<MeshRenderer>()) {
var target = renderer.transform;
var filter = target.GetComponent<MeshFilter>();
// check if the target has any missing data
if (!ProjectionMeshTarget.ValidateTarget(target, renderer, filter)) continue;
// create new ProjectionTarget to represent the renderer
var projectionTarget = new ProjectionMeshTarget(target, part.transform, renderer, filter.sharedMesh, useBaseNormal);
// add the target to the list
meshTargets.Add(projectionTarget);
}
}
public bool Project(Matrix4x4 orthoMatrix, Transform projector, Bounds projectionBounds) {
enabled = false;
foreach (var meshTarget in meshTargets) {
enabled |= meshTarget.Project(orthoMatrix, projector, projectionBounds);
}
return enabled;
}
public void Render(Material decalMaterial, MaterialPropertyBlock partMPB, Camera camera) {
if (!enabled) return;
foreach (var target in meshTargets) {
target.Render(decalMaterial, partMPB, camera);
}
}
}
}

@ -1,68 +0,0 @@
using UnityEngine;
using UnityEngine.Rendering;
namespace ConformalDecals {
public class ProjectionTarget {
// Target object data
public readonly Transform target;
private readonly Renderer _targetRenderer;
private readonly Mesh _targetMesh;
private bool _projectionEnabled;
// property block
private readonly MaterialPropertyBlock _decalMPB;
public ProjectionTarget(MeshRenderer targetRenderer, Mesh targetMesh) {
target = targetRenderer.transform;
_targetRenderer = targetRenderer;
_targetMesh = targetMesh;
_decalMPB = new MaterialPropertyBlock();
}
public void Project(Matrix4x4 orthoMatrix, Transform projector, Bounds projectorBounds, bool useBaseNormal) {
if (projectorBounds.Intersects(_targetRenderer.bounds)) {
_projectionEnabled = true;
var targetMaterial = _targetRenderer.sharedMaterial;
var projectorToTargetMatrix = target.worldToLocalMatrix * projector.localToWorldMatrix;
var projectionMatrix = orthoMatrix * projectorToTargetMatrix.inverse;
var decalNormal = projectorToTargetMatrix.MultiplyVector(Vector3.back).normalized;
var decalTangent = projectorToTargetMatrix.MultiplyVector(Vector3.right).normalized;
_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);
}
}
else {
_projectionEnabled = false;
}
}
public bool Render(Material decalMaterial, MaterialPropertyBlock partMPB, Camera camera) {
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);
return true;
}
return false;
}
}
}

@ -1,38 +1 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ConformalDecals")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Cineboxandrew")]
[assembly: AssemblyProduct("ConformalDecals")]
[assembly: AssemblyCopyright("Copyright © Andrew Cassidy 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1ea983f9-42e5-494e-9683-fdac9c9121f4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: KSPAssembly("ConformalDecals", 0, 1, 0)]
[assembly: KSPAssembly("ConformalDecals", 0, 2)]

@ -3,58 +3,68 @@ using System.Collections.Generic;
using ConformalDecals.Util;
using TMPro;
using UniLinq;
using UnityEngine;
namespace ConformalDecals.Text {
public class DecalFont : IEquatable<DecalFont> {
public class DecalFont : ScriptableObject, ISerializationCallbackReceiver, IEquatable<DecalFont> {
[SerializeField] private string _title;
[SerializeField] private TMP_FontAsset _fontAsset;
[SerializeField] private FontStyles _fontStyle;
[SerializeField] private FontStyles _fontStyleMask;
/// Human-readable name for the font
public string Title { get; }
public string Title => _title;
/// Internal name for the font
public string Name => FontAsset.name;
public string Name => _fontAsset.name;
/// The font asset itself
public TMP_FontAsset FontAsset { get; }
public TMP_FontAsset FontAsset => _fontAsset;
/// Styles that are forced on for this font,
/// e.g. smallcaps for a font without lower case characters
public FontStyles FontStyle { get; }
public FontStyles FontStyle => _fontStyle;
public bool Bold => (FontStyle & FontStyles.Bold) != 0;
public bool Bold => (_fontStyle & FontStyles.Bold) != 0;
public bool Italic => (FontStyle & FontStyles.Italic) != 0;
public bool Italic => (_fontStyle & FontStyles.Italic) != 0;
public bool Underline => (FontStyle & FontStyles.Underline) != 0;
public bool Underline => (_fontStyle & FontStyles.Underline) != 0;
public bool SmallCaps => (FontStyle & FontStyles.SmallCaps) != 0;
public bool SmallCaps => (_fontStyle & FontStyles.SmallCaps) != 0;
/// Styles that are forced off for this font,
/// e.g. underline for a font with no underscore character
public FontStyles FontStyleMask { get; }
public FontStyles FontStyleMask => _fontStyleMask;
public bool BoldMask => (FontStyleMask & FontStyles.Bold) != 0;
public bool BoldMask => (_fontStyleMask & FontStyles.Bold) != 0;
public bool ItalicMask => (FontStyleMask & FontStyles.Italic) != 0;
public bool ItalicMask => (_fontStyleMask & FontStyles.Italic) != 0;
public bool UnderlineMask => (FontStyleMask & FontStyles.Underline) != 0;
public bool UnderlineMask => (_fontStyleMask & FontStyles.Underline) != 0;
public bool SmallCapsMask => (FontStyleMask & FontStyles.SmallCaps) != 0;
public bool SmallCapsMask => (_fontStyleMask & FontStyles.SmallCaps) != 0;
public DecalFont(ConfigNode node, IEnumerable<TMP_FontAsset> fontAssets) {
public static DecalFont Parse(ConfigNode node, IEnumerable<TMP_FontAsset> fontAssets) {
if (node == null) throw new ArgumentNullException(nameof(node));
if (fontAssets == null) throw new ArgumentNullException(nameof(fontAssets));
var font = ScriptableObject.CreateInstance<DecalFont>();
var name = ParseUtil.ParseString(node, "name");
FontAsset = fontAssets.First(o => o.name == name);
if (FontAsset == null) {
var fontAsset = fontAssets.First(o => o.name == name);
if (fontAsset == null) {
throw new FormatException($"Could not find font asset named {name}");
}
Title = ParseUtil.ParseString(node, "title", true, name);
FontStyle = (FontStyles) ParseUtil.ParseInt(node, "style", true);
FontStyleMask = (FontStyles) ParseUtil.ParseInt(node, "styleMask", true);
}
font._fontAsset = fontAsset;
font._title = ParseUtil.ParseString(node, "title", true, name);
font._fontStyle = (FontStyles) ParseUtil.ParseInt(node, "style", true);
font._fontStyleMask = (FontStyles) ParseUtil.ParseInt(node, "styleMask", true);
return font;
}
public void SetupSample(TMP_Text tmp) {
if (tmp == null) throw new ArgumentNullException(nameof(tmp));
@ -95,5 +105,13 @@ namespace ConformalDecals.Text {
public static bool operator !=(DecalFont left, DecalFont right) {
return !Equals(left, right);
}
public void OnBeforeSerialize() { }
public void OnAfterDeserialize() { }
public override string ToString() {
return _title;
}
}
}

@ -1,21 +1,39 @@
using System;
using System.Text.RegularExpressions;
using TMPro;
namespace ConformalDecals.Text {
public class DecalText : IEquatable<DecalText> {
private readonly string _text;
private readonly DecalFont _font;
private readonly FontStyles _style;
private readonly bool _vertical;
private readonly float _lineSpacing;
private readonly float _charSpacing;
/// Raw text contents
public string Text { get; }
public string Text => _text;
/// Font asset used by this text snippet
public DecalFont Font { get; }
public DecalFont Font => _font;
/// Style used by this text snippet
public DecalTextStyle Style { get; }
public FontStyles Style => _style;
/// If this text snippet is vertical
public bool Vertical => _vertical;
/// The text snippet's line spacing
public float LineSpacing => _lineSpacing;
/// The text snippet's character spacing
public float CharSpacing => _charSpacing;
/// The text formatted with newlines for vertical text
public string FormattedText {
get {
if (Style.Vertical) {
if (string.IsNullOrWhiteSpace(Text)) return "•";
if (Vertical) {
return Regex.Replace(Text, @"(.)", "$1\n");
}
else {
@ -24,17 +42,22 @@ namespace ConformalDecals.Text {
}
}
public DecalText(string text, DecalFont font, DecalTextStyle style) {
public DecalText(string text, DecalFont font, FontStyles style, bool vertical, float linespacing, float charspacing) {
if (font == null) throw new ArgumentNullException(nameof(font));
Text = text;
Font = font;
Style = style;
_text = text;
_font = font;
_style = style;
_vertical = vertical;
_lineSpacing = linespacing;
_charSpacing = charspacing;
}
public bool Equals(DecalText other) {
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Text == other.Text && Equals(Font, other.Font) && Style.Equals(other.Style);
return _text == other._text && Equals(_font, other._font) && _style == other._style && _vertical == other._vertical && _lineSpacing.Equals(other._lineSpacing) &&
_charSpacing.Equals(other._charSpacing);
}
public override bool Equals(object obj) {
@ -46,9 +69,12 @@ namespace ConformalDecals.Text {
public override int GetHashCode() {
unchecked {
var hashCode = (Text != null ? Text.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Font != null ? Font.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ Style.GetHashCode();
var hashCode = (_text != null ? _text.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (_font != null ? _font.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (int) _style;
hashCode = (hashCode * 397) ^ _vertical.GetHashCode();
hashCode = (hashCode * 397) ^ _lineSpacing.GetHashCode();
hashCode = (hashCode * 397) ^ _charSpacing.GetHashCode();
return hashCode;
}
}
@ -60,5 +86,9 @@ namespace ConformalDecals.Text {
public static bool operator !=(DecalText left, DecalText right) {
return !Equals(left, right);
}
public override string ToString() {
return $"{nameof(_text)}: {_text}, {nameof(_font)}: {_font}, {nameof(_style)}: {_style}, {nameof(_vertical)}: {_vertical}, {nameof(_lineSpacing)}: {_lineSpacing}, {nameof(_charSpacing)}: {_charSpacing}";
}
}
}

@ -1,101 +0,0 @@
using System;
using TMPro;
using UnityEngine;
// ReSharper disable NonReadonlyMemberInGetHashCode
namespace ConformalDecals.Text {
public struct DecalTextStyle : IEquatable<DecalTextStyle> {
private FontStyles _fontStyle;
private bool _vertical;
private float _lineSpacing;
private float _charSpacing;
public FontStyles FontStyle {
get => _fontStyle;
set => _fontStyle = value;
}
public bool Bold {
get => (FontStyle & FontStyles.Bold) != 0;
set {
if (value) FontStyle |= FontStyles.Bold;
else FontStyle &= ~FontStyles.Bold;
}
}
public bool Italic {
get => (FontStyle & FontStyles.Italic) != 0;
set {
if (value) FontStyle |= FontStyles.Italic;
else FontStyle &= ~FontStyles.Italic;
}
}
public bool Underline {
get => (FontStyle & FontStyles.Underline) != 0;
set {
if (value) FontStyle |= FontStyles.Underline;
else FontStyle &= ~FontStyles.Underline;
}
}
public bool SmallCaps {
get => (FontStyle & FontStyles.SmallCaps) != 0;
set {
if (value) FontStyle |= FontStyles.SmallCaps;
else FontStyle &= ~FontStyles.SmallCaps;
}
}
public bool Vertical {
get => _vertical;
set => _vertical = value;
}
public float LineSpacing {
get => _lineSpacing;
set => _lineSpacing = value;
}
public float CharSpacing {
get => _charSpacing;
set => _charSpacing = value;
}
public DecalTextStyle(FontStyles fontStyle, bool vertical, float lineSpacing, float charSpacing) {
_fontStyle = fontStyle;
_vertical = vertical;
_lineSpacing = lineSpacing;
_charSpacing = charSpacing;
}
public bool Equals(DecalTextStyle other) {
return FontStyle == other.FontStyle && Vertical == other.Vertical &&
Mathf.Approximately(LineSpacing, other.LineSpacing) &&
Mathf.Approximately(CharSpacing, other.CharSpacing);
}
public override bool Equals(object obj) {
return obj is DecalTextStyle other && Equals(other);
}
public override int GetHashCode() {
unchecked {
var hashCode = (int) FontStyle;
hashCode = (hashCode * 397) ^ Vertical.GetHashCode();
hashCode = (hashCode * 397) ^ LineSpacing.GetHashCode();
hashCode = (hashCode * 397) ^ CharSpacing.GetHashCode();
return hashCode;
}
}
public static bool operator ==(DecalTextStyle left, DecalTextStyle right) {
return left.Equals(right);
}
public static bool operator !=(DecalTextStyle left, DecalTextStyle right) {
return !left.Equals(right);
}
}
}

@ -1,6 +1,5 @@
using System.IO;
using System.Collections;
using System.Collections.Generic;
using ConformalDecals.Util;
using TMPro;
using UniLinq;

@ -1,35 +0,0 @@
using System;
using UnityEngine.Events;
namespace ConformalDecals.Text {
public class TextRenderJob {
public DecalText OldText { get; }
public DecalText NewText { get; }
public bool Needed { get; private set; }
public bool IsStarted { get; private set; }
public bool IsDone { get; private set; }
public readonly TextRenderer.TextRenderEvent onRenderFinished = new TextRenderer.TextRenderEvent();
public TextRenderJob(DecalText oldText, DecalText newText, UnityAction<TextRenderOutput> renderFinishedCallback) {
OldText = oldText;
NewText = newText ?? throw new ArgumentNullException(nameof(newText));
Needed = true;
if (renderFinishedCallback != null) onRenderFinished.AddListener(renderFinishedCallback);
}
public void Cancel() {
Needed = false;
}
public void Start() {
IsStarted = true;
}
public void Finish(TextRenderOutput output) {
IsDone = true;
onRenderFinished.Invoke(output);
}
}
}

@ -9,7 +9,7 @@ namespace ConformalDecals.Text {
/// The rectangle that the rendered text takes up within the texture
public Rect Window { get; private set; }
/// The number of users for this render output. If 0, it can be discarded from the cache and the texture reused
/// The number of users for this render output. If 0, it can be discarded from the cache
public int UserCount { get; set; }
public TextRenderOutput(Texture2D texture, Rect window) {

@ -3,16 +3,12 @@ using System.Collections.Generic;
using ConformalDecals.Util;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Rendering;
using Object = UnityEngine.Object;
namespace ConformalDecals.Text {
// TODO: Testing shows the job system is unnecessary, so remove job system code.
/// Class handing text rendering.
/// Is a singleton referencing a single gameobject in the scene which contains the TextMeshPro component
[KSPAddon(KSPAddon.Startup.Instantly, true)]
public class TextRenderer : MonoBehaviour {
public static class TextRenderer {
/// Texture format used for returned textures.
/// Unfortunately due to how Unity textures work, this cannot be R8 or Alpha8,
/// so theres always a superfluous green channel using memory
@ -22,161 +18,73 @@ namespace ConformalDecals.Text {
/// Overriden below to be ARGB32 on DirectX because DirectX is dumb
public static RenderTextureFormat textRenderTextureFormat = RenderTextureFormat.R8;
/// The text renderer object within the scene which contains the TextMeshPro component used for rendering.
public static TextRenderer Instance {
get {
if (!_instance._isSetup) {
_instance.Setup();
}
return _instance;
}
}
/// Text Render unityevent, used with the job system to signal render completion
[Serializable]
public class TextRenderEvent : UnityEvent<TextRenderOutput> { }
private const string ShaderName = "ConformalDecals/Text Blit";
private const int MaxTextureSize = 4096;
private const float FontSize = 100;
private const float PixelDensity = 5;
private static TextRenderer _instance;
private bool _isSetup;
private TextMeshPro _tmp;
private Shader _blitShader;
private static Shader _blitShader;
private static Texture2D _blankTexture;
private static readonly Dictionary<DecalText, TextRenderOutput> RenderCache = new Dictionary<DecalText, TextRenderOutput>();
private static readonly Queue<TextRenderJob> RenderJobs = new Queue<TextRenderJob>();
/// Update text using the job queue
public static TextRenderJob UpdateText(DecalText oldText, DecalText newText, UnityAction<TextRenderOutput> renderFinishedCallback) {
/// Update text immediately without using job queue
public static TextRenderOutput UpdateText(DecalText oldText, DecalText newText) {
if (newText == null) throw new ArgumentNullException(nameof(newText));
var job = new TextRenderJob(oldText, newText, renderFinishedCallback);
RenderJobs.Enqueue(job);
return job;
}
if (!(oldText is null)) UnregisterText(oldText);
/// Update text immediately without using job queue
public static TextRenderOutput UpdateTextNow(DecalText oldText, DecalText newText) {
if (newText == null) throw new ArgumentNullException(nameof(newText));
// now that all old references are handled, begin rendering the new output
if (!RenderCache.TryGetValue(newText, out var renderOutput)) {
renderOutput = RenderText(newText);
RenderCache.Add(newText, renderOutput);
}
return Instance.RunJob(new TextRenderJob(oldText, newText, null), out _);
renderOutput.UserCount++;
return renderOutput;
}
/// Unregister a user of a piece of text
public static void UnregisterText(DecalText text) {
if (text == null) throw new ArgumentNullException(nameof(text));
if (RenderCache.TryGetValue(text, out var renderedText)) {
renderedText.UserCount--;
if (renderedText.UserCount <= 0) {
RenderCache.Remove(text);
Destroy(renderedText.Texture);
var texture = renderedText.Texture;
if (texture != _blankTexture) Object.Destroy(texture);
}
}
}
private void Start() {
if (_instance != null) {
Logging.LogError("Duplicate TextRenderer created???");
}
Logging.Log("Creating TextRenderer Object");
_instance = this;
DontDestroyOnLoad(gameObject);
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D11 || SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12) {
textRenderTextureFormat = RenderTextureFormat.ARGB32; // DirectX is dumb
}
if (!SystemInfo.SupportsTextureFormat(textTextureFormat)) {
Logging.LogError($"Text texture format {textTextureFormat} not supported on this platform.");
}
if (!SystemInfo.SupportsRenderTextureFormat(textRenderTextureFormat)) {
Logging.LogError($"Text texture format {textRenderTextureFormat} not supported on this platform.");
}
}
/// Setup this text renderer instance for rendering
private void Setup() {
if (_isSetup) return;
Logging.Log("Setting Up TextRenderer Object");
_tmp = gameObject.AddComponent<TextMeshPro>();
_tmp.renderer.enabled = false; // dont automatically render
_blitShader = Shabby.Shabby.FindShader(ShaderName);
if (_blitShader == null) Logging.LogError($"Could not find text blit shader named '{ShaderName}'");
_isSetup = true;
}
/// Run a text render job
private TextRenderOutput RunJob(TextRenderJob job, out bool renderNeeded) {
if (!job.Needed) {
renderNeeded = false;
return null;
}
job.Start();
Texture2D texture = null;
if (job.OldText != null && RenderCache.TryGetValue(job.OldText, out var oldRender)) {
// old output still exists
oldRender.UserCount--;
if (oldRender.UserCount <= 0) {
// this is the only usage of this output, so we are free to re-render into the texture
texture = oldRender.Texture;
RenderCache.Remove(job.OldText);
}
}
// now that all old references are handled, begin rendering the new output
if (RenderCache.TryGetValue(job.NewText, out var renderOutput)) {
renderNeeded = false;
}
else {
renderNeeded = true;
renderOutput = RenderText(job.NewText, texture);
RenderCache.Add(job.NewText, renderOutput);
}
renderOutput.UserCount++;
job.Finish(renderOutput);
return renderOutput;
}
/// Render a piece of text to a given texture
public TextRenderOutput RenderText(DecalText text, Texture2D texture) {
public static TextRenderOutput RenderText(DecalText text) {
if (text == null) throw new ArgumentNullException(nameof(text));
if (_tmp == null) throw new InvalidOperationException("TextMeshPro object not yet created.");
var tmpObject = new GameObject("Text Mesh Pro renderer");
var tmp = tmpObject.AddComponent<TextMeshPro>();
// SETUP TMP OBJECT FOR RENDERING
_tmp.text = text.FormattedText;
_tmp.font = text.Font.FontAsset;
_tmp.fontStyle = text.Style.FontStyle | text.Font.FontStyle;
_tmp.lineSpacing = text.Style.LineSpacing;
_tmp.characterSpacing = text.Style.CharSpacing;
_tmp.extraPadding = true;
_tmp.enableKerning = true;
_tmp.enableWordWrapping = false;
_tmp.overflowMode = TextOverflowModes.Overflow;
_tmp.alignment = TextAlignmentOptions.Center;
_tmp.fontSize = FontSize;
tmp.text = text.FormattedText;
tmp.font = text.Font.FontAsset;
tmp.fontStyle = text.Style | text.Font.FontStyle;
tmp.lineSpacing = text.LineSpacing;
tmp.characterSpacing = text.CharSpacing;
tmp.extraPadding = true;
tmp.enableKerning = true;
tmp.enableWordWrapping = false;
tmp.overflowMode = TextOverflowModes.Overflow;
tmp.alignment = TextAlignmentOptions.Center;
tmp.fontSize = FontSize;
// GENERATE MESH
_tmp.ClearMesh(false);
_tmp.ForceMeshUpdate();
tmp.ClearMesh(false);
tmp.ForceMeshUpdate();
var meshFilters = gameObject.GetComponentsInChildren<MeshFilter>();
var meshFilters = tmpObject.GetComponentsInChildren<MeshFilter>();
var meshes = new Mesh[meshFilters.Length];
var materials = new Material[meshFilters.Length];
@ -187,9 +95,9 @@ namespace ConformalDecals.Text {
var renderer = meshFilters[i].gameObject.GetComponent<MeshRenderer>();
meshes[i] = meshFilters[i].mesh;
if (i == 0) meshes[i] = _tmp.mesh;
if (i == 0) meshes[i] = tmp.mesh;
materials[i] = Instantiate(renderer.material);
materials[i] = Object.Instantiate(renderer.material);
materials[i].shader = _blitShader;
if (renderer == null) throw new FormatException($"Object {meshFilters[i].gameObject.name} has filter but no renderer");
@ -205,14 +113,18 @@ namespace ConformalDecals.Text {
// CALCULATE SIZES
var size = bounds.size * PixelDensity;
size.x = Mathf.Max(size.x, 0.1f);
size.y = Mathf.Max(size.y, 0.1f);
var textureSize = new Vector2Int {
x = Mathf.NextPowerOfTwo((int) size.x),
y = Mathf.NextPowerOfTwo((int) size.y)
};
if (textureSize.x == 0 || textureSize.y == 0) {
Logging.LogWarning("No text present or error in texture size calculation. Aborting.");
return new TextRenderOutput(Texture2D.blackTexture, Rect.zero);
Logging.LogError("No text present or error in texture size calculation. Aborting.");
Object.Destroy(tmpObject);
return new TextRenderOutput(_blankTexture, Rect.zero);
}
// make sure texture isnt too big, scale it down if it is
@ -237,12 +149,7 @@ namespace ConformalDecals.Text {
};
// SETUP TEXTURE
if (texture == null) {
texture = new Texture2D(textureSize.x, textureSize.y, textTextureFormat, true);
}
else if (texture.width != textureSize.x || texture.height != textureSize.y || texture.format != textTextureFormat) {
texture.Resize(textureSize.x, textureSize.y, textTextureFormat, true);
}
var texture = new Texture2D(textureSize.x, textureSize.y, textTextureFormat, false);
// GENERATE PROJECTION MATRIX
var halfSize = (Vector2) textureSize / PixelDensity / 2 / sizeRatio;
@ -250,13 +157,13 @@ namespace ConformalDecals.Text {
bounds.center.y - halfSize.y, bounds.center.y + halfSize.y, -1, 1);
// GET RENDERTEX
var renderTex = RenderTexture.GetTemporary(textureSize.x, textureSize.y, 0, textRenderTextureFormat, RenderTextureReadWrite.Linear, 1);
renderTex.autoGenerateMips = false;
var renderTex = RenderTexture.GetTemporary(textureSize.x, textureSize.y, 0, textRenderTextureFormat, RenderTextureReadWrite.Linear);
// RENDER
Graphics.SetRenderTarget(renderTex);
GL.PushMatrix();
GL.LoadProjectionMatrix(matrix);
GL.LoadIdentity();
GL.Clear(false, true, Color.black);
for (var i = 0; i < meshes.Length; i++) {
@ -266,22 +173,42 @@ namespace ConformalDecals.Text {
}
}
GL.PopMatrix();
// COPY TEXTURE BACK INTO RAM
// COPY RENDERTEX INTO TEXTURE
var prevRT = RenderTexture.active;
RenderTexture.active = renderTex;
texture.ReadPixels(new Rect(0, 0, textureSize.x, textureSize.y), 0, 0, true);
texture.Apply();
texture.ReadPixels(new Rect(0, 0, textureSize.x, textureSize.y), 0, 0, false);
texture.Apply(false, true);
RenderTexture.active = prevRT;
GL.PopMatrix();
// RELEASE RENDERTEX
RenderTexture.ReleaseTemporary(renderTex);
// CLEAR SUBMESHES
for (int i = 0; i < transform.childCount; i++) {
Destroy(transform.GetChild(i).gameObject);
}
// DESTROY THE RENDERER OBJECT
Object.Destroy(tmpObject);
return new TextRenderOutput(texture, window);
}
/// Setup shader and texture
public static void ModuleManagerPostLoad() {
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D11 || SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12) {
textRenderTextureFormat = RenderTextureFormat.ARGB32; // DirectX is dumb
}
if (!SystemInfo.SupportsTextureFormat(textTextureFormat)) {
Logging.LogError($"Text texture format {textTextureFormat} not supported on this platform.");
}
if (!SystemInfo.SupportsRenderTextureFormat(textRenderTextureFormat)) {
Logging.LogError($"Text texture format {textRenderTextureFormat} not supported on this platform.");
}
_blankTexture = Texture2D.blackTexture;
_blitShader = Shabby.Shabby.FindShader(ShaderName);
if (_blitShader == null) Logging.LogError($"Could not find text blit shader named '{ShaderName}'");
}
}
}

@ -3,15 +3,12 @@ using ConformalDecals.Text;
using ConformalDecals.Util;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
namespace ConformalDecals.UI {
public class TextEntryController : MonoBehaviour {
[Serializable]
public class TextUpdateEvent : UnityEvent<string, DecalFont, DecalTextStyle> { }
[SerializeField] public TextUpdateEvent onValueChanged = new TextUpdateEvent();
public delegate void TextUpdateDelegate(string newText, DecalFont newFont, FontStyles style, bool vertical, float linespacing, float charspacing);
[SerializeField] private Selectable _textBox;
[SerializeField] private Button _fontButton;
@ -28,21 +25,29 @@ namespace ConformalDecals.UI {
[SerializeField] private Toggle _smallCapsButton;
[SerializeField] private Toggle _verticalButton;
private string _text;
private DecalFont _font;
private DecalTextStyle _style;
private Vector2 _lineSpacingRange;
private Vector2 _charSpacingRange;
private TMP_InputField _textBoxTMP;
private string _text;
private DecalFont _font;
private FontStyles _style;
private bool _vertical;
private float _lineSpacing;
private float _charSpacing;
private Vector2 _lineSpacingRange;
private Vector2 _charSpacingRange;
private TMP_InputField _textBoxTMP;
private FontMenuController _fontMenu;
private TextUpdateDelegate _onValueChanged;
private static int _lockCounter;
private bool _ignoreUpdates;
private bool _isLocked;
private string _lockString;
private bool _ignoreUpdates;
private bool _textUpdated;
public static TextEntryController Create(
string text, DecalFont font, DecalTextStyle style,
string text, DecalFont font, FontStyles style, bool vertical, float linespacing, float charspacing,
Vector2 lineSpacingRange, Vector2 charSpacingRange,
UnityAction<string, DecalFont, DecalTextStyle> textUpdateCallback) {
TextUpdateDelegate textUpdateCallback) {
var window = Instantiate(UILoader.TextEntryPrefab, MainCanvasUtil.MainCanvas.transform, true);
window.AddComponent<DragPanel>();
@ -52,9 +57,12 @@ namespace ConformalDecals.UI {
controller._text = text;
controller._font = font;
controller._style = style;
controller._vertical = vertical;
controller._lineSpacing = linespacing;
controller._charSpacing = charspacing;
controller._lineSpacingRange = lineSpacingRange;
controller._charSpacingRange = charSpacingRange;
controller.onValueChanged.AddListener(textUpdateCallback);
controller._onValueChanged = textUpdateCallback;
return controller;
}
@ -64,10 +72,21 @@ namespace ConformalDecals.UI {
Destroy(gameObject);
}
public void SetControlLock(string value = null) {
if (_isLocked) return;
InputLockManager.SetControlLock(ControlTypes.EDITOR_UI, _lockString);
_isLocked = true;
}
public void RemoveControlLock(string value = null) {
if (!_isLocked) return;
InputLockManager.RemoveControlLock(_lockString);
_isLocked = false;
}
public void OnTextUpdate(string newText) {
this._text = newText;
OnValueChanged();
_textUpdated = true;
}
public void OnFontMenu() {
@ -81,104 +100,123 @@ namespace ConformalDecals.UI {
font.SetupSample(_fontButton.GetComponentInChildren<TextMeshProUGUI>());
_textBoxTMP.text = _text;
_textBoxTMP.textComponent.fontStyle = _style.FontStyle | _font.FontStyle & ~_font.FontStyleMask;
_textBoxTMP.textComponent.fontStyle = _style | _font.FontStyle & ~_font.FontStyleMask;
_textBoxTMP.fontAsset = _font.FontAsset;
UpdateStyleButtons();
OnValueChanged();
_textUpdated = true;
}
public void OnLineSpacingUpdate(float value) {
if (_ignoreUpdates) return;
_style.LineSpacing = Mathf.Lerp(_lineSpacingRange.x, _lineSpacingRange.y, value);
_lineSpacing = Mathf.Lerp(_lineSpacingRange.x, _lineSpacingRange.y, value);
UpdateLineSpacing();
OnValueChanged();
_textUpdated = true;
}
public void OnLineSpacingUpdate(string text) {
if (_ignoreUpdates) return;
if (float.TryParse(text, out var value)) {
_style.LineSpacing = Mathf.Clamp(value, _lineSpacingRange.x, _lineSpacingRange.y);
_lineSpacing = Mathf.Clamp(value, _lineSpacingRange.x, _lineSpacingRange.y);
}
else {
Logging.LogWarning("Line spacing value '{text}' could not be parsed.");
}
UpdateLineSpacing();
OnValueChanged();
_textUpdated = true;
}
public void OnCharSpacingUpdate(float value) {
if (_ignoreUpdates) return;
_style.CharSpacing = Mathf.Lerp(_charSpacingRange.x, _charSpacingRange.y, value);
_charSpacing = Mathf.Lerp(_charSpacingRange.x, _charSpacingRange.y, value);
UpdateCharSpacing();
OnValueChanged();
_textUpdated = true;
}
public void OnCharSpacingUpdate(string text) {
if (_ignoreUpdates) return;
if (float.TryParse(text, out var value)) {
_style.CharSpacing = Mathf.Clamp(value, _charSpacingRange.x, _charSpacingRange.y);
_charSpacing = Mathf.Clamp(value, _charSpacingRange.x, _charSpacingRange.y);
}
else {
Logging.LogWarning("Char spacing value '{text}' could not be parsed.");
}
UpdateCharSpacing();
OnValueChanged();
_textUpdated = true;
}
public void OnBoldUpdate(bool state) {
if (_ignoreUpdates) return;
_style.Bold = state;
_textBoxTMP.textComponent.fontStyle = _style.FontStyle | _font.FontStyle & ~_font.FontStyleMask;
OnValueChanged();
if (state)
_style |= FontStyles.Bold;
else
_style &= ~FontStyles.Bold;
_textBoxTMP.textComponent.fontStyle = _style | _font.FontStyle & ~_font.FontStyleMask;
_textUpdated = true;
}
public void OnItalicUpdate(bool state) {
if (_ignoreUpdates) return;
_style.Italic = state;
_textBoxTMP.textComponent.fontStyle = _style.FontStyle | _font.FontStyle & ~_font.FontStyleMask;
OnValueChanged();
if (state)
_style |= FontStyles.Italic;
else
_style &= ~FontStyles.Italic;
_textBoxTMP.textComponent.fontStyle = _style | _font.FontStyle & ~_font.FontStyleMask;
_textUpdated = true;
}
public void OnUnderlineUpdate(bool state) {
if (_ignoreUpdates) return;
_style.Underline = state;
_textBoxTMP.textComponent.fontStyle = _style.FontStyle | _font.FontStyle & ~_font.FontStyleMask;
OnValueChanged();
if (state)
_style |= FontStyles.Underline;
else
_style &= ~FontStyles.Underline;
_textBoxTMP.textComponent.fontStyle = _style | _font.FontStyle & ~_font.FontStyleMask;
_textUpdated = true;
}
public void OnSmallCapsUpdate(bool state) {
if (_ignoreUpdates) return;
_style.SmallCaps = state;
_textBoxTMP.textComponent.fontStyle = _style.FontStyle | _font.FontStyle & ~_font.FontStyleMask;
OnValueChanged();
if (state)
_style |= FontStyles.SmallCaps;
else
_style &= ~FontStyles.SmallCaps;
_textBoxTMP.textComponent.fontStyle = _style | _font.FontStyle & ~_font.FontStyleMask;
_textUpdated = true;
}
public void OnVerticalUpdate(bool state) {
if (_ignoreUpdates) return;
_style.Vertical = state;
OnValueChanged();
}
_vertical = state;
_textUpdated = true;
}
private void Start() {
_lockString = $"ConformalDecals_TextEditor_{_lockCounter++}";
_textBoxTMP = ((TMP_InputField) _textBox);
_textBoxTMP.text = _text;
_textBoxTMP.textComponent.fontStyle = _style.FontStyle | _font.FontStyle & ~_font.FontStyleMask;
_textBoxTMP.textComponent.fontStyle = _style | _font.FontStyle & ~_font.FontStyleMask;
_textBoxTMP.fontAsset = _font.FontAsset;
_textBoxTMP.onSelect.AddListener(SetControlLock);
_textBoxTMP.onDeselect.AddListener(RemoveControlLock);
_font.SetupSample(_fontButton.GetComponentInChildren<TextMeshProUGUI>());
@ -187,8 +225,15 @@ namespace ConformalDecals.UI {
UpdateCharSpacing();
}
private void OnValueChanged() {
onValueChanged.Invoke(_text, _font, _style);
private void OnDestroy() {
RemoveControlLock();
}
private void LateUpdate() {
if (_textUpdated) {
_onValueChanged(_text, _font, _style, _vertical, _lineSpacing, _charSpacing);
_textUpdated = false;
}
}
private void UpdateStyleButtons() {
@ -204,7 +249,7 @@ namespace ConformalDecals.UI {
}
else {
_boldButton.interactable = true;
_boldButton.isOn = _style.Bold;
_boldButton.isOn = (_style & FontStyles.Bold) != 0;
}
if (_font.Italic) {
@ -217,7 +262,7 @@ namespace ConformalDecals.UI {
}
else {
_italicButton.interactable = true;
_italicButton.isOn = _style.Italic;
_italicButton.isOn = (_style & FontStyles.Italic) != 0;
}
if (_font.Underline) {
@ -230,7 +275,7 @@ namespace ConformalDecals.UI {
}
else {
_underlineButton.interactable = true;
_underlineButton.isOn = _style.Underline;
_underlineButton.isOn = (_style & FontStyles.Underline) != 0;
}
if (_font.SmallCaps) {
@ -243,10 +288,10 @@ namespace ConformalDecals.UI {
}
else {
_smallCapsButton.interactable = true;
_smallCapsButton.isOn = _style.SmallCaps;
_smallCapsButton.isOn = (_style & FontStyles.SmallCaps) != 0;
}
_verticalButton.isOn = _style.Vertical;
_verticalButton.isOn = _vertical;
_ignoreUpdates = false;
}
@ -254,8 +299,8 @@ namespace ConformalDecals.UI {
private void UpdateLineSpacing() {
_ignoreUpdates = true;
_lineSpacingSlider.value = Mathf.InverseLerp(_lineSpacingRange.x, _lineSpacingRange.y, _style.LineSpacing);
((TMP_InputField) _lineSpacingTextBox).text = $"{_style.LineSpacing:F1}";
_lineSpacingSlider.value = Mathf.InverseLerp(_lineSpacingRange.x, _lineSpacingRange.y, _lineSpacing);
((TMP_InputField) _lineSpacingTextBox).text = $"{_lineSpacing:F1}";
_ignoreUpdates = false;
}
@ -263,8 +308,8 @@ namespace ConformalDecals.UI {
private void UpdateCharSpacing() {
_ignoreUpdates = true;
_charSpacingSlider.value = Mathf.InverseLerp(_charSpacingRange.x, _charSpacingRange.y, _style.CharSpacing);
((TMP_InputField) _charSpacingTextBox).text = $"{_style.CharSpacing:F1}";
_charSpacingSlider.value = Mathf.InverseLerp(_charSpacingRange.x, _charSpacingRange.y, _charSpacing);
((TMP_InputField) _charSpacingTextBox).text = $"{_charSpacing:F1}";
_ignoreUpdates = false;
}

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using UniLinq;
using UnityEngine;
namespace ConformalDecals.Util {
@ -30,9 +31,15 @@ namespace ConformalDecals.Util {
}
public static string ParseString(ConfigNode node, string valueName, bool isOptional = false, string defaultValue = "") {
if (!node.HasValue(valueName)) throw new FormatException($"Missing value for {valueName}");
if (node.HasValue(valueName)) return node.GetValue(valueName);
if (isOptional) {
return defaultValue;
}
else {
throw new FormatException($"Missing value for {valueName}");
}
return node.GetValue(valueName);
}
public static bool ParseStringIndirect(ref string value, ConfigNode node, string valueName) {
@ -68,6 +75,14 @@ namespace ConformalDecals.Util {
return ParseValueIndirect(ref value, node, valueName, int.TryParse);
}
public static uint ParseUint(ConfigNode node, string valueName, bool isOptional = false, uint defaultValue = 0) {
return ParseValue(node, valueName, uint.TryParse, isOptional, defaultValue);
}
public static bool ParseUintIndirect(ref uint value, ConfigNode node, string valueName) {
return ParseValueIndirect(ref value, node, valueName, uint.TryParse);
}
public static Color32 ParseColor32(ConfigNode node, string valueName, bool isOptional = false, Color32 defaultValue = default) {
return ParseValue(node, valueName, TryParseColor32, isOptional, defaultValue);
}
@ -100,6 +115,15 @@ namespace ConformalDecals.Util {
return ParseValueIndirect(ref value, node, valueName, ParseExtensions.TryParseVector3);
}
public static Matrix4x4 ParseMatrix4x4(ConfigNode node, string valueName, bool isOptional = false, Matrix4x4 defaultValue = default) {
return ParseValue(node, valueName, ParseUtil.TryParseMatrix4x4, isOptional, defaultValue);
}
public static bool ParseMatrix4x4Indirect(ref Matrix4x4 value, ConfigNode node, string valueName) {
return ParseValueIndirect(ref value, node, valueName, ParseUtil.TryParseMatrix4x4);
}
public static T ParseValue<T>(ConfigNode node, string valueName, TryParseDelegate<T> tryParse, bool isOptional = false, T defaultValue = default) {
string valueString = node.GetValue(valueName);
@ -139,6 +163,26 @@ namespace ConformalDecals.Util {
throw new FormatException($"Improperly formatted {typeof(T)} value for {valueName} : '{valueString}");
}
public static bool TryParseMatrix4x4(string valueString, out Matrix4x4 value) {
value = new Matrix4x4();
var split = valueString.Split(Separator, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < split.Length; i++) {
split[i] = split[i].Trim();
}
if (split.Length != 16) return false;
int index = 0;
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 4; col++) {
if (!float.TryParse(split[index], out float component)) return false;
value[row, col] = component;
}
}
return true;
}
public static bool TryParseHexColor(string valueString, out Color32 value) {
value = new Color32(0, 0, 0, byte.MaxValue);

@ -1,8 +1,53 @@
v0.2.7
------
- Supported KSP versions: 1.8.x to 1.11.x
- Notes:
- Attaching decal parts in flight using engineer kerbals is not supported.
- Fixes:
- Fixed certain non-ascii strings not rendering correctly under certain circumstances.
- Yet another attempted fix for the planet text glitch.
v0.2.6
------
- Fixes:
- Fixed stock flags appearing stretched by forcing their aspect ratio to be correct.
- Another attempted fix for the planet text glitch.
v0.2.5
------
- Fixes:
- Fixed line spacing, character spacing, and vertical settings not applying to symmetry counterparts
v0.2.4
------
- Fixes:
- Fixed red text appearing on planets due to KSP bug by clearing render textures afterwards.
- Fixed fonts not saving correctly.
- Changes:
- Lowered step size for decal size and depth to 1cm.
- Changed default max size to 5m.
- Changed default text decal size to 0.2m
- Text decals now show as a circle if they contain only whitespace.
v0.2.3
------
- Fixes:
- Fixed TMP subobjects being deleted, causing fallback fonts to fail in some situations.
- Started using URL-style encoding for text decals behind the scenes to prevent issues with certain characters.
- Fixed text decals having zero size when they had only whitespace or an empty string.
- Fixed decals having drag and causing issues when using FAR.
- Fixed broken saving of text decals in certain circumstances.
v0.2.2
------
- Fixes:
- Fixed corrupted text rendering when a vessel loads during a scene change.
v0.2.1
------
- Changes
- Changes:
- Pressing enter in the text entry window now types a newline.
- Fixes
- Fixes:
- Renamed font assetbundle. The old extension was causing the game to try to load it twice on Windows due to legacy compatability features.
- Fixed text rendering on DirectX resulting in black boxes by using ARGB32 instead of RG16 for the render texture in DirectX.

Loading…
Cancel
Save