备份CatanBuilding瘦身独立工程

This commit is contained in:
JSD\13999
2026-05-26 16:15:54 +08:00
commit 2d0e6a61b7
12001 changed files with 2431925 additions and 0 deletions

View File

@@ -0,0 +1,29 @@
{
"name": "CW.Common",
"rootNamespace": "",
"references": [
"Unity.InputSystem",
"Unity.RenderPipelines.Core.Runtime",
"Unity.RenderPipelines.HighDefinition.Runtime"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.render-pipelines.high-definition",
"expression": "",
"define": "__HDRP__"
},
{
"name": "com.unity.inputsystem",
"expression": "",
"define": "__INPUTSYSTEM__"
}
],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 637dfb2b87b2cf0499a8da5b0b91da54
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3fd74f0005021374780840b66d0eefc1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 206ff270d3884e74193a896d61f583c6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,28 @@
fileFormatVersion: 2
guid: da9a51ce28f0d7443a5bcbdbe04c4f4b
TrueTypeFontImporter:
externalObjects: {}
serializedVersion: 4
fontSize: 16
forceTextureCase: -2
characterSpacing: 0
characterPadding: 1
includeFontData: 1
fontName: Varela Round
fontNames:
- Varela Round
fallbackFontReferences:
- {fileID: 12800000, guid: 9d3d4dd557b981049813477256dc3ce2, type: 3}
- {fileID: 12800000, guid: ff571517d53cf074b86d221e07573a65, type: 3}
- {fileID: 12800000, guid: 3b7b1439619bf9340bca76d13d88b660, type: 3}
- {fileID: 12800000, guid: d54323c94c164de478170d5e7d0273be, type: 3}
- {fileID: 12800000, guid: 8d740e6d8d6ead245bde62e484121613, type: 3}
- {fileID: 12800000, guid: 7eef45af5c153d24ab577857816f16bc, type: 3}
customCharacters:
fontRenderingMode: 0
ascentCalculationMode: 1
useLegacyBoundsCalculation: 0
shouldRoundAdvanceValue: 1
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,93 @@
Copyright 2011-2016 The Varela Round Project Authors (https://github.com/alefalefalef/Varela-Round-Hebrew/), with Reserved Font Names 'Varela' and Varela Round.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 08365a11a49ae6f41ade544399c3da84
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 685ab5efc56b77343985bfc78c17ab5c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,77 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Grid
m_Shader: {fileID: 4800000, guid: 0d949f33aae55df4d92d64ec31581556, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 2800000, guid: 026cfa8e99aa0914faa770f5d4c58a23, type: 3}
m_Scale: {x: 100, y: 100}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 0, g: 0, b: 0, a: 0.5019608}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 41cd2401d126859418d064ea8f4fee8c
timeCreated: 1554524255
licenseType: Store
NativeFormatImporter:
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,88 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Skybox
m_Shader: {fileID: 4800000, guid: 960aca9aa5d48ad4b8b522dbbab26d8a, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 5
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 2800000, guid: 4101ccb8f2386d14c843c54610af1778, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Tex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _AtmosphereThickness: 2.79
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _EmissionScaleUI: 0
- _Exposure: 5.94
- _Glossiness: 0.5
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _Rotation: 0
- _Scale: 0.3
- _SrcBlend: 1
- _SunSize: 0.295
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _Color1: {r: 0.37800002, g: 0.9999997, b: 1, a: 1}
- _Color2: {r: 0, g: 0.17241383, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _EmissionColorUI: {r: 1, g: 1, b: 1, a: 1}
- _GroundColor: {r: 0.07586193, g: 0, b: 1, a: 1}
- _SkyTint: {r: 1, g: 0, b: 0, a: 1}
- _Tint: {r: 0.5, g: 0.5, b: 0.5, a: 0.5}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 17380c24072c0954898ab03528ac9077
timeCreated: 1474763489
licenseType: Store
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8ece9783b3fc55b4f85e26ef1cea10c8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,122 @@
using UnityEngine;
namespace CW.Common
{
/// <summary>This component allows you to freely rotate the current GameObject using local rotations.</summary>
[HelpURL(CwShared.HelpUrlPrefix + "CwCameraLook")]
[AddComponentMenu(CwShared.ComponentMenuPrefix + "Camera Look")]
public class CwCameraLook : MonoBehaviour
{
/// <summary>Is this component currently listening for inputs?</summary>
public bool Listen { set { listen = value; } get { return listen; } } [SerializeField] private bool listen = true;
/// <summary>How quickly the rotation transitions from the current to the target value (-1 = instant).</summary>
public float Damping { set { damping = value; } get { return damping; } } [SerializeField] private float damping = 10.0f;
/// <summary>How quickly the mouse/finger movements rotate the camera.</summary>
public float Sensitivity { set { sensitivity = value; } get { return sensitivity; } } [SerializeField] private float sensitivity = 1.0f;
/// <summary>The keys/fingers required to pitch down/up.</summary>
public CwInputManager.Axis PitchControls { set { pitchControls = value; } get { return pitchControls; } } [SerializeField] private CwInputManager.Axis pitchControls = new CwInputManager.Axis(1, true, CwInputManager.AxisGesture.VerticalDrag, -10.0f, KeyCode.None, KeyCode.None, KeyCode.None, KeyCode.None, 45.0f);
/// <summary>The keys/fingers required to yaw left/right.</summary>
public CwInputManager.Axis YawControls { set { yawControls = value; } get { return yawControls; } } [SerializeField] private CwInputManager.Axis yawControls = new CwInputManager.Axis(1, true, CwInputManager.AxisGesture.HorizontalDrag, 10.0f, KeyCode.None, KeyCode.None, KeyCode.None, KeyCode.None, 45.0f);
/// <summary>The keys/fingers required to roll left/right.</summary>
public CwInputManager.Axis RollControls { set { rollControls = value; } get { return rollControls; } } [SerializeField] private CwInputManager.Axis rollControls = new CwInputManager.Axis(2, true, CwInputManager.AxisGesture.Twist, 1.0f, KeyCode.E, KeyCode.Q, KeyCode.None, KeyCode.None, 45.0f);
[System.NonSerialized]
private Quaternion remainingDelta = Quaternion.identity;
protected virtual void Start()
{
CwInputManager.EnsureThisComponentExists();
}
protected virtual void OnDisable()
{
//oldMousePositionSet = false;
}
protected virtual void Update()
{
if (listen == true)
{
AddToDelta();
}
DampenDelta();
}
protected virtual void OnApplicationFocus(bool focus)
{
//oldMousePositionSet = false;
}
private void AddToDelta()
{
// Get delta from binds
var delta = default(Vector3);
delta.x = pitchControls.GetValue(Time.deltaTime);
delta.y = yawControls.GetValue(Time.deltaTime);
delta.z = rollControls.GetValue(Time.deltaTime);
delta *= sensitivity;
// Store old rotation
var oldRotation = transform.localRotation;
// Rotate
transform.Rotate(delta.x, delta.y, 0.0f, Space.Self);
transform.Rotate(0.0f, 0.0f, delta.z, Space.Self);
// Add to remaining
remainingDelta *= Quaternion.Inverse(oldRotation) * transform.localRotation;
// Revert rotation
transform.localRotation = oldRotation;
}
private void DampenDelta()
{
// Dampen remaining delta
var factor = CwHelper.DampenFactor(damping, Time.deltaTime);
var newDelta = Quaternion.Slerp(remainingDelta, Quaternion.identity, factor);
// Rotate by difference
transform.localRotation = transform.localRotation * Quaternion.Inverse(newDelta) * remainingDelta;
// Update remaining
remainingDelta = newDelta;
}
}
}
#if UNITY_EDITOR
namespace CW.Common
{
using UnityEditor;
using TARGET = CwCameraLook;
[CanEditMultipleObjects]
[CustomEditor(typeof(TARGET))]
public class CwCameraLook_Editor : CwEditor
{
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
Draw("listen", "Is this component currently listening for inputs?");
Draw("damping", "How quickly the rotation transitions from the current to the target value (-1 = instant).");
Separator();
Draw("pitchControls", "The keys/fingers required to pitch down/up.");
Draw("yawControls", "The keys/fingers required to yaw left/right.");
Draw("rollControls", "The keys/fingers required to roll left/right.");
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8f6d5316b170fe34e886c05572b3006e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,111 @@
using UnityEngine;
namespace CW.Common
{
/// <summary>This component allows you to freely move the current GameObject based on mouse/finger drags.</summary>
[HelpURL(CwShared.HelpUrlPrefix + "CwCameraMove")]
[AddComponentMenu(CwShared.ComponentMenuPrefix + "Camera Move")]
public class CwCameraMove : MonoBehaviour
{
/// <summary>Is this component currently listening for inputs?</summary>
public bool Listen { set { listen = value; } get { return listen; } } [SerializeField] private bool listen = true;
/// <summary>How quickly the position transitions from the current to the target value (-1 = instant).</summary>
public float Damping { set { damping = value; } get { return damping; } } [SerializeField] private float damping = 10.0f;
/// <summary>The movement speed will be multiplied by this.</summary>
public float Sensitivity { set { sensitivity = value; } get { return sensitivity; } } [SerializeField] private float sensitivity = 1.0f;
/// <summary>The keys/fingers required to move left/right.</summary>
public CwInputManager.Axis HorizontalControls { set { horizontalControls = value; } get { return horizontalControls; } } [SerializeField] private CwInputManager.Axis horizontalControls = new CwInputManager.Axis(2, false, CwInputManager.AxisGesture.HorizontalDrag, 1.0f, KeyCode.A, KeyCode.D, KeyCode.LeftArrow, KeyCode.RightArrow, 100.0f);
/// <summary>The keys/fingers required to move backward/forward.</summary>
public CwInputManager.Axis DepthControls { set { depthControls = value; } get { return depthControls; } } [SerializeField] private CwInputManager.Axis depthControls = new CwInputManager.Axis(2, false, CwInputManager.AxisGesture.HorizontalDrag, 1.0f, KeyCode.S, KeyCode.W, KeyCode.DownArrow, KeyCode.UpArrow, 100.0f);
/// <summary>The keys/fingers required to move down/up.</summary>
public CwInputManager.Axis VerticalControls { set { verticalControls = value; } get { return verticalControls; } } [SerializeField] private CwInputManager.Axis verticalControls = new CwInputManager.Axis(3, false, CwInputManager.AxisGesture.HorizontalDrag, 1.0f, KeyCode.F, KeyCode.R, KeyCode.None, KeyCode.None, 100.0f);
[System.NonSerialized]
private Vector3 remainingDelta;
protected virtual void Start()
{
CwInputManager.EnsureThisComponentExists();
}
protected virtual void Update()
{
if (listen == true)
{
AddToDelta();
}
DampenDelta();
}
private void AddToDelta()
{
// Get delta from binds
var delta = default(Vector3);
delta.x = horizontalControls.GetValue(Time.deltaTime);
delta.y = verticalControls .GetValue(Time.deltaTime);
delta.z = depthControls .GetValue(Time.deltaTime);
// Store old position
var oldPosition = transform.position;
// Translate
transform.Translate(delta * sensitivity * Time.deltaTime, Space.Self);
// Add to remaining
var acceleration = transform.position - oldPosition;
remainingDelta += acceleration;
// Revert position
transform.position = oldPosition;
}
private void DampenDelta()
{
// Dampen remaining delta
var factor = CwHelper.DampenFactor(damping, Time.deltaTime);
var newDelta = Vector3.Lerp(remainingDelta, Vector3.zero, factor);
// Translate by difference
transform.position += remainingDelta - newDelta;
// Update remaining
remainingDelta = newDelta;
}
}
}
#if UNITY_EDITOR
namespace CW.Common
{
using UnityEditor;
using TARGET = CwCameraMove;
[CanEditMultipleObjects]
[CustomEditor(typeof(TARGET))]
public class CwCameraMove_Editor : CwEditor
{
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
Draw("listen", "Is this component currently listening for inputs?");
Draw("damping", "How quickly the rotation transitions from the current to the target value (-1 = instant).");
Draw("sensitivity", "The movement speed will be multiplied by this.");
Separator();
Draw("horizontalControls", "The keys/fingers required to move right/left.");
Draw("depthControls", "The keys/fingers required to move backward/forward.");
Draw("verticalControls", "The keys/fingers required to move down/up.");
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4cabc7c514a17ca41a6c62cc43dcb94d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,93 @@
using UnityEngine;
namespace CW.Common
{
/// <summary>This component allows you to rotate the current GameObject using local Euler rotations, allowing you to create a typical FPS camera system, or orbital camera system.</summary>
[HelpURL(CwShared.HelpUrlPrefix + "CwCameraPivot")]
[AddComponentMenu(CwShared.ComponentMenuPrefix + "Camera Pivot")]
public class CwCameraPivot : MonoBehaviour
{
/// <summary>Is this component currently listening for inputs?</summary>
public bool Listen { set { listen = value; } get { return listen; } } [SerializeField] private bool listen = true;
/// <summary>How quickly the position transitions from the current to the target value (-1 = instant).</summary>
public float Damping { set { damping = value; } get { return damping; } } [SerializeField] private float damping = 10.0f;
/// <summary>The keys/fingers required to pitch down/up.</summary>
public CwInputManager.Axis PitchControls { set { pitchControls = value; } get { return pitchControls; } } [SerializeField] private CwInputManager.Axis pitchControls = new CwInputManager.Axis(1, true, CwInputManager.AxisGesture.VerticalDrag, -0.1f, KeyCode.None, KeyCode.None, KeyCode.None, KeyCode.None, 45.0f);
/// <summary>The keys/fingers required to yaw left/right.</summary>
public CwInputManager.Axis YawControls { set { yawControls = value; } get { return yawControls; } } [SerializeField] private CwInputManager.Axis yawControls = new CwInputManager.Axis(1, true, CwInputManager.AxisGesture.HorizontalDrag, 0.1f, KeyCode.None, KeyCode.None, KeyCode.None, KeyCode.None, 45.0f);
[System.NonSerialized]
private Vector3 remainingDelta;
protected virtual void OnEnable()
{
CwInputManager.EnsureThisComponentExists();
}
protected virtual void Update()
{
if (listen == true)
{
AddToDelta();
}
DampenDelta();
}
private void AddToDelta()
{
remainingDelta.x += pitchControls.GetValue(Time.deltaTime);
remainingDelta.y += yawControls .GetValue(Time.deltaTime);
}
private void DampenDelta()
{
// Dampen remaining delta
var factor = CwHelper.DampenFactor(damping, Time.deltaTime);
var newDelta = Vector3.Lerp(remainingDelta, Vector3.zero, factor);
// Rotate by difference
var euler = transform.localEulerAngles;
euler.x = -Mathf.DeltaAngle(euler.x, 0.0f);
euler += remainingDelta - newDelta;
euler.x = Mathf.Clamp(euler.x, -89.0f, 89.0f);
transform.localEulerAngles = euler;
// Update remaining
remainingDelta = newDelta;
}
}
}
#if UNITY_EDITOR
namespace CW.Common
{
using UnityEditor;
using TARGET = CwCameraPivot;
[CanEditMultipleObjects]
[CustomEditor(typeof(TARGET))]
public class CwCameraPivot_Editor : CwEditor
{
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
Draw("listen", "Is this component currently listening for inputs?");
Draw("damping", "How quickly the rotation transitions from the current to the target value (-1 = instant).");
Separator();
Draw("pitchControls", "The keys/fingers required to pitch down/up.");
Draw("yawControls", "The keys/fingers required to yaw left/right.");
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4c5a919098a173e40a35fd1c493ae39e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,213 @@
using UnityEngine;
using UnityEngine.Rendering;
namespace CW.Common
{
/// <summary>This component is used by all the demo scenes to perform common tasks. Including modifying the current scene to make it look consistent between different rendering pipelines.</summary>
[ExecuteInEditMode]
[AddComponentMenu("")]
public class CwDemo : MonoBehaviour
{
/// <summary>If you enable this setting and your project is running with the new InputSystem then the <b>EventSystem's InputModule</b> component will be upgraded.</summary>
public bool UpgradeInputModule { set { upgradeInputModule = value; } get { return upgradeInputModule; } } [SerializeField] private bool upgradeInputModule = true;
/// <summary>If you enable this setting and your project is running with HDRP then a <b>Volume</b> component will be added to the scene that adjusts the camera exposure to match the other pipelines.</summary>
public bool ChangeExposureInHDRP { set { changeExposureInHDRP = value; } get { return changeExposureInHDRP; } } [SerializeField] private bool changeExposureInHDRP = true;
/// <summary>If you enable this setting and your project is running with HDRP then a <b>Volume</b> component will be added to the scene that adjusts the background to match the other pipelines.</summary>
public bool ChangeVisualEnvironmentInHDRP { set { changeVisualEnvironmentInHDRP = value; } get { return changeVisualEnvironmentInHDRP; } } [SerializeField] private bool changeVisualEnvironmentInHDRP = true;
/// <summary>If you enable this setting and your project is running with HDRP then a <b>Volume</b> component will be added to the scene that adjusts the fog to match the other pipelines.</summary>
public bool ChangeFogInHDRP { set { changeFogInHDRP = value; } get { return changeFogInHDRP; } } [SerializeField] private bool changeFogInHDRP = true;
/// <summary>If you enable this setting and your project is running with HDRP then a <b>Volume</b> component will be added to the scene that adjusts the clouds to match the other pipelines.</summary>
public bool ChangeCloudsInHDRP { set { changeCloudsInHDRP = value; } get { return changeCloudsInHDRP; } } [SerializeField] private bool changeCloudsInHDRP = true;
/// <summary>If you enable this setting and your project is running with HDRP then a <b>Volume</b> component will be added to the scene that adjusts the motion blur to match the other pipelines.</summary>
public bool ChangeMotionBlurInHDRP { set { changeMotionBlurInHDRP = value; } get { return changeMotionBlurInHDRP; } } [SerializeField] private bool changeMotionBlurInHDRP = true;
/// <summary>If you enable this setting and your project is running with HDRP then any lights missing the <b>HDAdditionalLightData</b> component will have it added.</summary>
public bool UpgradeLightsInHDRP { set { upgradeLightsInHDRP = value; } get { return upgradeLightsInHDRP; } } [SerializeField] private bool upgradeLightsInHDRP = true;
/// <summary>If you enable this setting and your project is running with HDRP then any cameras missing the <b>HDAdditionalCameraData</b> component will have it added.</summary>
public bool UpgradeCamerasInHDRP { set { upgradeCamerasInHDRP = value; } get { return upgradeCamerasInHDRP; } } [SerializeField] private bool upgradeCamerasInHDRP = true;
protected virtual void OnEnable()
{
if (upgradeInputModule == true)
{
TryUpgradeEventSystem();
}
if (CwHelper.IsURP == true)
{
TryApplyURP();
}
if (CwHelper.IsHDRP == true)
{
TryApplyHDRP();
}
}
protected virtual void TryApplyURP()
{
}
protected virtual void TryApplyHDRP()
{
if (changeExposureInHDRP == true || changeVisualEnvironmentInHDRP == true || changeFogInHDRP == true)
{
TryCreateVolume();
}
if (upgradeLightsInHDRP == true)
{
TryUpgradeLights();
}
if (upgradeCamerasInHDRP == true)
{
TryUpgradeCameras();
}
}
private void TryCreateVolume()
{
#if __HDRP__
var volume = GetComponent<Volume>();
if (volume == null)
{
volume = gameObject.AddComponent<Volume>();
}
var profile = volume.profile;
if (profile == null)
{
profile = ScriptableObject.CreateInstance<VolumeProfile>();
profile.hideFlags = HideFlags.DontSaveInBuild | HideFlags.DontSaveInEditor;
}
if (profile.components.Count == 0)
{
name = "Demo (Volume Added)";
if (changeExposureInHDRP == true)
{
var exposure = profile.Add<UnityEngine.Rendering.HighDefinition.Exposure>(true);
exposure.fixedExposure.value = 14.0f;
}
if (changeVisualEnvironmentInHDRP == true)
{
var visualEnvironment = profile.Add<UnityEngine.Rendering.HighDefinition.VisualEnvironment>(true);
visualEnvironment.skyType.value = 0;
}
if (changeFogInHDRP == true)
{
var fog = profile.Add<UnityEngine.Rendering.HighDefinition.Fog>(true);
fog.enabled.value = false;
}
#if UNITY_2021_2_OR_NEWER
if (changeCloudsInHDRP == true)
{
var clouds = profile.Add<UnityEngine.Rendering.HighDefinition.VolumetricClouds>(true);
clouds.enable.value = false;
}
#endif
if (changeMotionBlurInHDRP == true)
{
var motionBlur = profile.Add<UnityEngine.Rendering.HighDefinition.MotionBlur>(true);
motionBlur.intensity.value = 0.0f;
}
}
volume.profile = profile;
#endif
}
private void TryUpgradeLights()
{
#if __HDRP__
foreach (var light in CwHelper.FindObjectsByType<Light>())
{
if (light.GetComponent<UnityEngine.Rendering.HighDefinition.HDAdditionalLightData>() == null)
{
light.gameObject.AddComponent<UnityEngine.Rendering.HighDefinition.HDAdditionalLightData>();
}
}
#endif
}
private void TryUpgradeCameras()
{
#if __HDRP__
foreach (var camera in CwHelper.FindObjectsByType<Camera>())
{
if (camera.GetComponent<UnityEngine.Rendering.HighDefinition.HDAdditionalCameraData>() == null)
{
var hdCamera = camera.gameObject.AddComponent<UnityEngine.Rendering.HighDefinition.HDAdditionalCameraData>();
hdCamera.backgroundColorHDR = Color.black;
}
}
#endif
}
private void TryUpgradeEventSystem()
{
#if UNITY_EDITOR && ENABLE_INPUT_SYSTEM && __INPUTSYSTEM__
var module = CwHelper.FindAnyObjectByType<UnityEngine.EventSystems.StandaloneInputModule>();
if (module != null)
{
module.gameObject.AddComponent<UnityEngine.InputSystem.UI.InputSystemUIInputModule>();
DestroyImmediate(module);
}
#endif
}
}
}
#if UNITY_EDITOR
namespace CW.Common
{
using UnityEditor;
using TARGET = CwDemo;
[CustomEditor(typeof(TARGET))]
public class CwDemo_Editor : CwEditor
{
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
Draw("upgradeInputModule", "If you enable this setting and your project is running with the new InputSystem then the EventSystem's InputModule component will be upgraded.");
Separator();
Draw("changeExposureInHDRP", "If you enable this setting and your project is running with HDRP then a Volume component will be added to this GameObject that adjusts the camera exposure to match the other pipelines.");
Draw("changeVisualEnvironmentInHDRP", "If you enable this setting and your project is running with HDRP then a Volume component will be added to this GameObject that adjusts the background to match the other pipelines.");
Draw("changeFogInHDRP", "If you enable this setting and your project is running with HDRP then a Volume component will be added to the scene that adjusts the fog to match the other pipelines.");
Draw("changeCloudsInHDRP", "If you enable this setting and your project is running with HDRP then a Volume component will be added to the scene that adjusts the clouds to match the other pipelines.");
Draw("changeMotionBlurInHDRP", "If you enable this setting and your project is running with HDRP then a <b>Volume</b> component will be added to the scene that adjusts the motion blur to match the other pipelines.");
Draw("upgradeLightsInHDRP", "If you enable this setting and your project is running with HDRP then any lights missing the HDAdditionalLightData component will have it added.");
Draw("upgradeCamerasInHDRP", "If you enable this setting and your project is running with HDRP then any cameras missing the HDAdditionalCameraData component will have it added.");
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a5270a8e97f926a4bbcf95d4fa31866d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,245 @@
using UnityEngine;
using UnityEngine.EventSystems;
namespace CW.Common
{
/// <summary>This component turns the current UI element into a button that links to the specified action.</summary>
[ExecuteInEditMode]
[HelpURL(CwShared.HelpUrlPrefix + "CwDemoButton")]
[AddComponentMenu(CwShared.ComponentMenuPrefix + "Demo Button")]
public class CwDemoButton : MonoBehaviour, IPointerDownHandler
{
public enum LinkType
{
PreviousScene,
NextScene,
Publisher,
URL,
Isolate
}
public enum ToggleType
{
KeepSelected,
ToggleSelection,
SelectPrevious
}
/// <summary>The action that will be performed when this UI element is clicked.</summary>
public LinkType Link { set { link = value; } get { return link; } } [SerializeField] private LinkType link;
/// <summary>The URL that will be opened.</summary>
public string UrlTarget { set { urlTarget = value; } get { return urlTarget; } } [SerializeField] private string urlTarget;
/// <summary>If this GameObject is active, then the button will be faded in.</summary>
public Transform IsolateTarget { set { isolateTarget = value; } get { return isolateTarget; } } [SerializeField] private Transform isolateTarget;
/// <summary>If this button is already selected and you click/tap it again, what should happen?</summary>
public ToggleType IsolateToggle { set { isolateToggle = value; } get { return isolateToggle; } } [SerializeField] private ToggleType isolateToggle;
[System.NonSerialized]
private CanvasGroup cachedCanvasGroup;
[System.NonSerialized]
private Transform previousChild;
protected virtual void OnEnable()
{
cachedCanvasGroup = GetComponent<CanvasGroup>();
}
protected virtual void Update()
{
var group = GetComponent<CanvasGroup>();
if (group != null)
{
var alpha = 1.0f;
switch (link)
{
case LinkType.PreviousScene:
case LinkType.NextScene:
{
alpha = GetCurrentLevel() >= 0 && GetLevelCount() > 1 ? 1.0f : 0.0f;
}
break;
case LinkType.Isolate:
{
if (isolateTarget != null)
{
alpha = isolateTarget.gameObject.activeInHierarchy == true ? 1.0f : 0.5f;
}
}
break;
}
group.alpha = alpha;
group.blocksRaycasts = alpha > 0.0f;
group.interactable = alpha > 0.0f;
}
}
public void OnPointerDown(PointerEventData eventData)
{
switch (link)
{
case LinkType.PreviousScene:
{
var index = GetCurrentLevel();
if (index >= 0)
{
if (--index < 0)
{
index = GetLevelCount() - 1;
}
LoadLevel(index);
}
}
break;
case LinkType.NextScene:
{
var index = GetCurrentLevel();
if (index >= 0)
{
if (++index >= GetLevelCount())
{
index = 0;
}
LoadLevel(index);
}
}
break;
case LinkType.Publisher:
{
Application.OpenURL("https://carloswilkes.com");
}
break;
case LinkType.URL:
{
if (string.IsNullOrEmpty(urlTarget) == false)
{
Application.OpenURL(urlTarget);
}
}
break;
case LinkType.Isolate:
{
if (isolateTarget != null)
{
var parent = isolateTarget.transform.parent;
var active = isolateTarget.gameObject.activeSelf;
foreach (Transform child in parent.transform)
{
if (child.gameObject.activeSelf == true)
{
if (child != isolateTarget)
{
previousChild = child;
}
child.gameObject.SetActive(false);
}
}
switch (isolateToggle)
{
case ToggleType.KeepSelected:
{
isolateTarget.gameObject.SetActive(true);
}
break;
case ToggleType.ToggleSelection:
{
isolateTarget.gameObject.SetActive(active == false);
}
break;
case ToggleType.SelectPrevious:
{
if (active == true && previousChild != null)
{
previousChild.gameObject.SetActive(true);
}
else
{
isolateTarget.gameObject.SetActive(true);
}
}
break;
}
}
}
break;
}
}
private static int GetCurrentLevel()
{
var scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene();
var index = scene.buildIndex;
if (index >= 0)
{
if (UnityEngine.SceneManagement.SceneManager.GetSceneByBuildIndex(index).handle != scene.handle)
{
return -1;
}
}
return index;
}
private static int GetLevelCount()
{
return UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings;
}
private static void LoadLevel(int index)
{
UnityEngine.SceneManagement.SceneManager.LoadScene(index);
}
}
}
#if UNITY_EDITOR
namespace CW.Common
{
using UnityEditor;
using TARGET = CwDemoButton;
[CanEditMultipleObjects]
[CustomEditor(typeof(TARGET))]
public class CwDemoButton_Editor : CwEditor
{
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
Draw("link", "The action that will be performed when this UI element is clicked.");
BeginIndent();
if (Any(tgts, t => t.Link == CwDemoButton.LinkType.URL))
{
Draw("urlTarget", "The URL that will be opened.", "Target");
}
if (Any(tgts, t => t.Link == CwDemoButton.LinkType.Isolate))
{
Draw("isolateTarget", "If this GameObject is active, then the button will be faded in.", "Target");
Draw("isolateToggle", "If this button is already selected and you click/tap it again, what should happen?", "Toggle");
}
EndIndent();
}
}
}
#endif

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 207d6a51d513da54db00bf553470072f
timeCreated: 1574550986
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,124 @@
using UnityEngine;
using UnityEngine.UI;
using CW.Common;
namespace CW.Common
{
/// <summary>This component allows you to quickly build a UI button to activate only this GameObject when clicked.</summary>
[HelpURL(CwShared.HelpUrlPrefix + "CwDemoButtonBuilder")]
[AddComponentMenu(CwShared.ComponentMenuPrefix + "Demo Button Builder")]
public class CwDemoButtonBuilder : MonoBehaviour
{
/// <summary>The built button will be based on this prefab.</summary>
public GameObject ButtonPrefab { set { buttonPrefab = value; } get { return buttonPrefab; } } [SerializeField] private GameObject buttonPrefab;
/// <summary>The built button will be placed under this transform.</summary>
public RectTransform ButtonRoot { set { buttonRoot = value; } get { return buttonRoot; } } [SerializeField] private RectTransform buttonRoot;
/// <summary>The icon given to this button.</summary>
public Sprite Icon { set { icon = value; } get { return icon; } } [SerializeField] private Sprite icon;
/// <summary>The icon will be tinted by this.</summary>
public Color Color { set { color = value; } get { return color; } } [SerializeField] private Color color = Color.white;
/// <summary>Use a different name for the button text?</summary>
public string OverrideName { set { overrideName = value; } get { return overrideName; } } [SerializeField] [Multiline(3)] private string overrideName;
[SerializeField]
private GameObject clone;
[ContextMenu("Build")]
public void Build()
{
if (clone != null)
{
DestroyImmediate(clone);
}
if (buttonPrefab != null)
{
clone = DoInstantiate();
clone.name = name;
var image = clone.GetComponent<Image>();
if (image != null)
{
image.sprite = icon;
image.color = color;
}
var title = clone.GetComponentInChildren<Text>();
if (title != null)
{
title.text = string.IsNullOrEmpty(overrideName) == false ? overrideName : name;
}
var isolate = clone.GetComponent<CwDemoButton>();
if (isolate != null)
{
isolate.IsolateTarget = transform;
}
}
}
[ContextMenu("Build All")]
public void BuildAll()
{
foreach (var builder in transform.parent.GetComponentsInChildren<CwDemoButtonBuilder>(true))
{
builder.Build();
}
}
private GameObject DoInstantiate()
{
#if UNITY_EDITOR
if (Application.isPlaying == false)
{
return (GameObject)UnityEditor.PrefabUtility.InstantiatePrefab(buttonPrefab, buttonRoot);
}
#endif
return Instantiate(buttonPrefab, buttonRoot, false);
}
}
}
#if UNITY_EDITOR
namespace PaintIn3D
{
using UnityEditor;
using TARGET = CwDemoButtonBuilder;
[CanEditMultipleObjects]
[CustomEditor(typeof(TARGET))]
public class CwDemoButtonBuilder_Editor : CwEditor
{
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
Draw("buttonPrefab", "The built button will be based on this prefab.");
Draw("buttonRoot", "The built button will be placed under this transform.");
Separator();
Draw("icon", "The icon given to this button.");
Draw("color", "The icon will be tinted by this.");
Draw("overrideName", "Use a different name for the button text?");
Separator();
if (Button("Build All") == true)
{
Undo.RecordObjects(tgts, "Build All");
tgt.BuildAll();
}
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ee2055732bd5a4a4a8f4fe43e20eca6e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,103 @@
using UnityEngine;
using CW.Common;
namespace CW.Common
{
/// <summary>This component allows you to control a Camera component's depthTextureMode setting.</summary>
[ExecuteInEditMode]
[DisallowMultipleComponent]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("CW/Common/CW Depth Texture Mode")]
public class CwDepthTextureMode : MonoBehaviour
{
/// <summary>The depth mode that will be applied to the camera.</summary>
public DepthTextureMode DepthMode { set { depthMode = value; UpdateDepthMode(); } get { return depthMode; } } [SerializeField] private DepthTextureMode depthMode = DepthTextureMode.None;
[System.NonSerialized]
private Camera cachedCamera;
public void UpdateDepthMode()
{
if (cachedCamera == null) cachedCamera = GetComponent<Camera>();
cachedCamera.depthTextureMode = depthMode;
}
protected virtual void Update()
{
UpdateDepthMode();
}
}
}
#if UNITY_EDITOR
namespace CW.Common
{
using UnityEditor;
using TARGET = CwDepthTextureMode;
[CanEditMultipleObjects]
[CustomEditor(typeof(TARGET))]
public class CwDepthTextureMode_Editor : CwEditor
{
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
Draw("depthMode", "The depth mode that will be applied to the camera.");
}
public static void RequireDepth()
{
var found = false;
foreach (var camera in Camera.allCameras)
{
var mask = camera.depthTextureMode;
if (mask == DepthTextureMode.DepthNormals || ((int)mask & 1) != 0)
{
found = true; break;
}
}
if (found == false)
{
CwEditor.Separator();
if (Camera.main != null)
{
if (WritesDepth(Camera.main) == false)
{
if (CwEditor.HelpButton("This component requires your camera to render a Depth Texture, but it doesn't.", UnityEditor.MessageType.Error, "Fix", 50.0f) == true)
{
CwHelper.GetOrAddComponent<CwDepthTextureMode>(Camera.main.gameObject).DepthMode = DepthTextureMode.Depth;
CwHelper.SelectAndPing(Camera.main);
}
}
}
else
{
CwEditor.Error("This component requires your camera to render a Depth Texture, but none of the cameras in your scene do. This can be fixed with the SgtDepthTextureMode component.");
foreach (var camera in Camera.allCameras)
{
if (CwHelper.Enabled(camera) == true)
{
CwHelper.GetOrAddComponent<CwDepthTextureMode>(camera.gameObject).DepthMode = DepthTextureMode.Depth;
CwHelper.SelectAndPing(camera);
}
}
}
}
}
private static bool WritesDepth(Camera camera)
{
return camera != null && camera.depthTextureMode == DepthTextureMode.DepthNormals || ((int)camera.depthTextureMode & 1) != 0;
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 543105670369c7e49b28b587c69ad997
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,115 @@
using UnityEngine;
using CW.Common;
namespace CW.Common
{
/// <summary>This component will change the light intensity based on the current render pipeline.</summary>
[ExecuteInEditMode]
[RequireComponent(typeof(Light))]
[AddComponentMenu("CW/Common/CW Light Intensity")]
public class CwLightIntensity : MonoBehaviour
{
/// <summary>All light values will be multiplied by this before use.</summary>
public float Multiplier { set { multiplier = value; } get { return multiplier; } } [SerializeField] private float multiplier = 1.0f;
/// <summary>This allows you to control the intensity of the attached light when using the <b>Standard</b> rendering pipeline.
/// -1 = The attached light intensity will not be modified.</summary>
public float IntensityInStandard { set { intensityInStandard = value; } get { return intensityInStandard; } } [SerializeField] private float intensityInStandard = 1.0f;
/// <summary>This allows you to control the intensity of the attached light when using the <b>URP</b> rendering pipeline.
/// -1 = The attached light intensity will not be modified.</summary>
public float IntensityInURP { set { intensityInURP = value; } get { return intensityInURP; } } [SerializeField] private float intensityInURP = 1.0f;
/// <summary>This allows you to control the intensity of the attached light when using the <b>HDRP</b> rendering pipeline.
/// -1 = The attached light intensity will not be modified.</summary>
public float IntensityInHDRP { set { intensityInHDRP = value; } get { return intensityInHDRP; } } [SerializeField] private float intensityInHDRP = 120000.0f;
[System.NonSerialized]
private Light cachedLight;
[System.NonSerialized]
private bool cachedLightSet;
#if __HDRP__
[System.NonSerialized]
private UnityEngine.Rendering.HighDefinition.HDAdditionalLightData cachedLightData;
#endif
public Light CachedLight
{
get
{
if (cachedLightSet == false)
{
cachedLight = GetComponent<Light>();
cachedLightSet = true;
}
return cachedLight;
}
}
protected virtual void Update()
{
if (CwHelper.IsBIRP == true)
{
ApplyIntensity(intensityInStandard);
}
else if (CwHelper.IsURP == true)
{
ApplyIntensity(intensityInURP);
}
else if (CwHelper.IsHDRP == true)
{
ApplyIntensity(intensityInHDRP);
}
}
private void ApplyIntensity(float intensity)
{
if (intensity >= 0.0f)
{
if (cachedLightSet == false)
{
cachedLight = GetComponent<Light>();
cachedLightSet = true;
}
#if __HDRP__
if (cachedLightData == null)
{
cachedLightData = GetComponent<UnityEngine.Rendering.HighDefinition.HDAdditionalLightData>();
}
if (cachedLightData != null)
{
cachedLightData.SetIntensity(intensity * multiplier, UnityEngine.Rendering.HighDefinition.LightUnit.Lux);
}
#else
cachedLight.intensity = intensity * multiplier;
#endif
}
}
}
}
#if UNITY_EDITOR
namespace CW.Common
{
using UnityEditor;
using TARGET = CwLightIntensity;
[CanEditMultipleObjects]
[CustomEditor(typeof(TARGET))]
public class P3dLight_Editor : CwEditor
{
protected override void OnInspector()
{
Draw("multiplier", "All light values will be multiplied by this before use.");
Draw("intensityInStandard", "This allows you to control the intensity of the attached light when using the Standard rendering pipeline.\n\n-1 = The attached light intensity will not be modified.");
Draw("intensityInURP", "This allows you to control the intensity of the attached light when using the URP rendering pipeline.\n\n-1 = The attached light intensity will not be modified.");
Draw("intensityInHDRP", "This allows you to control the intensity of the attached light when using the HDRP rendering pipeline.\n\n-1 = The attached light intensity will not be modified.");
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1c97b30f38749284eab37996f9f5bd2a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,44 @@
using UnityEngine;
namespace CW.Common
{
/// <summary>This component rotates the current <b>Transform</b>.</summary>
[HelpURL(CwShared.HelpUrlPrefix + "CwRotate")]
[AddComponentMenu(CwShared.ComponentMenuPrefix + "Rotate")]
public class CwRotate : MonoBehaviour
{
/// <summary>The speed of the rotation in degrees per second.</summary>
public Vector3 AngularVelocity { set { angularVelocity = value; } get { return angularVelocity; } } [SerializeField] private Vector3 angularVelocity = Vector3.up;
/// <summary>The rotation space.</summary>
public Space RelativeTo { set { relativeTo = value; } get { return relativeTo; } } [SerializeField] private Space relativeTo;
protected virtual void Update()
{
transform.Rotate(angularVelocity * Time.deltaTime, relativeTo);
}
}
}
#if UNITY_EDITOR
namespace CW.Common
{
using UnityEditor;
using TARGET = CwRotate;
[CanEditMultipleObjects]
[CustomEditor(typeof(TARGET))]
public class CwRotate_Editor : CwEditor
{
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
BeginError(Any(tgts, t => t.AngularVelocity.magnitude == 0.0f));
Draw("angularVelocity", "The speed of the rotation in degrees per second.");
EndError();
Draw("relativeTo", "The rotation space.");
}
}
}
#endif

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 92ede0252ef7e92459ff5df2a16cd28e
timeCreated: 1526027124
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: b77d517d5da251844a7289759e258705
folderAsset: yes
timeCreated: 1474763801
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,70 @@
Shader "CW/RimAlpha"
{
Properties
{
_MainTex("Main Tex", 2D) = "white" {}
_Color("Color", Color) = (1.0, 1.0, 1.0, 1.0)
}
SubShader
{
Tags
{
"Queue" = "Transparent"
"PreviewType" = "Sphere"
"DisableBatching" = "True"
}
Blend SrcAlpha OneMinusSrcAlpha
ZWrite Off
Pass
{
CGPROGRAM
#pragma vertex Vert
#pragma fragment Frag
#include "UnityCG.cginc"
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _Color;
struct a2v
{
float4 vertex : POSITION;
float4 normal : NORMAL;
float4 color : COLOR;
float2 texcoord0 : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
float3 normal : TEXCOORD1;
float3 direction : TEXCOORD2;
float4 color : COLOR;
};
struct f2g
{
float4 color : SV_TARGET;
};
void Vert(a2v i, out v2f o)
{
o.vertex = UnityObjectToClipPos(i.vertex);
o.uv = TRANSFORM_TEX(i.texcoord0, _MainTex);
o.normal = mul((float3x3)unity_ObjectToWorld, i.normal);
o.direction = _WorldSpaceCameraPos - mul(unity_ObjectToWorld, i.vertex).xyz;
o.color = i.color * _Color;
}
void Frag(v2f i, out f2g o)
{
o.color = tex2D(_MainTex, i.uv) * i.color;
}
ENDCG
} // Pass
} // SubShader
} // Shader

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 0d949f33aae55df4d92d64ec31581556
timeCreated: 1474810484
licenseType: Store
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,98 @@
Shader "CW/RimOpaque"
{
Properties
{
_MainTex("Main Tex", 2D) = "white" {}
_Color("Color", Color) = (1.0, 1.0, 1.0, 1.0)
_Color1("Color 1", Color) = (1.0, 0.5, 0.5, 1.0)
_Color2("Color 2", Color) = (0.5, 0.5, 1.0, 1.0)
_Rim("Rim", Float) = 1.0
_Shift("Shift", Float) = 1.0
}
SubShader
{
Cull Off
Tags
{
"Queue" = "Geometry"
"DisableBatching" = "True"
}
Pass
{
CGPROGRAM
#pragma vertex Vert
#pragma fragment Frag
#include "UnityCG.cginc"
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _Color;
float4 _Color1;
float4 _Color2;
float _Rim;
float _Shift;
struct a2v
{
float4 vertex : POSITION;
float4 normal : NORMAL;
float4 color : COLOR;
float2 texcoord0 : TEXCOORD0;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
float3 normal : TEXCOORD1;
float3 direction : TEXCOORD2;
float4 screenPos : TEXCOORD3;
float4 color : COLOR;
};
struct f2g
{
float4 color : SV_TARGET;
};
float Dither(float4 ScreenPosition)
{
float2 uv = ScreenPosition.xy * _ScreenParams.xy;
float DITHER_THRESHOLDS[16] =
{
1.0 / 17.0, 9.0 / 17.0, 3.0 / 17.0, 11.0 / 17.0,
13.0 / 17.0, 5.0 / 17.0, 15.0 / 17.0, 7.0 / 17.0,
4.0 / 17.0, 12.0 / 17.0, 2.0 / 17.0, 10.0 / 17.0,
16.0 / 17.0, 8.0 / 17.0, 14.0 / 17.0, 6.0 / 17.0
};
uint index = (uint(uv.x) % 4) * 4 + uint(uv.y) % 4;
return DITHER_THRESHOLDS[index];
}
void Vert(a2v i, out v2f o)
{
o.vertex = UnityObjectToClipPos(i.vertex);
o.uv = TRANSFORM_TEX(i.texcoord0, _MainTex);
o.normal = mul((float3x3)unity_ObjectToWorld, i.normal);
o.direction = _WorldSpaceCameraPos - mul(unity_ObjectToWorld, i.vertex).xyz;
o.screenPos = ComputeScreenPos(o.vertex);
o.color = i.color * _Color;
}
void Frag(v2f i, out f2g o)
{
float ang = abs(dot(normalize(i.direction), normalize(i.normal)));
float rim = _Shift - pow(saturate(1.0f - ang), _Rim);
o.color = tex2D(_MainTex, i.uv) * i.color * lerp(_Color1, _Color2, rim);
clip(o.color.a - Dither(i.screenPos / i.screenPos.w));
}
ENDCG
} // Pass
} // SubShader
} // Shader

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 952471cc7e81a214fbe1eade4ae7c649
timeCreated: 1497417690
licenseType: Store
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,59 @@
Shader "CW/Skybox"
{
Properties
{
_Color1("Color 1", Color) = (1.0, 0.5, 0.5, 1.0)
_Color2("Color 2", Color) = (0.5, 0.5, 1.0, 1.0)
_Scale("Scale", Float) = 1.0
}
SubShader
{
Cull Front
ZWrite Off
Tags
{
"Queue" = "Geometry"
"PreviewType" = "Skybox"
}
Pass
{
CGPROGRAM
#pragma vertex Vert
#pragma fragment Frag
float4 _Color1;
float4 _Color2;
float _Scale;
struct a2v
{
float4 vertex : POSITION;
};
struct v2f
{
float4 vertex : SV_POSITION;
float4 position : TEXCOORD0;
};
struct f2g
{
float4 color : SV_TARGET;
};
void Vert(a2v i, out v2f o)
{
o.vertex = o.position = UnityObjectToClipPos(i.vertex);
}
void Frag(v2f i, out f2g o)
{
o.color = lerp(_Color1, _Color2, length(i.position.xy / i.position.w) * _Scale);
}
ENDCG
} // Pass
} // SubShader
} // Shader

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 960aca9aa5d48ad4b8b522dbbab26d8a
timeCreated: 1474763809
licenseType: Store
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8cf01d56b89089d42be94e77d527be91
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

View File

@@ -0,0 +1,99 @@
fileFormatVersion: 2
guid: 4c8c2181307afa7468274ba3e0d16e9c
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 9
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: 1
wrapV: 1
wrapW: -1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 108, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: 4d5051848484c9a44945ce5d706f31f0
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -0,0 +1,99 @@
fileFormatVersion: 2
guid: 8548d034b532fc64f9e26ecfe5f35ff7
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 9
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 2
aniso: 8
mipBias: -100
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 20, z: 21, w: 20}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: a3eaf35dd2392604aae3d8c3eae112bb
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -0,0 +1,99 @@
fileFormatVersion: 2
guid: 873b489a73575b14fa7f49597735beaa
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 9
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 2
aniso: 8
mipBias: -100
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 21, y: 20, z: 0, w: 20}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 2
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- serializedVersion: 2
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: a9a0d2cbd7735514a85086cb89845fc6
vertices: []
indices:
edges: []
weights: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -0,0 +1,76 @@
fileFormatVersion: 2
guid: 026cfa8e99aa0914faa770f5d4c58a23
timeCreated: 1554521128
licenseType: Store
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 4
mipmaps:
mipMapMode: 0
enableMipMap: 1
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
filterMode: 2
aniso: 8
mipBias: -1
wrapMode: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 128
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
textureType: 0
textureShape: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
- buildTarget: Standalone
maxTextureSize: 2048
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f9d0d3468e28b7846a32128b6898ca6f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 388552ada77be9a4ea13526b21d3a28d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,47 @@
using UnityEngine;
namespace CW.Common
{
/// <summary>This is the base class for all components that are created as children of another component, allowing them to be more easily managed.</summary>
public abstract class CwChild : MonoBehaviour
{
public interface IHasChildren
{
bool HasChild(CwChild child);
}
[ContextMenu("Destroy GameObject If Invalid All")]
public void DestroyGameObjectIfInvalidAll()
{
if (transform.parent != null)
{
foreach (var siblings in transform.parent.GetComponentsInChildren<CwChild>())
{
siblings.DestroyGameObjectIfInvalid();
}
}
}
[ContextMenu("Destroy GameObject If Invalid")]
public void DestroyGameObjectIfInvalid()
{
var parent = GetParent();
if (parent == null || parent.HasChild(this) == false)
{
#if UNITY_EDITOR
UnityEditor.Undo.DestroyObjectImmediate(gameObject);
#else
DestroyImmediate(gameObject);
#endif
}
}
protected abstract IHasChildren GetParent();
protected virtual void Start()
{
//DestroyGameObjectIfInvalid();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8d2ec44108dda21438f164cae219f224
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,139 @@
using UnityEngine;
namespace CW.Common
{
/// <summary>This makes the current <b>Transform</b> follow the <b>Target</b> Transform as if it were a child.</summary>
[ExecuteInEditMode]
[HelpURL(CwShared.HelpUrlPrefix + "CwFollow")]
[AddComponentMenu(CwShared.ComponentMenuPrefix + "Follow")]
public class CwFollow : MonoBehaviour
{
public enum FollowType
{
TargetTransform,
MainCamera
}
public enum UpdateType
{
Update,
LateUpdate
}
/// <summary>What should this component follow?</summary>
public FollowType Follow { set { follow = value; } get { return follow; } } [SerializeField] private FollowType follow;
/// <summary>The transform that will be followed.</summary>
public Transform Target { set { target = value; } get { return target; } } [SerializeField] private Transform target;
/// <summary>How quickly this Transform follows the target.
/// -1 = instant.</summary>
public float Damping { set { damping = value; } get { return damping; } } [SerializeField] private float damping = -1.0f;
/// <summary>Follow the target's rotation too?</summary>
public bool Rotate { set { rotate = value; } get { return rotate; } } [SerializeField] private bool rotate = true;
/// <summary>Ignore Z axis for 2D?</summary>
public bool IgnoreZ { set { ignoreZ = value; } get { return ignoreZ; } } [SerializeField] private bool ignoreZ;
/// <summary>Where in the game loop should this component update?</summary>
public UpdateType FollowIn { set { followIn = value; } get { return followIn; } } [SerializeField] private UpdateType followIn = UpdateType.LateUpdate;
/// <summary>This allows you to specify a positional offset relative to the <b>Target</b>.</summary>
public Vector3 LocalPosition { set { localPosition = value; } get { return localPosition; } } [SerializeField] private Vector3 localPosition;
/// <summary>This allows you to specify a rotational offset relative to the <b>Target</b>.</summary>
public Vector3 LocalRotation { set { localRotation = value; } get { return localRotation; } } [SerializeField] private Vector3 localRotation;
/// <summary>This method will update the follow position now.</summary>
[ContextMenu("UpdatePosition")]
public void UpdatePosition()
{
var finalTarget = target;
if (follow == FollowType.MainCamera)
{
var mainCamera = Camera.main;
if (mainCamera != null)
{
finalTarget = mainCamera.transform;
}
}
if (finalTarget != null)
{
var currentPosition = transform.position;
var targetPosition = finalTarget.TransformPoint(localPosition);
var factor = CwHelper.DampenFactor(damping, Time.deltaTime);
if (ignoreZ == true)
{
targetPosition.z = currentPosition.z;
}
transform.position = Vector3.Lerp(currentPosition, targetPosition, factor);
if (rotate == true)
{
var targetRotation = finalTarget.rotation * Quaternion.Euler(localRotation);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, factor);
}
}
}
protected virtual void Update()
{
if (followIn == UpdateType.Update)
{
UpdatePosition();
}
}
protected virtual void LateUpdate()
{
if (followIn == UpdateType.LateUpdate)
{
UpdatePosition();
}
}
}
}
#if UNITY_EDITOR
namespace CW.Common
{
using UnityEditor;
using TARGET = CwFollow;
[CanEditMultipleObjects]
[CustomEditor(typeof(TARGET))]
public class CwFollow_Editor : CwEditor
{
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
Draw("follow", "What should this component follow?");
if (Any(tgts, t => t.Follow == CwFollow.FollowType.TargetTransform))
{
BeginIndent();
BeginError(Any(tgts, t => t.Target == null));
Draw("target", "The transform that will be followed.");
EndError();
EndIndent();
}
Draw("damping", "How quickly this Transform follows the target.\n\n-1 = instant.");
Draw("rotate", "Follow the target's rotation too?");
Draw("ignoreZ", "Ignore Z axis for 2D?");
Draw("followIn", "Where in the game loop should this component update?");
Separator();
Draw("localPosition", "This allows you to specify a positional offset relative to the Target transform.");
Draw("localRotation", "This allows you to specify a rotational offset relative to the Target transform.");
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2d2927631b10c2f4b9ce492ed53fd69b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 200
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,623 @@
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections.Generic;
namespace CW.Common
{
/// <summary>This component combines finger and mouse and keyboard inputs into a single interface.</summary>
[HelpURL(CwShared.HelpUrlPrefix + "CwInputManager")]
[AddComponentMenu(CwShared.ComponentMenuPrefix + "Input Manager")]
public class CwInputManager : MonoBehaviour
{
public enum AxisGesture
{
HorizontalDrag,
VerticalDrag,
Twist,
HorizontalPull,
VerticalPull
}
[System.Serializable]
public struct Axis
{
public int FingerCount;
public bool FingerInvert;
public AxisGesture FingerGesture;
public float FingerSensitivity;
public KeyCode KeyNegative;
public KeyCode KeyPositive;
public KeyCode KeyNegativeAlt;
public KeyCode KeyPositiveAlt;
public float KeySensitivity;
public Axis(int fCount, bool fInvert, AxisGesture fGesture, float fSensitivty, KeyCode kNegative, KeyCode kPositive, KeyCode kNegativeAlt, KeyCode kPositiveAlt, float kSensitivity)
{
FingerCount = fCount;
FingerInvert = fInvert;
FingerGesture = fGesture;
FingerSensitivity = fSensitivty;
KeyNegative = kNegative;
KeyPositive = kPositive;
KeyNegativeAlt = kNegativeAlt;
KeyPositiveAlt = kPositiveAlt;
KeySensitivity = kSensitivity;
}
public float GetValue(float delta)
{
var value = 0.0f;
var fingers = GetFingers(true, true);
var scale = 1.0f;
value -= CwInput.GetKeyIsHeld(KeyNegative) == true ? KeySensitivity * delta : 0.0f;
value += CwInput.GetKeyIsHeld(KeyPositive) == true ? KeySensitivity * delta : 0.0f;
value -= CwInput.GetKeyIsHeld(KeyNegativeAlt) == true ? KeySensitivity * delta : 0.0f;
value += CwInput.GetKeyIsHeld(KeyPositiveAlt) == true ? KeySensitivity * delta : 0.0f;
if (FingerCount > 0 && fingers.Count == FingerCount)
{
if (FingerInvert == true && fingers[0].Index >= 0)
{
scale = -1.0f;
}
switch (FingerGesture)
{
case AxisGesture.HorizontalDrag: value += GetAverageDeltaScaled(fingers).x * FingerSensitivity * scale; break;
case AxisGesture.VerticalDrag: value += GetAverageDeltaScaled(fingers).y * FingerSensitivity * scale; break;
case AxisGesture.Twist: value += GetAverageTwistRadians(fingers) * FingerSensitivity; break;
case AxisGesture.HorizontalPull: value += GetAveragePullScaled(fingers).x * FingerSensitivity * delta * scale; break;
case AxisGesture.VerticalPull: value += GetAveragePullScaled(fingers).y * FingerSensitivity * delta * scale; break;
}
}
return value;
}
}
[System.Serializable]
public struct Trigger
{
public bool UseFinger;
public bool UseMouse;
public KeyCode UseKey;
public Trigger(bool uFinger, bool uMouse, KeyCode uKey)
{
UseFinger = uFinger;
UseMouse = uMouse;
UseKey = uKey;
}
public bool WentDown(Finger finger)
{
if (UseFinger == true && finger.Index >= 0 && finger.Down == true)
{
return true;
}
if (UseMouse == true && finger.Index == MOUSE_FINGER_INDEX && finger.Down == true)
{
return true;
}
if (UseKey != KeyCode.None && finger.Index == HOVER_FINGER_INDEX && CwInput.GetKeyWentDown(UseKey) == true)
{
return true;
}
return false;
}
public bool IsDown(Finger finger)
{
if (UseFinger == true && finger.Index >= 0 && finger.Up == false)
{
return true;
}
if (UseMouse == true && finger.Index == MOUSE_FINGER_INDEX && finger.Up == false)
{
return true;
}
if (UseKey != KeyCode.None && finger.Index == HOVER_FINGER_INDEX && CwInput.GetKeyIsHeld(UseKey) == true)
{
return true;
}
return false;
}
public bool WentUp(Finger finger, bool useAnyFinger = false)
{
if (useAnyFinger == true && finger.Up == true)
{
return true;
}
if (UseFinger == true && finger.Index >= 0 && finger.Up == true)
{
return true;
}
if (UseMouse == true && finger.Index == MOUSE_FINGER_INDEX && finger.Up == true)
{
return true;
}
if (UseKey != KeyCode.None && finger.Index == HOVER_FINGER_INDEX && CwInput.GetKeyWentUp(UseKey) == true)
{
return true;
}
return false;
}
}
public abstract class Link
{
public Finger Finger;
public static T Find<T>(List<T> links, Finger finger)
where T : Link, new()
{
if (links != null)
{
foreach (var link in links)
{
if (link.Finger == finger)
{
return link;
}
}
}
return null;
}
public static T Create<T>(ref List<T> links, Finger finger)
where T : Link, new()
{
var link = Find(links, finger);
if (link == null)
{
if (links == null)
{
links = new List<T>();
}
link = new T();
link.Finger = finger;
links.Add(link);
}
else
{
Debug.LogError("Link already exists!");
}
return link;
}
public static void ClearAll<T>(List<T> links)
where T : Link
{
if (links != null)
{
foreach (var link in links)
{
link.Clear();
}
links.Clear();
}
}
public static void ClearAndRemove<T>(List<T> links, T link)
where T : Link
{
if (link != null)
{
link.Clear();
if (links != null)
{
links.Remove(link);
}
}
}
public virtual void Clear()
{
}
}
public class Finger
{
public int Index;
public float Pressure;
public bool Down;
public bool Up;
public float Age;
public bool StartedOverGui;
public Vector2 StartScreenPosition;
public Vector2 ScreenPosition;
public Vector2 ScreenPositionOld;
public Vector2 ScreenPositionOldOld;
public Vector2 ScreenPositionOldOldOld;
public float SmoothScreenPositionDelta
{
get
{
if (Up == false)
{
return Vector2.Distance(ScreenPositionOldOld, ScreenPositionOld);
}
return Vector2.Distance(ScreenPositionOldOld, ScreenPosition);
}
}
public Vector2 GetSmoothScreenPosition(float t)
{
if (Up == false)
{
return Hermite(ScreenPositionOldOldOld, ScreenPositionOldOld, ScreenPositionOld, ScreenPosition, t);
}
return Vector2.LerpUnclamped(ScreenPositionOldOld, ScreenPosition, t);
}
}
/// <summary>Fingers that began touching the screen on top of these UI layers will be ignored.</summary>
public LayerMask GuiLayers { set { guiLayers = value; } get { return guiLayers; } } [SerializeField] private LayerMask guiLayers = 1 << 5;
/// <summary>This event will tell you when a finger begins touching the screen.</summary>
public static event System.Action<Finger> OnFingerDown;
/// <summary>This event will tell you when a finger has begun, is, or has just stopped touching the screen.</summary>
public static event System.Action<Finger> OnFingerUpdate;
/// <summary>This event will tell you when a finger stops touching the screen.</summary>
public static event System.Action<Finger> OnFingerUp;
public const int MOUSE_FINGER_INDEX = -1;
public const int HOVER_FINGER_INDEX = -1337;
private static List<RaycastResult> tempRaycastResults = new List<RaycastResult>(10);
private static PointerEventData tempPointerEventData;
private static EventSystem tempEventSystem;
private static List<Finger> fingers = new List<Finger>();
private static List<Finger> filteredFingers = new List<Finger>();
private static Stack<Finger> pool = new Stack<Finger>();
public static List<Finger> Fingers
{
get
{
return fingers;
}
}
public static float ScaleFactor
{
get
{
var dpi = Screen.dpi;
if (dpi <= 0)
{
dpi = 200.0f;
}
return 200.0f / dpi;
}
}
public static List<Finger> GetFingers(bool ignoreStartedOverGui = false, bool ignoreHover = false)
{
filteredFingers.Clear();
foreach (var finger in fingers)
{
if (ignoreStartedOverGui == true && finger.StartedOverGui == true)
{
continue;
}
if (ignoreHover == true && finger.Index == HOVER_FINGER_INDEX)
{
continue;
}
filteredFingers.Add(finger);
}
return filteredFingers;
}
public static bool PointOverGui(Vector2 screenPosition, int guiLayers = 1 << 5)
{
return RaycastGui(screenPosition, guiLayers).Count > 0;
}
/// <summary>This method gives you all UI elements under the specified screen position, where element 0 is the first/top one.</summary>
public static List<RaycastResult> RaycastGui(Vector2 screenPosition, int guiLayers = 1 << 5)
{
tempRaycastResults.Clear();
var currentEventSystem = EventSystem.current;
if (currentEventSystem != null)
{
// Create point event data for this event system?
if (currentEventSystem != tempEventSystem)
{
tempEventSystem = currentEventSystem;
if (tempPointerEventData == null)
{
tempPointerEventData = new PointerEventData(tempEventSystem);
}
else
{
tempPointerEventData.Reset();
}
}
// Raycast event system at the specified point
tempPointerEventData.position = screenPosition;
currentEventSystem.RaycastAll(tempPointerEventData, tempRaycastResults);
// Loop through all results and remove any that don't match the layer mask
if (tempRaycastResults.Count > 0)
{
for (var i = tempRaycastResults.Count - 1; i >= 0; i--)
{
var raycastResult = tempRaycastResults[i];
var raycastLayer = 1 << raycastResult.gameObject.layer;
if ((raycastLayer & guiLayers) == 0)
{
tempRaycastResults.RemoveAt(i);
}
}
}
}
return tempRaycastResults;
}
public static Vector2 GetAveragePosition(List<Finger> fingers)
{
var total = Vector2.zero;
foreach (var finger in fingers)
{
total += finger.ScreenPosition;
}
return fingers.Count == 0 ? total : total / fingers.Count;
}
public static Vector2 GetAverageOldPosition(List<Finger> fingers)
{
var total = Vector2.zero;
foreach (var finger in fingers)
{
total += finger.ScreenPositionOld;
}
return fingers.Count == 0 ? total : total / fingers.Count;
}
public static Vector2 GetAveragePullScaled(List<Finger> fingers)
{
var total = Vector2.zero;
foreach (var finger in fingers)
{
total += finger.ScreenPosition - finger.StartScreenPosition;
}
return fingers.Count == 0 ? total : total * ScaleFactor / fingers.Count;
}
public static Vector2 GetAverageDeltaScaled(List<Finger> fingers)
{
var total = Vector2.zero;
foreach (var finger in fingers)
{
total += finger.ScreenPosition - finger.ScreenPositionOld;
}
return fingers.Count == 0 ? total : total * ScaleFactor / fingers.Count;
}
public static float GetAverageTwistRadians(List<Finger> fingers)
{
var total = 0.0f;
var center = GetAveragePosition(fingers);
var oldCenter = GetAverageOldPosition(fingers);
foreach (var finger in fingers)
{
total += GetDeltaRadians(finger, center, oldCenter);
}
return fingers.Count == 0 ? total : total / fingers.Count;
}
/// <summary>If your component uses this component, then make sure you call this method at least once before you use it (e.g. from <b>Awake</b>).</summary>
public static void EnsureThisComponentExists()
{
if (Application.isPlaying == true && CwHelper.FindAnyObjectByType<CwInputManager>() == null)
{
new GameObject(typeof(CwInputManager).Name).AddComponent<CwInputManager>();
}
}
protected virtual void Update()
{
// Remove previously up fingers, or mark them as up in case the up event isn't read correctly
for (var i = fingers.Count - 1; i >= 0; i--)
{
var finger = fingers[i];
if (finger.Up == true)
{
fingers.RemoveAt(i); pool.Push(finger);
}
else
{
finger.Up = true;
}
}
// Update real fingers
if (CwInput.GetTouchCount() > 0)
{
for (var i = 0; i < CwInput.GetTouchCount(); i++)
{
int id; Vector2 position; float pressure; bool set;
CwInput.GetTouch(i, out id, out position, out pressure, out set);
AddFinger(id, position, pressure, set);
}
}
// If there are no real touches, simulate some from the mouse?
else if (CwInput.GetMouseExists() == true)
{
var mouseSet = false;
var mouseUp = false;
for (var i = 0; i < 5; i++)
{
mouseSet |= CwInput.GetMouseIsHeld(i);
mouseUp |= CwInput.GetMouseWentUp(i);
}
AddFinger(HOVER_FINGER_INDEX, CwInput.GetMousePosition(), 0.0f, true);
if (mouseSet == true || mouseUp == true)
{
AddFinger(MOUSE_FINGER_INDEX, CwInput.GetMousePosition(), 1.0f, mouseSet);
}
}
// Events
foreach (var finger in fingers)
{
if (finger.Down == true && OnFingerDown != null) OnFingerDown .Invoke(finger);
if ( OnFingerUpdate != null) OnFingerUpdate.Invoke(finger);
if (finger.Up == true && OnFingerUp != null) OnFingerUp .Invoke(finger);
}
}
private Finger FindFinger(int index)
{
foreach (var finger in fingers)
{
if (finger.Index == index)
{
return finger;
}
}
return null;
}
private void AddFinger(int index, Vector2 screenPosition, float pressure, bool set)
{
var finger = FindFinger(index);
if (finger == null)
{
finger = pool.Count > 0 ? pool.Pop() : new Finger();
finger.Index = index;
finger.Down = true;
finger.Age = 0.0f;
finger.StartedOverGui = PointOverGui(screenPosition, guiLayers);
finger.StartScreenPosition = screenPosition;
finger.ScreenPositionOld = screenPosition;
finger.ScreenPositionOldOld = screenPosition;
finger.ScreenPositionOldOldOld = screenPosition;
fingers.Add(finger);
}
else
{
finger.Down = false;
finger.Age += Time.deltaTime;
finger.ScreenPositionOldOldOld = finger.ScreenPositionOldOld;
finger.ScreenPositionOldOld = finger.ScreenPositionOld;
finger.ScreenPositionOld = finger.ScreenPosition;
}
finger.Pressure = pressure;
finger.ScreenPosition = screenPosition;
finger.Up = set == false;
}
private static Vector2 Hermite(Vector2 a, Vector2 b, Vector2 c, Vector2 d, float t)
{
var mu2 = t * t;
var mu3 = mu2 * t;
var x = HermiteInterpolate(a.x, b.x, c.x, d.x, t, mu2, mu3);
var y = HermiteInterpolate(a.y, b.y, c.y, d.y, t, mu2, mu3);
return new Vector2(x, y);
}
private static float HermiteInterpolate(float y0,float y1, float y2,float y3, float mu, float mu2, float mu3)
{
var m0 = (y1 - y0) * 0.5f + (y2 - y1) * 0.5f;
var m1 = (y2 - y1) * 0.5f + (y3 - y2) * 0.5f;
var a0 = 2.0f * mu3 - 3.0f * mu2 + 1.0f;
var a1 = mu3 - 2.0f * mu2 + mu;
var a2 = mu3 - mu2;
var a3 = -2.0f * mu3 + 3.0f * mu2;
return(a0*y1+a1*m0+a2*m1+a3*y2);
}
private static float GetRadians(Vector2 screenPosition, Vector2 referencePoint)
{
return Mathf.Atan2(screenPosition.x - referencePoint.x, screenPosition.y - referencePoint.y);
}
private static float GetDeltaRadians(Finger finger, Vector2 referencePoint, Vector2 lastReferencePoint)
{
var a = GetRadians(finger.ScreenPositionOld, lastReferencePoint);
var b = GetRadians(finger.ScreenPosition, referencePoint);
var d = Mathf.Repeat(a - b, Mathf.PI * 2.0f);
if (d > Mathf.PI)
{
d -= Mathf.PI * 2.0f;
}
return d;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8da33d20535c346499a0c78cabe4d750
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,238 @@
//#define USE_CUSTOM_TEMPORARY
using UnityEngine;
using System.Collections.Generic;
namespace CW.Common
{
[ExecuteInEditMode]
[DefaultExecutionOrder(1000)]
[HelpURL(CwShared.HelpUrlPrefix + "CwRenderTextureManager")]
[AddComponentMenu(CwShared.ComponentMenuPrefix + "Render Texture Manager")]
public class CwRenderTextureManager : MonoBehaviour
{
/// <summary>This allows you to set how many frames an unused RenderTexture will remaining in memory before it's released.</summary>
public int Lifetime { set { lifetime = value; } get { return lifetime; } } [SerializeField] private int lifetime = 3;
#if USE_CUSTOM_TEMPORARY
private class Entry
{
public RenderTexture RT;
public RenderTextureDescriptor Desc;
public int Life;
public static Stack<Entry> Pool = new Stack<Entry>();
}
private static List<Entry> entries = new List<Entry>();
private static LinkedList<CwRenderTextureManager> instances = new LinkedList<CwRenderTextureManager>();
private LinkedListNode<CwRenderTextureManager> node;
public static RenderTexture GetTemporary(RenderTextureDescriptor desc, string title)
{
if (instances.Count == 0)
{
new GameObject("CwRenderTextureManager").AddComponent<CwRenderTextureManager>();
}
for (var i = entries.Count - 1; i >= 0; i--)
{
var entry = entries[i];
if (entry.RT == null)
{
entry.RT = null;
Entry.Pool.Push(entry);
entries.RemoveAt(i);
continue;
}
if (Match(ref entry.Desc, ref desc) == true)
{
Entry.Pool.Push(entry);
entries.RemoveAt(i);
entry.RT.name = title;
if (entry.RT.IsCreated() == false)
{
entry.RT.Create();
}
return entry.RT;
}
}
var rt = new RenderTexture(desc);
rt.name = title;
return rt;
}
public static RenderTexture ReleaseTemporary(RenderTexture rt)
{
if (rt != null)
{
if (instances.Count > 0)
{
var entry = Entry.Pool.Count > 0 ? Entry.Pool.Pop() : new Entry();
entry.RT = rt;
entry.Desc = rt.descriptor;
entry.Life = Mathf.Max(1, instances.First.Value.lifetime);
entries.Add(entry);
rt.DiscardContents();
}
else
{
rt.Release();
DestroyImmediate(rt);
}
}
return null;
}
protected virtual void OnEnable()
{
node = instances.AddLast(this);
}
protected virtual void OnDisable()
{
instances.Remove(node); node = null;
if (instances.Count == 0)
{
for (var i = entries.Count - 1; i >= 0; i--)
{
var entry = entries[i];
if (entry.RT != null)
{
entry.RT.Release();
DestroyImmediate(entry.RT);
}
Entry.Pool.Push(entry);
}
entries.Clear();
}
}
protected virtual void LateUpdate()
{
if (node == instances.First)
{
Tick();
}
}
private void Tick()
{
for (var i = entries.Count - 1; i >= 0; i--)
{
var entry = entries[i];
if (entry.Life > 0)
{
entry.Life -= 1;
if (entry.Life == 0 && entry.RT != null && entry.RT.IsCreated() == true)
{
entry.RT.Release();
}
}
}
}
private static bool Match(ref RenderTextureDescriptor a, ref RenderTextureDescriptor b)
{
if (a.enableRandomWrite != b.enableRandomWrite) return false;
if (a.autoGenerateMips != b.autoGenerateMips) return false;
if (a.useMipMap != b.useMipMap) return false;
if (a.memoryless != b.memoryless) return false;
if (a.flags != b.flags) return false;
if (a.vrUsage != b.vrUsage) return false;
if (a.shadowSamplingMode != b.shadowSamplingMode) return false;
if (a.dimension != b.dimension) return false;
if (a.depthBufferBits != b.depthBufferBits) return false;
if (a.stencilFormat != b.stencilFormat) return false;
if (a.colorFormat != b.colorFormat) return false;
if (a.bindMS != b.bindMS) return false;
if (a.graphicsFormat != b.graphicsFormat) return false;
if (a.mipCount != b.mipCount) return false;
if (a.volumeDepth != b.volumeDepth) return false;
if (a.msaaSamples != b.msaaSamples) return false;
if (a.height != b.height) return false;
if (a.width != b.width) return false;
if (a.sRGB != b.sRGB) return false;
if (a.useDynamicScale != b.useDynamicScale) return false;
return true;
}
#else
public static RenderTexture GetTemporary(RenderTextureDescriptor desc, string title)
{
var renderTexture = RenderTexture.GetTemporary(desc);
// TODO: For some reason RenderTexture.GetTemporary ignores the useMipMap flag?!
if (renderTexture.useMipMap != desc.useMipMap)
{
renderTexture.Release();
renderTexture.descriptor = desc;
renderTexture.Create();
}
return renderTexture;
}
public static RenderTexture ReleaseTemporary(RenderTexture renderTexture)
{
if (renderTexture != null)
{
renderTexture.DiscardContents();
RenderTexture.ReleaseTemporary(renderTexture);
}
return null;
}
#endif
}
}
#if UNITY_EDITOR
namespace CW.Common
{
using UnityEditor;
using TARGET = CwRenderTextureManager;
[CanEditMultipleObjects]
[CustomEditor(typeof(TARGET))]
public class CwRenderTextureManager_Editor : CwEditor
{
protected override void OnInspector()
{
TARGET tgt; TARGET[] tgts; GetTargets(out tgt, out tgts);
Draw("lifetime", "This allows you to set how many frames an unused RenderTexture will remaining in memory before it's released.");
}
}
}
#endif

View File

@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 074581640de185e4f9953ebbc6d61a87
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 26286
packageName: Paint in 3D
packageVersion: 3.0.2
assetPath: Assets/Plugins/CW/Shared/Common/Extras/Scripts/CwRenderTextureManager.cs
uploadId: 595998

View File

@@ -0,0 +1,33 @@
using UnityEngine;
namespace CW.Common
{
/// <summary>This attribute can be added to any int field to make it a random seed value that can easily be randomized.</summary>
public class CwSeedAttribute : PropertyAttribute
{
}
}
#if UNITY_EDITOR
namespace CW.Common
{
using UnityEditor;
[CustomPropertyDrawer(typeof(CwSeedAttribute))]
public class CwSeedDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var rect1 = position; rect1.xMax = position.xMax - 20;
var rect2 = position; rect2.xMin = position.xMax - 18;
EditorGUI.PropertyField(rect1, property, label);
if (GUI.Button(rect2, "R") == true)
{
property.intValue = Random.Range(int.MinValue, int.MaxValue);
}
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d0c2debde2a068741bac1cf9efca66ac
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0f41b5d72be5b534b9d9f5394d24c50e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ebb371642e8bcb141a02849e93f43a37
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,16 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace CW.Common
{
/// <summary>This class contains some useful methods used by this asset.</summary>
internal static class CwShared
{
public const string HelpUrlPrefix = "https://carloswilkes.com/Documentation/Common#";
public const string ComponentMenuPrefix = "Common/CW ";
public const string GameObjectMenuPrefix = "GameObject/CW/Common/";
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d0de2c3cc880c084084779b3c82e4391
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,519 @@
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace CW.Common
{
/// <summary>This is the base class for all inspectors.</summary>
public abstract class CwEditor : UnityEditor.Editor
{
private static Stack<object> datas = new Stack<object>();
private static GUIContent customContent = new GUIContent();
private static List<Color> colors = new List<Color>();
private static List<float> labelWidths = new List<float>();
private static List<bool> mixedValues = new List<bool>();
public void GetTargets<T>(out T tgt, out T[] tgts)
where T : Object
{
tgt = (T)target;
tgts = System.Array.ConvertAll(targets, item => (T)item);
}
public static void BeginData(SerializedObject newData)
{
datas.Push(newData);
}
public static void BeginData(SerializedProperty newData)
{
datas.Push(newData);
}
public static void EndData()
{
datas.Pop();
}
public override void OnInspectorGUI()
{
BeginData(serializedObject);
ClearStacks();
Separator();
OnInspector();
Separator();
serializedObject.ApplyModifiedProperties();
EndData();
}
protected void Each<T>(T[] tgts, System.Action<T> update, bool dirty = false, bool apply = false, string undo = null)
where T : Object
{
if (string.IsNullOrEmpty(undo) == false)
{
Undo.RecordObjects(tgts, undo);
}
if (apply == true)
{
serializedObject.ApplyModifiedProperties();
}
foreach (var t in tgts)
{
update(t);
if (dirty == true)
{
EditorUtility.SetDirty(t);
}
}
}
protected bool Any<T>(T[] tgts, System.Func<T, bool> check)
where T : Object
{
foreach (var t in tgts)
{
if (check(t) == true)
{
return true;
}
}
return false;
}
protected bool All<T>(T[] tgts, System.Func<T, bool> check)
where T : Object
{
foreach (var t in tgts)
{
if (check(t) == false)
{
return false;
}
}
return true;
}
public static Rect Reserve(float height = 19.0f)
{
var rect =
EditorGUILayout.BeginVertical();
EditorGUILayout.LabelField(string.Empty, GUILayout.Height(height), GUILayout.ExpandWidth(true), GUILayout.MinWidth(0.0f));
EditorGUILayout.EndVertical();
return rect;
}
public static void Info(string message)
{
EditorGUILayout.HelpBox(StripRichText(message), MessageType.Info); // Help boxes can't display rich text for some reason, so strip it
}
public static void Warning(string message)
{
EditorGUILayout.HelpBox(StripRichText(message), MessageType.Warning); // Help boxes can't display rich text for some reason, so strip it
}
public static void Error(string message)
{
EditorGUILayout.HelpBox(StripRichText(message), MessageType.Error); // Help boxes can't display rich text for some reason, so strip it
}
public static void Separator()
{
EditorGUILayout.Separator();
}
public static void BeginIndent()
{
EditorGUI.indentLevel += 1;
}
public static void EndIndent()
{
EditorGUI.indentLevel -= 1;
}
public static bool Button(string text)
{
return GUILayout.Button(text);
}
public static bool HelpButton(string helpText, UnityEditor.MessageType type, string buttonText, float buttonWidth)
{
var clicked = false;
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.HelpBox(helpText, type);
var style = new GUIStyle(GUI.skin.button); style.wordWrap = true;
clicked = GUILayout.Button(buttonText, style, GUILayout.ExpandHeight(true), GUILayout.Width(buttonWidth));
}
EditorGUILayout.EndHorizontal();
return clicked;
}
public static void ClearStacks()
{
while (colors.Count > 0)
{
EndColor();
}
while (labelWidths.Count > 0)
{
EndLabelWidth();
}
while (mixedValues.Count > 0)
{
EndMixedValue();
}
}
public static void BeginMixedValue(bool mixed = true)
{
mixedValues.Add(EditorGUI.showMixedValue);
EditorGUI.showMixedValue = mixed;
}
public static void EndMixedValue()
{
if (mixedValues.Count > 0)
{
var index = mixedValues.Count - 1;
EditorGUI.showMixedValue = mixedValues[index];
mixedValues.RemoveAt(index);
}
}
public static void BeginDisabled(bool disabled = true)
{
EditorGUI.BeginDisabledGroup(disabled);
}
public static void EndDisabled()
{
EditorGUI.EndDisabledGroup();
}
public static void BeginError(bool error = true)
{
BeginColor(Color.red, error);
}
public static void EndError()
{
EndColor();
}
public static void BeginColor(Color color, bool show = true)
{
colors.Add(GUI.color);
GUI.color = show == true ? color : colors[0];
}
public static void EndColor()
{
if (colors.Count > 0)
{
var index = colors.Count - 1;
GUI.color = colors[index];
colors.RemoveAt(index);
}
}
public static void BeginLabelWidth(float width)
{
labelWidths.Add(EditorGUIUtility.labelWidth);
EditorGUIUtility.labelWidth = width;
}
public static void EndLabelWidth()
{
if (labelWidths.Count > 0)
{
var index = labelWidths.Count - 1;
EditorGUIUtility.labelWidth = labelWidths[index];
labelWidths.RemoveAt(index);
}
}
public static bool DrawFoldout(string overrideText, string overrideTooltip, string propertyPath = "m_Name")
{
var property = GetPropertyAndSetCustomContent(propertyPath, overrideTooltip, overrideText);
property.isExpanded = EditorGUILayout.Foldout(property.isExpanded, customContent);
return property.isExpanded;
}
public static bool DrawExpand(string propertyPath, ref bool modified, string overrideTooltip = null, string overrideText = null)
{
var property = GetPropertyAndSetCustomContent(propertyPath, overrideTooltip, overrideText);
var rect = EditorGUILayout.BeginVertical(); EditorGUILayout.LabelField(string.Empty, GUILayout.Height(EditorGUI.GetPropertyHeight(property))); EditorGUILayout.EndVertical();
var rectF = rect; rectF.height = 16;
property.isExpanded = EditorGUI.Foldout(rectF, property.isExpanded, GUIContent.none);
EditorGUI.BeginChangeCheck();
EditorGUI.PropertyField(rect, property, customContent, true);
modified = EditorGUI.EndChangeCheck();
return property.isExpanded;
}
public static bool DrawExpand(string propertyPath, string overrideTooltip = null, string overrideText = null)
{
var modified = false; return DrawExpand(propertyPath, ref modified, overrideTooltip, overrideText);
}
public static bool Draw(string propertyPath, string overrideTooltip = null, string overrideText = null)
{
var property = GetPropertyAndSetCustomContent(propertyPath, overrideTooltip, overrideText);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(property, customContent, true);
return EditorGUI.EndChangeCheck();
}
public static void Draw(string propertyPath, ref bool dirty, string overrideTooltip = null, string overrideText = null)
{
if (Draw(propertyPath, overrideTooltip, overrideText) == true)
{
dirty = true;
}
}
public static void Draw(string propertyPath, ref bool dirty1, ref bool dirty2, string overrideTooltip = null, string overrideText = null)
{
if (Draw(propertyPath, overrideTooltip, overrideText) == true)
{
dirty1 = true;
dirty2 = true;
}
}
public static bool DrawSlider(string propertyPath, float min, float max, string overrideTooltip = null, string overrideText = null)
{
var property = GetPropertyAndSetCustomContent(propertyPath, overrideTooltip, overrideText);
var value = property.floatValue;
EditorGUI.BeginChangeCheck();
value = EditorGUILayout.Slider(customContent, value, min, max);
if (EditorGUI.EndChangeCheck() == true)
{
property.floatValue = value;
return true;
}
return false;
}
public static bool DrawIntSlider(string propertyPath, int min, int max, string overrideTooltip = null, string overrideText = null)
{
var property = GetPropertyAndSetCustomContent(propertyPath, overrideTooltip, overrideText);
var value = property.intValue;
EditorGUI.BeginChangeCheck();
value = EditorGUILayout.IntSlider(customContent, value, min, max);
if (EditorGUI.EndChangeCheck() == true)
{
property.intValue = value;
return true;
}
return false;
}
public static bool DrawMinMax(string propertyPath, float min, float max, string overrideTooltip = null, string overrideText = null)
{
var property = GetPropertyAndSetCustomContent(propertyPath, overrideTooltip, overrideText);
var value = property.vector2Value;
EditorGUI.BeginChangeCheck();
EditorGUILayout.MinMaxSlider(customContent, ref value.x, ref value.y, min, max);
if (EditorGUI.EndChangeCheck() == true)
{
property.vector2Value = value;
return true;
}
return false;
}
public static bool DrawVector4(string propertyPath, string overrideTooltip = null, string overrideText = null)
{
var property = GetPropertyAndSetCustomContent(propertyPath, overrideTooltip, overrideText);
var value = property.vector4Value;
EditorGUI.BeginChangeCheck();
value = EditorGUILayout.Vector4Field(customContent, value);
if (EditorGUI.EndChangeCheck() == true)
{
property.vector4Value = value;
return true;
}
return false;
}
public static bool DrawIntPopup(int[] values, GUIContent[] contents, string propertyPath, string overrideTooltip = null, string overrideText = null)
{
var property = GetPropertyAndSetCustomContent(propertyPath, overrideTooltip, overrideText);
EditorGUI.BeginChangeCheck();
EditorGUILayout.IntPopup(property, contents, values, customContent);
return EditorGUI.EndChangeCheck();
}
public static void DrawIntPopup(int[] values, GUIContent[] contents, string propertyPath, ref bool modified, string overrideTooltip = null, string overrideText = null)
{
if (DrawIntPopup(values, contents, propertyPath, overrideTooltip, overrideText) == true)
{
modified = true;
}
}
public static bool DrawLayer(string propertyPath, string overrideTooltip = null, string overrideText = null)
{
var property = GetPropertyAndSetCustomContent(propertyPath, overrideTooltip, overrideText);
var value = property.intValue;
EditorGUI.BeginChangeCheck();
value = EditorGUILayout.LayerField(customContent, value);
if (EditorGUI.EndChangeCheck() == true)
{
property.intValue = value;
return true;
}
return false;
}
public static bool DrawEulerAngles(string propertyPath, string overrideTooltip = null, string overrideText = null)
{
var property = GetPropertyAndSetCustomContent(propertyPath, overrideTooltip, overrideText);
var value = property.quaternionValue.eulerAngles;
EditorGUI.BeginChangeCheck();
BeginMixedValue(property.hasMultipleDifferentValues);
value = EditorGUILayout.Vector3Field(customContent, value);
EndMixedValue();
if (EditorGUI.EndChangeCheck() == true)
{
property.quaternionValue = Quaternion.Euler(value);
return true;
}
return false;
}
protected void DirtyAndUpdate()
{
for (var i = targets.Length - 1; i >= 0; i--)
{
EditorUtility.SetDirty(targets[i]);
}
serializedObject.Update();
}
public static SerializedProperty GetProperty(string propertyPath)
{
var data = datas.Peek();
if (data != null)
{
var dataA = data as SerializedObject;
if (dataA != null)
{
return dataA.FindProperty(propertyPath);
}
var dataB = data as SerializedProperty;
if (dataB != null)
{
return dataB.FindPropertyRelative(propertyPath);
}
}
return null;
}
private static SerializedProperty GetPropertyAndSetCustomContent(string propertyPath, string overrideTooltip, string overrideText)
{
var property = GetProperty(propertyPath);
customContent.text = string.IsNullOrEmpty(overrideText ) == false ? overrideText : property.displayName;
customContent.tooltip = string.IsNullOrEmpty(overrideTooltip) == false ? overrideTooltip : property.tooltip;
customContent.tooltip = StripRichText(customContent.tooltip); // Tooltips can't display rich text for some reason, so strip it
return property;
}
private static string StripRichText(string s)
{
return s.Replace("<b>", "").Replace("</b>", "");
}
protected virtual void OnInspector()
{
}
}
}
#endif

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6db2e50665ae04147b7ef6bf70fa0756
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 40a2a791e0ffb554885467adbda44772
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 45942563aa8bfe64bbeace4d9aa80a91
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,336 @@
#if ENABLE_INPUT_SYSTEM && __INPUTSYSTEM__
#define USE_NEW_INPUT_SYSTEM
using NewCode = UnityEngine.InputSystem.Key;
#endif
using UnityEngine;
namespace CW.Common
{
/// <summary>This class wraps <b>UnityEngine.Input</b> and <b>UnityEngine.InputSystem</b> so they can both be used from the same interface.</summary>
public static class CwInput
{
#if USE_NEW_INPUT_SYSTEM
private static System.Collections.Generic.Dictionary<KeyCode, NewCode> keyMapping = new System.Collections.Generic.Dictionary<KeyCode, NewCode>()
{
//{ KeyCode.None, NewCode.None },
{ KeyCode.Backspace, NewCode.Backspace },
{ KeyCode.Tab, NewCode.Tab },
{ KeyCode.Clear, NewCode.None },
{ KeyCode.Return, NewCode.Enter },
{ KeyCode.Pause, NewCode.Pause },
{ KeyCode.Escape, NewCode.Escape },
{ KeyCode.Space, NewCode.Space },
{ KeyCode.Exclaim, NewCode.None },
{ KeyCode.DoubleQuote, NewCode.None },
{ KeyCode.Hash, NewCode.None },
{ KeyCode.Dollar, NewCode.None },
{ KeyCode.Percent, NewCode.None },
{ KeyCode.Ampersand, NewCode.None },
{ KeyCode.Quote, NewCode.Quote },
{ KeyCode.LeftParen, NewCode.None },
{ KeyCode.RightParen, NewCode.None },
{ KeyCode.Asterisk, NewCode.None },
{ KeyCode.Plus, NewCode.None },
{ KeyCode.Comma, NewCode.Comma },
{ KeyCode.Minus, NewCode.Minus },
{ KeyCode.Period, NewCode.Period },
{ KeyCode.Slash, NewCode.Slash },
{ KeyCode.Alpha1, NewCode.Digit1 },
{ KeyCode.Alpha2, NewCode.Digit2 },
{ KeyCode.Alpha3, NewCode.Digit3 },
{ KeyCode.Alpha4, NewCode.Digit4 },
{ KeyCode.Alpha5, NewCode.Digit5 },
{ KeyCode.Alpha6, NewCode.Digit6 },
{ KeyCode.Alpha7, NewCode.Digit7 },
{ KeyCode.Alpha8, NewCode.Digit8 },
{ KeyCode.Alpha9, NewCode.Digit9 },
{ KeyCode.Alpha0, NewCode.Digit0 },
{ KeyCode.Colon, NewCode.None },
{ KeyCode.Semicolon, NewCode.Semicolon },
{ KeyCode.Less, NewCode.None },
{ KeyCode.Equals, NewCode.Equals },
{ KeyCode.Greater, NewCode.None },
{ KeyCode.Question, NewCode.None },
{ KeyCode.At, NewCode.None },
{ KeyCode.LeftBracket, NewCode.LeftBracket },
{ KeyCode.Backslash, NewCode.Backslash },
{ KeyCode.RightBracket, NewCode.RightBracket },
{ KeyCode.Caret, NewCode.None },
{ KeyCode.Underscore, NewCode.None },
{ KeyCode.BackQuote, NewCode.Backquote },
{ KeyCode.A, NewCode.A },
{ KeyCode.B, NewCode.B },
{ KeyCode.C, NewCode.C },
{ KeyCode.D, NewCode.D },
{ KeyCode.E, NewCode.E },
{ KeyCode.F, NewCode.F },
{ KeyCode.G, NewCode.G },
{ KeyCode.H, NewCode.H },
{ KeyCode.I, NewCode.I },
{ KeyCode.J, NewCode.J },
{ KeyCode.K, NewCode.K },
{ KeyCode.L, NewCode.L },
{ KeyCode.M, NewCode.M },
{ KeyCode.N, NewCode.N },
{ KeyCode.O, NewCode.O },
{ KeyCode.P, NewCode.P },
{ KeyCode.Q, NewCode.Q },
{ KeyCode.R, NewCode.R },
{ KeyCode.S, NewCode.S },
{ KeyCode.T, NewCode.T },
{ KeyCode.U, NewCode.U },
{ KeyCode.V, NewCode.V },
{ KeyCode.W, NewCode.W },
{ KeyCode.X, NewCode.X },
{ KeyCode.Y, NewCode.Y },
{ KeyCode.Z, NewCode.Z },
{ KeyCode.LeftCurlyBracket, NewCode.None },
{ KeyCode.Pipe, NewCode.None },
{ KeyCode.RightCurlyBracket, NewCode.None },
{ KeyCode.Tilde, NewCode.None },
{ KeyCode.Delete, NewCode.Delete },
{ KeyCode.Keypad0, NewCode.Numpad0 },
{ KeyCode.Keypad1, NewCode.Numpad1 },
{ KeyCode.Keypad2, NewCode.Numpad2 },
{ KeyCode.Keypad3, NewCode.Numpad3 },
{ KeyCode.Keypad4, NewCode.Numpad4 },
{ KeyCode.Keypad5, NewCode.Numpad5 },
{ KeyCode.Keypad6, NewCode.Numpad6 },
{ KeyCode.Keypad7, NewCode.Numpad7 },
{ KeyCode.Keypad8, NewCode.Numpad8 },
{ KeyCode.Keypad9, NewCode.Numpad9 },
{ KeyCode.KeypadPeriod, NewCode.NumpadPeriod },
{ KeyCode.KeypadDivide, NewCode.NumpadDivide },
{ KeyCode.KeypadMultiply, NewCode.NumpadMultiply },
{ KeyCode.KeypadMinus, NewCode.NumpadMinus },
{ KeyCode.KeypadPlus, NewCode.NumpadPlus },
{ KeyCode.KeypadEnter, NewCode.NumpadEnter },
{ KeyCode.KeypadEquals, NewCode.NumpadEquals },
{ KeyCode.UpArrow, NewCode.UpArrow },
{ KeyCode.DownArrow, NewCode.DownArrow },
{ KeyCode.RightArrow, NewCode.RightArrow },
{ KeyCode.LeftArrow, NewCode.LeftArrow },
{ KeyCode.Insert, NewCode.Insert },
{ KeyCode.Home, NewCode.Home },
{ KeyCode.End, NewCode.End },
{ KeyCode.PageUp, NewCode.PageUp },
{ KeyCode.PageDown, NewCode.PageDown },
{ KeyCode.F1, NewCode.F1 },
{ KeyCode.F2, NewCode.F2 },
{ KeyCode.F3, NewCode.F3 },
{ KeyCode.F4, NewCode.F4 },
{ KeyCode.F5, NewCode.F5 },
{ KeyCode.F6, NewCode.F6 },
{ KeyCode.F7, NewCode.F7 },
{ KeyCode.F8, NewCode.F8 },
{ KeyCode.F9, NewCode.F9 },
{ KeyCode.F10, NewCode.F10 },
{ KeyCode.F11, NewCode.F11 },
{ KeyCode.F12, NewCode.F12 },
{ KeyCode.F13, NewCode.None },
{ KeyCode.F14, NewCode.None },
{ KeyCode.F15, NewCode.None },
{ KeyCode.Numlock, NewCode.NumLock },
{ KeyCode.CapsLock, NewCode.CapsLock },
{ KeyCode.ScrollLock, NewCode.ScrollLock },
{ KeyCode.RightShift, NewCode.RightShift },
{ KeyCode.LeftShift, NewCode.LeftShift },
{ KeyCode.RightControl, NewCode.RightCtrl },
{ KeyCode.LeftControl, NewCode.LeftCtrl },
{ KeyCode.RightAlt, NewCode.RightAlt },
{ KeyCode.LeftAlt, NewCode.LeftAlt },
{ KeyCode.RightCommand, NewCode.RightCommand },
//{ KeyCode.RightApple, NewCode.RightApple },
{ KeyCode.LeftCommand, NewCode.LeftCommand },
//{ KeyCode.LeftApple, NewCode.LeftApple },
{ KeyCode.LeftWindows, NewCode.LeftWindows },
{ KeyCode.RightWindows, NewCode.RightWindows },
{ KeyCode.AltGr, NewCode.AltGr },
{ KeyCode.Help, NewCode.None },
{ KeyCode.Print, NewCode.PrintScreen },
{ KeyCode.SysReq, NewCode.None },
{ KeyCode.Break, NewCode.None },
{ KeyCode.Menu, NewCode.ContextMenu },
};
[UnityEngine.RuntimeInitializeOnLoadMethod]
static void Enable()
{
UnityEngine.InputSystem.EnhancedTouch.EnhancedTouchSupport.Enable();
}
private static UnityEngine.InputSystem.Controls.ButtonControl GetMouseButtonControl(int index)
{
if (UnityEngine.InputSystem.Mouse.current != null)
{
switch (index)
{
case 0: return UnityEngine.InputSystem.Mouse.current.leftButton;
case 1: return UnityEngine.InputSystem.Mouse.current.rightButton;
case 2: return UnityEngine.InputSystem.Mouse.current.middleButton;
case 3: return UnityEngine.InputSystem.Mouse.current.forwardButton;
case 4: return UnityEngine.InputSystem.Mouse.current.backButton;
}
}
return null;
}
private static UnityEngine.InputSystem.Controls.ButtonControl GetButtonControl(KeyCode oldKey)
{
if (UnityEngine.InputSystem.Mouse.current != null)
{
switch (oldKey)
{
case KeyCode.Mouse0: return UnityEngine.InputSystem.Mouse.current.leftButton;
case KeyCode.Mouse1: return UnityEngine.InputSystem.Mouse.current.rightButton;
case KeyCode.Mouse2: return UnityEngine.InputSystem.Mouse.current.middleButton;
case KeyCode.Mouse3: return UnityEngine.InputSystem.Mouse.current.forwardButton;
case KeyCode.Mouse4: return UnityEngine.InputSystem.Mouse.current.backButton;
}
}
if (UnityEngine.InputSystem.Keyboard.current != null)
{
var newKey = default(UnityEngine.InputSystem.Key);
if (keyMapping.TryGetValue(oldKey, out newKey) == true)
{
return UnityEngine.InputSystem.Keyboard.current[newKey];
}
}
return null;
}
#endif
public static int GetTouchCount()
{
#if USE_NEW_INPUT_SYSTEM
if (UnityEngine.InputSystem.EnhancedTouch.EnhancedTouchSupport.enabled == false)
{
UnityEngine.InputSystem.EnhancedTouch.EnhancedTouchSupport.Enable();
}
return UnityEngine.InputSystem.EnhancedTouch.Touch.activeTouches.Count;
#else
return UnityEngine.Input.touchCount;
#endif
}
public static void GetTouch(int index, out int id, out UnityEngine.Vector2 position, out float pressure, out bool set)
{
#if USE_NEW_INPUT_SYSTEM
var touch = UnityEngine.InputSystem.EnhancedTouch.Touch.activeTouches[index];
id = touch.finger.index;
position = touch.screenPosition;
pressure = touch.pressure;
set =
touch.phase == UnityEngine.InputSystem.TouchPhase.Began ||
touch.phase == UnityEngine.InputSystem.TouchPhase.Stationary ||
touch.phase == UnityEngine.InputSystem.TouchPhase.Moved;
#else
var touch = UnityEngine.Input.GetTouch(index);
id = touch.fingerId;
position = touch.position;
pressure = touch.pressure;
set =
touch.phase == UnityEngine.TouchPhase.Began ||
touch.phase == UnityEngine.TouchPhase.Stationary ||
touch.phase == UnityEngine.TouchPhase.Moved;
#endif
}
public static UnityEngine.Vector2 GetMousePosition()
{
#if USE_NEW_INPUT_SYSTEM
return UnityEngine.InputSystem.Mouse.current != null ? UnityEngine.InputSystem.Mouse.current.position.ReadValue() : default(UnityEngine.Vector2);
#else
return UnityEngine.Input.mousePosition;
#endif
}
public static bool GetKeyWentDown(KeyCode oldKey)
{
#if USE_NEW_INPUT_SYSTEM
var buttonControl = GetButtonControl(oldKey); return buttonControl != null ? buttonControl.wasPressedThisFrame : false;
#else
return UnityEngine.Input.GetKeyDown(oldKey);
#endif
}
public static bool GetKeyIsHeld(KeyCode oldKey)
{
#if USE_NEW_INPUT_SYSTEM
var buttonControl = GetButtonControl(oldKey); return buttonControl != null ? buttonControl.isPressed : false;
#else
return UnityEngine.Input.GetKey(oldKey);
#endif
}
public static bool GetKeyWentUp(KeyCode oldKey)
{
#if USE_NEW_INPUT_SYSTEM
var buttonControl = GetButtonControl(oldKey); return buttonControl != null ? buttonControl.wasReleasedThisFrame : false;
#else
return UnityEngine.Input.GetKeyUp(oldKey);
#endif
}
public static bool GetMouseWentDown(int index)
{
#if USE_NEW_INPUT_SYSTEM
var buttonControl = GetMouseButtonControl(index); return buttonControl != null ? buttonControl.wasPressedThisFrame : false;
#else
return UnityEngine.Input.GetMouseButtonDown(index);
#endif
}
public static bool GetMouseIsHeld(int index)
{
#if USE_NEW_INPUT_SYSTEM
var buttonControl = GetMouseButtonControl(index); return buttonControl != null ? buttonControl.isPressed : false;
#else
return UnityEngine.Input.GetMouseButton(index);
#endif
}
public static bool GetMouseWentUp(int index)
{
#if USE_NEW_INPUT_SYSTEM
var buttonControl = GetMouseButtonControl(index); return buttonControl != null ? buttonControl.wasReleasedThisFrame : false;
#else
return UnityEngine.Input.GetMouseButtonUp(index);
#endif
}
public static float GetMouseWheelDelta()
{
#if USE_NEW_INPUT_SYSTEM
return UnityEngine.InputSystem.Mouse.current.scroll != null ? UnityEngine.InputSystem.Mouse.current.scroll.ReadValue().y : 0.0f;
#else
return UnityEngine.Input.mouseScrollDelta.y;
#endif
}
public static bool GetMouseExists()
{
#if USE_NEW_INPUT_SYSTEM
return UnityEngine.InputSystem.Mouse.current != null;
#else
return UnityEngine.Input.mousePresent;
#endif
}
public static bool GetKeyboardExists()
{
#if USE_NEW_INPUT_SYSTEM
return UnityEngine.InputSystem.Keyboard.current != null;
#else
return true;
#endif
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fbb4d9a834e3b5b43801419bceffc9cb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 416a4697695e69a4f8517d1e5968f979
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,58 @@
Shader "Hidden/CW/ShapeOutline"
{
Properties
{
}
SubShader
{
Cull Off
Pass
{
CGPROGRAM
#pragma vertex Vert
#pragma fragment Frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
sampler2D _CW_ShapeTex;
float4 _CW_ShapeChannel;
float4 _CW_ShapeCoords;
float4 _CW_ShapeColor;
void Vert (in appdata i, out v2f o)
{
o.vertex = UnityObjectToClipPos(i.vertex);
o.uv = i.uv;
}
fixed4 Frag (v2f i) : SV_Target
{
float u = lerp(_CW_ShapeCoords.x, _CW_ShapeCoords.z, i.uv.x);
float v = lerp(_CW_ShapeCoords.y, _CW_ShapeCoords.w, i.uv.y);
float shape = dot(tex2D(_CW_ShapeTex, float2(u, v)), _CW_ShapeChannel);
float side = shape + abs(ddx(shape)) + abs(ddy(shape));
if (shape >= 0.5f || side < 0.5f)
{
discard;
}
return _CW_ShapeColor;
}
ENDCG
}
}
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: c55a8fe4b61dcfb41a8aaa1869b89fed
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,12 @@
{
"name": "com.cwilkes.common",
"displayName": "Common",
"version": "1.0.0",
"author": {
"name": "Carlos Wilkes",
"email": "carlos.wilkes@gmail.com",
"url": "https://carloswilkes.com"
},
"unity": "2019.4",
"description": "Shared code library."
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 3852ade87e749cc42b40760c9670fc6d
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: