Fix transform handling and projection culling

Now to figure out why my collider is disappearing...
This commit is contained in:
Andrew Cassidy 2020-05-31 23:04:59 -07:00
parent a12b11a339
commit 91a6613707
4 changed files with 136 additions and 92 deletions

View File

@ -45,7 +45,8 @@ PART
{ {
name = ModuleConformalDecal name = ModuleConformalDecal
decalPreviewTransform = Decal-Front decalFront = Decal-Front
decalBack = Decal-Back
MATERIAL MATERIAL
{ {

View File

@ -1,15 +1,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using ConformalDecals.MaterialModifiers; using ConformalDecals.MaterialModifiers;
using UniLinq;
using UnityEngine; using UnityEngine;
namespace ConformalDecals { namespace ConformalDecals {
public class ModuleConformalDecal : PartModule { public class ModuleConformalDecal : PartModule {
[KSPField] public string decalPreviewTransform = "";
[KSPField] public string decalModelTransform = "";
[KSPField] public string decalProjectorTransform = "";
[KSPField(guiName = "#LOC_ConformalDecals_gui-scale", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"), [KSPField(guiName = "#LOC_ConformalDecals_gui-scale", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"),
UI_FloatRange(minValue = 0.05f, maxValue = 4f, stepIncrement = 0.05f)] UI_FloatRange(minValue = 0.05f, maxValue = 4f, stepIncrement = 0.05f)]
public float scale = 1.0f; public float scale = 1.0f;
@ -17,33 +12,45 @@ namespace ConformalDecals {
[KSPField(guiName = "#LOC_ConformalDecals_gui-depth", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"), [KSPField(guiName = "#LOC_ConformalDecals_gui-depth", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"),
UI_FloatRange(minValue = 0.05f, maxValue = 4f, stepIncrement = 0.05f)] UI_FloatRange(minValue = 0.05f, maxValue = 4f, stepIncrement = 0.05f)]
public float depth = 1.0f; public float depth = 1.0f;
[KSPField(guiName = "#LOC_ConformalDecals_gui-opacity", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"), [KSPField(guiName = "#LOC_ConformalDecals_gui-opacity", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"),
UI_FloatRange(minValue = 0.05f, maxValue = 4f, stepIncrement = 0.05f)] UI_FloatRange(minValue = 0.05f, maxValue = 4f, stepIncrement = 0.05f)]
public float opacity= 1.0f; public float opacity = 1.0f;
[KSPField(guiName = "#LOC_ConformalDecals_gui-cutoff", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"), [KSPField(guiName = "#LOC_ConformalDecals_gui-cutoff", guiActive = false, guiActiveEditor = true, isPersistant = true, guiFormat = "F2", guiUnits = "m"),
UI_FloatRange(minValue = 0.05f, maxValue = 4f, stepIncrement = 0.05f)] UI_FloatRange(minValue = 0.05f, maxValue = 4f, stepIncrement = 0.05f)]
public float cutoff = 0.5f; public float cutoff = 0.5f;
[KSPField(guiName = "#LOC_ConformalDecals_gui-aspectratio", guiActive = true, guiFormat = "F2")] [KSPField(guiName = "#LOC_ConformalDecals_gui-aspectratio", guiActive = true, guiFormat = "F2")]
public float aspectRatio = 1.0f; public float aspectRatio = 1.0f;
[KSPField] public MaterialPropertyCollection materialProperties; [KSPField] public string decalFront = string.Empty;
[KSPField] public string decalBack = string.Empty;
[KSPField] public string decalModel = string.Empty;
[KSPField] public string decalProjector = string.Empty;
[KSPField] public Transform decalPreviewTransformRef; [KSPField] public Transform decalFrontTransform;
[KSPField] public Transform decalModelTransformRef; [KSPField] public Transform decalBackTransform;
[KSPField] public Transform decalProjectorTransformRef; [KSPField] public Transform decalModelTransform;
[KSPField] public Transform modelTransformRef; [KSPField] public Transform decalProjectorTransform;
[KSPField] public Transform colliderTransformRef;
[KSPField] public BoxCollider colliderRef; [KSPField] public bool adjustableScale = true;
[KSPField] public bool adjustableDepth = true;
[KSPField] public bool adjustableOpacity = true;
[KSPField] public bool adjustableCutoff = true;
[KSPField] public bool updateBackScale = true;
[KSPField] public MaterialPropertyCollection materialProperties;
private List<ProjectionTarget> _targets; private List<ProjectionTarget> _targets;
private bool _isAttached;
private Matrix4x4 _orthoMatrix; private Matrix4x4 _orthoMatrix;
private Bounds _decalBounds; private Bounds _decalBounds;
private Vector2 _backTextureBaseScale;
private bool IsAttached => part.parent != null; private Material _backMaterial;
public override void OnLoad(ConfigNode node) { public override void OnLoad(ConfigNode node) {
this.Log("Loading module"); this.Log("Loading module");
@ -62,35 +69,42 @@ namespace ConformalDecals {
aspectRatio = 1; aspectRatio = 1;
} }
// find preview object references // find front transform
modelTransformRef = part.transform.Find("model"); decalFrontTransform = part.FindModelTransform(decalFront);
if (decalFrontTransform == null) throw new FormatException($"Could not find decalFront transform: '{decalFront}'.");
decalPreviewTransformRef = part.FindModelTransform(decalPreviewTransform); // find back transform
if (decalPreviewTransformRef == null) throw new FormatException("Missing decal preview reference"); this.Log($"decalBack name is {decalBack}");
this.Log($"updateBaseScale is {updateBackScale}");
if (String.IsNullOrEmpty(decalModelTransform)) { if (string.IsNullOrEmpty(decalBack)) {
decalModelTransformRef = decalPreviewTransformRef; if (updateBackScale) {
this.LogWarning("updateBackScale is true but has no specified decalBack transform!");
this.LogWarning("Setting updateBackScale to false.");
updateBackScale = false;
}
} }
else { else {
decalModelTransformRef = part.FindModelTransform(decalModelTransform); decalBackTransform = part.FindModelTransform(decalBack);
if (decalModelTransformRef == null) throw new FormatException("Missing decal mesh reference"); if (decalBackTransform == null) throw new FormatException($"Could not find decalBack transform: '{decalBack}'.");
} }
if (String.IsNullOrEmpty(decalProjectorTransform)) { // find model transform
decalProjectorTransformRef = modelTransformRef; if (string.IsNullOrEmpty(decalModel)) {
decalModelTransform = decalFrontTransform;
} }
else { else {
decalProjectorTransformRef = part.FindModelTransform(decalProjectorTransform); decalModelTransform = part.FindModelTransform(decalModel);
if (decalProjectorTransform == null) throw new FormatException("Missing decal projector reference"); if (decalModelTransform == null) throw new FormatException($"Could not find decalModel transform: '{decalModel}'.");
} }
colliderTransformRef = new GameObject("Decal Collider").transform; // find projector transform
colliderTransformRef.parent = modelTransformRef; if (string.IsNullOrEmpty(decalProjector)) {
colliderTransformRef.position = decalProjectorTransformRef.position; decalProjectorTransform = part.transform.Find("model");
colliderTransformRef.rotation = decalProjectorTransformRef.rotation; }
colliderTransformRef.gameObject.SetActive(false); else {
decalProjectorTransform = part.FindModelTransform(decalProjector);
colliderRef = colliderTransformRef.gameObject.AddComponent<BoxCollider>(); if (decalProjectorTransform == null) throw new FormatException($"Could not find decalProjector transform: '{decalProjector}'.");
}
} }
catch (Exception e) { catch (Exception e) {
this.LogException("Exception parsing partmodule", e); this.LogException("Exception parsing partmodule", e);
@ -99,71 +113,95 @@ namespace ConformalDecals {
public override void OnStart(StartState state) { public override void OnStart(StartState state) {
this.Log("Starting module"); this.Log("Starting module");
// generate orthogonal projection matrix and offset it by 0.5 on x and y axes // generate orthogonal projection matrix and offset it by 0.5 on x and y axes
_orthoMatrix = Matrix4x4.identity; _orthoMatrix = Matrix4x4.identity;
_orthoMatrix[0, 3] = 0.5f; _orthoMatrix[0, 3] = 0.5f;
_orthoMatrix[1, 3] = 0.5f; _orthoMatrix[1, 3] = 0.5f;
// setup OnTweakEvent for scale and depth fields in editor
if ((state & StartState.Editor) != 0) { if ((state & StartState.Editor) != 0) {
// setup OnTweakEvent for scale and depth fields in editor
GameEvents.onEditorPartEvent.Add(OnEditorEvent); GameEvents.onEditorPartEvent.Add(OnEditorEvent);
GameEvents.onVariantApplied.Add(OnVariantApplied); GameEvents.onVariantApplied.Add(OnVariantApplied);
Fields[nameof(scale)].uiControlEditor.onFieldChanged = OnTweakEvent; Fields[nameof(scale)].uiControlEditor.onFieldChanged = OnScaleTweakEvent;
Fields[nameof(depth)].uiControlEditor.onFieldChanged = OnTweakEvent; Fields[nameof(depth)].uiControlEditor.onFieldChanged = OnScaleTweakEvent;
}
// get back material if necessary
if (updateBackScale) {
this.Log("Getting material and base scale for back material");
var backRenderer = decalBackTransform.GetComponent<MeshRenderer>();
if (backRenderer == null) {
this.LogError($"Specified decalBack transform {decalBack} has no renderer attached! Setting updateBackScale to false.");
updateBackScale = false;
}
else if ((_backMaterial = backRenderer.material) == null) {
this.LogError($"Specified decalBack transform {decalBack} has a renderer but no material! Setting updateBackScale to false.");
updateBackScale = false;
}
else {
_backTextureBaseScale = _backMaterial.GetTextureScale(PropertyIDs._MainTex);
}
}
// set initial attachment state
if (part.parent == null) {
OnDetach();
} }
else { else {
// if we start in the flight scene attached, call Attach OnAttach();
if (IsAttached) Attach();
} }
} }
private void OnDestroy() { public void OnDestroy() {
GameEvents.onEditorPartEvent.Remove(OnEditorEvent); GameEvents.onEditorPartEvent.Remove(OnEditorEvent);
GameEvents.onVariantApplied.Remove(OnVariantApplied); GameEvents.onVariantApplied.Remove(OnVariantApplied);
// remove from preCull delegate // remove from preCull delegate
Camera.onPreCull -= Render; Camera.onPreCull -= Render;
} }
private void OnScaleTweakEvent(BaseField field, object obj) {
public void OnTweakEvent(BaseField field, object obj) { // scale or depth values have been changed, so update scale
// scale or depth values have been changed, so update the projection matrix for each target // and update projection matrices if attached
Project(); UpdateScale();
if (_isAttached) UpdateProjection();
} }
public void OnVariantApplied(Part eventPart, PartVariant variant) { private void OnVariantApplied(Part eventPart, PartVariant variant) {
if (IsAttached && eventPart == part.parent) { if (_isAttached && eventPart == part.parent) {
Detach(); OnDetach();
Attach(); OnAttach();
} }
} }
public void OnEditorEvent(ConstructionEventType eventType, Part eventPart) { private void OnEditorEvent(ConstructionEventType eventType, Part eventPart) {
if (eventPart != this.part) return; if (eventPart != this.part) return;
switch (eventType) { switch (eventType) {
case ConstructionEventType.PartAttached: case ConstructionEventType.PartAttached:
Attach(); OnAttach();
break; break;
case ConstructionEventType.PartDetached: case ConstructionEventType.PartDetached:
Detach(); OnDetach();
break; break;
case ConstructionEventType.PartOffsetting: case ConstructionEventType.PartOffsetting:
case ConstructionEventType.PartRotating: case ConstructionEventType.PartRotating:
case ConstructionEventType.PartDragging: case ConstructionEventType.PartDragging:
Project(); UpdateProjection();
break; break;
} }
} }
public void Attach() { private void OnAttach() {
if (!IsAttached) { if (part.parent == null) {
this.LogError("Attach function called but part has no parent!"); this.LogError("Attach function called but part has no parent!");
_isAttached = false;
return; return;
} }
_isAttached = true;
this.Log($"Decal attached to {part.parent.partName}"); this.Log($"Decal attached to {part.parent.partName}");
this.Log($"{materialProperties == null}");
this.Log($"{decalModelTransformRef == null}");
if (_targets == null) { if (_targets == null) {
_targets = new List<ProjectionTarget>(); _targets = new List<ProjectionTarget>();
@ -177,7 +215,7 @@ namespace ConformalDecals {
foreach (var renderer in renderers) { foreach (var renderer in renderers) {
// skip disabled renderers // skip disabled renderers
if (renderer.gameObject.activeInHierarchy == false) continue; if (renderer.gameObject.activeInHierarchy == false) continue;
var meshFilter = renderer.GetComponent<MeshFilter>(); var meshFilter = renderer.GetComponent<MeshFilter>();
if (meshFilter == null) continue; // object has a meshRenderer with no filter, invalid if (meshFilter == null) continue; // object has a meshRenderer with no filter, invalid
var mesh = meshFilter.mesh; var mesh = meshFilter.mesh;
@ -194,58 +232,61 @@ namespace ConformalDecals {
} }
// hide preview model // hide preview model
decalModelTransformRef.gameObject.SetActive(false); decalModelTransform.gameObject.SetActive(false);
// enable decal collider
colliderTransformRef.gameObject.SetActive(true);
// add to preCull delegate // add to preCull delegate
Camera.onPreCull += Render; Camera.onPreCull += Render;
Project(); UpdateScale();
UpdateProjection();
} }
public void Detach() { private void OnDetach() {
// unhide preview model _isAttached = false;
decalModelTransformRef.gameObject.SetActive(true);
// enable decal collider // unhide preview model
colliderTransformRef.gameObject.SetActive(false); decalModelTransform.gameObject.SetActive(true);
// remove from preCull delegate // remove from preCull delegate
Camera.onPreCull -= Render; Camera.onPreCull -= Render;
UpdateScale();
} }
[KSPEvent(guiActive = false, guiName = "Project", guiActiveEditor = true, active = true)] private void UpdateScale() {
public void Project() { var size = new Vector2(scale, scale * aspectRatio);
if (!IsAttached) return;
float width = scale; // update orthogonal matrix scale
float height = scale * aspectRatio; _orthoMatrix[0, 0] = 1 / size.x;
// generate orthogonal matrix scale values _orthoMatrix[1, 1] = 1 / size.y;
_orthoMatrix[0, 0] = 1 / width;
_orthoMatrix[1, 1] = 1 / height;
_orthoMatrix[2, 2] = 1 / depth; _orthoMatrix[2, 2] = 1 / depth;
// generate bounding box for decal for culling purposes // generate bounding box for decal for culling purposes
_decalBounds.center = Vector3.forward * (depth / 2); _decalBounds.center = Vector3.forward * (depth / 2);
_decalBounds.extents = new Vector3(width / 2, height / 2, depth / 2); _decalBounds.extents = new Vector3(size.x / 2, size.y / 2, depth / 2);
// rescale preview model // rescale preview model
decalModelTransformRef.localScale = new Vector3(width, height, (width + height) / 2); decalModelTransform.localScale = new Vector3(size.x, size.y, (size.x + size.y) / 2);
// assign dimensions to collider // update back material scale
colliderRef.center = _decalBounds.center; if (updateBackScale) {
colliderRef.size = _decalBounds.size; _backMaterial.SetTextureScale(PropertyIDs._MainTex, new Vector2(size.x * _backTextureBaseScale.x, size.y * _backTextureBaseScale.y));
}
// update material scale
materialProperties.UpdateMaterial(size);
}
private void UpdateProjection() {
if (!_isAttached) return;
// project to each target object // project to each target object
foreach (var target in _targets) { foreach (var target in _targets) {
target.Project(_orthoMatrix, colliderRef.bounds, decalProjectorTransformRef); target.Project(_orthoMatrix, new OrientedBounds(decalProjectorTransform.localToWorldMatrix, _decalBounds), decalProjectorTransform);
} }
} }
public void Render(Camera camera) { private void Render(Camera camera) {
if (!IsAttached) return; if (!_isAttached) return;
// render on each target object // render on each target object
foreach (var target in _targets) { foreach (var target in _targets) {

View File

@ -45,9 +45,9 @@ namespace ConformalDecals {
} }
} }
public void Project(Matrix4x4 orthoMatrix, Bounds projectorBounds, Transform projector) { public void Project(Matrix4x4 orthoMatrix, OrientedBounds projectorBounds, Transform projector) {
var targetBounds = _targetRenderer.bounds; var targetBounds = _targetRenderer.bounds;
if (targetBounds.Intersects(projectorBounds)) { if (projectorBounds.Intersects(targetBounds)) {
_projectionEnabled = true; _projectionEnabled = true;
var projectorToTargetMatrix = target.worldToLocalMatrix * projector.localToWorldMatrix; var projectorToTargetMatrix = target.worldToLocalMatrix * projector.localToWorldMatrix;
@ -58,9 +58,11 @@ namespace ConformalDecals {
decalMPB.SetMatrix(_projectionMatrixID, projectionMatrix); decalMPB.SetMatrix(_projectionMatrixID, projectionMatrix);
decalMPB.SetVector(_decalNormalID, decalNormal); decalMPB.SetVector(_decalNormalID, decalNormal);
decalMPB.SetVector(_decalTangentID, decalTangent); decalMPB.SetVector(_decalTangentID, decalTangent);
Debug.Log($"Projection enabled for {target.gameObject}");
} }
else { else {
_projectionEnabled = false; _projectionEnabled = false;
Debug.Log($"Projection disabled for {target.gameObject}");
} }
} }