Add project files.

This commit is contained in:
2023-10-08 18:51:40 +02:00
commit 51cc9df14f
2249 changed files with 636804 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateAdditionalDefinesHelper : TemplateAdditionalParentHelper
{
public TemplateAdditionalDefinesHelper() : base( "Additional Defines" )
{
m_helpBoxMessage = "Please add your defines without the #define keywords";
}
public override void AddToDataCollector( ref MasterNodeDataCollector dataCollector, TemplateIncludePragmaContainter nativesContainer )
{
for( int i = 0; i < m_additionalItems.Count; i++ )
{
if( !string.IsNullOrEmpty( m_additionalItems[ i ] ) && !nativesContainer.HasDefine( m_additionalItems[ i ] ) )
dataCollector.AddToDefines( -1, m_additionalItems[ i ] );
}
for( int i = 0; i < m_outsideItems.Count; i++ )
{
if( !string.IsNullOrEmpty( m_outsideItems[ i ] ) && !nativesContainer.HasDefine( m_outsideItems[ i ] ) )
dataCollector.AddToDefines( -1, m_outsideItems[ i ] );
}
}
}
}

View File

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

View File

@@ -0,0 +1,837 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.IO;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEditorInternal;
namespace AmplifyShaderEditor
{
public enum AdditionalLineType
{
Include,
Define,
Pragma,
Custom
}
public enum AdditionalContainerOrigin
{
Native,
ShaderFunction,
Custom
}
[Serializable]
public class AdditionalDirectiveContainerSaveItem
{
public AdditionalLineType LineType = AdditionalLineType.Include;
public string LineValue = string.Empty;
public bool GUIDToggle = false;
public string GUIDValue = string.Empty;
public AdditionalContainerOrigin Origin = AdditionalContainerOrigin.Custom;
public AdditionalDirectiveContainerSaveItem( AdditionalLineType lineType, string lineValue, bool guidToggle, string guidValue, AdditionalContainerOrigin origin )
{
LineType = lineType;
LineValue = lineValue;
GUIDToggle = guidToggle;
GUIDValue = guidValue;
Origin = origin;
}
public AdditionalDirectiveContainerSaveItem( AdditionalDirectiveContainer container )
{
LineType = container.LineType;
LineValue = container.LineValue;
GUIDToggle = container.GUIDToggle;
GUIDValue = container.GUIDValue;
Origin = container.Origin;
}
}
[Serializable]
public class AdditionalDirectiveContainer : ScriptableObject
{
public AdditionalLineType LineType = AdditionalLineType.Include;
public string LineValue = string.Empty;
public bool GUIDToggle = false;
public string GUIDValue = string.Empty;
public AdditionalContainerOrigin Origin = AdditionalContainerOrigin.Custom;
public TextAsset LibObject = null;
public string OwnerId = string.Empty;
public void Init( string ownerId, AdditionalDirectiveContainer item )
{
LineType = item.LineType;
LineValue = item.LineValue;
GUIDToggle = item.GUIDToggle;
GUIDValue = item.GUIDValue;
Origin = item.Origin;
LibObject = item.LibObject;
OwnerId = ownerId;
}
public void Init( AdditionalDirectiveContainerSaveItem item )
{
LineType = item.LineType;
LineValue = item.LineValue;
GUIDToggle = item.GUIDToggle;
GUIDValue = item.GUIDValue;
Origin = item.Origin;
if( GUIDToggle )
{
LibObject = AssetDatabase.LoadAssetAtPath<TextAsset>( AssetDatabase.GUIDToAssetPath( GUIDValue ) );
}
}
public void OnDestroy()
{
//Debug.Log( "Destoying directives" );
LibObject = null;
}
public string Value
{
get
{
switch( LineType )
{
case AdditionalLineType.Include:
{
if( GUIDToggle )
{
string shaderPath = AssetDatabase.GUIDToAssetPath( GUIDValue );
if( !string.IsNullOrEmpty( shaderPath ) )
return shaderPath;
}
return LineValue;
}
case AdditionalLineType.Define: return LineValue;
case AdditionalLineType.Pragma: return LineValue;
}
return LineValue;
}
}
public string FormattedValue
{
get
{
switch( LineType )
{
case AdditionalLineType.Include:
{
if( GUIDToggle )
{
string shaderPath = AssetDatabase.GUIDToAssetPath( GUIDValue );
if( !string.IsNullOrEmpty( shaderPath ) )
return string.Format( Constants.IncludeFormat, shaderPath );
}
return string.Format( Constants.IncludeFormat, LineValue );
}
case AdditionalLineType.Define:
return string.Format( Constants.DefineFormat, LineValue );
case AdditionalLineType.Pragma:
return string.Format( Constants.PragmaFormat, LineValue );
}
return LineValue;
}
}
}
public enum ReordableAction
{
None,
Add,
Remove
}
[Serializable]
public sealed class TemplateAdditionalDirectivesHelper : TemplateModuleParent
{
private string NativeFoldoutStr = "Native";
[SerializeField]
private List<AdditionalDirectiveContainer> m_additionalDirectives = new List<AdditionalDirectiveContainer>();
[SerializeField]
private List<AdditionalDirectiveContainer> m_shaderFunctionDirectives = new List<AdditionalDirectiveContainer>();
[SerializeField]
private List<string> m_nativeDirectives = new List<string>();
[SerializeField]
private int m_nativeDirectivesIndex = -1;
[SerializeField]
private bool m_nativeDirectivesFoldout = false;
//ONLY USED BY SHADER FUNCTIONS
// Since AdditionalDirectiveContainer must be a ScriptableObject because of serialization shenanigans it will not serialize the info correctly into the shader function when saving it into a file ( it only saves the id )
// For it to properly work, each AdditionalDirectiveContainer should be added to the SF asset, but that would make it to have children ( which are seen on the project inspector )
// Must revisit this later on and come up with a proper solution
[SerializeField]
private List<AdditionalDirectiveContainerSaveItem> m_directivesSaveItems = new List<AdditionalDirectiveContainerSaveItem>();
private ReordableAction m_actionType = ReordableAction.None;
private int m_actionIndex = 0;
private ReorderableList m_reordableList = null;
private GUIStyle m_propertyAdjustment;
private UndoParentNode m_currOwner;
private Rect m_nativeRect = Rect.zero;
public TemplateAdditionalDirectivesHelper( string moduleName ) : base( moduleName ) { }
//public void AddShaderFunctionItem( AdditionalLineType type, string item )
//{
// UpdateShaderFunctionDictionary();
// string id = type + item;
// if( !m_shaderFunctionDictionary.ContainsKey( id ) )
// {
// AdditionalDirectiveContainer newItem = ScriptableObject.CreateInstance<AdditionalDirectiveContainer>();
// newItem.LineType = type;
// newItem.LineValue = item;
// newItem.hideFlags = HideFlags.HideAndDontSave;
// m_shaderFunctionDirectives.Add( newItem );
// m_shaderFunctionDictionary.Add( id, newItem );
// }
//}
public void AddShaderFunctionItems( string ownerOutputId, List<AdditionalDirectiveContainer> functionList )
{
RemoveShaderFunctionItems( ownerOutputId );
if( functionList.Count > 0 )
{
for( int i = 0; i < functionList.Count; i++ )
{
AdditionalDirectiveContainer item = ScriptableObject.CreateInstance<AdditionalDirectiveContainer>();
item.Init( ownerOutputId, functionList[ i ] );
m_shaderFunctionDirectives.Add( item );
}
}
//if( functionList.Count > 0 )
//{
// m_shaderFunctionDirectives.AddRange( functionList );
//}
}
public void RemoveShaderFunctionItems( string ownerOutputId/*, List<AdditionalDirectiveContainer> functionList */)
{
List<AdditionalDirectiveContainer> list = m_shaderFunctionDirectives.FindAll( ( x ) => x.OwnerId.Equals( ownerOutputId ));
for( int i = 0; i < list.Count; i++ )
{
m_shaderFunctionDirectives.Remove( list[ i ] );
ScriptableObject.DestroyImmediate( list[ i ] );
}
list.Clear();
list = null;
//for( int i = 0; i < functionList.Count; i++ )
//{
// m_shaderFunctionDirectives.Remove( functionList[ i ] );
//}
}
//public void RemoveShaderFunctionItem( AdditionalLineType type, string item )
//{
// m_shaderFunctionDirectives.RemoveAll( x => x.LineType == type && x.LineValue.Equals( item ) );
//}
public void AddItems( AdditionalLineType type, List<string> items )
{
int count = items.Count;
for( int i = 0; i < count; i++ )
{
AdditionalDirectiveContainer newItem = ScriptableObject.CreateInstance<AdditionalDirectiveContainer>();
newItem.LineType = type;
newItem.LineValue = items[ i ];
newItem.hideFlags = HideFlags.HideAndDontSave;
m_additionalDirectives.Add( newItem );
}
UpdateNativeIndex();
}
public void AddNativeContainer()
{
if( m_nativeDirectives.Count > 0 )
{
if( m_additionalDirectives.FindIndex( x => x.Origin.Equals( AdditionalContainerOrigin.Native ) ) == -1 )
{
AdditionalDirectiveContainer newItem = ScriptableObject.CreateInstance<AdditionalDirectiveContainer>();
newItem.Origin = AdditionalContainerOrigin.Native;
newItem.hideFlags = HideFlags.HideAndDontSave;
//m_additionalDirectives.Add( newItem );
//m_nativeDirectivesIndex = m_additionalDirectives.Count - 1;
m_additionalDirectives.Insert( 0, newItem );
m_nativeDirectivesIndex = 0;
}
}
}
public void FillNativeItems( List<string> nativeItems )
{
m_nativeDirectives.Clear();
m_nativeDirectives.AddRange( nativeItems );
AddNativeContainer();
}
void DrawNativeItems()
{
EditorGUILayout.Separator();
EditorGUI.indentLevel++;
int count = m_nativeDirectives.Count;
for( int i = 0; i < count; i++ )
{
EditorGUILayout.LabelField( m_nativeDirectives[ i ] );
}
EditorGUI.indentLevel--;
EditorGUILayout.Separator();
}
void DrawNativeItemsRect()
{
int count = m_nativeDirectives.Count;
m_nativeRect.y += EditorGUIUtility.singleLineHeight;
for( int i = 0; i < count; i++ )
{
EditorGUI.LabelField( m_nativeRect, m_nativeDirectives[ i ] );
m_nativeRect.y += EditorGUIUtility.singleLineHeight;
}
}
void DrawButtons()
{
EditorGUILayout.Separator();
// Add keyword
if( GUILayout.Button( string.Empty, UIUtils.PlusStyle, GUILayout.Width( Constants.PlusMinusButtonLayoutWidth ) ) )
{
AdditionalDirectiveContainer newItem = ScriptableObject.CreateInstance<AdditionalDirectiveContainer>();
newItem.hideFlags = HideFlags.HideAndDontSave;
m_additionalDirectives.Add( newItem );
UpdateNativeIndex();
EditorGUI.FocusTextInControl( null );
m_isDirty = true;
}
//Remove keyword
if( GUILayout.Button( string.Empty, UIUtils.MinusStyle, GUILayout.Width( Constants.PlusMinusButtonLayoutWidth ) ) )
{
if( m_additionalDirectives.Count > 0 )
{
AdditionalDirectiveContainer itemToDelete = m_additionalDirectives[ m_additionalDirectives.Count - 1 ];
m_additionalDirectives.RemoveAt( m_additionalDirectives.Count - 1 );
ScriptableObject.DestroyImmediate( itemToDelete );
EditorGUI.FocusTextInControl( null );
}
m_isDirty = true;
}
}
public override void Draw( UndoParentNode currOwner, bool style = true )
{
m_currOwner = currOwner;
if( m_reordableList == null )
{
m_reordableList = new ReorderableList( m_additionalDirectives, typeof( AdditionalDirectiveContainer ), true, false, false, false )
{
headerHeight = 0,
footerHeight = 0,
showDefaultBackground = false,
elementHeightCallback = ( index ) =>
{
if( m_additionalDirectives[ index ].Origin == AdditionalContainerOrigin.Native && m_nativeDirectivesFoldout )
{
return ( m_nativeDirectives.Count + 1 ) * ( EditorGUIUtility.singleLineHeight ) + 5;
}
return EditorGUIUtility.singleLineHeight + 5;
},
drawElementCallback = ( Rect rect, int index, bool isActive, bool isFocused ) =>
{
if( m_additionalDirectives[ index ].Origin == AdditionalContainerOrigin.Native && m_nativeDirectivesFoldout )
{
rect.height = ( m_nativeDirectives.Count + 1 ) * ( EditorGUIUtility.singleLineHeight ) + 5;
}
if( m_additionalDirectives[ index ] != null )
{
float labelWidthStyleAdjust = 0;
if( style )
{
rect.xMin -= 10;
labelWidthStyleAdjust = 15;
}
else
{
rect.xMin -= 1;
}
float popUpWidth = style ? 80 : 65f;
float widthAdjust = m_additionalDirectives[ index ].LineType == AdditionalLineType.Include ? -14 : 0;
Rect popupPos = new Rect( rect.x, rect.y, popUpWidth, EditorGUIUtility.singleLineHeight );
Rect GUIDTogglePos = m_additionalDirectives[ index ].LineType == AdditionalLineType.Include ? new Rect( rect.x + rect.width - 3 * Constants.PlusMinusButtonLayoutWidth, rect.y, Constants.PlusMinusButtonLayoutWidth, Constants.PlusMinusButtonLayoutWidth ) : new Rect();
Rect buttonPlusPos = new Rect( rect.x + rect.width - 2 * Constants.PlusMinusButtonLayoutWidth, rect.y - 2, Constants.PlusMinusButtonLayoutWidth, Constants.PlusMinusButtonLayoutWidth );
Rect buttonMinusPos = new Rect( rect.x + rect.width - Constants.PlusMinusButtonLayoutWidth, rect.y - 2, Constants.PlusMinusButtonLayoutWidth, Constants.PlusMinusButtonLayoutWidth );
float labelWidthBuffer = EditorGUIUtility.labelWidth;
Rect labelPos = new Rect( rect.x + popupPos.width - labelWidthStyleAdjust, rect.y, labelWidthStyleAdjust + rect.width - popupPos.width - buttonPlusPos.width - buttonMinusPos.width + widthAdjust, EditorGUIUtility.singleLineHeight );
if( m_additionalDirectives[ index ].Origin == AdditionalContainerOrigin.Native )
{
m_nativeRect = rect;
#if UNITY_2019_3_OR_NEWER
m_nativeRect.y -= ( m_nativeRect.height - ( EditorGUIUtility.singleLineHeight + 5 ) ) * 0.5f;
#endif
m_nativeRect.xMin += 2;
m_nativeRect.xMax -= 2;
m_nativeRect.yMax -= 2;
NodeUtils.DrawNestedPropertyGroup( ref m_nativeDirectivesFoldout, rect, NativeFoldoutStr, DrawNativeItemsRect, 4 );
return;
}
m_additionalDirectives[ index ].LineType = (AdditionalLineType)m_currOwner.EditorGUIEnumPopup( popupPos, m_additionalDirectives[ index ].LineType );
if( m_additionalDirectives[ index ].LineType == AdditionalLineType.Include )
{
if( m_additionalDirectives[ index ].GUIDToggle )
{
//if( m_additionalDirectives[ index ].LibObject == null && !string.IsNullOrEmpty( m_additionalDirectives[ index ].GUIDValue ) )
//{
// m_additionalDirectives[ index ].LibObject = AssetDatabase.LoadAssetAtPath<TextAsset>( AssetDatabase.GUIDToAssetPath( m_additionalDirectives[ index ].GUIDValue ) );
//}
EditorGUI.BeginChangeCheck();
TextAsset obj = m_currOwner.EditorGUIObjectField( labelPos, m_additionalDirectives[ index ].LibObject, typeof( TextAsset ), false ) as TextAsset;
if( EditorGUI.EndChangeCheck() )
{
string pathName = AssetDatabase.GetAssetPath( obj );
string extension = Path.GetExtension( pathName );
extension = extension.ToLower();
if( extension.Equals( ".cginc" ) || extension.Equals( ".hlsl" ) )
{
m_additionalDirectives[ index ].LibObject = obj;
m_additionalDirectives[ index ].GUIDValue = AssetDatabase.AssetPathToGUID( pathName );
}
}
}
else
{
m_additionalDirectives[ index ].LineValue = m_currOwner.EditorGUITextField( labelPos, string.Empty, m_additionalDirectives[ index ].LineValue );
}
if( GUI.Button( GUIDTogglePos, m_additionalDirectives[ index ].GUIDToggle ? UIUtils.FloatIntIconOFF : UIUtils.FloatIntIconON, UIUtils.FloatIntPickerONOFF ) )
m_additionalDirectives[ index ].GUIDToggle = !m_additionalDirectives[ index ].GUIDToggle;
}
else
{
m_additionalDirectives[ index ].LineValue = m_currOwner.EditorGUITextField( labelPos, string.Empty, m_additionalDirectives[ index ].LineValue );
}
if( GUI.Button( buttonPlusPos, string.Empty, UIUtils.PlusStyle ) )
{
m_actionType = ReordableAction.Add;
m_actionIndex = index;
}
if( GUI.Button( buttonMinusPos, string.Empty, UIUtils.MinusStyle ) )
{
m_actionType = ReordableAction.Remove;
m_actionIndex = index;
}
}
},
onReorderCallback = ( ReorderableList list ) =>
{
UpdateNativeIndex();
}
};
}
if( m_actionType != ReordableAction.None )
{
switch( m_actionType )
{
case ReordableAction.Add:
{
AdditionalDirectiveContainer newItem = ScriptableObject.CreateInstance<AdditionalDirectiveContainer>();
newItem.hideFlags = HideFlags.HideAndDontSave;
m_additionalDirectives.Insert( m_actionIndex + 1, newItem );
}
break;
case ReordableAction.Remove:
AdditionalDirectiveContainer itemToDelete = m_additionalDirectives[ m_actionIndex ];
m_additionalDirectives.RemoveAt( m_actionIndex );
ScriptableObject.DestroyImmediate( itemToDelete );
break;
}
m_isDirty = true;
m_actionType = ReordableAction.None;
EditorGUI.FocusTextInControl( null );
}
bool foldoutValue = currOwner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedAdditionalDirectives;
if( style )
{
NodeUtils.DrawPropertyGroup( ref foldoutValue, m_moduleName, DrawReordableList, DrawButtons );
}
else
{
NodeUtils.DrawNestedPropertyGroup( ref foldoutValue, m_moduleName, DrawReordableList, DrawButtons );
}
currOwner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedAdditionalDirectives = foldoutValue;
}
void DrawReordableList()
{
if( m_reordableList != null )
{
if( m_propertyAdjustment == null )
{
m_propertyAdjustment = new GUIStyle();
m_propertyAdjustment.padding.left = 17;
}
//EditorGUILayout.BeginVertical( m_propertyAdjustment );
EditorGUILayout.Space();
if( m_nativeDirectives.Count > 0 )
{
//NodeUtils.DrawNestedPropertyGroup( ref m_nativeDirectivesFoldout, NativeFoldoutStr, DrawNativeItems, 4 );
}
if( m_additionalDirectives.Count == 0 )
{
EditorGUILayout.HelpBox( "Your list is Empty!\nUse the plus button to add one.", MessageType.Info );
}
else
{
m_reordableList.DoLayoutList();
}
EditorGUILayout.Space();
//EditorGUILayout.EndVertical();
}
}
public void AddAllToDataCollector( ref MasterNodeDataCollector dataCollector, TemplateIncludePragmaContainter nativesContainer )
{
//List<AdditionalDirectiveContainer> list = m_additionalDirectives;
//int count = list.FindIndex( x => x.Origin.Equals( AdditionalContainerOrigin.Native ) );
//for( int i = 0; i < count; i++ )
//{
// switch( list[ i ].LineType )
// {
// case AdditionalLineType.Include:
// {
// string value = list[ i ].Value;
// if( !string.IsNullOrEmpty( value ) &&
// !nativesContainer.HasInclude( value ) )
// {
// dataCollector.AddToMisc( list[ i ].FormattedValue );
// }
// }
// break;
// case AdditionalLineType.Define:
// {
// if( !string.IsNullOrEmpty( list[ i ].LineValue ) &&
// !nativesContainer.HasDefine( list[ i ].LineValue ) )
// {
// dataCollector.AddToMisc( list[ i ].FormattedValue );
// }
// }
// break;
// case AdditionalLineType.Pragma:
// {
// if( !string.IsNullOrEmpty( list[ i ].LineValue ) &&
// !nativesContainer.HasPragma( list[ i ].LineValue ) )
// {
// dataCollector.AddToMisc( list[ i ].FormattedValue );
// }
// }
// break;
// default:
// case AdditionalLineType.Custom:
// dataCollector.AddToMisc( list[ i ].LineValue );
// break;
// }
//}
AddToDataCollector( ref dataCollector, nativesContainer, false );
AddToDataCollector( ref dataCollector, nativesContainer, true );
}
public void AddAllToDataCollector( ref MasterNodeDataCollector dataCollector )
{
AddToDataCollector( ref dataCollector, false );
AddToDataCollector( ref dataCollector, true );
}
void AddToDataCollector( ref MasterNodeDataCollector dataCollector, TemplateIncludePragmaContainter nativesContainer, bool fromSF )
{
List<AdditionalDirectiveContainer> list = fromSF ? m_shaderFunctionDirectives : m_additionalDirectives;
int count = list.Count;
for( int i = 0; i < count; i++ )
{
int orderIdx = fromSF ? 1 : ( i > m_nativeDirectivesIndex ? 1 : -1 );
switch( list[ i ].LineType )
{
case AdditionalLineType.Include:
{
string value = list[ i ].Value;
if( !string.IsNullOrEmpty( value ) &&
!nativesContainer.HasInclude( value ) )
{
dataCollector.AddToDirectives( list[ i ].FormattedValue, orderIdx );
}
}
break;
case AdditionalLineType.Define:
{
if( !string.IsNullOrEmpty( list[ i ].LineValue ) &&
!nativesContainer.HasDefine( list[ i ].LineValue ) )
{
dataCollector.AddToDirectives( list[ i ].FormattedValue, orderIdx );
}
}
break;
case AdditionalLineType.Pragma:
{
if( !string.IsNullOrEmpty( list[ i ].LineValue ) &&
!nativesContainer.HasPragma( list[ i ].LineValue ) )
{
dataCollector.AddToDirectives( list[ i ].FormattedValue, orderIdx );
}
}
break;
default:
case AdditionalLineType.Custom:
dataCollector.AddToDirectives( list[ i ].LineValue, orderIdx );
break;
}
}
}
void AddToDataCollector( ref MasterNodeDataCollector dataCollector, bool fromSF )
{
List<AdditionalDirectiveContainer> list = fromSF ? m_shaderFunctionDirectives : m_additionalDirectives;
int orderIdx = 1;
int count = list.Count;
for( int i = 0; i < count; i++ )
{
switch( list[ i ].LineType )
{
case AdditionalLineType.Include:
{
string value = list[ i ].FormattedValue;
if( !string.IsNullOrEmpty( value ) )
{
dataCollector.AddToDirectives( value, orderIdx );
}
}
break;
case AdditionalLineType.Define:
{
if( !string.IsNullOrEmpty( list[ i ].LineValue ) )
{
dataCollector.AddToDirectives( list[ i ].FormattedValue, orderIdx );
}
}
break;
case AdditionalLineType.Pragma:
{
if( !string.IsNullOrEmpty( list[ i ].LineValue ) )
{
dataCollector.AddToDirectives( list[ i ].FormattedValue, orderIdx );
}
}
break;
default:
case AdditionalLineType.Custom:
dataCollector.AddToDirectives( list[ i ].LineValue, orderIdx );
break;
}
}
}
public override void ReadFromString( ref uint index, ref string[] nodeParams )
{
try
{
m_nativeDirectivesIndex = -1;
int count = Convert.ToInt32( nodeParams[ index++ ] );
m_additionalDirectives.Clear();
for( int i = 0; i < count; i++ )
{
AdditionalLineType lineType = (AdditionalLineType)Enum.Parse( typeof( AdditionalLineType ), nodeParams[ index++ ] );
string lineValue = nodeParams[ index++ ];
AdditionalDirectiveContainer newItem = ScriptableObject.CreateInstance<AdditionalDirectiveContainer>();
newItem.hideFlags = HideFlags.HideAndDontSave;
newItem.LineType = lineType;
newItem.LineValue = lineValue.Replace( Constants.SemiColonSeparator, ';' );
if( UIUtils.CurrentShaderVersion() > 15607 )
{
newItem.GUIDToggle = Convert.ToBoolean( nodeParams[ index++ ] );
newItem.GUIDValue = nodeParams[ index++ ];
if( newItem.GUIDToggle )
{
newItem.LibObject = AssetDatabase.LoadAssetAtPath<TextAsset>( AssetDatabase.GUIDToAssetPath( newItem.GUIDValue ) );
if( newItem.LibObject == null )
{
Debug.LogWarning( "Include file not found with GUID " + newItem.GUIDValue );
}
}
}
AdditionalContainerOrigin origin = AdditionalContainerOrigin.Custom;
if( UIUtils.CurrentShaderVersion() > 16902 )
{
origin = (AdditionalContainerOrigin)Enum.Parse( typeof( AdditionalContainerOrigin ), nodeParams[ index++ ] );
newItem.Origin = origin;
}
m_additionalDirectives.Add( newItem );
if( origin == AdditionalContainerOrigin.Native )
{
m_nativeDirectivesIndex = i;
}
}
AddNativeContainer();
}
catch( Exception e )
{
Debug.LogException( e );
}
}
public override void WriteToString( ref string nodeInfo )
{
if( m_additionalDirectives.Count == 1 && m_additionalDirectives[ 0 ].Origin == AdditionalContainerOrigin.Native )
{
IOUtils.AddFieldValueToString( ref nodeInfo, 0 );
return;
}
IOUtils.AddFieldValueToString( ref nodeInfo, m_additionalDirectives.Count );
for( int i = 0; i < m_additionalDirectives.Count; i++ )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_additionalDirectives[ i ].LineType );
IOUtils.AddFieldValueToString( ref nodeInfo, m_additionalDirectives[ i ].LineValue.Replace( ';', Constants.SemiColonSeparator ) );
IOUtils.AddFieldValueToString( ref nodeInfo, m_additionalDirectives[ i ].GUIDToggle );
IOUtils.AddFieldValueToString( ref nodeInfo, m_additionalDirectives[ i ].GUIDValue );
IOUtils.AddFieldValueToString( ref nodeInfo, m_additionalDirectives[ i ].Origin );
}
}
// read comment on m_directivesSaveItems declaration
public void UpdateSaveItemsFromDirectives()
{
bool foundNull = false;
m_directivesSaveItems.Clear();
for( int i = 0; i < m_additionalDirectives.Count; i++ )
{
if( m_additionalDirectives[ i ] != null )
{
m_directivesSaveItems.Add( new AdditionalDirectiveContainerSaveItem( m_additionalDirectives[ i ] ) );
}
else
{
foundNull = true;
}
}
if( foundNull )
{
m_additionalDirectives.RemoveAll( item => item == null );
}
}
public void CleanNullDirectives()
{
m_additionalDirectives.RemoveAll( item => item == null );
}
public void ResetDirectivesOrigin()
{
for( int i = 0; i < m_directivesSaveItems.Count; i++ )
{
m_directivesSaveItems[ i ].Origin = AdditionalContainerOrigin.Custom;
}
}
// read comment on m_directivesSaveItems declaration
public void UpdateDirectivesFromSaveItems()
{
if( m_directivesSaveItems.Count > 0 )
{
for( int i = 0; i < m_additionalDirectives.Count; i++ )
{
if( m_additionalDirectives[ i ] != null )
ScriptableObject.DestroyImmediate( m_additionalDirectives[ i ] );
}
m_additionalDirectives.Clear();
for( int i = 0; i < m_directivesSaveItems.Count; i++ )
{
AdditionalDirectiveContainer newItem = ScriptableObject.CreateInstance<AdditionalDirectiveContainer>();
newItem.hideFlags = HideFlags.HideAndDontSave;
newItem.Init( m_directivesSaveItems[ i ] );
m_additionalDirectives.Add( newItem );
}
UpdateNativeIndex();
//m_directivesSaveItems.Clear();
}
}
void UpdateNativeIndex()
{
m_nativeDirectivesIndex = -1;
int count = m_additionalDirectives.Count;
for( int i = 0; i < count; i++ )
{
if( m_additionalDirectives[ i ].Origin == AdditionalContainerOrigin.Native )
{
m_nativeDirectivesIndex = i;
break;
}
}
}
public override void Destroy()
{
base.Destroy();
m_nativeDirectives.Clear();
m_nativeDirectives = null;
for( int i = 0; i < m_additionalDirectives.Count; i++ )
{
ScriptableObject.DestroyImmediate( m_additionalDirectives[ i ] );
}
m_additionalDirectives.Clear();
m_additionalDirectives = null;
for( int i = 0; i < m_shaderFunctionDirectives.Count; i++ )
{
ScriptableObject.DestroyImmediate( m_shaderFunctionDirectives[ i ] );
}
m_shaderFunctionDirectives.Clear();
m_shaderFunctionDirectives = null;
m_propertyAdjustment = null;
m_reordableList = null;
}
public List<AdditionalDirectiveContainer> DirectivesList { get { return m_additionalDirectives; } }
public bool IsValid { get { return m_validData; } set { m_validData = value; } }
}
}

View File

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

View File

@@ -0,0 +1,31 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateAdditionalIncludesHelper : TemplateAdditionalParentHelper
{
public TemplateAdditionalIncludesHelper() : base( "Additional Includes" )
{
m_helpBoxMessage = "Please add your includes without the #include \"\" keywords";
}
public override void AddToDataCollector( ref MasterNodeDataCollector dataCollector , TemplateIncludePragmaContainter nativesContainer )
{
for( int i = 0; i < m_additionalItems.Count; i++ )
{
if( !string.IsNullOrEmpty( m_additionalItems[ i ] ) && !nativesContainer.HasInclude( m_additionalItems[ i ] ) )
dataCollector.AddToIncludes( -1, m_additionalItems[ i ] );
}
for( int i = 0; i < m_outsideItems.Count; i++ )
{
if( !string.IsNullOrEmpty( m_outsideItems[ i ] ) && !nativesContainer.HasInclude( m_outsideItems[ i ] ) )
dataCollector.AddToIncludes( -1, m_outsideItems[ i ] );
}
}
}
}

View File

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

View File

@@ -0,0 +1,193 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateAdditionalParentHelper : TemplateModuleParent
{
private string NativeFoldoutStr = "Native";
protected string m_helpBoxMessage = string.Empty;
private const float ShaderKeywordButtonLayoutWidth = 15;
private ParentNode m_currentOwner;
[SerializeField]
protected List<string> m_nativeItems = new List<string>();
[SerializeField]
protected bool m_nativeItemsFoldout = false;
[SerializeField]
protected List<string> m_additionalItems = new List<string>();
[SerializeField]
protected List<string> m_outsideItems = new List<string>();
public TemplateAdditionalParentHelper( string moduleName ) : base( moduleName ) { }
public bool IsValid { set{ m_validData = value; } get{ return m_validData; } }
public void FillNativeItems( List<string> nativeItems )
{
m_nativeItems.Clear();
m_nativeItems.AddRange( nativeItems );
}
public void Draw( ParentNode owner )
{
m_currentOwner = owner;
bool foldout = owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedAdditionalDefines;
NodeUtils.DrawNestedPropertyGroup( ref foldout, m_moduleName, DrawMainBody, DrawButtons );
owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedAdditionalDefines = foldout;
}
public void CopyFrom( TemplateAdditionalParentHelper other )
{
m_additionalItems.Clear();
m_outsideItems.Clear();
int otherAdditionalItemsCount = other.ItemsList.Count;
for( int i = 0; i < otherAdditionalItemsCount; i++ )
{
m_additionalItems.Add( other.ItemsList[ i ] );
}
int otherOusideItemsCount = other.OutsideList.Count;
for( int i = 0; i < otherOusideItemsCount; i++ )
{
m_outsideItems.Add( other.OutsideList[ i ] );
}
}
void DrawButtons()
{
EditorGUILayout.Separator();
// Add keyword
if( GUILayout.Button( string.Empty, UIUtils.PlusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
m_additionalItems.Add( string.Empty );
EditorGUI.FocusTextInControl( null );
m_isDirty = true;
}
//Remove keyword
if( GUILayout.Button( string.Empty, UIUtils.MinusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
if( m_additionalItems.Count > 0 )
{
m_additionalItems.RemoveAt( m_additionalItems.Count - 1 );
EditorGUI.FocusTextInControl( null );
}
m_isDirty = true;
}
}
void DrawNativeItems()
{
EditorGUILayout.Separator();
EditorGUI.indentLevel++;
int count = m_nativeItems.Count;
for ( int i = 0; i < count; i++ )
{
EditorGUILayout.LabelField( m_nativeItems[i] );
}
EditorGUI.indentLevel--;
EditorGUILayout.Separator();
}
void DrawMainBody()
{
EditorGUILayout.Separator();
if( m_nativeItems.Count > 0 )
{
NodeUtils.DrawNestedPropertyGroup( ref m_nativeItemsFoldout, NativeFoldoutStr, DrawNativeItems ,4);
}
int itemCount = m_additionalItems.Count;
int markedToDelete = -1;
for( int i = 0; i < itemCount; i++ )
{
EditorGUILayout.BeginHorizontal();
{
EditorGUI.BeginChangeCheck();
m_additionalItems[ i ] = EditorGUILayout.TextField( m_additionalItems[ i ] );
if( EditorGUI.EndChangeCheck() )
{
m_additionalItems[ i ] = UIUtils.RemoveShaderInvalidCharacters( m_additionalItems[ i ] );
m_isDirty = true;
}
// Add new port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.PlusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
m_additionalItems.Insert( i + 1, string.Empty );
EditorGUI.FocusTextInControl( null );
m_isDirty = true;
}
//Remove port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.MinusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
markedToDelete = i;
m_isDirty = true;
}
}
EditorGUILayout.EndHorizontal();
}
if( markedToDelete > -1 )
{
if( m_additionalItems.Count > markedToDelete )
{
m_additionalItems.RemoveAt( markedToDelete );
EditorGUI.FocusTextInControl( null );
}
}
EditorGUILayout.Separator();
EditorGUILayout.HelpBox( m_helpBoxMessage, MessageType.Info );
}
public override void ReadFromString( ref uint index, ref string[] nodeParams )
{
try
{
int count = Convert.ToInt32( nodeParams[ index++ ] );
for( int i = 0; i < count; i++ )
{
m_additionalItems.Add( nodeParams[ index++ ] );
}
}
catch( Exception e )
{
Debug.LogException( e );
}
}
public override void WriteToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_additionalItems.Count );
for( int i = 0; i < m_additionalItems.Count; i++ )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_additionalItems[ i ] );
}
}
public virtual void AddToDataCollector( ref MasterNodeDataCollector dataCollector , TemplateIncludePragmaContainter nativesContainer ) { }
public override void Destroy()
{
m_additionalItems.Clear();
m_additionalItems = null;
m_currentOwner = null;
m_nativeItems.Clear();
m_nativeItems = null;
}
public List<string> ItemsList { get { return m_additionalItems; } set { m_additionalItems = value; } }
public List<string> OutsideList { get { return m_outsideItems; } set { m_outsideItems = value; } }
}
}

View File

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

View File

@@ -0,0 +1,31 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateAdditionalPragmasHelper : TemplateAdditionalParentHelper
{
public TemplateAdditionalPragmasHelper() : base( "Additional Pragmas" )
{
m_helpBoxMessage = "Please add your pragmas without the #pragma keywords";
}
public override void AddToDataCollector( ref MasterNodeDataCollector dataCollector, TemplateIncludePragmaContainter nativesContainer )
{
for( int i = 0; i < m_additionalItems.Count; i++ )
{
if( !string.IsNullOrEmpty( m_additionalItems[ i ] ) && !nativesContainer.HasPragma( m_additionalItems[ i ] ))
dataCollector.AddToPragmas( -1, m_additionalItems[ i ] );
}
for( int i = 0; i < m_outsideItems.Count; i++ )
{
if( !string.IsNullOrEmpty( m_outsideItems[ i ] ) && !nativesContainer.HasPragma( m_outsideItems[ i ] ) )
dataCollector.AddToPragmas( -1, m_outsideItems[ i ] );
}
}
}
}

View File

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

View File

@@ -0,0 +1,128 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
[Serializable]
public sealed class TemplateAlphaToMaskModule : TemplateModuleParent
{
private const string AlphaToMaskFormatStr = "AlphaToMask ";
private const string AlphaToMaskFormat = "AlphaToMask {0}";
public TemplateAlphaToMaskModule() : base( "Alpha To Coverage" ) { }
private static readonly string AlphaToMaskStr = "Alpha To Coverage";
[SerializeField]
private bool m_alphaToMask = false;
[SerializeField]
private InlineProperty m_inlineAlphaToMask = new InlineProperty();
public void CopyFrom( TemplateAlphaToMaskModule other , bool allData )
{
if( allData )
m_independentModule = other.IndependentModule;
m_alphaToMask = other.AlphaToMask;
m_inlineAlphaToMask.CopyFrom( other.AlphaToMaskInlineProperty );
}
public void ConfigureFromTemplateData( TemplateAlphaToMaskData data )
{
bool newValidData = ( data.DataCheck == TemplateDataCheck.Valid );
if( newValidData && m_validData != newValidData )
{
m_independentModule = data.IndependentModule;
if( string.IsNullOrEmpty( data.InlineData ) )
{
m_alphaToMask = data.AlphaToMaskData;
m_inlineAlphaToMask.IntValue = m_alphaToMask ? 1 : 0;
m_inlineAlphaToMask.ResetProperty();
}
else
{
m_inlineAlphaToMask.SetInlineByName( data.InlineData );
}
}
m_validData = newValidData;
}
public override void Draw( UndoParentNode owner, bool style = true )
{
EditorGUI.BeginChangeCheck();
m_inlineAlphaToMask.CustomDrawer( ref owner, ( x ) => { m_alphaToMask = owner.EditorGUILayoutToggle( AlphaToMaskStr, m_alphaToMask ); }, AlphaToMaskStr );
if( EditorGUI.EndChangeCheck() )
{
m_inlineAlphaToMask.IntValue = m_alphaToMask ? 1 : 0;
m_isDirty = true;
}
}
public override void ReadFromString( ref uint index, ref string[] nodeParams )
{
bool validDataOnMeta = m_validData;
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
validDataOnMeta = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( validDataOnMeta )
{
if( UIUtils.CurrentShaderVersion() < 15304 )
{
m_alphaToMask = Convert.ToBoolean( nodeParams[ index++ ] );
m_inlineAlphaToMask.IntValue = m_alphaToMask ? 1 : 0;
}
else
{
m_inlineAlphaToMask.ReadFromString( ref index, ref nodeParams );
m_alphaToMask = m_inlineAlphaToMask.IntValue == 1;
}
}
}
public override void WriteToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_validData );
if( m_validData )
{
m_inlineAlphaToMask.WriteToString( ref nodeInfo );
}
}
public override string GenerateShaderData( bool isSubShader )
{
return AlphaToMaskFormatStr + m_inlineAlphaToMask.GetValueOrProperty( m_alphaToMask ? "On" : "Off");
}
public override void Destroy()
{
base.Destroy();
m_inlineAlphaToMask = null;
}
//public string CurrentAlphaToMask
//{
// get { return string.Format( AlphaToMaskFormat, m_alphaToMask ? "On" : "Off" ); }
//}
public bool AlphaToMask
{
get { return m_alphaToMask; }
set
{
m_alphaToMask = value;
m_inlineAlphaToMask.IntValue = value ? 1 : 0;
m_inlineAlphaToMask.Active = false;
}
}
public InlineProperty AlphaToMaskInlineProperty { get { return m_inlineAlphaToMask; } }
}
}

View File

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

View File

@@ -0,0 +1,102 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using UnityEngine;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
public enum TemplateCodeSnippetType
{
Toggle
};
public enum TemplateCodeSnippetInfoIdx
{
Name = 0,
Type
};
[Serializable]
public class TemplateCodeSnippetElement
{
public string Id;
public string Snippet;
public TemplateCodeSnippetElement( string id, string snippet )
{
Id = id;
Snippet = snippet;
}
}
[Serializable]
public class TemplateCodeSnippetBase : ScriptableObject
{
[SerializeField]
private string m_nameId;
[SerializeField]
private TemplateCodeSnippetType m_type;
[SerializeField]
private List<TemplateCodeSnippetElement> m_elements = new List<TemplateCodeSnippetElement>();
public void Init( string nameId, TemplateCodeSnippetType type )
{
m_nameId = nameId;
m_type = type;
}
public void AddSnippet( TemplateCodeSnippetElement element )
{
m_elements.Add( element );
}
public void Destroy()
{
for ( int i = 0; i < m_elements.Count; i++ )
{
m_elements[ i ].Snippet = null;
}
m_elements.Clear();
m_elements = null;
}
public virtual void DrawProperties( ParentNode owner ) { }
public virtual bool CheckSnippet() { return true; }
public void InsertSnippet( ref string shaderBody )
{
bool insertSnippet = CheckSnippet();
for ( int i = 0; i < m_elements.Count; i++ )
{
shaderBody = shaderBody.Replace( m_elements[ i ].Id, ( insertSnippet ? m_elements[ i ].Snippet : string.Empty ) );
}
}
public string NameId { get { return m_nameId; } }
public TemplateCodeSnippetType Type { get { return m_type; } }
public List<TemplateCodeSnippetElement> Elements { get { return m_elements; } }
}
[Serializable]
public class TemplateCodeSnippetToggle : TemplateCodeSnippetBase
{
private const string Label = "Activate";
[SerializeField]
private bool m_value = false;
public override bool CheckSnippet()
{
return m_value;
}
public override void DrawProperties( ParentNode owner )
{
m_value = owner.EditorGUILayoutToggle( Label, m_value );
}
}
}

View File

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

View File

@@ -0,0 +1,200 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateColorMaskModule : TemplateModuleParent
{
private const string ColorMaskOp = "ColorMask ";
private const string ColorMaskOff = "ColorMask RGBA";
private GUIContent ColorMaskContent = new GUIContent( "Color Mask", "Sets color channel writing mask, turning all off makes the object completely invisible\nDefault: RGBA" );
private readonly char[] m_colorMaskChar = { 'R', 'G', 'B', 'A' };
private GUIStyle m_leftToggleColorMask;
private GUIStyle m_middleToggleColorMask;
private GUIStyle m_rightToggleColorMask;
public TemplateColorMaskModule() : base( "Color Mask" ) { }
[SerializeField]
private bool[] m_colorMask = { true, true, true, true };
[SerializeField]
private string m_target = string.Empty;
[SerializeField]
private InlineProperty m_inlineColorMask = new InlineProperty();
public void CopyFrom( TemplateColorMaskModule other, bool allData )
{
if( allData )
m_independentModule = other.IndependentModule;
for( int i = 0; i < m_colorMask.Length; i++ )
{
m_colorMask[ i ] = other.ColorMask[ i ];
}
m_target = other.Target;
m_inlineColorMask.CopyFrom( other.InlineColorMask );
}
public void ConfigureFromTemplateData( TemplateColorMaskData data )
{
bool newValidData = ( data.DataCheck == TemplateDataCheck.Valid );
if( newValidData && m_validData != newValidData )
{
m_independentModule = data.IndependentModule;
m_target = data.Target;
if( string.IsNullOrEmpty( data.InlineData ) )
{
for( int i = 0; i < 4; i++ )
{
m_colorMask[ i ] = data.ColorMaskData[ i ];
}
m_inlineColorMask.ResetProperty();
}
else
{
m_inlineColorMask.SetInlineByName( data.InlineData );
}
}
m_validData = newValidData;
}
public override void Draw( UndoParentNode owner, bool style = true )
{
EditorGUI.BeginChangeCheck();
{
m_inlineColorMask.CustomDrawer( ref owner, DrawColorMaskControls, ColorMaskContent.text + m_target );
}
if( EditorGUI.EndChangeCheck() )
{
m_isDirty = true;
CustomEdited = true;
}
}
private void DrawColorMaskControls( UndoParentNode owner )
{
if( m_leftToggleColorMask == null || m_leftToggleColorMask.normal.background == null )
{
m_leftToggleColorMask = GUI.skin.GetStyle( "ButtonLeft" );
}
if( m_middleToggleColorMask == null || m_middleToggleColorMask.normal.background == null )
{
m_middleToggleColorMask = GUI.skin.GetStyle( "ButtonMid" );
}
if( m_rightToggleColorMask == null || m_rightToggleColorMask.normal.background == null )
{
m_rightToggleColorMask = GUI.skin.GetStyle( "ButtonRight" );
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField( "Color Mask"+ m_target, GUILayout.Width( EditorGUIUtility.labelWidth - 3 ) );
m_colorMask[ 0 ] = owner.GUILayoutToggle( m_colorMask[ 0 ], "R", m_leftToggleColorMask );
m_colorMask[ 1 ] = owner.GUILayoutToggle( m_colorMask[ 1 ], "G", m_middleToggleColorMask );
m_colorMask[ 2 ] = owner.GUILayoutToggle( m_colorMask[ 2 ], "B", m_middleToggleColorMask );
m_colorMask[ 3 ] = owner.GUILayoutToggle( m_colorMask[ 3 ], "A", m_rightToggleColorMask );
EditorGUILayout.EndHorizontal();
}
public override string GenerateShaderData( bool isSubShader )
{
if( m_inlineColorMask.IsValid )
return ColorMaskOp + m_inlineColorMask.GetValueOrProperty() + Target;
int count = 0;
string colorMask = string.Empty;
for( int i = 0; i < m_colorMask.Length; i++ )
{
if( m_colorMask[ i ] )
{
count++;
colorMask += m_colorMaskChar[ i ];
}
}
if( count != m_colorMask.Length )
{
return ColorMaskOp + ( ( count == 0 ) ? "0" : colorMask ) + Target;
}
return ColorMaskOff + Target;
}
public override void ReadFromString( ref uint index, ref string[] nodeParams )
{
base.ReadFromString( ref index, ref nodeParams );
bool validDataOnMeta = m_validData;
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
validDataOnMeta = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( validDataOnMeta )
{
for( int i = 0; i < m_colorMask.Length; i++ )
{
m_colorMask[ i ] = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( UIUtils.CurrentShaderVersion() > 15303 )
{
m_inlineColorMask.ReadFromString( ref index, ref nodeParams );
}
}
}
public override void WriteToString( ref string nodeInfo )
{
base.WriteToString( ref nodeInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_validData );
if( m_validData )
{
for( int i = 0; i < m_colorMask.Length; i++ )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_colorMask[ i ] );
}
m_inlineColorMask.WriteToString( ref nodeInfo );
}
}
public bool[] ColorMask
{
get { return m_colorMask; }
set
{
m_colorMask = value;
m_inlineColorMask.Active = false;
}
}
public string Target
{
get { return m_target; }
set { m_target = value; }
}
public override void Destroy()
{
m_leftToggleColorMask = null;
m_middleToggleColorMask = null;
m_rightToggleColorMask = null;
m_inlineColorMask = null;
}
public InlineProperty InlineColorMask { get { return m_inlineColorMask; } }
}
}

View File

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

View File

@@ -0,0 +1,128 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
[Serializable]
public sealed class TemplateCullModeModule : TemplateModuleParent
{
private const string CullModeFormatStr = "Cull ";
public TemplateCullModeModule() : base("Cull Mode"){ }
private static readonly string CullModeStr = "Cull Mode";
[SerializeField]
private CullMode m_cullMode = CullMode.Back;
[SerializeField]
private InlineProperty m_inlineCullMode = new InlineProperty();
public void CopyFrom( TemplateCullModeModule other , bool allData )
{
if( allData )
m_independentModule = other.IndependentModule;
m_cullMode = other.CurrentCullMode;
m_inlineCullMode.CopyFrom( other.CullInlineProperty );
}
public void ConfigureFromTemplateData( TemplateCullModeData data )
{
bool newValidData = ( data.DataCheck == TemplateDataCheck.Valid );
if( newValidData && m_validData != newValidData )
{
m_independentModule = data.IndependentModule;
if( string.IsNullOrEmpty( data.InlineData ) )
{
m_cullMode = data.CullModeData;
m_inlineCullMode.IntValue = (int)m_cullMode;
m_inlineCullMode.ResetProperty();
}
else
{
m_inlineCullMode.SetInlineByName( data.InlineData );
}
}
m_validData = newValidData;
}
public override void Draw( UndoParentNode owner, bool style = true )
{
EditorGUI.BeginChangeCheck();
//m_cullMode = (CullMode)owner.EditorGUILayoutEnumPopup( CullModeStr, m_cullMode );
m_inlineCullMode.CustomDrawer( ref owner, ( x ) => { m_cullMode = (CullMode)owner.EditorGUILayoutEnumPopup( CullModeStr, m_cullMode ); }, CullModeStr );
if( EditorGUI.EndChangeCheck() )
{
m_inlineCullMode.IntValue = (int)m_cullMode;
m_isDirty = true;
CustomEdited = true;
}
}
public override void ReadFromString( ref uint index, ref string[] nodeParams )
{
base.ReadFromString( ref index, ref nodeParams );
bool validDataOnMeta = m_validData;
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
validDataOnMeta = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( validDataOnMeta )
{
if( UIUtils.CurrentShaderVersion() < 15304 )
{
m_cullMode = (CullMode)Enum.Parse( typeof( CullMode ), nodeParams[ index++ ] );
m_inlineCullMode.IntValue = (int)m_cullMode;
}
else
{
m_inlineCullMode.ReadFromString( ref index, ref nodeParams );
m_cullMode = (CullMode)m_inlineCullMode.IntValue;
}
}
}
public override void WriteToString( ref string nodeInfo )
{
base.WriteToString( ref nodeInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_validData );
if( m_validData )
{
//IOUtils.AddFieldValueToString( ref nodeInfo, m_cullMode );
m_inlineCullMode.WriteToString( ref nodeInfo );
}
}
public override string GenerateShaderData( bool isSubShader )
{
//return CullModeFormatStr + m_cullMode.ToString();
return CullModeFormatStr + m_inlineCullMode.GetValueOrProperty( m_cullMode.ToString());
}
public override void Destroy()
{
base.Destroy();
m_inlineCullMode = null;
}
public CullMode CurrentCullMode
{
get { return m_cullMode; }
set
{
m_cullMode = value;
m_inlineCullMode.IntValue = (int)value;
m_inlineCullMode.Active = false;
}
}
public InlineProperty CullInlineProperty { get { return m_inlineCullMode; } }
}
}

View File

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

View File

@@ -0,0 +1,21 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using UnityEngine;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateDBItem
{
public string GUID;
}
[Serializable]
public class TemplateDB : ScriptableObject
{
public List<TemplateDBItem> Items = new List<TemplateDBItem>();
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b12f2516af03f3443b1f2c08c72aa490
timeCreated: 1610016988
licenseType: Store
MonoImporter:
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,12 @@
fileFormatVersion: 2
guid: b03340e569366ae4dbd502e14c62e225
timeCreated: 1493904667
licenseType: Store
MonoImporter:
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,12 @@
fileFormatVersion: 2
guid: c757602c408f7354b96c2a5eb21662a4
timeCreated: 1495710491
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,217 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using UnityEngine;
namespace AmplifyShaderEditor
{
public enum TemplateDataType
{
LegacySinglePass,
MultiPass
}
[Serializable]
public class TemplateIncludePragmaContainter
{
[SerializeField]
private int m_nativeTopIndex = -1;
[SerializeField]
private List<string> m_nativeDirectivesList = new List<string>();
[SerializeField]
private List<string> m_includesList = new List<string>();
private Dictionary<string,string> m_includesDict = new Dictionary<string,string>();
[SerializeField]
private List<string> m_pragmasList = new List<string>();
private Dictionary<string, string> m_pragmasDict = new Dictionary<string, string>();
[SerializeField]
private List<string> m_definesList = new List<string>();
private Dictionary<string, string> m_definesDict = new Dictionary<string, string>();
public void RefreshIncludesList()
{
if ( m_includesDict.Count != m_includesList.Count )
{
m_includesDict.Clear();
int count = m_includesList.Count;
for ( int i = 0; i < count; i++ )
{
m_includesDict.Add( m_includesList[ i ], m_includesList[ i ] );
}
}
}
public void RefreshPragmasList()
{
if ( m_pragmasDict.Count != m_pragmasList.Count )
{
m_pragmasDict.Clear();
int count = m_pragmasList.Count;
for ( int i = 0; i < count; i++ )
{
m_pragmasDict.Add( m_pragmasList[ i ], m_pragmasList[ i ] );
}
}
}
public void RefreshDefinesList()
{
if ( m_definesDict.Count != m_definesList.Count )
{
m_definesDict.Clear();
int count = m_definesList.Count;
for ( int i = 0; i < count; i++ )
{
m_definesDict.Add( m_definesList[ i ], m_definesList[ i ] );
}
}
}
public bool HasInclude( string include )
{
RefreshIncludesList();
return m_includesDict.ContainsKey( include );
}
public bool HasPragma( string pragma )
{
RefreshPragmasList();
return m_pragmasDict.ContainsKey( pragma );
}
public bool HasDefine( string pragma )
{
RefreshDefinesList();
return m_definesDict.ContainsKey( pragma );
}
public void AddInclude( string include )
{
RefreshIncludesList();
if ( !m_includesDict.ContainsKey( include ) )
{
m_includesList.Add( include );
m_includesDict.Add( include, include );
}
}
public void AddPragma( string pragma )
{
RefreshPragmasList();
if ( !m_pragmasDict.ContainsKey( pragma ) )
{
m_pragmasList.Add( pragma );
m_pragmasDict.Add( pragma, pragma );
}
}
public void AddDefine( string define )
{
RefreshDefinesList();
if ( !m_definesDict.ContainsKey( define ) )
{
m_definesList.Add( define );
m_definesDict.Add( define, define );
}
}
public void AddNativeDirective( string native, int topIndex )
{
m_nativeTopIndex = topIndex;
m_nativeDirectivesList.Add( native );
}
public void Destroy()
{
m_nativeDirectivesList.Clear();
m_nativeDirectivesList = null;
m_includesList.Clear();
m_includesDict.Clear();
m_includesList = null;
m_includesDict = null;
m_pragmasList.Clear();
m_pragmasDict.Clear();
m_pragmasList = null;
m_pragmasDict = null;
m_definesList.Clear();
m_definesDict.Clear();
m_definesList = null;
m_definesDict = null;
}
public List<string> IncludesList { get { return m_includesList; } }
public List<string> PragmasList { get { return m_pragmasList; } }
public List<string> DefinesList { get { return m_definesList; } }
public List<string> NativeDirectivesList { get { return m_nativeDirectivesList; } }
public int NativeTopIndex { get { return m_nativeTopIndex; } }
}
[Serializable]
public class TemplateInfoContainer
{
public string Id = string.Empty;
public string Data = string.Empty;
public int Index = -1;
public bool IsValid { get { return Index > -1; } }
public void Reset()
{
Id = string.Empty;
Data = string.Empty;
Index = -1;
}
}
[Serializable]
public class TemplateDataParent : ScriptableObject
{
[SerializeField]
protected TemplateDataType m_templateType;
[SerializeField]
protected string m_name;
[SerializeField]
protected string m_guid;
[SerializeField]
protected int m_orderId;
[SerializeField]
protected string m_defaultShaderName = string.Empty;
[SerializeField]
protected bool m_isValid = true;
[SerializeField]
protected bool m_communityTemplate = false;
public virtual void Destroy() { }
public virtual bool Reload() { return true; }
public string Name
{
get { return m_name; }
set
{
m_name = value.StartsWith( "Hidden/" ) ? value.Replace( "Hidden/", string.Empty ) : value;
}
}
public string GUID { get { return m_guid; } set { m_guid = value; } }
public int OrderId { get { return m_orderId; } set { m_orderId = value; } }
public string DefaultShaderName { get { return m_defaultShaderName; } set { m_defaultShaderName = value; } }
public bool IsValid { get { return m_isValid; } }
public TemplateDataType TemplateType { get { return m_templateType; } }
public virtual void Init( string name, string guid, bool isCommunity ) { m_communityTemplate = isCommunity; }
}
}

View File

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

View File

@@ -0,0 +1,397 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
[Serializable]
public sealed class TemplateDepthModule : TemplateModuleParent
{
private const string ZWriteFormatter = "ZWrite {0}\n";
private const string ZTestFormatter = "ZTest {0}\n";
[SerializeField]
private bool m_validZTest = false;
[SerializeField]
private InlineProperty m_zTestMode = new InlineProperty( 0 );
[SerializeField]
private bool m_validZWrite = false;
[SerializeField]
private InlineProperty m_zWriteMode = new InlineProperty( 0 );
[SerializeField]
private InlineProperty m_offsetFactor = new InlineProperty( 0 );
[SerializeField]
private InlineProperty m_offsetUnits = new InlineProperty( 0 );
[SerializeField]
private bool m_offsetEnabled = false;
[SerializeField]
private bool m_validOffset = false;
public TemplateDepthModule() : base( "Depth" ) { }
public void CopyFrom( TemplateDepthModule other, bool allData )
{
if( allData )
{
m_independentModule = other.IndependentModule;
m_validZTest = other.ValidZTest;
m_validZWrite = other.ValidZWrite;
m_validOffset = other.ValidOffset;
}
m_zTestMode.CopyFrom( other.ZTestMode );
m_zWriteMode.CopyFrom( other.ZWriteMode );
m_offsetFactor.CopyFrom( other.OffsetFactor );
m_offsetUnits.CopyFrom( other.OffsetUnits );
m_offsetEnabled = other.OffsetEnabled;
}
public void ConfigureFromTemplateData( TemplateDepthData depthData )
{
m_independentModule = depthData.IndependentModule;
if( depthData.ValidZTest && m_validZTest != depthData.ValidZTest )
{
if( string.IsNullOrEmpty( depthData.ZTestInlineValue ) )
{
m_zTestMode.IntValue = ZBufferOpHelper.ZTestModeDict[ depthData.ZTestModeValue ];
m_zTestMode.ResetProperty();
}
else
{
m_zTestMode.SetInlineByName( depthData.ZTestInlineValue );
}
}
if( depthData.ValidZWrite && m_validZWrite != depthData.ValidZWrite )
{
if( string.IsNullOrEmpty( depthData.ZWriteInlineValue ) )
{
m_zWriteMode.IntValue = ZBufferOpHelper.ZWriteModeDict[ depthData.ZWriteModeValue ];
m_zWriteMode.ResetProperty();
}
else
{
m_zWriteMode.SetInlineByName( depthData.ZWriteInlineValue );
}
}
if( depthData.ValidOffset && m_validOffset != depthData.ValidOffset )
{
if( string.IsNullOrEmpty( depthData.OffsetFactorInlineValue ) )
{
m_offsetFactor.FloatValue = depthData.OffsetFactor;
m_offsetFactor.ResetProperty();
}
else
{
m_offsetFactor.SetInlineByName( depthData.OffsetFactorInlineValue );
}
if( string.IsNullOrEmpty( depthData.OffsetUnitsInlineValue ) )
{
m_offsetUnits.FloatValue = depthData.OffsetUnits;
m_offsetUnits.ResetProperty();
}
else
{
m_offsetUnits.SetInlineByName( depthData.OffsetUnitsInlineValue );
}
m_offsetEnabled = depthData.ValidOffset;
}
m_validZTest = depthData.ValidZTest;
m_validZWrite = depthData.ValidZWrite;
m_validOffset = depthData.ValidOffset;
m_validData = m_validZTest || m_validZWrite || m_validOffset;
}
public override void ShowUnreadableDataMessage( ParentNode owner )
{
bool foldoutValue = owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedDepth;
NodeUtils.DrawPropertyGroup( ref foldoutValue, ZBufferOpHelper.DepthParametersStr, base.ShowUnreadableDataMessage );
owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedDepth = foldoutValue;
}
public override void Draw( UndoParentNode owner, bool style = true )
{
bool foldout = owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedDepth;
if( style )
{
NodeUtils.DrawPropertyGroup( ref foldout, ZBufferOpHelper.DepthParametersStr, () =>
{
EditorGUI.indentLevel++;
DrawBlock( owner );
EditorGUI.indentLevel--;
} );
}
else
{
NodeUtils.DrawNestedPropertyGroup( ref foldout, ZBufferOpHelper.DepthParametersStr, () =>
{
DrawBlock( owner );
} );
}
owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedDepth = foldout;
}
void DrawBlock( UndoParentNode owner )
{
EditorGUI.BeginChangeCheck();
var cache = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = EditorGUIUtility.labelWidth - 20;
Color cachedColor = GUI.color;
GUI.color = new Color( cachedColor.r, cachedColor.g, cachedColor.b, ( EditorGUIUtility.isProSkin ? 0.5f : 0.25f ) );
//EditorGUILayout.BeginVertical( UIUtils.MenuItemBackgroundStyle );
GUI.color = cachedColor;
EditorGUILayout.Separator();
if( m_validZWrite )
m_zWriteMode.EnumTypePopup( ref owner, ZBufferOpHelper.ZWriteModeStr, ZBufferOpHelper.ZWriteModeValues );
if( m_validZTest )
m_zTestMode.EnumTypePopup( ref owner, ZBufferOpHelper.ZTestModeStr, ZBufferOpHelper.ZTestModeLabels );
if( m_validOffset )
{
m_offsetEnabled = owner.EditorGUILayoutToggle( ZBufferOpHelper.OffsetStr, m_offsetEnabled );
if( m_offsetEnabled )
{
EditorGUI.indentLevel++;
m_offsetFactor.FloatField( ref owner, ZBufferOpHelper.OffsetFactorStr );
m_offsetUnits.FloatField( ref owner, ZBufferOpHelper.OffsetUnitsStr );
EditorGUI.indentLevel--;
}
}
EditorGUILayout.Separator();
EditorGUIUtility.labelWidth = cache;
//EditorGUILayout.EndVertical();
if( EditorGUI.EndChangeCheck() )
{
m_isDirty = true;
CustomEdited = true;
}
}
public void ReadZWriteFromString( ref uint index, ref string[] nodeParams )
{
bool validDataOnMeta = m_validZWrite;
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
validDataOnMeta = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( validDataOnMeta )
{
if( UIUtils.CurrentShaderVersion() < 15304 )
{
m_zWriteMode.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
}
else
{
m_zWriteMode.ReadFromString( ref index, ref nodeParams );
}
}
}
public void ReadZTestFromString( ref uint index, ref string[] nodeParams )
{
bool validDataOnMeta = m_validZTest;
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
validDataOnMeta = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( validDataOnMeta )
{
if( UIUtils.CurrentShaderVersion() < 15304 )
{
m_zTestMode.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
}
else
{
m_zTestMode.ReadFromString( ref index, ref nodeParams );
}
}
}
public void ReadOffsetFromString( ref uint index, ref string[] nodeParams )
{
bool validDataOnMeta = m_validOffset;
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
validDataOnMeta = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( validDataOnMeta )
{
m_offsetEnabled = Convert.ToBoolean( nodeParams[ index++ ] );
if( UIUtils.CurrentShaderVersion() < 15304 )
{
m_offsetFactor.FloatValue = Convert.ToSingle( nodeParams[ index++ ] );
m_offsetUnits.FloatValue = Convert.ToSingle( nodeParams[ index++ ] );
}
else
{
m_offsetFactor.ReadFromString( ref index, ref nodeParams, false );
m_offsetUnits.ReadFromString( ref index, ref nodeParams, false );
}
}
}
public override void ReadFromString( ref uint index, ref string[] nodeParams )
{
base.ReadFromString( ref index, ref nodeParams );
ReadZWriteFromString( ref index, ref nodeParams );
ReadZTestFromString( ref index, ref nodeParams );
ReadOffsetFromString( ref index, ref nodeParams );
}
public void WriteZWriteToString( ref string nodeInfo )
{
base.WriteToString( ref nodeInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_validZWrite );
if( m_validZWrite )
m_zWriteMode.WriteToString( ref nodeInfo );
}
public void WriteZTestToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_validZTest );
if( m_validZTest )
m_zTestMode.WriteToString( ref nodeInfo );
}
public void WriteOffsetToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_validOffset );
if( m_validOffset )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_offsetEnabled );
m_offsetFactor.WriteToString( ref nodeInfo );
m_offsetUnits.WriteToString( ref nodeInfo );
}
}
public override void WriteToString( ref string nodeInfo )
{
WriteZWriteToString( ref nodeInfo );
WriteZTestToString( ref nodeInfo );
WriteOffsetToString( ref nodeInfo );
}
public bool IsActive { get { return ( m_zTestMode.IsValid || m_zTestMode.IntValue != 0 ) || ( m_zWriteMode.IsValid || m_zWriteMode.IntValue != 0 ) || m_offsetEnabled; } }
public string CurrentZWriteMode
{
get
{
if( m_zWriteMode.IsValid )
{
return string.Format( ZWriteFormatter, m_zWriteMode.GetValueOrProperty() ); ;
}
int finalZWrite = ( m_zWriteMode.IntValue == 0 ) ? 1 : m_zWriteMode.IntValue;
return string.Format( ZWriteFormatter, ZBufferOpHelper.ZWriteModeValues[ finalZWrite ] ); ;
}
}
public string CurrentZTestMode
{
get
{
if( m_zTestMode.IsValid )
return string.Format( ZTestFormatter, m_zTestMode.GetValueOrProperty() );
int finalZTestMode = ( m_zTestMode.IntValue == 0 ) ? 3 : m_zTestMode.IntValue;
return string.Format( ZTestFormatter, ZBufferOpHelper.ZTestModeValues[ finalZTestMode ] );
}
}
public string CurrentOffset
{
get
{
if( m_offsetEnabled )
return "Offset " + m_offsetFactor.GetValueOrProperty() + " , " + m_offsetUnits.GetValueOrProperty() + "\n";
else
return "Offset 0,0\n";
}
}
public bool ValidZTest { get { return m_validZTest; } }
public bool ValidZWrite { get { return m_validZWrite; } }
public bool ValidOffset { get { return m_validOffset; } }
public InlineProperty ZTestMode { get { return m_zTestMode; } }
public InlineProperty ZWriteMode { get { return m_zWriteMode; } }
public InlineProperty OffsetFactor { get { return m_offsetFactor; } }
public InlineProperty OffsetUnits { get { return m_offsetUnits; } }
public bool OffsetEnabled { get { return m_offsetEnabled; } }
public ZTestMode ZTestModeValue
{
set
{
m_zTestMode.IntValue = ZBufferOpHelper.ZTestModeDict[ value ];
m_zTestMode.Active = false;
}
get
{
return (ZTestMode)( m_zTestMode.IntValue - 1 );
}
}
public ZWriteMode ZWriteModeValue
{
set
{
m_zWriteMode.IntValue = ZBufferOpHelper.ZWriteModeDict[ value ];
m_zWriteMode.Active = false;
}
get
{
return (ZWriteMode)( m_zWriteMode.IntValue - 1 );
}
}
public float OffsetFactorValue
{
set
{
m_offsetEnabled = true;
m_offsetFactor.FloatValue = value;
m_offsetFactor.Active = false;
}
get
{
return m_offsetFactor.FloatValue;
}
}
public float OffsetUnitsValue
{
set
{
m_offsetEnabled = true;
m_offsetUnits.FloatValue = value;
m_offsetUnits.Active = false;
}
get
{
return m_offsetUnits.FloatValue;
}
}
}
}

View File

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

View File

@@ -0,0 +1,280 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Template Fragment Data", "Surface Data", "Select and use available interpolated fragment data from the template" )]
public class TemplateFragmentDataNode : TemplateNodeParent
{
private List<TemplateVertexData> m_interpolatorData = null;
[SerializeField]
private int m_currentDataIdx = -1;
[SerializeField]
private string m_dataName = string.Empty;
[SerializeField]
private string m_inVarName = string.Empty;
private string[] m_dataLabels = null;
private bool m_fetchDataId = false;
private UpperLeftWidgetHelper m_upperLeftWidgetHelper = new UpperLeftWidgetHelper();
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_autoWrapProperties = true;
}
void FetchDataId()
{
if( m_interpolatorData != null )
{
m_currentDataIdx = 0;
int count = m_interpolatorData.Count;
m_dataLabels = new string[ count ];
for( int i = 0; i < count; i++ )
{
m_dataLabels[ i ] = m_interpolatorData[ i ].VarName;
if( m_interpolatorData[ i ].VarName.Equals( m_dataName ) )
{
m_currentDataIdx = i;
}
}
UpdateFromId();
}
else
{
m_currentDataIdx = -1;
}
}
void UpdateFromId()
{
if( m_interpolatorData != null )
{
if( m_interpolatorData.Count == 0 )
{
for( int i = 0; i < 4; i++ )
m_containerGraph.DeleteConnection( false, UniqueId, i, false, true );
m_headerColor = UIUtils.GetColorFromCategory( "Default" );
m_content.text = "None";
m_additionalContent.text = string.Empty;
m_outputPorts[ 0 ].ChangeProperties( "None", WirePortDataType.OBJECT, false );
ConfigurePorts();
return;
}
bool areCompatible = TemplateHelperFunctions.CheckIfCompatibles( m_outputPorts[ 0 ].DataType, m_interpolatorData[ m_currentDataIdx ].DataType );
switch( m_interpolatorData[ m_currentDataIdx ].DataType )
{
default:
case WirePortDataType.INT:
case WirePortDataType.FLOAT:
m_outputPorts[ 0 ].ChangeProperties( Constants.EmptyPortValue, m_interpolatorData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.FLOAT2:
m_outputPorts[ 0 ].ChangeProperties( "XY", m_interpolatorData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.FLOAT3:
m_outputPorts[ 0 ].ChangeProperties( "XYZ", m_interpolatorData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.FLOAT4:
m_outputPorts[ 0 ].ChangeProperties( "XYZW", m_interpolatorData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.COLOR:
m_outputPorts[ 0 ].ChangeProperties( "RGBA", m_interpolatorData[ m_currentDataIdx ].DataType, false );
break;
}
ConfigurePorts();
if( !areCompatible )
{
m_containerGraph.DeleteConnection( false, UniqueId, 0, false, true );
}
m_dataName = m_interpolatorData[ m_currentDataIdx ].VarName;
m_content.text = m_dataName;
m_sizeIsDirty = true;
CheckWarningState();
}
}
public override void DrawProperties()
{
base.DrawProperties();
if( m_multiPassMode )
{
DrawMultipassProperties();
}
if( m_currentDataIdx > -1 )
{
EditorGUI.BeginChangeCheck();
m_currentDataIdx = EditorGUILayoutPopup( DataLabelStr, m_currentDataIdx, m_dataLabels );
if( EditorGUI.EndChangeCheck() )
{
UpdateFromId();
}
}
}
protected override void OnSubShaderChange()
{
base.OnSubShaderChange();
FetchInterpolator();
FetchDataId();
}
protected override void OnPassChange()
{
FetchInterpolator();
FetchDataId();
}
void DrawMultipassProperties()
{
DrawSubShaderUI();
DrawPassUI();
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if( m_containerGraph.CurrentCanvasMode != NodeAvailability.TemplateShader )
return;
if( m_interpolatorData == null || m_interpolatorData.Count == 0 )
{
MasterNode masterNode = m_containerGraph.CurrentMasterNode;
FetchInterpolator( masterNode );
}
if( m_fetchDataId )
{
m_fetchDataId = false;
FetchDataId();
}
if( m_currentDataIdx > -1 )
{
EditorGUI.BeginChangeCheck();
m_currentDataIdx = m_upperLeftWidgetHelper.DrawWidget( this, m_currentDataIdx, m_dataLabels );
if( EditorGUI.EndChangeCheck() )
{
UpdateFromId();
}
}
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if( dataCollector.MasterNodeCategory != AvailableShaderTypes.Template )
{
UIUtils.ShowMessage( UniqueId, "Template Fragmment Data node is only intended for templates use only" );
return m_outputPorts[ 0 ].ErrorValue;
}
if( !dataCollector.IsFragmentCategory )
{
UIUtils.ShowMessage( UniqueId, "Template Fragment Data node node is only intended for fragment use use only" );
return m_outputPorts[ 0 ].ErrorValue;
}
if( m_multiPassMode )
{
if( dataCollector.TemplateDataCollectorInstance.MultipassSubshaderIdx != SubShaderIdx ||
dataCollector.TemplateDataCollectorInstance.MultipassPassIdx != PassIdx
)
{
UIUtils.ShowMessage( UniqueId, string.Format( "{0} is only intended for subshader {1} and pass {2}", m_dataLabels[ m_currentDataIdx ], SubShaderIdx, PassIdx ) );
return m_outputPorts[ outputId ].ErrorValue;
}
}
return GetOutputVectorItem( 0, outputId, m_inVarName + m_dataName );
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
m_dataName = GetCurrentParam( ref nodeParams );
m_fetchDataId = true;
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_dataName );
}
public override void OnMasterNodeReplaced( MasterNode newMasterNode )
{
base.OnMasterNodeReplaced( newMasterNode );
if( newMasterNode.CurrentMasterNodeCategory == AvailableShaderTypes.Template )
{
FetchInterpolator( newMasterNode );
}
else
{
m_interpolatorData = null;
m_currentDataIdx = -1;
}
}
protected override bool ValidatePass( int passIdx )
{
return ( m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ passIdx ].FragmentFunctionData != null &&
m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ passIdx ].InterpolatorDataContainer != null );
}
void FetchInterpolator( MasterNode masterNode = null )
{
FetchMultiPassTemplate( masterNode );
if( m_multiPassMode )
{
if( m_templateMPData != null )
{
m_inVarName = m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ PassIdx ].FragmentFunctionData.InVarName + ".";
m_interpolatorData = m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ PassIdx ].InterpolatorDataContainer.RawInterpolators;
m_fetchDataId = true;
}
}
else
{
if( masterNode == null )
masterNode = m_containerGraph.CurrentMasterNode;
TemplateData currentTemplate = ( masterNode as TemplateMasterNode ).CurrentTemplate;
if( currentTemplate != null )
{
m_inVarName = currentTemplate.FragmentFunctionData.InVarName + ".";
m_interpolatorData = currentTemplate.InterpolatorData.RawInterpolators;
FetchDataId();
}
else
{
m_interpolatorData = null;
m_currentDataIdx = -1;
}
}
}
public override void Destroy()
{
base.Destroy();
m_dataLabels = null;
m_interpolatorData = null;
m_upperLeftWidgetHelper = null;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 2b53cc116abb0df45b028f41b8f0305e
timeCreated: 1506595629
licenseType: Store
MonoImporter:
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,12 @@
fileFormatVersion: 2
guid: 517aad6764d713946bc566f0a83cd44d
timeCreated: 1495548641
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,236 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using UnityEngine;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplatePassId
{
public string PassId;
public bool RemoveFromShader;
}
[Serializable]
public class TemplateTag
{
public string Tag = string.Empty;
public string Replacement = string.Empty;
public string Output = string.Empty;
public TemplateTag( string tag, string replacement = null )
{
Tag = tag;
if( replacement != null )
{
Replacement = replacement;
Output = replacement;
}
}
}
[Serializable]
public class TemplateId
{
public int StartIdx = -1;
public string UniqueID;
public string Tag;
public string ReplacementText;
public bool IsReplaced = false;
public bool EmptyReplacer = false;
public TemplateId( int bodyIdx, string uniqueID, string tag, bool emptyReplacer = false )
{
StartIdx = bodyIdx;
UniqueID = uniqueID;
Tag = tag;
EmptyReplacer = emptyReplacer;
ReplacementText = emptyReplacer ? string.Empty : tag;
}
public void SetReplacementText( string replacementText )
{
ReplacementText = replacementText;
IsReplaced = true;
}
public void Reset()
{
ReplacementText = EmptyReplacer?string.Empty:Tag;
IsReplaced = false;
}
}
[Serializable]
public class TemplateIdManager
{
[SerializeField]
private bool m_isSorted = false;
[SerializeField]
private string m_shaderBody;
[SerializeField]
private List<TemplateId> m_registeredIds = new List<TemplateId>();
[SerializeField]
private List<TemplateTag> m_registeredTags = new List<TemplateTag>();
[SerializeField]
private List<TemplatePassId> m_registeredPassIds = new List<TemplatePassId>();
private Dictionary<string, TemplateId> m_registeredIdsDict = new Dictionary<string, TemplateId>();
public TemplateIdManager( string shaderBody )
{
m_shaderBody = shaderBody;
}
public void Destroy()
{
m_registeredPassIds.Clear();
m_registeredPassIds = null;
m_registeredTags.Clear();
m_registeredTags = null;
m_registeredIds.Clear();
m_registeredIds = null;
if( m_registeredIdsDict != null )
{
m_registeredIdsDict.Clear();
m_registeredIdsDict = null;
}
}
void RefreshIds()
{
if( m_registeredIdsDict == null )
{
m_registeredIdsDict = new Dictionary<string, TemplateId>();
}
if( m_registeredIdsDict.Count != m_registeredIds.Count )
{
m_registeredIdsDict.Clear();
int count = m_registeredIds.Count;
for( int i = 0; i < count; i++ )
{
m_registeredIdsDict.Add( m_registeredIds[ i ].UniqueID, m_registeredIds[ i ] );
}
}
}
public void RegisterId( int bodyIdx, string uniqueID, string tag, bool emptyReplacer = false )
{
if( bodyIdx < 0 )
return;
RefreshIds();
TemplateId templateId = new TemplateId( bodyIdx, uniqueID, tag, emptyReplacer );
m_registeredIds.Add( templateId );
m_registeredIdsDict.Add( uniqueID, templateId );
}
public void RegisterTag( string tag, string replacement = null )
{
m_registeredTags.Add( new TemplateTag( tag, replacement ) );
}
public void RegisterPassId( string passId )
{
m_registeredPassIds.Add( new TemplatePassId() { PassId = passId, RemoveFromShader = false } );
}
public void SetPassIdUsage( int idx , bool removeFromShader )
{
m_registeredPassIds[ idx ].RemoveFromShader = removeFromShader;
}
public void SetReplacementText( string uniqueId, string replacementText )
{
RefreshIds();
if( m_registeredIdsDict.ContainsKey( uniqueId ) && m_registeredIdsDict[ uniqueId ].StartIdx >= 0 )
m_registeredIdsDict[ uniqueId ].SetReplacementText( replacementText );
}
public string BuildShader()
{
if( !m_isSorted )
{
m_registeredIds.Sort( ( x, y ) => { return x.StartIdx.CompareTo( y.StartIdx ); } );
}
int idCount = m_registeredIds.Count;
int offset = 0;
string finalShaderBody = m_shaderBody;
for( int i = 0; i < idCount; i++ )
{
if( m_registeredIds[ i ].StartIdx >= 0 && m_registeredIds[ i ].IsReplaced )
{
finalShaderBody = finalShaderBody.ReplaceAt( m_registeredIds[ i ].Tag, m_registeredIds[ i ].ReplacementText, offset + m_registeredIds[ i ].StartIdx );
offset += ( m_registeredIds[ i ].ReplacementText.Length - m_registeredIds[ i ].Tag.Length );
}
}
int count = m_registeredPassIds.Count;
for( int i = 0; i < count; i++ )
{
if( m_registeredPassIds[ i ].RemoveFromShader )
finalShaderBody = finalShaderBody.Replace( m_registeredPassIds[ i ].PassId, string.Empty );
}
for( int i = 0; i < idCount; i++ )
{
if( !m_registeredIds[ i ].IsReplaced && !m_registeredIds[ i ].Tag.Equals( m_registeredIds[ i ].ReplacementText ) )
{
finalShaderBody = finalShaderBody.Replace( m_registeredIds[ i ].Tag, m_registeredIds[ i ].ReplacementText );
}
}
count = m_registeredTags.Count;
for( int i = 0; i < count; i++ )
{
finalShaderBody = finalShaderBody.Replace( m_registeredTags[ i ].Tag, m_registeredTags[ i ].Replacement );
m_registeredTags[ i ].Replacement = m_registeredTags[ i ].Output;
}
//finalShaderBody = finalShaderBody.Replace( TemplatesManager.TemplateExcludeFromGraphTag, string.Empty );
//finalShaderBody = finalShaderBody.Replace( TemplatesManager.TemplateMainPassTag, string.Empty );
return finalShaderBody;
}
public void ResetRegistersState()
{
int count = m_registeredIds.Count;
for( int i = 0; i < count; i++ )
{
m_registeredIds[ i ].Reset();
}
}
public void Reset()
{
m_registeredIds.Clear();
if( m_registeredIdsDict == null )
{
m_registeredIdsDict = new Dictionary<string, TemplateId>();
}
else
{
m_registeredIdsDict.Clear();
}
}
public string ShaderBody
{
get { return m_shaderBody; }
set { m_shaderBody = value; }
}
public List<TemplateTag> RegisteredTags { get { return m_registeredTags; } set { m_registeredTags = value; } }
}
}

View File

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

View File

@@ -0,0 +1,239 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using UnityEngine;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateInterpElement
{
public TemplateSemantics Semantic;
public bool[] AvailableChannels = { true, true, true, true };
public bool IsFull = false;
public int Usage = 0;
public string Name;
//https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-struct
public bool NoInterpolation;
public bool Sample;
public TemplateInterpElement( TemplateInterpElement other )
{
Semantic = other.Semantic;
for ( int i = 0; i < AvailableChannels.Length; i++ )
{
AvailableChannels[ i ] = other.AvailableChannels[ i ];
}
IsFull = other.IsFull;
Usage = other.Usage;
Name = other.Name;
NoInterpolation = other.NoInterpolation;
Sample = other.Sample;
}
public TemplateInterpElement( TemplateSemantics semantic )
{
Semantic = semantic;
int semanticId = TemplateHelperFunctions.SemanticToInt[ Semantic ];
Name = ( semanticId == 0 ) ? TemplateHelperFunctions.BaseInterpolatorName : TemplateHelperFunctions.BaseInterpolatorName + semanticId.ToString();
}
public void SetAvailableChannelsFromString( string channels )
{
for ( int i = 0; i < AvailableChannels.Length; i++ )
{
AvailableChannels[ i ] = false;
}
Usage = AvailableChannels.Length;
for ( int i = 0; i < channels.Length; i++ )
{
switch ( channels[ i ] )
{
case 'x': if ( !AvailableChannels[ 0 ] ) { AvailableChannels[ 0 ] = true; Usage--; } break;
case 'y': if ( !AvailableChannels[ 1 ] ) { AvailableChannels[ 1 ] = true; Usage--; } break;
case 'z': if ( !AvailableChannels[ 2 ] ) { AvailableChannels[ 2 ] = true; Usage--; } break;
case 'w': if ( !AvailableChannels[ 3 ] ) { AvailableChannels[ 3 ] = true; Usage--; } break;
}
}
}
public TemplateVertexData RequestChannels( WirePortDataType type, bool isColor, string customName = null )
{
if ( IsFull )
return null;
int channelsRequired = TemplateHelperFunctions.DataTypeChannelUsage[ type ];
if ( channelsRequired == 0 )
return null;
int firstChannel = -1;
for ( int i = 0; i < AvailableChannels.Length; i++ )
{
if ( AvailableChannels[ i ] )
{
if ( firstChannel < 0 )
{
firstChannel = i;
}
channelsRequired -= 1;
if ( channelsRequired == 0 )
break;
}
}
//did not found enough channels to fill request
if ( channelsRequired > 0 )
return null;
if( Usage == 0 && customName != null )
{
Name = customName;
}
Usage += 1;
TemplateVertexData data = null;
if ( type == WirePortDataType.COLOR || type == WirePortDataType.FLOAT4 )
{
// Automatically lock all channels
for ( int i = firstChannel; i < ( firstChannel + channelsRequired ); i++ )
{
AvailableChannels[ i ] = false;
}
IsFull = true;
data = new TemplateVertexData( Semantic, type, Name );
}
else
{
string[] swizzleArray = ( isColor ) ? TemplateHelperFunctions.ColorSwizzle : TemplateHelperFunctions.VectorSwizzle;
string channels = ".";
int count = firstChannel + TemplateHelperFunctions.DataTypeChannelUsage[ type ];
for ( int i = firstChannel; i < count; i++ )
{
AvailableChannels[ i ] = false;
channels += swizzleArray[ i ];
if ( i == ( AvailableChannels.Length - 1 ) )
{
IsFull = true;
}
}
data = new TemplateVertexData( Semantic, type, Name, channels );
}
return data;
}
}
[Serializable]
public class TemplateInterpData
{
[SerializeField]
private string m_interpDataId = string.Empty;
[SerializeField]
private int m_interpDataStartIdx = -1;
[SerializeField]
private bool m_dynamicMax = false;
public List<TemplateInterpElement> AvailableInterpolators = new List<TemplateInterpElement>();
public List<TemplateVertexData> Interpolators = new List<TemplateVertexData>();
public List<TemplateVertexData> RawInterpolators = new List<TemplateVertexData>();
public TemplateInterpData() { }
public bool HasRawInterpolatorOfName( string name )
{
return RawInterpolators.Exists( ( x ) => x.VarName.Equals( name ));
}
public TemplateInterpData( TemplateInterpData other )
{
m_dynamicMax = other.DynamicMax;
foreach ( TemplateInterpElement data in other.AvailableInterpolators )
{
AvailableInterpolators.Add( new TemplateInterpElement( data ) );
}
for ( int i = 0; i < other.Interpolators.Count; i++ )
{
Interpolators.Add( new TemplateVertexData( other.Interpolators[ i ] ) );
}
for( int i = 0; i < other.RawInterpolators.Count; i++ )
{
RawInterpolators.Add( new TemplateVertexData( other.RawInterpolators[ i ] ) );
}
}
public void RecalculateAvailableInterpolators( int newMax )
{
if( m_dynamicMax )
{
if( !TemplateHelperFunctions.IntToSemantic.ContainsKey( ( newMax - 1 ) ) )
{
Debug.LogWarning( "Attempting to add inexisting available interpolators" );
return;
}
if( AvailableInterpolators.Count > 0 )
{
int currMax = 1 + TemplateHelperFunctions.SemanticToInt[ AvailableInterpolators[ AvailableInterpolators.Count - 1 ].Semantic ];
if( newMax > currMax )
{
int count = newMax - currMax;
for( int i = 0; i < count; i++ )
{
AvailableInterpolators.Add( new TemplateInterpElement( TemplateHelperFunctions.IntToSemantic[ currMax + i ] ));
}
}
else if( newMax < currMax )
{
int min = TemplateHelperFunctions.SemanticToInt[ AvailableInterpolators[ 0 ].Semantic ];
if( newMax > min )
{
int count = currMax - newMax;
for( int i = 0; i < count; i++ )
{
AvailableInterpolators.RemoveAt( AvailableInterpolators.Count - 1 );
}
}
}
}
}
}
public void ReplaceNameOnInterpolator( TemplateSemantics semantic, string newName )
{
for ( int i = 0; i < AvailableInterpolators.Count; i++ )
{
if ( AvailableInterpolators[ i ].Semantic == semantic )
{
AvailableInterpolators[ i ].Name = newName;
break;
}
}
}
public void Destroy()
{
AvailableInterpolators.Clear();
AvailableInterpolators = null;
Interpolators.Clear();
Interpolators = null;
RawInterpolators.Clear();
RawInterpolators = null;
}
public string InterpDataId { get { return m_interpDataId; } set { m_interpDataId = value; } }
public int InterpDataStartIdx { get { return m_interpDataStartIdx; } set { m_interpDataStartIdx = value; } }
public bool DynamicMax { get { return m_dynamicMax; } set { m_dynamicMax = value; } }
}
}

View File

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

View File

@@ -0,0 +1,59 @@
using System;
using UnityEngine;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateLocalVarData
{
[SerializeField]
private WirePortDataType m_dataType = WirePortDataType.OBJECT;
[SerializeField]
private string m_localVarName = string.Empty;
[SerializeField]
private int m_position = -1;
[SerializeField]
private bool m_isSpecialVar = false;
[SerializeField]
private TemplateInfoOnSematics m_specialVarType;
[SerializeField]
private MasterNodePortCategory m_category;
[SerializeField]
private string m_id;
public TemplateLocalVarData( WirePortDataType dataType, MasterNodePortCategory category, string localVarName, int position )
{
m_dataType = dataType;
m_localVarName = localVarName;
m_position = position;
m_category = category;
//Debug.Log( m_localVarName + " " + m_inputData.PortCategory + " " + m_inputData.PortName );
}
public TemplateLocalVarData( TemplateInfoOnSematics specialVarType,string id, WirePortDataType dataType, MasterNodePortCategory category, string localVarName, int position )
{
m_id = id;
m_dataType = dataType;
m_localVarName = localVarName;
m_position = position;
m_specialVarType = specialVarType;
m_isSpecialVar = true;
m_category = category;
//Debug.Log( m_localVarName + " " + m_inputData.PortCategory + " " + m_inputData.PortName );
}
public WirePortDataType DataType { get { return m_dataType; } }
public string LocalVarName { get { return m_localVarName; } }
public int Position { get { return m_position; } }
public bool IsSpecialVar { get { return m_isSpecialVar; } }
public TemplateInfoOnSematics SpecialVarType{ get { return m_specialVarType; } }
public MasterNodePortCategory Category { get { return m_category; } }
public string Id { get { return m_id; } }
}
}

View File

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

View File

@@ -0,0 +1,264 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Template Local Var Data", "Surface Data", "Select and use available local variable data from the template" )]
public sealed class TemplateLocalVarsNode : TemplateNodeParent
{
private List<TemplateLocalVarData> m_localVarsData = null;
[SerializeField]
private int m_currentDataIdx = -1;
[SerializeField]
private string m_dataName = string.Empty;
private string[] m_dataLabels = null;
private bool m_fetchDataId = false;
private UpperLeftWidgetHelper m_upperLeftWidgetHelper = new UpperLeftWidgetHelper();
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_autoWrapProperties = true;
}
void FetchDataId()
{
if( m_localVarsData != null && m_localVarsData.Count > 0 )
{
m_currentDataIdx = 0;
int count = m_localVarsData.Count;
m_dataLabels = new string[ count ];
for( int i = 0; i < count; i++ )
{
m_dataLabels[ i ] = m_localVarsData[ i ].LocalVarName;
if( m_localVarsData[ i ].LocalVarName.Equals( m_dataName ) )
{
m_currentDataIdx = i;
}
}
UpdateFromId();
}
else
{
m_currentDataIdx = -1;
}
}
void UpdateFromId()
{
if( m_localVarsData != null )
{
if( m_localVarsData.Count == 0 )
{
for( int i = 0; i < 4; i++ )
m_containerGraph.DeleteConnection( false, UniqueId, i, false, true );
m_headerColor = UIUtils.GetColorFromCategory( "Default" );
m_content.text = "None";
m_additionalContent.text = string.Empty;
m_outputPorts[ 0 ].ChangeProperties( "None", WirePortDataType.OBJECT, false );
ConfigurePorts();
return;
}
bool areCompatible = TemplateHelperFunctions.CheckIfCompatibles( m_outputPorts[ 0 ].DataType, m_localVarsData[ m_currentDataIdx ].DataType );
string category = m_localVarsData[ m_currentDataIdx ].Category == MasterNodePortCategory.Fragment ? "Surface Data" : "Vertex Data";
m_headerColor = UIUtils.GetColorFromCategory( category );
switch( m_localVarsData[ m_currentDataIdx ].DataType )
{
default:
case WirePortDataType.INT:
case WirePortDataType.FLOAT:
m_outputPorts[ 0 ].ChangeProperties( Constants.EmptyPortValue, m_localVarsData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.FLOAT2:
m_outputPorts[ 0 ].ChangeProperties( "XY", m_localVarsData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.FLOAT3:
m_outputPorts[ 0 ].ChangeProperties( "XYZ", m_localVarsData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.FLOAT4:
m_outputPorts[ 0 ].ChangeProperties( "XYZW", m_localVarsData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.COLOR:
m_outputPorts[ 0 ].ChangeProperties( "RGBA", m_localVarsData[ m_currentDataIdx ].DataType, false );
break;
}
ConfigurePorts();
if( !areCompatible )
{
m_containerGraph.DeleteConnection( false, UniqueId, 0, false, true );
}
m_dataName = m_localVarsData[ m_currentDataIdx ].LocalVarName;
m_content.text = m_dataName;
m_sizeIsDirty = true;
CheckWarningState();
}
}
public override void DrawProperties()
{
base.DrawProperties();
if( m_multiPassMode )
{
DrawMultipassProperties();
}
if( m_currentDataIdx > -1 )
{
EditorGUI.BeginChangeCheck();
m_currentDataIdx = EditorGUILayoutPopup( DataLabelStr, m_currentDataIdx, m_dataLabels );
if( EditorGUI.EndChangeCheck() )
{
UpdateFromId();
}
}
}
protected override void OnSubShaderChange()
{
FetchLocalVarData();
FetchDataId();
}
protected override void OnPassChange()
{
base.OnPassChange();
FetchLocalVarData();
FetchDataId();
}
void DrawMultipassProperties()
{
DrawSubShaderUI();
DrawPassUI();
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if( m_containerGraph.CurrentCanvasMode != NodeAvailability.TemplateShader )
return;
if( m_localVarsData == null || m_localVarsData.Count == 0 )
{
MasterNode masterNode = m_containerGraph.CurrentMasterNode;
if( masterNode.CurrentMasterNodeCategory == AvailableShaderTypes.Template )
{
FetchLocalVarData( masterNode );
}
}
if( m_fetchDataId )
{
m_fetchDataId = false;
FetchDataId();
}
if( m_currentDataIdx > -1 )
{
EditorGUI.BeginChangeCheck();
m_currentDataIdx = m_upperLeftWidgetHelper.DrawWidget( this, m_currentDataIdx, m_dataLabels );
if( EditorGUI.EndChangeCheck() )
{
UpdateFromId();
}
}
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if( m_localVarsData[ m_currentDataIdx ].Category != dataCollector.PortCategory )
{
UIUtils.ShowMessage( UniqueId, string.Format( "Local Var {0} can only work on ports of type {1}", m_localVarsData[ m_currentDataIdx ].LocalVarName, m_localVarsData[ m_currentDataIdx ].Category ) );
return m_outputPorts[ 0 ].ErrorValue;
}
if( m_multiPassMode )
{
if( dataCollector.TemplateDataCollectorInstance.MultipassSubshaderIdx != SubShaderIdx ||
dataCollector.TemplateDataCollectorInstance.MultipassPassIdx != PassIdx
)
{
UIUtils.ShowMessage( UniqueId, string.Format( "{0} is only intended for subshader {1} and pass {2}", m_dataLabels[ m_currentDataIdx ], SubShaderIdx, PassIdx ) );
return m_outputPorts[ outputId ].ErrorValue;
}
}
return GetOutputVectorItem( 0, outputId, m_dataName );
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
m_dataName = GetCurrentParam( ref nodeParams );
m_fetchDataId = true;
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_dataName );
}
public override void OnMasterNodeReplaced( MasterNode newMasterNode )
{
base.OnMasterNodeReplaced( newMasterNode );
if( newMasterNode.CurrentMasterNodeCategory == AvailableShaderTypes.Template )
{
FetchLocalVarData( newMasterNode );
}
else
{
m_localVarsData = null;
m_currentDataIdx = -1;
}
}
void FetchLocalVarData( MasterNode masterNode = null )
{
FetchMultiPassTemplate( masterNode );
if( m_multiPassMode )
{
if( m_templateMPData != null )
{
m_localVarsData = m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ PassIdx ].LocalVarsList;
m_fetchDataId = true;
}
}
else
{
TemplateData currentTemplate = ( masterNode as TemplateMasterNode ).CurrentTemplate;
if( currentTemplate != null )
{
m_localVarsData = currentTemplate.LocalVarsList;
m_fetchDataId = true;
}
else
{
m_localVarsData = null;
m_currentDataIdx = -1;
}
}
}
public override void Destroy()
{
base.Destroy();
m_dataLabels = null;
m_localVarsData = null;
m_upperLeftWidgetHelper = null;
}
}
}

View File

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

View File

@@ -0,0 +1,770 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
// THIS FILE IS DEPRECATED AND SHOULD NOT BE USED
#define SHOW_TEMPLATE_HELP_BOX
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Template Master Node", "Master", "Shader Generated according to template rules", null, KeyCode.None, false, true, "Template MultiPass Master Node", typeof( TemplateMultiPassMasterNode ) )]
public sealed class TemplateMasterNode : MasterNode
{
private const string WarningMessage = "Templates is a feature that is still heavily under development and users may experience some problems.\nPlease email support@amplify.pt if any issue occurs.";
private const string CurrentTemplateLabel = "Current Template";
private const string OpenTemplateStr = "Edit Template";
//protected const string SnippetsFoldoutStr = " Snippets";
//[SerializeField]
//private bool m_snippetsFoldout = true;
[NonSerialized]
private TemplateData m_currentTemplate = null;
private bool m_fireTemplateChange = false;
private bool m_fetchMasterNodeCategory = false;
private bool m_reRegisterTemplateData = false;
[SerializeField]
private string m_templateGUID = string.Empty;
[SerializeField]
private string m_templateName = string.Empty;
[SerializeField]
private TemplatesBlendModule m_blendOpHelper = new TemplatesBlendModule();
[SerializeField]
private TemplateAlphaToMaskModule m_alphaToMaskHelper = new TemplateAlphaToMaskModule();
[SerializeField]
private TemplateCullModeModule m_cullModeHelper = new TemplateCullModeModule();
[SerializeField]
private TemplateColorMaskModule m_colorMaskHelper = new TemplateColorMaskModule();
[SerializeField]
private TemplatesStencilBufferModule m_stencilBufferHelper = new TemplatesStencilBufferModule();
[SerializeField]
private TemplateDepthModule m_depthOphelper = new TemplateDepthModule();
[SerializeField]
private TemplateTagsModule m_tagsHelper = new TemplateTagsModule();
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_masterNodeCategory = 1;// First Template
m_marginPreviewLeft = 20;
m_insideSize.y = 60;
m_customPrecision = true;
}
public override void ReleaseResources()
{
if( m_currentTemplate != null && m_currentTemplate.AvailableShaderProperties != null )
{
// Unregister old template properties
int oldPropertyCount = m_currentTemplate.AvailableShaderProperties.Count;
for( int i = 0; i < oldPropertyCount; i++ )
{
UIUtils.ReleaseUniformName( UniqueId, m_currentTemplate.AvailableShaderProperties[ i ].PropertyName );
}
}
}
public override void OnEnable()
{
base.OnEnable();
m_reRegisterTemplateData = true;
}
void FetchInfoFromTemplate()
{
if( m_currentTemplate.BlendData.DataCheck == TemplateDataCheck.Valid )
m_blendOpHelper.ConfigureFromTemplateData( m_currentTemplate.BlendData );
if( m_currentTemplate.AlphaToMaskData.DataCheck == TemplateDataCheck.Valid )
m_alphaToMaskHelper.ConfigureFromTemplateData( m_currentTemplate.AlphaToMaskData );
if( m_currentTemplate.CullModeData.DataCheck == TemplateDataCheck.Valid )
m_cullModeHelper.ConfigureFromTemplateData( m_currentTemplate.CullModeData );
if( m_currentTemplate.ColorMaskData.DataCheck == TemplateDataCheck.Valid )
m_colorMaskHelper.ConfigureFromTemplateData( m_currentTemplate.ColorMaskData );
if( m_currentTemplate.StencilData.DataCheck == TemplateDataCheck.Valid )
m_stencilBufferHelper.ConfigureFromTemplateData( m_currentTemplate.StencilData );
if( m_currentTemplate.DepthData.DataCheck == TemplateDataCheck.Valid )
m_depthOphelper.ConfigureFromTemplateData( m_currentTemplate.DepthData );
if( m_currentTemplate.TagData.DataCheck == TemplateDataCheck.Valid )
m_tagsHelper.ConfigureFromTemplateData( m_currentTemplate.TagData );
}
void FetchCurrentTemplate()
{
m_currentTemplate = m_containerGraph.ParentWindow.TemplatesManagerInstance.GetTemplate( m_templateGUID ) as TemplateData;
if( m_currentTemplate == null )
{
m_currentTemplate = m_containerGraph.ParentWindow.TemplatesManagerInstance.GetTemplate( m_templateName ) as TemplateData;
}
if( m_currentTemplate != null )
{
if( m_inputPorts.Count != m_currentTemplate.InputDataList.Count )
{
DeleteAllInputConnections( true );
List<TemplateInputData> inputDataList = m_currentTemplate.InputDataList;
int count = inputDataList.Count;
for( int i = 0; i < count; i++ )
{
AddInputPort( inputDataList[ i ].DataType, false, inputDataList[ i ].PortName, inputDataList[ i ].OrderId, inputDataList[ i ].PortCategory, inputDataList[ i ].PortUniqueId );
}
FetchInfoFromTemplate();
}
else
{
List<TemplateInputData> inputDataList = m_currentTemplate.InputDataList;
int count = inputDataList.Count;
for( int i = 0; i < count; i++ )
{
m_inputPorts[ i ].ChangeProperties( inputDataList[ i ].PortName, inputDataList[ i ].DataType, false );
}
}
}
}
public override void RefreshAvailableCategories()
{
FetchCurrentTemplate();
int templateCount = m_containerGraph.ParentWindow.TemplatesManagerInstance.TemplateCount;
m_availableCategories = new MasterNodeCategoriesData[ templateCount + 1 ];
m_availableCategoryLabels = new GUIContent[ templateCount + 1 ];
m_availableCategories[ 0 ] = new MasterNodeCategoriesData( AvailableShaderTypes.SurfaceShader, string.Empty );
m_availableCategoryLabels[ 0 ] = new GUIContent( "Surface" );
if( m_currentTemplate == null )
{
m_masterNodeCategory = -1;
}
for( int i = 0; i < templateCount; i++ )
{
int idx = i + 1;
TemplateData templateData = m_containerGraph.ParentWindow.TemplatesManagerInstance.GetTemplate( i ) as TemplateData;
if( m_currentTemplate != null && m_currentTemplate.GUID.Equals( templateData.GUID ) )
m_masterNodeCategory = idx;
m_availableCategories[ idx ] = new MasterNodeCategoriesData( AvailableShaderTypes.Template, templateData.GUID );
m_availableCategoryLabels[ idx ] = new GUIContent( templateData.Name );
}
}
void SetCategoryIdxFromTemplate()
{
int templateCount = m_containerGraph.ParentWindow.TemplatesManagerInstance.TemplateCount;
for( int i = 0; i < templateCount; i++ )
{
int idx = i + 1;
TemplateData templateData = m_containerGraph.ParentWindow.TemplatesManagerInstance.GetTemplate( i ) as TemplateData;
if( templateData != null && m_currentTemplate != null && m_currentTemplate.GUID.Equals( templateData.GUID ) )
m_masterNodeCategory = idx;
}
}
public void SetTemplate( TemplateData newTemplate, bool writeDefaultData, bool fetchMasterNodeCategory )
{
ReleaseResources();
if( newTemplate == null || newTemplate.InputDataList == null )
return;
m_fetchMasterNodeCategory = fetchMasterNodeCategory;
DeleteAllInputConnections( true );
m_currentTemplate = newTemplate;
m_currentShaderData = newTemplate.Name;
List<TemplateInputData> inputDataList = newTemplate.InputDataList;
int count = inputDataList.Count;
for( int i = 0; i < count; i++ )
{
AddInputPort( inputDataList[ i ].DataType, false, inputDataList[ i ].PortName, inputDataList[ i ].OrderId, inputDataList[ i ].PortCategory, inputDataList[ i ].PortUniqueId );
}
if( writeDefaultData )
{
ShaderName = newTemplate.DefaultShaderName;
}
RegisterProperties();
m_fireTemplateChange = true;
m_templateGUID = newTemplate.GUID;
m_templateName = newTemplate.DefaultShaderName;
FetchInfoFromTemplate();
}
void RegisterProperties()
{
if( m_currentTemplate != null )
{
m_reRegisterTemplateData = false;
// Register old template properties
int newPropertyCount = m_currentTemplate.AvailableShaderProperties.Count;
for( int i = 0; i < newPropertyCount; i++ )
{
int nodeId = UIUtils.CheckUniformNameOwner( m_currentTemplate.AvailableShaderProperties[ i ].PropertyName );
if( nodeId > -1 )
{
ParentNode node = m_containerGraph.GetNode( nodeId );
if( node != null )
{
UIUtils.ShowMessage( string.Format( "Template requires property name {0} which is currently being used by {1}. Please rename it and reload template.", m_currentTemplate.AvailableShaderProperties[ i ].PropertyName, node.Attributes.Name ) );
}
else
{
UIUtils.ShowMessage( string.Format( "Template requires property name {0} which is currently being on your graph. Please rename it and reload template.", m_currentTemplate.AvailableShaderProperties[ i ].PropertyName ) );
}
}
else
{
UIUtils.RegisterUniformName( UniqueId, m_currentTemplate.AvailableShaderProperties[ i ].PropertyName );
}
}
}
}
public override void DrawProperties()
{
if( m_currentTemplate == null )
return;
base.DrawProperties();
bool generalIsVisible = ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedGeneralShaderOptions;
NodeUtils.DrawPropertyGroup( ref generalIsVisible, GeneralFoldoutStr, DrawGeneralOptions );
ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedGeneralShaderOptions = generalIsVisible;
if( m_currentTemplate.AlphaToMaskData.DataCheck == TemplateDataCheck.Valid )
m_alphaToMaskHelper.Draw( this );
if( m_currentTemplate.BlendData.DataCheck == TemplateDataCheck.Valid )
m_blendOpHelper.Draw( this );
if( m_currentTemplate.StencilData.DataCheck == TemplateDataCheck.Valid )
{
CullMode cullMode = ( m_currentTemplate.CullModeData.DataCheck == TemplateDataCheck.Valid ) ? m_cullModeHelper.CurrentCullMode : CullMode.Back;
m_stencilBufferHelper.Draw( this, cullMode );
}
if( m_currentTemplate.DepthData.DataCheck == TemplateDataCheck.Valid )
m_depthOphelper.Draw( this );
if( m_currentTemplate.TagData.DataCheck == TemplateDataCheck.Valid )
m_tagsHelper.Draw( this );
DrawMaterialInputs( UIUtils.MenuItemToolbarStyle );
// NodeUtils.DrawPropertyGroup( ref m_snippetsFoldout, SnippetsFoldoutStr, DrawSnippetOptions );
if( GUILayout.Button( OpenTemplateStr ) && m_currentTemplate != null )
{
try
{
string pathname = AssetDatabase.GUIDToAssetPath( m_currentTemplate.GUID );
if( !string.IsNullOrEmpty( pathname ) )
{
Shader selectedTemplate = AssetDatabase.LoadAssetAtPath<Shader>( pathname );
if( selectedTemplate != null )
{
AssetDatabase.OpenAsset( selectedTemplate, 1 );
}
}
}
catch( Exception e )
{
Debug.LogException( e );
}
}
#if SHOW_TEMPLATE_HELP_BOX
EditorGUILayout.HelpBox( WarningMessage, MessageType.Warning );
#endif
}
public void DrawGeneralOptions()
{
DrawShaderName();
DrawCurrentShaderType();
EditorGUI.BeginChangeCheck();
DrawPrecisionProperty( false );
if( EditorGUI.EndChangeCheck() )
ContainerGraph.CurrentPrecision = m_currentPrecisionType;
DrawSamplingMacros();
if( m_currentTemplate.CullModeData.DataCheck == TemplateDataCheck.Valid )
m_cullModeHelper.Draw( this );
if( m_currentTemplate.ColorMaskData.DataCheck == TemplateDataCheck.Valid )
m_colorMaskHelper.Draw( this );
}
//public void DrawSnippetOptions()
//{
// m_currentTemplate.DrawSnippetProperties( this );
//}
bool CreateInstructionsForList( ref List<InputPort> ports, ref string shaderBody, ref List<string> vertexInstructions, ref List<string> fragmentInstructions )
{
if( ports.Count == 0 )
return true;
bool isValid = true;
UIUtils.CurrentWindow.CurrentGraph.ResetNodesLocalVariables();
for( int i = 0; i < ports.Count; i++ )
{
TemplateInputData inputData = m_currentTemplate.InputDataFromId( ports[ i ].PortId );
if( ports[ i ].IsConnected )
{
m_currentDataCollector.ResetInstructions();
m_currentDataCollector.ResetVertexInstructions();
m_currentDataCollector.PortCategory = ports[ i ].Category;
string newPortInstruction = ports[ i ].GeneratePortInstructions( ref m_currentDataCollector );
if( m_currentDataCollector.DirtySpecialLocalVariables )
{
string cleanVariables = m_currentDataCollector.SpecialLocalVariables.Replace( "\t", string.Empty );
m_currentDataCollector.AddInstructions( cleanVariables, false );
m_currentDataCollector.ClearSpecialLocalVariables();
}
if( m_currentDataCollector.DirtyVertexVariables )
{
string cleanVariables = m_currentDataCollector.VertexLocalVariables.Replace( "\t", string.Empty );
m_currentDataCollector.AddVertexInstruction( cleanVariables, UniqueId, false );
m_currentDataCollector.ClearVertexLocalVariables();
}
// fill functions
for( int j = 0; j < m_currentDataCollector.InstructionsList.Count; j++ )
{
fragmentInstructions.Add( m_currentDataCollector.InstructionsList[ j ].PropertyName );
}
for( int j = 0; j < m_currentDataCollector.VertexDataList.Count; j++ )
{
vertexInstructions.Add( m_currentDataCollector.VertexDataList[ j ].PropertyName );
}
isValid = m_currentTemplate.FillTemplateBody( inputData.TagId, ref shaderBody, newPortInstruction ) && isValid;
}
else
{
isValid = m_currentTemplate.FillTemplateBody( inputData.TagId, ref shaderBody, inputData.DefaultValue ) && isValid;
}
}
return isValid;
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if( m_currentTemplate == null )
{
FetchCurrentTemplate();
}
if( m_reRegisterTemplateData )
{
RegisterProperties();
}
if( m_containerGraph.IsInstancedShader )
{
DrawInstancedIcon( drawInfo );
}
if( m_fetchMasterNodeCategory )
{
if( m_availableCategories != null )
{
m_fetchMasterNodeCategory = false;
SetCategoryIdxFromTemplate();
}
}
if( m_fireTemplateChange )
{
m_fireTemplateChange = false;
m_containerGraph.FireMasterNodeReplacedEvent();
}
}
public override void UpdateFromShader( Shader newShader )
{
if( m_currentMaterial != null )
{
m_currentMaterial.shader = newShader;
}
CurrentShader = newShader;
}
public override void UpdateMasterNodeMaterial( Material material )
{
m_currentMaterial = material;
FireMaterialChangedEvt();
}
public override Shader Execute( string pathname, bool isFullPath )
{
if( m_currentTemplate == null )
return m_currentShader;
//Create data collector
ForceReordering();
base.Execute( pathname, isFullPath );
SetupNodeCategories();
m_currentDataCollector.TemplateDataCollectorInstance.BuildFromTemplateData( m_currentDataCollector, m_currentTemplate );
int shaderPropertiesAmount = m_currentTemplate.AvailableShaderProperties.Count;
for( int i = 0; i < shaderPropertiesAmount; i++ )
{
m_currentDataCollector.SoftRegisterUniform( m_currentTemplate.AvailableShaderProperties[ i ] );
}
m_containerGraph.CheckPropertiesAutoRegister( ref m_currentDataCollector );
//Sort ports by both
List<InputPort> fragmentPorts = new List<InputPort>();
List<InputPort> vertexPorts = new List<InputPort>();
SortInputPorts( ref vertexPorts, ref fragmentPorts );
string shaderBody = m_currentTemplate.TemplateBody;
List<string> vertexInstructions = new List<string>();
List<string> fragmentInstructions = new List<string>();
bool validBody = true;
validBody = CreateInstructionsForList( ref fragmentPorts, ref shaderBody, ref vertexInstructions, ref fragmentInstructions ) && validBody;
ContainerGraph.ResetNodesLocalVariablesIfNot( MasterNodePortCategory.Vertex );
validBody = CreateInstructionsForList( ref vertexPorts, ref shaderBody, ref vertexInstructions, ref fragmentInstructions ) && validBody;
m_currentTemplate.ResetTemplateUsageData();
// Fill vertex interpolators assignment
for( int i = 0; i < m_currentDataCollector.VertexInterpDeclList.Count; i++ )
{
vertexInstructions.Add( m_currentDataCollector.VertexInterpDeclList[ i ] );
}
vertexInstructions.AddRange( m_currentDataCollector.TemplateDataCollectorInstance.GetInterpUnusedChannels() );
//Fill common local variables and operations
validBody = m_currentTemplate.FillVertexInstructions( ref shaderBody, vertexInstructions.ToArray() ) && validBody;
validBody = m_currentTemplate.FillFragmentInstructions( ref shaderBody, fragmentInstructions.ToArray() ) && validBody;
// Add Instanced Properties
if( m_containerGraph.IsInstancedShader )
{
m_currentDataCollector.TabifyInstancedVars();
m_currentDataCollector.InstancedPropertiesList.Insert( 0, new PropertyDataCollector( -1, string.Format( IOUtils.InstancedPropertiesBegin, UIUtils.RemoveInvalidCharacters( m_shaderName ) ) ) );
m_currentDataCollector.InstancedPropertiesList.Add( new PropertyDataCollector( -1, IOUtils.InstancedPropertiesEnd ) );
m_currentDataCollector.UniformsList.AddRange( m_currentDataCollector.InstancedPropertiesList );
}
//Add Functions
m_currentDataCollector.UniformsList.AddRange( m_currentDataCollector.FunctionsList );
// Fill common tags
m_currentDataCollector.IncludesList.AddRange( m_currentDataCollector.PragmasList );
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.ShaderNameId, ref shaderBody, string.Format( TemplatesManager.NameFormatter, m_shaderName ) ) && validBody;
validBody = m_currentTemplate.FillTemplateBody( TemplatesManager.TemplatePassTag, ref shaderBody, m_currentDataCollector.GrabPassList ) && validBody;
validBody = m_currentTemplate.FillTemplateBody( TemplatesManager.TemplatePragmaTag, ref shaderBody, m_currentDataCollector.IncludesList ) && validBody;
//validBody = m_currentTemplate.FillTemplateBody( TemplatesManager.TemplateTagsTag, ref shaderBody, m_currentDataCollector.TagsList ) && validBody;
validBody = m_currentTemplate.FillTemplateBody( TemplatesManager.TemplatePropertyTag, ref shaderBody, m_currentDataCollector.BuildUnformatedPropertiesStringArr() ) && validBody;
validBody = m_currentTemplate.FillTemplateBody( TemplatesManager.TemplateGlobalsTag, ref shaderBody, m_currentDataCollector.UniformsList ) && validBody;
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.VertexDataId, ref shaderBody, m_currentDataCollector.VertexInputList.ToArray() ) && validBody;
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.InterpDataId, ref shaderBody, m_currentDataCollector.InterpolatorList.ToArray() ) && validBody;
if( m_currentTemplate.BlendData.ValidBlendMode )
{
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.BlendData.BlendModeId, ref shaderBody, m_blendOpHelper.CurrentBlendFactor ) && validBody;
}
if( m_currentTemplate.BlendData.ValidBlendOp )
{
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.BlendData.BlendOpId, ref shaderBody, m_blendOpHelper.CurrentBlendOp ) && validBody;
}
if( m_currentTemplate.AlphaToMaskData.DataCheck == TemplateDataCheck.Valid )
{
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.AlphaToMaskData.AlphaToMaskId, ref shaderBody, m_alphaToMaskHelper.GenerateShaderData( false ) ) && validBody;
}
if( m_currentTemplate.DepthData.ValidZWrite )
{
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.DepthData.ZWriteModeId, ref shaderBody, m_depthOphelper.CurrentZWriteMode ) && validBody;
}
if( m_currentTemplate.DepthData.ValidZTest )
{
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.DepthData.ZTestModeId, ref shaderBody, m_depthOphelper.CurrentZTestMode ) && validBody;
}
if( m_currentTemplate.DepthData.ValidOffset )
{
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.DepthData.OffsetId, ref shaderBody, m_depthOphelper.CurrentOffset ) && validBody;
}
if( m_currentTemplate.CullModeData.DataCheck == TemplateDataCheck.Valid )
{
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.CullModeData.CullModeId, ref shaderBody, m_cullModeHelper.GenerateShaderData(false) ) && validBody;
}
if( m_currentTemplate.ColorMaskData.DataCheck == TemplateDataCheck.Valid )
{
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.ColorMaskData.ColorMaskId, ref shaderBody, m_colorMaskHelper.GenerateShaderData( false ) ) && validBody;
}
if( m_currentTemplate.StencilData.DataCheck == TemplateDataCheck.Valid )
{
CullMode cullMode = ( m_currentTemplate.CullModeData.DataCheck == TemplateDataCheck.Valid ) ? m_cullModeHelper.CurrentCullMode : CullMode.Back;
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.StencilData.StencilBufferId, ref shaderBody, m_stencilBufferHelper.CreateStencilOp( cullMode ) ) && validBody;
}
if( m_currentTemplate.TagData.DataCheck == TemplateDataCheck.Valid )
{
validBody = m_currentTemplate.FillTemplateBody( m_currentTemplate.TagData.TagsId, ref shaderBody, m_tagsHelper.GenerateTags() ) && validBody;
}
if( m_currentDataCollector.TemplateDataCollectorInstance.HasVertexInputParams )
{
validBody = m_currentTemplate.FillTemplateBody( TemplatesManager.TemplateInputsVertParamsTag, ref shaderBody, m_currentDataCollector.TemplateDataCollectorInstance.VertexInputParamsStr ) && validBody;
}
if( m_currentDataCollector.TemplateDataCollectorInstance.HasFragmentInputParams )
{
validBody = m_currentTemplate.FillTemplateBody( TemplatesManager.TemplateInputsFragParamsTag, ref shaderBody, m_currentDataCollector.TemplateDataCollectorInstance.FragInputParamsStr ) && validBody;
}
m_currentTemplate.FillEmptyTags( ref shaderBody );
//m_currentTemplate.InsertSnippets( ref shaderBody );
vertexInstructions.Clear();
vertexInstructions = null;
fragmentInstructions.Clear();
fragmentInstructions = null;
if( validBody )
{
UpdateShaderAsset( ref pathname, ref shaderBody, isFullPath );
}
return m_currentShader;
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
try
{
ShaderName = GetCurrentParam( ref nodeParams );
if( m_shaderName.Length > 0 )
ShaderName = UIUtils.RemoveShaderInvalidCharacters( ShaderName );
string templateGUID = GetCurrentParam( ref nodeParams );
string templateShaderName = string.Empty;
if( UIUtils.CurrentShaderVersion() > 13601 )
{
templateShaderName = GetCurrentParam( ref nodeParams );
}
TemplateData template = m_containerGraph.ParentWindow.TemplatesManagerInstance.GetTemplate( templateGUID ) as TemplateData;
if( template != null )
{
SetTemplate( template, false, true );
}
else
{
template = m_containerGraph.ParentWindow.TemplatesManagerInstance.GetTemplateByName( templateShaderName ) as TemplateData;
if( template != null )
{
SetTemplate( template, false, true );
}
else
{
m_masterNodeCategory = -1;
}
}
if( UIUtils.CurrentShaderVersion() > 13902 )
{
//BLEND MODULE
if( m_currentTemplate.BlendData.ValidBlendMode )
{
m_blendOpHelper.ReadBlendModeFromString( ref m_currentReadParamIdx, ref nodeParams );
}
if( m_currentTemplate.BlendData.ValidBlendOp )
{
m_blendOpHelper.ReadBlendOpFromString( ref m_currentReadParamIdx, ref nodeParams );
}
//CULL MODE
if( m_currentTemplate.CullModeData.DataCheck == TemplateDataCheck.Valid )
{
m_cullModeHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
}
//COLOR MASK
if( m_currentTemplate.ColorMaskData.DataCheck == TemplateDataCheck.Valid )
{
m_colorMaskHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
}
//STENCIL BUFFER
if( m_currentTemplate.StencilData.DataCheck == TemplateDataCheck.Valid )
{
m_stencilBufferHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
}
}
if( UIUtils.CurrentShaderVersion() > 14202 )
{
//DEPTH OPTIONS
if( m_currentTemplate.DepthData.ValidZWrite )
{
m_depthOphelper.ReadZWriteFromString( ref m_currentReadParamIdx, ref nodeParams );
}
if( m_currentTemplate.DepthData.ValidZTest )
{
m_depthOphelper.ReadZTestFromString( ref m_currentReadParamIdx, ref nodeParams );
}
if( m_currentTemplate.DepthData.ValidOffset )
{
m_depthOphelper.ReadOffsetFromString( ref m_currentReadParamIdx, ref nodeParams );
}
}
//TAGS
if( UIUtils.CurrentShaderVersion() > 14301 )
{
if( m_currentTemplate.TagData.DataCheck == TemplateDataCheck.Valid )
m_tagsHelper.ReadFromString( ref m_currentReadParamIdx, ref nodeParams );
}
if( UIUtils.CurrentShaderVersion() > 18302 )
SamplingMacros = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
else
SamplingMacros = false;
}
catch( Exception e )
{
Debug.LogException( e, this );
}
m_containerGraph.CurrentCanvasMode = NodeAvailability.TemplateShader;
m_containerGraph.CurrentPrecision = m_currentPrecisionType;
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_shaderName );
IOUtils.AddFieldValueToString( ref nodeInfo, ( m_currentTemplate != null ) ? m_currentTemplate.GUID : string.Empty );
IOUtils.AddFieldValueToString( ref nodeInfo, ( m_currentTemplate != null ) ? m_currentTemplate.DefaultShaderName : string.Empty );
//BLEND MODULE
if( m_currentTemplate.BlendData.ValidBlendMode )
{
m_blendOpHelper.WriteBlendModeToString( ref nodeInfo );
}
if( m_currentTemplate.BlendData.ValidBlendOp )
{
m_blendOpHelper.WriteBlendOpToString( ref nodeInfo );
}
//CULL MODULE
if( m_currentTemplate.CullModeData.DataCheck == TemplateDataCheck.Valid )
{
m_cullModeHelper.WriteToString( ref nodeInfo );
}
//COLOR MASK MODULE
if( m_currentTemplate.ColorMaskData.DataCheck == TemplateDataCheck.Valid )
{
m_colorMaskHelper.WriteToString( ref nodeInfo );
}
//STENCIL BUFFER MODULE
if( m_currentTemplate.StencilData.DataCheck == TemplateDataCheck.Valid )
{
m_stencilBufferHelper.WriteToString( ref nodeInfo );
}
//DEPTH MODULE
if( m_currentTemplate.DepthData.ValidZWrite )
{
m_depthOphelper.WriteZWriteToString( ref nodeInfo );
}
if( m_currentTemplate.DepthData.ValidZTest )
{
m_depthOphelper.WriteZTestToString( ref nodeInfo );
}
if( m_currentTemplate.DepthData.ValidOffset )
{
m_depthOphelper.WriteOffsetToString( ref nodeInfo );
}
//TAGS
if( m_currentTemplate.TagData.DataCheck == TemplateDataCheck.Valid )
{
m_tagsHelper.WriteToString( ref nodeInfo );
}
IOUtils.AddFieldValueToString( ref nodeInfo, m_samplingMacros );
}
public override void Destroy()
{
base.Destroy();
m_currentTemplate = null;
m_blendOpHelper = null;
m_alphaToMaskHelper = null;
m_cullModeHelper = null;
m_colorMaskHelper.Destroy();
m_colorMaskHelper = null;
m_stencilBufferHelper.Destroy();
m_stencilBufferHelper = null;
m_tagsHelper.Destroy();
m_tagsHelper = null;
}
public TemplateData CurrentTemplate { get { return m_currentTemplate; } }
}
}

View File

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

View File

@@ -0,0 +1,55 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEditor;
namespace AmplifyShaderEditor
{
public class TemplateMenuItems
{
[MenuItem( "Assets/Create/Amplify Shader/Legacy/Unlit", false, 85 )]
public static void ApplyTemplateLegacyUnlit()
{
AmplifyShaderEditorWindow.CreateConfirmationTemplateShader( "0770190933193b94aaa3065e307002fa" );
}
[MenuItem( "Assets/Create/Amplify Shader/Legacy/Post Process", false, 85 )]
public static void ApplyTemplateLegacyPostProcess()
{
AmplifyShaderEditorWindow.CreateConfirmationTemplateShader( "c71b220b631b6344493ea3cf87110c93" );
}
[MenuItem( "Assets/Create/Amplify Shader/Deprecated/Legacy/Default Unlit", false, 85 )]
public static void ApplyTemplateDeprecatedLegacyDefaultUnlit()
{
AmplifyShaderEditorWindow.CreateConfirmationTemplateShader( "6e114a916ca3e4b4bb51972669d463bf" );
}
[MenuItem( "Assets/Create/Amplify Shader/Legacy/Default UI", false, 85 )]
public static void ApplyTemplateLegacyDefaultUI()
{
AmplifyShaderEditorWindow.CreateConfirmationTemplateShader( "5056123faa0c79b47ab6ad7e8bf059a4" );
}
[MenuItem( "Assets/Create/Amplify Shader/Legacy/Unlit Lightmap", false, 85 )]
public static void ApplyTemplateLegacyUnlitLightmap()
{
AmplifyShaderEditorWindow.CreateConfirmationTemplateShader( "899e609c083c74c4ca567477c39edef0" );
}
[MenuItem( "Assets/Create/Amplify Shader/Legacy/Default Sprites", false, 85 )]
public static void ApplyTemplateLegacyDefaultSprites()
{
AmplifyShaderEditorWindow.CreateConfirmationTemplateShader( "0f8ba0101102bb14ebf021ddadce9b49" );
}
[MenuItem( "Assets/Create/Amplify Shader/Legacy/Particles Alpha Blended", false, 85 )]
public static void ApplyTemplateLegacyParticlesAlphaBlended()
{
AmplifyShaderEditorWindow.CreateConfirmationTemplateShader( "0b6a9f8b4f707c74ca64c0be8e590de0" );
}
[MenuItem( "Assets/Create/Amplify Shader/Legacy/Multi Pass Unlit", false, 85 )]
public static void ApplyTemplateLegacyMultiPassUnlit()
{
AmplifyShaderEditorWindow.CreateConfirmationTemplateShader( "e1de45c0d41f68c41b2cc20c8b9c05ef" );
}
[MenuItem( "Assets/Create/Amplify Shader/Legacy/Lit", false, 85 )]
public static void ApplyTemplateLegacyLit()
{
AmplifyShaderEditorWindow.CreateConfirmationTemplateShader( "ed95fe726fd7b4644bb42f4d1ddd2bcd" );
}
}
}

View File

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

View File

@@ -0,0 +1,755 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using UnityEngine;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateModulesHelper
{
[SerializeField]
internal bool Foldout = false;
private bool m_isDirty = false;
[SerializeField]
private TemplatesBlendModule m_blendOpHelper = new TemplatesBlendModule();
[SerializeField]
private TemplatesBlendModule m_blendOpHelper1 = new TemplatesBlendModule();
[SerializeField]
private TemplatesBlendModule m_blendOpHelper2 = new TemplatesBlendModule();
[SerializeField]
private TemplatesBlendModule m_blendOpHelper3 = new TemplatesBlendModule();
[SerializeField]
private TemplateAlphaToMaskModule m_alphaToMaskHelper = new TemplateAlphaToMaskModule();
[SerializeField]
private TemplateCullModeModule m_cullModeHelper = new TemplateCullModeModule();
[SerializeField]
private TemplateColorMaskModule m_colorMaskHelper = new TemplateColorMaskModule();
[SerializeField]
private TemplateColorMaskModule m_colorMaskHelper1 = new TemplateColorMaskModule();
[SerializeField]
private TemplateColorMaskModule m_colorMaskHelper2 = new TemplateColorMaskModule();
[SerializeField]
private TemplateColorMaskModule m_colorMaskHelper3 = new TemplateColorMaskModule();
[SerializeField]
private TemplatesStencilBufferModule m_stencilBufferHelper = new TemplatesStencilBufferModule();
[SerializeField]
private TemplateDepthModule m_depthOphelper = new TemplateDepthModule();
[SerializeField]
private TemplateTagsModule m_tagsHelper = new TemplateTagsModule();
[SerializeField]
private TemplateShaderModelModule m_shaderModelHelper = new TemplateShaderModelModule();
[SerializeField]
private TemplateAdditionalIncludesHelper m_additionalIncludes = new TemplateAdditionalIncludesHelper();
[SerializeField]
private TemplateAdditionalDefinesHelper m_additionalDefines = new TemplateAdditionalDefinesHelper();
[SerializeField]
private TemplateAdditionalPragmasHelper m_additionalPragmas = new TemplateAdditionalPragmasHelper();
[SerializeField]
private TemplateAdditionalDirectivesHelper m_additionalDirectives = new TemplateAdditionalDirectivesHelper(" Additional Directives");
[SerializeField]
private bool m_hasValidData = false;
[SerializeField]
private bool m_allModulesMode = false;
public void CopyFrom( TemplateModulesHelper other )
{
m_allModulesMode = other.AllModulesMode;
if( other.BlendOpHelper.IsDirty )
{
m_blendOpHelper.CopyFrom( other.BlendOpHelper, true );
}
if( other.BlendOpHelper1.IsDirty )
{
m_blendOpHelper1.CopyFrom( other.BlendOpHelper1, true );
}
if( other.BlendOpHelper2.IsDirty )
{
m_blendOpHelper2.CopyFrom( other.BlendOpHelper2, true );
}
if( other.BlendOpHelper3.IsDirty )
{
m_blendOpHelper3.CopyFrom( other.BlendOpHelper3, true );
}
if( other.AlphaToMaskHelper.IsDirty )
{
m_alphaToMaskHelper.CopyFrom( other.AlphaToMaskHelper, true );
}
if( other.CullModeHelper.IsDirty )
{
m_cullModeHelper.CopyFrom( other.CullModeHelper , true );
}
if( other.ColorMaskHelper.IsDirty )
{
m_colorMaskHelper.CopyFrom( other.ColorMaskHelper , true);
}
if( other.ColorMaskHelper1.IsDirty )
{
m_colorMaskHelper1.CopyFrom( other.ColorMaskHelper1, true );
}
if( other.ColorMaskHelper2.IsDirty )
{
m_colorMaskHelper2.CopyFrom( other.ColorMaskHelper2, true );
}
if( other.ColorMaskHelper3.IsDirty )
{
m_colorMaskHelper3.CopyFrom( other.ColorMaskHelper3, true );
}
if( other.StencilBufferHelper.IsDirty )
{
m_stencilBufferHelper.CopyFrom( other.StencilBufferHelper,true );
}
if( other.DepthOphelper.IsDirty )
{
m_depthOphelper.CopyFrom( other.DepthOphelper,true );
}
if( other.TagsHelper.IsDirty )
{
m_tagsHelper.CopyFrom( other.TagsHelper );
}
if( other.ShaderModelHelper.IsDirty )
{
m_shaderModelHelper.CopyFrom( other.ShaderModelHelper, true );
}
}
public void SyncWith( TemplateModulesHelper other )
{
if( m_blendOpHelper.ValidData && other.BlendOpHelper.ValidData )
{
m_blendOpHelper.CopyFrom( other.BlendOpHelper, false );
}
if( m_blendOpHelper1.ValidData && other.BlendOpHelper1.ValidData )
{
m_blendOpHelper1.CopyFrom( other.BlendOpHelper1, false );
}
if( m_blendOpHelper2.ValidData && other.BlendOpHelper2.ValidData )
{
m_blendOpHelper2.CopyFrom( other.BlendOpHelper2, false );
}
if( m_blendOpHelper3.ValidData && other.BlendOpHelper3.ValidData )
{
m_blendOpHelper3.CopyFrom( other.BlendOpHelper3, false );
}
if( m_alphaToMaskHelper.ValidData && other.AlphaToMaskHelper.ValidData )
{
m_alphaToMaskHelper.CopyFrom( other.AlphaToMaskHelper, false );
}
if( m_cullModeHelper.ValidData && other.CullModeHelper.ValidData )
{
m_cullModeHelper.CopyFrom( other.CullModeHelper, false );
}
if( m_colorMaskHelper.ValidData && other.ColorMaskHelper.ValidData )
{
m_colorMaskHelper.CopyFrom( other.ColorMaskHelper , false );
}
if( m_colorMaskHelper1.ValidData && other.ColorMaskHelper1.ValidData )
{
m_colorMaskHelper1.CopyFrom( other.ColorMaskHelper1, false );
}
if( m_colorMaskHelper2.ValidData && other.ColorMaskHelper2.ValidData )
{
m_colorMaskHelper2.CopyFrom( other.ColorMaskHelper2, false );
}
if( m_colorMaskHelper3.ValidData && other.ColorMaskHelper3.ValidData )
{
m_colorMaskHelper3.CopyFrom( other.ColorMaskHelper3, false );
}
if( m_stencilBufferHelper.ValidData && other.StencilBufferHelper.ValidData )
{
m_stencilBufferHelper.CopyFrom( other.StencilBufferHelper, false );
}
if( m_depthOphelper.ValidData && other.DepthOphelper.ValidData )
{
m_depthOphelper.CopyFrom( other.DepthOphelper, false );
}
if( m_shaderModelHelper.ValidData && other.ShaderModelHelper.ValidData )
{
m_shaderModelHelper.CopyFrom( other.ShaderModelHelper , false);
}
}
public void FetchDataFromTemplate( TemplateModulesData module )
{
m_allModulesMode = module.AllModulesMode;
if( module.PragmaTag.IsValid )
{
m_hasValidData = true;
//m_additionalPragmas.IsValid = true;
//m_additionalPragmas.FillNativeItems( module.IncludePragmaContainer.PragmasList );
//m_additionalIncludes.IsValid = true;
//m_additionalIncludes.FillNativeItems( module.IncludePragmaContainer.IncludesList );
//m_additionalDefines.IsValid = true;
//m_additionalDefines.FillNativeItems( module.IncludePragmaContainer.DefinesList );
m_additionalDirectives.FillNativeItems( module.IncludePragmaContainer.NativeDirectivesList );
m_additionalDirectives.IsValid = true;
}
else
{
//m_additionalPragmas.IsValid = false;
//m_additionalIncludes.IsValid = false;
//m_additionalDefines.IsValid = false;
m_additionalDirectives.IsValid = false;
}
m_blendOpHelper.ConfigureFromTemplateData( module.BlendData );
if( module.BlendData.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_blendOpHelper1.ConfigureFromTemplateData( module.BlendData1 );
if( module.BlendData1.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_blendOpHelper2.ConfigureFromTemplateData( module.BlendData2 );
if( module.BlendData2.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_blendOpHelper3.ConfigureFromTemplateData( module.BlendData3 );
if( module.BlendData3.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_alphaToMaskHelper.ConfigureFromTemplateData( module.AlphaToMaskData );
if( module.AlphaToMaskData.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_cullModeHelper.ConfigureFromTemplateData( module.CullModeData );
if( module.CullModeData.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_colorMaskHelper.ConfigureFromTemplateData( module.ColorMaskData );
if( module.ColorMaskData.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_colorMaskHelper1.ConfigureFromTemplateData( module.ColorMaskData1 );
if( module.ColorMaskData1.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_colorMaskHelper2.ConfigureFromTemplateData( module.ColorMaskData2 );
if( module.ColorMaskData2.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_colorMaskHelper3.ConfigureFromTemplateData( module.ColorMaskData3 );
if( module.ColorMaskData3.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_stencilBufferHelper.ConfigureFromTemplateData( module.StencilData );
if( module.StencilData.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_depthOphelper.ConfigureFromTemplateData( module.DepthData );
if( module.DepthData.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_tagsHelper.ConfigureFromTemplateData( module.TagData );
if( module.TagData.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
m_shaderModelHelper.ConfigureFromTemplateData( module.ShaderModel );
if( module.ShaderModel.DataCheck == TemplateDataCheck.Valid )
{
m_hasValidData = true;
}
}
public void OnLogicUpdate( TemplateModulesData currentModule )
{
if( currentModule.TagData.DataCheck == TemplateDataCheck.Valid )
m_tagsHelper.OnLogicUpdate();
}
public void Draw( ParentNode owner, TemplateModulesData currentModule , TemplateModulesHelper parent = null )
{
if( currentModule.ShaderModel.DataCheck == TemplateDataCheck.Valid )
m_shaderModelHelper.Draw( owner );
m_isDirty = m_shaderModelHelper.IsDirty;
if( currentModule.CullModeData.DataCheck == TemplateDataCheck.Valid )
m_cullModeHelper.Draw( owner );
m_isDirty = m_isDirty || m_cullModeHelper.IsDirty;
if( currentModule.ColorMaskData.DataCheck == TemplateDataCheck.Valid )
m_colorMaskHelper.Draw( owner );
m_isDirty = m_isDirty || m_colorMaskHelper.IsDirty;
if( currentModule.ColorMaskData1.DataCheck == TemplateDataCheck.Valid )
m_colorMaskHelper1.Draw( owner );
m_isDirty = m_isDirty || m_colorMaskHelper1.IsDirty;
if( currentModule.ColorMaskData2.DataCheck == TemplateDataCheck.Valid )
m_colorMaskHelper2.Draw( owner );
m_isDirty = m_isDirty || m_colorMaskHelper2.IsDirty;
if( currentModule.ColorMaskData3.DataCheck == TemplateDataCheck.Valid )
m_colorMaskHelper3.Draw( owner );
m_isDirty = m_isDirty || m_colorMaskHelper3.IsDirty;
if( currentModule.AlphaToMaskData.DataCheck == TemplateDataCheck.Valid )
m_alphaToMaskHelper.Draw( owner );
m_isDirty = m_isDirty || m_alphaToMaskHelper.IsDirty;
if( currentModule.DepthData.DataCheck == TemplateDataCheck.Valid )
m_depthOphelper.Draw( owner, false );
m_isDirty = m_isDirty || m_depthOphelper.IsDirty;
if( currentModule.BlendData.DataCheck == TemplateDataCheck.Valid )
m_blendOpHelper.Draw( owner, false );
m_isDirty = m_isDirty || m_blendOpHelper.IsDirty;
if( currentModule.BlendData1.DataCheck == TemplateDataCheck.Valid )
m_blendOpHelper1.Draw( owner, false );
m_isDirty = m_isDirty || m_blendOpHelper1.IsDirty;
if( currentModule.BlendData2.DataCheck == TemplateDataCheck.Valid )
m_blendOpHelper2.Draw( owner, false );
m_isDirty = m_isDirty || m_blendOpHelper2.IsDirty;
if( currentModule.BlendData3.DataCheck == TemplateDataCheck.Valid )
m_blendOpHelper3.Draw( owner, false );
m_isDirty = m_isDirty || m_blendOpHelper3.IsDirty;
if( currentModule.StencilData.DataCheck == TemplateDataCheck.Valid )
{
CullMode cullMode = CullMode.Back;
if( currentModule.CullModeData.DataCheck == TemplateDataCheck.Valid )
{
cullMode = m_cullModeHelper.CurrentCullMode;
}
else if( parent != null && parent.CullModeHelper.ValidData )
{
cullMode = parent.CullModeHelper.CurrentCullMode;
}
m_stencilBufferHelper.Draw( owner, cullMode, false );
}
m_isDirty = m_isDirty || m_stencilBufferHelper.IsDirty;
if( currentModule.TagData.DataCheck == TemplateDataCheck.Valid )
m_tagsHelper.Draw( owner, false );
m_isDirty = m_isDirty || m_tagsHelper.IsDirty;
if( currentModule.PragmaTag.IsValid )
{
//m_additionalDefines.Draw( owner );
//m_additionalIncludes.Draw( owner );
//m_additionalPragmas.Draw( owner );
m_additionalDirectives.Draw( owner , false);
}
m_isDirty = m_isDirty ||
//m_additionalDefines.IsDirty ||
//m_additionalIncludes.IsDirty ||
//m_additionalPragmas.IsDirty ||
m_additionalDirectives.IsDirty;
}
public void Destroy()
{
m_shaderModelHelper = null;
m_blendOpHelper = null;
m_blendOpHelper1 = null;
m_blendOpHelper2 = null;
m_blendOpHelper3 = null;
m_cullModeHelper = null;
m_alphaToMaskHelper = null;
m_colorMaskHelper.Destroy();
m_colorMaskHelper = null;
m_colorMaskHelper1.Destroy();
m_colorMaskHelper1 = null;
m_colorMaskHelper2.Destroy();
m_colorMaskHelper2 = null;
m_colorMaskHelper3.Destroy();
m_colorMaskHelper3 = null;
m_stencilBufferHelper.Destroy();
m_stencilBufferHelper = null;
m_tagsHelper.Destroy();
m_tagsHelper = null;
m_additionalDefines.Destroy();
m_additionalDefines = null;
m_additionalIncludes.Destroy();
m_additionalIncludes = null;
m_additionalPragmas.Destroy();
m_additionalPragmas = null;
m_additionalDirectives.Destroy();
m_additionalDirectives = null;
}
public string GenerateAllModulesString( bool isSubShader )
{
string moduleBody = string.Empty;
if( !ShaderModelHelper.IndependentModule )
{
moduleBody += ShaderModelHelper.GenerateShaderData( isSubShader ) + "\n";
}
if( !BlendOpHelper.IndependentModule )
{
if( BlendOpHelper.BlendModeEnabled )
moduleBody += BlendOpHelper.CurrentBlendFactor + "\n";
if( BlendOpHelper.BlendOpActive )
moduleBody += BlendOpHelper.CurrentBlendOp + "\n";
}
if( !AlphaToMaskHelper.IndependentModule )
moduleBody += AlphaToMaskHelper.GenerateShaderData( isSubShader ) + "\n";
if( !CullModeHelper.IndependentModule )
moduleBody += CullModeHelper.GenerateShaderData( isSubShader ) + "\n";
if( !ColorMaskHelper.IndependentModule )
moduleBody += ColorMaskHelper.GenerateShaderData( isSubShader ) + "\n";
if( !DepthOphelper.IndependentModule )
{
moduleBody += DepthOphelper.CurrentZWriteMode;
moduleBody += DepthOphelper.CurrentZTestMode;
if( DepthOphelper.OffsetEnabled )
moduleBody += DepthOphelper.CurrentOffset;
}
if( !StencilBufferHelper.IndependentModule && StencilBufferHelper.Active )
{
CullMode cullMode = ( CullModeHelper.ValidData ) ? CullModeHelper.CurrentCullMode : CullMode.Back;
moduleBody += StencilBufferHelper.CreateStencilOp( cullMode );
}
return moduleBody;
}
public void ReadFromString( ref uint index, ref string[] nodeParams )
{
try
{
m_blendOpHelper.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
if( UIUtils.CurrentShaderVersion() > 18103 )
{
try
{
m_blendOpHelper1.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
try
{
m_blendOpHelper2.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
try
{
m_blendOpHelper3.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
try
{
m_alphaToMaskHelper.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
}
try
{
m_cullModeHelper.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
try
{
m_colorMaskHelper.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
if( UIUtils.CurrentShaderVersion() > 18103 )
{
try
{
m_colorMaskHelper1.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
try
{
m_colorMaskHelper2.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
try
{
m_colorMaskHelper3.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
}
try
{
m_stencilBufferHelper.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
try
{
m_depthOphelper.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
try
{
m_tagsHelper.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
try
{
m_shaderModelHelper.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
if( UIUtils.CurrentShaderVersion() < 15312 )
{
try
{
m_additionalDefines.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
try
{
m_additionalPragmas.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
try
{
m_additionalIncludes.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
m_additionalDirectives.AddItems( AdditionalLineType.Include, m_additionalIncludes.ItemsList );
m_additionalDirectives.AddItems( AdditionalLineType.Define, m_additionalDefines.ItemsList );
m_additionalDirectives.AddItems( AdditionalLineType.Pragma, m_additionalPragmas.ItemsList );
}
else
{
try
{
m_additionalDirectives.ReadFromString( ref index, ref nodeParams );
}
catch( Exception e )
{
Debug.LogException( e );
}
}
}
public void WriteToString( ref string nodeInfo )
{
m_blendOpHelper.WriteToString( ref nodeInfo );
m_blendOpHelper1.WriteToString( ref nodeInfo );
m_blendOpHelper2.WriteToString( ref nodeInfo );
m_blendOpHelper3.WriteToString( ref nodeInfo );
m_alphaToMaskHelper.WriteToString( ref nodeInfo );
m_cullModeHelper.WriteToString( ref nodeInfo );
m_colorMaskHelper.WriteToString( ref nodeInfo );
m_colorMaskHelper1.WriteToString( ref nodeInfo );
m_colorMaskHelper2.WriteToString( ref nodeInfo );
m_colorMaskHelper3.WriteToString( ref nodeInfo );
m_stencilBufferHelper.WriteToString( ref nodeInfo );
m_depthOphelper.WriteToString( ref nodeInfo );
m_tagsHelper.WriteToString( ref nodeInfo );
m_shaderModelHelper.WriteToString( ref nodeInfo );
//m_additionalDefines.WriteToString( ref nodeInfo );
//m_additionalPragmas.WriteToString( ref nodeInfo );
//m_additionalIncludes.WriteToString( ref nodeInfo );
m_additionalDirectives.WriteToString( ref nodeInfo );
}
public TemplatesBlendModule BlendOpHelper { get { return m_blendOpHelper; } }
public TemplatesBlendModule BlendOpHelper1 { get { return m_blendOpHelper1; } }
public TemplatesBlendModule BlendOpHelper2 { get { return m_blendOpHelper2; } }
public TemplatesBlendModule BlendOpHelper3 { get { return m_blendOpHelper3; } }
public TemplateAlphaToMaskModule AlphaToMaskHelper { get { return m_alphaToMaskHelper; } }
public TemplateCullModeModule CullModeHelper { get { return m_cullModeHelper; } }
public TemplateColorMaskModule ColorMaskHelper { get { return m_colorMaskHelper; } }
public TemplateColorMaskModule ColorMaskHelper1 { get { return m_colorMaskHelper1; } }
public TemplateColorMaskModule ColorMaskHelper2 { get { return m_colorMaskHelper2; } }
public TemplateColorMaskModule ColorMaskHelper3 { get { return m_colorMaskHelper3; } }
public TemplatesStencilBufferModule StencilBufferHelper { get { return m_stencilBufferHelper; } }
public TemplateDepthModule DepthOphelper { get { return m_depthOphelper; } }
public TemplateTagsModule TagsHelper { get { return m_tagsHelper; } }
public TemplateShaderModelModule ShaderModelHelper { get { return m_shaderModelHelper; } }
//public TemplateAdditionalIncludesHelper AdditionalIncludes { get { return m_additionalIncludes; } }
//public TemplateAdditionalDefinesHelper AdditionalDefines { get { return m_additionalDefines; } }
//public TemplateAdditionalPragmasHelper AdditionalPragmas { get { return m_additionalPragmas; } }
public TemplateAdditionalDirectivesHelper AdditionalDirectives { get { return m_additionalDirectives; } }
public bool AllModulesMode { get { return m_allModulesMode; } }
public bool HasValidData { get { return m_hasValidData; } }
public bool IsDirty
{
get { return m_isDirty; }
set
{
m_isDirty = value;
if( !value )
{
m_blendOpHelper.IsDirty = false;
m_blendOpHelper1.IsDirty = false;
m_blendOpHelper2.IsDirty = false;
m_blendOpHelper3.IsDirty = false;
m_cullModeHelper.IsDirty = false;
m_alphaToMaskHelper.IsDirty = false;
m_colorMaskHelper.IsDirty = false;
m_colorMaskHelper1.IsDirty = false;
m_colorMaskHelper2.IsDirty = false;
m_colorMaskHelper3.IsDirty = false;
m_stencilBufferHelper.IsDirty = false;
m_tagsHelper.IsDirty = false;
m_shaderModelHelper.IsDirty = false;
//m_additionalDefines.IsDirty = false;
//m_additionalPragmas.IsDirty = false;
//m_additionalIncludes.IsDirty = false;
m_additionalDirectives.IsDirty = false;
}
}
}
// public bool Foldout { get { return m_foldout; } set { m_foldout = value; } }
}
}

View File

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

View File

@@ -0,0 +1,82 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateModuleParent
{
private const string UnreadableDataMessagePrefix = "Unreadable data on Module ";
protected string m_unreadableMessage;
[SerializeField]
protected bool m_validData = false;
[SerializeField]
protected bool m_isDirty = false;
[SerializeField]
protected string m_moduleName = string.Empty;
//[SerializeField]
//protected bool m_foldoutValue = false;
[SerializeField]
protected bool m_independentModule = true;
[SerializeField]
private bool m_customEdited = false;
public TemplateModuleParent( string moduleName ) { m_moduleName = moduleName; m_unreadableMessage = UnreadableDataMessagePrefix + moduleName; }
public virtual void Draw( UndoParentNode owner , bool style = true) { }
public virtual void ReadFromString( ref uint index, ref string[] nodeParams )
{
if( UIUtils.CurrentShaderVersion() > 18805 )
{
CustomEdited = Convert.ToBoolean( nodeParams[ index++ ] );
}
}
public virtual void WriteToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_customEdited );
}
public virtual string GenerateShaderData( bool isSubShader ) { return string.Empty; }
public virtual void Destroy() { }
public bool ValidData { get { return m_validData; } }
public bool ValidAndIndependent { get { return m_validData && m_independentModule; } }
public virtual void ShowUnreadableDataMessage( ParentNode owner )
{
ShowUnreadableDataMessage();
}
public virtual void ShowUnreadableDataMessage()
{
EditorGUILayout.HelpBox( m_unreadableMessage, MessageType.Info );
}
public bool IsDirty
{
get { return m_isDirty; }
set { m_isDirty = value; }
}
public bool IndependentModule
{
get { return m_independentModule; }
set { m_independentModule = value; }
}
public bool CustomEdited
{
get { return m_customEdited; }
set { m_customEdited = value; }
}
}
}

View File

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

View File

@@ -0,0 +1,800 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using UnityEngine;
namespace AmplifyShaderEditor
{
public enum TemplateModuleDataType
{
ModuleShaderModel,
ModuleBlendMode,
ModuleBlendMode1,
ModuleBlendMode2,
ModuleBlendMode3,
ModuleBlendOp,
ModuleBlendOp1,
ModuleBlendOp2,
ModuleBlendOp3,
ModuleAlphaToMask,
ModuleCullMode,
ModuleColorMask,
ModuleColorMask1,
ModuleColorMask2,
ModuleColorMask3,
ModuleStencil,
ModuleZwrite,
ModuleZTest,
ModuleZOffset,
ModuleTag,
ModuleGlobals,
ModuleSRPBatcher,
ModuleFunctions,
ModulePragma,
ModulePragmaBefore,
ModulePass,
ModuleInputVert,
ModuleInputFrag,
PassVertexFunction,
PassFragmentFunction,
PassVertexData,
PassInterpolatorData,
PassNameData,
AllModules,
VControl,
ControlData,
DomainData
//EndPass
}
public enum TemplateSRPType
{
BuiltIn,
HD,
Lightweight
}
[Serializable]
public class TemplateModulesData
{
[SerializeField]
private TemplateBlendData m_blendData = new TemplateBlendData();
[SerializeField]
private TemplateBlendData m_blendData1 = new TemplateBlendData();
[SerializeField]
private TemplateBlendData m_blendData2 = new TemplateBlendData();
[SerializeField]
private TemplateBlendData m_blendData3 = new TemplateBlendData();
[SerializeField]
private TemplateAlphaToMaskData m_alphaToMaskData = new TemplateAlphaToMaskData();
[SerializeField]
private TemplateCullModeData m_cullModeData = new TemplateCullModeData();
[SerializeField]
private TemplateColorMaskData m_colorMaskData = new TemplateColorMaskData();
[SerializeField]
private TemplateColorMaskData m_colorMaskData1 = new TemplateColorMaskData();
[SerializeField]
private TemplateColorMaskData m_colorMaskData2 = new TemplateColorMaskData();
[SerializeField]
private TemplateColorMaskData m_colorMaskData3 = new TemplateColorMaskData();
[SerializeField]
private TemplateStencilData m_stencilData = new TemplateStencilData();
[SerializeField]
private TemplateDepthData m_depthData = new TemplateDepthData();
[SerializeField]
private TemplateTagsModuleData m_tagData = new TemplateTagsModuleData();
[SerializeField]
private TemplateTagData m_globalsTag = new TemplateTagData( TemplatesManager.TemplateGlobalsTag, true );
[SerializeField]
private TemplateTagData m_srpBatcherTag = new TemplateTagData( TemplatesManager.TemplateSRPBatcherTag, true );
[SerializeField]
private TemplateTagData m_allModulesTag = new TemplateTagData( TemplatesManager.TemplateAllModulesTag, true );
[SerializeField]
private TemplateTagData m_functionsTag = new TemplateTagData( TemplatesManager.TemplateFunctionsTag, true );
[SerializeField]
private TemplateTagData m_pragmaTag = new TemplateTagData( TemplatesManager.TemplatePragmaTag, true );
[SerializeField]
private TemplateTagData m_pragmaBeforeTag = new TemplateTagData( TemplatesManager.TemplatePragmaBeforeTag, true );
[SerializeField]
private TemplateTagData m_passTag = new TemplateTagData( TemplatesManager.TemplatePassTag, true );
[SerializeField]
private TemplateTagData m_inputsVertTag = new TemplateTagData( TemplatesManager.TemplateInputsVertParamsTag, false );
[SerializeField]
private TemplateTagData m_inputsFragTag = new TemplateTagData( TemplatesManager.TemplateInputsFragParamsTag, false );
[SerializeField]
private TemplateShaderModelData m_shaderModel = new TemplateShaderModelData();
[SerializeField]
private TemplateSRPType m_srpType = TemplateSRPType.BuiltIn;
[SerializeField]
private bool m_srpIsPBR = false;
[SerializeField]
private string m_uniquePrefix;
[SerializeField]
private TemplateIncludePragmaContainter m_includePragmaContainer = new TemplateIncludePragmaContainter();
[SerializeField]
private bool m_allModulesMode = false;
[SerializeField]
private string m_passUniqueName = string.Empty;
public void Destroy()
{
m_blendData = null;
m_blendData1 = null;
m_blendData2 = null;
m_blendData3 = null;
m_alphaToMaskData = null;
m_cullModeData = null;
m_colorMaskData = null;
m_colorMaskData1 = null;
m_colorMaskData2 = null;
m_colorMaskData3 = null;
m_stencilData = null;
m_depthData = null;
m_tagData.Destroy();
m_tagData = null;
m_globalsTag = null;
m_srpBatcherTag = null;
m_allModulesTag = null;
m_functionsTag = null;
m_pragmaTag = null;
m_pragmaBeforeTag = null;
m_passTag = null;
m_inputsVertTag = null;
m_inputsFragTag = null;
m_includePragmaContainer.Destroy();
m_includePragmaContainer = null;
}
public void ConfigureCommonTag( TemplateTagData tagData, TemplatePropertyContainer propertyContainer, TemplateIdManager idManager, string uniquePrefix, int offsetIdx, string subBody )
{
int id = subBody.IndexOf( tagData.Id );
if ( id >= 0 )
{
tagData.StartIdx = offsetIdx + id;
idManager.RegisterId( tagData.StartIdx, uniquePrefix + tagData.Id, tagData.Id );
propertyContainer.AddId( subBody, tagData.Id, tagData.SearchIndentation );
}
}
public TemplateModulesData( TemplateOptionsContainer optionsContainer, TemplateIdManager idManager, TemplatePropertyContainer propertyContainer, string uniquePrefix, int offsetIdx, string subBody, bool isSubShader )
{
if ( string.IsNullOrEmpty( subBody ) )
return;
m_uniquePrefix = uniquePrefix;
//PRAGMAS AND INCLUDES
TemplateHelperFunctions.CreatePragmaIncludeList( subBody, m_includePragmaContainer );
//COMMON TAGS
ConfigureCommonTag( m_globalsTag, propertyContainer, idManager, uniquePrefix, offsetIdx, subBody );
ConfigureCommonTag( m_srpBatcherTag, propertyContainer, idManager, uniquePrefix, offsetIdx, subBody );
ConfigureCommonTag( m_functionsTag, propertyContainer, idManager, uniquePrefix, offsetIdx, subBody );
ConfigureCommonTag( m_pragmaTag, propertyContainer, idManager, uniquePrefix, offsetIdx, subBody );
ConfigureCommonTag( m_pragmaBeforeTag, propertyContainer, idManager, uniquePrefix, offsetIdx, subBody );
if( !TemplateHelperFunctions.GetPassUniqueId( m_passTag, propertyContainer, idManager, uniquePrefix, offsetIdx, subBody, ref m_passUniqueName ) )
{
ConfigureCommonTag( m_passTag, propertyContainer, idManager, uniquePrefix, offsetIdx, subBody );
}
ConfigureCommonTag( m_inputsVertTag, propertyContainer, idManager, uniquePrefix, offsetIdx, subBody );
ConfigureCommonTag( m_inputsFragTag, propertyContainer, idManager, uniquePrefix, offsetIdx, subBody );
// If Options are enabled then remove them so they won't influence Regex matches
if( optionsContainer.Enabled && optionsContainer.EndIndex > 0 )
{
offsetIdx += optionsContainer.EndIndex;
subBody = subBody.Substring( optionsContainer.EndIndex );
}
//BlEND MODE
{
Match blendModeMatch = Regex.Match( subBody, TemplateHelperFunctions.BlendModePattern1 );
if( blendModeMatch.Success )
{
int blendModeIdx = blendModeMatch.Index;
int end = blendModeMatch.Length + blendModeIdx;
string blendParams = subBody.Substring( blendModeIdx, end - blendModeIdx );
m_blendData1.BlendModeId = blendParams;
m_blendData1.BlendModeStartIndex = offsetIdx + blendModeIdx;
idManager.RegisterId( m_blendData1.BlendModeStartIndex, uniquePrefix + m_blendData1.BlendModeId, m_blendData1.BlendModeId );
TemplateHelperFunctions.CreateBlendMode( blendParams, ref m_blendData1, TemplateHelperFunctions.BlendModePattern1 );
if( m_blendData1.ValidBlendMode )
{
propertyContainer.AddId( subBody, blendParams, false );
}
}
}
{
Match blendModeMatch = Regex.Match( subBody, TemplateHelperFunctions.BlendModePattern2 );
if( blendModeMatch.Success )
{
int blendModeIdx = blendModeMatch.Index;
int end = blendModeMatch.Length + blendModeIdx;
string blendParams = subBody.Substring( blendModeIdx, end - blendModeIdx );
m_blendData2.BlendModeId = blendParams;
m_blendData2.BlendModeStartIndex = offsetIdx + blendModeIdx;
idManager.RegisterId( m_blendData2.BlendModeStartIndex, uniquePrefix + m_blendData2.BlendModeId, m_blendData2.BlendModeId );
TemplateHelperFunctions.CreateBlendMode( blendParams, ref m_blendData2, TemplateHelperFunctions.BlendModePattern2 );
if( m_blendData2.ValidBlendMode )
{
propertyContainer.AddId( subBody, blendParams, false );
}
}
}
{
Match blendModeMatch = Regex.Match( subBody, TemplateHelperFunctions.BlendModePattern3 );
if( blendModeMatch.Success )
{
int blendModeIdx = blendModeMatch.Index;
int end = blendModeMatch.Length + blendModeIdx;
string blendParams = subBody.Substring( blendModeIdx, end - blendModeIdx );
m_blendData3.BlendModeId = blendParams;
m_blendData3.BlendModeStartIndex = offsetIdx + blendModeIdx;
idManager.RegisterId( m_blendData3.BlendModeStartIndex, uniquePrefix + m_blendData3.BlendModeId, m_blendData3.BlendModeId );
TemplateHelperFunctions.CreateBlendMode( blendParams, ref m_blendData3, TemplateHelperFunctions.BlendModePattern3 );
if( m_blendData3.ValidBlendMode )
{
propertyContainer.AddId( subBody, blendParams, false );
}
}
}
{
string pattern = TemplateHelperFunctions.BlendModePattern;
Match blendModeMatch = Regex.Match( subBody, pattern );
if( !blendModeMatch.Success && !m_blendData1.ValidBlendMode && !m_blendData2.ValidBlendMode && !m_blendData3.ValidBlendMode )
{
pattern = TemplateHelperFunctions.BlendModePatternFirst;
blendModeMatch = Regex.Match( subBody, pattern );
}
if( blendModeMatch.Success )
{
int blendModeIdx = blendModeMatch.Index;
int end = blendModeMatch.Length + blendModeIdx;
string blendParams = subBody.Substring( blendModeIdx, end - blendModeIdx );
m_blendData.BlendModeId = blendParams;
m_blendData.BlendModeStartIndex = offsetIdx + blendModeIdx;
idManager.RegisterId( m_blendData.BlendModeStartIndex, uniquePrefix + m_blendData.BlendModeId, m_blendData.BlendModeId );
TemplateHelperFunctions.CreateBlendMode( blendParams, ref m_blendData, pattern );
if( m_blendData.ValidBlendMode )
{
propertyContainer.AddId( subBody, blendParams, false );
}
}
}
//BLEND OP
{
Match blendOpMatch = Regex.Match( subBody, TemplateHelperFunctions.BlendOpPattern1 );
if( blendOpMatch.Success )
{
int blendOpIdx = blendOpMatch.Index;
int end = blendOpMatch.Length + blendOpIdx;
string blendOpParams = subBody.Substring( blendOpIdx, end - blendOpIdx );
m_blendData1.BlendOpId = blendOpParams;
m_blendData1.BlendOpStartIndex = offsetIdx + blendOpIdx;
idManager.RegisterId( m_blendData1.BlendOpStartIndex, uniquePrefix + m_blendData1.BlendOpId, m_blendData1.BlendOpId );
TemplateHelperFunctions.CreateBlendOp( blendOpParams, ref m_blendData1, TemplateHelperFunctions.BlendOpPattern1 );
if( m_blendData1.ValidBlendOp )
{
propertyContainer.AddId( subBody, blendOpParams, false );
}
}
m_blendData1.DataCheck = ( m_blendData1.ValidBlendMode || m_blendData1.ValidBlendOp ) ? TemplateDataCheck.Valid : TemplateDataCheck.Invalid;
}
{
Match blendOpMatch = Regex.Match( subBody, TemplateHelperFunctions.BlendOpPattern2 );
if( blendOpMatch.Success )
{
int blendOpIdx = blendOpMatch.Index;
int end = blendOpMatch.Length + blendOpIdx;
string blendOpParams = subBody.Substring( blendOpIdx, end - blendOpIdx );
m_blendData2.BlendOpId = blendOpParams;
m_blendData2.BlendOpStartIndex = offsetIdx + blendOpIdx;
idManager.RegisterId( m_blendData2.BlendOpStartIndex, uniquePrefix + m_blendData2.BlendOpId, m_blendData2.BlendOpId );
TemplateHelperFunctions.CreateBlendOp( blendOpParams, ref m_blendData2, TemplateHelperFunctions.BlendOpPattern2 );
if( m_blendData2.ValidBlendOp )
{
propertyContainer.AddId( subBody, blendOpParams, false );
}
}
m_blendData2.DataCheck = ( m_blendData2.ValidBlendMode || m_blendData2.ValidBlendOp ) ? TemplateDataCheck.Valid : TemplateDataCheck.Invalid;
}
{
Match blendOpMatch = Regex.Match( subBody, TemplateHelperFunctions.BlendOpPattern3 );
if( blendOpMatch.Success )
{
int blendOpIdx = blendOpMatch.Index;
int end = blendOpMatch.Length + blendOpIdx;
string blendOpParams = subBody.Substring( blendOpIdx, end - blendOpIdx );
m_blendData3.BlendOpId = blendOpParams;
m_blendData3.BlendOpStartIndex = offsetIdx + blendOpIdx;
idManager.RegisterId( m_blendData3.BlendOpStartIndex, uniquePrefix + m_blendData3.BlendOpId, m_blendData3.BlendOpId );
TemplateHelperFunctions.CreateBlendOp( blendOpParams, ref m_blendData3, TemplateHelperFunctions.BlendOpPattern3 );
if( m_blendData3.ValidBlendOp )
{
propertyContainer.AddId( subBody, blendOpParams, false );
}
}
m_blendData3.DataCheck = ( m_blendData3.ValidBlendMode || m_blendData3.ValidBlendOp ) ? TemplateDataCheck.Valid : TemplateDataCheck.Invalid;
}
{
string pattern = TemplateHelperFunctions.BlendOpPattern;
Match blendOpMatch = Regex.Match( subBody, pattern );
if( !blendOpMatch.Success && !m_blendData1.ValidBlendOp && !m_blendData2.ValidBlendOp && !m_blendData3.ValidBlendOp )
{
pattern = TemplateHelperFunctions.BlendOpPatternFirst;
blendOpMatch = Regex.Match( subBody, pattern );
}
if( blendOpMatch.Success )
{
int blendOpIdx = blendOpMatch.Index;
int end = blendOpMatch.Length + blendOpIdx;
string blendOpParams = subBody.Substring( blendOpIdx, end - blendOpIdx );
m_blendData.BlendOpId = blendOpParams;
m_blendData.BlendOpStartIndex = offsetIdx + blendOpIdx;
idManager.RegisterId( m_blendData.BlendOpStartIndex, uniquePrefix + m_blendData.BlendOpId, m_blendData.BlendOpId );
TemplateHelperFunctions.CreateBlendOp( blendOpParams, ref m_blendData, pattern );
if( m_blendData.ValidBlendOp )
{
propertyContainer.AddId( subBody, blendOpParams, false );
}
}
m_blendData.DataCheck = ( m_blendData.ValidBlendMode || m_blendData.ValidBlendOp ) ? TemplateDataCheck.Valid : TemplateDataCheck.Invalid;
}
//ALPHA TO MASK
{
Match alphaToMaskMatch = Regex.Match( subBody, TemplateHelperFunctions.AlphaToMaskPattern );
if( alphaToMaskMatch.Success )
{
int alphaIdx = alphaToMaskMatch.Index;
int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, alphaIdx );
string alphaParams = subBody.Substring( alphaIdx, end - alphaIdx );
m_alphaToMaskData.AlphaToMaskId = alphaParams;
m_alphaToMaskData.StartIdx = offsetIdx + alphaIdx;
idManager.RegisterId( m_alphaToMaskData.StartIdx, uniquePrefix + m_alphaToMaskData.AlphaToMaskId, m_alphaToMaskData.AlphaToMaskId );
TemplateHelperFunctions.CreateAlphaToMask( alphaParams, ref m_alphaToMaskData );
if( m_alphaToMaskData.DataCheck == TemplateDataCheck.Valid )
propertyContainer.AddId( subBody, alphaParams, false, string.Empty );
}
}
//CULL MODE
{
Match cullMatch = Regex.Match( subBody, TemplateHelperFunctions.CullWholeWordPattern );
if( cullMatch.Success )
{
int cullIdx = cullMatch.Index;
int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, cullIdx );
string cullParams = subBody.Substring( cullIdx, end - cullIdx );
m_cullModeData.CullModeId = cullParams;
m_cullModeData.StartIdx = offsetIdx + cullIdx;
idManager.RegisterId( m_cullModeData.StartIdx, uniquePrefix + m_cullModeData.CullModeId, m_cullModeData.CullModeId );
TemplateHelperFunctions.CreateCullMode( cullParams, ref m_cullModeData );
if( m_cullModeData.DataCheck == TemplateDataCheck.Valid )
propertyContainer.AddId( subBody, cullParams, false, string.Empty );
}
}
//COLOR MASK
{
Match colorMaskMatch = Regex.Match( subBody, TemplateHelperFunctions.ColorMask1Pattern );
if( colorMaskMatch.Success )
{
int colorMaskIdx = colorMaskMatch.Index;
int end = colorMaskMatch.Length + colorMaskIdx;// subBody.IndexOf( TemplatesManager.TemplateNewLine, colorMaskIdx );
string colorMaskParams = subBody.Substring( colorMaskIdx, end - colorMaskIdx );
m_colorMaskData1.ColorMaskId = colorMaskParams;
m_colorMaskData1.StartIdx = offsetIdx + colorMaskIdx;
idManager.RegisterId( m_colorMaskData1.StartIdx, uniquePrefix + m_colorMaskData1.ColorMaskId, m_colorMaskData1.ColorMaskId );
TemplateHelperFunctions.CreateColorMask( colorMaskParams, ref m_colorMaskData1, TemplateHelperFunctions.ColorMask1Pattern );
if( m_colorMaskData1.DataCheck == TemplateDataCheck.Valid )
propertyContainer.AddId( subBody, colorMaskParams, false );
}
}
{
Match colorMaskMatch = Regex.Match( subBody, TemplateHelperFunctions.ColorMask2Pattern );
if( colorMaskMatch.Success )
{
int colorMaskIdx = colorMaskMatch.Index;
int end = colorMaskMatch.Length + colorMaskIdx;// subBody.IndexOf( TemplatesManager.TemplateNewLine, colorMaskIdx );
string colorMaskParams = subBody.Substring( colorMaskIdx, end - colorMaskIdx );
m_colorMaskData2.ColorMaskId = colorMaskParams;
m_colorMaskData2.StartIdx = offsetIdx + colorMaskIdx;
idManager.RegisterId( m_colorMaskData2.StartIdx, uniquePrefix + m_colorMaskData2.ColorMaskId, m_colorMaskData2.ColorMaskId );
TemplateHelperFunctions.CreateColorMask( colorMaskParams, ref m_colorMaskData2, TemplateHelperFunctions.ColorMask2Pattern );
if( m_colorMaskData2.DataCheck == TemplateDataCheck.Valid )
propertyContainer.AddId( subBody, colorMaskParams, false );
}
}
{
Match colorMaskMatch = Regex.Match( subBody, TemplateHelperFunctions.ColorMask3Pattern );
if( colorMaskMatch.Success )
{
int colorMaskIdx = colorMaskMatch.Index;
int end = colorMaskMatch.Length + colorMaskIdx;// subBody.IndexOf( TemplatesManager.TemplateNewLine, colorMaskIdx );
string colorMaskParams = subBody.Substring( colorMaskIdx, end - colorMaskIdx );
m_colorMaskData3.ColorMaskId = colorMaskParams;
m_colorMaskData3.StartIdx = offsetIdx + colorMaskIdx;
idManager.RegisterId( m_colorMaskData3.StartIdx, uniquePrefix + m_colorMaskData3.ColorMaskId, m_colorMaskData3.ColorMaskId );
TemplateHelperFunctions.CreateColorMask( colorMaskParams, ref m_colorMaskData3, TemplateHelperFunctions.ColorMask3Pattern );
if( m_colorMaskData3.DataCheck == TemplateDataCheck.Valid )
propertyContainer.AddId( subBody, colorMaskParams, false );
}
}
{
string pattern = TemplateHelperFunctions.ColorMaskPattern;
Match colorMaskMatch = Regex.Match( subBody, pattern );
if( !colorMaskMatch.Success && m_colorMaskData1.DataCheck == TemplateDataCheck.Invalid && m_colorMaskData2.DataCheck == TemplateDataCheck.Invalid && m_colorMaskData3.DataCheck == TemplateDataCheck.Invalid )
{
pattern = TemplateHelperFunctions.ColorMaskPatternFirst;
colorMaskMatch = Regex.Match( subBody, pattern );
}
if( colorMaskMatch.Success )
{
int colorMaskIdx = colorMaskMatch.Index;
int end = colorMaskMatch.Length + colorMaskIdx; //subBody.IndexOf( TemplatesManager.TemplateNewLine, colorMaskIdx );
string colorMaskParams = subBody.Substring( colorMaskIdx, end - colorMaskIdx );
m_colorMaskData.ColorMaskId = colorMaskParams;
m_colorMaskData.StartIdx = offsetIdx + colorMaskIdx;
idManager.RegisterId( m_colorMaskData.StartIdx, uniquePrefix + m_colorMaskData.ColorMaskId, m_colorMaskData.ColorMaskId );
TemplateHelperFunctions.CreateColorMask( colorMaskParams, ref m_colorMaskData, pattern );
if( m_colorMaskData.DataCheck == TemplateDataCheck.Valid )
propertyContainer.AddId( subBody, colorMaskParams, false );
}
}
//STENCIL
{
Match stencilMatch = Regex.Match( subBody, TemplateHelperFunctions.StencilWholeWordPattern );
if( stencilMatch.Success )
{
int stencilIdx = stencilMatch.Index;
int stencilEndIdx = subBody.IndexOf( "}", stencilIdx );
if( stencilEndIdx > 0 )
{
string stencilParams = subBody.Substring( stencilIdx, stencilEndIdx + 1 - stencilIdx );
m_stencilData.StencilBufferId = stencilParams;
m_stencilData.StartIdx = offsetIdx + stencilIdx;
idManager.RegisterId( m_stencilData.StartIdx, uniquePrefix + m_stencilData.StencilBufferId, m_stencilData.StencilBufferId );
TemplateHelperFunctions.CreateStencilOps( stencilParams, ref m_stencilData );
if( m_stencilData.DataCheck == TemplateDataCheck.Valid )
{
propertyContainer.AddId( subBody, stencilParams, true );
}
}
}
else
{
int stencilTagIdx = subBody.IndexOf( TemplatesManager.TemplateStencilTag );
if( stencilTagIdx > -1 )
{
m_stencilData.SetIndependentDefault();
m_stencilData.StencilBufferId = TemplatesManager.TemplateStencilTag;
m_stencilData.StartIdx = offsetIdx + stencilTagIdx;
idManager.RegisterId( m_stencilData.StartIdx, uniquePrefix + m_stencilData.StencilBufferId, m_stencilData.StencilBufferId );
propertyContainer.AddId( subBody, m_stencilData.StencilBufferId, true );
}
}
}
//ZWRITE
{
Match zWriteMatch = Regex.Match( subBody, TemplateHelperFunctions.ZWriteWholeWordPattern );
if( zWriteMatch.Success )
{
int zWriteOpIdx = zWriteMatch.Index;
int zWriteEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zWriteOpIdx );
if( zWriteEndIdx > 0 )
{
m_depthData.ZWriteModeId = subBody.Substring( zWriteOpIdx, zWriteEndIdx + 1 - zWriteOpIdx );
m_depthData.ZWriteStartIndex = offsetIdx + zWriteOpIdx;
idManager.RegisterId( m_depthData.ZWriteStartIndex, uniquePrefix + m_depthData.ZWriteModeId, m_depthData.ZWriteModeId );
TemplateHelperFunctions.CreateZWriteMode( m_depthData.ZWriteModeId, ref m_depthData );
if( m_depthData.DataCheck == TemplateDataCheck.Valid )
{
propertyContainer.AddId( subBody, m_depthData.ZWriteModeId, true );
}
}
}
}
//ZTEST
{
Match zTestMatch = Regex.Match( subBody, TemplateHelperFunctions.ZTestWholeWordPattern );
if( zTestMatch.Success )
{
int zTestOpIdx = zTestMatch.Index;
int zTestEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zTestOpIdx );
if( zTestEndIdx > 0 )
{
m_depthData.ZTestModeId = subBody.Substring( zTestOpIdx, zTestEndIdx + 1 - zTestOpIdx );
m_depthData.ZTestStartIndex = offsetIdx + zTestOpIdx;
idManager.RegisterId( m_depthData.ZTestStartIndex, uniquePrefix + m_depthData.ZTestModeId, m_depthData.ZTestModeId );
TemplateHelperFunctions.CreateZTestMode( m_depthData.ZTestModeId, ref m_depthData );
if( m_depthData.DataCheck == TemplateDataCheck.Valid )
{
propertyContainer.AddId( subBody, m_depthData.ZTestModeId, true );
}
}
}
}
//ZOFFSET
{
Match zOffsetMatch = Regex.Match( subBody, TemplateHelperFunctions.ZOffsetWholeWordPattern );
if( zOffsetMatch.Success )
{
int zOffsetIdx = zOffsetMatch.Index;
int zOffsetEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zOffsetIdx );
if( zOffsetEndIdx > 0 )
{
m_depthData.OffsetId = subBody.Substring( zOffsetIdx, zOffsetEndIdx + 1 - zOffsetIdx );
m_depthData.OffsetStartIndex = offsetIdx + zOffsetIdx;
idManager.RegisterId( m_depthData.OffsetStartIndex, uniquePrefix + m_depthData.OffsetId, m_depthData.OffsetId );
TemplateHelperFunctions.CreateZOffsetMode( m_depthData.OffsetId, ref m_depthData );
if( m_depthData.DataCheck == TemplateDataCheck.Valid )
{
propertyContainer.AddId( subBody, m_depthData.OffsetId, true );
}
}
}
m_depthData.SetDataCheck();
}
//TAGS
{
Match tagsMatch = Regex.Match( subBody, TemplateHelperFunctions.TagsWholeWordPattern );
if ( tagsMatch.Success )
{
int tagsIdx = tagsMatch.Index;
int tagsEndIdx = subBody.IndexOf( "}", tagsIdx );
if ( tagsEndIdx > -1 )
{
m_tagData.Reset();
m_tagData.TagsId = subBody.Substring( tagsIdx, tagsEndIdx + 1 - tagsIdx );
m_tagData.StartIdx = offsetIdx + tagsIdx;
idManager.RegisterId( m_tagData.StartIdx, uniquePrefix + m_tagData.TagsId, m_tagData.TagsId );
m_srpType = TemplateHelperFunctions.CreateTags( ref m_tagData, isSubShader );
propertyContainer.AddId( subBody, m_tagData.TagsId, false );
m_tagData.DataCheck = TemplateDataCheck.Valid;
}
else
{
m_tagData.DataCheck = TemplateDataCheck.Invalid;
}
}
else
{
m_tagData.DataCheck = TemplateDataCheck.Invalid;
}
}
//SHADER MODEL
{
Match match = Regex.Match( subBody, TemplateHelperFunctions.ShaderModelPattern );
if ( match != null && match.Groups.Count > 1 )
{
if ( TemplateHelperFunctions.AvailableInterpolators.ContainsKey( match.Groups[ 1 ].Value ) )
{
m_shaderModel.Id = match.Groups[ 0 ].Value;
m_shaderModel.StartIdx = offsetIdx + match.Index;
m_shaderModel.Value = match.Groups[ 1 ].Value;
m_shaderModel.InterpolatorAmount = TemplateHelperFunctions.AvailableInterpolators[ match.Groups[ 1 ].Value ];
m_shaderModel.DataCheck = TemplateDataCheck.Valid;
idManager.RegisterId( m_shaderModel.StartIdx, uniquePrefix + m_shaderModel.Id, m_shaderModel.Id );
}
else
{
m_shaderModel.DataCheck = TemplateDataCheck.Invalid;
}
}
}
// ALL MODULES
int allModulesIndex = subBody.IndexOf( TemplatesManager.TemplateAllModulesTag );
if( allModulesIndex > 0 )
{
//ONLY REGISTER MISSING TAGS
ConfigureCommonTag( m_allModulesTag, propertyContainer, idManager, uniquePrefix, offsetIdx, subBody );
m_allModulesMode = true;
m_blendData.SetAllModulesDefault();
if( !m_alphaToMaskData.IsValid )
m_alphaToMaskData.SetAllModulesDefault();
if( !m_cullModeData.IsValid )
m_cullModeData.SetAllModulesDefault();
if( !m_colorMaskData.IsValid )
m_colorMaskData.SetAllModulesDefault();
if( !m_stencilData.IsValid )
m_stencilData.SetAllModulesDefault();
if( !m_depthData.IsValid )
m_depthData.SetAllModulesDefault();
if( !m_shaderModel.IsValid )
m_shaderModel.SetAllModulesDefault();
}
}
public void TestPropertyInternalName( string name, ref List<TemplateShaderPropertyData> availableShaderProperties, ref Dictionary<string, TemplateShaderPropertyData> duplicatesHelper )
{
if( !string.IsNullOrEmpty( name ) && !duplicatesHelper.ContainsKey( name ))
{
TemplateShaderPropertyData newData = new TemplateShaderPropertyData( -1, string.Empty, string.Empty, name, name, WirePortDataType.INT, PropertyType.Property,-1,-1 );
availableShaderProperties.Add( newData );
duplicatesHelper.Add( newData.PropertyName , newData );
}
}
public void RegisterInternalUnityInlines( ref List<TemplateShaderPropertyData> availableShaderProperties, ref Dictionary<string, TemplateShaderPropertyData> duplicatesHelper )
{
TestPropertyInternalName( m_depthData.ZWriteInlineValue, ref availableShaderProperties , ref duplicatesHelper);
TestPropertyInternalName( m_depthData.ZTestInlineValue, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_depthData.OffsetFactorInlineValue, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_depthData.OffsetUnitsInlineValue, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData.SourceFactorRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData.DestFactorRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData.SourceFactorAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData.DestFactorAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData.BlendOpRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData.BlendOpAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData1.SourceFactorRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData1.DestFactorRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData1.SourceFactorAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData1.DestFactorAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData1.BlendOpRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData1.BlendOpAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData2.SourceFactorRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData2.DestFactorRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData2.SourceFactorAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData2.DestFactorAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData2.BlendOpRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData2.BlendOpAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData3.SourceFactorRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData3.DestFactorRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData3.SourceFactorAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData3.DestFactorAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData3.BlendOpRGBInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_blendData3.BlendOpAlphaInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_alphaToMaskData.InlineData, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_stencilData.ReferenceInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_stencilData.ReadMaskInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_stencilData.WriteMaskInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_stencilData.ComparisonFrontInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_stencilData.PassFrontInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_stencilData.FailFrontInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_stencilData.ZFailFrontInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_stencilData.ComparisonBackInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_stencilData.PassBackInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_stencilData.FailBackInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_stencilData.ZFailBackInline, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_cullModeData.InlineData, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_colorMaskData.InlineData, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_colorMaskData1.InlineData, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_colorMaskData2.InlineData, ref availableShaderProperties, ref duplicatesHelper );
TestPropertyInternalName( m_colorMaskData3.InlineData, ref availableShaderProperties, ref duplicatesHelper );
}
public void SetPassUniqueNameIfUndefined( string value )
{
if( string.IsNullOrEmpty( m_passUniqueName ) )
m_passUniqueName = value;
}
public bool HasValidData
{
get
{
return m_blendData.DataCheck == TemplateDataCheck.Valid ||
m_blendData1.DataCheck == TemplateDataCheck.Valid ||
m_blendData2.DataCheck == TemplateDataCheck.Valid ||
m_blendData3.DataCheck == TemplateDataCheck.Valid ||
m_alphaToMaskData.DataCheck == TemplateDataCheck.Valid ||
m_cullModeData.DataCheck == TemplateDataCheck.Valid ||
m_colorMaskData.DataCheck == TemplateDataCheck.Valid ||
m_colorMaskData1.DataCheck == TemplateDataCheck.Valid ||
m_colorMaskData2.DataCheck == TemplateDataCheck.Valid ||
m_colorMaskData3.DataCheck == TemplateDataCheck.Valid ||
m_stencilData.DataCheck == TemplateDataCheck.Valid ||
m_depthData.DataCheck == TemplateDataCheck.Valid ||
m_tagData.DataCheck == TemplateDataCheck.Valid ||
m_shaderModel.DataCheck == TemplateDataCheck.Valid ||
m_globalsTag.IsValid ||
m_srpBatcherTag.IsValid ||
m_allModulesTag.IsValid ||
m_functionsTag.IsValid ||
m_pragmaTag.IsValid ||
m_pragmaBeforeTag.IsValid ||
m_passTag.IsValid ||
m_inputsVertTag.IsValid ||
m_inputsFragTag.IsValid;
}
}
public TemplateBlendData BlendData { get { return m_blendData; } }
public TemplateBlendData BlendData1 { get { return m_blendData1; } }
public TemplateBlendData BlendData2 { get { return m_blendData2; } }
public TemplateBlendData BlendData3 { get { return m_blendData3; } }
public TemplateAlphaToMaskData AlphaToMaskData { get { return m_alphaToMaskData; } }
public TemplateCullModeData CullModeData { get { return m_cullModeData; } }
public TemplateColorMaskData ColorMaskData { get { return m_colorMaskData; } }
public TemplateColorMaskData ColorMaskData1 { get { return m_colorMaskData1; } }
public TemplateColorMaskData ColorMaskData2 { get { return m_colorMaskData2; } }
public TemplateColorMaskData ColorMaskData3 { get { return m_colorMaskData3; } }
public TemplateStencilData StencilData { get { return m_stencilData; } }
public TemplateDepthData DepthData { get { return m_depthData; } }
public TemplateTagsModuleData TagData { get { return m_tagData; } }
public TemplateTagData GlobalsTag { get { return m_globalsTag; } }
public TemplateTagData SRPBatcherTag { get { return m_srpBatcherTag; } }
public TemplateTagData AllModulesTag { get { return m_allModulesTag; } }
public TemplateTagData FunctionsTag { get { return m_functionsTag; } }
public TemplateTagData PragmaTag { get { return m_pragmaTag; } }
public TemplateTagData PragmaBeforeTag { get { return m_pragmaBeforeTag; } }
public TemplateTagData PassTag { get { return m_passTag; } }
public TemplateTagData InputsVertTag { get { return m_inputsVertTag; } }
public TemplateTagData InputsFragTag { get { return m_inputsFragTag; } }
public TemplateShaderModelData ShaderModel { get { return m_shaderModel; } }
public TemplateSRPType SRPType { get { return m_srpType; } set { m_srpType = value; } }
public bool SRPIsPBR { get { return m_srpIsPBR; } set { m_srpIsPBR = value; } }
public bool SRPIsPBRHD { get { return m_srpIsPBR && m_srpType == TemplateSRPType.HD; } }
public string UniquePrefix { get { return m_uniquePrefix; } }
public string PassUniqueName { get { return m_passUniqueName; } }
public bool HasPassUniqueName { get { return !string.IsNullOrEmpty( m_passUniqueName ); } }
public TemplateIncludePragmaContainter IncludePragmaContainer { get { return m_includePragmaContainer; } }
public bool AllModulesMode { get { return m_allModulesMode; } }
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 122447ac2bc376a448a42a0f5373e63b
timeCreated: 1521718529
licenseType: Store
MonoImporter:
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,12 @@
fileFormatVersion: 2
guid: 4214390aa7f66364bbab454dc15a04ac
timeCreated: 1516981847
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

@@ -0,0 +1,328 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
[Serializable]
public class InputSwitchMPHelper
{
public int SubShaderIdx;
public int PassIdx;
public InputSwitchMPHelper( int subShaderIdx, int passIdx )
{
SubShaderIdx = subShaderIdx;
PassIdx = passIdx;
}
}
[Serializable]
[NodeAttributes( "Template Multi-Pass Switch", "Logical Operators", "Relays, in compile time, the correct input port according to current analyzed sub-shader/pass." )]
public sealed class TemplateMultiPassSwitchNode : TemplateNodeParent
{
private const string InputLabelStr = "SubShader {0} Pass {1}";
[SerializeField]
private List<InputSwitchMPHelper> m_inputHelper = new List<InputSwitchMPHelper>();
[SerializeField]
private int m_inputCountHelper = -1;
protected override void CommonInit( int uniqueId )
{
m_createAllOutputs = false;
base.CommonInit( uniqueId );
}
public override void OnInputPortConnected( int portId, int otherNodeId, int otherPortId, bool activateNode = true )
{
base.OnInputPortConnected( portId, otherNodeId, otherPortId, activateNode );
UpdateConnections();
}
public override void OnConnectedOutputNodeChanges( int inputPortId, int otherNodeId, int otherPortId, string name, WirePortDataType type )
{
base.OnConnectedOutputNodeChanges( inputPortId, otherNodeId, otherPortId, name, type );
UpdateConnections();
}
public override void OnInputPortDisconnected( int portId )
{
base.OnInputPortDisconnected( portId );
UpdateConnections();
}
private void UpdateConnections()
{
WirePortDataType mainType = WirePortDataType.FLOAT;
int highest = UIUtils.GetPriority( mainType );
for( int i = 0; i < m_inputPorts.Count; i++ )
{
if( m_inputPorts[ i ].IsConnected )
{
WirePortDataType portType = m_inputPorts[ i ].GetOutputConnection().DataType;
if( UIUtils.GetPriority( portType ) > highest )
{
mainType = portType;
highest = UIUtils.GetPriority( portType );
}
}
}
for( int i = 0; i < m_inputPorts.Count; i++ )
{
m_inputPorts[ i ].ChangeType( mainType, false );
}
m_outputPorts[ 0 ].ChangeType( mainType, false );
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if( m_templateMPData == null )
{
FetchMultiPassTemplate();
if( m_inputPorts.Count != m_inputCountHelper )
{
CreateInputPorts();
}
else
{
RefreshInputPorts();
}
}
}
public void RefreshInputPorts()
{
if( m_multiPassMode )
{
m_inputHelper.Clear();
if( m_templateMPData != null )
{
int index = 0;
int subShaderCount = m_templateMPData.SubShaders.Count;
for( int subShaderIdx = 0; subShaderIdx < subShaderCount; subShaderIdx++ )
{
int passCount = m_templateMPData.SubShaders[ subShaderIdx ].Passes.Count;
for( int passIdx = 0; passIdx < passCount; passIdx++ )
{
if( m_templateMPData.SubShaders[ subShaderIdx ].Passes[ passIdx ].HasValidFunctionBody )
{
m_inputPorts[ index ].Name = string.Format( InputLabelStr, subShaderIdx, passIdx );
m_inputHelper.Add( new InputSwitchMPHelper( subShaderIdx, passIdx ) );
index += 1;
}
}
}
}
}
else
{
m_inputPorts[0].Name = "In";
}
}
public int RefreshInputCountHelper()
{
int inputCountHelper = 0;
if( m_multiPassMode )
{
if( m_templateMPData != null )
{
int subShaderCount = m_templateMPData.SubShaders.Count;
for( int subShaderIdx = 0; subShaderIdx < subShaderCount; subShaderIdx++ )
{
int passCount = m_templateMPData.SubShaders[ subShaderIdx ].Passes.Count;
for( int passIdx = 0; passIdx < passCount; passIdx++ )
{
if( m_templateMPData.SubShaders[ subShaderIdx ].Passes[passIdx].HasValidFunctionBody )
inputCountHelper += 1;
}
}
}
}
else
{
inputCountHelper += 1;
}
return inputCountHelper;
}
public void CreateInputPorts()
{
m_inputCountHelper = 0;
DeleteAllInputConnections( true );
if( m_multiPassMode )
{
m_inputHelper.Clear();
if( m_templateMPData != null )
{
int subShaderCount = m_templateMPData.SubShaders.Count;
for( int subShaderIdx = 0; subShaderIdx < subShaderCount; subShaderIdx++ )
{
int passCount = m_templateMPData.SubShaders[ subShaderIdx ].Passes.Count;
for( int passIdx = 0; passIdx < passCount; passIdx++ )
{
if( m_templateMPData.SubShaders[ subShaderIdx ].Passes[ passIdx ].HasValidFunctionBody )
{
AddInputPort( WirePortDataType.FLOAT, false, string.Format( InputLabelStr, subShaderIdx, passIdx ) );
m_inputHelper.Add( new InputSwitchMPHelper( subShaderIdx, passIdx ) );
m_inputCountHelper += 1;
}
}
}
}
}
else
{
AddInputPort( WirePortDataType.FLOAT, false, "In" );
m_inputCountHelper += 1;
}
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if( dataCollector.MasterNodeCategory != AvailableShaderTypes.Template )
{
UIUtils.ShowMessage( "Template Multi-Pass Switch Data node is only intended for templates use only" );
return m_outputPorts[ 0 ].ErrorValue;
}
int currSubShaderIdx = dataCollector.TemplateDataCollectorInstance.MultipassSubshaderIdx;
int currPassIdx = dataCollector.TemplateDataCollectorInstance.MultipassPassIdx;
int inputHelperCount = m_inputHelper.Count;
for( int i = 0; i< inputHelperCount; i++ )
{
if(m_inputHelper[i].SubShaderIdx == currSubShaderIdx && m_inputHelper[ i ].PassIdx == currPassIdx )
return m_inputPorts[ i ].GeneratePortInstructions( ref dataCollector );
}
UIUtils.ShowMessage( "Invalid subshader or pass on Template Multi-Pass Switch Data" );
return m_outputPorts[ 0 ].ErrorValue;
}
public override void OnMasterNodeReplaced( MasterNode newMasterNode )
{
base.OnMasterNodeReplaced( newMasterNode );
if( newMasterNode.CurrentMasterNodeCategory == AvailableShaderTypes.Template )
{
FetchMultiPassTemplate( newMasterNode );
m_inputCountHelper = RefreshInputCountHelper();
if( m_inputPorts.Count != m_inputCountHelper )
{
CreateInputPorts();
}
else
{
RefreshInputPorts();
}
}
else
{
DeleteAllInputConnections( true );
}
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
m_inputCountHelper = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
// Need to add ports here so read internal data is correct
for( int i = 0; i < m_inputCountHelper; i++ )
{
AddInputPort( WirePortDataType.FLOAT, false, Constants.EmptyPortValue );
}
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_inputCountHelper );
}
public override void Destroy()
{
base.Destroy();
m_inputHelper.Clear();
m_inputHelper = null;
}
public override void RefreshExternalReferences()
{
base.RefreshExternalReferences();
FetchMultiPassTemplate();
bool create = false;
if( m_inputCountHelper == -1 )
{
create = true;
}
else
{
int newInputCount = RefreshInputCountHelper();
if( newInputCount != m_inputCountHelper )
{
create = true;
}
}
if( m_multiPassMode )
{
if( m_templateMPData != null )
{
if( create )
{
CreateInputPorts();
}
else
{
m_inputHelper.Clear();
int index = 0;
int subShaderCount = m_templateMPData.SubShaders.Count;
for( int subShaderIdx = 0; subShaderIdx < subShaderCount; subShaderIdx++ )
{
int passCount = m_templateMPData.SubShaders[ subShaderIdx ].Passes.Count;
for( int passIdx = 0; passIdx < passCount; passIdx++ )
{
if( m_templateMPData.SubShaders[ subShaderIdx ].Passes[ passIdx ].HasValidFunctionBody )
{
m_inputPorts[ index ].Name = string.Format( InputLabelStr, subShaderIdx, passIdx );
m_inputHelper.Add( new InputSwitchMPHelper( subShaderIdx, passIdx ));
index += 1;
}
}
}
if( index != m_inputCountHelper )
{
Debug.LogWarning( "Something wrong occured in reading MultiPass Switch node" );
}
}
}
}
else
{
if( create )
{
AddInputPort( WirePortDataType.FLOAT, false, "In" );
}
else
{
m_inputPorts[ 0 ].Name = "In";
}
}
}
}
}

View File

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

View File

@@ -0,0 +1,272 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateNodeParent : ParentNode
{
protected const string ErrorMessageStr = "This node can only be used inside a Template category!";
protected const string DataLabelStr = "Data";
protected const string SubShaderStr = "SubShader";
protected const string PassStr = "Pass";
[SerializeField]
private int m_subShaderIdx = 0;
[SerializeField]
private int m_passIdx = 0;
[SerializeField]
private int m_passLocalArrayIdx = 0;
[SerializeField]
protected bool m_multiPassMode = false;
[SerializeField]
protected string[] m_availableSubshaders;
[SerializeField]
protected string[] m_availablePassesLabels;
[SerializeField]
protected int[] m_availablePassesValues;
[NonSerialized]
protected TemplateMultiPass m_templateMPData = null;
protected bool m_createAllOutputs = true;
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
AddOutputPort( WirePortDataType.FLOAT, "Out" );
if( m_createAllOutputs )
{
AddOutputPort( WirePortDataType.FLOAT, "X" );
AddOutputPort( WirePortDataType.FLOAT, "Y" );
AddOutputPort( WirePortDataType.FLOAT, "Z" );
AddOutputPort( WirePortDataType.FLOAT, "W" );
}
m_textLabelWidth = 67;
m_hasLeftDropdown = true;
}
public override void AfterCommonInit()
{
base.AfterCommonInit();
if( PaddingTitleLeft == 0 )
{
PaddingTitleLeft = Constants.PropertyPickerWidth + Constants.IconsLeftRightMargin;
if( PaddingTitleRight == 0 )
PaddingTitleRight = Constants.PropertyPickerWidth + Constants.IconsLeftRightMargin;
}
}
protected void ConfigurePorts()
{
switch( m_outputPorts[ 0 ].DataType )
{
default:
{
for( int i = 1; i < 5; i++ )
{
m_outputPorts[ i ].Visible = false;
}
}
break;
case WirePortDataType.FLOAT2:
{
for( int i = 1; i < 5; i++ )
{
m_outputPorts[ i ].Visible = ( i < 3 );
if( m_outputPorts[ i ].Visible )
{
m_outputPorts[ i ].Name = Constants.ChannelNamesVector[ i - 1 ];
}
}
}
break;
case WirePortDataType.FLOAT3:
{
for( int i = 1; i < 5; i++ )
{
m_outputPorts[ i ].Visible = ( i < 4 );
if( m_outputPorts[ i ].Visible )
{
m_outputPorts[ i ].Name = Constants.ChannelNamesVector[ i - 1 ];
}
}
}
break;
case WirePortDataType.FLOAT4:
{
for( int i = 1; i < 5; i++ )
{
m_outputPorts[ i ].Visible = true;
m_outputPorts[ i ].Name = Constants.ChannelNamesVector[ i - 1 ];
}
}
break;
case WirePortDataType.COLOR:
{
for( int i = 1; i < 5; i++ )
{
m_outputPorts[ i ].Visible = true;
m_outputPorts[ i ].Name = Constants.ChannelNamesColor[ i - 1 ];
}
}
break;
}
m_sizeIsDirty = true;
}
protected virtual void OnSubShaderChange() { }
protected virtual void OnPassChange() { }
protected void DrawSubShaderUI()
{
EditorGUI.BeginChangeCheck();
m_subShaderIdx = EditorGUILayoutPopup( SubShaderStr, m_subShaderIdx, m_availableSubshaders );
if( EditorGUI.EndChangeCheck() )
{
//UpdateSubShaderAmount();
UpdatePassAmount();
OnSubShaderChange();
}
}
protected void DrawPassUI()
{
EditorGUI.BeginChangeCheck();
m_passLocalArrayIdx = EditorGUILayoutPopup( PassStr, m_passLocalArrayIdx, m_availablePassesLabels );
if( EditorGUI.EndChangeCheck() )
{
m_passIdx = m_availablePassesValues[ m_passLocalArrayIdx ];
//UpdatePassAmount();
OnPassChange();
}
}
virtual protected void CheckWarningState()
{
if( m_containerGraph.CurrentCanvasMode != NodeAvailability.TemplateShader )
{
ShowTab( NodeMessageType.Error, ErrorMessageStr );
}
else
{
m_showErrorMessage = false;
}
}
protected void FetchMultiPassTemplate( MasterNode masterNode = null )
{
m_multiPassMode = m_containerGraph.MultiPassMasterNodes.NodesList.Count > 0;
if( m_multiPassMode )
{
m_templateMPData = ( ( ( masterNode == null ) ? m_containerGraph.CurrentMasterNode : masterNode ) as TemplateMultiPassMasterNode ).CurrentTemplate;
if( m_templateMPData != null )
{
UpdateSubShaderAmount();
}
}
}
protected void UpdateSubShaderAmount()
{
if( m_templateMPData == null )
m_templateMPData = ( m_containerGraph.CurrentMasterNode as TemplateMultiPassMasterNode ).CurrentTemplate;
if( m_templateMPData != null )
{
int subShaderCount = m_templateMPData.SubShaders.Count;
if( m_availableSubshaders == null || subShaderCount != m_availableSubshaders.Length )
{
m_availableSubshaders = new string[ subShaderCount ];
for( int i = 0; i < subShaderCount; i++ )
{
m_availableSubshaders[ i ] = i.ToString();
}
}
m_subShaderIdx = Mathf.Min( m_subShaderIdx, subShaderCount - 1 );
UpdatePassAmount();
}
}
protected virtual bool ValidatePass( int passIdx ) { return true; }
protected void UpdatePassAmount()
{
if( !m_multiPassMode )
return;
if( m_templateMPData == null )
m_templateMPData = ( m_containerGraph.CurrentMasterNode as TemplateMultiPassMasterNode ).CurrentTemplate;
List<string> passLabels = new List<string>();
List<int> passValues = new List<int>();
int minPassIdx = int.MaxValue;
int passCount = m_templateMPData.SubShaders[ m_subShaderIdx ].Passes.Count;
bool resetPassIdx = true;
for( int i = 0; i < passCount; i++ )
{
if( ValidatePass( i ) )
{
passLabels.Add( i.ToString() );
passValues.Add( i );
minPassIdx = Mathf.Min( minPassIdx, i );
if( m_passIdx == i )
resetPassIdx = false;
}
}
m_availablePassesLabels = passLabels.ToArray();
m_availablePassesValues = passValues.ToArray();
if( resetPassIdx )
m_passIdx = minPassIdx;
RefreshPassLocalArrayIdx();
}
void RefreshPassLocalArrayIdx( )
{
for( int i = 0; i < m_availablePassesValues.Length; i++ )
{
if( m_availablePassesValues[ i ] == m_passIdx )
{
m_passLocalArrayIdx = i;
}
}
}
public override void Destroy()
{
base.Destroy();
m_templateMPData = null;
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
m_subShaderIdx = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
m_passIdx = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
}
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_subShaderIdx );
IOUtils.AddFieldValueToString( ref nodeInfo, m_passIdx );
}
public int SubShaderIdx { get { return m_subShaderIdx; } set { m_subShaderIdx = value; } }
public int PassIdx { get { return m_passIdx; } set { m_passIdx = value; } }
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b21cb297a12ef0a4281213619e3e76bf
timeCreated: 1519235586
licenseType: Store
MonoImporter:
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,12 @@
fileFormatVersion: 2
guid: 019dfacde4ed75a41851c7f15f69963f
timeCreated: 1533143812
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,69 @@
using UnityEngine;
using System;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateOptionsDefinesContainer
{
[SerializeField]
private List<PropertyDataCollector> m_definesList = new List<PropertyDataCollector>();
[NonSerialized]
private Dictionary<string, PropertyDataCollector> m_definesDict = new Dictionary<string, PropertyDataCollector>();
void Refresh()
{
if( m_definesDict.Count != m_definesList.Count )
{
m_definesDict.Clear();
for( int i = 0; i < m_definesList.Count; i++ )
{
m_definesDict.Add( m_definesList[ i ].PropertyName, m_definesList[ i ] );
}
}
}
public void RemoveTemporaries()
{
List<PropertyDataCollector> temporaries = m_definesList.FindAll( ( x ) => ( x.NodeId == 1 ) );
for( int i = 0; i < temporaries.Count; i++ )
{
m_definesList.Remove( temporaries[ i ] );
m_definesDict.Remove( temporaries[ i ].PropertyName );
}
}
public void AddDefine( string define , bool temporary )
{
Refresh();
if( !m_definesDict.ContainsKey( define ) )
{
int nodeId = temporary ? 1 : 0;
PropertyDataCollector data = new PropertyDataCollector( nodeId, define );
m_definesDict.Add( define, data );
m_definesList.Add( data );
}
}
public void RemoveDefine( string define )
{
Refresh();
if( m_definesDict.ContainsKey( define ) )
{
m_definesList.Remove( m_definesDict[define] );
m_definesDict.Remove( define );
}
}
public void Destroy()
{
m_definesDict.Clear();
m_definesDict = null;
m_definesList.Clear();
m_definesList = null;
}
public List<PropertyDataCollector> DefinesList { get { return m_definesList; } }
}
}

View File

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

View File

@@ -0,0 +1,174 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using UnityEngine;
namespace AmplifyShaderEditor
{
// PORT CONTROLLERS
[Serializable]
public class TemplateOptionPortItem
{
[SerializeField]
private int m_portId = -1;
[SerializeField]
private TemplateOptionsItem m_options;
public TemplateOptionPortItem( TemplateMultiPassMasterNode owner, TemplateOptionsItem options )
{
m_options = options;
InputPort port = owner.InputPorts.Find( x => x.Name.Equals( options.Name ) );
if( port != null )
{
m_portId = port.PortId;
}
}
public void FillDataCollector( TemplateMultiPassMasterNode owner, ref MasterNodeDataCollector dataCollector )
{
InputPort port = null;
if( m_portId > -1 )
{
port = owner.GetInputPortByUniqueId( m_portId );
}
else
{
port = owner.InputPorts.Find( x => x.Name.Equals( m_options.Name ) );
}
if( port != null )
{
int optionId = port.HasOwnOrLinkConnection ? 0 : 1;
for( int i = 0; i < m_options.ActionsPerOption[ optionId ].Length; i++ )
{
switch( m_options.ActionsPerOption[ optionId ][ i ].ActionType )
{
case AseOptionsActionType.SetDefine:
{
List<TemplateMultiPassMasterNode> nodes = owner.ContainerGraph.GetMultiPassMasterNodes( owner.LODIndex );
int count = nodes.Count;
for( int nodeIdx = 0; nodeIdx < count; nodeIdx++ )
{
nodes[ nodeIdx ].OptionsDefineContainer.AddDefine( "#define "+m_options.ActionsPerOption[ optionId ][ i ].ActionData, false );
}
//dataCollector.AddToDefines( -1, m_options.ActionsPerOption[ optionId ][ i ].ActionData );
}
break;
case AseOptionsActionType.SetUndefine:
{
List<TemplateMultiPassMasterNode> nodes = owner.ContainerGraph.GetMultiPassMasterNodes( owner.LODIndex );
int count = nodes.Count;
for( int nodeIdx = 0; nodeIdx < count; nodeIdx++ )
{
nodes[ nodeIdx ].OptionsDefineContainer.AddDefine( "#undef " + m_options.ActionsPerOption[ optionId ][ i ].ActionData, false );
}
//dataCollector.AddToDefines( -1, m_options.ActionsPerOption[ optionId ][ i ].ActionData, false );
}
break;
case AseOptionsActionType.SetShaderProperty:
{
TemplateShaderPropertyData data = owner.CurrentTemplate.GetShaderPropertyData( m_options.ActionsPerOption[ optionId ][ i ].ActionData );
if( data != null )
{
string newPropertyValue = data.CreatePropertyForValue( m_options.ActionsPerOption[ optionId ][ i ].ActionBuffer );
owner.CurrentTemplate.IdManager.SetReplacementText( data.FullValue, newPropertyValue );
}
}
break;
}
}
}
}
public void SubShaderFillDataCollector( TemplateMultiPassMasterNode owner, ref MasterNodeDataCollector dataCollector )
{
//TemplateMultiPassMasterNode targetNode = string.IsNullOrEmpty(m_options.Id) ? owner:owner.ContainerGraph.GetMasterNodeOfPass( m_options.Id , owner.LODIndex );
TemplateMultiPassMasterNode targetNode = string.IsNullOrEmpty( m_options.Id ) ?
owner.ContainerGraph.GetMainMasterNodeOfLOD( owner.LODIndex ) :
owner.ContainerGraph.GetMasterNodeOfPass( m_options.Id , owner.LODIndex );
InputPort port = null;
if( m_portId > -1 )
{
port = targetNode.GetInputPortByUniqueId( m_portId );
}
else
{
port = targetNode.InputPorts.Find( x => x.Name.Equals( m_options.Name ) );
}
if( port != null )
{
int optionId = port.HasOwnOrLinkConnection ? 0 : 1;
for( int i = 0; i < m_options.ActionsPerOption[ optionId ].Length; i++ )
{
if( string.IsNullOrEmpty( m_options.ActionsPerOption[ optionId ][ i ].PassName ) ||
m_options.ActionsPerOption[ optionId ][ i ].PassName.Equals( owner.PassName ) )
{
switch( m_options.ActionsPerOption[ optionId ][ i ].ActionType )
{
case AseOptionsActionType.SetDefine:
{
owner.OptionsDefineContainer.AddDefine( "#define " + m_options.ActionsPerOption[ optionId ][ i ].ActionData, true );
}
break;
case AseOptionsActionType.SetUndefine:
{
owner.OptionsDefineContainer.AddDefine( "#undef " + m_options.ActionsPerOption[ optionId ][ i ].ActionData, true );
}
break;
case AseOptionsActionType.SetShaderProperty:
{
TemplateShaderPropertyData data = owner.CurrentTemplate.GetShaderPropertyData( m_options.ActionsPerOption[ optionId ][ i ].ActionData );
if( data != null )
{
string newPropertyValue = data.CreatePropertyForValue( m_options.ActionsPerOption[ optionId ][ i ].ActionBuffer );
owner.CurrentTemplate.IdManager.SetReplacementText( data.FullValue, newPropertyValue );
}
}
break;
}
}
}
}
}
public void CheckImediateActionsForPort( TemplateMultiPassMasterNode owner, int portId )
{
if( portId != m_portId )
return;
InputPort port = null;
if( m_portId > -1 )
{
port = owner.GetInputPortByUniqueId( m_portId );
}
else
{
port = owner.InputPorts.Find( x => x.Name.Equals( m_options.Name ) );
}
if( port != null )
{
int optionId = port.HasOwnOrLinkConnection ? 0 : 1;
for( int i = 0; i < m_options.ActionsPerOption[ optionId ].Length; i++ )
{
switch( m_options.ActionsPerOption[ optionId ][ i ].ActionType )
{
case AseOptionsActionType.SetPortName:
{
port.Name = m_options.ActionsPerOption[ optionId ][ i ].ActionData;
owner.SizeIsDirty = true;
}
break;
}
}
}
}
public TemplateOptionsItem Options { get { return m_options; } }
}
}

View File

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

View File

@@ -0,0 +1,323 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
// UI STRUCTURES
[Serializable]
public class TemplateOptionUIItem
{
public delegate void OnActionPerformed( bool actionFromUser, bool isRefreshing, bool invertAction, TemplateOptionUIItem uiItem, params TemplateActionItem[] validActions );
public event OnActionPerformed OnActionPerformedEvt;
[SerializeField]
private bool m_isVisible = true;
[SerializeField]
private bool m_wasVisible = true;
[SerializeField]
private int m_currentOption = 0;
[SerializeField]
private TemplateOptionsItem m_options;
[SerializeField]
private bool m_checkOnExecute = false;
[SerializeField]
private bool m_invertActionOnDeselection = false;
public TemplateOptionUIItem( TemplateOptionsItem options )
{
m_options = options;
if( m_options.Type == AseOptionsType.Field )
{
m_options.FieldValue.FloatValue = m_options.DefaultFieldValue;
}
else
{
m_currentOption = m_options.DefaultOptionIndex;
}
m_invertActionOnDeselection = options.Setup == AseOptionItemSetup.InvertActionOnDeselection;
}
public void CopyValuesFrom( TemplateOptionUIItem origin )
{
m_isVisible = origin.IsVisible;
m_wasVisible = origin.WasVisible;
m_currentOption = origin.CurrentOption;
m_options.FieldValue.FloatValue = origin.CurrentFieldValue;
m_checkOnExecute = origin.CheckOnExecute;
m_invertActionOnDeselection = origin.InvertActionOnDeselection;
}
public void Draw( UndoParentNode owner )
{
if( m_isVisible )
{
int lastOption = m_currentOption;
EditorGUI.BeginChangeCheck();
switch( m_options.UIWidget )
{
case AseOptionsUIWidget.Dropdown:
{
m_currentOption = owner.EditorGUILayoutPopup( m_options.Name, m_currentOption, m_options.DisplayOptions );
}
break;
case AseOptionsUIWidget.Toggle:
{
m_currentOption = owner.EditorGUILayoutToggle( m_options.Name, m_currentOption == 1 ) ? 1 : 0;
}
break;
case AseOptionsUIWidget.Float:
{
if( m_options.FieldInline )
{
m_options.FieldValue.FloatField( ref owner, m_options.Name );
if( m_options.FieldValue.Active )
m_currentOption = 1;
else
m_currentOption = 0;
}
else
{
m_options.FieldValue.FloatValue = owner.EditorGUILayoutFloatField( m_options.Name, m_options.FieldValue.FloatValue );
}
}
break;
case AseOptionsUIWidget.Int:
{
if( m_options.FieldInline )
{
m_options.FieldValue.IntField( ref owner, m_options.Name );
if( m_options.FieldValue.Active )
m_currentOption = 1;
else
m_currentOption = 0;
}
else
m_options.FieldValue.FloatValue = owner.EditorGUILayoutIntField( m_options.Name, (int)m_options.FieldValue.FloatValue );
}
break;
case AseOptionsUIWidget.FloatRange:
{
if( m_options.FieldInline )
{
m_options.FieldValue.SliderField( ref owner, m_options.Name, m_options.FieldMin, m_options.FieldMax );
if( m_options.FieldValue.Active )
m_currentOption = 1;
else
m_currentOption = 0;
}
else
m_options.FieldValue.FloatValue = owner.EditorGUILayoutSlider( m_options.Name, m_options.FieldValue.FloatValue, m_options.FieldMin, m_options.FieldMax );
}
break;
case AseOptionsUIWidget.IntRange:
{
if( m_options.FieldInline )
{
m_options.FieldValue.IntSlider( ref owner, m_options.Name, (int)m_options.FieldMin, (int)m_options.FieldMax );
if( m_options.FieldValue.Active )
m_currentOption = 1;
else
m_currentOption = 0;
}
else
m_options.FieldValue.FloatValue = owner.EditorGUILayoutIntSlider( m_options.Name, (int)m_options.FieldValue.FloatValue, (int)m_options.FieldMin, (int)m_options.FieldMax );
}
break;
}
if( EditorGUI.EndChangeCheck() )
{
if( OnActionPerformedEvt != null )
{
if( m_invertActionOnDeselection )
OnActionPerformedEvt( true, false, lastOption != m_options.DisableIdx, this, m_options.ActionsPerOption[ lastOption ] );
OnActionPerformedEvt( true, false, false, this, m_options.ActionsPerOption[ m_currentOption ] );
}
}
}
}
public void CheckEnDisable( bool actionFromUser )
{
//string deb = string.Empty;// "-- Checked --" + m_options.Name+" "+ m_isVisible + " "+ m_wasVisible;
if( m_isVisible )
{
if( !m_wasVisible )
{
//deb = "-- Enable --" + m_options.Name;
//Debug.Log( deb );
if( OnActionPerformedEvt != null )
{
if( m_invertActionOnDeselection )
{
for( int i = 0; i < m_options.Count; i++ )
{
if( i != m_currentOption && i != m_options.DisableIdx )
{
OnActionPerformedEvt( actionFromUser, false, true, this, m_options.ActionsPerOption[ i ] );
}
}
}
OnActionPerformedEvt( actionFromUser, false, false, this, m_options.ActionsPerOption[ m_currentOption ] );
//if( !m_isVisible )
//OnActionPerformedEvt( isRefreshing, false, this, m_options.ActionsPerOption[ m_options.DisableIdx ] );
}
}
m_wasVisible = true;
}
else if( m_wasVisible )
{
//deb = "-- Disable --" + m_options.Name;
//Debug.Log( deb );
m_wasVisible = false;
if( OnActionPerformedEvt != null )
{
OnActionPerformedEvt( actionFromUser, false, false, this, m_options.ActionsPerOption[ m_options.DisableIdx ] );
}
}
}
public void FillDataCollector( ref MasterNodeDataCollector dataCollector )
{
if( m_isVisible && m_checkOnExecute )
{
for( int i = 0; i < m_options.ActionsPerOption[ m_currentOption ].Length; i++ )
{
switch( m_options.ActionsPerOption[ m_currentOption ][ i ].ActionType )
{
case AseOptionsActionType.SetDefine:
{
dataCollector.AddToDefines( -1, m_options.ActionsPerOption[ m_currentOption ][ i ].ActionData );
}
break;
case AseOptionsActionType.SetUndefine:
{
dataCollector.AddToDefines( -1, m_options.ActionsPerOption[ m_currentOption ][ i ].ActionData, false );
}
break;
}
}
}
}
public void Refresh()
{
if( OnActionPerformedEvt != null )
{
if( m_invertActionOnDeselection )
{
for( int i = 0; i < m_options.Count; i++ )
{
if( i != m_currentOption && i != m_options.DisableIdx )
{
OnActionPerformedEvt( false, true, true, this, m_options.ActionsPerOption[ i ] );
}
}
}
OnActionPerformedEvt( false, true, false, this, m_options.ActionsPerOption[ m_currentOption ] );
}
}
public TemplateOptionsItem Options { get { return m_options; } }
public void Destroy()
{
OnActionPerformedEvt = null;
}
public bool IsVisible
{
get { return m_isVisible; }
set { m_isVisible = value; }
}
public bool WasVisible
{
get { return m_wasVisible; }
set { m_wasVisible = value; }
}
public bool CheckOnExecute
{
get { return m_checkOnExecute; }
set { m_checkOnExecute = value; }
}
public InlineProperty FieldValue
{
get { return m_options.FieldValue; }
set { m_options.FieldValue = value; }
}
public float CurrentFieldValue
{
get { return m_options.FieldValue.FloatValue; }
set { m_options.FieldValue.FloatValue = value; }
}
public int CurrentOption
{
get { return m_currentOption; }
set
{
m_currentOption = Mathf.Clamp( value, 0, m_options.Options.Length - 1 );
// why refreshing here?
//Refresh();
}
}
public int CurrentOptionIdx
{
set
{
m_currentOption = Mathf.Clamp( value, 0, m_options.Options.Length - 1 );
}
}
public bool EmptyEvent { get { return OnActionPerformedEvt == null; } }
public TemplateActionItemGrid.TemplateActionItemRow CurrentOptionActions
{
get
{
if( m_options.Type == AseOptionsType.Field &&
m_currentOption == 1 )
{
if( m_options.FieldValue.NodeId < -1 )
{
//This is quite the hack. The bug is related to if a user chooses an inline property on the field option, then the behavior is to comment the original property set on the template
// The problem is that, if the user sets an inline property and select its own internal property from there, then the behavior that will prevail without this hack is to call the actions associated with setting a new inline property
// Which is on all templates to comment the original template internal property leaving the property commented on the final code (This was detected on URP PBR)
PropertyNode node = UIUtils.CurrentWindow.OutsideGraph.GetInternalTemplateNode( m_options.FieldValue.NodeId ) as PropertyNode;
if( node != null )
{
if( node.PropertyName.Equals( m_options.FieldInlineName ) )
{
return m_options.ActionsPerOption.Rows[ 0 ];
}
}
}
else if( m_options.FieldValue.NodeId == -1 )
{
// If node id is -1 then no node is selected on the inline dropdown then we should also fallback to using its internal property
return m_options.ActionsPerOption.Rows[ 0 ];
}
}
return m_options.ActionsPerOption.Rows[m_currentOption];
}
}
public bool InvertActionOnDeselection { get { return m_invertActionOnDeselection; } }
}
}

View File

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

View File

@@ -0,0 +1,869 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateOptionsUIHelper
{
private const string CustomOptionsLabel = " Custom Options";
private bool m_isSubShader = false;
[SerializeField]
private bool m_passCustomOptionsFoldout = true;
[SerializeField]
private string m_passCustomOptionsLabel = CustomOptionsLabel;
[SerializeField]
private int m_passCustomOptionsSizeCheck = 0;
[SerializeField]
private List<TemplateOptionUIItem> m_passCustomOptionsUI = new List<TemplateOptionUIItem>();
[NonSerialized]
private Dictionary<string, TemplateOptionUIItem> m_passCustomOptionsUIDict = new Dictionary<string, TemplateOptionUIItem>();
[NonSerialized]
private TemplateMultiPassMasterNode m_owner;
[NonSerialized]
private string[] m_readOptionNames;
[NonSerialized]
private string[] m_readOptionSelections;
[SerializeField]
private List<TemplateOptionPortItem> m_passCustomOptionsPorts = new List<TemplateOptionPortItem>();
public TemplateOptionsUIHelper( bool isSubShader )
{
m_isSubShader = isSubShader;
}
public void CopyOptionsValuesFrom( TemplateOptionsUIHelper origin )
{
for( int i = 0; i < origin.PassCustomOptionsUI.Count; i++ )
{
m_passCustomOptionsUI[ i ].CopyValuesFrom( origin.PassCustomOptionsUI[ i ] );
}
}
public void Destroy()
{
for( int i = 0; i < m_passCustomOptionsUI.Count; i++ )
{
m_passCustomOptionsUI[ i ].Destroy();
}
m_passCustomOptionsUI.Clear();
m_passCustomOptionsUI = null;
m_passCustomOptionsUIDict.Clear();
m_passCustomOptionsUIDict = null;
m_passCustomOptionsPorts.Clear();
m_passCustomOptionsPorts = null;
}
public void DrawCustomOptions( TemplateMultiPassMasterNode owner )
{
m_owner = owner;
if( m_passCustomOptionsUI.Count > 0 )
{
NodeUtils.DrawNestedPropertyGroup( ref m_passCustomOptionsFoldout, m_passCustomOptionsLabel, DrawCustomOptionsBlock );
}
}
public void DrawCustomOptionsBlock()
{
float currWidth = EditorGUIUtility.labelWidth;
#if UNITY_2019_3_OR_NEWER
float size = Mathf.Max( UIUtils.CurrentWindow.ParametersWindow.TransformedArea.width * 0.385f, 0 );
#else
float size = Mathf.Max( UIUtils.CurrentWindow.ParametersWindow.TransformedArea.width * 0.34f, 0 );
#endif
EditorGUIUtility.labelWidth = size;
for( int i = 0; i < m_passCustomOptionsUI.Count; i++ )
{
m_passCustomOptionsUI[ i ].Draw( m_owner );
}
EditorGUILayout.Space();
EditorGUIUtility.labelWidth = currWidth;
}
public void OnCustomOptionSelected( bool actionFromUser, bool isRefreshing, bool invertAction, TemplateMultiPassMasterNode owner, TemplateOptionUIItem uiItem, params TemplateActionItem[] validActions )
{
uiItem.CheckOnExecute = false;
for( int i = 0; i < validActions.Length; i++ )
{
AseOptionsActionType actionType = validActions[ i ].ActionType;
if( invertAction )
{
if( !TemplateOptionsToolsHelper.InvertAction( validActions[ i ].ActionType, ref actionType ) )
{
continue;
}
}
switch( actionType )
{
case AseOptionsActionType.ShowOption:
{
TemplateOptionUIItem item = m_passCustomOptionsUI.Find( x => ( x.Options.Name.Equals( validActions[ i ].ActionData ) ) );
if( item != null )
{
if( isRefreshing )
{
string optionId = validActions[ i ].PassName + validActions[ i ].ActionData + "Option";
owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( optionId, true );
}
// this prevents options from showing up when loading by checking if they were hidden by another option
// it works on the assumption that an option that may possible hide this one is checked first
if( !isRefreshing )
item.IsVisible = true;
else if( item.WasVisible )
item.IsVisible = true;
if( !invertAction && validActions[ i ].ActionDataIdx > -1 )
item.CurrentOption = validActions[ i ].ActionDataIdx;
item.CheckEnDisable( actionFromUser );
}
else
{
Debug.LogFormat( "Could not find Option {0} for action {1}", validActions[ i ].ActionData, validActions[ i ].ActionType );
}
}
break;
case AseOptionsActionType.HideOption:
{
TemplateOptionUIItem item = m_passCustomOptionsUI.Find( x => ( x.Options.Name.Equals( validActions[ i ].ActionData ) ) );
if( item != null )
{
bool flag = false;
if( isRefreshing )
{
string optionId = validActions[ i ].PassName + validActions[ i ].ActionData + "Option";
flag = owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( optionId, false );
}
item.IsVisible = false || flag;
if( !invertAction && validActions[ i ].ActionDataIdx > -1 )
item.CurrentOption = validActions[ i ].ActionDataIdx;
item.CheckEnDisable( actionFromUser );
}
else
{
Debug.LogFormat( "Could not find Option {0} for action {1}", validActions[ i ].ActionData, validActions[ i ].ActionType );
}
}
break;
case AseOptionsActionType.SetOption:
{
if( !uiItem.IsVisible )
break;
TemplateOptionUIItem item = m_passCustomOptionsUI.Find( x => ( x.Options.Name.Equals( validActions[ i ].ActionData ) ) );
if( item != null )
{
item.CurrentOption = validActions[ i ].ActionDataIdx;
item.Refresh();
}
else
{
Debug.LogFormat( "Could not find Option {0} for action {1}", validActions[ i ].ActionData, validActions[ i ].ActionType );
}
}
break;
case AseOptionsActionType.HidePort:
{
TemplateMultiPassMasterNode passMasterNode = owner;
if( !string.IsNullOrEmpty( validActions[ i ].PassName ) )
{
passMasterNode = owner.ContainerGraph.GetMasterNodeOfPass( validActions[ i ].PassName,owner.LODIndex );
}
if( passMasterNode != null )
{
InputPort port = validActions[ i ].ActionDataIdx > -1 ?
passMasterNode.GetInputPortByUniqueId( validActions[ i ].ActionDataIdx ) :
passMasterNode.InputPorts.Find( x => x.Name.Equals( validActions[ i ].ActionData ) );
if( port != null )
{
if( isRefreshing )
{
string optionId = validActions[ i ].PassName + port.Name;
owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( optionId, port.IsConnected );
port.Visible = port.IsConnected;
}
else
{
port.Visible = false;
}
passMasterNode.SizeIsDirty = true;
}
else
{
Debug.LogFormat( "Could not find port {0},{1} for action {2}", validActions[ i ].ActionDataIdx, validActions[ i ].ActionData, validActions[ i ].ActionType );
}
}
else
{
Debug.LogFormat( "Could not find pass {0} for action {1} on {2}", validActions[ i ].PassName, validActions[ i ].ActionType, validActions[ i ].ActionData );
}
}
break;
case AseOptionsActionType.ShowPort:
{
if( !uiItem.IsVisible )
break;
TemplateMultiPassMasterNode passMasterNode = owner;
if( !string.IsNullOrEmpty( validActions[ i ].PassName ) )
{
passMasterNode = owner.ContainerGraph.GetMasterNodeOfPass( validActions[ i ].PassName, owner.LODIndex );
}
if( passMasterNode != null )
{
InputPort port = validActions[ i ].ActionDataIdx > -1 ?
passMasterNode.GetInputPortByUniqueId( validActions[ i ].ActionDataIdx ) :
passMasterNode.InputPorts.Find( x => x.Name.Equals( validActions[ i ].ActionData ) );
if( port != null )
{
if( isRefreshing )
{
string optionId = validActions[ i ].PassName + port.Name;
owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( optionId, true );
}
port.Visible = true;
passMasterNode.SizeIsDirty = true;
}
else
{
Debug.LogFormat( "Could not find port {0},{1} for action {2}", validActions[ i ].ActionDataIdx, validActions[ i ].ActionData, validActions[ i ].ActionType );
}
}
else
{
Debug.LogFormat( "Could not find pass {0} for action {1} on {2}", validActions[ i ].PassName, validActions[ i ].ActionType, validActions[ i ].ActionData );
}
}
break;
case AseOptionsActionType.SetPortName:
{
if( !uiItem.IsVisible )
break;
TemplateMultiPassMasterNode passMasterNode = owner;
if( !string.IsNullOrEmpty( validActions[ i ].PassName ) )
{
passMasterNode = owner.ContainerGraph.GetMasterNodeOfPass( validActions[ i ].PassName, owner.LODIndex );
}
if( passMasterNode != null )
{
InputPort port = passMasterNode.GetInputPortByUniqueId( validActions[ i ].ActionDataIdx );
if( port != null )
{
port.Name = validActions[ i ].ActionData;
passMasterNode.SizeIsDirty = true;
}
else
{
Debug.LogFormat( "Could not find port {0},{1} for action {2}", validActions[ i ].ActionDataIdx, validActions[ i ].ActionData, validActions[ i ].ActionType );
}
}
else
{
Debug.LogFormat( "Could not find pass {0} for action {1} on {2}", validActions[ i ].PassName, validActions[ i ].ActionType, validActions[ i ].ActionData );
}
}
break;
case AseOptionsActionType.SetDefine:
{
if( !uiItem.IsVisible )
{
uiItem.CheckOnExecute = true;
break;
}
//Debug.Log( "DEFINE " + validActions[ i ].ActionData );
if( validActions[ i ].AllPasses )
{
string actionData = validActions[ i ].ActionData;
string defineValue = string.Empty;
if( actionData.StartsWith( "pragma" ) )
{
defineValue = "#" + actionData;
}
else
{
defineValue = "#define " + validActions[ i ].ActionData;
}
if( isRefreshing )
{
owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( defineValue, true );
}
List<TemplateMultiPassMasterNode> nodes = owner.ContainerGraph.GetMultiPassMasterNodes( owner.LODIndex );
int count = nodes.Count;
for( int nodeIdx = 0; nodeIdx < count; nodeIdx++ )
{
nodes[ nodeIdx ].OptionsDefineContainer.AddDefine( defineValue, false );
}
}
else if( !string.IsNullOrEmpty( validActions[ i ].PassName ) )
{
TemplateMultiPassMasterNode passMasterNode = owner.ContainerGraph.GetMasterNodeOfPass( validActions[ i ].PassName, owner.LODIndex );
if( passMasterNode != null )
{
string actionData = validActions[ i ].ActionData;
string defineValue = string.Empty;
if( actionData.StartsWith( "pragma" ) )
{
defineValue = "#" + actionData;
}
else
{
defineValue = "#define " + validActions[ i ].ActionData;
}
if( isRefreshing )
{
string optionsId = validActions[ i ].PassName + defineValue;
owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( optionsId, true );
}
passMasterNode.OptionsDefineContainer.AddDefine( defineValue, false );
}
else
{
Debug.LogFormat( "Could not find pass {0} for action {1} on {2}", validActions[ i ].PassName, validActions[ i ].ActionType, validActions[ i ].ActionData );
}
}
else
{
uiItem.CheckOnExecute = true;
}
}
break;
case AseOptionsActionType.RemoveDefine:
{
//Debug.Log( "UNDEFINE " + validActions[ i ].ActionData );
if( validActions[ i ].AllPasses )
{
string actionData = validActions[ i ].ActionData;
string defineValue = string.Empty;
if( actionData.StartsWith( "pragma" ) )
{
defineValue = "#" + actionData;
}
else
{
defineValue = "#define " + validActions[ i ].ActionData;
}
bool flag = false;
if( isRefreshing )
{
flag = owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( defineValue, false );
}
if( !flag )
{
List<TemplateMultiPassMasterNode> nodes = owner.ContainerGraph.GetMultiPassMasterNodes( owner.LODIndex );
int count = nodes.Count;
for( int nodeIdx = 0; nodeIdx < count; nodeIdx++ )
{
nodes[ nodeIdx ].OptionsDefineContainer.RemoveDefine( defineValue );
}
}
}
else if( !string.IsNullOrEmpty( validActions[ i ].PassName ) )
{
TemplateMultiPassMasterNode passMasterNode = owner.ContainerGraph.GetMasterNodeOfPass( validActions[ i ].PassName, owner.LODIndex );
if( passMasterNode != null )
{
string actionData = validActions[ i ].ActionData;
string defineValue = string.Empty;
if( actionData.StartsWith( "pragma" ) )
{
defineValue = "#" + actionData;
}
else
{
defineValue = "#define " + validActions[ i ].ActionData;
}
bool flag = false;
if( isRefreshing )
{
string optionId = validActions[ i ].PassName + defineValue;
flag = owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( optionId, false );
}
if( !flag )
{
passMasterNode.OptionsDefineContainer.RemoveDefine( defineValue );
}
}
else
{
Debug.LogFormat( "Could not find pass {0} for action {1} on {2}", validActions[ i ].PassName, validActions[ i ].ActionType, validActions[ i ].ActionData );
}
}
else
{
uiItem.CheckOnExecute = false;
}
}
break;
case AseOptionsActionType.SetUndefine:
{
if( !uiItem.IsVisible )
{
uiItem.CheckOnExecute = true;
break;
}
if( validActions[ i ].AllPasses )
{
string defineValue = "#undef " + validActions[ i ].ActionData;
if( isRefreshing )
{
owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( defineValue, true );
}
List<TemplateMultiPassMasterNode> nodes = owner.ContainerGraph.GetMultiPassMasterNodes(owner.LODIndex);
int count = nodes.Count;
for( int nodeIdx = 0; nodeIdx < count; nodeIdx++ )
{
nodes[ nodeIdx ].OptionsDefineContainer.AddDefine( defineValue, false );
}
}
else if( !string.IsNullOrEmpty( validActions[ i ].PassName ) )
{
TemplateMultiPassMasterNode passMasterNode = owner.ContainerGraph.GetMasterNodeOfPass( validActions[ i ].PassName, owner.LODIndex );
if( passMasterNode != null )
{
string defineValue = "#undef " + validActions[ i ].ActionData;
if( isRefreshing )
{
string optionsId = validActions[ i ].PassName + defineValue;
owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( optionsId, true );
}
passMasterNode.OptionsDefineContainer.AddDefine( defineValue, false );
}
else
{
Debug.LogFormat( "Could not find pass {0} for action {1} on {2}", validActions[ i ].PassName, validActions[ i ].ActionType, validActions[ i ].ActionData );
}
}
else
{
uiItem.CheckOnExecute = true;
}
}
break;
case AseOptionsActionType.RemoveUndefine:
{
if( validActions[ i ].AllPasses )
{
string defineValue = "#undef " + validActions[ i ].ActionData;
bool flag = false;
if( isRefreshing )
{
flag = owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( defineValue, false );
}
if( !flag )
{
List<TemplateMultiPassMasterNode> nodes = owner.ContainerGraph.GetMultiPassMasterNodes( owner.LODIndex );
int count = nodes.Count;
for( int nodeIdx = 0; nodeIdx < count; nodeIdx++ )
{
nodes[ nodeIdx ].OptionsDefineContainer.RemoveDefine( defineValue );
}
}
}
else if( !string.IsNullOrEmpty( validActions[ i ].PassName ) )
{
TemplateMultiPassMasterNode passMasterNode = owner.ContainerGraph.GetMasterNodeOfPass( validActions[ i ].PassName, owner.LODIndex );
if( passMasterNode != null )
{
bool flag = false;
string defineValue = "#undef " + validActions[ i ].ActionData;
if( isRefreshing )
{
string optionId = validActions[ i ].PassName + defineValue;
flag = owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( optionId, false );
}
if( !flag )
{
passMasterNode.OptionsDefineContainer.RemoveDefine( defineValue );
}
}
else
{
Debug.LogFormat( "Could not find pass {0} for action {1} on {2}", validActions[ i ].PassName, validActions[ i ].ActionType, validActions[ i ].ActionData );
}
}
else
{
uiItem.CheckOnExecute = false;
}
}
break;
case AseOptionsActionType.ExcludePass:
{
string optionId = validActions[ i ].ActionData + "Pass";
bool flag = isRefreshing ? owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( optionId, false ) : false;
if( !flag )
owner.SetPassVisible( validActions[ i ].ActionData, false );
}
break;
case AseOptionsActionType.IncludePass:
{
if( !uiItem.IsVisible )
break;
string optionId = validActions[ i ].ActionData + "Pass";
owner.ContainerGraph.ParentWindow.TemplatesManagerInstance.SetOptionsValue( optionId, true );
owner.SetPassVisible( validActions[ i ].ActionData, true );
}
break;
case AseOptionsActionType.SetPropertyOnPass:
{
//Debug.Log( "PASSPROP " + validActions[ i ].ActionData );
//Refresh happens on hotcode reload and shader load and in those situation
// The property own serialization handles its setup
if( isRefreshing )
continue;
if( !string.IsNullOrEmpty( validActions[ i ].PassName ) )
{
TemplateMultiPassMasterNode passMasterNode = owner.ContainerGraph.GetMasterNodeOfPass( validActions[ i ].PassName, owner.LODIndex );
if( passMasterNode != null )
{
passMasterNode.SetPropertyActionFromItem( actionFromUser, passMasterNode.PassModule, validActions[ i ] );
}
else
{
Debug.LogFormat( "Could not find pass {0} for action {1} on {2}", validActions[ i ].PassName, validActions[ i ].ActionType, validActions[ i ].ActionData );
}
}
else
{
owner.SetPropertyActionFromItem( actionFromUser, owner.PassModule, validActions[ i ] );
}
}
break;
case AseOptionsActionType.SetPropertyOnSubShader:
{
//Refresh happens on hotcode reload and shader load and in those situation
// The property own serialization handles its setup
if( isRefreshing )
continue;
owner.SetPropertyActionFromItem( actionFromUser, owner.SubShaderModule, validActions[ i ] );
}
break;
case AseOptionsActionType.SetShaderProperty:
{
//This action is only check when shader is compiled over
//the TemplateMultiPassMasterNode via the on CheckPropertyChangesOnOptions() method
}
break;
case AseOptionsActionType.ExcludeAllPassesBut:
{
//This action is only check when shader is compiled over
//the TemplateMultiPassMasterNode via the on CheckExcludeAllPassOptions() method
}
break;
case AseOptionsActionType.SetMaterialProperty:
{
if( isRefreshing )
continue;
if( !uiItem.IsVisible )
break;
if( owner.ContainerGraph.CurrentMaterial != null )
{
string prop = validActions[ i ].ActionData;
if( owner.ContainerGraph.CurrentMaterial.HasProperty( prop ) )
{
if( uiItem.Options.UIWidget == AseOptionsUIWidget.Float || uiItem.Options.UIWidget == AseOptionsUIWidget.FloatRange )
owner.ContainerGraph.CurrentMaterial.SetFloat( prop, uiItem.CurrentFieldValue );
else
owner.ContainerGraph.CurrentMaterial.SetInt( prop, (int)uiItem.CurrentFieldValue );
if( ASEMaterialInspector.Instance != null )
ASEMaterialInspector.Instance.Repaint();
}
}
}
break;
}
}
}
public void SetupCustomOptionsFromTemplate( TemplateMultiPassMasterNode owner, bool newTemplate )
{
TemplateOptionsContainer customOptionsContainer = m_isSubShader ? owner.SubShader.CustomOptionsContainer : owner.Pass.CustomOptionsContainer;
if( !newTemplate && customOptionsContainer.Body.Length == m_passCustomOptionsSizeCheck )
{
for( int i = 0; i < m_passCustomOptionsUI.Count; i++ )
{
if( m_passCustomOptionsUI[ i ].EmptyEvent )
{
if( m_isSubShader )
{
m_passCustomOptionsUI[ i ].OnActionPerformedEvt += owner.OnCustomSubShaderOptionSelected;
}
else
{
m_passCustomOptionsUI[ i ].OnActionPerformedEvt += owner.OnCustomPassOptionSelected;
}
}
}
return;
}
m_passCustomOptionsLabel = string.IsNullOrEmpty( customOptionsContainer.Name ) ? CustomOptionsLabel : " " + customOptionsContainer.Name;
for( int i = 0; i < m_passCustomOptionsUI.Count; i++ )
{
m_passCustomOptionsUI[ i ].Destroy();
}
m_passCustomOptionsUI.Clear();
m_passCustomOptionsUIDict.Clear();
m_passCustomOptionsPorts.Clear();
if( customOptionsContainer.Enabled )
{
m_passCustomOptionsSizeCheck = customOptionsContainer.Body.Length;
for( int i = 0; i < customOptionsContainer.Options.Length; i++ )
{
switch( customOptionsContainer.Options[ i ].Type )
{
case AseOptionsType.Option:
{
TemplateOptionUIItem item = new TemplateOptionUIItem( customOptionsContainer.Options[ i ] );
if( m_isSubShader )
{
item.OnActionPerformedEvt += owner.OnCustomSubShaderOptionSelected;
}
else
{
item.OnActionPerformedEvt += owner.OnCustomPassOptionSelected;
}
m_passCustomOptionsUI.Add( item );
m_passCustomOptionsUIDict.Add( customOptionsContainer.Options[ i ].Id, item );
}
break;
case AseOptionsType.Port:
{
TemplateOptionPortItem item = new TemplateOptionPortItem( owner, customOptionsContainer.Options[ i ] );
m_passCustomOptionsPorts.Add( item );
//if( m_isSubShader )
//{
// if( string.IsNullOrEmpty( customOptionsContainer.Options[ i ].Id ) )
// {
// //No pass name selected. inject on all passes
// TemplateOptionPortItem item = new TemplateOptionPortItem( owner, customOptionsContainer.Options[ i ] );
// m_passCustomOptionsPorts.Add( item );
// }
// else if( customOptionsContainer.Options[ i ].Id.Equals( owner.PassName ) )
// {
// TemplateOptionPortItem item = new TemplateOptionPortItem( owner, customOptionsContainer.Options[ i ] );
// m_passCustomOptionsPorts.Add( item );
// }
//}
//else
//{
// TemplateOptionPortItem item = new TemplateOptionPortItem( owner, customOptionsContainer.Options[ i ] );
// m_passCustomOptionsPorts.Add( item );
//}
}
break;
case AseOptionsType.Field:
{
TemplateOptionUIItem item = new TemplateOptionUIItem( customOptionsContainer.Options[ i ] );
if( m_isSubShader )
{
item.OnActionPerformedEvt += owner.OnCustomSubShaderOptionSelected;
}
else
{
item.OnActionPerformedEvt += owner.OnCustomPassOptionSelected;
}
m_passCustomOptionsUI.Add( item );
m_passCustomOptionsUIDict.Add( customOptionsContainer.Options[ i ].Id, item );
}
break;
}
}
}
else
{
m_passCustomOptionsSizeCheck = 0;
}
}
public void SetCustomOptionsInfo( TemplateMultiPassMasterNode masterNode, ref MasterNodeDataCollector dataCollector )
{
if( masterNode == null )
return;
for( int i = 0; i < m_passCustomOptionsUI.Count; i++ )
{
m_passCustomOptionsUI[ i ].FillDataCollector( ref dataCollector );
}
for( int i = 0; i < m_passCustomOptionsPorts.Count; i++ )
{
m_passCustomOptionsPorts[ i ].FillDataCollector( masterNode, ref dataCollector );
}
}
public void CheckImediateActionsForPort( TemplateMultiPassMasterNode masterNode , int portId )
{
for( int i = 0; i < m_passCustomOptionsPorts.Count; i++ )
{
m_passCustomOptionsPorts[ i ].CheckImediateActionsForPort( masterNode, portId );
}
}
public void SetSubShaderCustomOptionsPortsInfo( TemplateMultiPassMasterNode masterNode, ref MasterNodeDataCollector dataCollector )
{
if( masterNode == null )
return;
//for( int i = 0; i < m_passCustomOptionsPorts.Count; i++ )
//{
// if( string.IsNullOrEmpty( m_passCustomOptionsPorts[ i ].Options.Id ) ||
// masterNode.PassUniqueName.Equals( m_passCustomOptionsPorts[ i ].Options.Id ) )
// {
// m_passCustomOptionsPorts[ i ].FillDataCollector( masterNode, ref dataCollector );
// }
//}
for( int i = 0; i < m_passCustomOptionsPorts.Count; i++ )
{
m_passCustomOptionsPorts[ i ].SubShaderFillDataCollector( masterNode, ref dataCollector );
}
}
public void RefreshCustomOptionsDict()
{
if( m_passCustomOptionsUIDict.Count != m_passCustomOptionsUI.Count )
{
m_passCustomOptionsUIDict.Clear();
int count = m_passCustomOptionsUI.Count;
for( int i = 0; i < count; i++ )
{
m_passCustomOptionsUIDict.Add( m_passCustomOptionsUI[ i ].Options.Id, m_passCustomOptionsUI[ i ] );
}
}
}
public void ReadFromString( ref uint index, ref string[] nodeParams )
{
RefreshCustomOptionsDict();
int savedOptions = Convert.ToInt32( nodeParams[ index++ ] );
m_readOptionNames = new string[ savedOptions ];
m_readOptionSelections = new string[ savedOptions ];
for( int i = 0; i < savedOptions; i++ )
{
string optionName = nodeParams[ index++ ];
string optionSelection = nodeParams[ index++ ];
m_readOptionNames[ i ] = optionName;
m_readOptionSelections[ i ] = optionSelection;
}
}
public void SetReadOptions()
{
if( m_readOptionNames != null && m_readOptionSelections != null )
{
for( int i = 0; i < m_readOptionNames.Length; i++ )
{
if( m_passCustomOptionsUIDict.ContainsKey( m_readOptionNames[ i ] ) )
{
if( m_passCustomOptionsUIDict[ m_readOptionNames[ i ] ].Options.Type == AseOptionsType.Field )
{
m_passCustomOptionsUIDict[ m_readOptionNames[ i ] ].FieldValue.ReadFromSingle( m_readOptionSelections[ i ] );
foreach( var item in m_passCustomOptionsUIDict[ m_readOptionNames[ i ] ].Options.ActionsPerOption.Rows )
{
if( item.Columns.Length>0 && item.Columns[ 0 ].ActionType == AseOptionsActionType.SetMaterialProperty )
{
if( UIUtils.CurrentWindow.CurrentGraph.CurrentMaterial != null )
{
if( UIUtils.CurrentWindow.CurrentGraph.CurrentMaterial.HasProperty( item.Columns[ 0 ].ActionData ) )
{
m_passCustomOptionsUIDict[ m_readOptionNames[ i ] ].CurrentFieldValue = UIUtils.CurrentWindow.CurrentGraph.CurrentMaterial.GetFloat( item.Columns[ 0 ].ActionData );
}
}
}
}
}
else
m_passCustomOptionsUIDict[ m_readOptionNames[ i ] ].CurrentOptionIdx = Convert.ToInt32( m_readOptionSelections[ i ] );
}
}
}
}
public void Refresh()
{
int count = m_passCustomOptionsUI.Count;
for( int i = 0; i < count; i++ )
{
m_passCustomOptionsUI[ i ].Refresh();
}
}
public void CheckDisable()
{
int count = m_passCustomOptionsUI.Count;
for( int i = 0; i < count; i++ )
{
m_passCustomOptionsUI[ i ].CheckEnDisable(false);
}
}
public void WriteToString( ref string nodeInfo )
{
int optionsCount = m_passCustomOptionsUI.Count;
IOUtils.AddFieldValueToString( ref nodeInfo, optionsCount );
for( int i = 0; i < optionsCount; i++ )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_passCustomOptionsUI[ i ].Options.Id );
if( m_passCustomOptionsUI[ i ].Options.Type == AseOptionsType.Field )
IOUtils.AddFieldValueToString( ref nodeInfo, m_passCustomOptionsUI[ i ].FieldValue.WriteToSingle() );
else
IOUtils.AddFieldValueToString( ref nodeInfo, m_passCustomOptionsUI[ i ].CurrentOption );
}
}
public List<TemplateOptionUIItem> PassCustomOptionsUI { get { return m_passCustomOptionsUI; } }
}
}

View File

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

View File

@@ -0,0 +1,637 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
#define CUSTOM_OPTIONS_AVAILABLE
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplatePass
{
private const string DefaultPassNameStr = "SubShader {0} Pass {1}";
[SerializeField]
private int m_idx = -1;
[SerializeField]
private bool m_isInvisible = false;
[SerializeField]
private int m_invisibleOptions = 0;
[SerializeField]
private bool m_isMainPass = false;
[SerializeField]
private TemplateModulesData m_modules;
[SerializeField]
private List<TemplateInputData> m_inputDataList = new List<TemplateInputData>();
private Dictionary<int, TemplateInputData> m_inputDataDict = new Dictionary<int, TemplateInputData>();
[SerializeField]
private TemplateFunctionData m_vertexFunctionData;
[SerializeField]
private TemplateFunctionData m_fragmentFunctionData;
[SerializeField]
private VertexDataContainer m_vertexDataContainer;
[SerializeField]
private TemplateInterpData m_interpolatorDataContainer;
[SerializeField]
private TemplateTessVControlTag m_tessVControlTag;
[SerializeField]
private TemplateTessControlData m_tessControlData;
[SerializeField]
private TemplateTessDomainData m_tessDomainData;
[SerializeField]
private List<TemplateLocalVarData> m_localVarsList = new List<TemplateLocalVarData>();
[SerializeField]
private string m_uniquePrefix;
[SerializeField]
private TemplatePropertyContainer m_templateProperties = new TemplatePropertyContainer();
[SerializeField]
private List<TemplateShaderPropertyData> m_availableShaderGlobals = new List<TemplateShaderPropertyData>();
[SerializeField]
TemplateInfoContainer m_passNameContainer = new TemplateInfoContainer();
#if CUSTOM_OPTIONS_AVAILABLE
[SerializeField]
TemplateOptionsContainer m_customOptionsContainer = new TemplateOptionsContainer();
#endif
public TemplatePass( TemplateMultiPass template, TemplateSubShader subShader, int subshaderIdx, int passIdx, TemplateIdManager idManager, string uniquePrefix, int offsetIdx, TemplatePassInfo passInfo, ref Dictionary<string, TemplateShaderPropertyData> duplicatesHelper )
{
m_idx = passIdx;
m_uniquePrefix = uniquePrefix;
idManager.RegisterPassId( passInfo.Data );
m_isMainPass = passInfo.Data.Contains( TemplatesManager.TemplateMainPassTag );
if( !m_isMainPass )
{
string id = string.Empty;
int idIndex = 0;
m_isInvisible = TemplateHelperFunctions.FetchInvisibleInfo( passInfo.Data, ref m_invisibleOptions, ref id, ref idIndex );
if( m_isInvisible )
{
idManager.RegisterId( idIndex, uniquePrefix + id, id, true );
}
}
FetchPassName( offsetIdx, passInfo.Data );
if( m_passNameContainer.Index > -1 )
{
idManager.RegisterId( m_passNameContainer.Index, uniquePrefix + m_passNameContainer.Id, m_passNameContainer.Id );
}
else
{
m_passNameContainer.Data = string.Format( DefaultPassNameStr, subshaderIdx, passIdx );
}
#if CUSTOM_OPTIONS_AVAILABLE
m_customOptionsContainer = TemplateOptionsToolsHelper.GenerateOptionsContainer( false, passInfo.Data );
if( m_customOptionsContainer.Enabled )
{
idManager.RegisterId( m_customOptionsContainer.Index, uniquePrefix + m_customOptionsContainer.Body, m_customOptionsContainer.Body, true );
}
//m_customOptionsContainer.CopyPortOptionsFrom( subShader.CustomOptionsContainer, m_passNameContainer.Data );
#endif
m_modules = new TemplateModulesData( m_customOptionsContainer,idManager, m_templateProperties, uniquePrefix + "Module", offsetIdx, passInfo.Data, false );
if( !m_modules.PassTag.IsValid )
{
m_modules.PassTag.StartIdx = passInfo.GlobalStartIdx;
m_templateProperties.AddId( passInfo.Data, m_modules.PassTag.Id, passInfo.LocalStartIdx, false );
//m_modules.PassTag.StartIdx -= m_templateProperties.PropertyDict[ m_modules.PassTag.Id ].Indentation.Length;
//m_templateProperties.PropertyDict[ m_modules.PassTag.Id ].UseIndentationAtStart = false;
idManager.RegisterId( m_modules.PassTag.StartIdx, m_modules.UniquePrefix + m_modules.PassTag.Id, string.Empty );
}
m_modules.SetPassUniqueNameIfUndefined( m_passNameContainer.Data );
m_modules.SRPType = subShader.Modules.SRPType;
if( m_modules.SRPType == TemplateSRPType.HD )
{
m_modules.SRPIsPBR = passInfo.Data.Contains( TemplateHelperFunctions.HDPBRTag );
}
Dictionary<string, TemplateShaderPropertyData> ownDuplicatesDict = new Dictionary<string, TemplateShaderPropertyData>( duplicatesHelper );
TemplateHelperFunctions.CreateShaderGlobalsList( passInfo.Data, ref m_availableShaderGlobals, ref ownDuplicatesDict,subshaderIdx,passIdx );
if( m_modules.SRPType == TemplateSRPType.BuiltIn )
{
TemplateHelperFunctions.CheckUnityBuiltinGlobalMacros( passInfo.Data, ref m_availableShaderGlobals, ref ownDuplicatesDict, subshaderIdx, passIdx );
}
// Vertex and Interpolator data
FetchVertexAndInterpData( template, subShader.Modules, offsetIdx, passInfo.Data );
if( m_vertexDataContainer != null )
idManager.RegisterId( m_vertexDataContainer.VertexDataStartIdx, uniquePrefix + m_vertexDataContainer.VertexDataId, m_vertexDataContainer.VertexDataId );
if( m_interpolatorDataContainer != null )
idManager.RegisterId( m_interpolatorDataContainer.InterpDataStartIdx, uniquePrefix + m_interpolatorDataContainer.InterpDataId, m_interpolatorDataContainer.InterpDataId );
//Fetch function code areas
FetchCodeAreas( offsetIdx, TemplatesManager.TemplateVertexCodeBeginArea, MasterNodePortCategory.Vertex, passInfo.Data );
if( m_vertexFunctionData != null )
idManager.RegisterId( m_vertexFunctionData.Position, uniquePrefix + m_vertexFunctionData.Id, m_vertexFunctionData.Id );
FetchCodeAreas( offsetIdx, TemplatesManager.TemplateFragmentCodeBeginArea, MasterNodePortCategory.Fragment, passInfo.Data );
if( m_fragmentFunctionData != null )
idManager.RegisterId( m_fragmentFunctionData.Position, uniquePrefix + m_fragmentFunctionData.Id, m_fragmentFunctionData.Id );
//Fetching inputs, must be do
if( m_fragmentFunctionData != null )
FetchInputs( offsetIdx, MasterNodePortCategory.Fragment, passInfo.Data );
if( m_vertexFunctionData != null )
FetchInputs( offsetIdx, MasterNodePortCategory.Vertex, passInfo.Data );
FetchTessellationData( template, subShader.Modules, offsetIdx, passInfo.Data );
if( m_tessVControlTag != null )
idManager.RegisterId( m_tessVControlTag.StartIdx, uniquePrefix + m_tessVControlTag.Id, m_tessVControlTag.Id );
if( m_tessControlData != null )
idManager.RegisterId( m_tessControlData.StartIdx, uniquePrefix + m_tessControlData.Id, m_tessControlData.Id );
if( m_tessDomainData != null )
idManager.RegisterId( m_tessDomainData.StartIdx, uniquePrefix + m_tessDomainData.Id, m_tessDomainData.Id );
TemplateHelperFunctions.FetchInlineVars( passInfo.Data, ref idManager );
//Fetch local variables must be done after fetching code areas as it needs them to see is variable is on vertex or fragment
TemplateHelperFunctions.FetchLocalVars( passInfo.Data, ref m_localVarsList, m_vertexFunctionData, m_fragmentFunctionData );
int localVarCount = m_localVarsList.Count;
if( localVarCount > 0 )
{
idManager.RegisterTag( TemplatesManager.TemplateLocalVarTag );
for( int i = 0; i < localVarCount; i++ )
{
if( m_localVarsList[ i ].IsSpecialVar )
{
idManager.RegisterTag( m_localVarsList[ i ].Id );
}
}
}
int inputsCount = m_inputDataList.Count;
for( int i = 0; i < inputsCount; i++ )
{
if( m_inputDataList[ i ] != null )
idManager.RegisterId( m_inputDataList[ i ].TagGlobalStartIdx, uniquePrefix + m_inputDataList[ i ].TagId, m_inputDataList[ i ].TagId );
}
//int passEndIndex = passInfo.Data.LastIndexOf( "}" );
//if( passEndIndex > 0 )
//{
// int identationIndex = -1;
// for( int i = passEndIndex; i >= 0; i-- )
// {
// if( passInfo.Data[ i ] == TemplatesManager.TemplateNewLine )
// {
// identationIndex = i + 1;
// break;
// }
// if( i == 0 )
// {
// identationIndex = 0;
// }
// }
// if( identationIndex > -1 )
// {
// int length = passEndIndex - identationIndex;
// string indentation = ( length > 0 ) ? passInfo.Data.Substring( identationIndex, length ) : string.Empty;
// TemplateProperty templateProperty = new TemplateProperty( TemplatesManager.TemplateEndPassTag, indentation, false );
// m_templateProperties.AddId( templateProperty );
// idManager.RegisterId( offsetIdx + passEndIndex, uniquePrefix + TemplatesManager.TemplateEndPassTag, string.Empty );
// }
//}
ownDuplicatesDict.Clear();
ownDuplicatesDict = null;
}
public void Destroy()
{
m_passNameContainer = null;
#if CUSTOM_OPTIONS_AVAILABLE
m_customOptionsContainer = null;
#endif
if( m_templateProperties != null )
m_templateProperties.Destroy();
m_templateProperties = null;
if( m_modules != null )
m_modules.Destroy();
m_modules = null;
if( m_inputDataList != null )
m_inputDataList.Clear();
m_inputDataList = null;
if( m_inputDataDict != null )
m_inputDataDict.Clear();
m_inputDataDict = null;
m_vertexFunctionData = null;
m_fragmentFunctionData = null;
if( m_vertexDataContainer != null )
m_vertexDataContainer.Destroy();
m_vertexDataContainer = null;
m_tessVControlTag = null;
m_tessControlData = null;
m_tessDomainData = null;
if( m_interpolatorDataContainer != null )
m_interpolatorDataContainer.Destroy();
if( m_localVarsList != null )
{
m_localVarsList.Clear();
m_localVarsList = null;
}
m_interpolatorDataContainer = null;
if( m_availableShaderGlobals != null )
m_availableShaderGlobals.Clear();
m_availableShaderGlobals = null;
}
public TemplateInputData InputDataFromId( int id )
{
if( m_inputDataDict == null )
m_inputDataDict = new Dictionary<int, TemplateInputData>();
if( m_inputDataDict.Count != m_inputDataList.Count )
{
m_inputDataDict.Clear();
for( int i = 0; i < m_inputDataList.Count; i++ )
{
m_inputDataDict.Add( m_inputDataList[ i ].PortUniqueId, m_inputDataList[ i ] );
}
}
if( m_inputDataDict.ContainsKey( id ) )
return m_inputDataDict[ id ];
return null;
}
void FetchPassName( int offsetIdx, string body )
{
Match match = Regex.Match( body, TemplateHelperFunctions.PassNamePattern );
if( match != null && match.Groups.Count > 1 )
{
m_passNameContainer.Id = match.Groups[ 0 ].Value;
m_passNameContainer.Data = match.Groups[ 1 ].Value;
m_passNameContainer.Index = offsetIdx + match.Index;
}
}
void FetchTessellationData( TemplateMultiPass template, TemplateModulesData subShaderModule, int offsetIdx, string body )
{
// Tessellation VControl Tag
try
{
int vcontrolcodeBegin = body.IndexOf( TemplatesManager.TemplateTessVControlTag );
if( vcontrolcodeBegin > -1 )
{
m_tessVControlTag = new TemplateTessVControlTag();
m_tessVControlTag.Id = TemplatesManager.TemplateTessVControlTag;
m_tessVControlTag.StartIdx = offsetIdx + vcontrolcodeBegin;
m_templateProperties.AddId( body, m_tessVControlTag.Id );
}
}
catch( Exception e )
{
Debug.LogException( e );
}
// Tessellation Control Data
try
{
int controlCodeBegin = body.IndexOf( TemplatesManager.TemplateTessControlCodeArea );
if( controlCodeBegin > -1 )
{
int beginIdx = controlCodeBegin + TemplatesManager.TemplateTessControlCodeArea.Length;
int endIdx = body.IndexOf( TemplatesManager.TemplateEndOfLine, beginIdx );
int length = endIdx - beginIdx;
string parameters = body.Substring( beginIdx, length );
string[] parametersArr = parameters.Split( IOUtils.FIELD_SEPARATOR );
string id = body.Substring( controlCodeBegin, endIdx + TemplatesManager.TemplateEndOfLine.Length - controlCodeBegin );
string inParameters = parametersArr[ 0 ];
string outParameters = ( parametersArr.Length > 1 ) ? parametersArr[ 1 ] : string.Empty;
m_tessControlData = new TemplateTessControlData( offsetIdx + controlCodeBegin, id, inParameters, outParameters );
m_templateProperties.AddId( body, id );
}
}
catch( Exception e )
{
Debug.LogException( e );
}
// Tessellation Domain Data
try
{
int domainCodeBegin = body.IndexOf( TemplatesManager.TemplateTessDomainCodeArea );
if( domainCodeBegin > -1 )
{
int beginIdx = domainCodeBegin + TemplatesManager.TemplateTessDomainCodeArea.Length;
int endIdx = body.IndexOf( TemplatesManager.TemplateEndOfLine, beginIdx );
int length = endIdx - beginIdx;
string parameters = body.Substring( beginIdx, length );
string[] parametersArr = parameters.Split( IOUtils.FIELD_SEPARATOR );
string id = body.Substring( domainCodeBegin, endIdx + TemplatesManager.TemplateEndOfLine.Length - domainCodeBegin );
string inParameters = ( parametersArr.Length > 0 ) ? parametersArr[ 0 ] : string.Empty;
string outParameters = ( parametersArr.Length > 1 ) ? parametersArr[ 1 ] : string.Empty;
string baryParameters = ( parametersArr.Length > 2 ) ? parametersArr[ 2 ] : string.Empty;
m_tessDomainData = new TemplateTessDomainData( offsetIdx + domainCodeBegin, id, inParameters, outParameters, baryParameters );
m_templateProperties.AddId( body, id );
}
}
catch( Exception e )
{
Debug.LogException( e );
}
}
void FetchVertexAndInterpData(TemplateMultiPass template, TemplateModulesData subShaderModule, int offsetIdx, string body )
{
// Vertex Data
try
{
int vertexDataTagBegin = body.IndexOf( TemplatesManager.TemplateVertexDataTag );
if( vertexDataTagBegin > -1 )
{
m_vertexDataContainer = new VertexDataContainer();
m_vertexDataContainer.VertexDataStartIdx = offsetIdx + vertexDataTagBegin;
int vertexDataTagEnd = body.IndexOf( TemplatesManager.TemplateEndOfLine, vertexDataTagBegin );
m_vertexDataContainer.VertexDataId = body.Substring( vertexDataTagBegin, vertexDataTagEnd + TemplatesManager.TemplateEndOfLine.Length - vertexDataTagBegin );
int dataBeginIdx = body.LastIndexOf( '{', vertexDataTagBegin, vertexDataTagBegin );
int dataEndIdx = body.IndexOf( '}', vertexDataTagEnd );
string vertexData = body.Substring( dataBeginIdx + 1, dataEndIdx - dataBeginIdx );
int parametersBegin = vertexDataTagBegin + TemplatesManager.TemplateVertexDataTag.Length;
string parameters = body.Substring( parametersBegin, vertexDataTagEnd - parametersBegin );
m_vertexDataContainer.VertexData = TemplateHelperFunctions.CreateVertexDataList( vertexData, parameters );
m_templateProperties.AddId( body, m_vertexDataContainer.VertexDataId );
}
}
catch( Exception e )
{
Debug.LogException( e );
}
// Available interpolators
try
{
int interpDataBegin = body.IndexOf( TemplatesManager.TemplateInterpolatorBeginTag );
if( interpDataBegin > -1 )
{
int interpDataEnd = body.IndexOf( TemplatesManager.TemplateEndOfLine, interpDataBegin );
string interpDataId = body.Substring( interpDataBegin, interpDataEnd + TemplatesManager.TemplateEndOfLine.Length - interpDataBegin );
int dataBeginIdx = body.LastIndexOf( '{', interpDataBegin, interpDataBegin );
int dataEndIdx = body.IndexOf( '}', interpDataEnd );
string interpData = body.Substring( dataBeginIdx + 1, dataEndIdx - dataBeginIdx );
int interpolatorAmount = TemplateHelperFunctions.AvailableInterpolators[ "2.5" ];
if( m_modules.ShaderModel.IsValid )
{
interpolatorAmount = m_modules.ShaderModel.InterpolatorAmount;
}
else if( subShaderModule.ShaderModel.IsValid )
{
interpolatorAmount = subShaderModule.ShaderModel.InterpolatorAmount;
}
else if( template.GlobalShaderModel.IsValid )
{
interpolatorAmount = template.GlobalShaderModel.InterpolatorAmount;
}
m_interpolatorDataContainer = TemplateHelperFunctions.CreateInterpDataList( interpData, interpDataId, interpolatorAmount );
m_interpolatorDataContainer.InterpDataId = interpDataId;
m_interpolatorDataContainer.InterpDataStartIdx = offsetIdx + interpDataBegin;
m_templateProperties.AddId( body, interpDataId );
}
}
catch( Exception e )
{
Debug.LogException( e );
}
}
void FetchCodeAreas( int offsetIdx, string begin, MasterNodePortCategory category, string body )
{
int areaBeginIndexes = body.IndexOf( begin );
if( areaBeginIndexes > -1 )
{
int beginIdx = areaBeginIndexes + begin.Length;
int endIdx = body.IndexOf( TemplatesManager.TemplateEndOfLine, beginIdx );
int length = endIdx - beginIdx;
string parameters = body.Substring( beginIdx, length );
string[] parametersArr = parameters.Split( IOUtils.FIELD_SEPARATOR );
string id = body.Substring( areaBeginIndexes, endIdx + TemplatesManager.TemplateEndOfLine.Length - areaBeginIndexes );
string inParameters = parametersArr[ 0 ];
string outParameters = ( parametersArr.Length > 1 ) ? parametersArr[ 1 ] : string.Empty;
if( category == MasterNodePortCategory.Fragment )
{
string mainBodyName = string.Empty;
int mainBodyLocalIndex = -1;
Match mainBodyNameMatch = Regex.Match( body, TemplateHelperFunctions.FragmentPragmaPattern );
if( mainBodyNameMatch != null && mainBodyNameMatch.Groups.Count == 2 )
{
mainBodyName = mainBodyNameMatch.Groups[ 1 ].Value;
string pattern = string.Format( TemplateHelperFunctions.FunctionBodyStartPattern, mainBodyName );
Match mainBodyIdMatch = Regex.Match( body, pattern );
if( mainBodyIdMatch != null && mainBodyIdMatch.Groups.Count > 0 )
{
mainBodyLocalIndex = mainBodyIdMatch.Index;
}
}
m_fragmentFunctionData = new TemplateFunctionData( mainBodyLocalIndex, mainBodyName, id, offsetIdx + areaBeginIndexes, inParameters, outParameters, category );
}
else
{
string mainBodyName = string.Empty;
int mainBodyLocalIndex = -1;
Match mainBodyNameMatch = Regex.Match( body, TemplateHelperFunctions.VertexPragmaPattern );
if( mainBodyNameMatch != null && mainBodyNameMatch.Groups.Count == 2 )
{
mainBodyName = mainBodyNameMatch.Groups[ 1 ].Value;
string pattern = string.Format( TemplateHelperFunctions.FunctionBodyStartPattern, mainBodyName );
Match mainBodyIdMatch = Regex.Match( body, pattern );
if( mainBodyIdMatch != null && mainBodyIdMatch.Groups.Count > 0 )
{
mainBodyLocalIndex = mainBodyIdMatch.Index;
}
}
m_vertexFunctionData = new TemplateFunctionData( mainBodyLocalIndex, mainBodyName, id, offsetIdx + areaBeginIndexes, inParameters, outParameters, category );
}
m_templateProperties.AddId( body, id, true );
}
}
void FetchInputs( int offset, MasterNodePortCategory portCategory, string body )
{
string beginTag = ( portCategory == MasterNodePortCategory.Fragment ) ? TemplatesManager.TemplateInputsFragBeginTag : TemplatesManager.TemplateInputsVertBeginTag;
int[] inputBeginIndexes = body.AllIndexesOf( beginTag );
if( inputBeginIndexes != null && inputBeginIndexes.Length > 0 )
{
for( int i = 0; i < inputBeginIndexes.Length; i++ )
{
int inputEndIdx = body.IndexOf( TemplatesManager.TemplateEndSectionTag, inputBeginIndexes[ i ] );
int defaultValueBeginIdx = inputEndIdx + TemplatesManager.TemplateEndSectionTag.Length;
int endLineIdx = body.IndexOf( TemplatesManager.TemplateFullEndTag, defaultValueBeginIdx );
string defaultValue = body.Substring( defaultValueBeginIdx, endLineIdx - defaultValueBeginIdx );
string tagId = body.Substring( inputBeginIndexes[ i ], endLineIdx + TemplatesManager.TemplateFullEndTag.Length - inputBeginIndexes[ i ] );
int beginIndex = inputBeginIndexes[ i ] + beginTag.Length;
int length = inputEndIdx - beginIndex;
string inputData = body.Substring( beginIndex, length );
string[] inputDataArray = inputData.Split( IOUtils.FIELD_SEPARATOR );
if( inputDataArray != null && inputDataArray.Length > 0 )
{
try
{
string portName = inputDataArray[ (int)TemplatePortIds.Name ];
WirePortDataType dataType = (WirePortDataType)Enum.Parse( typeof( WirePortDataType ), inputDataArray[ (int)TemplatePortIds.DataType ].ToUpper() );
if( inputDataArray.Length == 3 )
{
int portOrderId = m_inputDataList.Count;
int portUniqueId = -1;
bool isInt = int.TryParse( inputDataArray[ 2 ], out portUniqueId );
if( isInt )
{
if( portUniqueId < 0 )
portUniqueId = m_inputDataList.Count;
m_inputDataList.Add( new TemplateInputData( inputBeginIndexes[ i ], offset + inputBeginIndexes[ i ], tagId, portName, defaultValue, dataType, portCategory, portUniqueId, portOrderId, string.Empty ) );
m_templateProperties.AddId( body, tagId, false );
}
else
{
portUniqueId = m_inputDataList.Count;
m_inputDataList.Add( new TemplateInputData( inputBeginIndexes[ i ], offset + inputBeginIndexes[ i ], tagId, portName, defaultValue, dataType, portCategory, portUniqueId, portOrderId, inputDataArray[ 2 ] ) );
m_templateProperties.AddId( body, tagId, false );
}
}
else
{
int portUniqueIDArrIdx = (int)TemplatePortIds.UniqueId;
int portUniqueId = ( portUniqueIDArrIdx < inputDataArray.Length ) ? Convert.ToInt32( inputDataArray[ portUniqueIDArrIdx ] ) : -1;
if( portUniqueId < 0 )
portUniqueId = m_inputDataList.Count;
int portOrderArrayIdx = (int)TemplatePortIds.OrderId;
int portOrderId = ( portOrderArrayIdx < inputDataArray.Length ) ? Convert.ToInt32( inputDataArray[ portOrderArrayIdx ] ) : -1;
if( portOrderId < 0 )
portOrderId = m_inputDataList.Count;
int portLinkIdx = (int)TemplatePortIds.Link;
string linkId = ( portLinkIdx < inputDataArray.Length ) ? inputDataArray[ portLinkIdx ] : string.Empty;
m_inputDataList.Add( new TemplateInputData( inputBeginIndexes[ i ], offset + inputBeginIndexes[ i ], tagId, portName, defaultValue, dataType, portCategory, portUniqueId, portOrderId, linkId ) );
m_templateProperties.AddId( body, tagId, false );
}
}
catch( Exception e )
{
Debug.LogException( e );
}
}
}
}
}
#if CUSTOM_OPTIONS_AVAILABLE
public TemplateOptionsContainer CustomOptionsContainer { get { return m_customOptionsContainer; } }
#endif
public TemplateModulesData Modules { get { return m_modules; } }
public List<TemplateInputData> InputDataList { get { return m_inputDataList; } }
public TemplateFunctionData VertexFunctionData { get { return m_vertexFunctionData; } }
public TemplateFunctionData FragmentFunctionData { get { return m_fragmentFunctionData; } }
public VertexDataContainer VertexDataContainer { get { return m_vertexDataContainer; } }
public TemplateInterpData InterpolatorDataContainer { get { return m_interpolatorDataContainer; } }
public TemplateTessVControlTag TessVControlTag { get { return m_tessVControlTag; } }
public TemplateTessControlData TessControlData { get { return m_tessControlData; } }
public TemplateTessDomainData TessDomainData { get { return m_tessDomainData; } }
public string UniquePrefix { get { return m_uniquePrefix; } }
public TemplatePropertyContainer TemplateProperties { get { return m_templateProperties; } }
public List<TemplateShaderPropertyData> AvailableShaderGlobals { get { return m_availableShaderGlobals; } }
public List<TemplateLocalVarData> LocalVarsList { get { return m_localVarsList; } }
public TemplateInfoContainer PassNameContainer { get { return m_passNameContainer; } }
public bool IsMainPass { get { return m_isMainPass; } set { m_isMainPass = value; } }
public bool IsInvisible { get { return m_isInvisible; } }
public int InvisibleOptions { get { return m_invisibleOptions; } }
public int Idx { get { return m_idx; } }
public bool AddToList
{
get
{
if( m_isInvisible )
{
return ( m_inputDataList.Count > 0 );
}
return true;
}
}
public bool HasValidFunctionBody
{
get
{
if( m_fragmentFunctionData != null || m_vertexFunctionData != null )
return true;
return false;
}
}
}
}

View File

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

View File

@@ -0,0 +1,167 @@
using UnityEditor;
using UnityEngine;
using System;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
[Serializable]
public class PassVisibleOptionsItems
{
public bool Visible;
public string Name;
public int Idx = -1;
}
[Serializable]
public class TemplatePassSelectorHelper
{
private const string Label = " Available Passes";
[SerializeField]
private bool m_foldout;
[SerializeField]
private PassVisibleOptionsItems[] m_currentPasses;
[NonSerialized]
private Dictionary<string, PassVisibleOptionsItems> m_currentPassesDict;
[SerializeField]
private int m_mainPassId;
public void CopyFrom( TemplatePassSelectorHelper from )
{
for( int i = 0; i < from.AvailablePasses.Length; i++ )
{
SetPassVisible( from.AvailablePasses[ i ].Name, from.AvailablePasses[ i ].Visible );
}
}
public void Setup( TemplateSubShader subShader )
{
if( m_currentPasses == null )
{
m_currentPassesDict = new Dictionary<string, PassVisibleOptionsItems>();
m_currentPasses = new PassVisibleOptionsItems[ subShader.Passes.Count ];
for( int i = 0; i < m_currentPasses.Length; i++ )
{
if( subShader.Passes[ i ].IsMainPass )
m_mainPassId = i;
m_currentPasses[ i ] = new PassVisibleOptionsItems() { Name = subShader.Passes[ i ].PassNameContainer.Data, Visible = true, Idx = i };
m_currentPassesDict.Add( m_currentPasses[ i ].Name, m_currentPasses[ i ] );
}
}
}
public void Clear()
{
m_currentPasses = null;
if( m_currentPassesDict != null )
m_currentPassesDict.Clear();
m_currentPassesDict = null;
}
public void Destroy()
{
m_currentPasses = null;
if( m_currentPassesDict != null )
m_currentPassesDict.Clear();
m_currentPassesDict = null;
}
public void Draw( TemplateMultiPassMasterNode owner )
{
if( m_currentPasses.Length < 2 )
return;
NodeUtils.DrawNestedPropertyGroup( ref m_foldout, Label, () =>
{
for( int i = 0; i < m_currentPasses.Length; i++ )
{
EditorGUI.BeginChangeCheck();
m_currentPasses[ i ].Visible = owner.EditorGUILayoutToggleLeft( m_currentPasses[ i ].Name, m_currentPasses[ i ].Visible );
if( EditorGUI.EndChangeCheck() )
{
owner.ContainerGraph.GetMultiPassMasterNodes( owner.LODIndex)[ m_currentPasses[ i ].Idx ].IsInvisible = !m_currentPasses[ i ].Visible;
}
}
EditorGUILayout.Space();
} );
}
public void ReadFromString( ref uint index, ref string[] nodeParams )
{
int passAmount = Convert.ToInt32( nodeParams[ index++ ] );
for( int i = 0; i < passAmount; i++ )
{
bool value = Convert.ToBoolean( nodeParams[ index++ ] );
if( i < m_currentPasses.Length )
{
m_currentPasses[ i ].Visible = value;
}
}
}
public void WriteToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_currentPasses.Length );
for( int i = 0; i < m_currentPasses.Length; i++ )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_currentPasses[ i ].Visible );
}
}
public void SetPassVisible( string passName, bool visible )
{
bool refresh = false;
if( m_currentPassesDict == null )
{
m_currentPassesDict = new Dictionary<string, PassVisibleOptionsItems>();
refresh = true;
}
else if( m_currentPassesDict.Count != m_currentPasses.Length )
{
refresh = true;
}
if( refresh )
{
for( int i = 0; i < m_currentPasses.Length; i++ )
{
m_currentPassesDict.Add( m_currentPasses[ i ].Name, m_currentPasses[ i ] );
}
}
if( m_currentPassesDict.ContainsKey( passName ) )
{
m_currentPassesDict[ passName ].Visible = visible;
}
}
public int LastActivePass
{
get
{
if( m_currentPasses != null )
{
for( int i = m_currentPasses.Length - 1; i > -1; i-- )
{
if( m_currentPasses[ i ].Visible )
return i;
}
}
m_currentPasses[ m_mainPassId ].Visible = true;
return m_mainPassId;
}
}
public bool IsVisible( int passId ) { return m_currentPasses[ passId ].Visible; }
private PassVisibleOptionsItems[] AvailablePasses { get { return m_currentPasses; } }
}
}

View File

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

View File

@@ -0,0 +1,177 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEditor;
using UnityEngine;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text.RegularExpressions;
using Debug = UnityEngine.Debug;
namespace AmplifyShaderEditor
{
public sealed class TemplatePostProcessor : AssetPostprocessor
{
public static TemplatesManager DummyManager;
public static void Destroy()
{
if( DummyManager != null )
{
DummyManager.Destroy();
ScriptableObject.DestroyImmediate( DummyManager );
DummyManager = null;
}
}
static void OnPostprocessAllAssets( string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths )
{
bool containsShaders = false;
for( int i = 0; i < importedAssets.Length; i++ )
{
if( importedAssets[ i ].EndsWith( ".shader" ) )
{
containsShaders = true;
break;
}
}
// leave early if there's no shaders among the imports
if( !containsShaders )
return;
TemplatesManager templatesManager;
bool firstTimeDummyFlag = false;
if( UIUtils.CurrentWindow == null )
{
if( DummyManager == null )
{
DummyManager = ScriptableObject.CreateInstance<TemplatesManager>();
DummyManager.hideFlags = HideFlags.HideAndDontSave;
firstTimeDummyFlag = true;
}
templatesManager = DummyManager;
}
else
{
Destroy();
templatesManager = UIUtils.CurrentWindow.TemplatesManagerInstance;
}
if( templatesManager == null )
{
return;
}
if( !templatesManager.Initialized )
{
templatesManager.Init();
}
bool refreshMenuItems = false;
for( int i = 0; i < importedAssets.Length; i++ )
{
if( TemplateHelperFunctions.CheckIfTemplate( importedAssets[ i ] ) )
{
string guid = AssetDatabase.AssetPathToGUID( importedAssets[ i ] );
TemplateDataParent templateData = templatesManager.GetTemplate( guid );
if( templateData != null )
{
refreshMenuItems = templateData.Reload() || refreshMenuItems || firstTimeDummyFlag;
int windowCount = IOUtils.AllOpenedWindows.Count;
AmplifyShaderEditorWindow currWindow = UIUtils.CurrentWindow;
for( int windowIdx = 0; windowIdx < windowCount; windowIdx++ )
{
if( IOUtils.AllOpenedWindows[ windowIdx ].OutsideGraph.CurrentCanvasMode == NodeAvailability.TemplateShader )
{
if( IOUtils.AllOpenedWindows[ windowIdx ].OutsideGraph.MultiPassMasterNodes.NodesList[ 0 ].CurrentTemplate == templateData )
{
UIUtils.CurrentWindow = IOUtils.AllOpenedWindows[ windowIdx ];
IOUtils.AllOpenedWindows[ windowIdx ].OutsideGraph.ForceMultiPassMasterNodesRefresh();
}
}
}
UIUtils.CurrentWindow = currWindow;
}
else
{
refreshMenuItems = true;
string name = TemplatesManager.OfficialTemplates.ContainsKey( guid ) ? TemplatesManager.OfficialTemplates[ guid ] : string.Empty;
TemplateMultiPass mp = TemplateMultiPass.CreateInstance<TemplateMultiPass>();
mp.Init( name, guid, true );
templatesManager.AddTemplate( mp );
}
}
}
if( deletedAssets.Length > 0 )
{
if( deletedAssets[ 0 ].IndexOf( Constants.InvalidPostProcessDatapath ) < 0 )
{
for( int i = 0; i < deletedAssets.Length; i++ )
{
string guid = AssetDatabase.AssetPathToGUID( deletedAssets[ i ] );
TemplateDataParent templateData = templatesManager.GetTemplate( guid );
if( templateData != null )
{
// Close any window using that template
int windowCount = IOUtils.AllOpenedWindows.Count;
for( int windowIdx = 0; windowIdx < windowCount; windowIdx++ )
{
TemplateMasterNode masterNode = IOUtils.AllOpenedWindows[ windowIdx ].CurrentGraph.CurrentMasterNode as TemplateMasterNode;
if( masterNode != null && masterNode.CurrentTemplate.GUID.Equals( templateData.GUID ) )
{
IOUtils.AllOpenedWindows[ windowIdx ].Close();
}
}
templatesManager.RemoveTemplate( templateData );
refreshMenuItems = true;
}
}
}
}
//for ( int i = 0; i < movedAssets.Length; i++ )
//{
// if ( TemplateHelperFunctions.CheckIfTemplate( movedAssets[ i ] ) )
// {
// refreshMenuItems = true;
// break;
// }
//}
//for ( int i = 0; i < movedFromAssetPaths.Length; i++ )
//{
// if ( TemplateHelperFunctions.CheckIfTemplate( movedFromAssetPaths[ i ] ) )
// {
// refreshMenuItems = true;
// break;
// }
//}
if( refreshMenuItems )
{
//UnityEngine.Debug.Log( "Refresh Menu Items" );
refreshMenuItems = false;
templatesManager.CreateTemplateMenuItems();
AmplifyShaderEditorWindow currWindow = UIUtils.CurrentWindow;
int windowCount = IOUtils.AllOpenedWindows.Count;
for( int windowIdx = 0; windowIdx < windowCount; windowIdx++ )
{
UIUtils.CurrentWindow = IOUtils.AllOpenedWindows[ windowIdx ];
IOUtils.AllOpenedWindows[ windowIdx ].CurrentGraph.ForceCategoryRefresh();
}
UIUtils.CurrentWindow = currWindow;
}
// reimport menu items at the end of everything, hopefully preventing import loops
templatesManager.ReimportMenuItems();
// destroying the DummyManager, not doing so will create leaks over time
Destroy();
}
}
}

View File

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

View File

@@ -0,0 +1,121 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplatePassInfo
{
public string Modules;
public string Data;
public int GlobalStartIdx = -1;
public int LocalStartIdx = -1;
}
[Serializable]
public class TemplateSubShaderInfo
{
public string Data;
public string Modules;
public int StartIdx = -1;
public List<TemplatePassInfo> Passes = new List<TemplatePassInfo>();
public void Destroy()
{
Passes.Clear();
Passes = null;
}
}
[Serializable]
public class TemplateShaderInfo
{
public string Body;
public string Properties;
public int PropertyStartIdx = -1;
public List<TemplateSubShaderInfo> SubShaders = new List<TemplateSubShaderInfo>();
public void Destroy()
{
int count = SubShaders.Count;
for( int i = 0; i < count; i++ )
{
SubShaders[ i ].Destroy();
}
SubShaders.Clear();
SubShaders = null;
}
}
public class TemplateShaderInfoUtil
{
public static TemplateShaderInfo CreateShaderData( string body )
{
int nameBegin = body.IndexOf( TemplatesManager.TemplateShaderNameBeginTag );
if( nameBegin < 0 )
{
// Not a template
return null;
}
TemplateShaderInfo shaderData = null;
//SHADER
MatchCollection shaderMatch = Regex.Matches( body, "\\bShader\\b" );
if( shaderMatch.Count > 0 )
{
//SUBSHADER
MatchCollection subShaderMatch = Regex.Matches( body, TemplatesManager.TemplateMPSubShaderTag );
int subShaderAmount = subShaderMatch.Count;
if( subShaderAmount > 0 )
{
shaderData = new TemplateShaderInfo();
shaderData.Body = body;
int length = subShaderMatch[ 0 ].Index - shaderMatch[ 0 ].Groups[ 0 ].Index;
shaderData.Properties = body.Substring( shaderMatch[ 0 ].Index, length );
shaderData.PropertyStartIdx = body.IndexOf( TemplatesManager.TemplatePropertyTag );
for( int subShaderIdx = 0; subShaderIdx < subShaderAmount; subShaderIdx++ )
{
TemplateSubShaderInfo subShaderData = new TemplateSubShaderInfo();
int subshaderBeginIndex = subShaderMatch[ subShaderIdx ].Index;
int subShaderEndIndex = ( subShaderIdx == ( subShaderAmount - 1 ) ) ? body.Length - 1 : subShaderMatch[ subShaderIdx + 1 ].Index;
subShaderData.Data = body.Substring( subshaderBeginIndex, subShaderEndIndex - subshaderBeginIndex );
subShaderData.StartIdx = subshaderBeginIndex;
//PASS
MatchCollection passMatch = Regex.Matches( subShaderData.Data, TemplatesManager.TemplatePassTagPattern );
if( passMatch.Count == 0 )
{
passMatch = Regex.Matches( subShaderData.Data, TemplatesManager.TemplateMPPassTag );
}
int passCount = passMatch.Count;
if( passCount > 0 )
{
int lastPassIndex = subShaderData.Data.LastIndexOf( TemplatesManager.TemplatePassesEndTag );
if( lastPassIndex < 0 )
{
lastPassIndex = subShaderData.Data.Length - 1;
}
subShaderData.Modules = subShaderData.Data.Substring( 0, passMatch[ 0 ].Index );
for( int passIdx = 0; passIdx < passCount; passIdx++ )
{
int passBeginIndex = passMatch[ passIdx ].Index;
int passEndIdx = ( passIdx == ( passCount - 1 ) ) ? lastPassIndex : passMatch[ passIdx + 1 ].Index;
TemplatePassInfo passData = new TemplatePassInfo();
passData.Data = subShaderData.Data.Substring( passBeginIndex, passEndIdx - passBeginIndex );
passData.GlobalStartIdx = subshaderBeginIndex + passBeginIndex;
passData.LocalStartIdx = passBeginIndex;
subShaderData.Passes.Add( passData );
}
shaderData.SubShaders.Add( subShaderData );
}
}
}
}
return shaderData;
}
}
}

View File

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

View File

@@ -0,0 +1,107 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
[Serializable]
public sealed class TemplateShaderModelModule : TemplateModuleParent
{
private const string ShaderModelStr = "Shader Model";
private const string ShaderModelFormatStr = "#pragma target ";
private const string ShaderModelEncapsulateFormatStr = "CGINCLUDE\n#pragma target {0}\nENDCG";
[SerializeField]
private int m_shaderModelIdx = 2;
[SerializeField]
private bool m_encapsulateOnCGInlude = false;
public TemplateShaderModelModule() : base("Shader Model"){ }
public override void Draw( UndoParentNode owner, bool style = true )
{
EditorGUI.BeginChangeCheck();
m_shaderModelIdx = owner.EditorGUILayoutPopup( ShaderModelStr, m_shaderModelIdx, TemplateHelperFunctions.AvailableShaderModels );
if( EditorGUI.EndChangeCheck() )
{
m_isDirty = true;
}
}
public void CopyFrom( TemplateShaderModelModule other , bool allData )
{
if( allData )
{
m_independentModule = other.IndependentModule;
m_encapsulateOnCGInlude = other.EncapsulateOnCGInlude;
}
m_shaderModelIdx = other.CurrentShaderModelIdx;
}
public override void ReadFromString( ref uint index, ref string[] nodeParams )
{
bool validDataOnMeta = m_validData;
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
validDataOnMeta = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( validDataOnMeta )
m_shaderModelIdx = Convert.ToInt32( nodeParams[ index++ ] );
}
public override void WriteToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_validData );
if( m_validData )
IOUtils.AddFieldValueToString( ref nodeInfo, m_shaderModelIdx );
}
public override string GenerateShaderData( bool isSubShader )
{
if( m_encapsulateOnCGInlude )
{
return string.Format( ShaderModelEncapsulateFormatStr, TemplateHelperFunctions.AvailableShaderModels[ m_shaderModelIdx ] );
}
else
{
return ShaderModelFormatStr + TemplateHelperFunctions.AvailableShaderModels[ m_shaderModelIdx ];
}
}
public void ConfigureFromTemplateData( TemplateShaderModelData data )
{
bool newValidData = ( data.DataCheck == TemplateDataCheck.Valid );
if( newValidData && m_validData != newValidData )
{
m_independentModule = data.IndependentModule;
if( TemplateHelperFunctions.ShaderModelToArrayIdx.ContainsKey( data.Value ) )
{
m_shaderModelIdx = TemplateHelperFunctions.ShaderModelToArrayIdx[ data.Value ];
}
m_encapsulateOnCGInlude = data.Encapsulate;
}
m_validData = newValidData;
}
public int CurrentShaderModelIdx { get { return m_shaderModelIdx; } }
public string CurrentShaderModel { get { return TemplateHelperFunctions.AvailableShaderModels[ m_shaderModelIdx ]; } }
public bool EncapsulateOnCGInlude { get { return m_encapsulateOnCGInlude; } }
public int InterpolatorAmount
{
get
{
return TemplateHelperFunctions.AvailableInterpolators[ TemplateHelperFunctions.AvailableShaderModels[ m_shaderModelIdx ] ];
}
}
}
}

View File

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

View File

@@ -0,0 +1,52 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateShaderPropertyData
{
public string PropertyInspectorName;
public string PropertyName;
public WirePortDataType PropertyDataType;
public PropertyType PropertyType;
public int Index;
public string FullValue;
public string ReplacementValueHelper;
public string Identation;
public bool IsMacro;
public int SubShaderId;
public int PassId;
public TemplateShaderPropertyData( int index, string fullValue, string identation, string propertyInspectorName, string propertyName, WirePortDataType propertyDataType, PropertyType propertyType,int subShaderId, int passId, bool isMacro = false )
{
Index = index;
FullValue = fullValue;
Identation = identation;
PropertyInspectorName = string.IsNullOrEmpty( propertyInspectorName )?propertyName: propertyInspectorName;
PropertyName = propertyName;
PropertyDataType = propertyDataType;
PropertyType = propertyType;
int idx = FullValue.LastIndexOf( "=" );
ReplacementValueHelper = ( idx >= 0 ) ? FullValue.Substring( 0, idx + 1 ) +" ": FullValue + " = ";
IsMacro = isMacro;
SubShaderId = subShaderId;
PassId = passId;
}
public string CreatePropertyForValue( string value )
{
return value.Contains( PropertyName ) ? Identation + value : ReplacementValueHelper + value;
}
public override string ToString()
{
return string.Format( "{0}(\"{1}\", {2})", PropertyName, PropertyInspectorName,UIUtils.WirePortToCgType( PropertyDataType ) );
}
}
}

View File

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

View File

@@ -0,0 +1,715 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
public enum ShaderPropertyScope
{
Shader,
SubShader,
Pass
}
[Serializable]
[NodeAttributes( "Template Parameter", "Constants And Properties", "Select and use one of the pre-existing properties given by the template" )]
public sealed class TemplateShaderPropertyNode : TemplateNodeParent
{
private const string CurrentScopeStr = "Scope";
private const string WarningStr = "Preview doesn't work with global variables";
private const string PropertyLabelStr = "Parameter";
private const string TypeLabelStr = "Type: ";
private const string PropertyNameStr = "Property Name: ";
private int IntPropertyId;
private int FloatPropertyId;
private int VectorPropertyId;
private int Sampler2DPropertyId;
private int Sampler3DPropertyId;
private int SamplerCubePropertyId;
[SerializeField]
private int m_currentPropertyIdx = -1;
[SerializeField]
private string m_propertyName = string.Empty;
[SerializeField]
private int m_propertyNameId = 0;
[SerializeField]
private string m_typeName = string.Empty;
[SerializeField]
private string m_propertyNameLabel = string.Empty;
private bool m_fetchPropertyId = false;
private bool m_fetchScopeFromProperty = false;
private List<TemplateShaderPropertyData> m_shaderProperties = null;
private string[] m_propertyLabels = null;
private UpperLeftWidgetHelper m_upperLeftWidgetHelper = new UpperLeftWidgetHelper();
//Multi-Pass only properties
[SerializeField]
private ShaderPropertyScope m_currentScope = ShaderPropertyScope.Shader;
[SerializeField]
private bool m_advancedView = false;
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_previewShaderGUID = "4feb2016be0ece148b8bf234508f6aa4";
m_autoWrapProperties = true;
}
void FetchScope()
{
int shaderScopeCount = m_templateMPData.AvailableShaderProperties.Count;
for( int i = 0; i < shaderScopeCount; i++ )
{
if( m_templateMPData.AvailableShaderProperties[ i ].PropertyName.Equals( m_propertyName ) )
{
m_currentScope = ShaderPropertyScope.Shader;
}
}
int subShaderScopeCount = m_templateMPData.SubShaders[ SubShaderIdx ].AvailableShaderGlobals.Count;
for( int i = 0; i < subShaderScopeCount; i++ )
{
if( m_templateMPData.SubShaders[ SubShaderIdx ].AvailableShaderGlobals[ i ].PropertyName.Equals( m_propertyName ) )
{
m_currentScope = ShaderPropertyScope.SubShader;
}
}
int passScopeCount = m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ PassIdx ].AvailableShaderGlobals.Count;
for( int i = 0; i < passScopeCount; i++ )
{
if( m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ PassIdx ].AvailableShaderGlobals[ i ].PropertyName.Equals( m_propertyName ) )
{
m_currentScope = ShaderPropertyScope.Pass;
}
}
}
void FetchShaderProperties()
{
if( m_templateMPData == null )
m_templateMPData = ( m_containerGraph.CurrentMasterNode as TemplateMultiPassMasterNode ).CurrentTemplate;
if( m_templateMPData != null )
{
if( m_advancedView )
{
switch( m_currentScope )
{
case ShaderPropertyScope.Shader:
m_shaderProperties = m_templateMPData.AvailableShaderProperties;
break;
case ShaderPropertyScope.SubShader:
m_shaderProperties = m_templateMPData.SubShaders[ SubShaderIdx ].AvailableShaderGlobals;
break;
case ShaderPropertyScope.Pass:
m_shaderProperties = m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ PassIdx ].AvailableShaderGlobals;
break;
}
}
else
{
m_shaderProperties = m_templateMPData.AllShaderProperties;
if( m_currentPropertyIdx < 0 && m_shaderProperties.Count > 0 )
{
m_currentPropertyIdx = 0;
}
}
}
}
public override void OnEnable()
{
base.OnEnable();
IntPropertyId = Shader.PropertyToID( "_IntData" );
FloatPropertyId = Shader.PropertyToID( "_FloatData" );
VectorPropertyId = Shader.PropertyToID( "_VectorData" );
Sampler2DPropertyId = Shader.PropertyToID( "_Sampler2DData" );
Sampler3DPropertyId = Shader.PropertyToID( "_Sampler3DData" );
SamplerCubePropertyId = Shader.PropertyToID( "_SamplerCubeData" );
}
public override void DrawProperties()
{
base.DrawProperties();
EditorGUI.BeginChangeCheck();
m_advancedView = EditorGUILayoutToggle( "Advanced View", m_advancedView );
if( EditorGUI.EndChangeCheck() )
{
if( m_advancedView )
{
if( m_shaderProperties[ m_currentPropertyIdx ].PassId >= 0 )
{
m_currentScope = ShaderPropertyScope.Pass;
PassIdx = m_shaderProperties[ m_currentPropertyIdx ].PassId;
SubShaderIdx = m_shaderProperties[ m_currentPropertyIdx ].SubShaderId;
}
else if( m_shaderProperties[ m_currentPropertyIdx ].SubShaderId >= 0 )
{
m_currentScope = ShaderPropertyScope.SubShader;
SubShaderIdx = m_shaderProperties[ m_currentPropertyIdx ].SubShaderId;
PassIdx = 0;
}
else
{
m_currentScope = ShaderPropertyScope.Shader;
SubShaderIdx = 0;
PassIdx = 0;
}
}
FetchShaderProperties();
FetchPropertyId();
}
if( m_advancedView && m_multiPassMode )
{
DrawMultipassProperties();
}
if( m_currentPropertyIdx > -1 )
{
bool hasProperties = ( m_shaderProperties != null && m_shaderProperties.Count > 0 );
if( hasProperties )
{
EditorGUI.BeginChangeCheck();
m_currentPropertyIdx = EditorGUILayoutPopup( PropertyLabelStr, m_currentPropertyIdx, m_propertyLabels );
if( EditorGUI.EndChangeCheck() )
{
UpdateFromId();
}
EditorGUILayout.LabelField( m_typeName );
if( m_shaderProperties[ m_currentPropertyIdx ].PropertyType != PropertyType.Global )
{
EditorGUILayout.LabelField( m_propertyNameLabel );
}
}
}
}
void DrawMultipassProperties()
{
EditorGUI.BeginChangeCheck();
m_currentScope = (ShaderPropertyScope)EditorGUILayoutEnumPopup( CurrentScopeStr, m_currentScope );
if( EditorGUI.EndChangeCheck() )
{
FetchShaderProperties();
FetchPropertyId();
}
bool showSubShader = false;
bool showPass = false;
switch( m_currentScope )
{
case ShaderPropertyScope.SubShader:
{
showSubShader = true;
}
break;
case ShaderPropertyScope.Pass:
{
showSubShader = true;
showPass = true;
}
break;
}
if( showSubShader )
{
DrawSubShaderUI();
}
if( showPass )
{
DrawPassUI();
}
}
protected override void OnSubShaderChange()
{
FetchShaderProperties();
FetchPropertyId();
}
protected override void OnPassChange()
{
FetchShaderProperties();
FetchPropertyId();
}
override protected void CheckWarningState()
{
if( m_containerGraph.CurrentCanvasMode != NodeAvailability.TemplateShader )
{
ShowTab( NodeMessageType.Error, ErrorMessageStr );
}
else
{
if( m_shaderProperties != null &&
m_shaderProperties.Count > 0 &&
m_shaderProperties.Count > m_currentPropertyIdx &&
m_shaderProperties[ m_currentPropertyIdx ].PropertyType == PropertyType.Global &&
m_showPreview )
{
ShowTab( NodeMessageType.Info, WarningStr );
}
else
{
m_showErrorMessage = false;
}
}
}
public override void SetPreviewInputs()
{
if( m_containerGraph.CurrentCanvasMode != NodeAvailability.TemplateShader )
return;
if( m_shaderProperties == null || m_currentPropertyIdx >= m_shaderProperties.Count || m_currentPropertyIdx < 0 )
return;
if( m_shaderProperties[ m_currentPropertyIdx ].PropertyType == PropertyType.Global )
{
m_additionalContent.text = string.Empty;
PreviewMaterial.SetInt( IntPropertyId, 0 );
return;
}
Material currMat = m_containerGraph.CurrentMaterial;
if( currMat != null && currMat.HasProperty( m_propertyNameId ) )
{
switch( m_shaderProperties[ m_currentPropertyIdx ].PropertyDataType )
{
case WirePortDataType.INT:
{
int value = currMat.GetInt( m_propertyNameId );
SetAdditonalTitleText( string.Format( Constants.SubTitleValueFormatStr, GenerateTitle( value ) ) );
PreviewMaterial.SetInt( IntPropertyId, value );
}
break;
case WirePortDataType.FLOAT:
{
float value = currMat.GetFloat( m_propertyNameId );
SetAdditonalTitleText( string.Format( Constants.SubTitleValueFormatStr, GenerateTitle( value ) ) );
PreviewMaterial.SetFloat( FloatPropertyId, value );
}
break;
case WirePortDataType.FLOAT4:
{
Vector4 value = currMat.GetVector( m_propertyNameId );
SetAdditonalTitleText( string.Format( Constants.SubTitleValueFormatStr, GenerateTitle( value.x, value.y, value.z, value.w ) ) );
PreviewMaterial.SetVector( VectorPropertyId, value );
}
break;
case WirePortDataType.COLOR:
{
Color value = currMat.GetColor( m_propertyNameId );
SetAdditonalTitleText( string.Format( Constants.SubTitleValueFormatStr, GenerateTitle( value.r, value.g, value.b, value.a ) ) );
PreviewMaterial.SetColor( VectorPropertyId, value );
}
break;
case WirePortDataType.SAMPLER2D:
{
Texture value = currMat.GetTexture( m_propertyNameId );
if( value )
SetAdditonalTitleText( string.Format( Constants.SubTitleValueFormatStr, value.name ) );
else
SetAdditonalTitleText( string.Empty );
PreviewMaterial.SetTexture( Sampler2DPropertyId, value );
}
break;
case WirePortDataType.SAMPLER3D:
{
Texture value = currMat.GetTexture( m_propertyNameId );
if( value )
SetAdditonalTitleText( string.Format( Constants.SubTitleValueFormatStr, value.name ) );
else
SetAdditonalTitleText( string.Empty );
PreviewMaterial.SetTexture( Sampler3DPropertyId, value );
}
break;
case WirePortDataType.SAMPLERCUBE:
{
Texture value = currMat.GetTexture( m_propertyNameId );
if( value )
SetAdditonalTitleText( string.Format( Constants.SubTitleValueFormatStr, value.name ) );
else
SetAdditonalTitleText( string.Empty );
PreviewMaterial.SetTexture( SamplerCubePropertyId, value );
}
break;
case WirePortDataType.SAMPLER2DARRAY:
{
Texture value = currMat.GetTexture( m_propertyNameId );
if( value )
SetAdditonalTitleText( string.Format( Constants.SubTitleValueFormatStr, value.name ) );
else
SetAdditonalTitleText( string.Empty );
PreviewMaterial.SetTexture( SamplerCubePropertyId, value );
}
break;
}
}
else
{
SetAdditonalTitleText( string.Empty );
}
}
public override void Draw( DrawInfo drawInfo )
{
if( m_containerGraph.CurrentCanvasMode != NodeAvailability.TemplateShader )
{
if( !m_showErrorMessage || m_errorMessageTypeIsError == NodeMessageType.Info )
{
ShowTab( NodeMessageType.Error, ErrorMessageStr );
}
}
else if( m_showErrorMessage )
{
if( m_errorMessageTypeIsError == NodeMessageType.Error )
HideTab();
}
base.Draw( drawInfo );
if( m_containerGraph.CurrentCanvasMode != NodeAvailability.TemplateShader )
return;
if( m_shaderProperties == null )
{
MasterNode masterNode = m_containerGraph.CurrentMasterNode;
if( masterNode.CurrentMasterNodeCategory == AvailableShaderTypes.Template )
{
if( SetTemplate( masterNode ) )
{
m_fetchPropertyId = true;
}
}
}
if( m_fetchScopeFromProperty )
{
m_fetchScopeFromProperty = false;
FetchScope();
FetchShaderProperties();
}
if( m_fetchPropertyId )
{
m_fetchPropertyId = false;
FetchPropertyId();
}
if( m_currentPropertyIdx > -1 )
{
EditorGUI.BeginChangeCheck();
m_currentPropertyIdx = m_upperLeftWidgetHelper.DrawWidget( this, m_currentPropertyIdx, m_propertyLabels );
if( EditorGUI.EndChangeCheck() )
{
UpdateFromId();
}
}
}
void FetchPropertyId()
{
if( m_shaderProperties != null )
{
m_currentPropertyIdx = 0;
m_propertyLabels = new string[ m_shaderProperties.Count ];
for( int i = 0; i < m_shaderProperties.Count; i++ )
{
if( m_shaderProperties[ i ].PropertyName.Equals( m_propertyName ) )
{
m_currentPropertyIdx = i;
}
m_propertyLabels[ i ] = m_shaderProperties[ i ].PropertyInspectorName;
}
UpdateFromId();
}
else
{
m_currentPropertyIdx = -1;
}
}
void UpdateFromId()
{
if( m_shaderProperties != null )
{
if( m_shaderProperties.Count == 0 )
{
for( int i = 0; i < 4; i++ )
m_containerGraph.DeleteConnection( false, UniqueId, i, false, true );
m_headerColor = UIUtils.GetColorFromCategory( "Default" );
m_content.text = "None";
m_additionalContent.text = string.Empty;
m_previewMaterialPassId = 1;
PreviewMaterial.SetFloat( FloatPropertyId, 0 );
m_showPreview = false;
m_drawPreviewExpander = false;
m_outputPorts[ 0 ].ChangeProperties( "None", WirePortDataType.FLOAT, false );
ConfigurePorts();
return;
}
m_drawPreviewExpander = true;
bool areCompatible = TemplateHelperFunctions.CheckIfCompatibles( m_outputPorts[ 0 ].DataType, m_shaderProperties[ m_currentPropertyIdx ].PropertyDataType );
switch( m_shaderProperties[ m_currentPropertyIdx ].PropertyDataType )
{
case WirePortDataType.SAMPLER1D:
case WirePortDataType.SAMPLER2D:
case WirePortDataType.SAMPLER3D:
case WirePortDataType.SAMPLERCUBE:
case WirePortDataType.SAMPLER2DARRAY:
m_outputPorts[ 0 ].ChangeProperties( "Tex", m_shaderProperties[ m_currentPropertyIdx ].PropertyDataType, false );
m_headerColor = UIUtils.GetColorFromCategory( "Textures" );
break;
case WirePortDataType.INT:
case WirePortDataType.FLOAT:
m_outputPorts[ 0 ].ChangeProperties( Constants.EmptyPortValue, m_shaderProperties[ m_currentPropertyIdx ].PropertyDataType, false );
m_headerColor = UIUtils.GetColorFromCategory( "Constants And Properties" );
break;
case WirePortDataType.FLOAT4:
m_outputPorts[ 0 ].ChangeProperties( "XYZW", m_shaderProperties[ m_currentPropertyIdx ].PropertyDataType, false );
m_headerColor = UIUtils.GetColorFromCategory( "Constants And Properties" );
break;
case WirePortDataType.COLOR:
m_outputPorts[ 0 ].ChangeProperties( "RGBA", m_shaderProperties[ m_currentPropertyIdx ].PropertyDataType, false );
m_headerColor = UIUtils.GetColorFromCategory( "Constants And Properties" );
break;
default:
case WirePortDataType.OBJECT:
case WirePortDataType.FLOAT3x3:
case WirePortDataType.FLOAT4x4:
m_outputPorts[ 0 ].ChangeProperties( "Out", m_shaderProperties[ m_currentPropertyIdx ].PropertyDataType, false );
m_headerColor = UIUtils.GetColorFromCategory( "Constants And Properties" );
break;
}
if( !areCompatible )
{
for( int i = 0; i < 4; i++ )
m_containerGraph.DeleteConnection( false, UniqueId, i, false, true );
}
ConfigurePorts();
m_propertyName = m_shaderProperties[ m_currentPropertyIdx ].PropertyName;
m_content.text = m_shaderProperties[ m_currentPropertyIdx ].PropertyInspectorName;
m_propertyNameId = Shader.PropertyToID( m_propertyName );
m_typeName = TypeLabelStr + m_shaderProperties[ m_currentPropertyIdx ].PropertyType.ToString();
if( m_shaderProperties[ m_currentPropertyIdx ].PropertyType != PropertyType.Global )
{
m_propertyNameLabel = PropertyNameStr + m_shaderProperties[ m_currentPropertyIdx ].PropertyName;
}
m_sizeIsDirty = true;
Material currMat = m_containerGraph.CurrentMaterial;
if( currMat != null )
{
if( m_shaderProperties[ m_currentPropertyIdx ].PropertyType == PropertyType.Global )
{
m_previewMaterialPassId = 0;
if( !m_showErrorMessage && m_showPreview )
{
ShowTab( NodeMessageType.Info, WarningStr );
}
}
else
{
if( m_showErrorMessage && m_errorMessageTypeIsError != NodeMessageType.Error )
{
HideTab();
}
switch( m_shaderProperties[ m_currentPropertyIdx ].PropertyDataType )
{
case WirePortDataType.INT: m_previewMaterialPassId = 0; break;
case WirePortDataType.FLOAT: m_previewMaterialPassId = 1; break;
case WirePortDataType.FLOAT4:
case WirePortDataType.COLOR: m_previewMaterialPassId = 2; break;
case WirePortDataType.SAMPLER2D: m_previewMaterialPassId = 3; break;
case WirePortDataType.SAMPLER3D: m_previewMaterialPassId = 4; break;
case WirePortDataType.SAMPLERCUBE: m_previewMaterialPassId = 5; break;
default: PreviewMaterial.SetPass( 0 ); break;
}
}
}
CheckWarningState();
}
}
string GenerateTitle( params float[] values )
{
//string finalResult = "( ";
string finalResult = string.Empty;
if( values.Length == 1 )
{
finalResult += values[ 0 ].ToString( Mathf.Abs( values[ 0 ] ) > 1000 ? Constants.PropertyBigFloatFormatLabel : Constants.PropertyFloatFormatLabel );
}
else
{
for( int i = 0; i < values.Length; i++ )
{
finalResult += values[ i ].ToString( Mathf.Abs( values[ i ] ) > 1000 ? Constants.PropertyBigVectorFormatLabel : Constants.PropertyVectorFormatLabel );
if( i < ( values.Length - 1 ) )
finalResult += ",";
}
}
//finalResult += " )";
return finalResult;
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if( dataCollector.MasterNodeCategory != AvailableShaderTypes.Template )
{
UIUtils.ShowMessage( UniqueId, "Template Parameter node is only intended for templates use only" );
return m_outputPorts[ outputId ].ErrorValue;
}
if( m_shaderProperties == null || m_shaderProperties.Count ==0 )
{
UIUtils.ShowMessage( UniqueId, "Attempting to fetch inexistant parameter on " + m_nodeAttribs.Name +" node");
return m_outputPorts[ outputId ].ErrorValue;
}
if( m_multiPassMode )
{
switch( m_currentScope )
{
case ShaderPropertyScope.SubShader:
{
if( dataCollector.TemplateDataCollectorInstance.MultipassSubshaderIdx != SubShaderIdx )
{
UIUtils.ShowMessage( UniqueId, string.Format( "{0} is only intended for subshader {1}", m_propertyLabels[ m_currentPropertyIdx ], SubShaderIdx ) );
return m_outputPorts[ outputId ].ErrorValue;
}
}
break;
case ShaderPropertyScope.Pass:
{
if( dataCollector.TemplateDataCollectorInstance.MultipassSubshaderIdx != SubShaderIdx ||
dataCollector.TemplateDataCollectorInstance.MultipassPassIdx != PassIdx
)
{
UIUtils.ShowMessage( UniqueId, string.Format( "{0} is only intended for subshader {1} and pass {2}", m_propertyLabels[ m_currentPropertyIdx ], SubShaderIdx, PassIdx ) );
return m_outputPorts[ outputId ].ErrorValue;
}
}
break;
}
}
return GetOutputVectorItem( 0, outputId, m_propertyName );
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
m_propertyName = GetCurrentParam( ref nodeParams );
m_propertyNameId = Shader.PropertyToID( m_propertyName );
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
m_currentScope = (ShaderPropertyScope)Enum.Parse( typeof( ShaderPropertyScope ), GetCurrentParam( ref nodeParams ) );
}
else
{
m_fetchScopeFromProperty = true;
}
m_fetchPropertyId = true;
if( UIUtils.CurrentShaderVersion() > 18502 )
{
m_advancedView = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) );
}
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_propertyName );
IOUtils.AddFieldValueToString( ref nodeInfo, m_currentScope );
IOUtils.AddFieldValueToString( ref nodeInfo, m_advancedView );
}
public override void OnMasterNodeReplaced( MasterNode newMasterNode )
{
base.OnMasterNodeReplaced( newMasterNode );
if( newMasterNode.CurrentMasterNodeCategory == AvailableShaderTypes.Template )
{
SetTemplate( newMasterNode );
if( m_fetchScopeFromProperty )
{
m_fetchScopeFromProperty = false;
FetchScope();
}
FetchShaderProperties();
FetchPropertyId();
//m_containerGraph.DeleteConnection( false, UniqueId, 0, false, true );
}
}
bool SetTemplate( MasterNode newMasterNode )
{
if( m_containerGraph.MultiPassMasterNodes.NodesList.Count > 0 )
{
m_multiPassMode = true;
TemplateMultiPassMasterNode templateMasterNode = ( newMasterNode as TemplateMultiPassMasterNode );
if( templateMasterNode != null )
{
m_templateMPData = templateMasterNode.CurrentTemplate;
UpdateSubShaderAmount();
FetchShaderProperties();
return true;
}
}
else
{
m_multiPassMode = false;
TemplateMasterNode templateMasterNode = ( newMasterNode as TemplateMasterNode );
if( templateMasterNode != null )
{
m_shaderProperties = templateMasterNode.CurrentTemplate.AvailableShaderProperties;
return true;
}
}
return false;
}
public override void RefreshExternalReferences()
{
base.RefreshExternalReferences();
CheckWarningState();
}
public override void Destroy()
{
base.Destroy();
m_propertyLabels = null;
m_shaderProperties = null;
m_upperLeftWidgetHelper = null;
}
}
}

View File

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

View File

@@ -0,0 +1,172 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateSubShader
{
[SerializeField]
private int m_idx = -1;
[SerializeField]
private List<TemplatePass> m_passes = new List<TemplatePass>();
[SerializeField]
private TemplateModulesData m_modules;
[SerializeField]
private string m_uniquePrefix;
[SerializeField]
private TemplatePropertyContainer m_templateProperties = new TemplatePropertyContainer();
[SerializeField]
private List<TemplateShaderPropertyData> m_availableShaderGlobals = new List<TemplateShaderPropertyData>();
[SerializeField]
private TemplateInfoContainer m_LODContainer = new TemplateInfoContainer();
[SerializeField]
private int m_passAmount = 0;
[SerializeField]
private int m_mainPass = -1;
[SerializeField]
private bool m_foundMainPassTag = false;
[SerializeField]
TemplateOptionsContainer m_customOptionsContainer = new TemplateOptionsContainer();
public TemplateSubShader(TemplateMultiPass template, int subShaderIx, TemplateIdManager idManager, string uniquePrefix, TemplateSubShaderInfo subShaderInfo, ref Dictionary<string, TemplateShaderPropertyData> duplicatesHelper )
{
m_idx = subShaderIx;
m_uniquePrefix = uniquePrefix;
FetchLOD( subShaderInfo.StartIdx, subShaderInfo.Modules );
if( m_LODContainer.Index > -1 )
{
idManager.RegisterId( m_LODContainer.Index, uniquePrefix + "Module" + m_LODContainer.Id, m_LODContainer.Id );
}
m_customOptionsContainer = TemplateOptionsToolsHelper.GenerateOptionsContainer( true, subShaderInfo.Data );
if( m_customOptionsContainer.Enabled )
{
idManager.RegisterId( m_customOptionsContainer.Index, uniquePrefix + m_customOptionsContainer.Body, m_customOptionsContainer.Body, true );
}
m_modules = new TemplateModulesData( m_customOptionsContainer, idManager, m_templateProperties, uniquePrefix + "Module", subShaderInfo.StartIdx, subShaderInfo.Modules, true );
if( m_modules.SRPType == TemplateSRPType.HD )
{
m_modules.SRPIsPBR = subShaderInfo.Data.Contains( TemplateHelperFunctions.HDPBRTag );
}
Dictionary<string, TemplateShaderPropertyData> ownDuplicatesDict = new Dictionary<string, TemplateShaderPropertyData>( duplicatesHelper );
TemplateHelperFunctions.CreateShaderGlobalsList( subShaderInfo.Modules, ref m_availableShaderGlobals, ref ownDuplicatesDict,subShaderIx,-1 );
if( m_modules.SRPType == TemplateSRPType.BuiltIn )
{
TemplateHelperFunctions.CheckUnityBuiltinGlobalMacros( subShaderInfo.Modules, ref m_availableShaderGlobals, ref ownDuplicatesDict,subShaderIx,-1 );
}
m_passAmount = subShaderInfo.Passes.Count;
//if( !m_modules.PassTag.IsValid )
//{
// m_modules.PassTag.StartIdx = subShaderData.Passes[ 0 ].GlobalStartIdx;
// m_templateProperties.AddId( subShaderData.Data, m_modules.PassTag.Id, subShaderData.Passes[ 0 ].LocalStartIdx, m_modules.PassTag.SearchIndentation );
// m_modules.PassTag.StartIdx -= m_templateProperties.PropertyDict[ m_modules.PassTag.Id ].Indentation.Length;
// m_templateProperties.PropertyDict[ m_modules.PassTag.Id ].UseIndentationAtStart = true;
// idManager.RegisterId( m_modules.PassTag.StartIdx, m_modules.UniquePrefix + m_modules.PassTag.Id, string.Empty );
//}
int firstVisible = -1;
int currAddedPassIdx = 0;
for( int passIdx = 0; passIdx < m_passAmount; passIdx++ )
{
TemplatePass newPass = new TemplatePass( template, this,subShaderIx, passIdx, idManager, uniquePrefix + "Pass" + passIdx, subShaderInfo.Passes[ passIdx ].GlobalStartIdx, subShaderInfo.Passes[ passIdx ], ref ownDuplicatesDict );
if( newPass.AddToList )
{
if( newPass.IsMainPass && m_mainPass < 0 )
{
m_mainPass = currAddedPassIdx;
m_foundMainPassTag = true;
}
else if(!newPass.IsInvisible && firstVisible < 0 )
{
firstVisible = currAddedPassIdx;
}
m_passes.Add( newPass );
currAddedPassIdx++;
}
else
{
newPass.Destroy();
newPass = null;
}
}
if( m_mainPass < 0 )
{
// If no main pass was set then choose the first visible one
m_mainPass = ( firstVisible < 0 ) ? 0 : firstVisible;
m_passes[ m_mainPass ].IsMainPass = true;
}
ownDuplicatesDict.Clear();
ownDuplicatesDict = null;
}
public void Destroy()
{
m_LODContainer = null;
m_customOptionsContainer = null;
m_templateProperties.Destroy();
m_templateProperties = null;
m_passes.Clear();
m_passes = null;
m_modules.Destroy();
m_modules = null;
m_availableShaderGlobals.Clear();
m_availableShaderGlobals = null;
}
void FetchLOD( int offsetIdx, string body )
{
Match match = Regex.Match( body, TemplateHelperFunctions.SubShaderLODPattern );
if( match != null && match.Groups.Count > 1 )
{
m_LODContainer.Id = match.Groups[ 0 ].Value;
m_LODContainer.Data = match.Groups[ 1 ].Value;
m_LODContainer.Index = offsetIdx + match.Index;
}
}
public List<TemplatePass> Passes { get { return m_passes; } }
public TemplateModulesData Modules { get { return m_modules; } }
public string UniquePrefix { get { return m_uniquePrefix; } }
public TemplatePropertyContainer TemplateProperties { get { return m_templateProperties; } }
public List<TemplateShaderPropertyData> AvailableShaderGlobals { get { return m_availableShaderGlobals; } }
public TemplateInfoContainer LODContainer { get { return m_LODContainer; } }
public int PassAmount { get { return m_passAmount; } }
public bool FoundMainPass { get { return m_foundMainPassTag; } }
public int MainPass { get { return m_mainPass; } }
public int Idx { get { return m_idx; } }
public TemplateOptionsContainer CustomOptionsContainer { get { return m_customOptionsContainer; } }
}
}

View File

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

View File

@@ -0,0 +1,465 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateTagsModule : TemplateModuleParent
{
private const string CustomTagsStr = "Tags";
private const string TagNameStr = "Name";
private const string TagValueStr = "Value";
private const string QueueIndexStr = "Index";
private const string QueueLabelStr = "Queue";
private const string RenderTypeLabelStr = "Type";
private const string CustomRenderTypeLabelStr = "Custom";
private const float ShaderKeywordButtonLayoutWidth = 15;
private UndoParentNode m_currentOwner;
private double m_tagNameCheckTimestamp = 0;
private bool m_tagNameCheckFlag = true;
private int m_tagNameCheckItemId = 0;
private const double TagNameCheckMaxInterval = 1.5;
[SerializeField]
private bool m_foldout = false;
[SerializeField]
private List<CustomTagData> m_availableTags = new List<CustomTagData>();
private Dictionary<string, CustomTagData> m_availableTagsDict = new Dictionary<string, CustomTagData>();
public TemplateTagsModule() : base( "Tags" ) { }
public void CopyFrom( TemplateTagsModule other )
{
m_availableTags.Clear();
m_availableTagsDict.Clear();
int count = other.AvailableTags.Count;
for( int i = 0; i < count; i++ )
{
CustomTagData newData = new CustomTagData( other.AvailableTags[ i ] );
m_availableTags.Add( newData );
m_availableTagsDict.Add( newData.TagName, newData );
}
}
public void ConfigureFromTemplateData( TemplateTagsModuleData tagsData )
{
bool newValidData = tagsData.DataCheck == TemplateDataCheck.Valid;
if( newValidData && newValidData != m_validData )
{
m_availableTags.Clear();
m_availableTagsDict.Clear();
int count = tagsData.Tags.Count;
for( int i = 0; i < count; i++ )
{
CustomTagData tagData = new CustomTagData( tagsData.Tags[ i ].Name, tagsData.Tags[ i ].Value, i );
m_availableTags.Add( tagData );
m_availableTagsDict.Add( tagsData.Tags[ i ].Name, tagData );
}
}
m_validData = newValidData;
}
public override void ShowUnreadableDataMessage( ParentNode owner )
{
//bool foldout = owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedCustomTags;
NodeUtils.DrawPropertyGroup( ref m_foldout, CustomTagsStr, base.ShowUnreadableDataMessage );
//owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedCustomTags = foldout;
}
public void OnLogicUpdate()
{
if( m_tagNameCheckFlag && ( EditorApplication.timeSinceStartup - m_tagNameCheckTimestamp ) > TagNameCheckMaxInterval )
{
m_tagNameCheckFlag = false;
if( m_tagNameCheckItemId < m_availableTags.Count )
{
if( m_availableTags[ m_tagNameCheckItemId ].TagName.Equals( Constants.RenderQueueHelperStr ) )
{
m_availableTags[ m_tagNameCheckItemId ].SpecialTag = TemplateSpecialTags.Queue;
}
else if( m_availableTags[ m_tagNameCheckItemId ].TagName.Equals( Constants.RenderTypeHelperStr ) )
{
m_availableTags[ m_tagNameCheckItemId ].SpecialTag = TemplateSpecialTags.RenderType;
}
else if( m_availableTags[ m_tagNameCheckItemId ].TagName.Equals( Constants.DisableBatchingHelperStr ) )
{
m_availableTags[ m_tagNameCheckItemId ].SpecialTag = TemplateSpecialTags.DisableBatching;
}
else
{
m_availableTags[ m_tagNameCheckItemId ].SpecialTag = TemplateSpecialTags.None;
}
}
}
}
public override void Draw( UndoParentNode owner, bool style = true )
{
m_currentOwner = owner;
//bool foldout = owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedCustomTags;
if( style )
{
NodeUtils.DrawPropertyGroup( ref m_foldout, CustomTagsStr, DrawMainBody, DrawButtons );
}
else
{
NodeUtils.DrawNestedPropertyGroup( ref m_foldout, CustomTagsStr, DrawMainBody, DrawButtons );
}
//owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedCustomTags = foldout;
}
void DrawButtons()
{
EditorGUILayout.Separator();
// Add tag
if( GUILayout.Button( string.Empty, UIUtils.PlusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
m_availableTags.Add( new CustomTagData() );
EditorGUI.FocusTextInControl( null );
}
//Remove tag
if( GUILayout.Button( string.Empty, UIUtils.MinusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
if( m_availableTags.Count > 0 )
{
m_availableTags.RemoveAt( m_availableTags.Count - 1 );
EditorGUI.FocusTextInControl( null );
}
}
}
void DrawMainBody()
{
EditorGUI.BeginChangeCheck();
{
EditorGUILayout.Separator();
int itemCount = m_availableTags.Count;
if( itemCount == 0 )
{
EditorGUILayout.HelpBox( "Your list is Empty!\nUse the plus button to add one.", MessageType.Info );
}
int markedToDelete = -1;
float originalLabelWidth = EditorGUIUtility.labelWidth;
for( int i = 0; i < itemCount; i++ )
{
m_availableTags[ i ].TagFoldout = m_currentOwner.EditorGUILayoutFoldout( m_availableTags[ i ].TagFoldout, string.Format( "[{0}] - {1}", i, m_availableTags[ i ].TagName ) );
if( m_availableTags[ i ].TagFoldout )
{
EditorGUI.indentLevel += 1;
EditorGUIUtility.labelWidth = 70;
//Tag Name
EditorGUI.BeginChangeCheck();
m_availableTags[ i ].TagName = m_currentOwner.EditorGUILayoutTextField( TagNameStr, m_availableTags[ i ].TagName );
if( EditorGUI.EndChangeCheck() )
{
m_availableTags[ i ].TagName = UIUtils.RemoveShaderInvalidCharacters( m_availableTags[ i ].TagName );
m_tagNameCheckFlag = true;
m_tagNameCheckItemId = i;
m_tagNameCheckTimestamp = EditorApplication.timeSinceStartup;
}
//Tag Value
switch( m_availableTags[ i ].SpecialTag )
{
case TemplateSpecialTags.DisableBatching:
{
m_availableTags[ i ].Batching = (DisableBatching)m_currentOwner.EditorGUILayoutEnumPopup( RenderTypeLabelStr, m_availableTags[ i ].Batching );
m_availableTags[ i ].TagValue = m_availableTags[ i ].Batching.ToString();
}
break;
case TemplateSpecialTags.RenderType:
{
m_availableTags[ i ].RenderType = (RenderType)m_currentOwner.EditorGUILayoutEnumPopup( RenderTypeLabelStr, m_availableTags[ i ].RenderType );
if( m_availableTags[ i ].RenderType == RenderType.Custom )
{
m_availableTags[ i ].TagValue = m_currentOwner.EditorGUILayoutTextField( CustomRenderTypeLabelStr, m_availableTags[ i ].TagValue );
}
}
break;
case TemplateSpecialTags.Queue:
{
EditorGUI.BeginChangeCheck();
m_availableTags[ i ].RenderQueue = (RenderQueue)m_currentOwner.EditorGUILayoutEnumPopup( QueueLabelStr, m_availableTags[ i ].RenderQueue, GUILayout.MinWidth( 150 ) );
m_availableTags[ i ].RenderQueueOffset = m_currentOwner.EditorGUILayoutIntField( QueueIndexStr, m_availableTags[ i ].RenderQueueOffset );
if( EditorGUI.EndChangeCheck() )
{
m_availableTags[ i ].BuildQueueTagValue();
}
}
break;
case TemplateSpecialTags.None:
{
EditorGUI.BeginChangeCheck();
m_availableTags[ i ].TagValue = m_currentOwner.EditorGUILayoutTextField( TagValueStr, m_availableTags[ i ].TagValue );
if( EditorGUI.EndChangeCheck() )
{
m_availableTags[ i ].TagValue = UIUtils.RemoveShaderInvalidCharacters( m_availableTags[ i ].TagValue );
}
}
break;
}
EditorGUIUtility.labelWidth = originalLabelWidth;
EditorGUILayout.BeginHorizontal();
{
GUILayout.Label( " " );
// Add new port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.PlusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
m_availableTags.Insert( i + 1, new CustomTagData() );
EditorGUI.FocusTextInControl( null );
}
//Remove port
if( m_currentOwner.GUILayoutButton( string.Empty, UIUtils.MinusStyle, GUILayout.Width( ShaderKeywordButtonLayoutWidth ) ) )
{
markedToDelete = i;
}
}
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel -= 1;
}
}
if( markedToDelete > -1 )
{
if( m_availableTags.Count > markedToDelete )
{
m_availableTags.RemoveAt( markedToDelete );
EditorGUI.FocusTextInControl( null );
}
}
EditorGUILayout.Separator();
}
if( EditorGUI.EndChangeCheck() )
{
m_isDirty = true;
}
}
//Method used by template options
// As such. Render Queue will have value and offset separated by ,
public void AddSpecialTag( TemplateSpecialTags tag, TemplateActionItem item )
{
if( tag == TemplateSpecialTags.None )
return;
int count = m_availableTags.Count;
for( int i = 0; i < count; i++ )
{
if( m_availableTags[ i ].SpecialTag == tag )
{
switch( tag )
{
case TemplateSpecialTags.DisableBatching:
{
m_availableTags[ i ].Batching = TemplateHelperFunctions.StringToDisableBatching[ item.ActionData ];
return;
}
case TemplateSpecialTags.RenderType:
{
m_availableTags[ i ].RenderType = TemplateHelperFunctions.StringToRenderType[ item.ActionData ];
return;
}
case TemplateSpecialTags.Queue:
{
m_availableTags[ i ].RenderQueue = TemplateHelperFunctions.StringToRenderQueue[ item.ActionData ];
m_availableTags[ i ].RenderQueueOffset = item.ActionDataIdx;
m_availableTags[ i ].BuildQueueTagValue();
return;
}
}
}
}
CustomTagData data = new CustomTagData();
switch( tag )
{
case TemplateSpecialTags.DisableBatching:
{
data.SpecialTag = TemplateSpecialTags.DisableBatching;
data.TagName = "DisableBatching";
data.Batching = TemplateHelperFunctions.StringToDisableBatching[ item.ActionData ];
}
break;
case TemplateSpecialTags.RenderType:
{
data.SpecialTag = TemplateSpecialTags.RenderType;
data.TagName = "RenderType";
data.RenderType = TemplateHelperFunctions.StringToRenderType[ item.ActionData ];
}
break;
case TemplateSpecialTags.Queue:
{
data.SpecialTag = TemplateSpecialTags.Queue;
data.TagName = "Queue";
data.RenderQueue = TemplateHelperFunctions.StringToRenderQueue[ item.ActionData ];
data.RenderQueueOffset = item.ActionDataIdx;
data.BuildQueueTagValue();
}
break;
}
m_availableTags.Add( data );
}
void AddTagFromRead( string data )
{
string[] arr = data.Split( IOUtils.VALUE_SEPARATOR );
if( arr.Length > 1 )
{
string name = arr[ 0 ];
string value = arr[ 1 ];
if( !m_availableTagsDict.ContainsKey( name ) )
{
CustomTagData tagData = new CustomTagData( data, m_availableTags.Count - 1 );
m_availableTags.Add( tagData );
m_availableTagsDict.Add( name, tagData );
}
else
{
if( m_availableTagsDict[ name ].TagId > -1 &&
m_availableTagsDict[ name ].TagId < m_availableTags.Count )
{
if( arr.Length == 4 )
{
m_availableTags[ m_availableTagsDict[ name ].TagId ].SetTagValue( value, arr[ 3 ] );
}
else
{
m_availableTags[ m_availableTagsDict[ name ].TagId ].SetTagValue( value );
}
}
else
{
int count = m_availableTags.Count;
for( int i = 0; i < count; i++ )
{
if( m_availableTags[ i ].TagName.Equals( name ) )
{
m_availableTags[ i ].SetTagValue( value );
}
}
}
}
}
}
public override void ReadFromString( ref uint index, ref string[] nodeParams )
{
bool validDataOnMeta = m_validData;
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
validDataOnMeta = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( validDataOnMeta )
{
int count = Convert.ToInt32( nodeParams[ index++ ] );
for( int i = 0; i < count; i++ )
{
AddTagFromRead( nodeParams[ index++ ] );
}
}
}
public override void WriteToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_validData );
if( m_validData )
{
int tagsCount = m_availableTags.Count;
IOUtils.AddFieldValueToString( ref nodeInfo, tagsCount );
for( int i = 0; i < tagsCount; i++ )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_availableTags[ i ].ToString() );
}
}
}
public string GenerateTags()
{
int tagsCount = m_availableTags.Count;
if( tagsCount == 0 )
return string.Empty;
string result = "Tags { ";
for( int i = 0; i < tagsCount; i++ )
{
if( m_availableTags[ i ].IsValid )
{
result += m_availableTags[ i ].GenerateTag();
if( i < tagsCount - 1 )
{
result += " ";
}
}
}
result += " }";
return result;
}
public override void Destroy()
{
m_availableTags.Clear();
m_availableTags = null;
m_currentOwner = null;
m_availableTagsDict.Clear();
m_availableTagsDict = null;
}
public List<CustomTagData> AvailableTags { get { return m_availableTags; } }
public bool HasRenderInfo( ref RenderType renderType, ref RenderQueue renderQueue )
{
if( !m_validData )
return false;
bool foundRenderType = false;
bool foundRenderQueue = false;
int count = m_availableTags.Count;
for( int i = 0; i < count; i++ )
{
if( m_availableTags[ i ].TagName.Equals( Constants.RenderTypeHelperStr ) )
{
if( TemplateHelperFunctions.StringToRenderType.ContainsKey( m_availableTags[ i ].TagValue ) )
{
renderType = TemplateHelperFunctions.StringToRenderType[ m_availableTags[ i ].TagValue ];
foundRenderType = true;
}
}
else if( m_availableTags[ i ].TagName.Equals( Constants.RenderQueueHelperStr ) )
{
string value = m_availableTags[ i ].TagValue.Split( '+' )[ 0 ].Split( '-' )[ 0 ];
if( TemplateHelperFunctions.StringToRenderQueue.ContainsKey( value ) )
{
renderQueue = TemplateHelperFunctions.StringToRenderQueue[ value ];
foundRenderQueue = true;
}
}
}
return foundRenderType && foundRenderQueue;
}
}
}

View File

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

View File

@@ -0,0 +1,190 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using UnityEngine;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateVertexData
{
[SerializeField]
private TemplateSemantics m_semantics = TemplateSemantics.NONE;
[SerializeField]
private WirePortDataType m_dataType = WirePortDataType.OBJECT;
[SerializeField]
private string m_varName = string.Empty;
[SerializeField]
private TemplateInfoOnSematics m_dataInfo = TemplateInfoOnSematics.NONE;
[SerializeField]
private string m_dataSwizzle = string.Empty;
[SerializeField]
private bool m_available = false;
[SerializeField]
private string m_varNameWithSwizzle = string.Empty;
[SerializeField]
private bool m_isSingleComponent = true;
[SerializeField]
private bool m_excludeStructPrefix = false;
[SerializeField]
private string[] m_components = { "0", "0", "0", "0" };
[SerializeField]
private bool[] m_componentUsage = { false, false,false,false };
public TemplateVertexData( TemplateSemantics semantics, WirePortDataType dataType, string varName )
{
m_semantics = semantics;
m_dataType = dataType;
m_varName = varName;
m_varNameWithSwizzle = varName;
}
public TemplateVertexData( TemplateSemantics semantics, WirePortDataType dataType, string varName, string dataSwizzle )
{
m_semantics = semantics;
m_dataType = dataType;
m_varName = varName;
m_dataSwizzle = dataSwizzle;
m_varNameWithSwizzle = varName + dataSwizzle;
}
public TemplateVertexData( TemplateVertexData other )
{
m_semantics = other.m_semantics;
m_dataType = other.m_dataType;
m_varName = other.m_varName;
m_dataInfo = other.m_dataInfo;
m_dataSwizzle = other.m_dataSwizzle;
m_available = other.m_available;
m_varNameWithSwizzle = other.m_varNameWithSwizzle;
m_isSingleComponent = other.IsSingleComponent;
m_excludeStructPrefix = other.ExcludeStructPrefix;
for( int i = 0; i < 4; i++ )
{
m_components[ i ] = other.Components[ i ];
}
}
public void RegisterComponent( char channelId, string value )
{
int channelIdInt = -1;
switch( channelId )
{
case 'r':
case 'x': channelIdInt = 0; break;
case 'g':
case 'y': channelIdInt = 1; break;
case 'b':
case 'z': channelIdInt = 2; break;
case 'a':
case 'w': channelIdInt = 3; break;
}
if( channelId < 0 )
{
Debug.LogWarning( "Attempting to create interpolated data from invalid channel " + channelId );
return;
}
RegisterComponent( channelIdInt, value );
}
public void RegisterComponent( int channelId, string value )
{
channelId = Mathf.Clamp( channelId, 0, 3 );
m_components[ channelId ] = value;
m_componentUsage[ channelId ] = true;
m_isSingleComponent = false;
}
public void BuildVar( PrecisionType precisionType = PrecisionType.Float )
{
if( m_isSingleComponent )
return;
WirePortDataType dataType = WirePortDataType.FLOAT;
if( m_componentUsage[ 3 ] )
{
dataType = WirePortDataType.FLOAT4;
}
else if( m_componentUsage[ 2 ] )
{
dataType = WirePortDataType.FLOAT3;
}
else if( m_componentUsage[ 1 ] )
{
dataType = WirePortDataType.FLOAT2;
}
string newVar = UIUtils.PrecisionWirePortToCgType( precisionType, dataType );
newVar += "( ";
switch( dataType )
{
default: newVar += "0"; break;
case WirePortDataType.INT:
case WirePortDataType.FLOAT:
{
newVar += "{0}."+Components[ 0 ];
}
break;
case WirePortDataType.FLOAT2:
{
newVar += "{0}." + Components[ 0 ] + ", " +
"{0}." + Components[ 1 ];
}
break;
case WirePortDataType.FLOAT3:
{
newVar += "{0}." + Components[ 0 ] + ", " +
"{0}." + Components[ 1 ] + ", " +
"{0}." + Components[ 2 ];
}
break;
case WirePortDataType.FLOAT4:
case WirePortDataType.COLOR:
{
newVar += "{0}." + Components[ 0 ] + ", " +
"{0}." + Components[ 1 ] + ", " +
"{0}." + Components[ 2 ] + ", " +
"{0}." + Components[ 3 ];
}
break;
}
newVar += " )";
m_varName = newVar;
m_varNameWithSwizzle = newVar;
}
public bool ExcludeStructPrefix { get { return m_excludeStructPrefix; } set { m_excludeStructPrefix = value; } }
public bool IsSingleComponent { get { return m_isSingleComponent; } }
public string[] Components { get { return m_components; } }
public TemplateSemantics Semantics { get { return m_semantics; } }
public WirePortDataType DataType { get { return m_dataType; } }
public string VarName { get { return m_varName; } set { m_varName = value; m_varNameWithSwizzle = value + m_dataSwizzle; } }
public string DataSwizzle { get { return m_dataSwizzle; } set { m_dataSwizzle = value; m_varNameWithSwizzle = m_varName + value; } }
public TemplateInfoOnSematics DataInfo { get { return m_dataInfo; } set { m_dataInfo = value; } }
public bool Available { get { return m_available; } set { m_available = value; } }
public string VarNameWithSwizzle { get { return m_varNameWithSwizzle; } }
public WirePortDataType SwizzleType
{
get
{
if ( string.IsNullOrEmpty( m_dataSwizzle ) )
return m_dataType;
WirePortDataType newType = m_dataType;
switch ( m_dataSwizzle.Length )
{
case 2: newType = WirePortDataType.FLOAT;break;
case 3: newType = WirePortDataType.FLOAT2; break;
case 4: newType = WirePortDataType.FLOAT3; break;
case 5: newType = WirePortDataType.FLOAT4; break;
}
return newType;
}
}
}
}

View File

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

View File

@@ -0,0 +1,278 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Template Vertex Data", "Vertex Data", "Select and use available vertex data from the template" )]
public class TemplateVertexDataNode : TemplateNodeParent
{
private List<TemplateVertexData> m_interpolatorData = null;
[SerializeField]
private int m_currentDataIdx = -1;
[SerializeField]
private string m_dataName = string.Empty;
[SerializeField]
private string m_inVarName = string.Empty;
private string[] m_dataLabels = null;
private bool m_fetchDataId = false;
private UpperLeftWidgetHelper m_upperLeftWidgetHelper = new UpperLeftWidgetHelper();
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
m_autoWrapProperties = true;
}
void FetchDataId()
{
if( m_interpolatorData != null )
{
m_currentDataIdx = 0;
int count = m_interpolatorData.Count;
m_dataLabels = new string[ count ];
for( int i = 0; i < count; i++ )
{
m_dataLabels[ i ] = m_interpolatorData[ i ].VarName;
if( m_interpolatorData[ i ].VarName.Equals( m_dataName ) )
{
m_currentDataIdx = i;
}
}
UpdateFromId();
}
else
{
m_currentDataIdx = -1;
}
}
void UpdateFromId()
{
if( m_interpolatorData != null )
{
if( m_interpolatorData.Count == 0 )
{
for( int i = 0; i < 4; i++ )
m_containerGraph.DeleteConnection( false, UniqueId, i, false, true );
m_headerColor = UIUtils.GetColorFromCategory( "Default" );
m_content.text = "None";
m_additionalContent.text = string.Empty;
m_outputPorts[ 0 ].ChangeProperties( "None", WirePortDataType.OBJECT, false );
ConfigurePorts();
return;
}
bool areCompatible = TemplateHelperFunctions.CheckIfCompatibles( m_outputPorts[ 0 ].DataType, m_interpolatorData[ m_currentDataIdx ].DataType );
switch( m_interpolatorData[ m_currentDataIdx ].DataType )
{
default:
case WirePortDataType.INT:
case WirePortDataType.FLOAT:
m_outputPorts[ 0 ].ChangeProperties( Constants.EmptyPortValue, m_interpolatorData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.FLOAT2:
m_outputPorts[ 0 ].ChangeProperties( "XY", m_interpolatorData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.FLOAT3:
m_outputPorts[ 0 ].ChangeProperties( "XYZ", m_interpolatorData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.FLOAT4:
m_outputPorts[ 0 ].ChangeProperties( "XYZW", m_interpolatorData[ m_currentDataIdx ].DataType, false );
break;
case WirePortDataType.COLOR:
m_outputPorts[ 0 ].ChangeProperties( "RGBA", m_interpolatorData[ m_currentDataIdx ].DataType, false );
break;
}
ConfigurePorts();
if( !areCompatible )
{
m_containerGraph.DeleteConnection( false, UniqueId, 0, false, true );
}
m_dataName = m_interpolatorData[ m_currentDataIdx ].VarName;
m_content.text = m_dataName;
m_sizeIsDirty = true;
CheckWarningState();
}
}
public override void DrawProperties()
{
base.DrawProperties();
if( m_multiPassMode )
{
DrawMultipassProperties();
}
if( m_currentDataIdx > -1 )
{
EditorGUI.BeginChangeCheck();
m_currentDataIdx = EditorGUILayoutPopup( DataLabelStr, m_currentDataIdx, m_dataLabels );
if( EditorGUI.EndChangeCheck() )
{
UpdateFromId();
}
}
}
protected override void OnSubShaderChange()
{
FetchInterpolator();
FetchDataId();
}
protected override void OnPassChange()
{
FetchInterpolator();
FetchDataId();
}
void DrawMultipassProperties()
{
DrawSubShaderUI();
DrawPassUI();
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if( m_containerGraph.CurrentCanvasMode != NodeAvailability.TemplateShader )
return;
if( m_interpolatorData == null || m_interpolatorData.Count == 0 )
{
MasterNode masterNode = m_containerGraph.CurrentMasterNode;
FetchInterpolator( masterNode );
}
if( m_fetchDataId )
{
m_fetchDataId = false;
FetchDataId();
}
if( m_currentDataIdx > -1 )
{
EditorGUI.BeginChangeCheck();
m_currentDataIdx = m_upperLeftWidgetHelper.DrawWidget( this, m_currentDataIdx, m_dataLabels );
if( EditorGUI.EndChangeCheck() )
{
UpdateFromId();
}
}
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if( dataCollector.MasterNodeCategory != AvailableShaderTypes.Template )
{
UIUtils.ShowMessage( UniqueId, "Template Vertex Data node is only intended for templates use only" );
return m_outputPorts[ 0 ].ErrorValue;
}
if( dataCollector.IsFragmentCategory )
{
UIUtils.ShowMessage( UniqueId, "Template Vertex Data node node is only intended for vertex use use only" );
return m_outputPorts[ 0 ].ErrorValue;
}
if( m_multiPassMode )
{
if( dataCollector.TemplateDataCollectorInstance.MultipassSubshaderIdx != SubShaderIdx ||
dataCollector.TemplateDataCollectorInstance.MultipassPassIdx != PassIdx
)
{
UIUtils.ShowMessage( UniqueId, string.Format( "{0} is only intended for subshader {1} and pass {2}", m_dataLabels[ m_currentDataIdx ], SubShaderIdx, PassIdx ) );
return m_outputPorts[ outputId ].ErrorValue;
}
}
return GetOutputVectorItem( 0, outputId, m_inVarName + m_dataName );
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
m_dataName = GetCurrentParam( ref nodeParams );
m_fetchDataId = true;
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_dataName );
}
protected override bool ValidatePass( int passIdx )
{
return ( m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ passIdx ].VertexFunctionData != null &&
m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ passIdx ].VertexDataContainer != null );
}
void FetchInterpolator( MasterNode masterNode = null )
{
FetchMultiPassTemplate( masterNode );
if( m_multiPassMode )
{
if( m_templateMPData != null )
{
m_inVarName = m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ PassIdx ].VertexFunctionData.InVarName + ".";
m_interpolatorData = m_templateMPData.SubShaders[ SubShaderIdx ].Passes[ PassIdx ].VertexDataContainer.VertexData;
m_fetchDataId = true;
}
}
else
{
if( masterNode == null )
masterNode = m_containerGraph.CurrentMasterNode;
TemplateData currentTemplate = ( masterNode as TemplateMasterNode ).CurrentTemplate;
if( currentTemplate != null )
{
m_inVarName = currentTemplate.VertexFunctionData.InVarName + ".";
m_interpolatorData = currentTemplate.VertexDataList;
m_fetchDataId = true;
}
else
{
m_interpolatorData = null;
m_currentDataIdx = -1;
}
}
}
public override void OnMasterNodeReplaced( MasterNode newMasterNode )
{
base.OnMasterNodeReplaced( newMasterNode );
if( newMasterNode.CurrentMasterNodeCategory == AvailableShaderTypes.Template )
{
FetchInterpolator( newMasterNode );
}
else
{
m_interpolatorData = null;
m_currentDataIdx = -1;
}
}
public override void Destroy()
{
base.Destroy();
m_dataLabels = null;
m_interpolatorData = null;
m_upperLeftWidgetHelper = null;
}
}
}

View File

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

View File

@@ -0,0 +1,756 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace AmplifyShaderEditor
{
[Serializable]
public sealed class TemplatesBlendModule : TemplateModuleParent
{
private const string AlphaToMaskStr = "Alpha To Coverage";
private const string BlendModeStr = " Blend Mode";
private const string BlendModesRGBStr = "Blend RGB";
private const string BlendModesAlphaStr = "Blend Alpha";
private const string BlendOpsRGBStr = "Blend Op RGB";
private const string BlendOpsAlphaStr = "Blend Op Alpha";
private const string SourceFactorStr = "Src";
private const string DstFactorStr = "Dst";
private const string AlphaToMaskFormat = "AlphaToMask {0}";
private const string BlendFactorOff = "Blend Off";
private const string SingleBlendFactorStr = "Blend{0} {1} {2}";
private const string SeparateBlendFactorStr = "Blend{0} {1} {2}, {3} {4}";
private const string SingleBlendOpStr = "BlendOp{0} {1}";
private const string SeparateBlendOpStr = "BlendOp{0} {1}, {2}";
private const string BlendOpOffStr = "BlendOp Off";
private string[] m_commonBlendTypesArr;
private List<CommonBlendTypes> m_commonBlendTypes = new List<CommonBlendTypes>
{
new CommonBlendTypes("<OFF>", AvailableBlendFactor.Zero, AvailableBlendFactor.Zero ),
new CommonBlendTypes("Custom", AvailableBlendFactor.Zero, AvailableBlendFactor.Zero ) ,
new CommonBlendTypes("Alpha Blend", AvailableBlendFactor.SrcAlpha, AvailableBlendFactor.OneMinusSrcAlpha ) ,
new CommonBlendTypes("Premultiplied", AvailableBlendFactor.One, AvailableBlendFactor.OneMinusSrcAlpha ),
new CommonBlendTypes("Additive", AvailableBlendFactor.One, AvailableBlendFactor.One ),
new CommonBlendTypes("Soft Additive", AvailableBlendFactor.OneMinusDstColor, AvailableBlendFactor.One ),
new CommonBlendTypes("Multiplicative", AvailableBlendFactor.DstColor, AvailableBlendFactor.Zero ),
new CommonBlendTypes("2x Multiplicative", AvailableBlendFactor.DstColor, AvailableBlendFactor.SrcColor ),
new CommonBlendTypes("Particle Additive", AvailableBlendFactor.SrcAlpha, AvailableBlendFactor.One )
};
[SerializeField]
private string m_target = string.Empty;
[SerializeField]
private bool m_validBlendMode = false;
[SerializeField]
private bool m_validBlendOp = false;
[SerializeField]
private bool m_blendModeEnabled = false;
// Blend Factor
// RGB
[SerializeField]
private int m_currentRGBIndex = 0;
[SerializeField]
private AvailableBlendFactor m_sourceFactorRGB = AvailableBlendFactor.Zero;
[SerializeField]
private InlineProperty m_sourceFactorRGBInline = new InlineProperty();
[SerializeField]
private AvailableBlendFactor m_destFactorRGB = AvailableBlendFactor.Zero;
[SerializeField]
private InlineProperty m_destFactorRGBInline = new InlineProperty();
//Alpha
[SerializeField]
private int m_currentAlphaIndex = 0;
[SerializeField]
private AvailableBlendFactor m_sourceFactorAlpha = AvailableBlendFactor.Zero;
[SerializeField]
private InlineProperty m_sourceFactorAlphaInline = new InlineProperty();
[SerializeField]
private AvailableBlendFactor m_destFactorAlpha = AvailableBlendFactor.Zero;
[SerializeField]
private InlineProperty m_destFactorAlphaInline = new InlineProperty();
//Blend Ops
[SerializeField]
private bool m_blendOpEnabled = false;
[SerializeField]
private AvailableBlendOps m_blendOpRGB = AvailableBlendOps.OFF;
[SerializeField]
private InlineProperty m_blendOpRGBInline = new InlineProperty();
[SerializeField]
private AvailableBlendOps m_blendOpAlpha = AvailableBlendOps.OFF;
[SerializeField]
private InlineProperty m_blendOpAlphaInline = new InlineProperty();
public TemplatesBlendModule() : base( "Blend Mode and Ops" )
{
m_commonBlendTypesArr = new string[ m_commonBlendTypes.Count ];
for( int i = 0; i < m_commonBlendTypesArr.Length; i++ )
{
m_commonBlendTypesArr[ i ] = m_commonBlendTypes[ i ].Name;
}
}
public void CopyFrom( TemplatesBlendModule other, bool allData )
{
if( allData )
{
m_independentModule = other.IndependentModule;
m_validBlendMode = other.ValidBlendMode;
m_target = other.Target;
m_validBlendOp = other.ValidBlendOp;
}
m_blendModeEnabled = other.BlendModeEnabled;
m_currentRGBIndex = other.CurrentRGBIndex;
m_sourceFactorRGB = other.SourceFactorRGB;
m_destFactorRGB = other.DestFactorRGB;
m_currentAlphaIndex = other.CurrentAlphaIndex;
m_sourceFactorAlpha = other.SourceFactorAlpha;
m_destFactorAlpha = other.DestFactorAlpha;
m_blendOpEnabled = other.BlendOpEnabled;
m_blendOpRGB = other.BlendOpRGB;
m_blendOpAlpha = other.BlendOpAlpha;
m_sourceFactorRGBInline = other.SourceFactorRGBInline;
m_destFactorRGBInline = other.DestFactorRGBInline;
m_sourceFactorAlphaInline = other.SourceFactorAlphaInline;
m_destFactorAlphaInline = other.DestFactorAlphaInline;
m_blendOpRGBInline = other.BlendOpRGBInline;
m_blendOpAlphaInline = other.BlendOpAlphaInline;
}
public void ConfigureFromTemplateData( TemplateBlendData blendData )
{
if( blendData.ValidBlendMode )
{
if( m_validBlendMode != blendData.ValidBlendMode )
{
m_blendModeEnabled = true;
m_independentModule = blendData.IndependentModule;
if( string.IsNullOrEmpty( blendData.SourceFactorRGBInline ) )
{
m_sourceFactorRGB = blendData.SourceFactorRGB;
m_sourceFactorRGBInline.ResetProperty();
}
else
{
m_sourceFactorRGBInline.SetInlineByName( blendData.SourceFactorRGBInline );
}
if( string.IsNullOrEmpty( blendData.DestFactorRGBInline ) )
{
m_destFactorRGB = blendData.DestFactorRGB;
m_destFactorRGBInline.ResetProperty();
}
else
{
m_destFactorRGBInline.SetInlineByName( blendData.DestFactorRGBInline );
}
if( string.IsNullOrEmpty( blendData.SourceFactorAlphaInline ) )
{
m_sourceFactorAlpha = blendData.SourceFactorAlpha;
m_sourceFactorAlphaInline.ResetProperty();
}
else
{
m_sourceFactorAlphaInline.SetInlineByName( blendData.SourceFactorAlphaInline );
}
if( string.IsNullOrEmpty( blendData.DestFactorAlphaInline ) )
{
m_destFactorAlpha = blendData.DestFactorAlpha;
m_destFactorAlphaInline.ResetProperty();
}
else
{
m_destFactorAlphaInline.SetInlineByName( blendData.DestFactorAlphaInline );
}
if( blendData.SeparateBlendFactors )
{
if( blendData.BlendModeOff )
{
m_currentRGBIndex = 0;
}
else
{
CheckRGBIndex();
}
CheckAlphaIndex();
}
else
{
if( blendData.BlendModeOff )
{
m_currentRGBIndex = 0;
}
else
{
CheckRGBIndex();
}
m_currentAlphaIndex = 0;
}
}
}
else
{
m_blendModeEnabled = false;
}
if( blendData.ValidBlendOp )
{
if( m_validBlendOp != blendData.ValidBlendOp )
{
m_blendOpEnabled = true;
if( string.IsNullOrEmpty( blendData.BlendOpRGBInline ) )
{
m_blendOpRGB = blendData.BlendOpRGB;
m_blendOpRGBInline.ResetProperty();
}
else
{
m_blendOpRGBInline.SetInlineByName( blendData.BlendOpRGBInline );
}
if( string.IsNullOrEmpty( blendData.BlendOpAlphaInline ) )
{
m_blendOpAlpha = blendData.BlendOpAlpha;
m_blendOpAlphaInline.ResetProperty();
}
else
{
m_blendOpAlphaInline.SetInlineByName( blendData.BlendOpAlphaInline );
}
}
}
else
{
m_blendOpEnabled = false;
}
m_target = blendData.Target;
m_validBlendMode = blendData.ValidBlendMode;
m_validBlendOp = blendData.ValidBlendOp;
m_validData = m_validBlendMode || m_validBlendOp;
}
public override void ShowUnreadableDataMessage( ParentNode owner )
{
bool foldout = owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedBlendModeModule;
NodeUtils.DrawPropertyGroup( ref foldout, BlendModeStr, base.ShowUnreadableDataMessage );
owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedBlendModeModule = foldout;
}
public override void Draw( UndoParentNode owner, bool style = true )
{
bool foldout = owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedBlendModeModule;
if( style )
{
NodeUtils.DrawPropertyGroup( ref foldout, BlendModeStr + Target, () =>
{
DrawBlock( owner, style );
} );
}
else
{
NodeUtils.DrawNestedPropertyGroup( ref foldout, BlendModeStr + Target, () =>
{
DrawBlock( owner, style );
} );
}
owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedBlendModeModule = foldout;
}
void DrawBlock( UndoParentNode owner, bool style )
{
EditorGUI.BeginChangeCheck();
{
var cache = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = EditorGUIUtility.labelWidth - 20;
if( m_blendModeEnabled )
{
// RGB
EditorGUI.BeginChangeCheck();
m_currentRGBIndex = owner.EditorGUILayoutPopup( BlendModesRGBStr, m_currentRGBIndex, m_commonBlendTypesArr );
if( EditorGUI.EndChangeCheck() )
{
if( m_currentRGBIndex > 1 )
{
m_sourceFactorRGB = m_commonBlendTypes[ m_currentRGBIndex ].SourceFactor;
m_sourceFactorRGBInline.IntValue = (int)m_sourceFactorRGB;
m_sourceFactorRGBInline.SetInlineNodeValue();
m_destFactorRGB = m_commonBlendTypes[ m_currentRGBIndex ].DestFactor;
m_destFactorRGBInline.IntValue = (int)m_destFactorRGB;
m_destFactorRGBInline.SetInlineNodeValue();
}
}
EditorGUI.BeginDisabledGroup( m_currentRGBIndex == 0 );
EditorGUI.BeginChangeCheck();
float cached = EditorGUIUtility.labelWidth;
if( style )
{
EditorGUIUtility.labelWidth = 40;
}
else
{
EditorGUIUtility.labelWidth = 25;
}
EditorGUILayout.BeginHorizontal();
//m_sourceFactorRGB = (AvailableBlendFactor)owner.EditorGUILayoutEnumPopup( SourceFactorStr, m_sourceFactorRGB );
m_sourceFactorRGBInline.CustomDrawer( ref owner, ( x ) => { m_sourceFactorRGB = (AvailableBlendFactor)x.EditorGUILayoutEnumPopup( SourceFactorStr, m_sourceFactorRGB ); }, SourceFactorStr );
if( style )
{
EditorGUI.indentLevel--;
EditorGUIUtility.labelWidth = 25;
}
//m_destFactorRGB = (AvailableBlendFactor)owner.EditorGUILayoutEnumPopup( DstFactorStr, m_destFactorRGB );
m_destFactorRGBInline.CustomDrawer( ref owner, ( x ) => { m_destFactorRGB = (AvailableBlendFactor)x.EditorGUILayoutEnumPopup( DstFactorStr, m_destFactorRGB ); }, DstFactorStr );
if( style )
EditorGUI.indentLevel++;
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = cached;
if( EditorGUI.EndChangeCheck() )
{
CheckRGBIndex();
}
EditorGUI.EndDisabledGroup();
}
if( m_blendOpEnabled )
{
// Both these tests should be removed on a later stage
// ASE v154dev004 changed AvailableBlendOps.OFF value from -1 to 0
// If importing the new package into an already opened ASE window makes
// hotcode to preserve the -1 value on these variables
if( (int)m_blendOpRGB == -1 )
m_blendOpRGB = AvailableBlendOps.OFF;
//m_blendOpRGB = (AvailableBlendOps)owner.EditorGUILayoutEnumPopup( BlendOpsRGBStr, m_blendOpRGB );
m_blendOpRGBInline.CustomDrawer( ref owner, ( x ) => { m_blendOpRGB = (AvailableBlendOps)x.EditorGUILayoutPopup( BlendOpsRGBStr, (int)m_blendOpRGB, BlendOpsHelper.BlendOpsLabels ); }, BlendOpsRGBStr );
}
if( m_blendModeEnabled )
{
// Alpha
EditorGUILayout.Separator();
EditorGUI.BeginChangeCheck();
m_currentAlphaIndex = owner.EditorGUILayoutPopup( BlendModesAlphaStr, m_currentAlphaIndex, m_commonBlendTypesArr );
if( EditorGUI.EndChangeCheck() )
{
if( m_currentAlphaIndex > 0 )
{
m_sourceFactorAlpha = m_commonBlendTypes[ m_currentAlphaIndex ].SourceFactor;
m_sourceFactorAlphaInline.IntValue = (int)m_sourceFactorAlpha;
m_sourceFactorAlphaInline.SetInlineNodeValue();
m_destFactorAlpha = m_commonBlendTypes[ m_currentAlphaIndex ].DestFactor;
m_destFactorAlphaInline.IntValue = (int)m_destFactorAlpha;
m_destFactorAlphaInline.SetInlineNodeValue();
}
}
EditorGUI.BeginDisabledGroup( m_currentAlphaIndex == 0 );
EditorGUI.BeginChangeCheck();
float cached = EditorGUIUtility.labelWidth;
if( style )
{
EditorGUIUtility.labelWidth = 40;
}
else
{
EditorGUIUtility.labelWidth = 25;
}
EditorGUILayout.BeginHorizontal();
//m_sourceFactorAlpha = (AvailableBlendFactor)owner.EditorGUILayoutEnumPopup( SourceFactorStr, m_sourceFactorAlpha );
m_sourceFactorAlphaInline.CustomDrawer( ref owner, ( x ) => { m_sourceFactorAlpha = (AvailableBlendFactor)x.EditorGUILayoutEnumPopup( SourceFactorStr, m_sourceFactorAlpha ); }, SourceFactorStr );
if( style )
{
EditorGUI.indentLevel--;
EditorGUIUtility.labelWidth = 25;
}
//m_destFactorAlpha = (AvailableBlendFactor)owner.EditorGUILayoutEnumPopup( DstFactorStr, m_destFactorAlpha );
m_destFactorAlphaInline.CustomDrawer( ref owner, ( x ) => { m_destFactorAlpha = (AvailableBlendFactor)x.EditorGUILayoutEnumPopup( DstFactorStr, m_destFactorAlpha ); }, DstFactorStr );
if( style )
EditorGUI.indentLevel++;
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = cached;
if( EditorGUI.EndChangeCheck() )
{
CheckAlphaIndex();
}
EditorGUI.EndDisabledGroup();
//EditorGUILayout.Separator();
}
if( m_blendOpEnabled )
{
if( (int)m_blendOpAlpha == -1 )
m_blendOpAlpha = AvailableBlendOps.OFF;
//m_blendOpAlpha = (AvailableBlendOps)owner.EditorGUILayoutEnumPopup( BlendOpsAlphaStr, m_blendOpAlpha );
m_blendOpAlphaInline.CustomDrawer( ref owner, ( x ) => { m_blendOpAlpha = (AvailableBlendOps)x.EditorGUILayoutPopup( BlendOpsAlphaStr, (int)m_blendOpAlpha, BlendOpsHelper.BlendOpsLabels ); }, BlendOpsAlphaStr );
}
EditorGUIUtility.labelWidth = cache;
}
if( EditorGUI.EndChangeCheck() )
{
m_isDirty = true;
CustomEdited = true;
}
}
void CheckRGBIndex()
{
int count = m_commonBlendTypes.Count;
m_currentRGBIndex = 1;
for( int i = 1; i < count; i++ )
{
if( m_commonBlendTypes[ i ].SourceFactor == m_sourceFactorRGB && m_commonBlendTypes[ i ].DestFactor == m_destFactorRGB )
{
m_currentRGBIndex = i;
return;
}
}
}
void CheckAlphaIndex()
{
int count = m_commonBlendTypes.Count;
m_currentAlphaIndex = 1;
for( int i = 1; i < count; i++ )
{
if( m_commonBlendTypes[ i ].SourceFactor == m_sourceFactorAlpha && m_commonBlendTypes[ i ].DestFactor == m_destFactorAlpha )
{
m_currentAlphaIndex = i;
if( m_currentAlphaIndex > 0 && m_currentRGBIndex == 0 )
m_currentRGBIndex = 1;
return;
}
}
if( m_currentAlphaIndex > 0 && m_currentRGBIndex == 0 )
m_currentRGBIndex = 1;
}
public void ReadAlphaToMaskFromString( ref uint index, ref string[] nodeParams )
{
//TODO: we should send this data to the alpha to mask module instead
if( UIUtils.CurrentShaderVersion() > 16102 && UIUtils.CurrentShaderVersion() <= 18103)
{
bool validAlphaToMask = Convert.ToBoolean( nodeParams[ index++ ] );
if( validAlphaToMask )
{
/*bool alphaToMaskValue = */Convert.ToBoolean( nodeParams[ index++ ] );
}
}
}
public void ReadBlendModeFromString( ref uint index, ref string[] nodeParams )
{
bool validDataOnMeta = m_validBlendMode;
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
validDataOnMeta = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( validDataOnMeta )
{
if( UIUtils.CurrentShaderVersion() < 15304 )
{
m_currentRGBIndex = Convert.ToInt32( nodeParams[ index++ ] );
m_sourceFactorRGB = (AvailableBlendFactor)Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
m_destFactorRGB = (AvailableBlendFactor)Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
m_currentAlphaIndex = Convert.ToInt32( nodeParams[ index++ ] );
m_sourceFactorAlpha = (AvailableBlendFactor)Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
m_destFactorAlpha = (AvailableBlendFactor)Enum.Parse( typeof( AvailableBlendFactor ), nodeParams[ index++ ] );
}
else
{
m_currentRGBIndex = Convert.ToInt32( nodeParams[ index++ ] );
m_sourceFactorRGBInline.ReadFromString( ref index, ref nodeParams );
m_sourceFactorRGB = (AvailableBlendFactor)m_sourceFactorRGBInline.IntValue;
m_destFactorRGBInline.ReadFromString( ref index, ref nodeParams );
m_destFactorRGB = (AvailableBlendFactor)m_destFactorRGBInline.IntValue;
m_currentAlphaIndex = Convert.ToInt32( nodeParams[ index++ ] );
m_sourceFactorAlphaInline.ReadFromString( ref index, ref nodeParams );
m_sourceFactorAlpha = (AvailableBlendFactor)m_sourceFactorAlphaInline.IntValue;
m_destFactorAlphaInline.ReadFromString( ref index, ref nodeParams );
m_destFactorAlpha = (AvailableBlendFactor)m_destFactorAlphaInline.IntValue;
}
}
}
public void ReadBlendOpFromString( ref uint index, ref string[] nodeParams )
{
bool validDataOnMeta = m_validBlendOp;
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
validDataOnMeta = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( validDataOnMeta )
{
if( UIUtils.CurrentShaderVersion() < 15304 )
{
m_blendOpRGB = (AvailableBlendOps)Enum.Parse( typeof( AvailableBlendOps ), nodeParams[ index++ ] );
m_blendOpAlpha = (AvailableBlendOps)Enum.Parse( typeof( AvailableBlendOps ), nodeParams[ index++ ] );
}
else
{
m_blendOpRGBInline.ReadFromString( ref index, ref nodeParams );
m_blendOpAlphaInline.ReadFromString( ref index, ref nodeParams );
if( UIUtils.CurrentShaderVersion() < 15404 )
{
// Now BlendOps enum starts at 0 and not -1
m_blendOpRGBInline.FloatValue += 1;
m_blendOpAlphaInline.FloatValue += 1;
}
m_blendOpRGB = (AvailableBlendOps)m_blendOpRGBInline.IntValue;
m_blendOpAlpha = (AvailableBlendOps)m_blendOpAlphaInline.IntValue;
}
//m_blendOpEnabled = ( m_blendOpRGB != AvailableBlendOps.OFF );
}
}
public void WriteBlendModeToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_validBlendMode );
if( m_validBlendMode )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_currentRGBIndex );
if( !m_sourceFactorRGBInline.IsValid ) m_sourceFactorRGBInline.IntValue = (int)m_sourceFactorRGB;
m_sourceFactorRGBInline.WriteToString( ref nodeInfo );
if( !m_destFactorRGBInline.IsValid ) m_destFactorRGBInline.IntValue = (int)m_destFactorRGB;
m_destFactorRGBInline.WriteToString( ref nodeInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_currentAlphaIndex );
if( !m_sourceFactorAlphaInline.IsValid ) m_sourceFactorAlphaInline.IntValue = (int)m_sourceFactorAlpha;
m_sourceFactorAlphaInline.WriteToString( ref nodeInfo );
if( !m_destFactorAlphaInline.IsValid ) m_destFactorAlphaInline.IntValue = (int)m_destFactorAlpha;
m_destFactorAlphaInline.WriteToString( ref nodeInfo );
}
}
public void WriteBlendOpToString( ref string nodeInfo )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_validBlendOp );
if( m_validBlendOp )
{
if( !m_blendOpRGBInline.IsValid ) m_blendOpRGBInline.IntValue = (int)m_blendOpRGB;
m_blendOpRGBInline.WriteToString( ref nodeInfo );
if( !m_blendOpAlphaInline.IsValid ) m_blendOpAlphaInline.IntValue = (int)m_blendOpAlpha;
m_blendOpAlphaInline.WriteToString( ref nodeInfo );
}
}
public override void ReadFromString( ref uint index, ref string[] nodeParams )
{
base.ReadFromString( ref index, ref nodeParams );
ReadBlendModeFromString( ref index, ref nodeParams );
ReadBlendOpFromString( ref index, ref nodeParams );
ReadAlphaToMaskFromString( ref index, ref nodeParams );
}
public override void WriteToString( ref string nodeInfo )
{
base.WriteToString( ref nodeInfo );
WriteBlendModeToString( ref nodeInfo );
WriteBlendOpToString( ref nodeInfo );
}
public override void Destroy()
{
base.Destroy();
m_sourceFactorRGBInline = null;
m_destFactorRGBInline = null;
m_sourceFactorAlphaInline = null;
m_destFactorAlphaInline = null;
m_blendOpRGBInline = null;
m_blendOpAlphaInline = null;
}
public string CurrentBlendFactorSingle
{
get
{
return ( m_currentRGBIndex > 0 ) ? string.Format( SingleBlendFactorStr, m_target, m_sourceFactorRGBInline.GetValueOrProperty( m_sourceFactorRGB.ToString() ), m_destFactorRGBInline.GetValueOrProperty( m_destFactorRGB.ToString() ) ) : BlendFactorOff;
}
}
public string CurrentBlendFactorSeparate
{
get
{
return string.Format( SeparateBlendFactorStr, m_target,
m_sourceFactorRGBInline.GetValueOrProperty( ( m_currentRGBIndex > 0 ? m_sourceFactorRGB.ToString() : AvailableBlendFactor.One.ToString() ) ),
m_destFactorRGBInline.GetValueOrProperty( m_currentRGBIndex > 0 ? m_destFactorRGB.ToString() : AvailableBlendFactor.Zero.ToString() ),
m_sourceFactorAlphaInline.GetValueOrProperty( m_sourceFactorAlpha.ToString() ),
m_destFactorAlphaInline.GetValueOrProperty( m_destFactorAlpha.ToString() ) );
}
}
public string CurrentBlendFactor
{
get
{
return ( ( m_currentAlphaIndex > 0 ) ? CurrentBlendFactorSeparate : CurrentBlendFactorSingle );
}
}
public string CurrentBlendOpSingle
{
get
{
return ( m_blendOpRGB != AvailableBlendOps.OFF || m_blendOpRGBInline.IsValid ) ? string.Format( SingleBlendOpStr, Target, m_blendOpRGBInline.GetValueOrProperty( m_blendOpRGB.ToString() ) ) : string.Empty;
}
}
public string CurrentBlendOpSeparate
{
get
{
return string.Format( SeparateBlendOpStr, Target, m_blendOpRGBInline.GetValueOrProperty( ( m_currentRGBIndex > 0 && m_blendOpRGB != AvailableBlendOps.OFF ) ? m_blendOpRGB.ToString() : AvailableBlendOps.Add.ToString() ), m_blendOpAlphaInline.GetValueOrProperty( m_blendOpAlpha.ToString() ) );
}
}
public string CurrentBlendOp { get { return ( ( m_blendOpAlpha != AvailableBlendOps.OFF || m_blendOpAlphaInline.IsValid ) ? CurrentBlendOpSeparate : CurrentBlendOpSingle ); } }
public bool Active { get { return m_blendModeEnabled && ( m_currentRGBIndex > 0 || m_currentAlphaIndex > 0 ); } }
public bool BlendOpActive
{
get
{
return m_blendOpEnabled &&
(
m_blendOpRGBInline.Active ||
m_blendOpAlphaInline.Active ||
( !m_blendOpRGBInline.Active && m_blendOpRGB != AvailableBlendOps.OFF ) ||
( !m_blendOpAlphaInline.Active && m_blendOpAlpha != AvailableBlendOps.OFF ) );
}
}
public string Target { get { return m_target; } }
public bool ValidBlendMode { get { return m_validBlendMode; } }
public bool ValidBlendOp { get { return m_validBlendOp; } }
public int CurrentRGBIndex { get { return m_currentRGBIndex; } }
public AvailableBlendFactor SourceFactorRGB
{
get { return m_sourceFactorRGB; }
set
{
m_sourceFactorRGB = value;
m_sourceFactorRGBInline.IntValue = (int)m_sourceFactorRGB;
m_sourceFactorRGBInline.Active = false;
}
}
public AvailableBlendFactor DestFactorRGB
{
get { return m_destFactorRGB; }
set
{
m_destFactorRGB = value;
m_destFactorRGBInline.IntValue = (int)value;
}
}
public int CurrentAlphaIndex { get { return m_currentAlphaIndex; } set { m_currentAlphaIndex = value; } }
public AvailableBlendFactor SourceFactorAlpha
{
get { return m_sourceFactorAlpha; }
set
{
m_sourceFactorAlpha = value;
m_sourceFactorAlphaInline.IntValue = (int)value;
m_sourceFactorAlphaInline.Active = false;
}
}
public AvailableBlendFactor DestFactorAlpha
{
get { return m_destFactorAlpha; }
set
{
m_destFactorAlpha = value;
m_destFactorAlphaInline.IntValue = (int)value;
m_destFactorAlphaInline.Active = false;
}
}
public bool BlendModeEnabled { get { return m_blendModeEnabled; } }
public bool BlendOpEnabled { get { return m_blendOpEnabled; } }
public AvailableBlendOps BlendOpRGB
{
get { return m_blendOpRGB; }
set
{
m_blendOpRGB = value;
m_blendOpRGBInline.IntValue = (int)value;
m_blendOpRGBInline.Active = false;
}
}
public AvailableBlendOps BlendOpAlpha
{
get { return m_blendOpAlpha; }
set
{
m_blendOpAlpha = value;
m_blendOpAlphaInline.IntValue = (int)value;
m_blendOpAlphaInline.Active = false;
}
}
public InlineProperty SourceFactorRGBInline { get { return m_sourceFactorRGBInline; } }
public InlineProperty DestFactorRGBInline { get { return m_destFactorRGBInline; } }
public InlineProperty SourceFactorAlphaInline { get { return m_sourceFactorAlphaInline; } }
public InlineProperty DestFactorAlphaInline { get { return m_destFactorAlphaInline; } }
public InlineProperty BlendOpRGBInline { get { return m_blendOpRGBInline; } }
public InlineProperty BlendOpAlphaInline { get { return m_blendOpAlphaInline; } }
public bool IsAdditiveRGB { get { return m_validBlendMode && m_blendModeEnabled && ( m_currentRGBIndex > 0 ) && ( m_sourceFactorRGB == AvailableBlendFactor.One ) && ( m_destFactorRGB == AvailableBlendFactor.One ); } }
public bool IsAlphaBlendRGB { get { return m_validBlendMode && m_blendModeEnabled && ( m_currentRGBIndex > 0 ) && ( m_sourceFactorRGB == AvailableBlendFactor.SrcAlpha ) && ( m_destFactorRGB == AvailableBlendFactor.OneMinusSrcAlpha ); } }
}
}

View File

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

View File

@@ -0,0 +1,936 @@
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using System;
using UnityEditor;
using System.Collections.Generic;
using UnityEngine;
using System.Text.RegularExpressions;
namespace AmplifyShaderEditor
{
[Serializable]
public class TemplateInputData
{
public string PortName;
public WirePortDataType DataType;
public MasterNodePortCategory PortCategory;
public int PortUniqueId;
public int OrderId;
public int TagGlobalStartIdx;
public int TagLocalStartIdx;
public string TagId;
public string DefaultValue;
public string LinkId;
public TemplateInputData( int tagLocalStartIdx, int tagGlobalStartIdx, string tagId, string portName, string defaultValue, WirePortDataType dataType, MasterNodePortCategory portCategory, int portUniqueId, int orderId, string linkId )
{
DefaultValue = defaultValue;
PortName = portName;
DataType = dataType;
PortCategory = portCategory;
PortUniqueId = portUniqueId;
OrderId = orderId;
TagId = tagId;
TagGlobalStartIdx = tagGlobalStartIdx;
TagLocalStartIdx = tagLocalStartIdx;
LinkId = linkId;
}
public TemplateInputData( TemplateInputData other )
{
DefaultValue = other.DefaultValue;
PortName = other.PortName;
DataType = other.DataType;
PortCategory = other.PortCategory;
PortUniqueId = other.PortUniqueId;
OrderId = other.OrderId;
TagId = other.TagId;
TagGlobalStartIdx = other.TagGlobalStartIdx;
LinkId = other.LinkId;
}
}
[Serializable]
public class TemplatePropertyContainer
{
[SerializeField]
private List<TemplateProperty> m_propertyList = new List<TemplateProperty>();
private Dictionary<string, TemplateProperty> m_propertyDict = new Dictionary<string, TemplateProperty>();
public void AddId( TemplateProperty templateProperty )
{
BuildInfo();
m_propertyList.Add( templateProperty );
m_propertyDict.Add( templateProperty.Id, templateProperty );
}
public void AddId( string body, string ID, bool searchIndentation = true )
{
AddId( body, ID, searchIndentation, string.Empty );
}
public void AddId( string body, string ID, bool searchIndentation, string customIndentation )
{
BuildInfo();
int propertyIndex = body.IndexOf( ID );
if( propertyIndex > -1 )
{
if( searchIndentation )
{
int identationIndex = -1;
for( int i = propertyIndex; i >= 0; i-- )
{
if( body[ i ] == TemplatesManager.TemplateNewLine )
{
identationIndex = i + 1;
break;
}
if( i == 0 )
{
identationIndex = 0;
}
}
if( identationIndex > -1 )
{
int length = propertyIndex - identationIndex;
string indentation = ( length > 0 ) ? body.Substring( identationIndex, length ) : string.Empty;
TemplateProperty templateProperty = new TemplateProperty( ID, indentation, false );
m_propertyList.Add( templateProperty );
m_propertyDict.Add( templateProperty.Id, templateProperty );
}
else
{
TemplateProperty templateProperty = new TemplateProperty( ID, string.Empty, false );
m_propertyList.Add( templateProperty );
m_propertyDict.Add( templateProperty.Id, templateProperty );
}
}
else
{
TemplateProperty templateProperty = new TemplateProperty( ID, customIndentation, true );
m_propertyList.Add( templateProperty );
m_propertyDict.Add( templateProperty.Id, templateProperty );
}
}
}
public void AddId( string body, string ID, int propertyIndex, bool searchIndentation )
{
AddId( body, ID, propertyIndex, searchIndentation, string.Empty );
}
public void AddId( string body, string ID, int propertyIndex, bool searchIndentation, string customIndentation )
{
if( body == null || string.IsNullOrEmpty( body ) )
return;
BuildInfo();
if( searchIndentation && propertyIndex > -1 && propertyIndex < body.Length )
{
int indentationIndex = -1;
for( int i = propertyIndex; i > 0; i-- )
{
if( body[ i ] == TemplatesManager.TemplateNewLine )
{
indentationIndex = i + 1;
break;
}
}
if( indentationIndex > -1 )
{
int length = propertyIndex - indentationIndex;
string indentation = ( length > 0 ) ? body.Substring( indentationIndex, length ) : string.Empty;
TemplateProperty templateProperty = new TemplateProperty( ID, indentation, false );
m_propertyList.Add( templateProperty );
m_propertyDict.Add( templateProperty.Id, templateProperty );
}
}
else
{
TemplateProperty templateProperty = new TemplateProperty( ID, customIndentation, true );
m_propertyList.Add( templateProperty );
m_propertyDict.Add( templateProperty.Id, templateProperty );
}
}
public void BuildInfo()
{
if( m_propertyDict == null )
{
m_propertyDict = new Dictionary<string, TemplateProperty>();
}
if( m_propertyList.Count != m_propertyDict.Count )
{
m_propertyDict.Clear();
for( int i = 0; i < m_propertyList.Count; i++ )
{
m_propertyDict.Add( m_propertyList[ i ].Id, m_propertyList[ i ] );
}
}
}
public void ResetTemplateUsageData()
{
BuildInfo();
for( int i = 0; i < m_propertyList.Count; i++ )
{
m_propertyList[ i ].Used = false;
}
}
public void Reset()
{
m_propertyList.Clear();
m_propertyDict.Clear();
}
public void Destroy()
{
m_propertyList.Clear();
m_propertyList = null;
m_propertyDict.Clear();
m_propertyDict = null;
}
public Dictionary<string, TemplateProperty> PropertyDict
{
get
{
BuildInfo();
return m_propertyDict;
}
}
public List<TemplateProperty> PropertyList { get { return m_propertyList; } }
}
[Serializable]
public class TemplateProperty
{
public bool UseIndentationAtStart = false;
public string Indentation;
public bool UseCustomIndentation;
public string Id;
public bool AutoLineFeed;
public bool Used;
public TemplateProperty( string id, string indentation, bool useCustomIndentation )
{
Id = id;
Indentation = indentation;
UseCustomIndentation = useCustomIndentation;
AutoLineFeed = !string.IsNullOrEmpty( indentation );
Used = false;
}
}
[Serializable]
public class TemplateTessVControlTag
{
public string Id;
public int StartIdx;
public TemplateTessVControlTag()
{
StartIdx = -1;
}
public bool IsValid { get { return StartIdx >= 0; } }
}
[Serializable]
public class TemplateTessControlData
{
public string Id;
public int StartIdx;
public string InVarType;
public string InVarName;
public string OutVarType;
public string OutVarName;
public bool IsValid { get { return StartIdx >= 0; } }
public TemplateTessControlData()
{
StartIdx = -1;
}
public TemplateTessControlData( int startIdx, string id, string inVarInfo, string outVarInfo )
{
StartIdx = startIdx;
Id = id;
string[] inVarInfoArr = inVarInfo.Split( IOUtils.VALUE_SEPARATOR );
if( inVarInfoArr.Length > 1 )
{
InVarType = inVarInfoArr[ 1 ];
InVarName = inVarInfoArr[ 0 ];
}
string[] outVarInfoArr = outVarInfo.Split( IOUtils.VALUE_SEPARATOR );
if( outVarInfoArr.Length > 1 )
{
OutVarType = outVarInfoArr[ 1 ];
OutVarName = outVarInfoArr[ 0 ];
}
}
public string[] GenerateControl( Dictionary<TemplateSemantics, TemplateVertexData> vertexData, List<string> inputList )
{
List<string> value = new List<string>();
if( vertexData != null && vertexData.Count > 0 )
{
foreach( var item in vertexData )
{
if( inputList.FindIndex( x => { return x.Contains( item.Value.VarName ); } ) > -1 )
value.Add( string.Format( "{0}.{1} = {2}.{1};", OutVarName, item.Value.VarName, InVarName ) );
}
}
return value.ToArray();
}
}
[Serializable]
public class TemplateTessDomainData
{
public string Id;
public int StartIdx;
public string InVarType;
public string InVarName;
public string OutVarType;
public string OutVarName;
public string BaryVarType;
public string BaryVarName;
public bool IsValid { get { return StartIdx >= 0; } }
public TemplateTessDomainData()
{
StartIdx = -1;
}
public TemplateTessDomainData( int startIdx, string id, string inVarInfo, string outVarInfo, string baryVarInfo )
{
StartIdx = startIdx;
Id = id;
string[] inVarInfoArr = inVarInfo.Split( IOUtils.VALUE_SEPARATOR );
if( inVarInfoArr.Length > 1 )
{
InVarType = inVarInfoArr[ 1 ];
InVarName = inVarInfoArr[ 0 ];
}
string[] outVarInfoArr = outVarInfo.Split( IOUtils.VALUE_SEPARATOR );
if( outVarInfoArr.Length > 1 )
{
OutVarType = outVarInfoArr[ 1 ];
OutVarName = outVarInfoArr[ 0 ];
}
string[] baryVarInfoArr = baryVarInfo.Split( IOUtils.VALUE_SEPARATOR );
if( baryVarInfoArr.Length > 1 )
{
BaryVarType = baryVarInfoArr[ 1 ];
BaryVarName = baryVarInfoArr[ 0 ];
}
}
public string[] GenerateDomain( Dictionary<TemplateSemantics, TemplateVertexData> vertexData, List<string> inputList )
{
List<string> value = new List<string>();
if( vertexData != null && vertexData.Count > 0 )
{
foreach( var item in vertexData )
{
//o.ase_normal = patch[0].ase_normal * bary.x + patch[1].ase_normal * bary.y + patch[2].ase_normal * bary.z;
if( inputList.FindIndex( x => { return x.Contains( item.Value.VarName ); } ) > -1 )
value.Add( string.Format( "{0}.{1} = {2}[0].{1} * {3}.x + {2}[1].{1} * {3}.y + {2}[2].{1} * {3}.z;", OutVarName, item.Value.VarName, InVarName, BaryVarName ) );
}
}
return value.ToArray();
}
}
[Serializable]
public class TemplateFunctionData
{
public int MainBodyLocalIdx;
public string MainBodyName;
public string Id;
public int Position;
public string InVarType;
public string InVarName;
public string OutVarType;
public string OutVarName;
public MasterNodePortCategory Category;
public TemplateFunctionData( int mainBodyLocalIdx, string mainBodyName, string id, int position, string inVarInfo, string outVarInfo, MasterNodePortCategory category )
{
MainBodyLocalIdx = mainBodyLocalIdx;
MainBodyName = mainBodyName;
Id = id;
Position = position;
{
string[] inVarInfoArr = inVarInfo.Split( IOUtils.VALUE_SEPARATOR );
if( inVarInfoArr.Length > 1 )
{
InVarType = inVarInfoArr[ 1 ];
InVarName = inVarInfoArr[ 0 ];
}
}
{
string[] outVarInfoArr = outVarInfo.Split( IOUtils.VALUE_SEPARATOR );
if( outVarInfoArr.Length > 1 )
{
OutVarType = outVarInfoArr[ 1 ];
OutVarName = outVarInfoArr[ 0 ];
}
}
Category = category;
}
}
[Serializable]
public class TemplateTagData
{
public int StartIdx = -1;
public string Id;
public bool SearchIndentation;
public string CustomIndentation;
public TemplateTagData( int startIdx, string id, bool searchIndentation )
{
StartIdx = startIdx;
Id = id;
SearchIndentation = searchIndentation;
CustomIndentation = string.Empty;
}
public TemplateTagData( string id, bool searchIndentation )
{
Id = id;
SearchIndentation = searchIndentation;
CustomIndentation = string.Empty;
}
public TemplateTagData( string id, bool searchIndentation, string customIndentation )
{
Id = id;
SearchIndentation = searchIndentation;
CustomIndentation = customIndentation;
}
public bool IsValid { get { return StartIdx >= 0; } }
}
public enum TemplatePortIds
{
Name = 0,
DataType,
UniqueId,
OrderId,
Link
}
public enum TemplateCommonTagId
{
Property = 0,
Global = 1,
Function = 2,
Tag = 3,
Pragmas = 4,
Pass = 5,
Params_Vert = 6,
Params_Frag = 7
//CullMode = 8,
//BlendMode = 9,
//BlendOp = 10,
//ColorMask = 11,
//StencilOp = 12
}
[Serializable]
public class TemplatesManager : ScriptableObject
{
public static int MPShaderVersion = 14503;
public static readonly string TemplateShaderNameBeginTag = "/*ase_name*/";
public static readonly string TemplateStencilTag = "/*ase_stencil*/\n";
public static readonly string TemplateAllModulesTag = "/*ase_all_modules*/\n";
public static readonly string TemplateMPSubShaderTag = "\\bSubShader\\b\\s*{";
//public static readonly string TemplateMPPassTag = "^\\s*Pass\b\\s*{";//"\\bPass\\b\\s*{";
public static readonly string TemplateMPPassTag = "\\bPass\\b\\s*{";
public static readonly string TemplateLocalVarTag = "/*ase_local_var*/";
public static readonly string TemplateDependenciesListTag = "/*ase_dependencies_list*/";
public static readonly string TemplatePragmaBeforeTag = "/*ase_pragma_before*/";
public static readonly string TemplatePragmaTag = "/*ase_pragma*/";
public static readonly string TemplatePassTag = "/*ase_pass*/";
public static readonly string TemplatePassesEndTag = "/*ase_pass_end*/";
public static readonly string TemplateLODsTag = "/*ase_lod*/";
//public static readonly string TemplatePassTagPattern = @"\s\/\*ase_pass\*\/";
public static readonly string TemplatePassTagPattern = @"\s\/\*ase_pass[:\*]+";
public static readonly string TemplatePropertyTag = "/*ase_props*/";
public static readonly string TemplateGlobalsTag = "/*ase_globals*/";
public static readonly string TemplateSRPBatcherTag = "/*ase_srp_batcher*/\n";
public static readonly string TemplateInterpolatorBeginTag = "/*ase_interp(";
public static readonly string TemplateVertexDataTag = "/*ase_vdata:";
public static readonly string TemplateTessVControlTag = "/*ase_vcontrol*/";
public static readonly string TemplateTessControlCodeArea = "/*ase_control_code:";
public static readonly string TemplateTessDomainCodeArea = "/*ase_domain_code:";
//public static readonly string TemplateExcludeFromGraphTag = "/*ase_hide_pass*/";
public static readonly string TemplateMainPassTag = "/*ase_main_pass*/";
public static readonly string TemplateFunctionsTag = "/*ase_funcs*/\n";
//public static readonly string TemplateTagsTag = "/*ase_tags*/";
//public static readonly string TemplateCullModeTag = "/*ase_cull_mode*/";
//public static readonly string TemplateBlendModeTag = "/*ase_blend_mode*/";
//public static readonly string TemplateBlendOpTag = "/*ase_blend_op*/";
//public static readonly string TemplateColorMaskTag = "/*ase_color_mask*/";
//public static readonly string TemplateStencilOpTag = "/*ase_stencil*/";
public static readonly string TemplateCodeSnippetAttribBegin = "#CODE_SNIPPET_ATTRIBS_BEGIN#";
public static readonly string TemplateCodeSnippetAttribEnd = "#CODE_SNIPPET_ATTRIBS_END#\n";
public static readonly string TemplateCodeSnippetEnd = "#CODE_SNIPPET_END#\n";
public static readonly char TemplateNewLine = '\n';
// INPUTS AREA
public static readonly string TemplateInputsVertBeginTag = "/*ase_vert_out:";
public static readonly string TemplateInputsFragBeginTag = "/*ase_frag_out:";
public static readonly string TemplateInputsVertParamsTag = "/*ase_vert_input*/";
public static readonly string TemplateInputsFragParamsTag = "/*ase_frag_input*/";
// CODE AREA
public static readonly string TemplateVertexCodeBeginArea = "/*ase_vert_code:";
public static readonly string TemplateFragmentCodeBeginArea = "/*ase_frag_code:";
public static readonly string TemplateEndOfLine = "*/\n";
public static readonly string TemplateEndSectionTag = "*/";
public static readonly string TemplateFullEndTag = "/*end*/";
public static readonly string NameFormatter = "\"{0}\"";
public static readonly TemplateTagData[] CommonTags = { new TemplateTagData( TemplatePropertyTag,true),
new TemplateTagData( TemplateGlobalsTag,true),
new TemplateTagData( TemplateSRPBatcherTag,true),
new TemplateTagData( TemplateFunctionsTag,true),
//new TemplateTagData( TemplateTagsTag,false," "),
new TemplateTagData( TemplatePragmaBeforeTag,true),
new TemplateTagData( TemplatePragmaTag,true),
new TemplateTagData( TemplatePassTag,true),
new TemplateTagData( TemplateInputsVertParamsTag,false),
new TemplateTagData( TemplateInputsFragParamsTag,false),
new TemplateTagData( TemplateLODsTag,true)
//new TemplateTagData( TemplateCullModeTag,false),
//new TemplateTagData( TemplateBlendModeTag,false),
//new TemplateTagData( TemplateBlendOpTag,false),
//new TemplateTagData( TemplateColorMaskTag,false),
//new TemplateTagData( TemplateStencilOpTag,true),
};
public static string LightweigthPBRGUID = "1976390536c6c564abb90fe41f6ee334";
public static string LightweigthUnlitGUID = "e2514bdcf5e5399499a9eb24d175b9db";
public static string UniversalPBRGUID = "94348b07e5e8bab40bd6c8a1e3df54cd";
public static string UniversalUnlitGUID = "2992e84f91cbeb14eab234972e07ea9d";
public static string HDNewLitGUID = "53b46d85872c5b24c8f4f0a1c3fe4c87";
public static string HDNewPBRGUID = "41e04be03f2c20941bc749271be1c937";
public static string HDNewUnlitGUID = "7f5cb9c3ea6481f469fdd856555439ef";
public static string HDLitGUID = "091c43ba8bd92c9459798d59b089ce4e";
public static string HDPBRGUID = "bb308bce79762c34e823049efce65141";
public static string HDUnlitGUID = "dfe2f27ac20b08c469b2f95c236be0c3";
public static Dictionary<string, string> DeprecatedTemplates = new Dictionary<string, string>()
{
{ HDLitGUID, HDNewLitGUID},
{ HDUnlitGUID,HDNewUnlitGUID},
{ HDPBRGUID,HDNewLitGUID},
{ HDNewPBRGUID,HDNewLitGUID}
};
public static Dictionary<string, string> OfficialTemplates = new Dictionary<string, string>()
{
{ "0770190933193b94aaa3065e307002fa","Legacy/Unlit"},
{ "32139be9c1eb75640a847f011acf3bcf","Legacy/Post-Processing Stack"},
{ "6ce779933eb99f049b78d6163735e06f","Legacy/Custom RT Init"},
{ "32120270d1b3a8746af2aca8bc749736","Legacy/Custom RT Update"},
{ LightweigthPBRGUID,"LW/PBR"},
{ LightweigthUnlitGUID,"LW/Unlit"},
{ UniversalPBRGUID,"Universal/PBR"},
{ UniversalUnlitGUID,"Universal/Unlit"},
{ "53b46d85872c5b24c8f4f0a1c3fe4c87","HD/Lit"},
{ HDLitGUID,"Deprecated/HD/Lit"},
{ HDPBRGUID,"Deprecated/HD/PBR"},
{ HDUnlitGUID,"Deprecated/HD/Unlit"},
{ "c71b220b631b6344493ea3cf87110c93","Legacy/Post Process" },
{ "6e114a916ca3e4b4bb51972669d463bf","Deprecated/Legacy/Default Unlit" },
{ "5056123faa0c79b47ab6ad7e8bf059a4","Legacy/Default UI" },
{ "899e609c083c74c4ca567477c39edef0","Legacy/Unlit Lightmap" },
{ "0f8ba0101102bb14ebf021ddadce9b49","Legacy/Default Sprites" },
{ "0b6a9f8b4f707c74ca64c0be8e590de0","Legacy/Particles Alpha Blended" },
{ "e1de45c0d41f68c41b2cc20c8b9c05ef","Legacy/Multi Pass Unlit" }
};
public static readonly string TemplateMenuItemsFileGUID = "da0b931bd234a1e43b65f684d4b59bfb";
private Dictionary<string, TemplateDataParent> m_availableTemplates = new Dictionary<string, TemplateDataParent>();
[SerializeField]
private List<TemplateDataParent> m_sortedTemplates = new List<TemplateDataParent>();
[SerializeField]
public string[] AvailableTemplateNames;
[SerializeField]
public bool Initialized = false;
private Dictionary<string, bool> m_optionsInitialSetup = new Dictionary<string, bool>();
public static string CurrTemplateGUIDLoaded = string.Empty;
public static bool IsTestTemplate { get { return CurrTemplateGUIDLoaded.Equals( "a95a019bbc760714bb8228af04c291d1" ); } }
public static bool ShowDebugMessages = false;
public void RefreshAvailableTemplates()
{
if( m_availableTemplates.Count != m_sortedTemplates.Count )
{
m_availableTemplates.Clear();
int count = m_sortedTemplates.Count;
for( int i = 0; i < count; i++ )
{
m_availableTemplates.Add( m_sortedTemplates[ i ].GUID, m_sortedTemplates[ i ] );
}
}
}
public void Init()
{
if( !Initialized )
{
if( ShowDebugMessages )
Debug.Log( "Initialize" );
string templateMenuItems = IOUtils.LoadTextFileFromDisk( AssetDatabase.GUIDToAssetPath( TemplateMenuItemsFileGUID ) );
bool refreshTemplateMenuItems = false;
foreach( KeyValuePair<string, string> kvp in OfficialTemplates )
{
if( !string.IsNullOrEmpty( AssetDatabase.GUIDToAssetPath( kvp.Key ) ) )
{
TemplateMultiPass template = ScriptableObject.CreateInstance<TemplateMultiPass>();
template.Init( kvp.Value, kvp.Key, false );
AddTemplate( template );
if( !refreshTemplateMenuItems && templateMenuItems.IndexOf( kvp.Value ) < 0 )
refreshTemplateMenuItems = true;
}
}
// Search for other possible templates on the project
string[] allShaders = AssetDatabase.FindAssets( "t:shader" );
for( int i = 0; i < allShaders.Length; i++ )
{
if( !m_availableTemplates.ContainsKey( allShaders[ i ] ) )
{
CheckAndLoadTemplate( allShaders[ i ] );
}
}
// TODO: Sort list alphabeticaly
AvailableTemplateNames = new string[ m_sortedTemplates.Count + 1 ];
AvailableTemplateNames[ 0 ] = "Custom";
for( int i = 0; i < m_sortedTemplates.Count; i++ )
{
m_sortedTemplates[ i ].OrderId = i;
AvailableTemplateNames[ i + 1 ] = m_sortedTemplates[ i ].Name;
}
if( refreshTemplateMenuItems )
CreateTemplateMenuItems();
Initialized = true;
}
}
//[MenuItem( "Window/Amplify Shader Editor/Create Menu Items", false, 1000 )]
//public static void ForceCreateTemplateMenuItems()
//{
// UIUtils.CurrentWindow.TemplatesManagerInstance.CreateTemplateMenuItems();
//}
public void CreateTemplateMenuItems()
{
if( m_sortedTemplates == null || m_sortedTemplates.Count == 0 )
return;
// change names for duplicates
for( int i = 0; i < m_sortedTemplates.Count; i++ )
{
for( int j = 0; j < i; j++ )
{
if( m_sortedTemplates[ i ].Name == m_sortedTemplates[ j ].Name )
{
var match = Regex.Match( m_sortedTemplates[ i ].Name, @".+(\d+)" );
if( match.Success )
{
string strNumber = match.Groups[ 1 ].Value;
int number = int.Parse( strNumber ) + 1;
string firstPart = m_sortedTemplates[ i ].Name.Substring( 0, match.Groups[ 1 ].Index );
string secondPart = m_sortedTemplates[ i ].Name.Substring( match.Groups[ 1 ].Index + strNumber.Length );
m_sortedTemplates[ i ].Name = firstPart + number + secondPart;
}
else
{
m_sortedTemplates[ i ].Name += " 1";
}
}
}
}
System.Text.StringBuilder fileContents = new System.Text.StringBuilder();
fileContents.Append( "// Amplify Shader Editor - Visual Shader Editing Tool\n" );
fileContents.Append( "// Copyright (c) Amplify Creations, Lda <info@amplify.pt>\n" );
fileContents.Append( "using UnityEditor;\n" );
fileContents.Append( "\n" );
fileContents.Append( "namespace AmplifyShaderEditor\n" );
fileContents.Append( "{\n" );
fileContents.Append( "\tpublic class TemplateMenuItems\n" );
fileContents.Append( "\t{\n" );
int fixedPriority = 85;
for( int i = 0; i < m_sortedTemplates.Count; i++ )
{
fileContents.AppendFormat( "\t\t[MenuItem( \"Assets/Create/Amplify Shader/{0}\", false, {1} )]\n", m_sortedTemplates[ i ].Name, fixedPriority );
string itemName = UIUtils.RemoveInvalidCharacters( m_sortedTemplates[ i ].Name );
fileContents.AppendFormat( "\t\tpublic static void ApplyTemplate{0}()\n", itemName/*i*/ );
fileContents.Append( "\t\t{\n" );
//fileContents.AppendFormat( "\t\t\tAmplifyShaderEditorWindow.CreateNewTemplateShader( \"{0}\" );\n", m_sortedTemplates[ i ].GUID );
fileContents.AppendFormat( "\t\t\tAmplifyShaderEditorWindow.CreateConfirmationTemplateShader( \"{0}\" );\n", m_sortedTemplates[ i ].GUID );
fileContents.Append( "\t\t}\n" );
}
fileContents.Append( "\t}\n" );
fileContents.Append( "}\n" );
string filePath = AssetDatabase.GUIDToAssetPath( TemplateMenuItemsFileGUID );
IOUtils.SaveTextfileToDisk( fileContents.ToString(), filePath, false );
m_filepath = filePath;
//AssetDatabase.ImportAsset( filePath );
}
string m_filepath = string.Empty;
public void ReimportMenuItems()
{
if( !string.IsNullOrEmpty( m_filepath ) )
{
AssetDatabase.ImportAsset( m_filepath );
m_filepath = string.Empty;
}
}
public int GetIdForTemplate( TemplateData templateData )
{
if( templateData == null )
return -1;
for( int i = 0; i < m_sortedTemplates.Count; i++ )
{
if( m_sortedTemplates[ i ].GUID.Equals( templateData.GUID ) )
return m_sortedTemplates[ i ].OrderId;
}
return -1;
}
public void AddTemplate( TemplateDataParent templateData )
{
if( templateData == null || !templateData.IsValid )
return;
RefreshAvailableTemplates();
if( !m_availableTemplates.ContainsKey( templateData.GUID ) )
{
m_sortedTemplates.Add( templateData );
m_availableTemplates.Add( templateData.GUID, templateData );
}
}
public void RemoveTemplate( string guid )
{
TemplateDataParent templateData = GetTemplate( guid );
if( templateData != null )
{
RemoveTemplate( templateData );
}
}
public void RemoveTemplate( TemplateDataParent templateData )
{
RefreshAvailableTemplates();
if( m_availableTemplates != null )
m_availableTemplates.Remove( templateData.GUID );
m_sortedTemplates.Remove( templateData );
templateData.Destroy();
}
public void Destroy()
{
if( TemplatesManager.ShowDebugMessages )
Debug.Log( "Destroy Manager" );
if( m_availableTemplates != null )
{
foreach( KeyValuePair<string, TemplateDataParent> kvp in m_availableTemplates )
{
kvp.Value.Destroy();
}
m_availableTemplates.Clear();
m_availableTemplates = null;
}
int count = m_sortedTemplates.Count;
for( int i = 0; i < count; i++ )
{
ScriptableObject.DestroyImmediate( m_sortedTemplates[ i ] );
}
m_sortedTemplates.Clear();
m_sortedTemplates = null;
AvailableTemplateNames = null;
Initialized = false;
}
public TemplateDataParent GetTemplate( int id )
{
if( id < m_sortedTemplates.Count )
return m_sortedTemplates[ id ];
return null;
}
public TemplateDataParent GetTemplate( string guid )
{
RefreshAvailableTemplates();
if( m_availableTemplates == null && m_sortedTemplates != null )
{
m_availableTemplates = new Dictionary<string, TemplateDataParent>();
for( int i = 0; i < m_sortedTemplates.Count; i++ )
{
m_availableTemplates.Add( m_sortedTemplates[ i ].GUID, m_sortedTemplates[ i ] );
}
}
if( m_availableTemplates.ContainsKey( guid ) )
return m_availableTemplates[ guid ];
return null;
}
public TemplateDataParent GetTemplateByName( string name )
{
RefreshAvailableTemplates();
if( m_availableTemplates == null && m_sortedTemplates != null )
{
m_availableTemplates = new Dictionary<string, TemplateDataParent>();
for( int i = 0; i < m_sortedTemplates.Count; i++ )
{
m_availableTemplates.Add( m_sortedTemplates[ i ].GUID, m_sortedTemplates[ i ] );
}
}
foreach( KeyValuePair<string, TemplateDataParent> kvp in m_availableTemplates )
{
if( kvp.Value.DefaultShaderName.Equals( name ) )
{
return kvp.Value;
}
}
return null;
}
public TemplateDataParent CheckAndLoadTemplate( string guid )
{
TemplateDataParent templateData = GetTemplate( guid );
if( templateData == null )
{
string datapath = AssetDatabase.GUIDToAssetPath( guid );
string body = IOUtils.LoadTextFileFromDisk( datapath );
if( body.IndexOf( TemplatesManager.TemplateShaderNameBeginTag ) > -1 )
{
templateData = ScriptableObject.CreateInstance<TemplateMultiPass>();
templateData.Init( string.Empty, guid, true );
if( templateData.IsValid )
{
AddTemplate( templateData );
return templateData;
}
}
}
return null;
}
private void OnEnable()
{
if( !Initialized )
{
Init();
}
else
{
RefreshAvailableTemplates();
}
hideFlags = HideFlags.HideAndDontSave;
if( ShowDebugMessages )
Debug.Log( "On Enable Manager: " + this.GetInstanceID() );
}
public void ResetOptionsSetupData()
{
if( ShowDebugMessages )
Debug.Log( "Reseting options setup data" );
m_optionsInitialSetup.Clear();
}
public bool SetOptionsValue( string optionId, bool value )
{
if( m_optionsInitialSetup.ContainsKey( optionId ) )
{
m_optionsInitialSetup[ optionId ] = m_optionsInitialSetup[ optionId ] || value;
}
else
{
m_optionsInitialSetup.Add( optionId, value );
}
return m_optionsInitialSetup[ optionId ];
}
public bool CheckIfDeprecated( string guid , out string newGUID )
{
if( DeprecatedTemplates.ContainsKey( guid ) )
{
UIUtils.ShowMessage( "Shader using deprecated template which no longer exists on ASE. Pointing to new correct one, options and connections to master node were reset." );
newGUID = DeprecatedTemplates[ guid ];
return true;
}
newGUID = string.Empty;
return false;
}
public int TemplateCount { get { return m_sortedTemplates.Count; } }
}
}

View File

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

View File

@@ -0,0 +1,669 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
namespace AmplifyShaderEditor
{
[Serializable]
public sealed class TemplatesStencilBufferModule : TemplateModuleParent
{
private const string FoldoutLabelStr = " Stencil Buffer";
private GUIContent ReferenceValueContent = new GUIContent( "Reference", "The value to be compared against (if Comparison is anything else than always) and/or the value to be written to the buffer (if either Pass, Fail or ZFail is set to replace)" );
private GUIContent ReadMaskContent = new GUIContent( "Read Mask", "An 8 bit mask as an 0-255 integer, used when comparing the reference value with the contents of the buffer (referenceValue & readMask) comparisonFunction (stencilBufferValue & readMask)" );
private GUIContent WriteMaskContent = new GUIContent( "Write Mask", "An 8 bit mask as an 0-255 integer, used when writing to the buffer" );
private const string ComparisonStr = "Comparison";
private const string PassStr = "Pass";
private const string FailStr = "Fail";
private const string ZFailStr = "ZFail";
private const string ComparisonFrontStr = "Comp. Front";
private const string PassFrontStr = "Pass Front";
private const string FailFrontStr = "Fail Front";
private const string ZFailFrontStr = "ZFail Front";
private const string ComparisonBackStr = "Comp. Back";
private const string PassBackStr = "Pass Back";
private const string FailBackStr = "Fail Back";
private const string ZFailBackStr = "ZFail Back";
private Dictionary<string, int> m_comparisonDict = new Dictionary<string, int>();
private Dictionary<string, int> m_stencilOpsDict = new Dictionary<string, int>();
[SerializeField]
private bool m_active = true;
[SerializeField]
private InlineProperty m_reference = new InlineProperty();
// Read Mask
private const int ReadMaskDefaultValue = 255;
[SerializeField]
private InlineProperty m_readMask = new InlineProperty( ReadMaskDefaultValue );
//Write Mask
private const int WriteMaskDefaultValue = 255;
[SerializeField]
private InlineProperty m_writeMask = new InlineProperty( WriteMaskDefaultValue );
//Comparison Function
private const int ComparisonDefaultValue = 0;
[SerializeField]
private InlineProperty m_comparisonFunctionFrontIdx = new InlineProperty( ComparisonDefaultValue );
[SerializeField]
private InlineProperty m_comparisonFunctionBackIdx = new InlineProperty( ComparisonDefaultValue );
//Pass Stencil Op
private const int PassStencilOpDefaultValue = 0;
[SerializeField]
private InlineProperty m_passStencilOpFrontIdx = new InlineProperty( PassStencilOpDefaultValue );
[SerializeField]
private InlineProperty m_passStencilOpBackIdx = new InlineProperty( PassStencilOpDefaultValue );
//Fail Stencil Op
private const int FailStencilOpDefaultValue = 0;
[SerializeField]
private InlineProperty m_failStencilOpFrontIdx = new InlineProperty( FailStencilOpDefaultValue );
[SerializeField]
private InlineProperty m_failStencilOpBackIdx = new InlineProperty( FailStencilOpDefaultValue );
//ZFail Stencil Op
private const int ZFailStencilOpDefaultValue = 0;
[SerializeField]
private InlineProperty m_zFailStencilOpFrontIdx = new InlineProperty( ZFailStencilOpDefaultValue );
[SerializeField]
private InlineProperty m_zFailStencilOpBackIdx = new InlineProperty( ZFailStencilOpDefaultValue );
public TemplatesStencilBufferModule() : base("Stencil Buffer")
{
for( int i = 0; i < StencilBufferOpHelper.StencilComparisonValues.Length; i++ )
{
m_comparisonDict.Add( StencilBufferOpHelper.StencilComparisonValues[ i ].ToLower(), i );
}
for( int i = 0; i < StencilBufferOpHelper.StencilOpsValues.Length; i++ )
{
m_stencilOpsDict.Add( StencilBufferOpHelper.StencilOpsValues[ i ].ToLower(), i );
}
}
public void CopyFrom( TemplatesStencilBufferModule other , bool allData )
{
if( allData )
m_independentModule = other.IndependentModule;
m_active = other.Active;
m_reference.CopyFrom( other.Reference );
m_readMask.CopyFrom( other.ReadMask );
m_writeMask.CopyFrom( other.WriteMask );
m_comparisonFunctionFrontIdx.CopyFrom( other.ComparisonFunctionIdx );
m_comparisonFunctionBackIdx.CopyFrom( other.ComparisonFunctionBackIdx );
m_passStencilOpFrontIdx.CopyFrom( other.PassStencilOpIdx );
m_passStencilOpBackIdx.CopyFrom( other.PassStencilOpBackIdx );
m_failStencilOpFrontIdx.CopyFrom( other.FailStencilOpIdx );
m_failStencilOpBackIdx.CopyFrom( other.FailStencilOpBackIdx );
m_zFailStencilOpFrontIdx.CopyFrom( other.ZFailStencilOpIdx );
m_zFailStencilOpBackIdx.CopyFrom( other.ZFailStencilOpBackIdx );
}
public void ConfigureFromTemplateData( TemplateStencilData stencilData )
{
bool newValidData = ( stencilData.DataCheck == TemplateDataCheck.Valid );
if( newValidData && m_validData != newValidData )
{
m_active = stencilData.Active;
m_independentModule = stencilData.IndependentModule;
if( string.IsNullOrEmpty( stencilData.ReferenceInline ) )
{
m_reference.IntValue = stencilData.Reference;
m_reference.ResetProperty();
}
else
{
m_reference.SetInlineByName( stencilData.ReferenceInline );
}
if( string.IsNullOrEmpty( stencilData.ReadMaskInline ) )
{
m_readMask.IntValue = stencilData.ReadMask;
m_readMask.ResetProperty();
}
else
{
m_readMask.SetInlineByName( stencilData.ReadMaskInline );
}
if( string.IsNullOrEmpty( stencilData.WriteMaskInline ) )
{
m_writeMask.IntValue = stencilData.WriteMask;
m_writeMask.ResetProperty();
}
else
{
m_writeMask.SetInlineByName( stencilData.WriteMaskInline );
}
if( string.IsNullOrEmpty( stencilData.ComparisonFrontInline ) )
{
if( !string.IsNullOrEmpty( stencilData.ComparisonFront ) )
{
m_comparisonFunctionFrontIdx.IntValue = m_comparisonDict[ stencilData.ComparisonFront.ToLower() ];
}
else
{
m_comparisonFunctionFrontIdx.IntValue = m_comparisonDict[ "always" ];
}
m_comparisonFunctionFrontIdx.ResetProperty();
}
else
{
m_comparisonFunctionFrontIdx.SetInlineByName( stencilData.ComparisonFrontInline );
}
if( string.IsNullOrEmpty( stencilData.PassFrontInline ) )
{
if( !string.IsNullOrEmpty( stencilData.PassFront ) )
{
m_passStencilOpFrontIdx.IntValue = m_stencilOpsDict[ stencilData.PassFront.ToLower() ];
}
else
{
m_passStencilOpFrontIdx.IntValue = m_stencilOpsDict[ "keep" ];
}
m_passStencilOpFrontIdx.ResetProperty();
}
else
{
m_passStencilOpFrontIdx.SetInlineByName( stencilData.PassFrontInline );
}
if( string.IsNullOrEmpty( stencilData.FailFrontInline ) )
{
if( !string.IsNullOrEmpty( stencilData.FailFront ) )
{
m_failStencilOpFrontIdx.IntValue = m_stencilOpsDict[ stencilData.FailFront.ToLower() ];
}
else
{
m_failStencilOpFrontIdx.IntValue = m_stencilOpsDict[ "keep" ];
}
m_failStencilOpFrontIdx.ResetProperty();
}
else
{
m_failStencilOpFrontIdx.SetInlineByName( stencilData.FailFrontInline );
}
if( string.IsNullOrEmpty( stencilData.ZFailFrontInline ) )
{
if( !string.IsNullOrEmpty( stencilData.ZFailFront ) )
{
m_zFailStencilOpFrontIdx.IntValue = m_stencilOpsDict[ stencilData.ZFailFront.ToLower() ];
}
else
{
m_zFailStencilOpFrontIdx.IntValue = m_stencilOpsDict[ "keep" ];
}
m_zFailStencilOpFrontIdx.ResetProperty();
}
else
{
m_zFailStencilOpFrontIdx.SetInlineByName( stencilData.ZFailFrontInline );
}
if( string.IsNullOrEmpty( stencilData.ComparisonBackInline ) )
{
if( !string.IsNullOrEmpty( stencilData.ComparisonBack ) )
{
m_comparisonFunctionBackIdx.IntValue = m_comparisonDict[ stencilData.ComparisonBack.ToLower() ];
}
else
{
m_comparisonFunctionBackIdx.IntValue = m_comparisonDict[ "always" ];
}
m_comparisonFunctionBackIdx.ResetProperty();
}
else
{
m_comparisonFunctionBackIdx.SetInlineByName( stencilData.ComparisonBackInline );
}
if( string.IsNullOrEmpty( stencilData.PassBackInline ) )
{
if( !string.IsNullOrEmpty( stencilData.PassBack ) )
{
m_passStencilOpBackIdx.IntValue = m_stencilOpsDict[ stencilData.PassBack.ToLower() ];
}
else
{
m_passStencilOpBackIdx.IntValue = m_stencilOpsDict[ "keep" ];
}
m_passStencilOpBackIdx.ResetProperty();
}
else
{
m_passStencilOpBackIdx.SetInlineByName( stencilData.PassBackInline );
}
if( string.IsNullOrEmpty( stencilData.FailBackInline ) )
{
if( !string.IsNullOrEmpty( stencilData.FailBack ) )
{
m_failStencilOpBackIdx.IntValue = m_stencilOpsDict[ stencilData.FailBack.ToLower() ];
}
else
{
m_failStencilOpBackIdx.IntValue = m_stencilOpsDict[ "keep" ];
}
m_failStencilOpBackIdx.ResetProperty();
}
else
{
m_failStencilOpBackIdx.SetInlineByName( stencilData.FailBackInline );
}
if( string.IsNullOrEmpty( stencilData.ZFailBackInline ) )
{
if( !string.IsNullOrEmpty( stencilData.ZFailBack ) )
{
m_zFailStencilOpBackIdx.IntValue = m_stencilOpsDict[ stencilData.ZFailBack.ToLower() ];
}
else
{
m_zFailStencilOpBackIdx.IntValue = m_stencilOpsDict[ "keep" ];
}
m_zFailStencilOpBackIdx.ResetProperty();
}
else
{
m_zFailStencilOpBackIdx.SetInlineByName( stencilData.ZFailBackInline );
}
}
m_validData = newValidData;
}
public string CreateStencilOp( CullMode cullMode )
{
if( !m_active )
return string.Empty;
string result = "Stencil\n{\n";
result += string.Format( "\tRef {0}\n", m_reference.GetValueOrProperty() );
if( m_readMask.IsValid || m_readMask.IntValue != ReadMaskDefaultValue )
{
result += string.Format( "\tReadMask {0}\n", m_readMask.GetValueOrProperty() );
}
if( m_writeMask.IsValid || m_writeMask.IntValue != WriteMaskDefaultValue )
{
result += string.Format( "\tWriteMask {0}\n", m_writeMask.GetValueOrProperty() );
}
if( cullMode == CullMode.Off &&
( m_comparisonFunctionBackIdx.IsValid || m_comparisonFunctionBackIdx.IntValue != ComparisonDefaultValue ||
m_passStencilOpBackIdx.IsValid || m_passStencilOpBackIdx.IntValue != PassStencilOpDefaultValue ||
m_failStencilOpBackIdx.IsValid || m_failStencilOpBackIdx.IntValue != FailStencilOpDefaultValue ||
m_zFailStencilOpBackIdx.IsValid || m_zFailStencilOpBackIdx.IntValue != ZFailStencilOpDefaultValue ) )
{
if( m_comparisonFunctionFrontIdx.IsValid || m_comparisonFunctionFrontIdx.IntValue != ComparisonDefaultValue )
result += string.Format( "\tCompFront {0}\n", m_comparisonFunctionFrontIdx.GetValueOrProperty( StencilBufferOpHelper.StencilComparisonValues[ m_comparisonFunctionFrontIdx.IntValue ] ) );
if( m_passStencilOpFrontIdx.IsValid || m_passStencilOpFrontIdx.IntValue != PassStencilOpDefaultValue )
result += string.Format( "\tPassFront {0}\n", m_passStencilOpFrontIdx.GetValueOrProperty( StencilBufferOpHelper.StencilOpsValues[ m_passStencilOpFrontIdx.IntValue ] ) );
if( m_failStencilOpFrontIdx.IsValid || m_failStencilOpFrontIdx.IntValue != FailStencilOpDefaultValue )
result += string.Format( "\tFailFront {0}\n", m_failStencilOpFrontIdx.GetValueOrProperty( StencilBufferOpHelper.StencilOpsValues[ m_failStencilOpFrontIdx.IntValue ] ) );
if( m_zFailStencilOpFrontIdx.IsValid || m_zFailStencilOpFrontIdx.IntValue != ZFailStencilOpDefaultValue )
result += string.Format( "\tZFailFront {0}\n", m_zFailStencilOpFrontIdx.GetValueOrProperty( StencilBufferOpHelper.StencilOpsValues[ m_zFailStencilOpFrontIdx.IntValue ] ) );
if( m_comparisonFunctionBackIdx.IsValid || m_comparisonFunctionBackIdx.IntValue != ComparisonDefaultValue )
result += string.Format( "\tCompBack {0}\n", m_comparisonFunctionBackIdx.GetValueOrProperty( StencilBufferOpHelper.StencilComparisonValues[ m_comparisonFunctionBackIdx.IntValue ] ) );
if( m_passStencilOpBackIdx.IsValid || m_passStencilOpBackIdx.IntValue != PassStencilOpDefaultValue )
result += string.Format( "\tPassBack {0}\n", m_passStencilOpBackIdx.GetValueOrProperty( StencilBufferOpHelper.StencilOpsValues[ m_passStencilOpBackIdx.IntValue ] ) );
if( m_failStencilOpBackIdx.IsValid || m_failStencilOpBackIdx.IntValue != FailStencilOpDefaultValue )
result += string.Format( "\tFailBack {0}\n", m_failStencilOpBackIdx.GetValueOrProperty( StencilBufferOpHelper.StencilOpsValues[ m_failStencilOpBackIdx.IntValue ] ));
if( m_zFailStencilOpBackIdx.IsValid || m_zFailStencilOpBackIdx.IntValue != ZFailStencilOpDefaultValue )
result += string.Format( "\tZFailBack {0}\n", m_zFailStencilOpBackIdx.GetValueOrProperty( StencilBufferOpHelper.StencilOpsValues[ m_zFailStencilOpBackIdx.IntValue ] ));
}
else
{
if( m_comparisonFunctionFrontIdx.IsValid || m_comparisonFunctionFrontIdx.IntValue != ComparisonDefaultValue )
result += string.Format( "\tComp {0}\n", m_comparisonFunctionFrontIdx.GetValueOrProperty(StencilBufferOpHelper.StencilComparisonValues[ m_comparisonFunctionFrontIdx.IntValue ] ));
if( m_passStencilOpFrontIdx.IsValid || m_passStencilOpFrontIdx.IntValue != PassStencilOpDefaultValue )
result += string.Format( "\tPass {0}\n", m_passStencilOpFrontIdx.GetValueOrProperty( StencilBufferOpHelper.StencilOpsValues[ m_passStencilOpFrontIdx.IntValue ] ));
if( m_failStencilOpFrontIdx.IsValid || m_failStencilOpFrontIdx.IntValue != FailStencilOpDefaultValue )
result += string.Format( "\tFail {0}\n", m_failStencilOpFrontIdx.GetValueOrProperty( StencilBufferOpHelper.StencilOpsValues[ m_failStencilOpFrontIdx.IntValue ] ));
if( m_zFailStencilOpFrontIdx.IsValid || m_zFailStencilOpFrontIdx.IntValue != ZFailStencilOpDefaultValue )
result += string.Format( "\tZFail {0}\n", m_zFailStencilOpFrontIdx.GetValueOrProperty(StencilBufferOpHelper.StencilOpsValues[ m_zFailStencilOpFrontIdx.IntValue ] ));
}
result += "}";
return result;
}
public override void ShowUnreadableDataMessage( ParentNode owner )
{
bool foldout = owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedStencilOptions;
NodeUtils.DrawPropertyGroup( ref foldout, FoldoutLabelStr, base.ShowUnreadableDataMessage );
owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedStencilOptions = foldout;
}
public void Draw( UndoParentNode owner, CullMode cullMode , bool style = true )
{
bool foldout = owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedStencilOptions;
if( style )
{
NodeUtils.DrawPropertyGroup( ref foldout, FoldoutLabelStr, () =>
{
DrawBlock( owner, cullMode );
} );
}
else
{
NodeUtils.DrawNestedPropertyGroup( owner, ref foldout, ref m_active, FoldoutLabelStr, () =>
{
DrawBlock( owner, cullMode );
} );
}
owner.ContainerGraph.ParentWindow.InnerWindowVariables.ExpandedStencilOptions = foldout;
}
void DrawBlock( UndoParentNode owner, CullMode cullMode )
{
bool guiEnabled = GUI.enabled;
GUI.enabled = m_active;
EditorGUI.BeginChangeCheck();
{
var cache = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = EditorGUIUtility.labelWidth - 20;
m_reference.IntSlider( ref owner, ReferenceValueContent, 0, 255 );
m_readMask.IntSlider( ref owner, ReadMaskContent, 0, 255 );
m_writeMask.IntSlider( ref owner, WriteMaskContent, 0, 255 );
if( cullMode == CullMode.Off )
{
m_comparisonFunctionFrontIdx.EnumTypePopup( ref owner, ComparisonFrontStr, StencilBufferOpHelper.StencilComparisonLabels );
m_passStencilOpFrontIdx.EnumTypePopup( ref owner, PassFrontStr, StencilBufferOpHelper.StencilOpsLabels );
m_failStencilOpFrontIdx.EnumTypePopup( ref owner, FailFrontStr, StencilBufferOpHelper.StencilOpsLabels );
m_zFailStencilOpFrontIdx.EnumTypePopup( ref owner, ZFailFrontStr, StencilBufferOpHelper.StencilOpsLabels );
EditorGUILayout.Separator();
m_comparisonFunctionBackIdx.EnumTypePopup( ref owner, ComparisonBackStr, StencilBufferOpHelper.StencilComparisonLabels );
m_passStencilOpBackIdx.EnumTypePopup( ref owner, PassBackStr, StencilBufferOpHelper.StencilOpsLabels );
m_failStencilOpBackIdx.EnumTypePopup( ref owner, FailBackStr, StencilBufferOpHelper.StencilOpsLabels );
m_zFailStencilOpBackIdx.EnumTypePopup( ref owner, ZFailBackStr, StencilBufferOpHelper.StencilOpsLabels );
}
else
{
m_comparisonFunctionFrontIdx.EnumTypePopup( ref owner, ComparisonStr, StencilBufferOpHelper.StencilComparisonLabels );
m_passStencilOpFrontIdx.EnumTypePopup( ref owner, PassFrontStr, StencilBufferOpHelper.StencilOpsLabels );
m_failStencilOpFrontIdx.EnumTypePopup( ref owner, FailFrontStr, StencilBufferOpHelper.StencilOpsLabels );
m_zFailStencilOpFrontIdx.EnumTypePopup( ref owner, ZFailFrontStr, StencilBufferOpHelper.StencilOpsLabels );
}
EditorGUIUtility.labelWidth = cache;
}
if( EditorGUI.EndChangeCheck() )
{
m_isDirty = true;
CustomEdited = true;
}
GUI.enabled = guiEnabled;
}
public override void ReadFromString( ref uint index, ref string[] nodeParams )
{
base.ReadFromString( ref index, ref nodeParams );
bool validDataOnMeta = m_validData;
if( UIUtils.CurrentShaderVersion() > TemplatesManager.MPShaderVersion )
{
validDataOnMeta = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( validDataOnMeta )
{
if( UIUtils.CurrentShaderVersion() > 15307 )
{
m_active = Convert.ToBoolean( nodeParams[ index++ ] );
}
if( UIUtils.CurrentShaderVersion() < 15304 )
{
m_reference.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
m_readMask.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
m_writeMask.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
m_comparisonFunctionFrontIdx.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
m_passStencilOpFrontIdx.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
m_failStencilOpFrontIdx.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
m_zFailStencilOpFrontIdx.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
m_comparisonFunctionBackIdx.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
m_passStencilOpBackIdx.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
m_failStencilOpBackIdx.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
m_zFailStencilOpBackIdx.IntValue = Convert.ToInt32( nodeParams[ index++ ] );
}
else
{
m_reference.ReadFromString( ref index, ref nodeParams );
m_readMask.ReadFromString( ref index, ref nodeParams );
m_writeMask.ReadFromString( ref index, ref nodeParams );
m_comparisonFunctionFrontIdx.ReadFromString( ref index, ref nodeParams );
m_passStencilOpFrontIdx.ReadFromString( ref index, ref nodeParams );
m_failStencilOpFrontIdx.ReadFromString( ref index, ref nodeParams );
m_zFailStencilOpFrontIdx.ReadFromString( ref index, ref nodeParams );
m_comparisonFunctionBackIdx.ReadFromString( ref index, ref nodeParams );
m_passStencilOpBackIdx.ReadFromString( ref index, ref nodeParams );
m_failStencilOpBackIdx.ReadFromString( ref index, ref nodeParams );
m_zFailStencilOpBackIdx.ReadFromString( ref index, ref nodeParams );
}
}
}
public override void WriteToString( ref string nodeInfo )
{
base.WriteToString( ref nodeInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, m_validData );
if( m_validData )
{
IOUtils.AddFieldValueToString( ref nodeInfo, m_active );
m_reference.WriteToString( ref nodeInfo );
m_readMask.WriteToString( ref nodeInfo );
m_writeMask.WriteToString( ref nodeInfo );
m_comparisonFunctionFrontIdx.WriteToString( ref nodeInfo );
m_passStencilOpFrontIdx.WriteToString( ref nodeInfo );
m_failStencilOpFrontIdx.WriteToString( ref nodeInfo );
m_zFailStencilOpFrontIdx.WriteToString( ref nodeInfo );
m_comparisonFunctionBackIdx.WriteToString( ref nodeInfo );
m_passStencilOpBackIdx.WriteToString( ref nodeInfo );
m_failStencilOpBackIdx.WriteToString( ref nodeInfo );
m_zFailStencilOpBackIdx.WriteToString( ref nodeInfo );
}
}
public override void Destroy()
{
m_comparisonDict.Clear();
m_comparisonDict = null;
m_stencilOpsDict.Clear();
m_stencilOpsDict = null;
m_reference = null;
m_readMask = null;
m_writeMask = null;
m_comparisonFunctionFrontIdx = null;
m_passStencilOpFrontIdx = null;
m_failStencilOpFrontIdx = null;
m_zFailStencilOpFrontIdx = null;
m_comparisonFunctionBackIdx = null;
m_passStencilOpBackIdx = null;
m_failStencilOpBackIdx = null;
m_zFailStencilOpBackIdx = null;
}
public bool Active { get { return m_active; } }
public InlineProperty Reference { get { return m_reference; } }
public InlineProperty ReadMask { get { return m_readMask; } }
public InlineProperty WriteMask { get { return m_writeMask; } }
public InlineProperty ComparisonFunctionIdx { get { return m_comparisonFunctionFrontIdx; } }
public InlineProperty ComparisonFunctionBackIdx { get { return m_comparisonFunctionBackIdx; } }
public InlineProperty PassStencilOpIdx { get { return m_passStencilOpFrontIdx; } }
public InlineProperty PassStencilOpBackIdx { get { return m_passStencilOpBackIdx; } }
public InlineProperty FailStencilOpIdx { get { return m_failStencilOpFrontIdx; } }
public InlineProperty FailStencilOpBackIdx { get { return m_failStencilOpBackIdx; } }
public InlineProperty ZFailStencilOpIdx { get { return m_zFailStencilOpFrontIdx; } }
public InlineProperty ZFailStencilOpBackIdx { get { return m_zFailStencilOpBackIdx; } }
public int ReferenceValue
{
set
{
m_reference.IntValue = value;
m_reference.Active = false;
}
get
{
return m_reference.IntValue;
}
}
public int ReadMaskValue
{
set
{
m_readMask.IntValue = value;
m_reference.Active = false;
}
get
{
return m_readMask.IntValue;
}
}
public int WriteMaskValue
{
set
{
m_writeMask.IntValue = value;
m_writeMask.Active = false;
}
get
{
return m_writeMask.IntValue;
}
}
public int ComparisonFunctionIdxValue
{
set
{
m_comparisonFunctionFrontIdx.IntValue = value;
m_comparisonFunctionFrontIdx.Active = false;
}
get
{
return m_comparisonFunctionFrontIdx.IntValue;
}
}
public int ComparisonFunctionBackIdxValue
{
set
{
m_comparisonFunctionBackIdx.IntValue = value;
m_comparisonFunctionBackIdx.Active = false;
}
get
{
return m_comparisonFunctionBackIdx.IntValue;
}
}
public int PassStencilOpIdxValue
{
set
{
m_passStencilOpFrontIdx.IntValue = value;
m_passStencilOpFrontIdx.Active = false;
}
get
{
return m_passStencilOpFrontIdx.IntValue;
}
}
public int PassStencilOpBackIdxValue
{
set
{
m_passStencilOpBackIdx.IntValue = value;
m_passStencilOpBackIdx.Active = false;
}
get
{
return m_passStencilOpBackIdx.IntValue;
}
}
public int FailStencilOpIdxValue
{
set
{
m_failStencilOpFrontIdx.IntValue = value;
m_failStencilOpFrontIdx.Active = false;
}
get
{
return m_failStencilOpFrontIdx.IntValue;
}
}
public int FailStencilOpBackIdxValue
{
set
{
m_failStencilOpBackIdx.IntValue = value;
m_failStencilOpBackIdx.Active = false;
}
get
{
return m_failStencilOpBackIdx.IntValue;
}
}
public int ZFailStencilOpIdxValue
{
set
{
m_zFailStencilOpFrontIdx.IntValue = value;
m_zFailStencilOpFrontIdx.Active = false;
}
get
{
return m_zFailStencilOpFrontIdx.IntValue;
}
}
public int ZFailStencilOpBackIdxValue
{
set
{
m_zFailStencilOpBackIdx.IntValue = value;
m_zFailStencilOpBackIdx.Active = false;
}
get
{
return m_zFailStencilOpBackIdx.IntValue;
}
}
}
}

View File

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