114 Commits

Author SHA1 Message Date
c653c9efc8 Release 0.2.11
### Fixed

- PR by LinuxGuruGamer:
	- Fixed nullref caused when an entry in `_targets` was null
	- Fixed memory leak caused by the OnDestroy() methods not being called due to them being virtual
2022-10-29 18:15:13 -07:00
374fc8b753 Format changelog 2022-10-29 18:13:46 -07:00
88b2b4841a Merge pull request #38 from linuxgurugamer/main
Nullref fix and memory leak fix
2022-10-05 22:53:10 -07:00
b2da56b1ca A few more edits 2022-09-03 18:03:01 -04:00
14bc694588 Fixed nullref caused when an entry in _targets was null
Fixed memory leak caused by the OnDestroy() methods not being called
	due to them being virtual
2022-09-03 18:01:15 -04:00
7e1b993d20 Update README.md 2022-03-19 20:34:33 -07:00
f8d692352d Remove leftover files from old deploy system 2022-03-14 21:52:43 -07:00
fa4b799788 Run on create 2022-03-13 19:12:18 -07:00
970a69be11 Release 0.2.10
### Fixed

- Fixed decals not projecting on loading prefabs

### Changed

- Re-enabled projecting onto TransparentFX layer

### Added

- Allowed for regular expressions to be used when blacklisting shaders
- Added all Waterfall shaders to the shader blacklist when Waterfall is present
2022-03-13 18:45:14 -07:00
dddb7f09f3 make log message make a bit more sense 2022-03-13 18:43:00 -07:00
3cd229bc23 Fix decals not projecting when loading prefabs
• Add support for regex shader blacklisting
• Re-allow projecting onto transparentFX
2022-03-13 14:02:39 -07:00
4948818065 Remove Travis badge 2022-03-11 23:10:20 -08:00
036b084d34 Fix remote version file url 2022-03-11 22:49:03 -08:00
1e3addeb4d Include Harmony in build 2022-03-11 22:42:31 -08:00
47c70d3071 Fix actions 2022-03-11 22:36:19 -08:00
9955b9ce30 Don't version the Readme 2022-03-11 22:33:05 -08:00
32ddc54019 Release 0.2.9
### Fixed

- Fixed text decals breaking when used in symmetry
- Fixed decals projecting onto the TransparentFX layer, such as Waterfall plumes
2022-03-11 22:29:14 -08:00
ff262d55c8 Automatically fast-forward the release branch on release 2022-03-11 22:28:15 -08:00
d1f3d1fa55 Merge branch 'release' 2022-03-11 22:10:05 -08:00
2965633235 Update changelog 2022-03-11 22:02:10 -08:00
a82369e595 Merge branch 'hotfix' 2022-03-11 21:57:18 -08:00
16c4fa2b96 Github mandates a .txt extension for text files??? 2022-03-11 21:31:45 -08:00
591ec0aa74 Setup version URL from releases
this is going to 404 until the next release but oh well
2022-03-11 21:28:14 -08:00
210d326469 Last touches 2022-03-10 19:31:16 -08:00
dd405a21db Fix speeling 2022-03-10 19:05:26 -08:00
c40f700235 Fix both deployment steps
thanks @DasSkelett!
2022-03-10 18:39:36 -08:00
36cc896b2a Fix file 2022-03-09 22:07:32 -08:00
4c02e91dfd Fix spacedock login 2022-03-09 22:05:26 -08:00
41b15477fb More shenanigans 2022-03-09 22:03:06 -08:00
b61f71bc00 github why 2022-03-09 21:53:46 -08:00
74fe42a7ff why 2022-03-09 21:37:22 -08:00
7fa8969d5b wtf 2022-03-09 21:36:33 -08:00
21f8332d66 Fix publish and artifact handling 2022-03-09 21:22:05 -08:00
cb219a52c0 Don't try to validate other mods version info 2022-03-09 21:03:38 -08:00
f2f2100334 fix spelling 2022-03-09 21:00:27 -08:00
9bdb95527a Fix python dependencies 2022-03-09 20:58:17 -08:00
ad504ce4cc Download dependencies and simple deploy script 2022-03-09 20:57:10 -08:00
18ebbd7b4c Pesky commas 2022-03-08 23:54:23 -08:00
ba189f18c4 Clean up version file and add some logging 2022-03-08 23:52:40 -08:00
322aaa613e Add script for updating version 2022-03-08 23:43:33 -08:00
5443377bfe Descriptive artifact name 2022-03-07 00:29:39 -08:00
1ed6dc0f68 Fix path 2022-03-07 00:28:00 -08:00
90dec1b42a Simplify uploading and ensure Plugin directory exists 2022-03-07 00:24:46 -08:00
80da98d95a Fix DLL copy snippet 2022-03-07 00:17:21 -08:00
76016fbbf1 Case sensitivity is evil 2022-03-07 00:10:10 -08:00
53657b8fad Fix zip command and name the artefact 2022-03-07 00:08:43 -08:00
9d7502091c Upload build output 2022-03-07 00:06:16 -08:00
f788c25837 Remove DLL from repo 2022-03-07 00:06:07 -08:00
017110738b correct dll location 2022-03-06 23:52:03 -08:00
fd7134ece9 Actually use the right command 2022-03-06 23:52:03 -08:00
68ceacfef4 URL is case sensitive 2022-03-06 23:52:03 -08:00
a452844cd1 Start on build script 2022-03-06 23:52:03 -08:00
4b8d11e1de Use markdown changelog 2022-03-06 23:52:03 -08:00
8f888ee552 Remove travis config 2022-03-06 23:52:03 -08:00
95b99d1d42 Clean up text update function 2022-03-06 00:01:23 -08:00
ba6676b625 Hide NRE warning in Rider
its terrible but I've never seen it NRE so 🤷‍♂️
2022-03-05 23:44:59 -08:00
495441be06 Fix text not updating correctly in symmetry 2022-03-05 23:38:12 -08:00
8025a0a418 Ignore thumbnails 2022-02-24 23:33:34 -08:00
760609fae2 Refactor flag decal
Not exhaustively tested but shouldnt be different from before
2022-02-24 23:33:07 -08:00
ecc60751f7 Don't project onto TransparentFX layer 2021-12-25 23:15:15 -08:00
e10b7e4b51 Merge branch 'main' into release 2021-03-18 04:27:11 -07:00
a91a83a280 Update B9PartSwitch 2021-03-18 04:26:45 -07:00
316f92df2c Update shabby to use Harmony 2 2021-03-18 04:22:13 -07:00
938babb41b Merge branch 'main' into release 2020-12-19 17:08:13 -08:00
3173dd914a Update version and remove debug statement 2020-12-19 17:06:52 -08:00
5f6712f476 Revert changes to ModuleConformalDecal.cs 2020-12-19 16:58:15 -08:00
6b7996fdd7 Text render simplification and small optimizations 2020-12-19 16:11:56 -08:00
5feb16dcfb Only update text once per frame
Fixed text re-rendering several times in a single frame when pasting in text
2020-12-18 21:14:34 -08:00
bf8e98caf0 Fix text rendering for some non-ascii strings 2020-12-17 16:14:33 -08:00
b634eb1e8e Update version and changelog 2020-12-16 13:04:46 -08:00
dadf38acd5 go back to using temporary rendertexs 2020-12-16 01:28:57 -08:00
f42e0d78d6 Don't reuse textures, and don't keep them in RAM
Hopefully fixes #28
2020-12-16 01:11:32 -08:00
1e7c6d81c9 Merge branch 'main' into release 2020-11-29 16:31:55 -08:00
dda988db17 Quick bugfix 2020-11-29 16:31:41 -08:00
900061f7f6 Merge branch 'main' into release 2020-11-29 16:09:03 -08:00
e56278c6cb Fix stock flags being stretched 2020-11-29 16:02:45 -08:00
2793f5fcb1 Fix DLL copying 2020-11-26 19:17:31 -08:00
833ec43a52 Update project files 2020-11-26 17:47:42 -08:00
e6856124e7 Another attempt at fixing the planet glitch 2020-11-25 02:44:04 -08:00
8ed7a130ab Alternate rendertex handling 2020-11-22 20:18:16 -08:00
d8d3d4ed92 Merge branch 'main' into release 2020-11-16 16:49:01 -08:00
334af786f6 Version change 2020-11-16 16:48:45 -08:00
17ef93bb6e Copy other text parameters to symmetry counterparts 2020-11-16 16:45:54 -08:00
a6d58690f9 Merge branch 'main' into release 2020-11-16 15:45:16 -08:00
a6de537e4a ScaleRange change 2020-11-16 15:44:40 -08:00
33b0307aa2 Lower text decal default size 2020-11-16 15:39:41 -08:00
121428414c Add input locks for text entry 2020-11-16 15:34:10 -08:00
98f774b2ae More font fixes and UI changes
- Lowered step size for decal size and depth to 1cm.
 - Changed default max size to 10m.
 - Text decals now show as a circle if they contain only whitespace.
 - Fixed font name in config and defaulted to Calibri if its missing
2020-11-16 15:05:55 -08:00
d31576fb0b Fix font saving and rendering 2020-11-16 14:44:07 -08:00
c9853049c5 Clear rendertex because KSP wont 2020-11-16 14:01:10 -08:00
f108341068 Merge branch 'main' into release 2020-11-14 21:26:28 -08:00
40d4e2cc8a Update changelog 2020-11-14 21:26:16 -08:00
fb0070f92f Merge branch 'main' into release 2020-11-14 21:22:56 -08:00
6f0c1f8ff5 Update Travis 2020-11-14 21:19:26 -08:00
4cf6de9693 Add defaults to text decal config 2020-11-14 21:17:54 -08:00
06137357c1 Close windows when text part is destroyed 2020-11-14 21:15:43 -08:00
dbbc621181 Fix text decal saving and loading
Closes #25
2020-11-14 21:11:16 -08:00
c6b9812fe3 Fix MM patch 2020-11-13 03:20:51 -08:00
8accabe9e5 Fix FAR incompatability 2020-11-13 02:22:56 -08:00
981a167864 Revert "Add fallbacks to all fonts, even squad ones"
This reverts commit ac1289a46e.
2020-11-13 01:55:42 -08:00
d4978b1b3c Update changelog 2020-11-13 01:44:52 -08:00
c42e443b4b Add minimum size for text decals 2020-11-13 01:43:08 -08:00
a6e2edc475 use URL-style string escaping 2020-11-13 01:42:55 -08:00
e82b02b0e5 Fix overlapping text and add text escaping 2020-11-12 21:25:24 -08:00
ea8c069d68 Fix issues with fallback fonts
Fixed TMP subobjects being deleted, causing fallback fonts to fail in some situations.
closes #24
2020-11-12 20:10:40 -08:00
ac1289a46e Add fallbacks to all fonts, even squad ones 2020-11-12 14:55:04 -08:00
16ef53ea65 remove lfs stuff from travis config 2020-10-14 20:08:25 -07:00
7b01848acc Merge branch 'release' into main 2020-10-11 16:55:18 -07:00
f37c3d57b7 For real this time 2020-10-11 16:49:59 -07:00
a937888c0d Fix deploy script 2020-10-11 16:48:10 -07:00
5065a8abf3 Merge branch 'main' into release 2020-10-11 16:21:34 -07:00
1ebed608a8 Fix corrupted text rendering
Fix text corruption when rendering text right after a scene change by delaying it by a single frame in OnLoad
2020-10-11 03:05:07 -07:00
98a790630e Remove call to get_dataPath from constructor
Fixes error in development build of KSP
2020-10-07 00:12:15 -07:00
ef90f73288 Update ConformalDecals.version 2020-10-04 21:03:46 -07:00
34 changed files with 986 additions and 825 deletions

23
.github/workflows/ff-release.yml vendored Normal file
View File

@ -0,0 +1,23 @@
name: Fast-Forward Release Branch
on:
release:
types: [created]
jobs:
fast-forward:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
ref: release
fetch-depth: 0
- name: Merge into Release
run: git merge ${{github.ref_name}} --ff-only
- name: Push Changes
uses: ad-m/github-push-action@master
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
branch: release

139
.github/workflows/ksp-publish.yml vendored Normal file
View File

@ -0,0 +1,139 @@
name: Build and Release
on: [ push ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Setup .NET Core SDK
uses: actions/setup-dotnet@v1.7.2
with:
dotnet-version: '6.0.x'
- name: Install Python Tools
run: |
python -m pip install --upgrade pip
python -m pip install yaclog yaclog-ksp
- name: Generate Version Info
run: |
echo "VERSION_TITLE=$(yaclog show -n)" >> $GITHUB_ENV
python Scripts/version.py
yaclog-ksp -n "Conformal Decals"
- name: Validate Version Info
uses: DasSkelett/AVC-VersionFileValidator@master
- name: Download DLL Dependencies
working-directory: Source
run: |
wget --user drewcassidy --password ${{ secrets.PILE_OF_ROCKS_PASS }} https://pileof.rocks/Secret/conformal-decals-dependencies-1.zip
unzip conformal-decals-dependencies-*.zip -d ConformalDecals/dlls
- name: Build DLL
working-directory: Source
run: |
mkdir -p ../GameData/ConformalDecals/Plugins
dotnet build --configuration Release ConformalDecals.sln
- name: Download KSP Dependencies
run: |
wget http://pileof.rocks/KSP/Shabby_v0.2.0.zip
wget https://ksp.sarbian.com/jenkins/job/ModuleManager/161/artifact/ModuleManager.4.2.1.dll
wget https://github.com/blowfishpro/B9PartSwitch/releases/download/v2.19.0/B9PartSwitch_v2.19.0.zip
wget https://github.com/KSPModdingLibs/HarmonyKSP/releases/download/2.0.4.0/HarmonyKSP_2.0.4.0_for_KSP1.8+.zip
unzip -d Shabby Shabby*.zip
unzip -d B9PartSwitch B9PartSwitch*.zip
unzip -d HarmonyKSP HarmonyKSP*.zip
mv Shabby/GameData/Shabby GameData/
mv ModuleManager*.dll GameData/
mv B9PartSwitch/GameData/B9PartSwitch GameData/
mv HarmonyKSP/GameData/000_Harmony GameData/
- name: Upload Unbundled Build
uses: actions/upload-artifact@v3
with:
name: ConformalDecals-unbundled
path: |
GameData/ConformalDecals
README.md
CHANGELOG.md
LICENSE-ART.md
LICENSE-SOURCE.md
- name: Upload Bundled Build
uses: actions/upload-artifact@v3
with:
name: ConformalDecals
path: |
GameData
README.md
CHANGELOG.md
LICENSE-ART.md
LICENSE-SOURCE.md
deploy:
needs: build
runs-on: ubuntu-latest
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags')
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install Python Tools
run: |
python -m pip install --upgrade pip
python -m pip install yaclog
- name: Get version name and body
run: |
echo "VERSION_TITLE=$(yaclog show -n)" >> $GITHUB_ENV
echo "$(yaclog show -mb)" >> RELEASE.md
- name: Download Build Artifacts
uses: actions/download-artifact@v3
- name: Zip Download Packages
run: |
mkdir bundled
mkdir unbundled
zip -r bundled/ConformalDecals-$VERSION_TITLE.zip ConformalDecals/*
zip -r unbundled/ConformalDecals-$VERSION_TITLE.zip ConformalDecals-unbundled/*
ls
- name: Publish to Spacedock
run: |
curl -F "username=drewcassidy" -F "password=${{ secrets.SPACEDOCK_PASS }}" \
-c ./cookies "https://spacedock.info/api/login"
curl -c ./cookies -b ./cookies \
-F "version=$VERSION_TITLE" \
-F "changelog=$(yaclog show -mb)" \
-F "game-version=1.12.3" \
-F "notify-followers=yes" \
-F "zipball=@bundled/ConformalDecals-$VERSION_TITLE.zip" \
"https://spacedock.info/api/mod/2451/update"
- name: Publish to Github
uses: softprops/action-gh-release@v1
with:
files: |
bundled/ConformalDecals-*.zip
ConformalDecals/GameData/ConformalDecals/Versioning/ConformalDecals.version
name: Conformal Decals ${{ env.VERSION_TITLE }}
body_path: RELEASE.md
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

5
.gitignore vendored
View File

@ -16,6 +16,9 @@ Temp/
GameData/ConformalDecals/Resources/Resources
GameData/ConformalDecals/Resources/*.manifest
# DLLs
GameData/ConformalDecals/Plugins
# Unity Project Files
PartTools.cfg
*.meta
@ -50,3 +53,5 @@ Source/ConformalDecals/bin
*.sublime*
.idea
obj
*.swp
@thumbs

View File

@ -1 +0,0 @@
USE_SSM_CREDENTIALS: false

View File

@ -1,30 +0,0 @@
# Example annotated build data file
mod-name: ConformalDecals
package:
include-dependencies: true # Include dependencies in the package
included-gamedata: # Include these gamedata-level folders in packages:
- ConformalDecals
included-support: # Include these root-level files in packages
- README.md
- LICENSE-ART.md
- LICENSE-SOURCE.md
- changelog.txt
dependencies: # Configure dependencies
ModuleManager:
location: url
url: https://ksp.sarbian.com/jenkins/job/ModuleManager/159/artifact/ModuleManager.4.1.4.dll
zip: false
B9PartSwitch:
location: url
url: http://pileof.rocks/KSP/B9PartSwitch-v2.16.0.zip
zip: true
Shabby:
location: url
url: http://taniwha.org/~bill/Shabby_v0.1.2.zip
zip: true
deploy:
SpaceDock:
enabled: true # activate/deactivate this deployment script
mod-id: 2451 # The Spacedock mod ID for deployment
GitHub:
enabled: true # activate/deactivate this deployment script

View File

@ -1,27 +0,0 @@
language: python
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
- cd build-deploy
- git checkout master
- cd ..
- pytest -s --testpath "GameData/" build-deploy/src/tests/ # run the deploy tests
- python build-deploy/src/package.py --f ".mod_data.yml" # Build package
before_deploy:
- python build-deploy/src/stage.py --f ".mod_data.yml" # Run the staging script
deploy:
- provider: script
script: python build-deploy/src/deploy.py --f ".mod_data.yml" # Deploy package to spacedock, curse, github
skip_cleanup: true
on:
branch: release

View File

@ -30,6 +30,8 @@ public class TextRenderTest : MonoBehaviour {
Debug.Log("starting...");
StartCoroutine(OnRender());
var thing = new GameObject();
thing.AddComponent<TextMeshPro>();
}
// Update is called once per frame

202
CHANGELOG.md Normal file
View File

@ -0,0 +1,202 @@
# Changelog
All notable changes to this project will be documented in this file
| modName | Conformal Decals |
| ------- |:-------------------------------------------------------------------------------------|
| license | CC-By-SA & GPL3 |
| website | https://forum.kerbalspaceprogram.com/index.php?/topic/194802-18-111-conformal-decals |
| author | Andrew Cassidy |
## 0.2.11 - 2022-10-30
### Fixed
- PR by LinuxGuruGamer:
- Fixed nullref caused when an entry in `_targets` was null
- Fixed memory leak caused by the OnDestroy() methods not being called due to them being virtual
## 0.2.10 - 2022-03-14
### Fixed
- Fixed decals not projecting on loading prefabs
### Changed
- Re-enabled projecting onto TransparentFX layer
### Added
- Allowed for regular expressions to be used when blacklisting shaders
- Added all Waterfall shaders to the shader blacklist when Waterfall is present
## 0.2.9 - 2022-03-12
### Fixed
- Fixed text decals breaking when used in symmetry
- Fixed decals projecting onto the TransparentFX layer, such as Waterfall plumes
## 0.2.8
- Update bundled Shabby to support Harmony 2 for compatibility with other mods
- Update bundled B9PartSwitch to 2.18.0
## 0.2.7
- Supported KSP versions: 1.8.x to 1.11.x
### Notes:
- Attaching decal parts in flight using engineer kerbals is not supported.
### Fixed:
- Fixed certain non-ascii strings not rendering correctly under certain circumstances.
- Yet another attempted fix for the planet text glitch.
## 0.2.6
### Fixed:
- Fixed stock flags appearing stretched by forcing their aspect ratio to be correct.
- Another attempted fix for the planet text glitch.
## 0.2.5
### Fixed:
- Fixed line spacing, character spacing, and vertical settings not applying to symmetry counterparts
## 0.2.4
### Fixed:
- Fixed red text appearing on planets due to KSP bug by clearing render textures afterwards.
- Fixed fonts not saving correctly.
### Changed:
- 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.
## 0.2.3
### Fixed:
- 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.
## 0.2.2
### Fixed:
- Fixed corrupted text rendering when a vessel loads during a scene change.
## 0.2.1
### Changed:
- Pressing enter in the text entry window now types a newline.
### Fixed:
- 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.
## 0.2.0
### New Parts:
- CDL-3 Surface Base Decal: A set of conformal decals based on the symbols from the movie Moon (2009) designed by Gavin Rothery
- CDL-T Custom Text Decal: A customizable text decal with a variety of fonts
### Changed:
- New ModuleConformalText module for customizable text
- Text, font, and style can all be customized, as well as text fill and outline colors and widths
- Same projection and opacity options as other conformal decals
- New StandardText decal shader supporting the text module
- Unified all decal shaders into a single "StandardDecal" shader with variants supporting any combination of bump, specular and emissive maps, plus SDF alphas.
- Old shaders are remapped to Standard shader plus keywords automatically.
- New SDF-based antialiasing for when decals extend to their borders, e.g. on opaque flags.
- New "KEYWORD" material modifier, allowing for shader features to be enabled and disabled.
- Material modifiers can now be removed in variants by setting `remove = true` inside them.
### Fixed:
- Fixed WIDTH and HEIGHT scale modes being flipped
- Removed some debug log statements
- Dependencies:
- Updated ModuleManager to version 4.1.4
## 0.1.4
Supported KSP versions: 1.8.x to 1.10.x
### Fixed:
- Fixed decals rendering onto disabled B9PS part variants
- Decals will still not update whan their parent part's B9PS variant is changed, both in flight and in the editor. This is known and awaiting a change to B9PS to be fixed.
- Fixed decal bounds rendering as dark cubes when shadowed by EVE clouds.
- Fixed decals being shadowed by EVE clouds, causing the part underneath to appear overly dark.
## 0.1.3
### Fixe:
- Fixed decals being able to be scaled down to 0
### Changed:
- Made decal bounds no longer collide in flight, this is done by repurposing layer 31 (which is configurable in the ConformalDecals.cfg file)
- Decals will now be unselectable in flight by default. This can be disabled with the `selectableInFlight` value in ConformalDecals.cfg, or in the module config itself.
- Decal parts will now destroy themselves automatically when the parent part is destroyed
- Small refactor of node parsing code
- Colors can now be specified in hex (#RGB, #RGBA, #RRGGBB, or #RRGGBBAA) or using the colors specified in the XKCDColors class
## 0.1.2
### Fixed:
- Disabled writing to the zbuffer in the decal bounds shader. Should fix any issues with Scatterer or EVE.
## 0.1.1
### Fixed:
- Fixed flag decal not adjusting to new texture sizes immediately.
- Fixed decal bounds being visible on launch.
- Fixed decal bounds being visible in the part icon.
## 0.1.0
Initial release!
### New Parts:
- CDL-F Flag Decal: Conformal flag decal, which uses either the mission flag or a flag of your choosing.
- CDL-1 Generic Decal: A set of conformal generic decals for planes and rockets
- CDL-2 Semiotic Standard Decal: A set of conformal decals based on the Semiotic Standard for All Commercial Trans-Stellar Utility Lifter and Transport Spacecraft designed by Ron Cobb for the movie Alien

View File

@ -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
}

View File

@ -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] {}
}

View File

@ -0,0 +1,7 @@
// Prevent projection onto Waterfall plumes
CONFORMALDECALS:NEEDS[Waterfall] {
SHADERBLACKLIST {
shaderRegex = Waterfall/.*
}
}

View File

@ -4,21 +4,13 @@ CONFORMALDECALS {
SHADERBLACKLIST {
shader = DepthMask
shader = KSP/Alpha/Cutoff
shader = KSP/Alpha/Cutoff Bumped
shader = KSP/Alpha/Translucent
shader = KSP/Alpha/Translucent Additive
shader = KSP/Alpha/Translucent Specular
shader = KSP/Alpha/Unlit Transparent
shader = KSP/Bumped Specular (Transparent)
shader = KSP/FX/ScrollingUnlit
shader = KSP/Particles/Additive
shader = KSP/Particles/Additive (Soft)
shader = KSP/Particles/Alpha Blended
shader = KSP/Particles/Alpha Blended Emissive Cutout
shader = KSP/Specular (Cutoff)
shader = KSP/Specular (Transparent)
shader = Solid Color (Alpha)
shaderRegex = KSP/Alpha/.*
shaderRegex = KSP/Particles/.*
}
FONT {

View File

@ -1,28 +1,24 @@
{
"NAME":"ConformalDecals",
"URL":"https://raw.githubusercontent.com/drewcassidy/KSP-Conformal-Decals/release/GameData/ConformalDecals/Versioning/ConformalDecals.version",
"DOWNLOAD":"https://github.com/drewcassidy/KSP-Conformal-Decals/releases",
"VERSION":
{
"MAJOR":0,
"MINOR":2,
"PATCH":1,
"BUILD":0
"NAME": "ConformalDecals",
"URL": "https://github.com/drewcassidy/KSP-Conformal-Decals/releases/latest/download/ConformalDecals.version",
"DOWNLOAD": "https://github.com/drewcassidy/KSP-Conformal-Decals/releases/latest",
"CHANGE_LOG_URL": "https://raw.githubusercontent.com/drewcassidy/KSP-Conformal-Decals/release/CHANGELOG.md",
"VERSION": {
"MAJOR": 9,
"MINOR": 9,
"PATCH": 9,
"BUILD": 100000
},
"KSP_VERSION":
{
"MAJOR":1,
"MINOR":9,
"PATCH":1
"KSP_VERSION": {
"MAJOR": 1,
"MINOR": 12
},
"KSP_VERSION_MIN":{
"MAJOR":1,
"MINOR":8,
"PATCH":0
"KSP_VERSION_MIN": {
"MAJOR": 1,
"MINOR": 8
},
"KSP_VERSION_MAX":{
"MAJOR":1,
"MINOR":10,
"PATCH":99
"KSP_VERSION_MAX": {
"MAJOR": 1,
"MINOR": 12
}
}

View File

@ -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
[![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) [![CKAN: Indexed](https://img.shields.io/badge/CKAN-Indexed-brightgreen.svg)](https://github.com/KSP-CKAN/CKAN)
![Screenshot](http://pileof.rocks/KSP/images/ConformalDecalsHeader.png)
@ -9,9 +9,10 @@ Conformal Decals adds a set of decal stickers to KSP, as well as providing a fra
Required:
- KSP (1.8.x to 1.10.x)
- B9 Part Switch (2.16.0). Bundled with release.
- B9 Part Switch (2.18.0). Bundled with release.
- ModuleManager (4.1.4). Bundled with release.
- Shabby (0.1.2). Bundled with release.
- Shabby (0.2.0 unofficial build). Bundled with release.
- HarmonyKSP (2.0.4.0). Bundled with release.
Optional:
- Wild Blue Tools. For custom decals category in the VAB and SPH.

61
Scripts/version.py Normal file
View File

@ -0,0 +1,61 @@
import yaclog
import yaclog.version
import git as gp
import os
import xml.dom.minidom as minidom
import json
def run():
repo = gp.Repo(os.curdir)
cl = yaclog.Changelog('CHANGELOG.md')
version = str(cl.current_version(released=True).version)
release = False
for tag in repo.tags:
if tag.commit == repo.head.commit:
release = True
build = 100000
break
if not release:
build = int.from_bytes(repo.head.commit.binsha[0:2], byteorder='big')
version = yaclog.version.increment_version(version, 2)
print(f'Setting up version {version} build {build}')
version_path = 'GameData/ConformalDecals/Versioning/ConformalDecals.version'
with open(version_path, 'r+') as version_file:
print('Updating version file')
segments = version.split('.')
# print(version_file.read())
decoded = json.load(version_file)
decoded['VERSION']['MAJOR'] = int(segments[0])
decoded['VERSION']['MINOR'] = int(segments[1])
decoded['VERSION']['PATCH'] = int(segments[2])
decoded['VERSION']['BUILD'] = build
version_file.seek(0)
json.dump(decoded, version_file, indent=4)
version_file.truncate()
project_path = 'Source/ConformalDecals/ConformalDecals.csproj'
with open(project_path, 'r+') as project_file:
print('Updating csproj file')
segments = version.split('.')
decoded = minidom.parse(project_file)
version_node = decoded.getElementsByTagName('AssemblyVersion')[0]
if release:
version_node.firstChild.nodeValue = f'{version}'
else:
version_node.firstChild.nodeValue = f'{version}.{build}'
# version_node.value = f'{version}.{build}'
project_file.seek(0)
decoded.writexml(project_file)
project_file.truncate()
print('Done!')
if __name__ == '__main__':
run()

View File

@ -1,6 +1,6 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConformalDecals", "ConformalDecals/ConformalDecals.csproj", "{1ea983f9-42e5-494e-9683-fdac9c9121f4}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConformalDecals", "ConformalDecals/ConformalDecals.csproj", "{1EA983F9-42E5-494E-9683-FDAC9C9121F4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -8,9 +8,9 @@ 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
EndGlobal

View File

@ -1,116 +1,55 @@
<?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')" />
<?xml version="1.0" ?><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>9.9.9</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>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="/bin/cp -v '$(OutDir)ConformalDecals.dll' '$(SolutionDir)../GameData/ConformalDecals/Plugins/ConformalDecals.dll'" IgnoreExitCode="true"/>
<!--Fuck you MSBuild stop trying to run CMD.exe on macOS-->
</Target>
</Project>

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using ConformalDecals.Text;
using ConformalDecals.Util;
using TMPro;
@ -10,6 +11,7 @@ namespace ConformalDecals {
public static class DecalConfig {
private static Texture2D _blankNormal;
private static List<string> _shaderBlacklist;
private static List<Regex> _shaderRegexBlacklist;
private static Dictionary<string, DecalFont> _fontList;
private static int _decalLayer = 31;
private static bool _selectableInFlight;
@ -51,14 +53,22 @@ namespace ConformalDecals {
public static IEnumerable<DecalFont> Fonts => _fontList.Values;
public static DecalFont FallbackFont { get; private set; }
public static bool IsBlacklisted(Shader shader) {
return IsBlacklisted(shader.name);
}
public static bool IsBlacklisted(string shaderName) {
return _shaderBlacklist.Contains(shaderName);
if (_shaderBlacklist.Contains(shaderName)) return true;
foreach (var regex in _shaderRegexBlacklist) {
if (regex.IsMatch(shaderName)) {
_shaderBlacklist.Add(shaderName);
Logging.Log($"Caching blacklisted shader name '{shaderName}' which matches '{regex}'");
return true;
}
}
return false;
}
public static bool IsLegacy(string shaderName, out string newShader, out string[] keywords) {
@ -91,6 +101,10 @@ namespace ConformalDecals {
foreach (var shaderName in blacklist.GetValuesList("shader")) {
_shaderBlacklist.Add(shaderName);
}
foreach (var shaderRegex in blacklist.GetValuesList("shaderRegex")) {
_shaderRegexBlacklist.Add(new Regex(shaderRegex));
}
}
var allFonts = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
@ -128,13 +142,14 @@ namespace ConformalDecals {
// ReSharper disable once UnusedMember.Global
public static void ModuleManagerPostLoad() {
_shaderBlacklist = new List<string>();
_shaderRegexBlacklist = new List<Regex>();
_fontList = new Dictionary<string, DecalFont>();
var configs = GameDatabase.Instance.GetConfigs("CONFORMALDECALS");
if (configs.Length > 0) {
Logging.Log("loading config");
foreach (var config in configs) {
Logging.Log($"loading config node '{config.url}'");
ParseConfig(config.config);
}
}

View File

@ -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;
return MaskedHeight / (float) MaskedWidth;
}
}
public override void ParseNode(ConfigNode node) {
base.ParseNode(node);

View File

@ -31,7 +31,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,19 +60,19 @@ 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"),
@ -283,7 +283,7 @@ namespace ConformalDecals {
}
}
public virtual void OnDestroy() {
public void OnDestroy() {
// remove GameEvents
if (HighLogic.LoadedSceneIsEditor) {
GameEvents.onEditorPartEvent.Remove(OnEditorEvent);
@ -400,7 +400,7 @@ namespace ConformalDecals {
protected void UpdateScale() {
scale = Mathf.Max(0.01f, scale);
depth = Mathf.Max(0.01f, depth);
var aspectRatio = materialProperties.AspectRatio;
var aspectRatio = Mathf.Max(0.01f, materialProperties.AspectRatio);
Vector2 size;
switch (scaleMode) {
@ -440,7 +440,8 @@ namespace ConformalDecals {
// update projection
foreach (var target in _targets) {
target.Project(_orthoMatrix, decalProjectorTransform, _boundsRenderer.bounds, useBaseNormal);
if (target != null)
target.Project(_orthoMatrix, decalProjectorTransform, _boundsRenderer.bounds, useBaseNormal);
}
}
else {
@ -512,7 +513,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,7 +522,7 @@ namespace ConformalDecals {
var scaleEditor = (UI_FloatRange) scaleField.uiControlEditor;
scaleEditor.minValue = minValue;
scaleEditor.maxValue = maxValue;
scaleEditor.stepIncrement = (maxValue - minValue) / steps;
scaleEditor.stepIncrement = 0.01f; //1cm
scaleEditor.onFieldChanged = OnSizeTweakEvent;
}
@ -532,7 +533,7 @@ namespace ConformalDecals {
var depthEditor = (UI_FloatRange) depthField.uiControlEditor;
depthEditor.minValue = minValue;
depthEditor.maxValue = maxValue;
depthEditor.stepIncrement = (maxValue - minValue) / steps;
depthEditor.stepIncrement = 0.01f; //1cm
depthEditor.onFieldChanged = OnSizeTweakEvent;
}
@ -577,7 +578,8 @@ namespace ConformalDecals {
// render on each target object
foreach (var target in _targets) {
target.Render(_decalMaterial, part.mpb, camera);
if (target != null)
target.Render(_decalMaterial, part.mpb, camera);
}
}
}

View File

@ -1,4 +1,3 @@
using ConformalDecals.Util;
using UnityEngine;
namespace ConformalDecals {
@ -9,6 +8,7 @@ namespace ConformalDecals {
[KSPField(isPersistant = true)] public bool useCustomFlag;
// The URL of the flag for the current mission or agency
public string MissionFlagUrl {
get {
if (HighLogic.LoadedSceneIsEditor) {
@ -19,6 +19,7 @@ namespace ConformalDecals {
return string.IsNullOrEmpty(part.flagURL) ? HighLogic.CurrentGame.flagURL : part.flagURL;
}
// If we are not in game, use the default flag (for icon rendering)
return DefaultFlag;
}
}
@ -26,84 +27,104 @@ namespace ConformalDecals {
public override void OnLoad(ConfigNode node) {
base.OnLoad(node);
if (useCustomFlag) {
SetFlag(flagUrl);
}
else {
SetFlag(MissionFlagUrl);
}
// Since OnLoad is called for all modules, we only need to update this module
// Updating symmetry counterparts would be redundent
UpdateFlag();
}
public override void OnStart(StartState state) {
base.OnStart(state);
if (HighLogic.LoadedSceneIsGame) {
GameEvents.onMissionFlagSelect.Add(OnEditorFlagSelected);
}
if (HighLogic.LoadedSceneIsEditor) {
// Register flag change event
GameEvents.onMissionFlagSelect.Add(OnEditorFlagSelected);
// Register reset button event
Events[nameof(ResetFlag)].guiActiveEditor = useCustomFlag;
}
if (useCustomFlag) {
SetFlag(flagUrl);
}
else {
SetFlag(MissionFlagUrl);
}
// Since OnStart is called for all modules, we only need to update this module
// Updating symmetry counterparts would be redundent
UpdateFlag();
}
public override void OnDestroy() {
GameEvents.onMissionFlagSelect.Remove(SetFlag);
base.OnDestroy();
}
public void OnDestroy() {
if (HighLogic.LoadedSceneIsEditor) {
// Unregister flag change event
GameEvents.onMissionFlagSelect.Remove(OnEditorFlagSelected);
}
}
[KSPEvent(guiActive = false, guiActiveEditor = true, guiName = "#LOC_ConformalDecals_gui-select-flag")]
public void SelectFlag() {
// Button for selecting a flag
// This is a bit of a hack to bring up the stock flag selection menu
// When its done, it calls OnCustomFlagSelected()
// ReSharper disable once PossibleNullReferenceException
var flagBrowser = (Instantiate((Object) (new FlagBrowserGUIButton(null, null, null, null)).FlagBrowserPrefab) as GameObject).GetComponent<FlagBrowser>();
flagBrowser.OnFlagSelected = OnCustomFlagSelected;
}
[KSPEvent(guiActive = false, guiActiveEditor = true, guiName = "#LOC_ConformalDecals_gui-reset-flag")]
public void ResetFlag() {
SetFlag(MissionFlagUrl);
SetFlagSymmetryCounterparts(MissionFlagUrl);
// we are no longer using a custom flag, so instead use the mission or agency flag
useCustomFlag = false;
flagUrl = "Mission";
UpdateFlag(true);
// disable the reset button, since it no longer makes sense
Events[nameof(ResetFlag)].guiActiveEditor = false;
}
private void OnCustomFlagSelected(FlagBrowser.FlagEntry newFlagEntry) {
SetFlag(newFlagEntry.textureInfo.name);
SetFlagSymmetryCounterparts(newFlagEntry.textureInfo.name);
// Callback for when a flag is selected in the menu spawned by SelectFlag()
// we are now using a custom flag with the URL of the new flag entry
useCustomFlag = true;
flagUrl = newFlagEntry.textureInfo.name;
UpdateFlag(true);
// make sure the reset button is now available
Events[nameof(ResetFlag)].guiActiveEditor = true;
}
private void OnEditorFlagSelected(string newFlagUrl) {
if (!useCustomFlag) {
SetFlag(newFlagUrl);
SetFlagSymmetryCounterparts(newFlagUrl);
flagUrl = newFlagUrl;
// Since this callback is called for all modules, we only need to update this module
// Updating symmetry counterparts would be redundent
UpdateFlag();
}
}
private void SetFlag(string newFlagUrl) {
this.Log($"Loading flag texture '{newFlagUrl}'.");
// Update the displayed flag texture for this decal or optionally any symmetry counterparts
private void UpdateFlag(bool recursive = false) {
// get the decal material property for the decal texture
var textureProperty = materialProperties.AddOrGetTextureProperty("_Decal", true);
flagUrl = newFlagUrl;
materialProperties.AddOrGetTextureProperty("_Decal", true).TextureUrl = newFlagUrl;
if(useCustomFlag) {
// set the texture to the custom flag
textureProperty.TextureUrl = flagUrl;
}
else {
// set the texture to the mission flag
textureProperty.TextureUrl = MissionFlagUrl;
}
UpdateMaterials();
UpdateScale();
}
private void SetFlagSymmetryCounterparts(string newFlagUrl) {
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalFlag>();
if (recursive) {
// for each symmetry counterpart, copy this part's properties and update it in turn
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalFlag>();
decal.SetFlag(newFlagUrl);
decal.useCustomFlag = useCustomFlag;
decal.useCustomFlag = useCustomFlag;
decal.flagUrl = flagUrl;
decal.UpdateFlag();
}
}
}
}

View File

@ -1,3 +1,5 @@
using System.Collections;
using System.Net;
using ConformalDecals.MaterialProperties;
using ConformalDecals.Text;
using ConformalDecals.UI;
@ -6,27 +8,26 @@ using TMPro;
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 +45,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 +68,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 +89,50 @@ namespace ConformalDecals {
private MaterialColorProperty _outlineColorProperty;
private MaterialFloatProperty _outlineWidthProperty;
private TextRenderJob _currentJob;
private DecalText _currentText;
public override void OnLoad(ConfigNode node) {
base.OnLoad(node);
OnAfterDeserialize();
UpdateTextRecursive();
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");
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");
if (HighLogic.LoadedSceneIsGame) {
// For some reason, rendering doesnt work right on the first frame a scene is loaded
// So delay any rendering until the next frame when called in OnLoad
// This is probably a problem with Unity, not KSP
StartCoroutine(UpdateTextLate());
}
else {
UpdateText();
}
}
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 +146,34 @@ namespace ConformalDecals {
_outlineWidthProperty = materialProperties.AddOrGetProperty<MaterialFloatProperty>("_OutlineWidth");
}
public void OnTextUpdate(string newText, DecalFont newFont, DecalTextStyle newStyle) {
text = newText;
_font = newFont;
_style = newStyle;
UpdateTextRecursive();
public void OnTextUpdate(string newText, DecalFont newFont, FontStyles newStyle, bool newVertical, float newLineSpacing, float newCharSpacing) {
this.text = newText;
this.font = newFont;
this.style = newStyle;
this.vertical = newVertical;
this.lineSpacing = newLineSpacing;
this.charSpacing = newCharSpacing;
UpdateText(true);
}
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,35 +220,13 @@ 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() {
public void OnDestroy() {
if (HighLogic.LoadedSceneIsGame && _currentText != null) TextRenderer.UnregisterText(_currentText);
base.OnDestroy();
// close all UIs
if (_textEntryController != null) _textEntryController.Close();
if (_fillColorPickerController != null) _fillColorPickerController.Close();
if (_outlineColorPickerController != null) _outlineColorPickerController.Close();
}
protected override void OnDetach() {
@ -237,33 +238,37 @@ namespace ConformalDecals {
base.OnDetach();
}
private void UpdateTextRecursive() {
private IEnumerator UpdateTextLate() {
yield return null;
UpdateText();
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalText>();
decal.text = text;
decal._font = _font;
decal._style = _style;
decal._currentJob = _currentJob;
decal._currentText = _currentText;
decal.UpdateText();
}
}
private void UpdateText() {
private void UpdateText(bool recursive = false) {
// Render text
var newText = new DecalText(text, _font, _style);
var output = TextRenderer.UpdateTextNow(_currentText, newText);
var newText = new DecalText(text, font, style, vertical, lineSpacing, charSpacing);
var output = TextRenderer.UpdateText(_currentText, newText);
// update the _currentText state variable
// this is the ONLY place this variable should be set! otherwise the current state is lost
_currentText = newText;
// Update the texture with the new rendered output
UpdateTexture(output);
// TODO: ASYNC RENDERING
// var newText = new DecalText(text, _font, _style);
// _currentJob = TextRenderer.UpdateText(_currentText, newText, UpdateTexture);
// _currentText = newText;
// If recursive, copy parameters to other parts and perform the same operation
if (recursive) {
foreach (var counterpart in part.symmetryCounterparts) {
var decal = counterpart.GetComponent<ModuleConformalText>();
decal.text = text;
decal.font = font;
decal.style = style;
decal.vertical = vertical;
decal.charSpacing = charSpacing;
decal.lineSpacing = lineSpacing;
decal.UpdateText();
}
}
}
public void UpdateTexture(TextRenderOutput output) {
@ -276,10 +281,10 @@ namespace ConformalDecals {
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();

View File

@ -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)]

View File

@ -3,41 +3,47 @@ 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) {
@ -45,14 +51,14 @@ namespace ConformalDecals.Text {
if (fontAssets == null) throw new ArgumentNullException(nameof(fontAssets));
var name = ParseUtil.ParseString(node, "name");
FontAsset = fontAssets.First(o => o.name == name);
_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);
_title = ParseUtil.ParseString(node, "title", true, name);
_fontStyle = (FontStyles) ParseUtil.ParseInt(node, "style", true);
_fontStyleMask = (FontStyles) ParseUtil.ParseInt(node, "styleMask", true);
}
@ -95,5 +101,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;
}
}
}

View File

@ -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}";
}
}
}

View File

@ -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);
}
}
}

View File

@ -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);
}
}
}

View File

@ -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) {

View File

@ -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) {
if (newText == null) throw new ArgumentNullException(nameof(newText));
var job = new TextRenderJob(oldText, newText, renderFinishedCallback);
RenderJobs.Enqueue(job);
return job;
}
/// Update text immediately without using job queue
public static TextRenderOutput UpdateTextNow(DecalText oldText, DecalText newText) {
public static TextRenderOutput UpdateText(DecalText oldText, DecalText newText) {
if (newText == null) throw new ArgumentNullException(nameof(newText));
return Instance.RunJob(new TextRenderJob(oldText, newText, null), out _);
if (!(oldText is null)) UnregisterText(oldText);
// 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);
}
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.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;
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}'");
}
}
}

View File

@ -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 bool _ignoreUpdates;
private static int _lockCounter;
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;
}

View File

@ -5,8 +5,8 @@ using UnityEngine.UI;
namespace ConformalDecals.UI {
[KSPAddon(KSPAddon.Startup.Instantly, true)]
public class UILoader : MonoBehaviour {
private static readonly string Path = KSPUtil.ApplicationRootPath + "GameData/ConformalDecals/Resources/";
private static string _path;
private static GameObject _textEntryPrefab;
private static GameObject _fontMenuPrefab;
private static GameObject _colorPickerPrefab;
@ -16,7 +16,8 @@ namespace ConformalDecals.UI {
public static GameObject ColorPickerPrefab => _colorPickerPrefab;
private void Awake() {
var prefabs = AssetBundle.LoadFromFile(Path + "ui.conformaldecals");
_path = KSPUtil.ApplicationRootPath + "GameData/ConformalDecals/Resources/";
var prefabs = AssetBundle.LoadFromFile(_path + "ui.conformaldecals");
_textEntryPrefab = prefabs.LoadAsset("TextEntryPanel") as GameObject;
_fontMenuPrefab = prefabs.LoadAsset("FontMenuPanel") as GameObject;

View File

@ -30,9 +30,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) {

View File

@ -1,70 +0,0 @@
v0.2.1
------
- Changes
- Pressing enter in the text entry window now types a newline.
- 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.
v0.2.0
------
- New Parts:
- CDL-3 Surface Base Decal: A set of conformal decals based on the symbols from the movie Moon (2009) designed by Gavin Rothery
- CDL-T Custom Text Decal: A customizable text decal with a variety of fonts
- Changes:
- New ModuleConformalText module for customizable text
- Text, font, and style can all be customized, as well as text fill and outline colors and widths
- Same projection and opacity options as other conformal decals
- New StandardText decal shader supporting the text module
- Unified all decal shaders into a single "StandardDecal" shader with variants supporting any combination of bump, specular and emissive maps, plus SDF alphas.
- Old shaders are remapped to Standard shader plus keywords automatically.
- New SDF-based antialiasing for when decals extend to their borders, e.g. on opaque flags.
- New "KEYWORD" material modifier, allowing for shader features to be enabled and disabled.
- Material modifiers can now be removed in variants by setting `remove = true` inside them.
- Fixes:
- Fixed WIDTH and HEIGHT scale modes being flipped
- Removed some debug log statements
- Dependencies:
- Updated ModuleManager to version 4.1.4
v0.1.4
------
- Supported KSP versions: 1.8.x to 1.10.x
- Fixes:
- Fixed decals rendering onto disabled B9PS part variants
- Decals will still not update whan their parent part's B9PS variant is changed, both in flight and in the editor. This is known and awaiting a change to B9PS to be fixed.
- Fixed decal bounds rendering as dark cubes when shadowed by EVE clouds.
- Fixed decals being shadowed by EVE clouds, causing the part underneath to appear overly dark.
v0.1.3
------
Fixes:
- Fixed decals being able to be scaled down to 0
Changes:
- Made decal bounds no longer collide in flight, this is done by repurposing layer 31 (which is configurable in the ConformalDecals.cfg file)
- Decals will now be unselectable in flight by default. This can be disabled with the `selectableInFlight` value in ConformalDecals.cfg, or in the module config itself.
- Decal parts will now destroy themselves automatically when the parent part is destroyed
- Small refactor of node parsing code
- Colors can now be specified in hex (#RGB, #RGBA, #RRGGBB, or #RRGGBBAA) or using the colors specified in the XKCDColors class
v0.1.2
------
Fixes:
- Disabled writing to the zbuffer in the decal bounds shader. Should fix any issues with Scatterer or EVE.
v0.1.1
------
Fixes:
- Fixed flag decal not adjusting to new texture sizes immediately.
- Fixed decal bounds being visible on launch.
- Fixed decal bounds being visible in the part icon.
v0.1.0
------
Initial release!
New parts:
- CDL-F Flag Decal: Conformal flag decal, which uses either the mission flag or a flag of your choosing.
- CDL-1 Generic Decal: A set of conformal generic decals for planes and rockets
- CDL-2 Semiotic Standard Decal: A set of conformal decals based on the Semiotic Standard for All Commercial Trans-Stellar Utility Lifter and Transport Spacecraft designed by Ron Cobb for the movie Alien